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/ProgressEvent.h"
134 #include "SDURLCache/SDURLCache.h"
141 #define _timestamp ({ \
143 gettimeofday(&tv, NULL); \
144 tv.tv_sec * 1000000 + tv.tv_usec; \
147 typedef std::vector<class ProfileTime *> TimeList;
157 ProfileTime(const char *name) :
161 times_.push_back(this);
164 void AddTime(uint64_t time) {
171 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
183 ProfileTimer(ProfileTime &time) :
190 time_.AddTime(_timestamp - start_);
195 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
197 std::cerr << "========" << std::endl;
200 #define _profile(name) { \
201 static ProfileTime name(#name); \
202 ProfileTimer _ ## name(name);
207 #define Cydia_ CYDIA_VERSION
209 #define lprintf(args...) fprintf(stderr, args)
212 #define TraceLogging (1 && !ForRelease)
213 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
214 #define ProfileTimes (0 && !ForRelease)
215 #define ForSaurik (0 && !ForRelease)
216 #define LogBrowser (0 && !ForRelease)
217 #define TrackResize (0 && !ForRelease)
218 #define ManualRefresh (1 && !ForRelease)
219 #define ShowInternals (0 && !ForRelease)
220 #define AlwaysReload (0 && !ForRelease)
221 #define TryIndexedCollation (0 && !ForRelease)
225 #define _trace(args...)
230 #define _profile(name) {
233 #define PrintTimes() do {} while (false)
236 // Hash Functions/Structures {{{
237 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
245 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
247 static _finline NSString *CydiaURL(NSString *path) {
249 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
250 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
251 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
252 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
253 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
255 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
258 static _finline void UpdateExternalStatus(uint64_t newStatus) {
260 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
261 notify_set_state(notify_token, newStatus);
262 notify_cancel(notify_token);
264 notify_post("com.saurik.Cydia.status");
267 /* NSForcedOrderingSearch doesn't work on the iPhone */
268 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
269 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
270 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
272 /* Insertion Sort {{{ */
274 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
275 const char *ptr = (const char *)list;
277 CFIndex half = count / 2;
278 const char *probe = ptr + elementSize * half;
279 CFComparisonResult cr = comparator(element, probe, context);
280 if (0 == cr) return (probe - (const char *)list) / elementSize;
281 ptr = (cr < 0) ? ptr : probe + elementSize;
282 count = (cr < 0) ? half : (half + (count & 1) - 1);
284 return (ptr - (const char *)list) / elementSize;
287 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
288 const char *ptr = (const char *)list;
290 CFIndex half = count / 2;
291 const char *probe = ptr + elementSize * half;
292 CFComparisonResult cr = comparator(element, probe, context);
293 if (0 == cr) return (probe - (const char *)list) / elementSize;
294 ptr = (cr < 0) ? ptr : probe + elementSize;
295 count = (cr < 0) ? half : (half + (count & 1) - 1);
297 return (ptr - (const char *)list) / elementSize;
300 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
301 if (range.length == 0)
303 const void **values(new const void *[range.length]);
304 CFArrayGetValues(array, range, values);
306 #if HistogramInsertionSort > 0
307 uint32_t total(0), *offsets(new uint32_t[range.length]);
310 for (CFIndex index(1); index != range.length; ++index) {
311 const void *value(values[index]);
312 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
313 CFIndex correct(index);
314 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
315 #if HistogramInsertionSort > 1
316 NSLog(@"%@ < %@", value, values[correct - 1]);
321 if (correct != index) {
322 size_t offset(index - correct);
323 #if HistogramInsertionSort
327 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
329 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
330 values[correct] = value;
334 CFArrayReplaceValues(array, range, values, range.length);
337 #if HistogramInsertionSort > 0
338 for (CFIndex index(0); index != range.length; ++index)
339 if (offsets[index] != 0)
340 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
341 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
348 /* Apple Bug Fixes {{{ */
349 @implementation UIWebDocumentView (Cydia)
351 - (void) _setScrollerOffset:(CGPoint)offset {
352 UIScroller *scroller([self _scroller]);
354 CGSize size([scroller contentSize]);
355 CGSize bounds([scroller bounds].size);
358 max.x = size.width - bounds.width;
359 max.y = size.height - bounds.height;
367 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
368 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
370 [scroller setOffset:offset];
376 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
377 size_t length([self length] - state->state);
380 else if (length > count)
382 for (size_t i(0); i != length; ++i)
383 objects[i] = [self item:state->state++];
384 state->itemsPtr = objects;
385 state->mutationsPtr = (unsigned long *) self;
389 /* Cydia NSString Additions {{{ */
390 @interface NSString (Cydia)
391 - (NSComparisonResult) compareByPath:(NSString *)other;
392 - (NSString *) stringByCachingURLWithCurrentCDN;
393 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
396 @implementation NSString (Cydia)
398 - (NSComparisonResult) compareByPath:(NSString *)other {
399 NSString *prefix = [self commonPrefixWithString:other options:0];
400 size_t length = [prefix length];
402 NSRange lrange = NSMakeRange(length, [self length] - length);
403 NSRange rrange = NSMakeRange(length, [other length] - length);
405 lrange = [self rangeOfString:@"/" options:0 range:lrange];
406 rrange = [other rangeOfString:@"/" options:0 range:rrange];
408 NSComparisonResult value;
410 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
411 value = NSOrderedSame;
412 else if (lrange.location == NSNotFound)
413 value = NSOrderedAscending;
414 else if (rrange.location == NSNotFound)
415 value = NSOrderedDescending;
417 value = NSOrderedSame;
419 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
420 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
421 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
422 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
424 NSComparisonResult result = [lpath compare:rpath];
425 return result == NSOrderedSame ? value : result;
428 - (NSString *) stringByCachingURLWithCurrentCDN {
430 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
431 withString:@"://cache.cydia.saurik.com/"
435 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
436 return [(id)CFURLCreateStringByAddingPercentEscapes(
441 kCFStringEncodingUTF8
448 /* C++ NSString Wrapper Cache {{{ */
449 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
450 return size == 0 ? NULL :
451 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
452 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
455 static _finline CFStringRef CYStringCreate(const char *data) {
456 return CYStringCreate(data, strlen(data));
465 _finline void clear_() {
466 if (cache_ != NULL) {
473 _finline bool empty() const {
477 _finline size_t size() const {
481 _finline char *data() const {
485 _finline void clear() {
490 _finline CYString() :
497 _finline ~CYString() {
501 void operator =(const CYString &rhs) {
505 if (rhs.cache_ == nil)
508 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
511 void copy(apr_pool_t *pool) {
512 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
513 memcpy(temp, data_, size_);
518 void set(apr_pool_t *pool, const char *data, size_t size) {
524 data_ = const_cast<char *>(data);
532 _finline void set(apr_pool_t *pool, const char *data) {
533 set(pool, data, data == NULL ? 0 : strlen(data));
536 _finline void set(apr_pool_t *pool, const std::string &rhs) {
537 set(pool, rhs.data(), rhs.size());
540 bool operator ==(const CYString &rhs) const {
541 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
544 _finline operator CFStringRef() {
546 cache_ = CYStringCreate(data_, size_);
550 _finline operator id() {
551 return (NSString *) static_cast<CFStringRef>(*this);
554 _finline operator const char *() {
555 return reinterpret_cast<const char *>(data_);
559 /* C++ NSString Algorithm Adapters {{{ */
561 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
564 struct NSStringMapHash :
565 std::unary_function<NSString *, size_t>
567 _finline size_t operator ()(NSString *value) const {
568 return CFStringHashNSString((CFStringRef) value);
572 struct NSStringMapLess :
573 std::binary_function<NSString *, NSString *, bool>
575 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
576 return [lhs compare:rhs] == NSOrderedAscending;
580 struct NSStringMapEqual :
581 std::binary_function<NSString *, NSString *, bool>
583 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
584 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
585 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
586 //[lhs isEqualToString:rhs];
591 /* Mime Addresses {{{ */
592 @interface Address : NSObject {
594 _H<NSString> address_;
598 - (NSString *) address;
600 - (void) setAddress:(NSString *)address;
602 + (Address *) addressWithString:(NSString *)string;
603 - (Address *) initWithString:(NSString *)string;
607 @implementation Address
609 - (NSString *) name {
613 - (NSString *) address {
617 - (void) setAddress:(NSString *)address {
621 + (Address *) addressWithString:(NSString *)string {
622 return [[[Address alloc] initWithString:string] autorelease];
625 + (NSArray *) _attributeKeys {
626 return [NSArray arrayWithObjects:
632 - (NSArray *) attributeKeys {
633 return [[self class] _attributeKeys];
636 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
637 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
640 - (Address *) initWithString:(NSString *)string {
641 if ((self = [super init]) != nil) {
642 const char *data = [string UTF8String];
643 size_t size = [string length];
645 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
647 if (address_r(data, size)) {
648 name_ = address_r[1];
649 address_ = address_r[2];
659 /* CoreGraphics Primitives {{{ */
664 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
665 CGFloat color[] = {red, green, blue, alpha};
666 return CGColorCreate(space, color);
675 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
676 color_(Create_(space, red, green, blue, alpha))
678 Set(space, red, green, blue, alpha);
683 CGColorRelease(color_);
690 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
692 color_ = Create_(space, red, green, blue, alpha);
695 operator CGColorRef() {
701 /* Random Global Variables {{{ */
702 static const int PulseInterval_ = 50000;
704 static const NSString *UI_;
707 static bool RestartSubstrate_;
708 static NSArray *Finishes_;
710 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
711 #define NotifyConfig_ "/etc/notify.conf"
713 static bool Queuing_;
715 static CYColor Blue_;
716 static CYColor Blueish_;
717 static CYColor Black_;
719 static CYColor White_;
720 static CYColor Gray_;
721 static CYColor Green_;
722 static CYColor Purple_;
723 static CYColor Purplish_;
725 static UIColor *InstallingColor_;
726 static UIColor *RemovingColor_;
728 static NSString *App_;
730 static BOOL Advanced_;
731 static BOOL Ignored_;
733 static _H<UIFont> Font12_;
734 static _H<UIFont> Font12Bold_;
735 static _H<UIFont> Font14_;
736 static _H<UIFont> Font18Bold_;
737 static _H<UIFont> Font22Bold_;
739 static const char *Machine_ = NULL;
740 static NSString *System_ = nil;
741 static NSString *SerialNumber_ = nil;
742 static NSString *ChipID_ = nil;
743 static NSString *BBSNum_ = nil;
744 static _H<NSString> Token_;
745 static NSString *UniqueID_ = nil;
746 static NSString *PLMN_ = nil;
747 static NSString *Build_ = nil;
748 static NSString *Product_ = nil;
749 static NSString *Safari_ = nil;
751 static CFLocaleRef Locale_;
752 static NSArray *Languages_;
753 static CGColorSpaceRef space_;
755 static NSDictionary *SectionMap_;
756 static NSMutableDictionary *Metadata_;
757 static _transient NSMutableDictionary *Settings_;
758 static _transient NSString *Role_;
759 static _transient NSMutableDictionary *Packages_;
760 static _transient NSMutableDictionary *Sections_;
761 static _transient NSMutableDictionary *Sources_;
762 static bool Changed_;
766 static CGFloat ScreenScale_;
767 static NSString *Idiom_;
769 static _H<NSMutableDictionary> SessionData_;
770 static _H<NSObject> HostConfig_;
771 static _H<NSMutableSet> BridgedHosts_;
772 static _H<NSMutableSet> PipelinedHosts_;
774 static NSString *kCydiaProgressEventTypeError = @"Error";
775 static NSString *kCydiaProgressEventTypeInformation = @"Information";
776 static NSString *kCydiaProgressEventTypeStatus = @"Status";
777 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
780 /* Display Helpers {{{ */
781 inline float Interpolate(float begin, float end, float fraction) {
782 return (end - begin) * fraction + begin;
785 static _finline const char *StripVersion_(const char *version) {
786 const char *colon(strchr(version, ':'));
787 return colon == NULL ? version : colon + 1;
790 NSString *LocalizeSection(NSString *section) {
791 static Pcre title_r("^(.*?) \\((.*)\\)$");
792 if (title_r(section)) {
793 NSString *parent(title_r[1]);
794 NSString *child(title_r[2]);
796 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
797 LocalizeSection(parent),
798 LocalizeSection(child)
802 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
805 NSString *Simplify(NSString *title) {
806 const char *data = [title UTF8String];
807 size_t size = [title length];
809 static Pcre square_r("^\\[(.*)\\]$");
810 if (square_r(data, size))
811 return Simplify(square_r[1]);
813 static Pcre paren_r("^\\((.*)\\)$");
814 if (paren_r(data, size))
815 return Simplify(paren_r[1]);
817 static Pcre title_r("^(.*?) \\((.*)\\)$");
818 if (title_r(data, size))
819 return Simplify(title_r[1]);
825 NSString *GetLastUpdate() {
826 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
829 return UCLocalize("NEVER_OR_UNKNOWN");
831 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
832 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
834 CFRelease(formatter);
836 return [(NSString *) formatted autorelease];
839 bool isSectionVisible(NSString *section) {
840 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
841 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
842 return hidden == nil || ![hidden boolValue];
845 static NSObject *CYIOGetValue(const char *path, NSString *property) {
846 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
847 if (entry == MACH_PORT_NULL)
850 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
851 IOObjectRelease(entry);
855 return [(id) value autorelease];
858 static NSString *CYHex(NSData *data, bool reverse = false) {
862 size_t length([data length]);
863 uint8_t bytes[length];
864 [data getBytes:bytes];
866 char string[length * 2 + 1];
867 for (size_t i(0); i != length; ++i)
868 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
870 return [NSString stringWithUTF8String:string];
875 /* Delegate Prototypes {{{ */
878 @class CydiaProgressEvent;
880 @protocol DatabaseDelegate
881 - (void) repairWithSelector:(SEL)selector;
882 - (void) setConfigurationData:(NSString *)data;
883 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
886 @class CYPackageController;
888 @protocol CydiaDelegate
889 - (void) retainNetworkActivityIndicator;
890 - (void) releaseNetworkActivityIndicator;
891 - (void) clearPackage:(Package *)package;
892 - (void) installPackage:(Package *)package;
893 - (void) installPackages:(NSArray *)packages;
894 - (void) removePackage:(Package *)package;
895 - (void) beginUpdate;
897 - (void) distUpgrade;
901 - (void) addTrivialSource:(NSString *)href;
902 - (void) showSettings;
903 - (UIProgressHUD *) addProgressHUD;
904 - (void) removeProgressHUD:(UIProgressHUD *)hud;
905 - (CyteViewController *) pageForPackage:(NSString *)name;
906 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
907 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
911 /* Status Delegation {{{ */
913 public pkgAcquireStatus
916 _transient NSObject<ProgressDelegate> *delegate_;
926 void setDelegate(NSObject<ProgressDelegate> *delegate) {
927 delegate_ = delegate;
930 NSObject<ProgressDelegate> *getDelegate() const {
934 virtual bool MediaChange(std::string media, std::string drive) {
938 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
941 virtual void Fetch(pkgAcquire::ItemDesc &item) {
942 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
943 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
944 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
947 virtual void Done(pkgAcquire::ItemDesc &item) {
950 virtual void Fail(pkgAcquire::ItemDesc &item) {
952 item.Owner->Status == pkgAcquire::Item::StatIdle ||
953 item.Owner->Status == pkgAcquire::Item::StatDone
957 std::string &error(item.Owner->ErrorText);
961 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
962 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
965 virtual bool Pulse(pkgAcquire *Owner) {
966 bool value = pkgAcquireStatus::Pulse(Owner);
969 double(CurrentBytes + CurrentItems) /
970 double(TotalBytes + TotalItems)
973 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
974 [NSNumber numberWithDouble:percent], @"Percent",
976 [NSNumber numberWithDouble:CurrentBytes], @"Current",
977 [NSNumber numberWithDouble:TotalBytes], @"Total",
978 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
979 nil] waitUntilDone:YES];
981 if (value && ![delegate_ isProgressCancelled])
989 _finline bool WasCancelled() const {
993 virtual void Start() {
994 pkgAcquireStatus::Start();
995 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
998 virtual void Stop() {
999 pkgAcquireStatus::Stop();
1000 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1001 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1005 /* Database Interface {{{ */
1006 typedef std::map< unsigned long, _H<Source> > SourceMap;
1008 @interface Database : NSObject {
1014 pkgCacheFile cache_;
1015 pkgDepCache::Policy *policy_;
1016 pkgRecords *records_;
1017 pkgProblemResolver *resolver_;
1018 pkgAcquire *fetcher_;
1020 SPtr<pkgPackageManager> manager_;
1021 pkgSourceList *list_;
1023 SourceMap sourceMap_;
1024 _H<NSMutableArray> sourceList_;
1026 CFMutableArrayRef packages_;
1028 _transient NSObject<DatabaseDelegate> *delegate_;
1029 _transient NSObject<ProgressDelegate> *progress_;
1037 std::map<const char *, _H<NSString> > sections_;
1040 + (Database *) sharedInstance;
1043 - (void) _readCydia:(NSNumber *)fd;
1044 - (void) _readStatus:(NSNumber *)fd;
1045 - (void) _readOutput:(NSNumber *)fd;
1049 - (Package *) packageWithName:(NSString *)name;
1051 - (pkgCacheFile &) cache;
1052 - (pkgDepCache::Policy *) policy;
1053 - (pkgRecords *) records;
1054 - (pkgProblemResolver *) resolver;
1055 - (pkgAcquire &) fetcher;
1056 - (pkgSourceList &) list;
1057 - (NSArray *) packages;
1058 - (NSArray *) sources;
1059 - (Source *) sourceWithKey:(NSString *)key;
1060 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1068 - (void) updateWithStatus:(Status &)status;
1070 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1072 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1073 - (NSObject<ProgressDelegate> *) progressDelegate;
1075 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1077 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1081 /* ProgressEvent Implementation {{{ */
1082 @implementation CydiaProgressEvent
1084 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1085 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1088 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1089 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1090 [event setPackage:package];
1094 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1095 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1097 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1098 NSArray *fields([description componentsSeparatedByString:@" "]);
1099 [event setItem:fields];
1101 if ([fields count] > 3) {
1102 [event setPackage:[fields objectAtIndex:2]];
1103 [event setVersion:[fields objectAtIndex:3]];
1106 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1111 + (NSArray *) _attributeKeys {
1112 return [NSArray arrayWithObjects:
1122 - (NSArray *) attributeKeys {
1123 return [[self class] _attributeKeys];
1126 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1127 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1130 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1131 if ((self = [super init]) != nil) {
1137 - (NSString *) message {
1141 - (NSString *) type {
1145 - (NSArray *) item {
1146 return (id) item_ ?: [NSNull null];
1149 - (void) setItem:(NSArray *)item {
1153 - (NSString *) package {
1154 return (id) package_ ?: [NSNull null];
1157 - (void) setPackage:(NSString *)package {
1161 - (NSString *) url {
1162 return (id) url_ ?: [NSNull null];
1165 - (void) setURL:(NSString *)url {
1169 - (void) setVersion:(NSString *)version {
1173 - (NSString *) version {
1174 return (id) version_ ?: [NSNull null];
1177 - (NSString *) compound:(NSString *)value {
1179 NSString *mode(nil); {
1180 NSString *type([self type]);
1181 if ([type isEqualToString:kCydiaProgressEventTypeError])
1182 mode = UCLocalize("ERROR");
1183 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1184 mode = UCLocalize("WARNING");
1188 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1194 - (NSString *) compoundMessage {
1195 return [self compound:[self message]];
1198 - (NSString *) compoundTitle {
1201 if (package_ == nil)
1203 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1204 title = [package name];
1208 return [self compound:title];
1214 // Cytore Definitions {{{
1215 struct PackageValue :
1218 Cytore::Offset<PackageValue> next_;
1220 uint32_t index_ : 23;
1221 uint32_t subscribed_ : 1;
1238 Cytore::Offset<PackageValue> packages_[1 << 16];
1241 static Cytore::File<MetaValue> MetaFile_;
1243 // Cytore Helper Functions {{{
1244 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1245 SplitHash nhash = { hashlittle(name, length) };
1247 PackageValue *metadata;
1249 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1250 offset: if (offset->IsNull()) {
1251 *offset = MetaFile_.New<PackageValue>(length + 1);
1252 metadata = &MetaFile_.Get(*offset);
1254 if (metadata == NULL) {
1258 metadata = new PackageValue();
1259 memset(metadata, 0, sizeof(*metadata));
1262 memcpy(metadata->name_, name, length + 1);
1263 metadata->nhash_ = nhash.u16[1];
1265 metadata = &MetaFile_.Get(*offset);
1267 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1268 offset = &metadata->next_;
1276 static void PackageImport(const void *key, const void *value, void *context) {
1277 bool &fail(*reinterpret_cast<bool *>(context));
1280 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1281 NSLog(@"failed to import package %@", key);
1285 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1286 NSDictionary *package((NSDictionary *) value);
1288 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1289 if ([subscribed boolValue] && !metadata->subscribed_)
1290 metadata->subscribed_ = true;
1292 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1293 time_t time([date timeIntervalSince1970]);
1294 if (metadata->first_ > time || metadata->first_ == 0)
1295 metadata->first_ = time;
1298 NSDate *date([package objectForKey:@"LastSeen"]);
1299 NSString *version([package objectForKey:@"LastVersion"]);
1301 if (date != nil && version != nil) {
1302 time_t time([date timeIntervalSince1970]);
1303 if (metadata->last_ < time || metadata->last_ == 0)
1304 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1305 size_t length(strlen(buffer));
1306 uint16_t vhash(hashlittle(buffer, length));
1308 size_t capped(std::min<size_t>(8, length));
1309 char *latest(buffer + length - capped);
1311 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1312 metadata->vhash_ = vhash;
1314 metadata->last_ = time;
1320 /* Source Class {{{ */
1321 @interface Source : NSObject {
1322 CYString depiction_;
1323 CYString description_;
1329 CYString distribution_;
1334 _H<NSString> authority_;
1336 CYString defaultIcon_;
1338 _H<NSDictionary> record_;
1342 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1344 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1346 - (NSString *) depictionForPackage:(NSString *)package;
1347 - (NSString *) supportForPackage:(NSString *)package;
1349 - (NSDictionary *) record;
1353 - (NSString *) distribution;
1354 - (NSString *) type;
1356 - (NSString *) host;
1358 - (NSString *) name;
1359 - (NSString *) shortDescription;
1360 - (NSString *) label;
1361 - (NSString *) origin;
1362 - (NSString *) version;
1364 - (NSString *) defaultIcon;
1368 @implementation Source
1372 distribution_.clear();
1375 description_.clear();
1381 defaultIcon_.clear();
1388 + (NSArray *) _attributeKeys {
1389 return [NSArray arrayWithObjects:
1396 @"shortDescription",
1404 - (NSArray *) attributeKeys {
1405 return [[self class] _attributeKeys];
1408 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1409 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1412 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1415 trusted_ = index->IsTrusted();
1417 uri_.set(pool, index->GetURI());
1418 distribution_.set(pool, index->GetDist());
1419 type_.set(pool, index->GetType());
1421 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1422 if (dindex != NULL) {
1424 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1427 pkgTagFile tags(&fd);
1429 pkgTagSection section;
1436 {"default-icon", &defaultIcon_},
1437 {"depiction", &depiction_},
1438 {"description", &description_},
1440 {"origin", &origin_},
1441 {"support", &support_},
1442 {"version", &version_},
1445 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1446 const char *start, *end;
1448 if (section.Find(names[i].name_, start, end)) {
1449 CYString &value(*names[i].value_);
1450 value.set(pool, start, end - start);
1456 record_ = [Sources_ objectForKey:[self key]];
1458 NSURL *url([NSURL URLWithString:uri_]);
1462 host_ = [host_ lowercaseString];
1467 authority_ = [url path];
1470 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1471 if ((self = [super init]) != nil) {
1472 [self setMetaIndex:index inPool:pool];
1476 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1477 NSDictionary *lhr = [self record];
1478 NSDictionary *rhr = [source record];
1481 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1483 NSString *lhs = [self name];
1484 NSString *rhs = [source name];
1486 if ([lhs length] != 0 && [rhs length] != 0) {
1487 unichar lhc = [lhs characterAtIndex:0];
1488 unichar rhc = [rhs characterAtIndex:0];
1490 if (isalpha(lhc) && !isalpha(rhc))
1491 return NSOrderedAscending;
1492 else if (!isalpha(lhc) && isalpha(rhc))
1493 return NSOrderedDescending;
1496 return [lhs compare:rhs options:LaxCompareOptions_];
1499 - (NSString *) depictionForPackage:(NSString *)package {
1500 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1503 - (NSString *) supportForPackage:(NSString *)package {
1504 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1507 - (NSDictionary *) record {
1515 - (NSString *) uri {
1519 - (NSString *) distribution {
1520 return distribution_;
1523 - (NSString *) type {
1527 - (NSString *) key {
1528 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1531 - (NSString *) host {
1535 - (NSString *) name {
1536 return origin_.empty() ? (id) authority_ : origin_;
1539 - (NSString *) shortDescription {
1540 return description_;
1543 - (NSString *) label {
1544 return label_.empty() ? (id) authority_ : label_;
1547 - (NSString *) origin {
1551 - (NSString *) version {
1555 - (NSString *) defaultIcon {
1556 return defaultIcon_;
1561 /* CydiaOperation Class {{{ */
1562 @interface CydiaOperation : NSObject {
1563 _H<NSString> operator_;
1564 _H<NSString> value_;
1567 - (NSString *) operator;
1568 - (NSString *) value;
1572 @implementation CydiaOperation
1574 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1575 if ((self = [super init]) != nil) {
1576 operator_ = [NSString stringWithUTF8String:_operator];
1577 value_ = [NSString stringWithUTF8String:value];
1581 + (NSArray *) _attributeKeys {
1582 return [NSArray arrayWithObjects:
1588 - (NSArray *) attributeKeys {
1589 return [[self class] _attributeKeys];
1592 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1593 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1596 - (NSString *) operator {
1600 - (NSString *) value {
1606 /* CydiaClause Class {{{ */
1607 @interface CydiaClause : NSObject {
1608 _H<NSString> package_;
1609 _H<CydiaOperation> version_;
1612 - (NSString *) package;
1613 - (CydiaOperation *) version;
1617 @implementation CydiaClause
1619 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1620 if ((self = [super init]) != nil) {
1621 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1623 if (const char *version = dep.TargetVer())
1624 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1626 version_ = (id) [NSNull null];
1630 + (NSArray *) _attributeKeys {
1631 return [NSArray arrayWithObjects:
1637 - (NSArray *) attributeKeys {
1638 return [[self class] _attributeKeys];
1641 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1642 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1645 - (NSString *) package {
1649 - (CydiaOperation *) version {
1655 /* CydiaRelation Class {{{ */
1656 @interface CydiaRelation : NSObject {
1657 _H<NSString> relationship_;
1658 _H<NSMutableArray> clauses_;
1661 - (NSString *) relationship;
1662 - (NSArray *) clauses;
1666 @implementation CydiaRelation
1668 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1669 if ((self = [super init]) != nil) {
1670 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1671 clauses_ = [NSMutableArray arrayWithCapacity:8];
1673 pkgCache::DepIterator start;
1674 pkgCache::DepIterator end;
1675 dep.GlobOr(start, end); // ++dep
1678 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1680 // yes, seriously. (wtf?)
1688 + (NSArray *) _attributeKeys {
1689 return [NSArray arrayWithObjects:
1695 - (NSArray *) attributeKeys {
1696 return [[self class] _attributeKeys];
1699 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1700 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1703 - (NSString *) relationship {
1704 return relationship_;
1707 - (NSArray *) clauses {
1711 - (void) addClause:(CydiaClause *)clause {
1712 [clauses_ addObject:clause];
1717 /* Package Class {{{ */
1718 struct ParsedPackage {
1723 CYString depiction_;
1733 @interface Package : NSObject {
1736 uint32_t essential_ : 1;
1737 uint32_t obsolete_ : 1;
1738 uint32_t ignored_ : 1;
1742 _transient Database *database_;
1744 pkgCache::VerIterator version_;
1745 pkgCache::PkgIterator iterator_;
1746 pkgCache::VerFileIterator file_;
1752 CYString installed_;
1754 const char *section_;
1755 _transient NSString *section$_;
1759 PackageValue *metadata_;
1760 ParsedPackage *parsed_;
1762 _H<NSMutableArray> tags_;
1765 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1766 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1768 - (pkgCache::PkgIterator) iterator;
1771 - (NSString *) section;
1772 - (NSString *) simpleSection;
1774 - (NSString *) longSection;
1775 - (NSString *) shortSection;
1779 - (Address *) maintainer;
1781 - (NSString *) longDescription;
1782 - (NSString *) shortDescription;
1785 - (PackageValue *) metadata;
1788 - (bool) subscribed;
1789 - (bool) setSubscribed:(bool)subscribed;
1793 - (NSString *) latest;
1794 - (NSString *) installed;
1795 - (BOOL) uninstalled;
1798 - (BOOL) upgradableAndEssential:(BOOL)essential;
1801 - (BOOL) unfiltered;
1805 - (BOOL) halfConfigured;
1806 - (BOOL) halfInstalled;
1808 - (NSString *) mode;
1811 - (NSString *) name;
1813 - (NSString *) homepage;
1814 - (NSString *) depiction;
1815 - (Address *) author;
1817 - (NSString *) support;
1819 - (NSArray *) files;
1820 - (NSArray *) warnings;
1821 - (NSArray *) applications;
1823 - (Source *) source;
1825 - (BOOL) matches:(NSString *)text;
1827 - (bool) hasSupportingRole;
1828 - (BOOL) hasTag:(NSString *)tag;
1829 - (NSString *) primaryPurpose;
1830 - (NSArray *) purposes;
1831 - (bool) isCommercial;
1833 - (void) setIndex:(size_t)index;
1835 - (CYString &) cyname;
1837 - (uint32_t) compareBySection:(NSArray *)sections;
1842 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1843 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1844 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1845 - (bool) isVisibleInSection:(NSString *)section;
1846 - (bool) isVisibleInSource:(Source *)source;
1850 uint32_t PackageChangesRadix(Package *self, void *) {
1855 uint32_t timestamp : 30;
1856 uint32_t ignored : 1;
1857 uint32_t upgradable : 1;
1861 bool upgradable([self upgradableAndEssential:YES]);
1862 value.bits.upgradable = upgradable ? 1 : 0;
1865 value.bits.timestamp = 0;
1866 value.bits.ignored = [self ignored] ? 0 : 1;
1867 value.bits.upgradable = 1;
1869 value.bits.timestamp = [self seen] >> 2;
1870 value.bits.ignored = 0;
1871 value.bits.upgradable = 0;
1874 return _not(uint32_t) - value.key;
1877 uint32_t PackagePrefixRadix(Package *self, void *context) {
1878 size_t offset(reinterpret_cast<size_t>(context));
1879 CYString &name([self cyname]);
1881 size_t size(name.size());
1884 char *text(name.data());
1887 if (!isdigit(text[0]))
1891 while (size != digits && isdigit(text[digits]))
1899 if (offset == 0 && zeros != 0) {
1900 memset(data, '0', zeros);
1901 memcpy(data + zeros, text, 4 - zeros);
1903 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1904 if (size <= offset - zeros)
1907 text += offset - zeros;
1908 size -= offset - zeros;
1911 memcpy(data, text, 4);
1913 memcpy(data, text, size);
1914 memset(data + size, 0, 4 - size);
1917 for (size_t i(0); i != 4; ++i)
1918 if (isalpha(data[i]))
1926 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1928 /* XXX: ntohl may be more honest */
1929 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1932 CYString &(*PackageName)(Package *self, SEL sel);
1934 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1935 _profile(PackageNameCompare)
1936 CYString &lhi(PackageName(lhs, @selector(cyname)));
1937 CYString &rhi(PackageName(rhs, @selector(cyname)));
1938 CFStringRef lhn(lhi), rhn(rhi);
1941 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1942 else if (rhn == NULL)
1943 return NSOrderedDescending;
1945 _profile(PackageNameCompare$NumbersLast)
1946 if (!lhi.empty() && !rhi.empty()) {
1947 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1948 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1949 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1950 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1951 return lha ? NSOrderedAscending : NSOrderedDescending;
1955 CFIndex length = CFStringGetLength(lhn);
1957 _profile(PackageNameCompare$Compare)
1958 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1963 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1964 return PackageNameCompare(*lhs, *rhs, context);
1967 struct PackageNameOrdering :
1968 std::binary_function<Package *, Package *, bool>
1970 _finline bool operator ()(Package *lhs, Package *rhs) const {
1971 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1975 @implementation Package
1977 - (NSString *) description {
1978 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1982 if (parsed_ != NULL)
1987 + (NSString *) webScriptNameForSelector:(SEL)selector {
1989 else if (selector == @selector(clear))
1991 else if (selector == @selector(getField:))
1993 else if (selector == @selector(hasTag:))
1995 else if (selector == @selector(install))
1997 else if (selector == @selector(remove))
2003 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2004 return [self webScriptNameForSelector:selector] == nil;
2007 + (NSArray *) _attributeKeys {
2008 return [NSArray arrayWithObjects:
2027 @"shortDescription",
2040 - (NSArray *) attributeKeys {
2041 return [[self class] _attributeKeys];
2044 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2045 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2048 - (NSArray *) relations {
2049 @synchronized (database_) {
2050 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2051 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2052 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2056 - (NSString *) getField:(NSString *)name {
2057 @synchronized (database_) {
2058 if ([database_ era] != era_ || file_.end())
2061 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2063 const char *start, *end;
2064 if (!parser.Find([name UTF8String], start, end))
2065 return (NSString *) [NSNull null];
2067 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2071 if (parsed_ != NULL)
2073 @synchronized (database_) {
2074 if ([database_ era] != era_ || file_.end())
2077 ParsedPackage *parsed(new ParsedPackage);
2080 _profile(Package$parse)
2081 pkgRecords::Parser *parser;
2083 _profile(Package$parse$Lookup)
2084 parser = &[database_ records]->Lookup(file_);
2089 _profile(Package$parse$Find)
2094 {"icon", &parsed->icon_},
2095 {"depiction", &parsed->depiction_},
2096 {"homepage", &parsed->homepage_},
2097 {"website", &website},
2098 {"bugs", &parsed->bugs_},
2099 {"support", &parsed->support_},
2100 {"sponsor", &parsed->sponsor_},
2101 {"author", &parsed->author_},
2104 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2105 const char *start, *end;
2107 if (parser->Find(names[i].name_, start, end)) {
2108 CYString &value(*names[i].value_);
2109 _profile(Package$parse$Value)
2110 value.set(pool_, start, end - start);
2116 _profile(Package$parse$Tagline)
2117 const char *start, *end;
2118 if (parser->ShortDesc(start, end)) {
2119 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2122 while (stop != start && stop[-1] == '\r')
2124 parsed->tagline_.set(pool_, start, stop - start);
2128 _profile(Package$parse$Retain)
2129 if (parsed->homepage_.empty())
2130 parsed->homepage_ = website;
2131 if (parsed->homepage_ == parsed->depiction_)
2132 parsed->homepage_.clear();
2137 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2138 if ((self = [super init]) != nil) {
2139 _profile(Package$initWithVersion)
2142 database_ = database;
2143 era_ = [database era];
2147 pkgCache::PkgIterator iterator(version.ParentPkg());
2148 iterator_ = iterator;
2150 _profile(Package$initWithVersion$Version)
2151 if (!version_.end())
2152 file_ = version_.FileList();
2154 pkgCache &cache([database_ cache]);
2155 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2159 _profile(Package$initWithVersion$Cache)
2160 name_.set(NULL, iterator.Display());
2162 latest_.set(NULL, StripVersion_(version_.VerStr()));
2164 pkgCache::VerIterator current(iterator.CurrentVer());
2166 installed_.set(NULL, StripVersion_(current.VerStr()));
2169 _profile(Package$initWithVersion$Tags)
2170 pkgCache::TagIterator tag(iterator.TagList());
2172 tags_ = [NSMutableArray arrayWithCapacity:8];
2174 const char *name(tag.Name());
2175 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2177 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2178 if (strcmp(name + 6, "enduser") == 0)
2180 else if (strcmp(name + 6, "hacker") == 0)
2182 else if (strcmp(name + 6, "developer") == 0)
2184 else if (strcmp(name + 6, "cydia") == 0)
2190 if (strncmp(name, "cydia::", 7) == 0) {
2191 if (strcmp(name + 7, "essential") == 0)
2193 else if (strcmp(name + 7, "obsolete") == 0)
2198 } while (!tag.end());
2202 _profile(Package$initWithVersion$Metadata)
2203 const char *mixed(iterator.Name());
2204 size_t size(strlen(mixed));
2205 char lower[size + 1];
2207 for (size_t i(0); i != size; ++i)
2208 lower[i] = mixed[i] | 0x20;
2211 PackageValue *metadata(PackageFind(lower, size));
2212 metadata_ = metadata;
2214 id_.set(NULL, metadata->name_, size);
2216 const char *latest(version_.VerStr());
2217 size_t length(strlen(latest));
2219 uint16_t vhash(hashlittle(latest, length));
2221 size_t capped(std::min<size_t>(8, length));
2222 latest = latest + length - capped;
2224 if (metadata->first_ == 0)
2225 metadata->first_ = now_;
2227 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2228 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2229 metadata->vhash_ = vhash;
2230 metadata->last_ = now_;
2231 } else if (metadata->last_ == 0)
2232 metadata->last_ = metadata->first_;
2235 _profile(Package$initWithVersion$Section)
2236 section_ = iterator.Section();
2239 _profile(Package$initWithVersion$Flags)
2240 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2241 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2246 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2247 pkgCache::VerIterator version;
2249 _profile(Package$packageWithIterator$GetCandidateVer)
2250 version = [database policy]->GetCandidateVer(iterator);
2258 _profile(Package$packageWithIterator$Allocate)
2259 package = [Package allocWithZone:zone];
2262 _profile(Package$packageWithIterator$Initialize)
2264 initWithVersion:version
2271 _profile(Package$packageWithIterator$Autorelease)
2272 package = [package autorelease];
2278 - (pkgCache::PkgIterator) iterator {
2282 - (NSString *) section {
2283 if (section$_ == nil) {
2284 if (section_ == NULL)
2287 _profile(Package$section$mappedSectionForPointer)
2288 section$_ = [database_ mappedSectionForPointer:section_];
2293 - (NSString *) simpleSection {
2294 if (NSString *section = [self section])
2295 return Simplify(section);
2300 - (NSString *) longSection {
2301 return LocalizeSection([self section]);
2304 - (NSString *) shortSection {
2305 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2308 - (NSString *) uri {
2311 pkgIndexFile *index;
2312 pkgCache::PkgFileIterator file(file_.File());
2313 if (![database_ list].FindIndex(file, index))
2315 return [NSString stringWithUTF8String:iterator_->Path];
2316 //return [NSString stringWithUTF8String:file.Site()];
2317 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2321 - (Address *) maintainer {
2322 @synchronized (database_) {
2323 if ([database_ era] != era_ || file_.end())
2326 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2327 const std::string &maintainer(parser->Maintainer());
2328 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2332 @synchronized (database_) {
2333 if ([database_ era] != era_ || version_.end())
2336 return version_->InstalledSize;
2339 - (NSString *) longDescription {
2340 @synchronized (database_) {
2341 if ([database_ era] != era_ || file_.end())
2344 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2345 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2347 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2348 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2349 if ([lines count] < 2)
2352 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2353 for (size_t i(1), e([lines count]); i != e; ++i) {
2354 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2355 [trimmed addObject:trim];
2358 return [trimmed componentsJoinedByString:@"\n"];
2361 - (NSString *) shortDescription {
2362 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2366 _profile(Package$index)
2367 CFStringRef name((CFStringRef) [self name]);
2368 if (CFStringGetLength(name) == 0)
2370 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2371 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2373 return toupper(character);
2377 - (PackageValue *) metadata {
2382 PackageValue *metadata([self metadata]);
2383 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2386 - (bool) subscribed {
2387 return [self metadata]->subscribed_;
2390 - (bool) setSubscribed:(bool)subscribed {
2391 PackageValue *metadata([self metadata]);
2392 if (metadata->subscribed_ == subscribed)
2394 metadata->subscribed_ = subscribed;
2402 - (NSString *) latest {
2406 - (NSString *) installed {
2410 - (BOOL) uninstalled {
2411 return installed_.empty();
2415 return !version_.end();
2418 - (BOOL) upgradableAndEssential:(BOOL)essential {
2419 _profile(Package$upgradableAndEssential)
2420 pkgCache::VerIterator current(iterator_.CurrentVer());
2422 return essential && essential_;
2424 return !version_.end() && version_ != current;
2428 - (BOOL) essential {
2433 return [database_ cache][iterator_].InstBroken();
2436 - (BOOL) unfiltered {
2437 _profile(Package$unfiltered$obsolete)
2438 if (_unlikely(obsolete_))
2442 _profile(Package$unfiltered$hasSupportingRole)
2443 if (_unlikely(![self hasSupportingRole]))
2451 if (![self unfiltered])
2456 _profile(Package$visible$section)
2457 section = [self section];
2460 _profile(Package$visible$isSectionVisible)
2461 if (!isSectionVisible(section))
2469 unsigned char current(iterator_->CurrentState);
2470 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2473 - (BOOL) halfConfigured {
2474 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2477 - (BOOL) halfInstalled {
2478 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2482 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2483 return state.Mode != pkgDepCache::ModeKeep;
2486 - (NSString *) mode {
2487 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2489 switch (state.Mode) {
2490 case pkgDepCache::ModeDelete:
2491 if ((state.iFlags & pkgDepCache::Purge) != 0)
2495 case pkgDepCache::ModeKeep:
2496 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2497 return @"REINSTALL";
2498 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2502 case pkgDepCache::ModeInstall:
2503 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2504 return @"REINSTALL";
2505 else*/ switch (state.Status) {
2507 return @"DOWNGRADE";
2513 return @"NEW_INSTALL";
2524 - (NSString *) name {
2525 return name_.empty() ? id_ : name_;
2528 - (UIImage *) icon {
2529 NSString *section = [self simpleSection];
2532 if (parsed_ != NULL)
2533 if (NSString *href = parsed_->icon_)
2534 if ([href hasPrefix:@"file:///"])
2535 // XXX: correct escaping
2536 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2537 if (icon == nil) if (section != nil)
2538 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2539 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2540 if ([dicon hasPrefix:@"file:///"])
2541 // XXX: correct escaping
2542 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2544 icon = [UIImage applicationImageNamed:@"unknown.png"];
2548 - (NSString *) homepage {
2549 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2552 - (NSString *) depiction {
2553 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2556 - (Address *) sponsor {
2557 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2560 - (Address *) author {
2561 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2564 - (NSString *) support {
2565 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2568 - (NSArray *) files {
2569 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2570 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2573 fin.open([path UTF8String]);
2578 while (std::getline(fin, line))
2579 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2584 - (NSString *) state {
2585 @synchronized (database_) {
2586 if ([database_ era] != era_ || file_.end())
2589 switch (iterator_->CurrentState) {
2590 case pkgCache::State::NotInstalled:
2591 return @"NotInstalled";
2592 case pkgCache::State::UnPacked:
2594 case pkgCache::State::HalfConfigured:
2595 return @"HalfConfigured";
2596 case pkgCache::State::HalfInstalled:
2597 return @"HalfInstalled";
2598 case pkgCache::State::ConfigFiles:
2599 return @"ConfigFiles";
2600 case pkgCache::State::Installed:
2601 return @"Installed";
2602 case pkgCache::State::TriggersAwaited:
2603 return @"TriggersAwaited";
2604 case pkgCache::State::TriggersPending:
2605 return @"TriggersPending";
2608 return (NSString *) [NSNull null];
2611 - (NSString *) selection {
2612 @synchronized (database_) {
2613 if ([database_ era] != era_ || file_.end())
2616 switch (iterator_->SelectedState) {
2617 case pkgCache::State::Unknown:
2619 case pkgCache::State::Install:
2621 case pkgCache::State::Hold:
2623 case pkgCache::State::DeInstall:
2624 return @"DeInstall";
2625 case pkgCache::State::Purge:
2629 return (NSString *) [NSNull null];
2632 - (NSArray *) warnings {
2633 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2634 const char *name(iterator_.Name());
2636 size_t length(strlen(name));
2637 if (length < 2) invalid:
2638 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2639 else for (size_t i(0); i != length; ++i)
2641 /* XXX: technically this is not allowed */
2642 (name[i] < 'A' || name[i] > 'Z') &&
2643 (name[i] < 'a' || name[i] > 'z') &&
2644 (name[i] < '0' || name[i] > '9') &&
2645 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2648 if (strcmp(name, "cydia") != 0) {
2651 bool _private = false;
2654 bool repository = [[self section] isEqualToString:@"Repositories"];
2656 if (NSArray *files = [self files])
2657 for (NSString *file in files)
2658 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2660 else if (!user && [file isEqualToString:@"/User"])
2662 else if (!_private && [file isEqualToString:@"/private"])
2664 else if (!stash && [file isEqualToString:@"/var/stash"])
2667 /* XXX: this is not sensitive enough. only some folders are valid. */
2668 if (cydia && !repository)
2669 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2671 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2673 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2675 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2678 return [warnings count] == 0 ? nil : warnings;
2681 - (NSArray *) applications {
2682 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2684 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2686 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2687 if (NSArray *files = [self files])
2688 for (NSString *file in files)
2689 if (application_r(file)) {
2690 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2691 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2692 if ([id isEqualToString:me])
2695 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2697 display = application_r[1];
2699 NSString *bundle([file stringByDeletingLastPathComponent]);
2700 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2701 if (icon == nil || [icon length] == 0)
2703 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2705 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2706 [applications addObject:application];
2708 [application addObject:id];
2709 [application addObject:display];
2710 [application addObject:url];
2713 return [applications count] == 0 ? nil : applications;
2716 - (Source *) source {
2717 if (source_ == nil) {
2718 @synchronized (database_) {
2719 if ([database_ era] != era_ || file_.end())
2720 source_ = (Source *) [NSNull null];
2722 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2726 return source_ == (Source *) [NSNull null] ? nil : source_;
2729 - (BOOL) matches:(NSString *)text {
2735 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2736 if (range.location != NSNotFound)
2739 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2740 if (range.location != NSNotFound)
2745 NSString *description([self shortDescription]);
2746 NSUInteger length([description length]);
2748 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_ range:NSMakeRange(0, std::min<NSUInteger>(length, 100))];
2749 if (range.location != NSNotFound)
2755 - (bool) hasSupportingRole {
2760 if ([Role_ isEqualToString:@"User"])
2764 if ([Role_ isEqualToString:@"Hacker"])
2768 if ([Role_ isEqualToString:@"Developer"])
2773 - (NSArray *) tags {
2777 - (BOOL) hasTag:(NSString *)tag {
2778 return tags_ == nil ? NO : [tags_ containsObject:tag];
2781 - (NSString *) primaryPurpose {
2782 for (NSString *tag in (NSArray *) tags_)
2783 if ([tag hasPrefix:@"purpose::"])
2784 return [tag substringFromIndex:9];
2788 - (NSArray *) purposes {
2789 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2790 for (NSString *tag in (NSArray *) tags_)
2791 if ([tag hasPrefix:@"purpose::"])
2792 [purposes addObject:[tag substringFromIndex:9]];
2793 return [purposes count] == 0 ? nil : purposes;
2796 - (bool) isCommercial {
2797 return [self hasTag:@"cydia::commercial"];
2800 - (void) setIndex:(size_t)index {
2801 if (metadata_->index_ != index)
2802 metadata_->index_ = index;
2805 - (CYString &) cyname {
2806 return name_.empty() ? id_ : name_;
2809 - (uint32_t) compareBySection:(NSArray *)sections {
2810 NSString *section([self section]);
2811 for (size_t i(0), e([sections count]); i != e; ++i) {
2812 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2816 return _not(uint32_t);
2820 @synchronized (database_) {
2821 pkgProblemResolver *resolver = [database_ resolver];
2822 resolver->Clear(iterator_);
2824 pkgCacheFile &cache([database_ cache]);
2825 cache->SetReInstall(iterator_, false);
2826 cache->MarkKeep(iterator_, false);
2830 @synchronized (database_) {
2831 pkgProblemResolver *resolver = [database_ resolver];
2832 resolver->Clear(iterator_);
2833 resolver->Protect(iterator_);
2835 pkgCacheFile &cache([database_ cache]);
2836 cache->SetReInstall(iterator_, false);
2837 cache->MarkInstall(iterator_, false);
2839 pkgDepCache::StateCache &state((*cache)[iterator_]);
2840 if (!state.Install())
2841 cache->SetReInstall(iterator_, true);
2845 @synchronized (database_) {
2846 pkgProblemResolver *resolver = [database_ resolver];
2847 resolver->Clear(iterator_);
2848 resolver->Remove(iterator_);
2849 resolver->Protect(iterator_);
2851 pkgCacheFile &cache([database_ cache]);
2852 cache->SetReInstall(iterator_, false);
2853 cache->MarkDelete(iterator_, true);
2856 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2857 _profile(Package$isUnfilteredAndSearchedForBy)
2860 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2861 value &= [self unfiltered];
2864 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2865 value &= [self matches:search];
2872 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2873 if ([search length] == 0)
2876 _profile(Package$isUnfilteredAndSelectedForBy)
2879 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2880 value &= [self unfiltered];
2883 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2884 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2891 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2892 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2895 - (bool) isVisibleInSection:(NSString *)name {
2896 NSString *section([self section]);
2900 section == nil && [name length] == 0 ||
2901 [name isEqualToString:section]
2902 ) && [self visible];
2905 - (bool) isVisibleInSource:(Source *)source {
2906 return [self source] == source && [self visible];
2911 /* Section Class {{{ */
2912 @interface Section : NSObject {
2917 _H<NSString> localized_;
2920 - (NSComparisonResult) compareByLocalized:(Section *)section;
2921 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2922 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2923 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2924 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2925 - (NSString *) name;
2932 - (void) addToCount;
2934 - (void) setCount:(size_t)count;
2935 - (NSString *) localized;
2939 @implementation Section
2941 - (NSComparisonResult) compareByLocalized:(Section *)section {
2942 NSString *lhs(localized_);
2943 NSString *rhs([section localized]);
2945 /*if ([lhs length] != 0 && [rhs length] != 0) {
2946 unichar lhc = [lhs characterAtIndex:0];
2947 unichar rhc = [rhs characterAtIndex:0];
2949 if (isalpha(lhc) && !isalpha(rhc))
2950 return NSOrderedAscending;
2951 else if (!isalpha(lhc) && isalpha(rhc))
2952 return NSOrderedDescending;
2955 return [lhs compare:rhs options:LaxCompareOptions_];
2958 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2959 if ((self = [self initWithName:name localize:NO]) != nil) {
2960 if (localized != nil)
2961 localized_ = localized;
2965 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2966 return [self initWithName:name row:0 localize:localize];
2969 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2970 if ((self = [super init]) != nil) {
2975 localized_ = LocalizeSection(name_);
2979 /* XXX: localize the index thingees */
2980 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2981 if ((self = [super init]) != nil) {
2982 name_ = [NSString stringWithCharacters:&index length:1];
2988 - (NSString *) name {
3008 - (void) addToCount {
3012 - (void) setCount:(size_t)count {
3016 - (NSString *) localized {
3023 static NSString *Colon_;
3024 static NSString *Elision_;
3025 static NSString *Error_;
3026 static NSString *Warning_;
3028 class CydiaLogCleaner :
3029 public pkgArchiveCleaner
3032 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3037 /* Database Implementation {{{ */
3038 @implementation Database
3040 + (Database *) sharedInstance {
3041 static _H<Database> instance;
3042 if (instance == nil)
3043 instance = [[[Database alloc] init] autorelease];
3051 - (void) releasePackages {
3052 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3053 CFArrayRemoveAllValues(packages_);
3057 // XXX: actually implement this thing
3059 [self releasePackages];
3060 apr_pool_destroy(pool_);
3061 NSRecycleZone(zone_);
3065 - (void) _readCydia:(NSNumber *)fd {
3066 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3067 std::istream is(&ib);
3070 static Pcre finish_r("^finish:([^:]*)$");
3072 while (std::getline(is, line)) {
3073 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3075 const char *data(line.c_str());
3076 size_t size = line.size();
3077 lprintf("C:%s\n", data);
3079 if (finish_r(data, size)) {
3080 NSString *finish = finish_r[1];
3081 int index = [Finishes_ indexOfObject:finish];
3082 if (index != INT_MAX && index > Finish_)
3092 - (void) _readStatus:(NSNumber *)fd {
3093 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3094 std::istream is(&ib);
3097 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3098 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3100 while (std::getline(is, line)) {
3101 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3103 const char *data(line.c_str());
3104 size_t size(line.size());
3105 lprintf("S:%s\n", data);
3107 if (conffile_r(data, size)) {
3108 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3109 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3110 } else if (strncmp(data, "status: ", 8) == 0) {
3111 // status: <package>: {unpacked,half-configured,installed}
3112 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3113 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3114 } else if (strncmp(data, "processing: ", 12) == 0) {
3115 // processing: configure: config-test
3116 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3117 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3118 } else if (pmstatus_r(data, size)) {
3119 std::string type([pmstatus_r[1] UTF8String]);
3121 NSString *package = pmstatus_r[2];
3122 if ([package isEqualToString:@"dpkg-exec"])
3125 float percent([pmstatus_r[3] floatValue]);
3126 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3128 NSString *string = pmstatus_r[4];
3130 if (type == "pmerror") {
3131 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3132 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3133 } else if (type == "pmstatus") {
3134 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3135 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3136 } else if (type == "pmconffile")
3137 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3139 lprintf("E:unknown pmstatus\n");
3141 lprintf("E:unknown status\n");
3149 - (void) _readOutput:(NSNumber *)fd {
3150 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3151 std::istream is(&ib);
3154 while (std::getline(is, line)) {
3155 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3157 lprintf("O:%s\n", line.c_str());
3159 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3160 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3172 - (Package *) packageWithName:(NSString *)name {
3173 @synchronized (self) {
3174 if (static_cast<pkgDepCache *>(cache_) == NULL)
3176 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3177 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3181 if ((self = [super init]) != nil) {
3188 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3189 apr_pool_create(&pool_, NULL);
3191 size_t capacity(MetaFile_->active_);
3197 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3198 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3202 _assert(pipe(fds) != -1);
3205 _config->Set("APT::Keep-Fds::", cydiafd_);
3206 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3209 detachNewThreadSelector:@selector(_readCydia:)
3211 withObject:[NSNumber numberWithInt:fds[0]]
3214 _assert(pipe(fds) != -1);
3218 detachNewThreadSelector:@selector(_readStatus:)
3220 withObject:[NSNumber numberWithInt:fds[0]]
3223 _assert(pipe(fds) != -1);
3224 _assert(dup2(fds[0], 0) != -1);
3225 _assert(close(fds[0]) != -1);
3227 input_ = fdopen(fds[1], "a");
3229 _assert(pipe(fds) != -1);
3230 _assert(dup2(fds[1], 1) != -1);
3231 _assert(close(fds[1]) != -1);
3234 detachNewThreadSelector:@selector(_readOutput:)
3236 withObject:[NSNumber numberWithInt:fds[0]]
3241 - (pkgCacheFile &) cache {
3245 - (pkgDepCache::Policy *) policy {
3249 - (pkgRecords *) records {
3253 - (pkgProblemResolver *) resolver {
3257 - (pkgAcquire &) fetcher {
3261 - (pkgSourceList &) list {
3265 - (NSArray *) packages {
3266 return (NSArray *) packages_;
3269 - (NSArray *) sources {
3273 - (Source *) sourceWithKey:(NSString *)key {
3274 for (Source *source in [self sources]) {
3275 if ([[source key] isEqualToString:key])
3280 - (bool) popErrorWithTitle:(NSString *)title {
3283 while (!_error->empty()) {
3285 bool warning(!_error->PopMessage(error));
3290 size_t size(error.size());
3291 if (size == 0 || error[size - 1] != '\n')
3293 error.resize(size - 1);
3296 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3298 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3304 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3305 return [self popErrorWithTitle:title] || !success;
3308 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3309 @synchronized (self) {
3312 [self releasePackages];
3315 [sourceList_ removeAllObjects];
3335 apr_pool_clear(pool_);
3337 NSRecycleZone(zone_);
3338 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3340 int chk(creat("/tmp/cydia.chk", 0644));
3344 if (invocation != nil)
3345 [invocation invoke];
3347 NSString *title(UCLocalize("DATABASE"));
3350 OpProgress progress;
3351 while (!cache_.Open(progress, true)) { pop:
3353 bool warning(!_error->PopMessage(error));
3354 lprintf("cache_.Open():[%s]\n", error.c_str());
3356 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3357 [delegate_ repairWithSelector:@selector(configure)];
3358 else if (error == "The package lists or status file could not be parsed or opened.")
3359 [delegate_ repairWithSelector:@selector(update)];
3360 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3361 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3362 // else if (error == "Malformed Status line")
3363 // else if (error == "The list of sources could not be read.")
3365 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3375 unlink("/tmp/cydia.chk");
3377 now_ = [[NSDate date] timeIntervalSince1970];
3379 policy_ = new pkgDepCache::Policy();
3380 records_ = new pkgRecords(cache_);
3381 resolver_ = new pkgProblemResolver(cache_);
3382 fetcher_ = new pkgAcquire(&status_);
3385 list_ = new pkgSourceList();
3386 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3389 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3390 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3394 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3397 if (cache_->BrokenCount() != 0) {
3398 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3401 if (cache_->BrokenCount() != 0) {
3402 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3406 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3410 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3411 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3412 [sourceList_ addObject:object];
3414 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3415 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3416 // XXX: this could be more intelligent
3417 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3418 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3420 sourceMap_[cached->ID] = object;
3425 /*std::vector<Package *> packages;
3426 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3431 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3432 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3433 //packages.push_back(package);
3434 CFArrayAppendValue(packages_, CFRetain(package));
3438 /*if (packages.empty())
3439 packages_ = [[NSArray alloc] init];
3441 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3444 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3445 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3446 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3454 /*if (!packages.empty())
3455 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3456 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3458 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3460 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3462 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3466 size_t count(CFArrayGetCount(packages_));
3467 MetaFile_->active_ = count;
3469 for (size_t index(0); index != count; ++index)
3470 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3477 @synchronized (self) {
3479 resolver_ = new pkgProblemResolver(cache_);
3481 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3482 if (!cache_[iterator].Keep())
3483 cache_->MarkKeep(iterator, false);
3484 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3485 cache_->SetReInstall(iterator, false);
3488 - (void) configure {
3489 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3491 system([dpkg UTF8String]);
3496 // XXX: I don't remember this condition
3501 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3503 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3505 if ([self popErrorWithTitle:title])
3509 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3511 CydiaLogCleaner cleaner;
3512 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3519 fetcher_->Shutdown();
3521 pkgRecords records(cache_);
3523 lock_ = new FileFd();
3524 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3526 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3528 if ([self popErrorWithTitle:title])
3532 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3535 manager_ = (_system->CreatePM(cache_));
3536 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3543 bool substrate(RestartSubstrate_);
3544 RestartSubstrate_ = false;
3546 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3548 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3550 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3552 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3553 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3556 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3558 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3560 [self popErrorWithTitle:title];
3564 bool failed = false;
3565 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3566 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3568 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3574 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3582 RestartSubstrate_ = true;
3585 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3587 if (_error->PendingError()) {
3592 if (result == pkgPackageManager::Failed) {
3597 if (result != pkgPackageManager::Completed) {
3602 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3604 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3606 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3607 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3610 if (![before isEqualToArray:after])
3615 NSString *title(UCLocalize("UPGRADE"));
3616 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3622 [self updateWithStatus:status_];
3625 - (void) updateWithStatus:(Status &)status {
3626 NSString *title(UCLocalize("REFRESHING_DATA"));
3629 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3633 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3634 if ([self popErrorWithTitle:title])
3637 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3639 bool success(ListUpdate(status, list, PulseInterval_));
3640 if (status.WasCancelled())
3643 [self popErrorWithTitle:title forOperation:success];
3644 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3648 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3651 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3652 delegate_ = delegate;
3655 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3656 progress_ = delegate;
3657 status_.setDelegate(delegate);
3660 - (NSObject<ProgressDelegate> *) progressDelegate {
3664 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3665 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3666 return i == sourceMap_.end() ? nil : i->second;
3669 - (NSString *) mappedSectionForPointer:(const char *)section {
3670 _H<NSString> *mapped;
3672 _profile(Database$mappedSectionForPointer$Cache)
3673 mapped = §ions_[section];
3676 if (*mapped == NULL) {
3677 size_t length(strlen(section));
3678 char spaced[length + 1];
3680 _profile(Database$mappedSectionForPointer$Replace)
3681 for (size_t index(0); index != length; ++index)
3682 spaced[index] = section[index] == '_' ? ' ' : section[index];
3683 spaced[length] = '\0';
3688 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3689 string = [NSString stringWithUTF8String:spaced];
3692 _profile(Database$mappedSectionForPointer$Map)
3693 string = [SectionMap_ objectForKey:string] ?: string;
3703 static _H<NSMutableSet> Diversions_;
3705 @interface Diversion : NSObject {
3708 _H<NSString> format_;
3713 @implementation Diversion
3715 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3716 if ((self = [super init]) != nil) {
3717 pattern_ = [from UTF8String];
3723 - (NSString *) divert:(NSString *)url {
3724 return !pattern_(url) ? nil : pattern_->*format_;
3727 + (NSURL *) divertURL:(NSURL *)url {
3729 NSString *href([url absoluteString]);
3731 for (Diversion *diversion in (id) Diversions_)
3732 if (NSString *diverted = [diversion divert:href]) {
3734 NSLog(@"div: %@", diverted);
3736 url = [NSURL URLWithString:diverted];
3743 - (NSString *) key {
3747 - (NSUInteger) hash {
3751 - (BOOL) isEqual:(Diversion *)object {
3752 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3757 @interface CydiaObject : NSObject {
3758 _H<IndirectDelegate> indirect_;
3759 _transient id delegate_;
3762 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3766 @interface CydiaWebViewController : CyteWebViewController {
3767 _H<CydiaObject> cydia_;
3770 + (void) addDiversion:(Diversion *)diversion;
3774 /* Web Scripting {{{ */
3775 @implementation CydiaObject
3777 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3778 if ((self = [super init]) != nil) {
3779 indirect_ = indirect;
3783 - (void) setDelegate:(id)delegate {
3784 delegate_ = delegate;
3787 + (NSArray *) _attributeKeys {
3788 return [NSArray arrayWithObjects:
3804 - (NSArray *) attributeKeys {
3805 return [[self class] _attributeKeys];
3808 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3809 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3812 - (NSString *) version {
3816 - (NSString *) device {
3817 return [[UIDevice currentDevice] uniqueIdentifier];
3820 - (NSString *) firmware {
3821 return [[UIDevice currentDevice] systemVersion];
3824 - (NSString *) hostname {
3825 return [[UIDevice currentDevice] name];
3828 - (NSString *) idiom {
3829 return (id) Idiom_ ?: [NSNull null];
3832 - (NSString *) plmn {
3833 return (id) PLMN_ ?: [NSNull null];
3836 - (NSString *) bbsnum {
3837 return (id) BBSNum_ ?: [NSNull null];
3840 - (NSString *) ecid {
3841 return (id) ChipID_ ?: [NSNull null];
3844 - (NSString *) serial {
3845 return SerialNumber_;
3848 - (NSString *) role {
3849 return (id) Role_ ?: [NSNull null];
3852 - (NSString *) model {
3853 return [NSString stringWithUTF8String:Machine_];
3856 - (NSString *) token {
3857 return (id) Token_ ?: [NSNull null];
3860 + (NSString *) webScriptNameForSelector:(SEL)selector {
3862 else if (selector == @selector(addBridgedHost:))
3863 return @"addBridgedHost";
3864 else if (selector == @selector(addInternalRedirect::))
3865 return @"addInternalRedirect";
3866 else if (selector == @selector(addPipelinedHost:scheme:))
3867 return @"addPipelinedHost";
3868 else if (selector == @selector(addTrivialSource:))
3869 return @"addTrivialSource";
3870 else if (selector == @selector(close))
3872 else if (selector == @selector(du:))
3874 else if (selector == @selector(stringWithFormat:arguments:))
3876 else if (selector == @selector(getAllSources))
3877 return @"getAllSourcs";
3878 else if (selector == @selector(getKernelNumber:))
3879 return @"getKernelNumber";
3880 else if (selector == @selector(getKernelString:))
3881 return @"getKernelString";
3882 else if (selector == @selector(getInstalledPackages))
3883 return @"getInstalledPackages";
3884 else if (selector == @selector(getIORegistryEntry::))
3885 return @"getIORegistryEntry";
3886 else if (selector == @selector(getLocaleIdentifier))
3887 return @"getLocaleIdentifier";
3888 else if (selector == @selector(getPreferredLanguages))
3889 return @"getPreferredLanguages";
3890 else if (selector == @selector(getPackageById:))
3891 return @"getPackageById";
3892 else if (selector == @selector(getSessionValue:))
3893 return @"getSessionValue";
3894 else if (selector == @selector(installPackages:))
3895 return @"installPackages";
3896 else if (selector == @selector(localizedStringForKey:value:table:))
3898 else if (selector == @selector(popViewController:))
3899 return @"popViewController";
3900 else if (selector == @selector(refreshSources))
3901 return @"refreshSources";
3902 else if (selector == @selector(removeButton))
3903 return @"removeButton";
3904 else if (selector == @selector(setSessionValue::))
3905 return @"setSessionValue";
3906 else if (selector == @selector(substitutePackageNames:))
3907 return @"substitutePackageNames";
3908 else if (selector == @selector(scrollToBottom:))
3909 return @"scrollToBottom";
3910 else if (selector == @selector(setAllowsNavigationAction:))
3911 return @"setAllowsNavigationAction";
3912 else if (selector == @selector(setBadgeValue:))
3913 return @"setBadgeValue";
3914 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3915 return @"setButtonImage";
3916 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3917 return @"setButtonTitle";
3918 else if (selector == @selector(setHidesBackButton:))
3919 return @"setHidesBackButton";
3920 else if (selector == @selector(setHidesNavigationBar:))
3921 return @"setHidesNavigationBar";
3922 else if (selector == @selector(setNavigationBarStyle:))
3923 return @"setNavigationBarStyle";
3924 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
3925 return @"setNavigationBarTintColor";
3926 else if (selector == @selector(setPasteboardString:))
3927 return @"setPasteboardString";
3928 else if (selector == @selector(setPasteboardURL:))
3929 return @"setPasteboardURL";
3930 else if (selector == @selector(setToken:))
3932 else if (selector == @selector(setViewportWidth:))
3933 return @"setViewportWidth";
3934 else if (selector == @selector(statfs:))
3936 else if (selector == @selector(supports:))
3942 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3943 return [self webScriptNameForSelector:selector] == nil;
3946 - (BOOL) supports:(NSString *)feature {
3947 return [feature isEqualToString:@"window.open"];
3950 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
3951 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
3954 - (NSNumber *) getKernelNumber:(NSString *)name {
3955 const char *string([name UTF8String]);
3958 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3959 return (id) [NSNull null];
3961 if (size != sizeof(int))
3962 return (id) [NSNull null];
3965 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3966 return (id) [NSNull null];
3968 return [NSNumber numberWithInt:value];
3971 - (NSString *) getKernelString:(NSString *)name {
3972 const char *string([name UTF8String]);
3975 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3976 return (id) [NSNull null];
3978 char value[size + 1];
3979 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3980 return (id) [NSNull null];
3982 // XXX: just in case you request something ludicrous
3985 return [NSString stringWithCString:value];
3988 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
3989 NSObject *value(CYIOGetValue([path UTF8String], entry));
3992 if ([value isKindOfClass:[NSData class]])
3993 value = CYHex((NSData *) value);
3998 - (id) getSessionValue:(NSString *)key {
3999 @synchronized (SessionData_) {
4000 return [SessionData_ objectForKey:key];
4003 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4004 @synchronized (SessionData_) {
4005 if (value == (id) [WebUndefined undefined])
4006 [SessionData_ removeObjectForKey:key];
4008 [SessionData_ setObject:value forKey:key];
4011 - (void) addBridgedHost:(NSString *)host {
4012 @synchronized (HostConfig_) {
4013 [BridgedHosts_ addObject:host];
4016 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4017 @synchronized (HostConfig_) {
4018 if (scheme != (id) [WebUndefined undefined])
4019 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4021 [PipelinedHosts_ addObject:host];
4024 - (void) popViewController:(NSNumber *)value {
4025 if (value == (id) [WebUndefined undefined])
4026 value = [NSNumber numberWithBool:YES];
4027 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4030 - (void) addTrivialSource:(NSString *)href {
4031 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4034 - (void) refreshSources {
4035 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4038 - (NSArray *) getAllSources {
4039 return [[Database sharedInstance] sources];
4042 - (NSArray *) getInstalledPackages {
4043 Database *database([Database sharedInstance]);
4044 @synchronized (database) {
4045 NSArray *packages([database packages]);
4046 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4047 for (Package *package in packages)
4048 if (![package uninstalled])
4049 [installed addObject:package];
4053 - (Package *) getPackageById:(NSString *)id {
4054 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4058 return (Package *) [NSNull null];
4061 - (NSString *) getLocaleIdentifier {
4062 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4065 - (NSArray *) getPreferredLanguages {
4069 - (NSArray *) statfs:(NSString *)path {
4072 if (path == nil || statfs([path UTF8String], &stat) == -1)
4075 return [NSArray arrayWithObjects:
4076 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4077 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4078 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4082 - (NSNumber *) du:(NSString *)path {
4083 NSNumber *value(nil);
4086 _assert(pipe(fds) != -1);
4088 pid_t pid(ExecFork());
4090 _assert(dup2(fds[1], 1) != -1);
4091 _assert(close(fds[0]) != -1);
4092 _assert(close(fds[1]) != -1);
4093 /* XXX: this should probably not use du */
4094 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4099 _assert(close(fds[1]) != -1);
4101 if (FILE *du = fdopen(fds[0], "r")) {
4103 while (fgets(line, sizeof(line), du) != NULL) {
4104 size_t length(strlen(line));
4105 while (length != 0 && line[length - 1] == '\n')
4106 line[--length] = '\0';
4107 if (char *tab = strchr(line, '\t')) {
4109 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4114 } else _assert(close(fds[0]));
4118 if (waitpid(pid, &status, 0) == -1)
4121 else _assert(false);
4127 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4130 - (void) installPackages:(NSArray *)packages {
4131 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4134 - (NSString *) substitutePackageNames:(NSString *)message {
4135 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4136 for (size_t i(0), e([words count]); i != e; ++i) {
4137 NSString *word([words objectAtIndex:i]);
4138 if (Package *package = [[Database sharedInstance] packageWithName:word])
4139 [words replaceObjectAtIndex:i withObject:[package name]];
4142 return [words componentsJoinedByString:@" "];
4145 - (void) removeButton {
4146 [indirect_ removeButton];
4149 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4150 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4153 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4154 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4157 - (void) setBadgeValue:(id)value {
4158 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4161 - (void) setAllowsNavigationAction:(NSString *)value {
4162 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4165 - (void) setHidesBackButton:(NSString *)value {
4166 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4169 - (void) setHidesNavigationBar:(NSString *)value {
4170 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4173 - (void) setNavigationBarStyle:(NSString *)value {
4174 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4177 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4178 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4179 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4180 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4183 - (void) setPasteboardString:(NSString *)value {
4184 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4187 - (void) setPasteboardURL:(NSString *)value {
4188 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4191 - (void) _setToken:(NSString *)token {
4195 [Metadata_ removeObjectForKey:@"Token"];
4197 [Metadata_ setObject:Token_ forKey:@"Token"];
4202 - (void) setToken:(NSString *)token {
4203 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4206 - (void) scrollToBottom:(NSNumber *)animated {
4207 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4210 - (void) setViewportWidth:(float)width {
4211 [indirect_ setViewportWidthOnMainThread:width];
4214 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4215 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4216 unsigned count([arguments count]);
4218 for (unsigned i(0); i != count; ++i)
4219 values[i] = [arguments objectAtIndex:i];
4220 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4223 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4224 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4226 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4228 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4234 /* @ Loading... Indicator {{{ */
4235 @interface CYLoadingIndicator : UIView {
4236 _H<UIActivityIndicatorView> spinner_;
4238 _H<UIView> container_;
4241 @property (readonly, nonatomic) UILabel *label;
4242 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4246 @implementation CYLoadingIndicator
4248 - (id) initWithFrame:(CGRect)frame {
4249 if ((self = [super initWithFrame:frame]) != nil) {
4250 container_ = [[[UIView alloc] init] autorelease];
4251 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4253 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4254 [spinner_ startAnimating];
4255 [container_ addSubview:spinner_];
4257 label_ = [[[UILabel alloc] init] autorelease];
4258 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4259 [label_ setBackgroundColor:[UIColor clearColor]];
4260 [label_ setTextColor:[UIColor blackColor]];
4261 [label_ setShadowColor:[UIColor whiteColor]];
4262 [label_ setShadowOffset:CGSizeMake(0, 1)];
4263 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4264 [container_ addSubview:label_];
4266 CGSize viewsize = frame.size;
4267 CGSize spinnersize = [spinner_ bounds].size;
4268 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4269 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4271 CGRect containrect = {
4272 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4273 CGSizeMake(bothwidth, spinnersize.height)
4276 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4284 [container_ setFrame:containrect];
4285 [spinner_ setFrame:spinrect];
4286 [label_ setFrame:textrect];
4287 [self addSubview:container_];
4291 - (UILabel *) label {
4295 - (UIActivityIndicatorView *) activityIndicatorView {
4301 /* Emulated Loading Controller {{{ */
4302 @interface CYEmulatedLoadingController : CyteViewController {
4303 _transient Database *database_;
4304 _H<CYLoadingIndicator> indicator_;
4305 _H<UITabBar> tabbar_;
4306 _H<UINavigationBar> navbar_;
4311 @implementation CYEmulatedLoadingController
4313 - (id) initWithDatabase:(Database *)database {
4314 if ((self = [super init]) != nil) {
4315 database_ = database;
4320 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4322 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4323 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4324 [[self view] addSubview:table];
4326 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4327 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4328 [[self view] addSubview:indicator_];
4330 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4331 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4332 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4333 [[self view] addSubview:tabbar_];
4335 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4336 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4337 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4338 [[self view] addSubview:navbar_];
4341 - (void) releaseSubviews {
4350 /* Cydia Browser Controller {{{ */
4351 @implementation CydiaWebViewController
4353 - (NSURL *) navigationURL {
4354 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4357 + (void) initialize {
4358 Diversions_ = [NSMutableSet setWithCapacity:0];
4361 + (void) addDiversion:(Diversion *)diversion {
4362 [Diversions_ addObject:diversion];
4365 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4366 [super webView:view didClearWindowObject:window forFrame:frame];
4368 WebDataSource *source([frame dataSource]);
4369 NSURLResponse *response([source response]);
4370 NSURL *url([response URL]);
4371 NSString *scheme([[url scheme] lowercaseString]);
4373 bool bridged(false);
4375 @synchronized (HostConfig_) {
4376 if ([scheme isEqualToString:@"file"])
4378 else if ([scheme isEqualToString:@"https"])
4379 if ([BridgedHosts_ containsObject:[url host]])
4384 [window setValue:cydia_ forKey:@"cydia"];
4387 - (NSURL *) URLWithURL:(NSURL *)url {
4388 return [Diversion divertURL:url];
4391 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4392 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4394 if (System_ != NULL)
4395 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4396 if (Machine_ != NULL)
4397 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4399 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4404 - (void) setDelegate:(id)delegate {
4405 [super setDelegate:delegate];
4406 [cydia_ setDelegate:delegate];
4410 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4411 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4413 WebView *webview([[webview_ _documentView] webView]);
4415 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4418 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4420 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4421 if (Product_ != nil)
4422 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4424 [webview setApplicationNameForUserAgent:application];
4432 @interface NSObject (CydiaScript)
4433 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4436 @implementation NSObject (CydiaScript)
4438 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4444 @implementation NSArray (CydiaScript)
4446 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4447 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4448 for (size_t i(0), e([self count]); i != e; ++i)
4449 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4455 @implementation NSDictionary (CydiaScript)
4457 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4458 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4460 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4467 /* Confirmation Controller {{{ */
4468 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4469 if (!iterator.end())
4470 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4471 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4473 pkgCache::PkgIterator package(dep.TargetPkg());
4476 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4483 @protocol ConfirmationControllerDelegate
4484 - (void) cancelAndClear:(bool)clear;
4485 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4489 @interface ConfirmationController : CydiaWebViewController {
4490 _transient Database *database_;
4492 _H<UIAlertView> essential_;
4494 _H<NSDictionary> changes_;
4495 _H<NSMutableArray> issues_;
4496 _H<NSDictionary> sizes_;
4501 - (id) initWithDatabase:(Database *)database;
4505 @implementation ConfirmationController
4509 RestartSubstrate_ = true;
4510 [delegate_ confirmWithNavigationController:[self navigationController]];
4513 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4514 NSString *context([alert context]);
4516 if ([context isEqualToString:@"remove"]) {
4517 if (button == [alert cancelButtonIndex])
4518 [self dismissModalViewControllerAnimated:YES];
4519 else if (button == [alert firstOtherButtonIndex]) {
4523 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4524 } else if ([context isEqualToString:@"unable"]) {
4525 [self dismissModalViewControllerAnimated:YES];
4526 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4528 [super alertView:alert clickedButtonAtIndex:button];
4532 - (void) _doContinue {
4533 [self dismissModalViewControllerAnimated:YES];
4534 [delegate_ cancelAndClear:NO];
4537 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4538 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4542 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4543 [super webView:view didClearWindowObject:window forFrame:frame];
4545 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4546 (id) changes_, @"changes",
4547 (id) issues_, @"issues",
4548 (id) sizes_, @"sizes",
4550 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4553 - (id) initWithDatabase:(Database *)database {
4554 if ((self = [super init]) != nil) {
4555 database_ = database;
4557 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4558 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4559 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4560 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4561 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4565 pkgCacheFile &cache([database_ cache]);
4566 NSArray *packages([database_ packages]);
4567 pkgDepCache::Policy *policy([database_ policy]);
4569 issues_ = [NSMutableArray arrayWithCapacity:4];
4571 for (Package *package in packages) {
4572 pkgCache::PkgIterator iterator([package iterator]);
4573 NSString *name([package id]);
4575 if ([package broken]) {
4576 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4578 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4580 reasons, @"reasons",
4583 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4587 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4588 pkgCache::DepIterator start;
4589 pkgCache::DepIterator end;
4590 dep.GlobOr(start, end); // ++dep
4592 if (!cache->IsImportantDep(end))
4594 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4597 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4599 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4600 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4601 clauses, @"clauses",
4605 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4607 pkgCache::PkgIterator target(start.TargetPkg());
4608 if (target->ProvidesList != 0)
4609 reason = @"missing";
4611 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4613 reason = @"installed";
4614 installed = [NSString stringWithUTF8String:ver.VerStr()];
4615 } else if (!cache[target].CandidateVerIter(cache).end())
4616 reason = @"uninstalled";
4617 else if (target->ProvidesList == 0)
4618 reason = @"uninstallable";
4620 reason = @"virtual";
4623 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4624 [NSString stringWithUTF8String:start.CompType()], @"operator",
4625 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4628 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4629 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4630 version, @"version",
4632 installed, @"installed",
4635 // yes, seriously. (wtf?)
4643 pkgDepCache::StateCache &state(cache[iterator]);
4645 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4647 if (state.NewInstall())
4648 [installs addObject:name];
4649 // XXX: else if (state.Install())
4650 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4651 [reinstalls addObject:name];
4652 // XXX: move before previous if
4653 else if (state.Upgrade())
4654 [upgrades addObject:name];
4655 else if (state.Downgrade())
4656 [downgrades addObject:name];
4657 else if (!state.Delete())
4658 // XXX: _assert(state.Keep());
4660 else if (special_r(name))
4661 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4662 [NSNull null], @"package",
4663 [NSArray arrayWithObjects:
4664 [NSDictionary dictionaryWithObjectsAndKeys:
4665 @"Conflicts", @"relationship",
4666 [NSArray arrayWithObjects:
4667 [NSDictionary dictionaryWithObjectsAndKeys:
4669 [NSNull null], @"version",
4670 @"installed", @"reason",
4677 if ([package essential])
4679 [removes addObject:name];
4682 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4683 substrate_ |= DepSubstrate(iterator.CurrentVer());
4688 else if (Advanced_) {
4689 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4691 essential_ = [[[UIAlertView alloc]
4692 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4693 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4695 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4697 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4701 [essential_ setContext:@"remove"];
4703 essential_ = [[[UIAlertView alloc]
4704 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4705 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4707 cancelButtonTitle:UCLocalize("OKAY")
4708 otherButtonTitles:nil
4711 [essential_ setContext:@"unable"];
4714 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4715 installs, @"installs",
4716 reinstalls, @"reinstalls",
4717 upgrades, @"upgrades",
4718 downgrades, @"downgrades",
4719 removes, @"removes",
4722 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4723 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4724 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4727 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4731 - (UIBarButtonItem *) leftButton {
4732 return [[[UIBarButtonItem alloc]
4733 initWithTitle:UCLocalize("CANCEL")
4734 style:UIBarButtonItemStylePlain
4736 action:@selector(cancelButtonClicked)
4741 - (void) applyRightButton {
4742 if ([issues_ count] == 0 && ![self isLoading])
4743 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4744 initWithTitle:UCLocalize("CONFIRM")
4745 style:UIBarButtonItemStyleDone
4747 action:@selector(confirmButtonClicked)
4750 [[self navigationItem] setRightBarButtonItem:nil];
4754 - (void) cancelButtonClicked {
4755 [self dismissModalViewControllerAnimated:YES];
4756 [delegate_ cancelAndClear:YES];
4760 - (void) confirmButtonClicked {
4761 if (essential_ != nil)
4771 /* Progress Data {{{ */
4772 @interface CydiaProgressData : NSObject {
4773 _transient id delegate_;
4782 _H<NSMutableArray> events_;
4783 _H<NSString> title_;
4785 _H<NSString> status_;
4786 _H<NSString> finish_;
4791 @implementation CydiaProgressData
4793 + (NSArray *) _attributeKeys {
4794 return [NSArray arrayWithObjects:
4806 - (NSArray *) attributeKeys {
4807 return [[self class] _attributeKeys];
4810 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4811 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4815 if ((self = [super init]) != nil) {
4816 events_ = [NSMutableArray arrayWithCapacity:32];
4820 - (void) setDelegate:(id)delegate {
4821 delegate_ = delegate;
4824 - (void) setPercent:(float)value {
4828 - (NSNumber *) percent {
4829 return [NSNumber numberWithFloat:percent_];
4832 - (void) setCurrent:(float)value {
4836 - (NSNumber *) current {
4837 return [NSNumber numberWithFloat:current_];
4840 - (void) setTotal:(float)value {
4844 - (NSNumber *) total {
4845 return [NSNumber numberWithFloat:total_];
4848 - (void) setSpeed:(float)value {
4852 - (NSNumber *) speed {
4853 return [NSNumber numberWithFloat:speed_];
4856 - (NSArray *) events {
4860 - (void) removeAllEvents {
4861 [events_ removeAllObjects];
4864 - (void) addEvent:(CydiaProgressEvent *)event {
4865 [events_ addObject:event];
4868 - (void) setTitle:(NSString *)text {
4872 - (NSString *) title {
4876 - (void) setFinish:(NSString *)text {
4880 - (NSString *) finish {
4881 return (id) finish_ ?: [NSNull null];
4884 - (void) setRunning:(bool)running {
4888 - (NSNumber *) running {
4889 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4894 /* Progress Controller {{{ */
4895 @interface ProgressController : CydiaWebViewController <
4898 _transient Database *database_;
4899 _H<CydiaProgressData, 1> progress_;
4903 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4905 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4907 - (void) setTitle:(NSString *)title;
4908 - (void) setCancellable:(bool)cancellable;
4912 @implementation ProgressController
4915 [database_ setProgressDelegate:nil];
4919 - (UIBarButtonItem *) leftButton {
4920 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
4921 initWithTitle:UCLocalize("CANCEL")
4922 style:UIBarButtonItemStylePlain
4924 action:@selector(cancel)
4925 ] autorelease] : nil;
4928 - (void) updateCancel {
4929 [super applyLeftButton];
4932 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4933 if ((self = [super init]) != nil) {
4934 database_ = database;
4935 delegate_ = delegate;
4937 [database_ setProgressDelegate:self];
4939 progress_ = [[[CydiaProgressData alloc] init] autorelease];
4940 [progress_ setDelegate:self];
4942 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
4944 [scroller_ setBackgroundColor:[UIColor blackColor]];
4946 [[self navigationItem] setHidesBackButton:YES];
4948 [self updateCancel];
4952 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4953 [super webView:view didClearWindowObject:window forFrame:frame];
4954 [window setValue:progress_ forKey:@"cydiaProgress"];
4957 - (void) updateProgress {
4958 [self dispatchEvent:@"CydiaProgressUpdate"];
4961 - (void) viewWillAppear:(BOOL)animated {
4962 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4963 [super viewWillAppear:animated];
4967 UpdateExternalStatus(0);
4974 [delegate_ terminateWithSuccess];
4975 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4976 [delegate_ suspendWithAnimation:YES];
4978 [delegate_ suspend];*/
4990 system("/usr/bin/sbreload");
4996 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4997 SBReboot(SBSSpringBoardServerPort());
4999 reboot2(RB_AUTOBOOT);
5006 - (void) setTitle:(NSString *)title {
5007 [progress_ setTitle:title];
5008 [self updateProgress];
5011 - (UIBarButtonItem *) rightButton {
5012 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5013 initWithTitle:UCLocalize("CLOSE")
5014 style:UIBarButtonItemStylePlain
5016 action:@selector(close)
5020 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5021 UpdateExternalStatus(1);
5023 [progress_ setRunning:true];
5024 [self setTitle:title];
5025 // implicit updateProgress
5027 SHA1SumValue notifyconf; {
5029 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5032 MMap mmap(file, MMap::ReadOnly);
5034 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5035 notifyconf = sha1.Result();
5039 SHA1SumValue springlist; {
5041 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5044 MMap mmap(file, MMap::ReadOnly);
5046 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5047 springlist = sha1.Result();
5051 if (invocation != nil) {
5052 [invocation yieldToSelector:@selector(invoke)];
5053 [self setTitle:@"COMPLETE"];
5058 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5061 MMap mmap(file, MMap::ReadOnly);
5063 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5064 if (!(notifyconf == sha1.Result()))
5071 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5074 MMap mmap(file, MMap::ReadOnly);
5076 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5077 if (!(springlist == sha1.Result()))
5083 if (RestartSubstrate_)
5087 RestartSubstrate_ = false;
5090 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5091 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5092 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5093 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5094 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5098 system("su -c /usr/bin/uicache mobile");
5101 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5103 [progress_ setRunning:false];
5104 [self updateProgress];
5106 [self applyRightButton];
5109 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5110 [progress_ addEvent:event];
5111 [self updateProgress];
5114 - (bool) isProgressCancelled {
5115 return cancel_ == 2;
5120 [self updateCancel];
5123 - (void) setCancellable:(bool)cancellable {
5124 unsigned cancel(cancel_);
5128 else if (cancel_ == 0)
5131 if (cancel != cancel_)
5132 [self updateCancel];
5135 - (void) setProgressCancellable:(NSNumber *)cancellable {
5136 [self setCancellable:[cancellable boolValue]];
5139 - (void) setProgressPercent:(NSNumber *)percent {
5140 [progress_ setPercent:[percent floatValue]];
5141 [self updateProgress];
5144 - (void) setProgressStatus:(NSDictionary *)status {
5145 if (status == nil) {
5146 [progress_ setCurrent:0];
5147 [progress_ setTotal:0];
5148 [progress_ setSpeed:0];
5150 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5152 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5153 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5154 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5157 [self updateProgress];
5163 /* Package Cell {{{ */
5164 @interface PackageCell : CyteTableViewCell <
5165 CyteTableViewCellDelegate
5169 _H<NSString> description_;
5171 _H<NSString> source_;
5173 _H<Package> package_;
5174 _H<UIImage> placard_;
5178 - (PackageCell *) init;
5179 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5181 - (void) drawContentRect:(CGRect)rect;
5185 @implementation PackageCell
5187 - (PackageCell *) init {
5188 CGRect frame(CGRectMake(0, 0, 320, 74));
5189 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5190 UIView *content([self contentView]);
5191 CGRect bounds([content bounds]);
5193 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5194 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5195 [content addSubview:content_];
5197 [content_ setDelegate:self];
5198 [content_ setOpaque:YES];
5202 - (NSString *) accessibilityLabel {
5203 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5206 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5207 summarized_ = summary;
5219 Source *source = [package source];
5221 icon_ = [package icon];
5222 name_ = [package name];
5225 description_ = [package longDescription];
5226 if (description_ == nil)
5227 description_ = [package shortDescription];
5229 commercial_ = [package isCommercial];
5233 NSString *label = nil;
5234 bool trusted = false;
5236 if (source != nil) {
5237 label = [source label];
5238 trusted = [source trusted];
5239 } else if ([[package id] isEqualToString:@"firmware"])
5240 label = UCLocalize("APPLE");
5242 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5244 NSString *from(label);
5246 NSString *section = [package simpleSection];
5247 if (section != nil && ![section isEqualToString:label]) {
5248 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5249 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5252 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5254 if (NSString *purpose = [package primaryPurpose])
5255 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5260 if (NSString *mode = [package_ mode]) {
5261 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5262 color = RemovingColor_;
5263 //placard = @"removing";
5265 color = InstallingColor_;
5266 //placard = @"installing";
5269 // XXX: the removing/installing placards are not @2x
5272 color = [UIColor whiteColor];
5274 if ([package installed] != nil)
5275 placard = @"installed";
5280 [content_ setBackgroundColor:color];
5283 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5285 [self setNeedsDisplay];
5286 [content_ setNeedsDisplay];
5289 - (void) drawSummaryContentRect:(CGRect)rect {
5290 bool highlighted(highlighted_);
5291 float width([self bounds].size.width);
5295 rect.size = [(UIImage *) icon_ size];
5297 rect.size.width /= 4;
5298 rect.size.height /= 4;
5300 rect.origin.x = 14 - rect.size.width / 4;
5301 rect.origin.y = 14 - rect.size.height / 4;
5303 [icon_ drawInRect:rect];
5306 if (badge_ != nil) {
5308 rect.size = [(UIImage *) badge_ size];
5310 rect.size.width /= 4;
5311 rect.size.height /= 4;
5313 rect.origin.x = 20 - rect.size.width / 4;
5314 rect.origin.y = 20 - rect.size.height / 4;
5316 [badge_ drawInRect:rect];
5323 UISetColor(commercial_ ? Purple_ : Black_);
5324 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5326 if (placard_ != nil)
5327 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5330 - (void) drawNormalContentRect:(CGRect)rect {
5331 bool highlighted(highlighted_);
5332 float width([self bounds].size.width);
5336 rect.size = [(UIImage *) icon_ size];
5338 rect.size.width /= 2;
5339 rect.size.height /= 2;
5341 rect.origin.x = 25 - rect.size.width / 2;
5342 rect.origin.y = 25 - rect.size.height / 2;
5344 [icon_ drawInRect:rect];
5347 if (badge_ != nil) {
5349 rect.size = [(UIImage *) badge_ size];
5351 rect.size.width /= 2;
5352 rect.size.height /= 2;
5354 rect.origin.x = 36 - rect.size.width / 2;
5355 rect.origin.y = 36 - rect.size.height / 2;
5357 [badge_ drawInRect:rect];
5364 UISetColor(commercial_ ? Purple_ : Black_);
5365 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5366 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5369 UISetColor(commercial_ ? Purplish_ : Gray_);
5370 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5372 if (placard_ != nil)
5373 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5376 - (void) drawContentRect:(CGRect)rect {
5378 [self drawSummaryContentRect:rect];
5380 [self drawNormalContentRect:rect];
5385 /* Section Cell {{{ */
5386 @interface SectionCell : CyteTableViewCell <
5387 CyteTableViewCellDelegate
5389 _H<NSString> basic_;
5390 _H<NSString> section_;
5392 _H<NSString> count_;
5394 _H<UISwitch> switch_;
5398 - (void) setSection:(Section *)section editing:(BOOL)editing;
5402 @implementation SectionCell
5404 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5405 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5406 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5407 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5408 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5410 UIView *content([self contentView]);
5411 CGRect bounds([content bounds]);
5413 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5414 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5415 [content addSubview:content_];
5416 [content_ setBackgroundColor:[UIColor whiteColor]];
5418 [content_ setDelegate:self];
5422 - (void) onSwitch:(id)sender {
5423 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5424 if (metadata == nil) {
5425 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5426 [Sections_ setObject:metadata forKey:basic_];
5429 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5433 - (void) setSection:(Section *)section editing:(BOOL)editing {
5434 if (editing != editing_) {
5436 [switch_ removeFromSuperview];
5438 [self addSubview:switch_];
5447 if (section == nil) {
5448 name_ = UCLocalize("ALL_PACKAGES");
5451 basic_ = [section name];
5452 section_ = [section localized];
5454 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5455 count_ = [NSString stringWithFormat:@"%d", [section count]];
5458 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5461 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5462 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5464 [content_ setNeedsDisplay];
5467 - (void) setFrame:(CGRect)frame {
5468 [super setFrame:frame];
5470 CGRect rect([switch_ frame]);
5471 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5474 - (NSString *) accessibilityLabel {
5478 - (void) drawContentRect:(CGRect)rect {
5479 bool highlighted(highlighted_ && !editing_);
5481 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5486 float width(rect.size.width);
5492 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5494 CGSize size = [count_ sizeWithFont:Font14_];
5498 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5504 /* File Table {{{ */
5505 @interface FileTable : CyteViewController <
5506 UITableViewDataSource,
5509 _transient Database *database_;
5510 _H<Package> package_;
5512 _H<NSMutableArray> files_;
5513 _H<UITableView, 2> list_;
5516 - (id) initWithDatabase:(Database *)database;
5517 - (void) setPackage:(Package *)package;
5521 @implementation FileTable
5523 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5524 return files_ == nil ? 0 : [files_ count];
5527 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5531 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5532 static NSString *reuseIdentifier = @"Cell";
5534 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5536 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5537 [cell setFont:[UIFont systemFontOfSize:16]];
5539 [cell setText:[files_ objectAtIndex:indexPath.row]];
5540 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5545 - (NSURL *) navigationURL {
5546 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5550 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5552 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5553 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5554 [list_ setRowHeight:24.0f];
5555 [(UITableView *) list_ setDataSource:self];
5556 [list_ setDelegate:self];
5557 [[self view] addSubview:list_];
5560 - (void) viewDidLoad {
5561 [super viewDidLoad];
5563 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5566 - (void) releaseSubviews {
5570 - (id) initWithDatabase:(Database *)database {
5571 if ((self = [super init]) != nil) {
5572 database_ = database;
5574 files_ = [NSMutableArray arrayWithCapacity:32];
5578 - (void) setPackage:(Package *)package {
5582 [files_ removeAllObjects];
5584 if (package != nil) {
5586 name_ = [package id];
5588 if (NSArray *files = [package files])
5589 [files_ addObjectsFromArray:files];
5591 if ([files_ count] != 0) {
5592 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5593 [files_ removeObjectAtIndex:0];
5594 [files_ sortUsingSelector:@selector(compareByPath:)];
5596 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5597 [stack addObject:@"/"];
5599 for (int i(0), e([files_ count]); i != e; ++i) {
5600 NSString *file = [files_ objectAtIndex:i];
5601 while (![file hasPrefix:[stack lastObject]])
5602 [stack removeLastObject];
5603 NSString *directory = [stack lastObject];
5604 [stack addObject:[file stringByAppendingString:@"/"]];
5605 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5606 ([stack count] - 2) * 3, "",
5607 [file substringFromIndex:[directory length]]
5616 - (void) reloadData {
5619 [self setPackage:[database_ packageWithName:name_]];
5624 /* Package Controller {{{ */
5625 @interface CYPackageController : CydiaWebViewController <
5626 UIActionSheetDelegate
5628 _transient Database *database_;
5629 _H<Package> package_;
5632 _H<NSMutableArray> buttons_;
5633 _H<UIBarButtonItem> button_;
5636 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5640 @implementation CYPackageController
5642 - (NSURL *) navigationURL {
5643 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5646 /* XXX: this is not safe at all... localization of /fail/ */
5647 - (void) _clickButtonWithName:(NSString *)name {
5648 if ([name isEqualToString:UCLocalize("CLEAR")])
5649 [delegate_ clearPackage:package_];
5650 else if ([name isEqualToString:UCLocalize("INSTALL")])
5651 [delegate_ installPackage:package_];
5652 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5653 [delegate_ installPackage:package_];
5654 else if ([name isEqualToString:UCLocalize("REMOVE")])
5655 [delegate_ removePackage:package_];
5656 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5657 [delegate_ installPackage:package_];
5658 else _assert(false);
5661 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5662 NSString *context([sheet context]);
5664 if ([context isEqualToString:@"modify"]) {
5665 if (button != [sheet cancelButtonIndex]) {
5666 NSString *buttonName = [buttons_ objectAtIndex:button];
5667 [self _clickButtonWithName:buttonName];
5670 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5674 - (bool) _allowJavaScriptPanel {
5679 - (void) _customButtonClicked {
5680 int count([buttons_ count]);
5685 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5687 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5688 [buttons addObjectsFromArray:buttons_];
5690 UIActionSheet *sheet = [[[UIActionSheet alloc]
5693 cancelButtonTitle:nil
5694 destructiveButtonTitle:nil
5695 otherButtonTitles:nil
5698 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5700 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5701 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5703 [sheet setContext:@"modify"];
5705 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5709 // We don't want to allow non-commercial packages to do custom things to the install button,
5710 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5711 - (void) customButtonClicked {
5713 [super customButtonClicked];
5715 [self _customButtonClicked];
5718 - (void) reloadButtonClicked {
5719 // Don't reload a commerical package by tapping the loading button,
5720 // but if it's not an Install button, we should forward it on.
5721 if (![package_ uninstalled])
5722 [self _customButtonClicked];
5725 - (void) applyLoadingTitle {
5726 // Don't show "Loading" as the title. Ever.
5729 - (UIBarButtonItem *) rightButton {
5734 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5735 if ((self = [super init]) != nil) {
5736 database_ = database;
5737 buttons_ = [NSMutableArray arrayWithCapacity:4];
5738 name_ = [NSString stringWithString:name];
5739 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5743 - (void) reloadData {
5746 package_ = [database_ packageWithName:name_];
5748 [buttons_ removeAllObjects];
5750 if (package_ != nil) {
5751 [(Package *) package_ parse];
5753 commercial_ = [package_ isCommercial];
5755 if ([package_ mode] != nil)
5756 [buttons_ addObject:UCLocalize("CLEAR")];
5757 if ([package_ source] == nil);
5758 else if ([package_ upgradableAndEssential:NO])
5759 [buttons_ addObject:UCLocalize("UPGRADE")];
5760 else if ([package_ uninstalled])
5761 [buttons_ addObject:UCLocalize("INSTALL")];
5763 [buttons_ addObject:UCLocalize("REINSTALL")];
5764 if (![package_ uninstalled])
5765 [buttons_ addObject:UCLocalize("REMOVE")];
5769 switch ([buttons_ count]) {
5770 case 0: title = nil; break;
5771 case 1: title = [buttons_ objectAtIndex:0]; break;
5772 default: title = UCLocalize("MODIFY"); break;
5775 button_ = [[[UIBarButtonItem alloc]
5777 style:UIBarButtonItemStylePlain
5779 action:@selector(customButtonClicked)
5783 - (bool) isLoading {
5784 return commercial_ ? [super isLoading] : false;
5790 /* Package List Controller {{{ */
5791 @interface PackageListController : CyteViewController <
5792 UITableViewDataSource,
5795 _transient Database *database_;
5797 _H<NSArray> packages_;
5798 _H<NSMutableArray> sections_;
5799 _H<UITableView, 2> list_;
5800 _H<NSMutableArray> index_;
5801 _H<NSMutableDictionary> indices_;
5802 _H<NSString> title_;
5803 unsigned reloading_;
5806 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5807 - (void) setDelegate:(id)delegate;
5808 - (void) resetCursor;
5813 @implementation PackageListController
5815 - (bool) isSummarized {
5819 - (void) deselectWithAnimation:(BOOL)animated {
5820 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5823 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5824 CGRect base = [[self view] bounds];
5825 base.size.height -= bounds.size.height;
5826 base.origin = [list_ frame].origin;
5828 [UIView beginAnimations:nil context:NULL];
5829 [UIView setAnimationBeginsFromCurrentState:YES];
5830 [UIView setAnimationCurve:curve];
5831 [UIView setAnimationDuration:duration];
5832 [list_ setFrame:base];
5833 [UIView commitAnimations];
5836 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5837 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5840 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5841 [self resizeForKeyboardBounds:bounds duration:0];
5844 - (void) keyboardWillShow:(NSNotification *)notification {
5847 NSTimeInterval duration;
5848 UIViewAnimationCurve curve;
5849 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5850 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5851 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5852 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5854 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);
5855 UIViewController *base = self;
5856 while ([base parentViewController] != nil)
5857 base = [base parentViewController];
5858 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5859 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5861 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5864 - (void) keyboardWillHide:(NSNotification *)notification {
5865 NSTimeInterval duration;
5866 UIViewAnimationCurve curve;
5867 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5868 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5870 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5873 - (void) viewWillAppear:(BOOL)animated {
5874 [super viewWillAppear:animated];
5876 [self resizeForKeyboardBounds:CGRectZero];
5877 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5878 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5881 - (void) viewWillDisappear:(BOOL)animated {
5882 [super viewWillDisappear:animated];
5884 [self resizeForKeyboardBounds:CGRectZero];
5885 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5886 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5889 - (void) viewDidAppear:(BOOL)animated {
5890 [super viewDidAppear:animated];
5891 [self deselectWithAnimation:animated];
5894 - (void) didSelectPackage:(Package *)package {
5895 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5896 [view setDelegate:delegate_];
5897 [[self navigationController] pushViewController:view animated:YES];
5900 #if TryIndexedCollation
5901 + (BOOL) hasIndexedCollation {
5902 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5906 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5907 NSInteger count([sections_ count]);
5908 return count == 0 ? 1 : count;
5911 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5912 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5914 return [[sections_ objectAtIndex:section] name];
5917 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5918 if ([sections_ count] == 0)
5920 return [[sections_ objectAtIndex:section] count];
5923 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5924 @synchronized (database_) {
5925 if ([database_ era] != era_)
5928 Section *section([sections_ objectAtIndex:[path section]]);
5929 NSInteger row([path row]);
5930 Package *package([packages_ objectAtIndex:([section row] + row)]);
5931 return [[package retain] autorelease];
5934 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5935 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5937 cell = [[[PackageCell alloc] init] autorelease];
5938 [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
5942 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5943 Package *package([self packageAtIndexPath:path]);
5944 package = [database_ packageWithName:[package id]];
5945 [self didSelectPackage:package];
5948 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5949 if ([self isSummarized])
5955 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5956 #if TryIndexedCollation
5957 if ([[self class] hasIndexedCollation]) {
5958 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5965 - (void) updateHeight {
5966 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
5969 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5970 if ((self = [super init]) != nil) {
5971 database_ = database;
5972 title_ = [title copy];
5973 [[self navigationItem] setTitle:title_];
5975 #if TryIndexedCollation
5976 if ([[self class] hasIndexedCollation])
5977 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
5980 index_ = [NSMutableArray arrayWithCapacity:32];
5982 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
5984 packages_ = [NSArray array];
5985 sections_ = [NSMutableArray arrayWithCapacity:16];
5987 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
5988 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5989 [[self view] addSubview:list_];
5991 // XXX: is 20 the most optimal number here?
5992 [list_ setSectionIndexMinimumDisplayRowCount:20];
5994 [(UITableView *) list_ setDataSource:self];
5995 [list_ setDelegate:self];
5997 [self updateHeight];
6001 - (void) setDelegate:(id)delegate {
6002 delegate_ = delegate;
6005 - (bool) hasPackage:(Package *)package {
6009 - (bool) shouldYield {
6013 - (bool) shouldBlock {
6017 - (NSArray *) _reloadPackages:(NSArray *)packages {
6018 // XXX: maybe move @synchronized() to _reloadData?
6019 @synchronized (database_) {
6020 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6022 _profile(PackageTable$reloadData$Filter)
6023 for (Package *package in packages)
6024 if ([self hasPackage:package])
6025 [filtered addObject:package];
6031 - (void) _reloadData {
6032 if (reloading_ != 0) {
6037 era_ = [database_ era];
6038 NSArray *packages = [database_ packages];
6040 if ([self shouldYield]) {
6043 if (![self shouldBlock])
6046 hud = [delegate_ addProgressHUD];
6047 [hud setText:UCLocalize("LOADING")];
6052 packages_ = [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
6053 } while (reloading_ == 2);
6058 [delegate_ removeProgressHUD:hud];
6060 packages_ = [self _reloadPackages:packages];
6063 [indices_ removeAllObjects];
6064 [sections_ removeAllObjects];
6066 Section *section = nil;
6068 #if TryIndexedCollation
6069 if ([[self class] hasIndexedCollation]) {
6070 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6071 NSArray *titles = [collation sectionIndexTitles];
6074 _profile(PackageTable$reloadData$Section)
6075 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6079 _profile(PackageTable$reloadData$Section$Package)
6080 package = [packages_ objectAtIndex:offset];
6081 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6084 while (secidx < index) {
6087 _profile(PackageTable$reloadData$Section$Allocate)
6088 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6091 _profile(PackageTable$reloadData$Section$Add)
6092 [sections_ addObject:section];
6096 [section addToCount];
6102 [index_ removeAllObjects];
6104 bool summary([self isSummarized]);
6106 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6107 [sections_ addObject:section];
6110 _profile(PackageTable$reloadData$Section)
6111 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6115 _profile(PackageTable$reloadData$Section$Package)
6116 package = [packages_ objectAtIndex:offset];
6117 index = [package index];
6120 if (!summary && (section == nil || [section index] != index)) {
6121 _profile(PackageTable$reloadData$Section$Allocate)
6122 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6125 [index_ addObject:[section name]];
6126 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6128 _profile(PackageTable$reloadData$Section$Add)
6129 [sections_ addObject:section];
6133 [section addToCount];
6138 [self updateHeight];
6140 _profile(PackageTable$reloadData$List)
6141 [(UITableView *) list_ setDataSource:self];
6146 - (void) reloadData {
6148 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6151 - (void) resetCursor {
6152 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6155 - (void) clearData {
6156 [self updateHeight];
6158 [list_ setDataSource:nil];
6166 /* Filtered Package List Controller {{{ */
6167 @interface FilteredPackageListController : PackageListController {
6170 _H<NSObject> object_;
6173 - (void) setObject:(id)object;
6174 - (void) setObject:(id)object forFilter:(SEL)filter;
6177 - (void) setFilter:(SEL)filter;
6179 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6183 @implementation FilteredPackageListController
6189 - (void) setFilter:(SEL)filter {
6192 /* XXX: this is an unsafe optimization of doomy hell */
6193 Method method(class_getInstanceMethod([Package class], filter));
6194 _assert(method != NULL);
6195 imp_ = method_getImplementation(method);
6196 _assert(imp_ != NULL);
6199 - (void) setObject:(id)object {
6203 - (void) setObject:(id)object forFilter:(SEL)filter {
6204 [self setFilter:filter];
6205 [self setObject:object];
6208 - (bool) hasPackage:(Package *)package {
6209 _profile(FilteredPackageTable$hasPackage)
6210 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6214 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6215 if ((self = [super initWithDatabase:database title:title]) != nil) {
6216 [self setFilter:filter];
6217 [self setObject:object];
6224 /* Home Controller {{{ */
6225 @interface HomeController : CydiaWebViewController {
6230 @implementation HomeController
6233 if ((self = [super init]) != nil) {
6234 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6239 - (NSURL *) navigationURL {
6240 return [NSURL URLWithString:@"cydia://home"];
6243 - (void) aboutButtonClicked {
6244 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6246 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6247 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6248 [alert setCancelButtonIndex:0];
6251 @"Copyright \u00a9 2008-2011\n"
6254 "Jay Freeman (saurik)\n"
6255 "saurik@saurik.com\n"
6256 "http://www.saurik.com/"
6262 - (UIBarButtonItem *) leftButton {
6263 return [[[UIBarButtonItem alloc]
6264 initWithTitle:UCLocalize("ABOUT")
6265 style:UIBarButtonItemStylePlain
6267 action:@selector(aboutButtonClicked)
6271 - (void) unloadData {
6278 /* Manage Controller {{{ */
6279 @interface ManageController : CydiaWebViewController {
6282 - (void) queueStatusDidChange;
6286 @implementation ManageController
6289 if ((self = [super init]) != nil) {
6290 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6294 - (NSURL *) navigationURL {
6295 return [NSURL URLWithString:@"cydia://manage"];
6298 - (UIBarButtonItem *) leftButton {
6299 return [[[UIBarButtonItem alloc]
6300 initWithTitle:UCLocalize("SETTINGS")
6301 style:UIBarButtonItemStylePlain
6303 action:@selector(settingsButtonClicked)
6307 - (void) settingsButtonClicked {
6308 [delegate_ showSettings];
6311 - (void) queueButtonClicked {
6315 - (UIBarButtonItem *) customButton {
6316 return Queuing_ ? [[[UIBarButtonItem alloc]
6317 initWithTitle:UCLocalize("QUEUE")
6318 style:UIBarButtonItemStyleDone
6320 action:@selector(queueButtonClicked)
6321 ] autorelease] : [super customButton];
6324 - (void) queueStatusDidChange {
6325 [self applyRightButton];
6328 - (bool) isLoading {
6329 return !Queuing_ && [super isLoading];
6335 /* Refresh Bar {{{ */
6336 @interface RefreshBar : UINavigationBar {
6337 _H<UIProgressIndicator> indicator_;
6338 _H<UITextLabel> prompt_;
6339 _H<UIProgressBar> progress_;
6340 _H<UINavigationButton> cancel_;
6345 @implementation RefreshBar
6347 - (void) positionViews {
6348 CGRect frame = [cancel_ frame];
6349 frame.size = [cancel_ sizeThatFits:frame.size];
6350 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6351 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6352 [cancel_ setFrame:frame];
6354 CGSize prgsize = {75, 100};
6356 [self frame].size.width - prgsize.width - 10,
6357 ([self frame].size.height - prgsize.height) / 2
6359 [progress_ setFrame:prgrect];
6361 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6362 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6363 CGRect indrect = {{indoffset, indoffset}, indsize};
6364 [indicator_ setFrame:indrect];
6366 CGSize prmsize = {215, indsize.height + 4};
6368 indoffset * 2 + indsize.width,
6369 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6371 [prompt_ setFrame:prmrect];
6374 - (void) setFrame:(CGRect)frame {
6375 [super setFrame:frame];
6376 [self positionViews];
6379 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6380 if ((self = [super initWithFrame:frame]) != nil) {
6381 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6383 [self setBarStyle:UIBarStyleBlack];
6385 UIBarStyle barstyle([self _barStyle:NO]);
6386 bool ugly(barstyle == UIBarStyleDefault);
6388 UIProgressIndicatorStyle style = ugly ?
6389 UIProgressIndicatorStyleMediumBrown :
6390 UIProgressIndicatorStyleMediumWhite;
6392 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6393 [(UIProgressIndicator *) indicator_ setStyle:style];
6394 [indicator_ startAnimation];
6395 [self addSubview:indicator_];
6397 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6398 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6399 [prompt_ setBackgroundColor:[UIColor clearColor]];
6400 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6401 [self addSubview:prompt_];
6403 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6404 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6405 [(UIProgressBar *) progress_ setStyle:0];
6406 [self addSubview:progress_];
6408 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6409 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6410 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6411 [cancel_ setBarStyle:barstyle];
6413 [self positionViews];
6417 - (void) setCancellable:(bool)cancellable {
6419 [self addSubview:cancel_];
6421 [cancel_ removeFromSuperview];
6425 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6426 [progress_ setProgress:0];
6430 [self setCancellable:NO];
6433 - (void) setPrompt:(NSString *)prompt {
6434 [prompt_ setText:prompt];
6437 - (void) setProgress:(float)progress {
6438 [progress_ setProgress:progress];
6444 /* Cydia Navigation Controller Interface {{{ */
6445 @interface UINavigationController (Cydia)
6447 - (NSArray *) navigationURLCollection;
6448 - (void) unloadData;
6453 /* Cydia Tab Bar Controller {{{ */
6454 @interface CYTabBarController : UITabBarController <
6455 UITabBarControllerDelegate,
6458 _transient Database *database_;
6459 _H<RefreshBar, 1> refreshbar_;
6463 // XXX: ok, "updatedelegate_"?...
6464 _transient NSObject<CydiaDelegate> *updatedelegate_;
6466 _H<UIViewController> remembered_;
6467 _transient UIViewController *transient_;
6470 - (NSArray *) navigationURLCollection;
6471 - (void) dropBar:(BOOL)animated;
6472 - (void) beginUpdate;
6473 - (void) raiseBar:(BOOL)animated;
6475 - (void) unloadData;
6479 @implementation CYTabBarController
6481 - (void) setUnselectedViewController:(UIViewController *)transient {
6482 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6483 if (transient != nil) {
6484 if (transient_ == nil)
6485 remembered_ = [controllers objectAtIndex:0];
6486 transient_ = transient;
6487 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6488 [controllers replaceObjectAtIndex:0 withObject:transient_];
6489 [self setSelectedIndex:0];
6490 [self setViewControllers:controllers];
6491 [self concealTabBarSelection];
6492 } else if (remembered_ != nil) {
6493 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6494 transient_ = transient;
6495 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6497 [self setViewControllers:controllers];
6498 [self revealTabBarSelection];
6502 - (UIViewController *) unselectedViewController {
6506 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6507 if ([self unselectedViewController])
6508 [self setUnselectedViewController:nil];
6511 - (NSArray *) navigationURLCollection {
6512 NSMutableArray *items([NSMutableArray array]);
6514 // XXX: Should this deal with transient view controllers?
6515 for (id navigation in [self viewControllers]) {
6516 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6518 [items addObject:stack];
6524 - (void) unloadData {
6525 UIViewController *selected([self selectedViewController]);
6526 for (UINavigationController *controller in [self viewControllers])
6527 [controller unloadData];
6529 [selected reloadData];
6531 if (UIViewController *unselected = [self unselectedViewController])
6532 [unselected reloadData];
6538 [[NSNotificationCenter defaultCenter] removeObserver:self];
6543 - (id) initWithDatabase:(Database *)database {
6544 if ((self = [super init]) != nil) {
6545 database_ = database;
6546 [self setDelegate:self];
6548 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6549 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6551 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6555 - (void) setUpdate:(NSDate *)date {
6559 - (void) beginUpdate {
6560 [(RefreshBar *) refreshbar_ start];
6563 [updatedelegate_ retainNetworkActivityIndicator];
6567 detachNewThreadSelector:@selector(performUpdate)
6573 - (void) performUpdate {
6574 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6577 status.setDelegate(self);
6578 [database_ updateWithStatus:status];
6581 performSelectorOnMainThread:@selector(completeUpdate)
6589 - (void) stopUpdateWithSelector:(SEL)selector {
6591 [updatedelegate_ releaseNetworkActivityIndicator];
6593 [self raiseBar:YES];
6596 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6599 - (void) completeUpdate {
6602 [self stopUpdateWithSelector:@selector(reloadData)];
6605 - (void) cancelUpdate {
6606 [self stopUpdateWithSelector:@selector(updateData)];
6609 - (void) cancelPressed {
6610 [self cancelUpdate];
6617 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6618 [refreshbar_ setPrompt:[event compoundMessage]];
6621 - (bool) isProgressCancelled {
6625 - (void) setProgressCancellable:(NSNumber *)cancellable {
6626 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6629 - (void) setProgressPercent:(NSNumber *)percent {
6630 [refreshbar_ setProgress:[percent floatValue]];
6633 - (void) setProgressStatus:(NSDictionary *)status {
6635 [self setProgressPercent:[status objectForKey:@"Percent"]];
6638 - (void) setUpdateDelegate:(id)delegate {
6639 updatedelegate_ = delegate;
6642 - (CGFloat) statusBarHeight {
6643 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6644 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6646 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6650 - (UIView *) transitionView {
6651 if ([self respondsToSelector:@selector(_transitionView)])
6652 return [self _transitionView];
6654 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6657 - (void) dropBar:(BOOL)animated {
6662 UIView *transition([self transitionView]);
6663 [[self view] addSubview:refreshbar_];
6665 CGRect barframe([refreshbar_ frame]);
6667 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6668 barframe.origin.y = [self statusBarHeight];
6670 barframe.origin.y = 0;
6672 [refreshbar_ setFrame:barframe];
6675 [UIView beginAnimations:nil context:NULL];
6677 CGRect viewframe = [transition frame];
6678 viewframe.origin.y += barframe.size.height;
6679 viewframe.size.height -= barframe.size.height;
6680 [transition setFrame:viewframe];
6683 [UIView commitAnimations];
6685 // Ensure bar has the proper width for our view, it might have changed
6686 barframe.size.width = viewframe.size.width;
6687 [refreshbar_ setFrame:barframe];
6690 - (void) raiseBar:(BOOL)animated {
6695 UIView *transition([self transitionView]);
6696 [refreshbar_ removeFromSuperview];
6698 CGRect barframe([refreshbar_ frame]);
6701 [UIView beginAnimations:nil context:NULL];
6703 CGRect viewframe = [transition frame];
6704 viewframe.origin.y -= barframe.size.height;
6705 viewframe.size.height += barframe.size.height;
6706 [transition setFrame:viewframe];
6709 [UIView commitAnimations];
6712 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6713 bool dropped(dropped_);
6718 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6724 - (void) statusBarFrameChanged:(NSNotification *)notification {
6734 /* Cydia Navigation Controller Implementation {{{ */
6735 @implementation UINavigationController (Cydia)
6737 - (NSArray *) navigationURLCollection {
6738 NSMutableArray *stack([NSMutableArray array]);
6740 for (CyteViewController *controller in [self viewControllers]) {
6741 NSString *url = [[controller navigationURL] absoluteString];
6743 [stack addObject:url];
6749 - (void) reloadData {
6752 if (UIViewController *visible = [self visibleViewController])
6753 [visible reloadData];
6756 - (void) unloadData {
6757 for (CyteViewController *page in [self viewControllers])
6766 /* Cydia:// Protocol {{{ */
6767 @interface CydiaURLProtocol : NSURLProtocol {
6772 @implementation CydiaURLProtocol
6774 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6775 NSURL *url([request URL]);
6779 NSString *scheme([[url scheme] lowercaseString]);
6780 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6782 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6788 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6792 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6793 id<NSURLProtocolClient> client([self client]);
6795 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6797 NSData *data(UIImagePNGRepresentation(icon));
6799 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6800 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6801 [client URLProtocol:self didLoadData:data];
6802 [client URLProtocolDidFinishLoading:self];
6806 - (void) startLoading {
6807 id<NSURLProtocolClient> client([self client]);
6808 NSURLRequest *request([self request]);
6810 NSURL *url([request URL]);
6811 NSString *href([url absoluteString]);
6812 NSString *scheme([[url scheme] lowercaseString]);
6816 if ([scheme isEqualToString:@"cydia"])
6817 path = [href substringFromIndex:8];
6818 else if ([scheme isEqualToString:@"about"])
6819 path = [href substringFromIndex:12];
6820 else _assert(false);
6822 NSRange slash([path rangeOfString:@"/"]);
6825 if (slash.location == NSNotFound) {
6829 command = [path substringToIndex:slash.location];
6830 path = [path substringFromIndex:(slash.location + 1)];
6833 Database *database([Database sharedInstance]);
6835 if ([command isEqualToString:@"package-icon"]) {
6838 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6839 Package *package([database packageWithName:path]);
6843 UIImage *icon([package icon]);
6844 [self _returnPNGWithImage:icon forRequest:request];
6845 } else if ([command isEqualToString:@"source-icon"]) {
6848 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6849 NSString *source(Simplify(path));
6850 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6852 icon = [UIImage applicationImageNamed:@"unknown.png"];
6853 [self _returnPNGWithImage:icon forRequest:request];
6854 } else if ([command isEqualToString:@"uikit-image"]) {
6857 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6858 UIImage *icon(_UIImageWithName(path));
6859 [self _returnPNGWithImage:icon forRequest:request];
6860 } else if ([command isEqualToString:@"section-icon"]) {
6863 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6864 NSString *section(Simplify(path));
6865 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6867 icon = [UIImage applicationImageNamed:@"unknown.png"];
6868 [self _returnPNGWithImage:icon forRequest:request];
6870 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6874 - (void) stopLoading {
6880 /* Section Controller {{{ */
6881 @interface SectionController : FilteredPackageListController {
6882 _H<NSString> section_;
6885 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6889 @implementation SectionController
6891 - (NSURL *) navigationURL {
6892 NSString *name = section_;
6896 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6899 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6902 title = UCLocalize("ALL_PACKAGES");
6903 else if (![name isEqual:@""])
6904 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6906 title = UCLocalize("NO_SECTION");
6908 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6915 /* Sections Controller {{{ */
6916 @interface SectionsController : CyteViewController <
6917 UITableViewDataSource,
6920 _transient Database *database_;
6921 _H<NSMutableArray> sections_;
6922 _H<NSMutableArray> filtered_;
6923 _H<UITableView, 2> list_;
6926 - (id) initWithDatabase:(Database *)database;
6927 - (void) editButtonClicked;
6931 @implementation SectionsController
6933 - (NSURL *) navigationURL {
6934 return [NSURL URLWithString:@"cydia://sections"];
6937 - (void) updateNavigationItem {
6938 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6939 if ([sections_ count] == 0) {
6940 [[self navigationItem] setRightBarButtonItem:nil];
6942 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6943 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6945 action:@selector(editButtonClicked)
6946 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6950 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6951 [super setEditing:editing animated:animated];
6956 [delegate_ updateData];
6958 [self updateNavigationItem];
6961 - (void) viewDidAppear:(BOOL)animated {
6962 [super viewDidAppear:animated];
6963 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6966 - (void) viewWillDisappear:(BOOL)animated {
6967 [super viewWillDisappear:animated];
6968 if ([self isEditing]) [self setEditing:NO];
6971 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6972 Section *section = nil;
6973 int index = [indexPath row];
6974 if (![self isEditing]) {
6977 section = [filtered_ objectAtIndex:index];
6979 section = [sections_ objectAtIndex:index];
6984 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6985 if ([self isEditing])
6986 return [sections_ count];
6988 return [filtered_ count] + 1;
6991 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6995 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6996 static NSString *reuseIdentifier = @"SectionCell";
6998 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7000 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7002 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7007 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7008 if ([self isEditing])
7011 Section *section = [self sectionAtIndexPath:indexPath];
7013 SectionController *controller = [[[SectionController alloc]
7014 initWithDatabase:database_
7015 section:[section name]
7017 [controller setDelegate:delegate_];
7019 [[self navigationController] pushViewController:controller animated:YES];
7023 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7025 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7026 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7027 [list_ setRowHeight:45.0f];
7028 [(UITableView *) list_ setDataSource:self];
7029 [list_ setDelegate:self];
7030 [[self view] addSubview:list_];
7033 - (void) viewDidLoad {
7034 [super viewDidLoad];
7036 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7039 - (void) releaseSubviews {
7043 - (id) initWithDatabase:(Database *)database {
7044 if ((self = [super init]) != nil) {
7045 database_ = database;
7047 sections_ = [NSMutableArray arrayWithCapacity:16];
7048 filtered_ = [NSMutableArray arrayWithCapacity:16];
7052 - (void) reloadData {
7055 NSArray *packages = [database_ packages];
7057 [sections_ removeAllObjects];
7058 [filtered_ removeAllObjects];
7060 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7063 for (Package *package in packages) {
7064 NSString *name([package section]);
7065 NSString *key(name == nil ? @"" : name);
7069 _profile(SectionsView$reloadData$Section)
7070 section = [sections objectForKey:key];
7071 if (section == nil) {
7072 _profile(SectionsView$reloadData$Section$Allocate)
7073 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7074 [sections setObject:section forKey:key];
7079 [section addToCount];
7081 _profile(SectionsView$reloadData$Filter)
7082 if (![package valid] || ![package visible])
7090 [sections_ addObjectsFromArray:[sections allValues]];
7092 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7094 for (Section *section in (id) sections_) {
7095 size_t count([section row]);
7099 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7100 [section setCount:count];
7101 [filtered_ addObject:section];
7104 [self updateNavigationItem];
7109 - (void) editButtonClicked {
7110 [self setEditing:![self isEditing] animated:YES];
7116 /* Changes Controller {{{ */
7117 @interface ChangesController : CyteViewController <
7118 UITableViewDataSource,
7121 _transient Database *database_;
7123 _H<NSArray> packages_;
7124 _H<NSMutableArray> sections_;
7125 _H<UITableView, 2> list_;
7129 - (id) initWithDatabase:(Database *)database;
7133 @implementation ChangesController
7135 - (NSURL *) navigationURL {
7136 return [NSURL URLWithString:@"cydia://changes"];
7139 - (void) viewDidAppear:(BOOL)animated {
7140 [super viewDidAppear:animated];
7141 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7144 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7145 NSInteger count([sections_ count]);
7146 return count == 0 ? 1 : count;
7149 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7150 if ([sections_ count] == 0)
7152 return [[sections_ objectAtIndex:section] name];
7155 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7156 if ([sections_ count] == 0)
7158 return [[sections_ objectAtIndex:section] count];
7161 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7162 @synchronized (database_) {
7163 if ([database_ era] != era_)
7166 NSUInteger sectionIndex([path section]);
7167 if (sectionIndex >= [sections_ count])
7169 Section *section([sections_ objectAtIndex:sectionIndex]);
7170 NSInteger row([path row]);
7171 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7174 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7175 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7177 cell = [[[PackageCell alloc] init] autorelease];
7178 [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
7182 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7183 Package *package([self packageAtIndexPath:path]);
7184 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7185 [view setDelegate:delegate_];
7186 [[self navigationController] pushViewController:view animated:YES];
7190 - (void) refreshButtonClicked {
7191 [delegate_ beginUpdate];
7192 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7195 - (void) upgradeButtonClicked {
7196 [delegate_ distUpgrade];
7200 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7202 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7203 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7204 [list_ setRowHeight:73];
7205 [(UITableView *) list_ setDataSource:self];
7206 [list_ setDelegate:self];
7207 [[self view] addSubview:list_];
7210 - (void) viewDidLoad {
7211 [super viewDidLoad];
7213 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7216 - (void) releaseSubviews {
7220 - (id) initWithDatabase:(Database *)database {
7221 if ((self = [super init]) != nil) {
7222 database_ = database;
7224 packages_ = [NSArray array];
7225 sections_ = [NSMutableArray arrayWithCapacity:16];
7229 - (NSArray *) _reloadPackages:(NSArray *)packages {
7230 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7233 _profile(ChangesController$_reloadPackages$Filter)
7234 for (Package *package in packages)
7235 if ([package upgradableAndEssential:YES] || [package visible])
7236 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7239 _profile(ChangesController$_reloadPackages$radixSort)
7240 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7247 - (void) _reloadData {
7248 @synchronized (database_) {
7249 era_ = [database_ era];
7250 NSArray *packages = [database_ packages];
7253 UIProgressHUD *hud([delegate_ addProgressHUD]);
7254 [hud setText:UCLocalize("LOADING")];
7255 //NSLog(@"HUD:%@::%@", delegate_, hud);
7256 packages_ = [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7257 [delegate_ removeProgressHUD:hud];
7259 packages_ = [self _reloadPackages:packages];
7262 [sections_ removeAllObjects];
7264 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7265 Section *ignored = nil;
7266 Section *section = nil;
7270 bool unseens = false;
7272 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7274 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7275 Package *package = [packages_ objectAtIndex:offset];
7277 BOOL uae = [package upgradableAndEssential:YES];
7281 time_t seen([package seen]);
7283 if (section == nil || last != seen) {
7287 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7290 _profile(ChangesController$reloadData$Allocate)
7291 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7292 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7293 [sections_ addObject:section];
7297 [section addToCount];
7298 } else if ([package ignored]) {
7299 if (ignored == nil) {
7300 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7302 [ignored addToCount];
7305 [upgradable addToCount];
7310 CFRelease(formatter);
7313 Section *last = [sections_ lastObject];
7314 size_t count = [last count];
7315 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7316 [sections_ removeLastObject];
7319 if ([ignored count] != 0)
7320 [sections_ insertObject:ignored atIndex:0];
7322 [sections_ insertObject:upgradable atIndex:0];
7327 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7328 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7329 style:UIBarButtonItemStylePlain
7331 action:@selector(upgradeButtonClicked)
7334 if (![delegate_ updating])
7335 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7336 initWithTitle:UCLocalize("REFRESH")
7337 style:UIBarButtonItemStylePlain
7339 action:@selector(refreshButtonClicked)
7345 - (void) reloadData {
7347 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7352 /* Search Controller {{{ */
7353 @interface SearchController : FilteredPackageListController <
7356 _H<UISearchBar, 1> search_;
7360 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7361 - (void) reloadData;
7365 @implementation SearchController
7367 - (NSURL *) navigationURL {
7368 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7369 return [NSURL URLWithString:@"cydia://search"];
7371 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7374 - (void) useSearch {
7375 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7380 - (void) viewWillAppear:(BOOL)animated {
7381 [super viewWillAppear:animated];
7383 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7387 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7388 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7393 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7394 [search_ resignFirstResponder];
7398 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7399 [search_ setText:@""];
7400 [self searchBarButtonClicked:searchBar];
7403 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7404 [self searchBarButtonClicked:searchBar];
7407 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7408 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7412 - (bool) shouldYield {
7416 - (bool) shouldBlock {
7417 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7420 - (bool) isSummarized {
7421 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7424 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7425 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:query])) {
7426 search_ = [[[UISearchBar alloc] init] autorelease];
7427 [search_ setDelegate:self];
7430 [search_ setText:query];
7434 - (void) viewDidAppear:(BOOL)animated {
7435 [super viewDidAppear:animated];
7437 if (!searchloaded_) {
7438 searchloaded_ = YES;
7439 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7440 [search_ layoutSubviews];
7441 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7443 UITextField *textField;
7444 if ([search_ respondsToSelector:@selector(searchField)])
7445 textField = [search_ searchField];
7447 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7449 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7450 [textField setEnablesReturnKeyAutomatically:NO];
7451 [[self navigationItem] setTitleView:textField];
7455 - (void) reloadData {
7456 [self setObject:[search_ text]];
7462 - (void) didSelectPackage:(Package *)package {
7463 [search_ resignFirstResponder];
7464 [super didSelectPackage:package];
7469 /* Package Settings Controller {{{ */
7470 @interface PackageSettingsController : CyteViewController <
7471 UITableViewDataSource,
7474 _transient Database *database_;
7476 _H<Package> package_;
7477 _H<UITableView, 2> table_;
7478 _H<UISwitch> subscribedSwitch_;
7479 _H<UISwitch> ignoredSwitch_;
7480 _H<UITableViewCell> subscribedCell_;
7481 _H<UITableViewCell> ignoredCell_;
7484 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7488 @implementation PackageSettingsController
7490 - (NSURL *) navigationURL {
7491 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7494 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7495 if (package_ == nil)
7498 if ([package_ installed] == nil)
7504 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7505 if (package_ == nil)
7508 // both sections contain just one item right now.
7512 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7516 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7518 return UCLocalize("SHOW_ALL_CHANGES_EX");
7520 return UCLocalize("IGNORE_UPGRADES_EX");
7523 - (void) onSubscribed:(id)control {
7524 bool value([control isOn]);
7525 if (package_ == nil)
7527 if ([package_ setSubscribed:value])
7528 [delegate_ updateData];
7531 - (void) _updateIgnored {
7532 const char *package([name_ UTF8String]);
7533 bool on([ignoredSwitch_ isOn]);
7535 pid_t pid(ExecFork());
7537 FILE *dpkg(popen("dpkg --set-selections", "w"));
7538 fwrite(package, strlen(package), 1, dpkg);
7541 fwrite(" hold\n", 6, 1, dpkg);
7543 fwrite(" install\n", 9, 1, dpkg);
7553 int result(waitpid(pid, &status, 0));
7556 _assert(result == pid);
7562 - (void) onIgnored:(id)control {
7563 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7564 [invocation setTarget:self];
7565 [invocation setSelector:@selector(_updateIgnored)];
7567 [delegate_ reloadDataWithInvocation:invocation];
7570 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7571 if (package_ == nil)
7574 switch ([indexPath section]) {
7575 case 0: return subscribedCell_;
7576 case 1: return ignoredCell_;
7585 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7587 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7588 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7589 [(UITableView *) table_ setDataSource:self];
7590 [table_ setDelegate:self];
7591 [[self view] addSubview:table_];
7593 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7594 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7595 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7597 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7598 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7599 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7601 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7602 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7603 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7604 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7606 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7607 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7608 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7609 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7612 - (void) viewDidLoad {
7613 [super viewDidLoad];
7615 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7618 - (void) releaseSubviews {
7620 subscribedCell_ = nil;
7622 ignoredSwitch_ = nil;
7623 subscribedSwitch_ = nil;
7626 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7627 if ((self = [super init]) != nil) {
7628 database_ = database;
7633 - (void) reloadData {
7636 package_ = [database_ packageWithName:name_];
7638 if (package_ != nil) {
7639 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7640 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7641 } // XXX: what now, G?
7643 [table_ reloadData];
7649 /* Installed Controller {{{ */
7650 @interface InstalledController : FilteredPackageListController {
7654 - (id) initWithDatabase:(Database *)database;
7656 - (void) updateRoleButton;
7657 - (void) queueStatusDidChange;
7661 @implementation InstalledController
7663 - (NSURL *) navigationURL {
7664 return [NSURL URLWithString:@"cydia://installed"];
7667 - (id) initWithDatabase:(Database *)database {
7668 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7669 [self updateRoleButton];
7670 [self queueStatusDidChange];
7675 - (void) queueButtonClicked {
7680 - (void) queueStatusDidChange {
7684 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7685 initWithTitle:UCLocalize("QUEUE")
7686 style:UIBarButtonItemStyleDone
7688 action:@selector(queueButtonClicked)
7691 [[self navigationItem] setLeftBarButtonItem:nil];
7697 - (void) updateRoleButton {
7698 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7699 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7700 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7701 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7703 action:@selector(roleButtonClicked)
7707 - (void) roleButtonClicked {
7708 [self setObject:[NSNumber numberWithBool:expert_]];
7712 [self updateRoleButton];
7718 /* Source Cell {{{ */
7719 @interface SourceCell : CyteTableViewCell <
7720 CyteTableViewCellDelegate
7723 _H<NSString> origin_;
7724 _H<NSString> label_;
7727 - (void) setSource:(Source *)source;
7731 @implementation SourceCell
7733 - (void) setSource:(Source *)source {
7736 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7738 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7740 origin_ = [source name];
7741 label_ = [source uri];
7743 [content_ setNeedsDisplay];
7746 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7747 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7748 UIView *content([self contentView]);
7749 CGRect bounds([content bounds]);
7751 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7752 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7753 [content_ setBackgroundColor:[UIColor whiteColor]];
7754 [content addSubview:content_];
7756 [content_ setDelegate:self];
7757 [content_ setOpaque:YES];
7761 - (NSString *) accessibilityLabel {
7765 - (void) drawContentRect:(CGRect)rect {
7766 bool highlighted(highlighted_);
7767 float width(rect.size.width);
7770 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7777 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7781 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7786 /* Source Controller {{{ */
7787 @interface SourceController : FilteredPackageListController {
7788 _transient Source *source_;
7792 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7796 @implementation SourceController
7798 - (NSURL *) navigationURL {
7799 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7802 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7803 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7805 key_ = [source key];
7809 - (void) reloadData {
7810 source_ = [database_ sourceWithKey:key_];
7811 key_ = [source_ key];
7812 [self setObject:source_];
7814 [[self navigationItem] setTitle:[source_ label]];
7821 /* Sources Controller {{{ */
7822 @interface SourcesController : CyteViewController <
7823 UITableViewDataSource,
7826 _transient Database *database_;
7827 _H<UITableView, 2> list_;
7828 _H<NSMutableArray> sources_;
7832 _H<UIProgressHUD> hud_;
7835 //NSURLConnection *installer_;
7836 NSURLConnection *trivial_;
7837 NSURLConnection *trivial_bz2_;
7838 NSURLConnection *trivial_gz_;
7839 //NSURLConnection *automatic_;
7844 - (id) initWithDatabase:(Database *)database;
7845 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7849 @implementation SourcesController
7851 - (void) _releaseConnection:(NSURLConnection *)connection {
7852 if (connection != nil) {
7853 [connection cancel];
7854 //[connection setDelegate:nil];
7855 [connection release];
7860 //[self _releaseConnection:installer_];
7861 [self _releaseConnection:trivial_];
7862 [self _releaseConnection:trivial_gz_];
7863 [self _releaseConnection:trivial_bz2_];
7864 //[self _releaseConnection:automatic_];
7869 - (NSURL *) navigationURL {
7870 return [NSURL URLWithString:@"cydia://sources"];
7873 - (void) viewDidAppear:(BOOL)animated {
7874 [super viewDidAppear:animated];
7875 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7878 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7879 return offset_ == 0 ? 1 : 2;
7882 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7883 switch (section + (offset_ == 0 ? 1 : 0)) {
7884 case 0: return UCLocalize("ENTERED_BY_USER");
7885 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7891 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7892 int count = [sources_ count];
7894 case 0: return (offset_ == 0 ? count : offset_);
7895 case 1: return count - offset_;
7901 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7903 switch (indexPath.section) {
7904 case 0: idx = indexPath.row; break;
7905 case 1: idx = indexPath.row + offset_; break;
7909 return [sources_ objectAtIndex:idx];
7912 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7913 static NSString *cellIdentifier = @"SourceCell";
7915 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7916 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7917 [cell setSource:[self sourceAtIndexPath:indexPath]];
7918 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7923 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7924 Source *source = [self sourceAtIndexPath:indexPath];
7926 SourceController *controller = [[[SourceController alloc]
7927 initWithDatabase:database_
7931 [controller setDelegate:delegate_];
7933 [[self navigationController] pushViewController:controller animated:YES];
7936 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7937 Source *source = [self sourceAtIndexPath:indexPath];
7938 return [source record] != nil;
7941 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7942 if (editingStyle == UITableViewCellEditingStyleDelete) {
7943 Source *source = [self sourceAtIndexPath:indexPath];
7944 [Sources_ removeObjectForKey:[source key]];
7945 [delegate_ syncData];
7950 [delegate_ addTrivialSource:href_];
7951 [delegate_ syncData];
7954 - (NSString *) getWarning {
7955 NSString *href(href_);
7956 NSRange colon([href rangeOfString:@"://"]);
7957 if (colon.location != NSNotFound)
7958 href = [href substringFromIndex:(colon.location + 3)];
7959 href = [href stringByAddingPercentEscapes];
7960 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7961 href = [href stringByCachingURLWithCurrentCDN];
7963 NSURL *url([NSURL URLWithString:href]);
7965 NSStringEncoding encoding;
7966 NSError *error(nil);
7968 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7969 return [warning length] == 0 ? nil : warning;
7973 - (void) _endConnection:(NSURLConnection *)connection {
7974 // XXX: the memory management in this method is horribly awkward
7976 NSURLConnection **field = NULL;
7977 if (connection == trivial_)
7979 else if (connection == trivial_bz2_)
7980 field = &trivial_bz2_;
7981 else if (connection == trivial_gz_)
7982 field = &trivial_gz_;
7983 _assert(field != NULL);
7984 [connection release];
7989 trivial_bz2_ == nil &&
7992 [delegate_ releaseNetworkActivityIndicator];
7994 [delegate_ removeProgressHUD:hud_];
8000 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8003 UIAlertView *alert = [[[UIAlertView alloc]
8004 initWithTitle:UCLocalize("SOURCE_WARNING")
8007 cancelButtonTitle:UCLocalize("CANCEL")
8009 UCLocalize("ADD_ANYWAY"),
8013 [alert setContext:@"warning"];
8014 [alert setNumberOfRows:1];
8018 } else if (error_ != nil) {
8019 UIAlertView *alert = [[[UIAlertView alloc]
8020 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8021 message:[error_ localizedDescription]
8023 cancelButtonTitle:UCLocalize("OK")
8024 otherButtonTitles:nil
8027 [alert setContext:@"urlerror"];
8030 UIAlertView *alert = [[[UIAlertView alloc]
8031 initWithTitle:UCLocalize("NOT_REPOSITORY")
8032 message:UCLocalize("NOT_REPOSITORY_EX")
8034 cancelButtonTitle:UCLocalize("OK")
8035 otherButtonTitles:nil
8038 [alert setContext:@"trivial"];
8047 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8048 switch ([response statusCode]) {
8054 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8055 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8057 [self _endConnection:connection];
8060 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8061 [self _endConnection:connection];
8064 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8065 NSMutableURLRequest *request = [NSMutableURLRequest
8066 requestWithURL:[NSURL URLWithString:href]
8067 cachePolicy:NSURLRequestUseProtocolCachePolicy
8068 timeoutInterval:120.0
8071 [request setHTTPMethod:method];
8073 if (Machine_ != NULL)
8074 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8075 if (UniqueID_ != nil)
8076 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8078 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8081 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8082 NSString *context([alert context]);
8084 if ([context isEqualToString:@"source"]) {
8087 NSString *href = [[alert textField] text];
8089 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8091 if (![href hasSuffix:@"/"])
8092 href_ = [href stringByAppendingString:@"/"];
8096 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8097 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8098 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8099 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8103 // XXX: this is stupid
8104 hud_ = [delegate_ addProgressHUD];
8105 [hud_ setText:UCLocalize("VERIFYING_URL")];
8106 [delegate_ retainNetworkActivityIndicator];
8115 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8116 } else if ([context isEqualToString:@"trivial"])
8117 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8118 else if ([context isEqualToString:@"urlerror"])
8119 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8120 else if ([context isEqualToString:@"warning"]) {
8134 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8139 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8141 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8142 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8143 [list_ setRowHeight:56];
8144 [(UITableView *) list_ setDataSource:self];
8145 [list_ setDelegate:self];
8146 [[self view] addSubview:list_];
8149 - (void) viewDidLoad {
8150 [super viewDidLoad];
8152 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8153 [self updateButtonsForEditingStatus:NO animated:NO];
8156 - (void) releaseSubviews {
8160 - (id) initWithDatabase:(Database *)database {
8161 if ((self = [super init]) != nil) {
8162 database_ = database;
8163 sources_ = [NSMutableArray arrayWithCapacity:16];
8167 - (void) reloadData {
8171 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8174 [sources_ removeAllObjects];
8175 [sources_ addObjectsFromArray:[database_ sources]];
8177 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8180 int count([sources_ count]);
8182 for (int i = 0; i != count; i++) {
8183 if ([[sources_ objectAtIndex:i] record] == nil)
8188 [list_ setEditing:NO];
8189 [self updateButtonsForEditingStatus:NO animated:NO];
8193 - (void) showAddSourcePrompt {
8194 UIAlertView *alert = [[[UIAlertView alloc]
8195 initWithTitle:UCLocalize("ENTER_APT_URL")
8198 cancelButtonTitle:UCLocalize("CANCEL")
8200 UCLocalize("ADD_SOURCE"),
8204 [alert setContext:@"source"];
8206 [alert setNumberOfRows:1];
8207 [alert addTextFieldWithValue:@"http://" label:@""];
8209 UITextInputTraits *traits = [[alert textField] textInputTraits];
8210 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8211 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8212 [traits setKeyboardType:UIKeyboardTypeURL];
8213 // XXX: UIReturnKeyDone
8214 [traits setReturnKeyType:UIReturnKeyNext];
8219 - (void) addButtonClicked {
8220 [self showAddSourcePrompt];
8223 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8224 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8225 initWithTitle:UCLocalize("ADD")
8226 style:UIBarButtonItemStylePlain
8228 action:@selector(addButtonClicked)
8229 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8231 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8232 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8233 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8235 action:@selector(editButtonClicked)
8236 ] autorelease] animated:animated];
8238 if (IsWildcat_ && !editing)
8239 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8240 initWithTitle:UCLocalize("SETTINGS")
8241 style:UIBarButtonItemStylePlain
8243 action:@selector(settingsButtonClicked)
8247 - (void) settingsButtonClicked {
8248 [delegate_ showSettings];
8251 - (void) editButtonClicked {
8252 [list_ setEditing:![list_ isEditing] animated:YES];
8254 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8260 /* Settings Controller {{{ */
8261 @interface SettingsController : CyteViewController <
8262 UITableViewDataSource,
8265 _transient Database *database_;
8266 // XXX: ok, "roledelegate_"?...
8267 _transient id roledelegate_;
8268 _H<UITableView, 2> table_;
8269 _H<UISegmentedControl> segment_;
8270 _H<UIView> container_;
8273 - (void) showDoneButton;
8274 - (void) resizeSegmentedControl;
8278 @implementation SettingsController
8281 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8283 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8284 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8285 [table_ setDelegate:self];
8286 [(UITableView *) table_ setDataSource:self];
8287 [[self view] addSubview:table_];
8289 NSArray *items = [NSArray arrayWithObjects:
8291 UCLocalize("HACKER"),
8292 UCLocalize("DEVELOPER"),
8294 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8295 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8296 [container_ addSubview:segment_];
8299 - (void) viewDidLoad {
8300 [super viewDidLoad];
8302 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8305 if ([Role_ isEqualToString:@"User"]) index = 0;
8306 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8307 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8309 [segment_ setSelectedSegmentIndex:index];
8310 [self showDoneButton];
8313 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8314 [self resizeSegmentedControl];
8317 - (void) releaseSubviews {
8323 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8324 if ((self = [super init]) != nil) {
8325 database_ = database;
8326 roledelegate_ = delegate;
8330 - (void) resizeSegmentedControl {
8331 CGFloat width = [[self view] frame].size.width;
8332 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8335 - (void) viewWillAppear:(BOOL)animated {
8336 [super viewWillAppear:animated];
8338 [self resizeSegmentedControl];
8341 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8342 [self resizeSegmentedControl];
8345 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8346 [self resizeSegmentedControl];
8350 NSString *role(nil);
8352 switch ([segment_ selectedSegmentIndex]) {
8353 case 0: role = @"User"; break;
8354 case 1: role = @"Hacker"; break;
8355 case 2: role = @"Developer"; break;
8360 if (![role isEqualToString:Role_]) {
8361 bool rolling(Role_ == nil);
8364 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8368 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8372 [roledelegate_ loadData];
8374 [roledelegate_ updateData];
8378 - (void) segmentChanged:(UISegmentedControl *)control {
8379 [self showDoneButton];
8382 - (void) saveAndClose {
8385 [[self navigationItem] setRightBarButtonItem:nil];
8386 [[self navigationController] dismissModalViewControllerAnimated:YES];
8389 - (void) doneButtonClicked {
8390 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8391 [spinner startAnimating];
8392 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8393 [[self navigationItem] setRightBarButtonItem:spinItem];
8395 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8398 - (void) showDoneButton {
8399 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8400 initWithTitle:UCLocalize("DONE")
8401 style:UIBarButtonItemStyleDone
8403 action:@selector(doneButtonClicked)
8404 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8407 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8408 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8412 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8416 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8417 return nil; // This method is required by the protocol.
8420 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8422 return UCLocalize("ROLE_EX");
8424 return [NSString stringWithFormat:
8425 @"%@: %@\n%@: %@\n%@: %@",
8426 UCLocalize("USER"), UCLocalize("USER_EX"),
8427 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8428 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8433 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8434 return section == 3 ? 44.0f : 0;
8437 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8438 return section == 3 ? container_ : nil;
8441 - (void) reloadData {
8444 [table_ reloadData];
8449 /* Stash Controller {{{ */
8450 @interface StashController : CyteViewController {
8451 _H<UIActivityIndicatorView> spinner_;
8452 _H<UILabel> status_;
8453 _H<UILabel> caption_;
8458 @implementation StashController
8461 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8462 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8464 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8465 CGRect spinrect = [spinner_ frame];
8466 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8467 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8468 [spinner_ setFrame:spinrect];
8469 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8470 [[self view] addSubview:spinner_];
8471 [spinner_ startAnimating];
8474 captrect.size.width = [[self view] frame].size.width;
8475 captrect.size.height = 40.0f;
8476 captrect.origin.x = 0;
8477 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8478 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8479 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8480 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8481 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8482 [caption_ setTextColor:[UIColor whiteColor]];
8483 [caption_ setBackgroundColor:[UIColor clearColor]];
8484 [caption_ setShadowColor:[UIColor blackColor]];
8485 [caption_ setTextAlignment:UITextAlignmentCenter];
8486 [[self view] addSubview:caption_];
8489 statusrect.size.width = [[self view] frame].size.width;
8490 statusrect.size.height = 30.0f;
8491 statusrect.origin.x = 0;
8492 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8493 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8494 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8495 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8496 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8497 [status_ setTextColor:[UIColor whiteColor]];
8498 [status_ setBackgroundColor:[UIColor clearColor]];
8499 [status_ setShadowColor:[UIColor blackColor]];
8500 [status_ setTextAlignment:UITextAlignmentCenter];
8501 [[self view] addSubview:status_];
8507 @interface CYURLCache : SDURLCache {
8512 @implementation CYURLCache
8514 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8517 else if ([event isEqualToString:@"no-cache"])
8519 else if ([event isEqualToString:@"store"])
8521 else if ([event isEqualToString:@"invalid"])
8523 else if ([event isEqualToString:@"memory"])
8525 else if ([event isEqualToString:@"disk"])
8527 else if ([event isEqualToString:@"miss"])
8530 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8536 @interface Cydia : UIApplication <
8537 ConfirmationControllerDelegate,
8540 UINavigationControllerDelegate,
8541 UITabBarControllerDelegate
8543 _H<UIWindow> window_;
8544 _H<CYTabBarController> tabbar_;
8545 _H<CYEmulatedLoadingController> emulated_;
8547 _H<NSMutableArray> essential_;
8548 _H<NSMutableArray> broken_;
8550 Database *database_;
8552 _H<NSURL> starturl_;
8557 _H<StashController> stash_;
8566 @implementation Cydia
8568 - (void) beginUpdate {
8569 [tabbar_ beginUpdate];
8573 return [tabbar_ updating];
8577 if ([broken_ count] != 0) {
8578 int count = [broken_ count];
8580 UIAlertView *alert = [[[UIAlertView alloc]
8581 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8582 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8584 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8586 UCLocalize("TEMPORARY_IGNORE"),
8590 [alert setContext:@"fixhalf"];
8591 [alert setNumberOfRows:2];
8593 } else if (!Ignored_ && [essential_ count] != 0) {
8594 int count = [essential_ count];
8596 UIAlertView *alert = [[[UIAlertView alloc]
8597 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8598 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8600 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8602 UCLocalize("UPGRADE_ESSENTIAL"),
8603 UCLocalize("COMPLETE_UPGRADE"),
8607 [alert setContext:@"upgrade"];
8612 - (void) _saveConfig {
8618 NSString *error(nil);
8620 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8622 NSError *error(nil);
8623 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8624 NSLog(@"failure to save metadata data: %@", error);
8629 NSLog(@"failure to serialize metadata: %@", error);
8634 // Navigation controller for the queuing badge.
8635 - (UINavigationController *) queueNavigationController {
8636 NSArray *controllers = [tabbar_ viewControllers];
8637 return [controllers objectAtIndex:3];
8640 - (void) unloadData {
8641 [tabbar_ unloadData];
8644 - (void) _updateData {
8649 UINavigationController *navigation = [self queueNavigationController];
8651 id queuedelegate = nil;
8652 if ([[navigation viewControllers] count] > 0)
8653 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8655 [queuedelegate queueStatusDidChange];
8656 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8659 - (void) _refreshIfPossible:(NSDate *)update {
8660 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8662 bool recently = false;
8663 if (update != nil) {
8664 NSTimeInterval interval([update timeIntervalSinceNow]);
8665 if (interval <= 0 && interval > -(15*60))
8669 // Don't automatic refresh if:
8670 // - We already refreshed recently.
8671 // - We already auto-refreshed this launch.
8672 // - Auto-refresh is disabled.
8673 if (recently || loaded_ || ManualRefresh) {
8674 // If we are cancelling, we need to make sure it knows it's already loaded.
8677 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8679 // We are going to load, so remember that.
8682 SCNetworkReachabilityFlags flags; {
8683 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8684 SCNetworkReachabilityGetFlags(reachability, &flags);
8685 CFRelease(reachability);
8688 // XXX: this elaborate mess is what Apple is using to determine this? :(
8689 // XXX: do we care if the user has to intervene? maybe that's ok?
8691 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8692 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8693 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8694 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8695 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8696 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8700 // If we can reach the server, auto-refresh!
8702 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8708 - (void) refreshIfPossible {
8709 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8712 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8713 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8714 [hud setText:UCLocalize("RELOADING_DATA")];
8716 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8719 [self removeProgressHUD:hud];
8723 [essential_ removeAllObjects];
8724 [broken_ removeAllObjects];
8726 NSArray *packages([database_ packages]);
8727 for (Package *package in packages) {
8729 [broken_ addObject:package];
8730 if ([package upgradableAndEssential:NO]) {
8731 if ([package essential])
8732 [essential_ addObject:package];
8737 NSLog(@"changes:#%u", changes);
8739 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8742 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8743 [changesItem setBadgeValue:badge];
8744 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8745 [self setApplicationIconBadgeNumber:changes];
8748 [changesItem setBadgeValue:nil];
8749 [changesItem setAnimatedBadge:NO];
8750 [self setApplicationIconBadgeNumber:0];
8755 [self refreshIfPossible];
8758 - (void) updateData {
8767 @synchronized (self) {
8768 [self _reloadDataWithInvocation:nil];
8772 - (void) disemulate {
8773 if (emulated_ == nil)
8776 [window_ addSubview:[tabbar_ view]];
8777 [[emulated_ view] removeFromSuperview];
8779 [window_ setUserInteractionEnabled:YES];
8782 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8783 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8785 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8787 UIViewController *parent;
8788 if (emulated_ == nil)
8797 [parent presentModalViewController:navigation animated:YES];
8800 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8801 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8803 if (navigation != nil)
8804 [navigation pushViewController:progress animated:YES];
8806 [self presentModalViewController:progress force:YES];
8808 [progress invoke:invocation withTitle:title];
8812 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8813 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8816 - (void) repairWithInvocation:(NSInvocation *)invocation {
8818 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8822 - (void) repairWithSelector:(SEL)selector {
8823 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8829 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8830 _assert(file != NULL);
8832 for (NSString *key in [Sources_ allKeys]) {
8833 NSDictionary *source([Sources_ objectForKey:key]);
8835 fprintf(file, "%s %s %s\n",
8836 [[source objectForKey:@"Type"] UTF8String],
8837 [[source objectForKey:@"URI"] UTF8String],
8838 [[source objectForKey:@"Distribution"] UTF8String]
8844 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8849 - (void) addTrivialSource:(NSString *)href {
8850 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8853 @"./", @"Distribution",
8854 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8859 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8860 @synchronized (self) {
8861 [self _reloadDataWithInvocation:invocation];
8865 - (void) reloadData {
8866 [self reloadDataWithInvocation:nil];
8870 pkgProblemResolver *resolver = [database_ resolver];
8872 resolver->InstallProtect();
8873 if (!resolver->Resolve(true))
8878 // XXX: this is a really crappy way of doing this.
8879 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8880 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8881 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8882 if ([tabbar_ updating])
8883 [tabbar_ cancelUpdate];
8885 if (![database_ prepare])
8888 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8889 [page setDelegate:self];
8890 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8893 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8894 [tabbar_ presentModalViewController:confirm_ animated:YES];
8900 @synchronized (self) {
8905 - (void) clearPackage:(Package *)package {
8906 @synchronized (self) {
8913 - (void) installPackages:(NSArray *)packages {
8914 @synchronized (self) {
8915 for (Package *package in packages)
8922 - (void) installPackage:(Package *)package {
8923 @synchronized (self) {
8930 - (void) removePackage:(Package *)package {
8931 @synchronized (self) {
8938 - (void) distUpgrade {
8939 @synchronized (self) {
8940 if (![database_ upgrade])
8946 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8949 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
8954 - (void) showSettings {
8955 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
8958 - (void) retainNetworkActivityIndicator {
8959 if (activity_++ == 0)
8960 [self setNetworkActivityIndicatorVisible:YES];
8963 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
8967 - (void) releaseNetworkActivityIndicator {
8968 if (--activity_ == 0)
8969 [self setNetworkActivityIndicatorVisible:NO];
8972 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
8977 - (void) cancelAndClear:(bool)clear {
8978 @synchronized (self) {
8990 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8991 NSString *context([alert context]);
8993 if ([context isEqualToString:@"conffile"]) {
8994 FILE *input = [database_ input];
8995 if (button == [alert cancelButtonIndex])
8996 fprintf(input, "N\n");
8997 else if (button == [alert firstOtherButtonIndex])
8998 fprintf(input, "Y\n");
9001 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9002 } else if ([context isEqualToString:@"fixhalf"]) {
9003 if (button == [alert cancelButtonIndex]) {
9004 @synchronized (self) {
9005 for (Package *broken in (id) broken_) {
9008 NSString *id = [broken id];
9009 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9010 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9011 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9012 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9018 } else if (button == [alert firstOtherButtonIndex]) {
9019 [broken_ removeAllObjects];
9023 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9024 } else if ([context isEqualToString:@"upgrade"]) {
9025 if (button == [alert firstOtherButtonIndex]) {
9026 @synchronized (self) {
9027 for (Package *essential in (id) essential_)
9028 [essential install];
9033 } else if (button == [alert firstOtherButtonIndex] + 1) {
9035 } else if (button == [alert cancelButtonIndex]) {
9039 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9043 - (void) system:(NSString *)command {
9044 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9047 system([command UTF8String]);
9053 - (void) applicationWillSuspend {
9055 [super applicationWillSuspend];
9058 - (BOOL) isSafeToSuspend {
9061 NSLog(@"isSafeToSuspend: locked_ != 0");
9066 // Use external process status API internally.
9067 // This is probably a really bad idea.
9068 // XXX: what is the point of this? does this solve anything at all?
9069 uint64_t status = 0;
9071 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9072 notify_get_state(notify_token, &status);
9073 notify_cancel(notify_token);
9078 NSLog(@"isSafeToSuspend: status != 0");
9084 NSLog(@"isSafeToSuspend: -> true");
9089 - (void) applicationSuspend:(__GSEvent *)event {
9090 if ([self isSafeToSuspend])
9091 [super applicationSuspend:event];
9094 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9095 if ([self isSafeToSuspend])
9096 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9099 - (void) _setSuspended:(BOOL)value {
9100 if ([self isSafeToSuspend])
9101 [super _setSuspended:value];
9104 - (UIProgressHUD *) addProgressHUD {
9105 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9106 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9108 [window_ setUserInteractionEnabled:NO];
9110 UIViewController *target(tabbar_);
9111 if (UIViewController *modal = [target modalViewController])
9114 UIView *view([target view]);
9115 [view addSubview:hud];
9123 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9126 [hud removeFromSuperview];
9127 [window_ setUserInteractionEnabled:YES];
9130 - (CyteViewController *) pageForPackage:(NSString *)name {
9131 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9134 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9135 NSString *scheme([[url scheme] lowercaseString]);
9136 if ([[url absoluteString] length] <= [scheme length] + 3)
9138 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9139 NSArray *components([path pathComponents]);
9141 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9142 return [self pageForPackage:[components objectAtIndex:1]];
9144 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9147 NSString *base([components objectAtIndex:0]);
9149 CyteViewController *controller = nil;
9151 if ([base isEqualToString:@"url"]) {
9152 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9153 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9154 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9155 } else if (!external && [components count] == 1) {
9156 if ([base isEqualToString:@"manage"]) {
9157 controller = [[[ManageController alloc] init] autorelease];
9160 if ([base isEqualToString:@"sources"]) {
9161 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9164 if ([base isEqualToString:@"home"]) {
9165 controller = [[[HomeController alloc] init] autorelease];
9168 if ([base isEqualToString:@"sections"]) {
9169 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9172 if ([base isEqualToString:@"search"]) {
9173 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9176 if ([base isEqualToString:@"changes"]) {
9177 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9180 if ([base isEqualToString:@"installed"]) {
9181 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9183 } else if ([components count] == 2) {
9184 NSString *argument = [components objectAtIndex:1];
9186 if ([base isEqualToString:@"package"]) {
9187 controller = [self pageForPackage:argument];
9190 if (!external && [base isEqualToString:@"search"]) {
9191 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9194 if (!external && [base isEqualToString:@"sections"]) {
9195 if ([argument isEqualToString:@"all"])
9197 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9200 if (!external && [base isEqualToString:@"sources"]) {
9201 if ([argument isEqualToString:@"add"]) {
9202 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9203 [(SourcesController *)controller showAddSourcePrompt];
9205 Source *source = [database_ sourceWithKey:argument];
9206 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9210 if (!external && [base isEqualToString:@"launch"]) {
9211 [self launchApplicationWithIdentifier:argument suspended:NO];
9214 } else if (!external && [components count] == 3) {
9215 NSString *arg1 = [components objectAtIndex:1];
9216 NSString *arg2 = [components objectAtIndex:2];
9218 if ([base isEqualToString:@"package"]) {
9219 if ([arg2 isEqualToString:@"settings"]) {
9220 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9221 } else if ([arg2 isEqualToString:@"files"]) {
9222 if (Package *package = [database_ packageWithName:arg1]) {
9223 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9224 [(FileTable *)controller setPackage:package];
9230 [controller setDelegate:self];
9234 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9235 CyteViewController *page([self pageForURL:url forExternal:external]);
9238 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9239 [nav setViewControllers:[NSArray arrayWithObject:page]];
9240 [tabbar_ setUnselectedViewController:nav];
9246 - (void) applicationOpenURL:(NSURL *)url {
9247 [super applicationOpenURL:url];
9252 [self openCydiaURL:url forExternal:YES];
9255 - (void) applicationWillResignActive:(UIApplication *)application {
9256 // Stop refreshing if you get a phone call or lock the device.
9257 if ([tabbar_ updating])
9258 [tabbar_ cancelUpdate];
9260 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9261 [super applicationWillResignActive:application];
9264 - (void) applicationWillTerminate:(UIApplication *)application {
9266 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9267 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9268 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9273 - (void) setConfigurationData:(NSString *)data {
9274 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9276 if (!conffile_r(data)) {
9277 lprintf("E:invalid conffile\n");
9281 NSString *ofile = conffile_r[1];
9282 //NSString *nfile = conffile_r[2];
9284 UIAlertView *alert = [[[UIAlertView alloc]
9285 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9286 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9288 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9290 UCLocalize("ACCEPT_NEW_COPY"),
9291 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9295 [alert setContext:@"conffile"];
9296 [alert setNumberOfRows:2];
9300 - (void) addStashController {
9302 stash_ = [[[StashController alloc] init] autorelease];
9303 [window_ addSubview:[stash_ view]];
9306 - (void) removeStashController {
9307 [[stash_ view] removeFromSuperview];
9313 [self setIdleTimerDisabled:YES];
9315 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9316 UpdateExternalStatus(1);
9317 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9318 UpdateExternalStatus(0);
9320 [self removeStashController];
9322 if (ExecFork() == 0) {
9323 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9324 perror("launchctl stop");
9328 - (void) setupViewControllers {
9329 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9331 NSMutableArray *items([NSMutableArray arrayWithObjects:
9332 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9333 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9334 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9335 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9339 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9340 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9342 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9345 NSMutableArray *controllers([NSMutableArray array]);
9346 for (UITabBarItem *item in items) {
9347 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9348 [controller setTabBarItem:item];
9349 [controllers addObject:controller];
9351 [tabbar_ setViewControllers:controllers];
9353 [tabbar_ setUpdateDelegate:self];
9356 - (void) applicationDidFinishLaunching:(id)unused {
9358 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9359 [self setApplicationSupportsShakeToEdit:NO];
9361 @synchronized (HostConfig_) {
9362 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9365 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9366 initWithMemoryCapacity:524288
9367 diskCapacity:10485760
9368 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9371 [CydiaWebViewController _initialize];
9373 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9375 // this would disallow http{,s} URLs from accessing this data
9376 //[WebView registerURLSchemeAsLocal:@"cydia"];
9378 Font12_ = [UIFont systemFontOfSize:12];
9379 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9380 Font14_ = [UIFont systemFontOfSize:14];
9381 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9382 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9384 essential_ = [NSMutableArray arrayWithCapacity:4];
9385 broken_ = [NSMutableArray arrayWithCapacity:4];
9387 // XXX: I really need this thing... like, seriously... I'm sorry
9388 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9390 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9391 [window_ orderFront:self];
9392 [window_ makeKey:self];
9393 [window_ setHidden:NO];
9396 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9397 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9398 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9399 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9400 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9401 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9402 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9403 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9404 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9407 [self addStashController];
9408 // XXX: this would be much cleaner as a yieldToSelector:
9409 // that way the removeStashController could happen right here inline
9410 // we also could no longer require the useless stash_ field anymore
9411 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9415 database_ = [Database sharedInstance];
9416 [database_ setDelegate:self];
9418 [window_ setUserInteractionEnabled:NO];
9419 [self setupViewControllers];
9421 emulated_ = [[[CYEmulatedLoadingController alloc] initWithDatabase:database_] autorelease];
9422 [window_ addSubview:[emulated_ view]];
9424 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9428 - (NSArray *) defaultStartPages {
9429 NSMutableArray *standard = [NSMutableArray array];
9430 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9431 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9432 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9434 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9436 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9437 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9439 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9446 [window_ setUserInteractionEnabled:YES];
9447 [self showSettings];
9450 if ([emulated_ modalViewController] != nil)
9451 [emulated_ dismissModalViewControllerAnimated:YES];
9452 [window_ setUserInteractionEnabled:NO];
9460 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9461 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9462 int standardIndex = 0;
9463 NSArray *standard = [self defaultStartPages];
9470 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9471 if (valid && closed != nil) {
9472 NSTimeInterval interval([closed timeIntervalSinceNow]);
9473 // XXX: Is 15 minutes the optimal time here?
9474 if (interval > 0 && interval <= -(15*60))
9478 if (valid && [saved count] != [standard count])
9482 for (unsigned int i = 0; i < [standard count]; i++) {
9483 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9484 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9485 // but it's good enough for now.
9486 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9493 NSArray *items = nil;
9495 [tabbar_ setSelectedIndex:savedIndex];
9498 [tabbar_ setSelectedIndex:standardIndex];
9502 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9503 NSArray *stack = [items objectAtIndex:tab];
9504 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9505 NSMutableArray *current = [NSMutableArray array];
9507 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9508 NSString *addr = [stack objectAtIndex:nav];
9509 NSURL *url = [NSURL URLWithString:addr];
9510 CyteViewController *page = [self pageForURL:url forExternal:NO];
9512 [current addObject:page];
9515 [navigation setViewControllers:current];
9518 // (Try to) show the startup URL.
9519 if (starturl_ != nil) {
9520 [self openCydiaURL:starturl_ forExternal:NO];
9525 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9526 if (item != nil && IsWildcat_) {
9527 [sheet showFromBarButtonItem:item animated:YES];
9529 [sheet showInView:window_];
9533 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9534 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9535 [progress setTitle:task];
9536 [progress addProgressEvent:event];
9539 - (void) addProgressEventForTask:(NSArray *)data {
9540 CydiaProgressEvent *event([data objectAtIndex:0]);
9541 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9542 [self addProgressEvent:event forTask:task];
9545 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9546 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9552 id Alloc_(id self, SEL selector) {
9553 id object = alloc_(self, selector);
9554 lprintf("[%s]A-%p\n", self->isa->name, object);
9559 id Dealloc_(id self, SEL selector) {
9560 id object = dealloc_(self, selector);
9561 lprintf("[%s]D-%p\n", self->isa->name, object);
9565 Class $WebDefaultUIKitDelegate;
9567 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9568 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9569 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9570 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9573 static NSSet *MobilizedFiles_;
9575 static NSURL *MobilizeURL(NSURL *url) {
9576 NSString *path([url path]);
9577 if ([path hasPrefix:@"/var/root/"]) {
9578 NSString *file([path substringFromIndex:10]);
9579 if ([MobilizedFiles_ containsObject:file])
9580 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9586 Class $CFXPreferencesPropertyListSource;
9587 @class CFXPreferencesPropertyListSource;
9589 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9590 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9591 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9592 url = MobilizeURL(url);
9593 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9594 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9600 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9601 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9602 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9603 url = MobilizeURL(url);
9604 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9605 //NSLog(@"%@ %@", [url absoluteString], value);
9611 Class $NSURLConnection;
9613 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9614 NSMutableURLRequest *copy([request mutableCopy]);
9616 NSURL *url([copy URL]);
9617 NSString *host([url host]);
9618 NSString *scheme([[url scheme] lowercaseString]);
9620 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9622 @synchronized (HostConfig_) {
9623 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9624 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9625 [copy setHTTPShouldUsePipelining:YES];
9628 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9632 int main(int argc, char *argv[]) {
9633 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9637 UpdateExternalStatus(0);
9639 if (Class $UIDevice = objc_getClass("UIDevice")) {
9640 UIDevice *device([$UIDevice currentDevice]);
9641 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9645 UIScreen *screen([UIScreen mainScreen]);
9646 if ([screen respondsToSelector:@selector(scale)])
9647 ScreenScale_ = [screen scale];
9651 UIDevice *device([UIDevice currentDevice]);
9652 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9655 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9656 if (idiom == UIUserInterfaceIdiomPhone)
9658 else if (idiom == UIUserInterfaceIdiomPad)
9661 NSLog(@"unknown UIUserInterfaceIdiom!");
9664 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9666 HostConfig_ = [[[NSObject alloc] init] autorelease];
9667 @synchronized (HostConfig_) {
9668 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9669 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9672 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9674 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9676 MobilizedFiles_ = [NSMutableSet setWithObjects:
9677 @"Library/Preferences/com.apple.Accessibility.plist",
9678 @"Library/Preferences/com.apple.preferences.sounds.plist",
9681 /* Library Hacks {{{ */
9682 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9684 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9686 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9687 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9688 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9689 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9692 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9693 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9694 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9695 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9698 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9699 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9700 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9701 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9702 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9705 $NSURLConnection = objc_getClass("NSURLConnection");
9706 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9707 if (NSURLConnection$init$ != NULL) {
9708 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9709 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9712 /* Set Locale {{{ */
9713 Locale_ = CFLocaleCopyCurrent();
9714 Languages_ = [NSLocale preferredLanguages];
9716 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9717 //NSLog(@"%@", [Languages_ description]);
9720 if (Locale_ != NULL)
9721 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9722 else if (Languages_ != nil && [Languages_ count] != 0)
9723 lang = [[Languages_ objectAtIndex:0] UTF8String];
9725 // XXX: consider just setting to C and then falling through?
9729 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9730 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9733 NSLog(@"Setting Language: %s", lang);
9736 setenv("LANG", lang, true);
9737 std::setlocale(LC_ALL, lang);
9741 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9743 /* Parse Arguments {{{ */
9744 bool substrate(false);
9750 for (int argi(1); argi != argc; ++argi)
9751 if (strcmp(argv[argi], "--") == 0) {
9753 argv[argi] = argv[0];
9759 for (int argi(1); argi != arge; ++argi)
9760 if (strcmp(args[argi], "--substrate") == 0)
9763 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9767 App_ = [[NSBundle mainBundle] bundlePath];
9773 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9774 alloc_ = alloc->method_imp;
9775 alloc->method_imp = (IMP) &Alloc_;*/
9777 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9778 dealloc_ = dealloc->method_imp;
9779 dealloc->method_imp = (IMP) &Dealloc_;*/
9781 /* System Information {{{ */
9785 size = sizeof(maxproc);
9786 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9787 perror("sysctlbyname(\"kern.maxproc\", ?)");
9788 else if (maxproc < 64) {
9790 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9791 perror("sysctlbyname(\"kern.maxproc\", #)");
9794 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9795 char *osversion = new char[size];
9796 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9797 perror("sysctlbyname(\"kern.osversion\", ?)");
9799 System_ = [NSString stringWithUTF8String:osversion];
9801 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9802 char *machine = new char[size];
9803 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9804 perror("sysctlbyname(\"hw.machine\", ?)");
9808 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
9809 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
9810 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
9812 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9814 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9815 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9816 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9818 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9819 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9820 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9822 if (mcc != NULL && mnc != NULL)
9823 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9830 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9831 Build_ = [system objectForKey:@"ProductBuildVersion"];
9832 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9833 Product_ = [info objectForKey:@"SafariProductVersion"];
9834 Safari_ = [info objectForKey:@"CFBundleVersion"];
9837 /* Load Database {{{ */
9839 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9841 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9843 if (Metadata_ == NULL)
9844 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9846 Settings_ = [Metadata_ objectForKey:@"Settings"];
9848 Packages_ = [Metadata_ objectForKey:@"Packages"];
9849 Sections_ = [Metadata_ objectForKey:@"Sections"];
9850 Sources_ = [Metadata_ objectForKey:@"Sources"];
9852 Token_ = [Metadata_ objectForKey:@"Token"];
9855 if (Settings_ != nil)
9856 Role_ = [Settings_ objectForKey:@"Role"];
9858 if (Sections_ == nil) {
9859 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9860 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9863 if (Sources_ == nil) {
9864 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9865 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9870 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9873 if (Packages_ != nil) {
9875 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9879 [Metadata_ removeObjectForKey:@"Packages"];
9885 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9887 #define MobileSubstrate_(name) \
9888 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
9889 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
9890 if (handle == NULL) \
9891 NSLog(@"%s", dlerror()); \
9894 MobileSubstrate_(Activator)
9895 MobileSubstrate_(libstatusbar)
9896 MobileSubstrate_(SimulatedKeyEvents)
9897 MobileSubstrate_(WinterBoard)
9899 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9900 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9902 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9904 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9905 unlink("/tmp/.cydia.fw");
9907 } else if (access("/User", F_OK) != 0 || version < 4) {
9910 system("/usr/libexec/cydia/firmware.sh");
9914 _assert([[NSFileManager defaultManager]
9915 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9916 withIntermediateDirectories:YES
9921 if (access("/tmp/cydia.chk", F_OK) == 0) {
9922 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9923 _assert(errno == ENOENT);
9924 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9925 _assert(errno == ENOENT);
9928 /* APT Initialization {{{ */
9929 _assert(pkgInitConfig(*_config));
9930 _assert(pkgInitSystem(*_config, _system));
9933 _config->Set("APT::Acquire::Translation", lang);
9935 // XXX: this timeout might be important :(
9936 //_config->Set("Acquire::http::Timeout", 15);
9938 _config->Set("Acquire::http::MaxParallel", 3);
9940 /* Color Choices {{{ */
9941 space_ = CGColorSpaceCreateDeviceRGB();
9943 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9944 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9945 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9946 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9947 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9948 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9949 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9950 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9951 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9953 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9954 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9956 /* UIKit Configuration {{{ */
9957 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9958 if ($GSFontSetUseLegacyFontMetrics != NULL)
9959 $GSFontSetUseLegacyFontMetrics(YES);
9961 // XXX: I have a feeling this was important
9962 //UIKeyboardDisableAutomaticAppearance();
9965 Colon_ = UCLocalize("COLON_DELIMITED");
9966 Elision_ = UCLocalize("ELISION");
9967 Error_ = UCLocalize("ERROR");
9968 Warning_ = UCLocalize("WARNING");
9971 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9973 CGColorSpaceRelease(space_);