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 "Menes/Menes.h"
125 #include "CyteKit/PerlCompatibleRegEx.hpp"
126 #include "CyteKit/TableViewCell.h"
127 #include "CyteKit/WebScriptObject-Cyte.h"
128 #include "CyteKit/WebViewController.h"
129 #include "CyteKit/stringWithUTF8Bytes.h"
131 #include "Cydia/ProgressEvent.h"
133 #include "SDURLCache/SDURLCache.h"
135 #include <CydiaSubstrate/CydiaSubstrate.h>
142 #define _timestamp ({ \
144 gettimeofday(&tv, NULL); \
145 tv.tv_sec * 1000000 + tv.tv_usec; \
148 typedef std::vector<class ProfileTime *> TimeList;
158 ProfileTime(const char *name) :
162 times_.push_back(this);
165 void AddTime(uint64_t time) {
172 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
184 ProfileTimer(ProfileTime &time) :
191 time_.AddTime(_timestamp - start_);
196 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
198 std::cerr << "========" << std::endl;
201 #define _profile(name) { \
202 static ProfileTime name(#name); \
203 ProfileTimer _ ## name(name);
208 #define Cydia_ CYDIA_VERSION
210 #define lprintf(args...) fprintf(stderr, args)
213 #define TraceLogging (1 && !ForRelease)
214 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
215 #define ProfileTimes (0 && !ForRelease)
216 #define ForSaurik (0 && !ForRelease)
217 #define LogBrowser (0 && !ForRelease)
218 #define TrackResize (0 && !ForRelease)
219 #define ManualRefresh (1 && !ForRelease)
220 #define ShowInternals (0 && !ForRelease)
221 #define AlwaysReload (0 && !ForRelease)
222 #define TryIndexedCollation (0 && !ForRelease)
226 #define _trace(args...)
231 #define _profile(name) {
234 #define PrintTimes() do {} while (false)
237 // Hash Functions/Structures {{{
238 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
246 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
248 static _finline NSString *CydiaURL(NSString *path) {
250 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
251 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
252 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
253 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
254 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
256 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
259 static _finline void UpdateExternalStatus(uint64_t newStatus) {
261 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
262 notify_set_state(notify_token, newStatus);
263 notify_cancel(notify_token);
265 notify_post("com.saurik.Cydia.status");
268 /* NSForcedOrderingSearch doesn't work on the iPhone */
269 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
270 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
271 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
273 /* Insertion Sort {{{ */
275 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
276 const char *ptr = (const char *)list;
278 CFIndex half = count / 2;
279 const char *probe = ptr + elementSize * half;
280 CFComparisonResult cr = comparator(element, probe, context);
281 if (0 == cr) return (probe - (const char *)list) / elementSize;
282 ptr = (cr < 0) ? ptr : probe + elementSize;
283 count = (cr < 0) ? half : (half + (count & 1) - 1);
285 return (ptr - (const char *)list) / elementSize;
288 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
289 const char *ptr = (const char *)list;
291 CFIndex half = count / 2;
292 const char *probe = ptr + elementSize * half;
293 CFComparisonResult cr = comparator(element, probe, context);
294 if (0 == cr) return (probe - (const char *)list) / elementSize;
295 ptr = (cr < 0) ? ptr : probe + elementSize;
296 count = (cr < 0) ? half : (half + (count & 1) - 1);
298 return (ptr - (const char *)list) / elementSize;
301 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
302 if (range.length == 0)
304 const void **values(new const void *[range.length]);
305 CFArrayGetValues(array, range, values);
307 #if HistogramInsertionSort > 0
308 uint32_t total(0), *offsets(new uint32_t[range.length]);
311 for (CFIndex index(1); index != range.length; ++index) {
312 const void *value(values[index]);
313 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
314 CFIndex correct(index);
315 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
316 #if HistogramInsertionSort > 1
317 NSLog(@"%@ < %@", value, values[correct - 1]);
322 if (correct != index) {
323 size_t offset(index - correct);
324 #if HistogramInsertionSort
328 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
330 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
331 values[correct] = value;
335 CFArrayReplaceValues(array, range, values, range.length);
338 #if HistogramInsertionSort > 0
339 for (CFIndex index(0); index != range.length; ++index)
340 if (offsets[index] != 0)
341 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
342 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
349 /* Apple Bug Fixes {{{ */
350 @implementation UIWebDocumentView (Cydia)
352 - (void) _setScrollerOffset:(CGPoint)offset {
353 UIScroller *scroller([self _scroller]);
355 CGSize size([scroller contentSize]);
356 CGSize bounds([scroller bounds].size);
359 max.x = size.width - bounds.width;
360 max.y = size.height - bounds.height;
368 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
369 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
371 [scroller setOffset:offset];
377 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
378 size_t length([self length] - state->state);
381 else if (length > count)
383 for (size_t i(0); i != length; ++i)
384 objects[i] = [self item:state->state++];
385 state->itemsPtr = objects;
386 state->mutationsPtr = (unsigned long *) self;
390 /* Cydia NSString Additions {{{ */
391 @interface NSString (Cydia)
392 - (NSComparisonResult) compareByPath:(NSString *)other;
393 - (NSString *) stringByCachingURLWithCurrentCDN;
394 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
397 @implementation NSString (Cydia)
399 - (NSComparisonResult) compareByPath:(NSString *)other {
400 NSString *prefix = [self commonPrefixWithString:other options:0];
401 size_t length = [prefix length];
403 NSRange lrange = NSMakeRange(length, [self length] - length);
404 NSRange rrange = NSMakeRange(length, [other length] - length);
406 lrange = [self rangeOfString:@"/" options:0 range:lrange];
407 rrange = [other rangeOfString:@"/" options:0 range:rrange];
409 NSComparisonResult value;
411 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
412 value = NSOrderedSame;
413 else if (lrange.location == NSNotFound)
414 value = NSOrderedAscending;
415 else if (rrange.location == NSNotFound)
416 value = NSOrderedDescending;
418 value = NSOrderedSame;
420 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
421 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
422 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
423 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
425 NSComparisonResult result = [lpath compare:rpath];
426 return result == NSOrderedSame ? value : result;
429 - (NSString *) stringByCachingURLWithCurrentCDN {
431 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
432 withString:@"://cache.cydia.saurik.com/"
436 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
437 return [(id)CFURLCreateStringByAddingPercentEscapes(
442 kCFStringEncodingUTF8
449 /* C++ NSString Wrapper Cache {{{ */
450 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
451 return size == 0 ? NULL :
452 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
453 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
456 static _finline CFStringRef CYStringCreate(const char *data) {
457 return CYStringCreate(data, strlen(data));
466 _finline void clear_() {
467 if (cache_ != NULL) {
474 _finline bool empty() const {
478 _finline size_t size() const {
482 _finline char *data() const {
486 _finline void clear() {
491 _finline CYString() :
498 _finline ~CYString() {
502 void operator =(const CYString &rhs) {
506 if (rhs.cache_ == nil)
509 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
512 void copy(apr_pool_t *pool) {
513 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
514 memcpy(temp, data_, size_);
519 void set(apr_pool_t *pool, const char *data, size_t size) {
525 data_ = const_cast<char *>(data);
533 _finline void set(apr_pool_t *pool, const char *data) {
534 set(pool, data, data == NULL ? 0 : strlen(data));
537 _finline void set(apr_pool_t *pool, const std::string &rhs) {
538 set(pool, rhs.data(), rhs.size());
541 bool operator ==(const CYString &rhs) const {
542 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
545 _finline operator CFStringRef() {
547 cache_ = CYStringCreate(data_, size_);
551 _finline operator id() {
552 return (NSString *) static_cast<CFStringRef>(*this);
555 _finline operator const char *() {
556 return reinterpret_cast<const char *>(data_);
560 /* C++ NSString Algorithm Adapters {{{ */
562 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
565 struct NSStringMapHash :
566 std::unary_function<NSString *, size_t>
568 _finline size_t operator ()(NSString *value) const {
569 return CFStringHashNSString((CFStringRef) value);
573 struct NSStringMapLess :
574 std::binary_function<NSString *, NSString *, bool>
576 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
577 return [lhs compare:rhs] == NSOrderedAscending;
581 struct NSStringMapEqual :
582 std::binary_function<NSString *, NSString *, bool>
584 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
585 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
586 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
587 //[lhs isEqualToString:rhs];
592 /* Mime Addresses {{{ */
593 @interface Address : NSObject {
595 _H<NSString> address_;
599 - (NSString *) address;
601 - (void) setAddress:(NSString *)address;
603 + (Address *) addressWithString:(NSString *)string;
604 - (Address *) initWithString:(NSString *)string;
608 @implementation Address
610 - (NSString *) name {
614 - (NSString *) address {
618 - (void) setAddress:(NSString *)address {
622 + (Address *) addressWithString:(NSString *)string {
623 return [[[Address alloc] initWithString:string] autorelease];
626 + (NSArray *) _attributeKeys {
627 return [NSArray arrayWithObjects:
633 - (NSArray *) attributeKeys {
634 return [[self class] _attributeKeys];
637 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
638 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
641 - (Address *) initWithString:(NSString *)string {
642 if ((self = [super init]) != nil) {
643 const char *data = [string UTF8String];
644 size_t size = [string length];
646 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
648 if (address_r(data, size)) {
649 name_ = address_r[1];
650 address_ = address_r[2];
660 /* CoreGraphics Primitives {{{ */
665 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
666 CGFloat color[] = {red, green, blue, alpha};
667 return CGColorCreate(space, color);
676 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
677 color_(Create_(space, red, green, blue, alpha))
679 Set(space, red, green, blue, alpha);
684 CGColorRelease(color_);
691 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
693 color_ = Create_(space, red, green, blue, alpha);
696 operator CGColorRef() {
702 /* Random Global Variables {{{ */
703 static const int PulseInterval_ = 50000;
705 static const NSString *UI_;
708 static bool RestartSubstrate_;
709 static NSArray *Finishes_;
711 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
712 #define NotifyConfig_ "/etc/notify.conf"
714 static bool Queuing_;
716 static CYColor Blue_;
717 static CYColor Blueish_;
718 static CYColor Black_;
720 static CYColor White_;
721 static CYColor Gray_;
722 static CYColor Green_;
723 static CYColor Purple_;
724 static CYColor Purplish_;
726 static UIColor *InstallingColor_;
727 static UIColor *RemovingColor_;
729 static NSString *App_;
731 static BOOL Advanced_;
732 static BOOL Ignored_;
734 static _H<UIFont> Font12_;
735 static _H<UIFont> Font12Bold_;
736 static _H<UIFont> Font14_;
737 static _H<UIFont> Font18Bold_;
738 static _H<UIFont> Font22Bold_;
740 static const char *Machine_ = NULL;
741 static NSString *System_ = nil;
742 static NSString *SerialNumber_ = nil;
743 static NSString *ChipID_ = nil;
744 static NSString *BBSNum_ = nil;
745 static _H<NSString> Token_;
746 static NSString *UniqueID_ = nil;
747 static NSString *PLMN_ = nil;
748 static NSString *Build_ = nil;
749 static NSString *Product_ = nil;
750 static NSString *Safari_ = nil;
752 static CFLocaleRef Locale_;
753 static NSArray *Languages_;
754 static CGColorSpaceRef space_;
756 static NSDictionary *SectionMap_;
757 static NSMutableDictionary *Metadata_;
758 static _transient NSMutableDictionary *Settings_;
759 static _transient NSString *Role_;
760 static _transient NSMutableDictionary *Packages_;
761 static _transient NSMutableDictionary *Sections_;
762 static _transient NSMutableDictionary *Sources_;
763 static bool Changed_;
767 static CGFloat ScreenScale_;
768 static NSString *Idiom_;
770 static _H<NSMutableDictionary> SessionData_;
771 static _H<NSObject> HostConfig_;
772 static _H<NSMutableSet> BridgedHosts_;
773 static _H<NSMutableSet> PipelinedHosts_;
775 static NSString *kCydiaProgressEventTypeError = @"Error";
776 static NSString *kCydiaProgressEventTypeInformation = @"Information";
777 static NSString *kCydiaProgressEventTypeStatus = @"Status";
778 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
781 /* Display Helpers {{{ */
782 inline float Interpolate(float begin, float end, float fraction) {
783 return (end - begin) * fraction + begin;
786 static _finline const char *StripVersion_(const char *version) {
787 const char *colon(strchr(version, ':'));
788 return colon == NULL ? version : colon + 1;
791 NSString *LocalizeSection(NSString *section) {
792 static Pcre title_r("^(.*?) \\((.*)\\)$");
793 if (title_r(section)) {
794 NSString *parent(title_r[1]);
795 NSString *child(title_r[2]);
797 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
798 LocalizeSection(parent),
799 LocalizeSection(child)
803 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
806 NSString *Simplify(NSString *title) {
807 const char *data = [title UTF8String];
808 size_t size = [title length];
810 static Pcre square_r("^\\[(.*)\\]$");
811 if (square_r(data, size))
812 return Simplify(square_r[1]);
814 static Pcre paren_r("^\\((.*)\\)$");
815 if (paren_r(data, size))
816 return Simplify(paren_r[1]);
818 static Pcre title_r("^(.*?) \\((.*)\\)$");
819 if (title_r(data, size))
820 return Simplify(title_r[1]);
826 NSString *GetLastUpdate() {
827 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
830 return UCLocalize("NEVER_OR_UNKNOWN");
832 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
833 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
835 CFRelease(formatter);
837 return [(NSString *) formatted autorelease];
840 bool isSectionVisible(NSString *section) {
841 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
842 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
843 return hidden == nil || ![hidden boolValue];
846 static NSObject *CYIOGetValue(const char *path, NSString *property) {
847 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
848 if (entry == MACH_PORT_NULL)
851 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
852 IOObjectRelease(entry);
856 return [(id) value autorelease];
859 static NSString *CYHex(NSData *data, bool reverse = false) {
863 size_t length([data length]);
864 uint8_t bytes[length];
865 [data getBytes:bytes];
867 char string[length * 2 + 1];
868 for (size_t i(0); i != length; ++i)
869 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
871 return [NSString stringWithUTF8String:string];
876 /* Delegate Prototypes {{{ */
879 @class CydiaProgressEvent;
881 @protocol DatabaseDelegate
882 - (void) repairWithSelector:(SEL)selector;
883 - (void) setConfigurationData:(NSString *)data;
884 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
887 @class CYPackageController;
889 @protocol CydiaDelegate
890 - (void) retainNetworkActivityIndicator;
891 - (void) releaseNetworkActivityIndicator;
892 - (void) clearPackage:(Package *)package;
893 - (void) installPackage:(Package *)package;
894 - (void) installPackages:(NSArray *)packages;
895 - (void) removePackage:(Package *)package;
896 - (void) beginUpdate;
898 - (void) distUpgrade;
902 - (void) addTrivialSource:(NSString *)href;
903 - (void) showSettings;
904 - (UIProgressHUD *) addProgressHUD;
905 - (void) removeProgressHUD:(UIProgressHUD *)hud;
906 - (CyteViewController *) pageForPackage:(NSString *)name;
907 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
908 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
912 /* Status Delegation {{{ */
914 public pkgAcquireStatus
917 _transient NSObject<ProgressDelegate> *delegate_;
927 void setDelegate(NSObject<ProgressDelegate> *delegate) {
928 delegate_ = delegate;
931 NSObject<ProgressDelegate> *getDelegate() const {
935 virtual bool MediaChange(std::string media, std::string drive) {
939 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
942 virtual void Fetch(pkgAcquire::ItemDesc &item) {
943 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
944 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
945 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
948 virtual void Done(pkgAcquire::ItemDesc &item) {
951 virtual void Fail(pkgAcquire::ItemDesc &item) {
953 item.Owner->Status == pkgAcquire::Item::StatIdle ||
954 item.Owner->Status == pkgAcquire::Item::StatDone
958 std::string &error(item.Owner->ErrorText);
962 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
963 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
966 virtual bool Pulse(pkgAcquire *Owner) {
967 bool value = pkgAcquireStatus::Pulse(Owner);
970 double(CurrentBytes + CurrentItems) /
971 double(TotalBytes + TotalItems)
974 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
975 [NSNumber numberWithDouble:percent], @"Percent",
977 [NSNumber numberWithDouble:CurrentBytes], @"Current",
978 [NSNumber numberWithDouble:TotalBytes], @"Total",
979 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
980 nil] waitUntilDone:YES];
982 if (value && ![delegate_ isProgressCancelled])
990 _finline bool WasCancelled() const {
994 virtual void Start() {
995 pkgAcquireStatus::Start();
996 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
999 virtual void Stop() {
1000 pkgAcquireStatus::Stop();
1001 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1002 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1006 /* Database Interface {{{ */
1007 typedef std::map< unsigned long, _H<Source> > SourceMap;
1009 @interface Database : NSObject {
1015 pkgCacheFile cache_;
1016 pkgDepCache::Policy *policy_;
1017 pkgRecords *records_;
1018 pkgProblemResolver *resolver_;
1019 pkgAcquire *fetcher_;
1021 SPtr<pkgPackageManager> manager_;
1022 pkgSourceList *list_;
1024 SourceMap sourceMap_;
1025 _H<NSMutableArray> sourceList_;
1027 CFMutableArrayRef packages_;
1029 _transient NSObject<DatabaseDelegate> *delegate_;
1030 _transient NSObject<ProgressDelegate> *progress_;
1038 std::map<const char *, _H<NSString> > sections_;
1041 + (Database *) sharedInstance;
1044 - (void) _readCydia:(NSNumber *)fd;
1045 - (void) _readStatus:(NSNumber *)fd;
1046 - (void) _readOutput:(NSNumber *)fd;
1050 - (Package *) packageWithName:(NSString *)name;
1052 - (pkgCacheFile &) cache;
1053 - (pkgDepCache::Policy *) policy;
1054 - (pkgRecords *) records;
1055 - (pkgProblemResolver *) resolver;
1056 - (pkgAcquire &) fetcher;
1057 - (pkgSourceList &) list;
1058 - (NSArray *) packages;
1059 - (NSArray *) sources;
1060 - (Source *) sourceWithKey:(NSString *)key;
1061 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1069 - (void) updateWithStatus:(Status &)status;
1071 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1073 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1074 - (NSObject<ProgressDelegate> *) progressDelegate;
1076 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1078 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1082 /* ProgressEvent Implementation {{{ */
1083 @implementation CydiaProgressEvent
1085 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1086 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1089 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1090 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1091 [event setPackage:package];
1095 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1096 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1098 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1099 NSArray *fields([description componentsSeparatedByString:@" "]);
1100 [event setItem:fields];
1102 if ([fields count] > 3) {
1103 [event setPackage:[fields objectAtIndex:2]];
1104 [event setVersion:[fields objectAtIndex:3]];
1107 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1112 + (NSArray *) _attributeKeys {
1113 return [NSArray arrayWithObjects:
1123 - (NSArray *) attributeKeys {
1124 return [[self class] _attributeKeys];
1127 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1128 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1131 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1132 if ((self = [super init]) != nil) {
1138 - (NSString *) message {
1142 - (NSString *) type {
1146 - (NSArray *) item {
1147 return (id) item_ ?: [NSNull null];
1150 - (void) setItem:(NSArray *)item {
1154 - (NSString *) package {
1155 return (id) package_ ?: [NSNull null];
1158 - (void) setPackage:(NSString *)package {
1162 - (NSString *) url {
1163 return (id) url_ ?: [NSNull null];
1166 - (void) setURL:(NSString *)url {
1170 - (void) setVersion:(NSString *)version {
1174 - (NSString *) version {
1175 return (id) version_ ?: [NSNull null];
1178 - (NSString *) compound:(NSString *)value {
1180 NSString *mode(nil); {
1181 NSString *type([self type]);
1182 if ([type isEqualToString:kCydiaProgressEventTypeError])
1183 mode = UCLocalize("ERROR");
1184 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1185 mode = UCLocalize("WARNING");
1189 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1195 - (NSString *) compoundMessage {
1196 return [self compound:[self message]];
1199 - (NSString *) compoundTitle {
1202 if (package_ == nil)
1204 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1205 title = [package name];
1209 return [self compound:title];
1215 // Cytore Definitions {{{
1216 struct PackageValue :
1219 Cytore::Offset<PackageValue> next_;
1221 uint32_t index_ : 23;
1222 uint32_t subscribed_ : 1;
1239 Cytore::Offset<PackageValue> packages_[1 << 16];
1242 static Cytore::File<MetaValue> MetaFile_;
1244 // Cytore Helper Functions {{{
1245 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1246 SplitHash nhash = { hashlittle(name, length) };
1248 PackageValue *metadata;
1250 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1251 offset: if (offset->IsNull()) {
1252 *offset = MetaFile_.New<PackageValue>(length + 1);
1253 metadata = &MetaFile_.Get(*offset);
1255 if (metadata == NULL) {
1259 metadata = new PackageValue();
1260 memset(metadata, 0, sizeof(*metadata));
1263 memcpy(metadata->name_, name, length + 1);
1264 metadata->nhash_ = nhash.u16[1];
1266 metadata = &MetaFile_.Get(*offset);
1268 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1269 offset = &metadata->next_;
1277 static void PackageImport(const void *key, const void *value, void *context) {
1278 bool &fail(*reinterpret_cast<bool *>(context));
1281 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1282 NSLog(@"failed to import package %@", key);
1286 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1287 NSDictionary *package((NSDictionary *) value);
1289 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1290 if ([subscribed boolValue] && !metadata->subscribed_)
1291 metadata->subscribed_ = true;
1293 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1294 time_t time([date timeIntervalSince1970]);
1295 if (metadata->first_ > time || metadata->first_ == 0)
1296 metadata->first_ = time;
1299 NSDate *date([package objectForKey:@"LastSeen"]);
1300 NSString *version([package objectForKey:@"LastVersion"]);
1302 if (date != nil && version != nil) {
1303 time_t time([date timeIntervalSince1970]);
1304 if (metadata->last_ < time || metadata->last_ == 0)
1305 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1306 size_t length(strlen(buffer));
1307 uint16_t vhash(hashlittle(buffer, length));
1309 size_t capped(std::min<size_t>(8, length));
1310 char *latest(buffer + length - capped);
1312 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1313 metadata->vhash_ = vhash;
1315 metadata->last_ = time;
1321 /* Source Class {{{ */
1322 @interface Source : NSObject {
1323 CYString depiction_;
1324 CYString description_;
1330 CYString distribution_;
1335 _H<NSString> authority_;
1337 CYString defaultIcon_;
1339 _H<NSDictionary> record_;
1343 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1345 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1347 - (NSString *) depictionForPackage:(NSString *)package;
1348 - (NSString *) supportForPackage:(NSString *)package;
1350 - (NSDictionary *) record;
1354 - (NSString *) distribution;
1355 - (NSString *) type;
1357 - (NSString *) host;
1359 - (NSString *) name;
1360 - (NSString *) shortDescription;
1361 - (NSString *) label;
1362 - (NSString *) origin;
1363 - (NSString *) version;
1365 - (NSString *) defaultIcon;
1369 @implementation Source
1373 distribution_.clear();
1376 description_.clear();
1382 defaultIcon_.clear();
1389 + (NSArray *) _attributeKeys {
1390 return [NSArray arrayWithObjects:
1397 @"shortDescription",
1405 - (NSArray *) attributeKeys {
1406 return [[self class] _attributeKeys];
1409 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1410 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1413 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1416 trusted_ = index->IsTrusted();
1418 uri_.set(pool, index->GetURI());
1419 distribution_.set(pool, index->GetDist());
1420 type_.set(pool, index->GetType());
1422 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1423 if (dindex != NULL) {
1425 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1428 pkgTagFile tags(&fd);
1430 pkgTagSection section;
1437 {"default-icon", &defaultIcon_},
1438 {"depiction", &depiction_},
1439 {"description", &description_},
1441 {"origin", &origin_},
1442 {"support", &support_},
1443 {"version", &version_},
1446 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1447 const char *start, *end;
1449 if (section.Find(names[i].name_, start, end)) {
1450 CYString &value(*names[i].value_);
1451 value.set(pool, start, end - start);
1457 record_ = [Sources_ objectForKey:[self key]];
1459 NSURL *url([NSURL URLWithString:uri_]);
1463 host_ = [host_ lowercaseString];
1466 // XXX: this is due to a bug in _H<>
1467 authority_ = (id) host_;
1469 authority_ = [url path];
1472 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1473 if ((self = [super init]) != nil) {
1474 [self setMetaIndex:index inPool:pool];
1478 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1479 NSDictionary *lhr = [self record];
1480 NSDictionary *rhr = [source record];
1483 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1485 NSString *lhs = [self name];
1486 NSString *rhs = [source name];
1488 if ([lhs length] != 0 && [rhs length] != 0) {
1489 unichar lhc = [lhs characterAtIndex:0];
1490 unichar rhc = [rhs characterAtIndex:0];
1492 if (isalpha(lhc) && !isalpha(rhc))
1493 return NSOrderedAscending;
1494 else if (!isalpha(lhc) && isalpha(rhc))
1495 return NSOrderedDescending;
1498 return [lhs compare:rhs options:LaxCompareOptions_];
1501 - (NSString *) depictionForPackage:(NSString *)package {
1502 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1505 - (NSString *) supportForPackage:(NSString *)package {
1506 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1509 - (NSDictionary *) record {
1517 - (NSString *) uri {
1521 - (NSString *) distribution {
1522 return distribution_;
1525 - (NSString *) type {
1529 - (NSString *) key {
1530 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1533 - (NSString *) host {
1537 - (NSString *) name {
1538 return origin_.empty() ? (id) authority_ : origin_;
1541 - (NSString *) shortDescription {
1542 return description_;
1545 - (NSString *) label {
1546 return label_.empty() ? (id) authority_ : label_;
1549 - (NSString *) origin {
1553 - (NSString *) version {
1557 - (NSString *) defaultIcon {
1558 return defaultIcon_;
1563 /* CydiaOperation Class {{{ */
1564 @interface CydiaOperation : NSObject {
1565 _H<NSString> operator_;
1566 _H<NSString> value_;
1569 - (NSString *) operator;
1570 - (NSString *) value;
1574 @implementation CydiaOperation
1576 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1577 if ((self = [super init]) != nil) {
1578 operator_ = [NSString stringWithUTF8String:_operator];
1579 value_ = [NSString stringWithUTF8String:value];
1583 + (NSArray *) _attributeKeys {
1584 return [NSArray arrayWithObjects:
1590 - (NSArray *) attributeKeys {
1591 return [[self class] _attributeKeys];
1594 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1595 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1598 - (NSString *) operator {
1602 - (NSString *) value {
1608 /* CydiaClause Class {{{ */
1609 @interface CydiaClause : NSObject {
1610 _H<NSString> package_;
1611 _H<CydiaOperation> version_;
1614 - (NSString *) package;
1615 - (CydiaOperation *) version;
1619 @implementation CydiaClause
1621 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1622 if ((self = [super init]) != nil) {
1623 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1625 if (const char *version = dep.TargetVer())
1626 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1628 version_ = (id) [NSNull null];
1632 + (NSArray *) _attributeKeys {
1633 return [NSArray arrayWithObjects:
1639 - (NSArray *) attributeKeys {
1640 return [[self class] _attributeKeys];
1643 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1644 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1647 - (NSString *) package {
1651 - (CydiaOperation *) version {
1657 /* CydiaRelation Class {{{ */
1658 @interface CydiaRelation : NSObject {
1659 _H<NSString> relationship_;
1660 _H<NSMutableArray> clauses_;
1663 - (NSString *) relationship;
1664 - (NSArray *) clauses;
1668 @implementation CydiaRelation
1670 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1671 if ((self = [super init]) != nil) {
1672 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1673 clauses_ = [NSMutableArray arrayWithCapacity:8];
1675 pkgCache::DepIterator start;
1676 pkgCache::DepIterator end;
1677 dep.GlobOr(start, end); // ++dep
1680 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1682 // yes, seriously. (wtf?)
1690 + (NSArray *) _attributeKeys {
1691 return [NSArray arrayWithObjects:
1697 - (NSArray *) attributeKeys {
1698 return [[self class] _attributeKeys];
1701 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1702 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1705 - (NSString *) relationship {
1706 return relationship_;
1709 - (NSArray *) clauses {
1713 - (void) addClause:(CydiaClause *)clause {
1714 [clauses_ addObject:clause];
1719 /* Package Class {{{ */
1720 struct ParsedPackage {
1725 CYString depiction_;
1735 @interface Package : NSObject {
1738 uint32_t essential_ : 1;
1739 uint32_t obsolete_ : 1;
1740 uint32_t ignored_ : 1;
1744 _transient Database *database_;
1746 pkgCache::VerIterator version_;
1747 pkgCache::PkgIterator iterator_;
1748 pkgCache::VerFileIterator file_;
1754 CYString installed_;
1756 const char *section_;
1757 _transient NSString *section$_;
1761 PackageValue *metadata_;
1762 ParsedPackage *parsed_;
1764 _H<NSMutableArray> tags_;
1767 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1768 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1770 - (pkgCache::PkgIterator) iterator;
1773 - (NSString *) section;
1774 - (NSString *) simpleSection;
1776 - (NSString *) longSection;
1777 - (NSString *) shortSection;
1781 - (Address *) maintainer;
1783 - (NSString *) longDescription;
1784 - (NSString *) shortDescription;
1787 - (PackageValue *) metadata;
1790 - (bool) subscribed;
1791 - (bool) setSubscribed:(bool)subscribed;
1795 - (NSString *) latest;
1796 - (NSString *) installed;
1797 - (BOOL) uninstalled;
1800 - (BOOL) upgradableAndEssential:(BOOL)essential;
1803 - (BOOL) unfiltered;
1807 - (BOOL) halfConfigured;
1808 - (BOOL) halfInstalled;
1810 - (NSString *) mode;
1813 - (NSString *) name;
1815 - (NSString *) homepage;
1816 - (NSString *) depiction;
1817 - (Address *) author;
1819 - (NSString *) support;
1821 - (NSArray *) files;
1822 - (NSArray *) warnings;
1823 - (NSArray *) applications;
1825 - (Source *) source;
1827 - (BOOL) matches:(NSString *)text;
1829 - (bool) hasSupportingRole;
1830 - (BOOL) hasTag:(NSString *)tag;
1831 - (NSString *) primaryPurpose;
1832 - (NSArray *) purposes;
1833 - (bool) isCommercial;
1835 - (void) setIndex:(size_t)index;
1837 - (CYString &) cyname;
1839 - (uint32_t) compareBySection:(NSArray *)sections;
1844 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1845 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1846 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1847 - (bool) isVisibleInSection:(NSString *)section;
1848 - (bool) isVisibleInSource:(Source *)source;
1852 uint32_t PackageChangesRadix(Package *self, void *) {
1857 uint32_t timestamp : 30;
1858 uint32_t ignored : 1;
1859 uint32_t upgradable : 1;
1863 bool upgradable([self upgradableAndEssential:YES]);
1864 value.bits.upgradable = upgradable ? 1 : 0;
1867 value.bits.timestamp = 0;
1868 value.bits.ignored = [self ignored] ? 0 : 1;
1869 value.bits.upgradable = 1;
1871 value.bits.timestamp = [self seen] >> 2;
1872 value.bits.ignored = 0;
1873 value.bits.upgradable = 0;
1876 return _not(uint32_t) - value.key;
1879 uint32_t PackagePrefixRadix(Package *self, void *context) {
1880 size_t offset(reinterpret_cast<size_t>(context));
1881 CYString &name([self cyname]);
1883 size_t size(name.size());
1886 char *text(name.data());
1889 if (!isdigit(text[0]))
1893 while (size != digits && isdigit(text[digits]))
1901 if (offset == 0 && zeros != 0) {
1902 memset(data, '0', zeros);
1903 memcpy(data + zeros, text, 4 - zeros);
1905 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1906 if (size <= offset - zeros)
1909 text += offset - zeros;
1910 size -= offset - zeros;
1913 memcpy(data, text, 4);
1915 memcpy(data, text, size);
1916 memset(data + size, 0, 4 - size);
1919 for (size_t i(0); i != 4; ++i)
1920 if (isalpha(data[i]))
1928 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1930 /* XXX: ntohl may be more honest */
1931 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1934 CYString &(*PackageName)(Package *self, SEL sel);
1936 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1937 _profile(PackageNameCompare)
1938 CYString &lhi(PackageName(lhs, @selector(cyname)));
1939 CYString &rhi(PackageName(rhs, @selector(cyname)));
1940 CFStringRef lhn(lhi), rhn(rhi);
1943 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1944 else if (rhn == NULL)
1945 return NSOrderedDescending;
1947 _profile(PackageNameCompare$NumbersLast)
1948 if (!lhi.empty() && !rhi.empty()) {
1949 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1950 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1951 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1952 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1953 return lha ? NSOrderedAscending : NSOrderedDescending;
1957 CFIndex length = CFStringGetLength(lhn);
1959 _profile(PackageNameCompare$Compare)
1960 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1965 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1966 return PackageNameCompare(*lhs, *rhs, context);
1969 struct PackageNameOrdering :
1970 std::binary_function<Package *, Package *, bool>
1972 _finline bool operator ()(Package *lhs, Package *rhs) const {
1973 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1977 @implementation Package
1979 - (NSString *) description {
1980 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1984 if (parsed_ != NULL)
1989 + (NSString *) webScriptNameForSelector:(SEL)selector {
1991 else if (selector == @selector(clear))
1993 else if (selector == @selector(getField:))
1995 else if (selector == @selector(hasTag:))
1997 else if (selector == @selector(install))
1999 else if (selector == @selector(remove))
2005 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2006 return [self webScriptNameForSelector:selector] == nil;
2009 + (NSArray *) _attributeKeys {
2010 return [NSArray arrayWithObjects:
2029 @"shortDescription",
2042 - (NSArray *) attributeKeys {
2043 return [[self class] _attributeKeys];
2046 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2047 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2050 - (NSArray *) relations {
2051 @synchronized (database_) {
2052 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2053 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2054 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2058 - (NSString *) getField:(NSString *)name {
2059 @synchronized (database_) {
2060 if ([database_ era] != era_ || file_.end())
2063 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2065 const char *start, *end;
2066 if (!parser.Find([name UTF8String], start, end))
2067 return (NSString *) [NSNull null];
2069 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2073 if (parsed_ != NULL)
2075 @synchronized (database_) {
2076 if ([database_ era] != era_ || file_.end())
2079 ParsedPackage *parsed(new ParsedPackage);
2082 _profile(Package$parse)
2083 pkgRecords::Parser *parser;
2085 _profile(Package$parse$Lookup)
2086 parser = &[database_ records]->Lookup(file_);
2091 _profile(Package$parse$Find)
2096 {"icon", &parsed->icon_},
2097 {"depiction", &parsed->depiction_},
2098 {"homepage", &parsed->homepage_},
2099 {"website", &website},
2100 {"bugs", &parsed->bugs_},
2101 {"support", &parsed->support_},
2102 {"sponsor", &parsed->sponsor_},
2103 {"author", &parsed->author_},
2106 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2107 const char *start, *end;
2109 if (parser->Find(names[i].name_, start, end)) {
2110 CYString &value(*names[i].value_);
2111 _profile(Package$parse$Value)
2112 value.set(pool_, start, end - start);
2118 _profile(Package$parse$Tagline)
2119 const char *start, *end;
2120 if (parser->ShortDesc(start, end)) {
2121 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2124 while (stop != start && stop[-1] == '\r')
2126 parsed->tagline_.set(pool_, start, stop - start);
2130 _profile(Package$parse$Retain)
2131 if (parsed->homepage_.empty())
2132 parsed->homepage_ = website;
2133 if (parsed->homepage_ == parsed->depiction_)
2134 parsed->homepage_.clear();
2139 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2140 if ((self = [super init]) != nil) {
2141 _profile(Package$initWithVersion)
2144 database_ = database;
2145 era_ = [database era];
2149 pkgCache::PkgIterator iterator(version.ParentPkg());
2150 iterator_ = iterator;
2152 _profile(Package$initWithVersion$Version)
2153 if (!version_.end())
2154 file_ = version_.FileList();
2156 pkgCache &cache([database_ cache]);
2157 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2161 _profile(Package$initWithVersion$Cache)
2162 name_.set(NULL, iterator.Display());
2164 latest_.set(NULL, StripVersion_(version_.VerStr()));
2166 pkgCache::VerIterator current(iterator.CurrentVer());
2168 installed_.set(NULL, StripVersion_(current.VerStr()));
2171 _profile(Package$initWithVersion$Tags)
2172 pkgCache::TagIterator tag(iterator.TagList());
2174 tags_ = [NSMutableArray arrayWithCapacity:8];
2176 const char *name(tag.Name());
2177 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2179 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2180 if (strcmp(name + 6, "enduser") == 0)
2182 else if (strcmp(name + 6, "hacker") == 0)
2184 else if (strcmp(name + 6, "developer") == 0)
2186 else if (strcmp(name + 6, "cydia") == 0)
2192 if (strncmp(name, "cydia::", 7) == 0) {
2193 if (strcmp(name + 7, "essential") == 0)
2195 else if (strcmp(name + 7, "obsolete") == 0)
2200 } while (!tag.end());
2204 _profile(Package$initWithVersion$Metadata)
2205 const char *mixed(iterator.Name());
2206 size_t size(strlen(mixed));
2207 char lower[size + 1];
2209 for (size_t i(0); i != size; ++i)
2210 lower[i] = mixed[i] | 0x20;
2213 PackageValue *metadata(PackageFind(lower, size));
2214 metadata_ = metadata;
2216 id_.set(NULL, metadata->name_, size);
2218 const char *latest(version_.VerStr());
2219 size_t length(strlen(latest));
2221 uint16_t vhash(hashlittle(latest, length));
2223 size_t capped(std::min<size_t>(8, length));
2224 latest = latest + length - capped;
2226 if (metadata->first_ == 0)
2227 metadata->first_ = now_;
2229 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2230 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2231 metadata->vhash_ = vhash;
2232 metadata->last_ = now_;
2233 } else if (metadata->last_ == 0)
2234 metadata->last_ = metadata->first_;
2237 _profile(Package$initWithVersion$Section)
2238 section_ = iterator.Section();
2241 _profile(Package$initWithVersion$Flags)
2242 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2243 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2248 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2249 pkgCache::VerIterator version;
2251 _profile(Package$packageWithIterator$GetCandidateVer)
2252 version = [database policy]->GetCandidateVer(iterator);
2260 _profile(Package$packageWithIterator$Allocate)
2261 package = [Package allocWithZone:zone];
2264 _profile(Package$packageWithIterator$Initialize)
2266 initWithVersion:version
2273 _profile(Package$packageWithIterator$Autorelease)
2274 package = [package autorelease];
2280 - (pkgCache::PkgIterator) iterator {
2284 - (NSString *) section {
2285 if (section$_ == nil) {
2286 if (section_ == NULL)
2289 _profile(Package$section$mappedSectionForPointer)
2290 section$_ = [database_ mappedSectionForPointer:section_];
2295 - (NSString *) simpleSection {
2296 if (NSString *section = [self section])
2297 return Simplify(section);
2302 - (NSString *) longSection {
2303 return LocalizeSection([self section]);
2306 - (NSString *) shortSection {
2307 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2310 - (NSString *) uri {
2313 pkgIndexFile *index;
2314 pkgCache::PkgFileIterator file(file_.File());
2315 if (![database_ list].FindIndex(file, index))
2317 return [NSString stringWithUTF8String:iterator_->Path];
2318 //return [NSString stringWithUTF8String:file.Site()];
2319 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2323 - (Address *) maintainer {
2324 @synchronized (database_) {
2325 if ([database_ era] != era_ || file_.end())
2328 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2329 const std::string &maintainer(parser->Maintainer());
2330 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2334 @synchronized (database_) {
2335 if ([database_ era] != era_ || version_.end())
2338 return version_->InstalledSize;
2341 - (NSString *) longDescription {
2342 @synchronized (database_) {
2343 if ([database_ era] != era_ || file_.end())
2346 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2347 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2349 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2350 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2351 if ([lines count] < 2)
2354 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2355 for (size_t i(1), e([lines count]); i != e; ++i) {
2356 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2357 [trimmed addObject:trim];
2360 return [trimmed componentsJoinedByString:@"\n"];
2363 - (NSString *) shortDescription {
2364 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2368 _profile(Package$index)
2369 CFStringRef name((CFStringRef) [self name]);
2370 if (CFStringGetLength(name) == 0)
2372 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2373 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2375 return toupper(character);
2379 - (PackageValue *) metadata {
2384 PackageValue *metadata([self metadata]);
2385 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2388 - (bool) subscribed {
2389 return [self metadata]->subscribed_;
2392 - (bool) setSubscribed:(bool)subscribed {
2393 PackageValue *metadata([self metadata]);
2394 if (metadata->subscribed_ == subscribed)
2396 metadata->subscribed_ = subscribed;
2404 - (NSString *) latest {
2408 - (NSString *) installed {
2412 - (BOOL) uninstalled {
2413 return installed_.empty();
2417 return !version_.end();
2420 - (BOOL) upgradableAndEssential:(BOOL)essential {
2421 _profile(Package$upgradableAndEssential)
2422 pkgCache::VerIterator current(iterator_.CurrentVer());
2424 return essential && essential_;
2426 return !version_.end() && version_ != current;
2430 - (BOOL) essential {
2435 return [database_ cache][iterator_].InstBroken();
2438 - (BOOL) unfiltered {
2439 _profile(Package$unfiltered$obsolete)
2440 if (_unlikely(obsolete_))
2444 _profile(Package$unfiltered$hasSupportingRole)
2445 if (_unlikely(![self hasSupportingRole]))
2453 if (![self unfiltered])
2458 _profile(Package$visible$section)
2459 section = [self section];
2462 _profile(Package$visible$isSectionVisible)
2463 if (!isSectionVisible(section))
2471 unsigned char current(iterator_->CurrentState);
2472 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2475 - (BOOL) halfConfigured {
2476 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2479 - (BOOL) halfInstalled {
2480 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2484 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2485 return state.Mode != pkgDepCache::ModeKeep;
2488 - (NSString *) mode {
2489 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2491 switch (state.Mode) {
2492 case pkgDepCache::ModeDelete:
2493 if ((state.iFlags & pkgDepCache::Purge) != 0)
2497 case pkgDepCache::ModeKeep:
2498 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2499 return @"REINSTALL";
2500 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2504 case pkgDepCache::ModeInstall:
2505 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2506 return @"REINSTALL";
2507 else*/ switch (state.Status) {
2509 return @"DOWNGRADE";
2515 return @"NEW_INSTALL";
2526 - (NSString *) name {
2527 return name_.empty() ? id_ : name_;
2530 - (UIImage *) icon {
2531 NSString *section = [self simpleSection];
2534 if (parsed_ != NULL)
2535 if (NSString *href = parsed_->icon_)
2536 if ([href hasPrefix:@"file:///"])
2537 // XXX: correct escaping
2538 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2539 if (icon == nil) if (section != nil)
2540 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2541 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2542 if ([dicon hasPrefix:@"file:///"])
2543 // XXX: correct escaping
2544 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2546 icon = [UIImage applicationImageNamed:@"unknown.png"];
2550 - (NSString *) homepage {
2551 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2554 - (NSString *) depiction {
2555 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2558 - (Address *) sponsor {
2559 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2562 - (Address *) author {
2563 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2566 - (NSString *) support {
2567 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2570 - (NSArray *) files {
2571 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2572 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2575 fin.open([path UTF8String]);
2580 while (std::getline(fin, line))
2581 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2586 - (NSString *) state {
2587 @synchronized (database_) {
2588 if ([database_ era] != era_ || file_.end())
2591 switch (iterator_->CurrentState) {
2592 case pkgCache::State::NotInstalled:
2593 return @"NotInstalled";
2594 case pkgCache::State::UnPacked:
2596 case pkgCache::State::HalfConfigured:
2597 return @"HalfConfigured";
2598 case pkgCache::State::HalfInstalled:
2599 return @"HalfInstalled";
2600 case pkgCache::State::ConfigFiles:
2601 return @"ConfigFiles";
2602 case pkgCache::State::Installed:
2603 return @"Installed";
2604 case pkgCache::State::TriggersAwaited:
2605 return @"TriggersAwaited";
2606 case pkgCache::State::TriggersPending:
2607 return @"TriggersPending";
2610 return (NSString *) [NSNull null];
2613 - (NSString *) selection {
2614 @synchronized (database_) {
2615 if ([database_ era] != era_ || file_.end())
2618 switch (iterator_->SelectedState) {
2619 case pkgCache::State::Unknown:
2621 case pkgCache::State::Install:
2623 case pkgCache::State::Hold:
2625 case pkgCache::State::DeInstall:
2626 return @"DeInstall";
2627 case pkgCache::State::Purge:
2631 return (NSString *) [NSNull null];
2634 - (NSArray *) warnings {
2635 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2636 const char *name(iterator_.Name());
2638 size_t length(strlen(name));
2639 if (length < 2) invalid:
2640 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2641 else for (size_t i(0); i != length; ++i)
2643 /* XXX: technically this is not allowed */
2644 (name[i] < 'A' || name[i] > 'Z') &&
2645 (name[i] < 'a' || name[i] > 'z') &&
2646 (name[i] < '0' || name[i] > '9') &&
2647 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2650 if (strcmp(name, "cydia") != 0) {
2653 bool _private = false;
2656 bool repository = [[self section] isEqualToString:@"Repositories"];
2658 if (NSArray *files = [self files])
2659 for (NSString *file in files)
2660 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2662 else if (!user && [file isEqualToString:@"/User"])
2664 else if (!_private && [file isEqualToString:@"/private"])
2666 else if (!stash && [file isEqualToString:@"/var/stash"])
2669 /* XXX: this is not sensitive enough. only some folders are valid. */
2670 if (cydia && !repository)
2671 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2673 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2675 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2677 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2680 return [warnings count] == 0 ? nil : warnings;
2683 - (NSArray *) applications {
2684 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2686 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2688 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2689 if (NSArray *files = [self files])
2690 for (NSString *file in files)
2691 if (application_r(file)) {
2692 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2693 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2694 if ([id isEqualToString:me])
2697 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2699 display = application_r[1];
2701 NSString *bundle([file stringByDeletingLastPathComponent]);
2702 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2703 if (icon == nil || [icon length] == 0)
2705 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2707 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2708 [applications addObject:application];
2710 [application addObject:id];
2711 [application addObject:display];
2712 [application addObject:url];
2715 return [applications count] == 0 ? nil : applications;
2718 - (Source *) source {
2719 if (source_ == nil) {
2720 @synchronized (database_) {
2721 if ([database_ era] != era_ || file_.end())
2722 source_ = (Source *) [NSNull null];
2724 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2728 return source_ == (Source *) [NSNull null] ? nil : source_;
2731 - (BOOL) matches:(NSString *)text {
2737 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2738 if (range.location != NSNotFound)
2741 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2742 if (range.location != NSNotFound)
2747 NSString *description([self shortDescription]);
2748 NSUInteger length([description length]);
2750 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_ range:NSMakeRange(0, std::min<NSUInteger>(length, 100))];
2751 if (range.location != NSNotFound)
2757 - (bool) hasSupportingRole {
2762 if ([Role_ isEqualToString:@"User"])
2766 if ([Role_ isEqualToString:@"Hacker"])
2770 if ([Role_ isEqualToString:@"Developer"])
2775 - (NSArray *) tags {
2779 - (BOOL) hasTag:(NSString *)tag {
2780 return tags_ == nil ? NO : [tags_ containsObject:tag];
2783 - (NSString *) primaryPurpose {
2784 for (NSString *tag in (NSArray *) tags_)
2785 if ([tag hasPrefix:@"purpose::"])
2786 return [tag substringFromIndex:9];
2790 - (NSArray *) purposes {
2791 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2792 for (NSString *tag in (NSArray *) tags_)
2793 if ([tag hasPrefix:@"purpose::"])
2794 [purposes addObject:[tag substringFromIndex:9]];
2795 return [purposes count] == 0 ? nil : purposes;
2798 - (bool) isCommercial {
2799 return [self hasTag:@"cydia::commercial"];
2802 - (void) setIndex:(size_t)index {
2803 if (metadata_->index_ != index)
2804 metadata_->index_ = index;
2807 - (CYString &) cyname {
2808 return name_.empty() ? id_ : name_;
2811 - (uint32_t) compareBySection:(NSArray *)sections {
2812 NSString *section([self section]);
2813 for (size_t i(0), e([sections count]); i != e; ++i) {
2814 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2818 return _not(uint32_t);
2822 @synchronized (database_) {
2823 pkgProblemResolver *resolver = [database_ resolver];
2824 resolver->Clear(iterator_);
2826 pkgCacheFile &cache([database_ cache]);
2827 cache->SetReInstall(iterator_, false);
2828 cache->MarkKeep(iterator_, false);
2832 @synchronized (database_) {
2833 pkgProblemResolver *resolver = [database_ resolver];
2834 resolver->Clear(iterator_);
2835 resolver->Protect(iterator_);
2837 pkgCacheFile &cache([database_ cache]);
2838 cache->SetReInstall(iterator_, false);
2839 cache->MarkInstall(iterator_, false);
2841 pkgDepCache::StateCache &state((*cache)[iterator_]);
2842 if (!state.Install())
2843 cache->SetReInstall(iterator_, true);
2847 @synchronized (database_) {
2848 pkgProblemResolver *resolver = [database_ resolver];
2849 resolver->Clear(iterator_);
2850 resolver->Remove(iterator_);
2851 resolver->Protect(iterator_);
2853 pkgCacheFile &cache([database_ cache]);
2854 cache->SetReInstall(iterator_, false);
2855 cache->MarkDelete(iterator_, true);
2858 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2859 _profile(Package$isUnfilteredAndSearchedForBy)
2862 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2863 value &= [self unfiltered];
2866 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2867 value &= [self matches:search];
2874 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2875 if ([search length] == 0)
2878 _profile(Package$isUnfilteredAndSelectedForBy)
2881 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2882 value &= [self unfiltered];
2885 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2886 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2893 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2894 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2897 - (bool) isVisibleInSection:(NSString *)name {
2898 NSString *section([self section]);
2902 section == nil && [name length] == 0 ||
2903 [name isEqualToString:section]
2904 ) && [self visible];
2907 - (bool) isVisibleInSource:(Source *)source {
2908 return [self source] == source && [self visible];
2913 /* Section Class {{{ */
2914 @interface Section : NSObject {
2919 _H<NSString> localized_;
2922 - (NSComparisonResult) compareByLocalized:(Section *)section;
2923 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2924 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2925 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2926 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2927 - (NSString *) name;
2934 - (void) addToCount;
2936 - (void) setCount:(size_t)count;
2937 - (NSString *) localized;
2941 @implementation Section
2943 - (NSComparisonResult) compareByLocalized:(Section *)section {
2944 NSString *lhs(localized_);
2945 NSString *rhs([section localized]);
2947 /*if ([lhs length] != 0 && [rhs length] != 0) {
2948 unichar lhc = [lhs characterAtIndex:0];
2949 unichar rhc = [rhs characterAtIndex:0];
2951 if (isalpha(lhc) && !isalpha(rhc))
2952 return NSOrderedAscending;
2953 else if (!isalpha(lhc) && isalpha(rhc))
2954 return NSOrderedDescending;
2957 return [lhs compare:rhs options:LaxCompareOptions_];
2960 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2961 if ((self = [self initWithName:name localize:NO]) != nil) {
2962 if (localized != nil)
2963 localized_ = localized;
2967 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2968 return [self initWithName:name row:0 localize:localize];
2971 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2972 if ((self = [super init]) != nil) {
2977 localized_ = LocalizeSection(name_);
2981 /* XXX: localize the index thingees */
2982 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2983 if ((self = [super init]) != nil) {
2984 name_ = [NSString stringWithCharacters:&index length:1];
2990 - (NSString *) name {
3010 - (void) addToCount {
3014 - (void) setCount:(size_t)count {
3018 - (NSString *) localized {
3025 static NSString *Colon_;
3026 static NSString *Elision_;
3027 static NSString *Error_;
3028 static NSString *Warning_;
3030 class CydiaLogCleaner :
3031 public pkgArchiveCleaner
3034 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3039 /* Database Implementation {{{ */
3040 @implementation Database
3042 + (Database *) sharedInstance {
3043 static _H<Database> instance;
3044 if (instance == nil)
3045 instance = [[[Database alloc] init] autorelease];
3053 - (void) releasePackages {
3054 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3055 CFArrayRemoveAllValues(packages_);
3059 // XXX: actually implement this thing
3061 [self releasePackages];
3062 apr_pool_destroy(pool_);
3063 NSRecycleZone(zone_);
3067 - (void) _readCydia:(NSNumber *)fd {
3068 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3069 std::istream is(&ib);
3072 static Pcre finish_r("^finish:([^:]*)$");
3074 while (std::getline(is, line)) {
3075 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3077 const char *data(line.c_str());
3078 size_t size = line.size();
3079 lprintf("C:%s\n", data);
3081 if (finish_r(data, size)) {
3082 NSString *finish = finish_r[1];
3083 int index = [Finishes_ indexOfObject:finish];
3084 if (index != INT_MAX && index > Finish_)
3094 - (void) _readStatus:(NSNumber *)fd {
3095 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3096 std::istream is(&ib);
3099 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3100 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3102 while (std::getline(is, line)) {
3103 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3105 const char *data(line.c_str());
3106 size_t size(line.size());
3107 lprintf("S:%s\n", data);
3109 if (conffile_r(data, size)) {
3110 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3111 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3112 } else if (strncmp(data, "status: ", 8) == 0) {
3113 // status: <package>: {unpacked,half-configured,installed}
3114 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3115 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3116 } else if (strncmp(data, "processing: ", 12) == 0) {
3117 // processing: configure: config-test
3118 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3119 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3120 } else if (pmstatus_r(data, size)) {
3121 std::string type([pmstatus_r[1] UTF8String]);
3123 NSString *package = pmstatus_r[2];
3124 if ([package isEqualToString:@"dpkg-exec"])
3127 float percent([pmstatus_r[3] floatValue]);
3128 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3130 NSString *string = pmstatus_r[4];
3132 if (type == "pmerror") {
3133 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3134 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3135 } else if (type == "pmstatus") {
3136 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3137 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3138 } else if (type == "pmconffile")
3139 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3141 lprintf("E:unknown pmstatus\n");
3143 lprintf("E:unknown status\n");
3151 - (void) _readOutput:(NSNumber *)fd {
3152 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3153 std::istream is(&ib);
3156 while (std::getline(is, line)) {
3157 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3159 lprintf("O:%s\n", line.c_str());
3161 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3162 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3174 - (Package *) packageWithName:(NSString *)name {
3175 @synchronized (self) {
3176 if (static_cast<pkgDepCache *>(cache_) == NULL)
3178 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3179 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3183 if ((self = [super init]) != nil) {
3190 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3191 apr_pool_create(&pool_, NULL);
3193 size_t capacity(MetaFile_->active_);
3199 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3200 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3204 _assert(pipe(fds) != -1);
3207 _config->Set("APT::Keep-Fds::", cydiafd_);
3208 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3211 detachNewThreadSelector:@selector(_readCydia:)
3213 withObject:[NSNumber numberWithInt:fds[0]]
3216 _assert(pipe(fds) != -1);
3220 detachNewThreadSelector:@selector(_readStatus:)
3222 withObject:[NSNumber numberWithInt:fds[0]]
3225 _assert(pipe(fds) != -1);
3226 _assert(dup2(fds[0], 0) != -1);
3227 _assert(close(fds[0]) != -1);
3229 input_ = fdopen(fds[1], "a");
3231 _assert(pipe(fds) != -1);
3232 _assert(dup2(fds[1], 1) != -1);
3233 _assert(close(fds[1]) != -1);
3236 detachNewThreadSelector:@selector(_readOutput:)
3238 withObject:[NSNumber numberWithInt:fds[0]]
3243 - (pkgCacheFile &) cache {
3247 - (pkgDepCache::Policy *) policy {
3251 - (pkgRecords *) records {
3255 - (pkgProblemResolver *) resolver {
3259 - (pkgAcquire &) fetcher {
3263 - (pkgSourceList &) list {
3267 - (NSArray *) packages {
3268 return (NSArray *) packages_;
3271 - (NSArray *) sources {
3275 - (Source *) sourceWithKey:(NSString *)key {
3276 for (Source *source in [self sources]) {
3277 if ([[source key] isEqualToString:key])
3282 - (bool) popErrorWithTitle:(NSString *)title {
3285 while (!_error->empty()) {
3287 bool warning(!_error->PopMessage(error));
3292 size_t size(error.size());
3293 if (size == 0 || error[size - 1] != '\n')
3295 error.resize(size - 1);
3298 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3300 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3306 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3307 return [self popErrorWithTitle:title] || !success;
3310 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3311 @synchronized (self) {
3314 [self releasePackages];
3317 [sourceList_ removeAllObjects];
3337 apr_pool_clear(pool_);
3339 NSRecycleZone(zone_);
3340 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3342 int chk(creat("/tmp/cydia.chk", 0644));
3346 if (invocation != nil)
3347 [invocation invoke];
3349 NSString *title(UCLocalize("DATABASE"));
3352 OpProgress progress;
3353 while (!cache_.Open(progress, true)) { pop:
3355 bool warning(!_error->PopMessage(error));
3356 lprintf("cache_.Open():[%s]\n", error.c_str());
3358 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3359 [delegate_ repairWithSelector:@selector(configure)];
3360 else if (error == "The package lists or status file could not be parsed or opened.")
3361 [delegate_ repairWithSelector:@selector(update)];
3362 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3363 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3364 // else if (error == "Malformed Status line")
3365 // else if (error == "The list of sources could not be read.")
3367 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3377 unlink("/tmp/cydia.chk");
3379 now_ = [[NSDate date] timeIntervalSince1970];
3381 policy_ = new pkgDepCache::Policy();
3382 records_ = new pkgRecords(cache_);
3383 resolver_ = new pkgProblemResolver(cache_);
3384 fetcher_ = new pkgAcquire(&status_);
3387 list_ = new pkgSourceList();
3388 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3391 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3392 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3396 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3399 if (cache_->BrokenCount() != 0) {
3400 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3403 if (cache_->BrokenCount() != 0) {
3404 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3408 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3412 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3413 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3414 [sourceList_ addObject:object];
3416 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3417 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3418 // XXX: this could be more intelligent
3419 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3420 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3422 sourceMap_[cached->ID] = object;
3427 /*std::vector<Package *> packages;
3428 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3433 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3434 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3435 //packages.push_back(package);
3436 CFArrayAppendValue(packages_, CFRetain(package));
3440 /*if (packages.empty())
3441 packages_ = [[NSArray alloc] init];
3443 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3446 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3447 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3448 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3456 /*if (!packages.empty())
3457 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3458 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3460 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3462 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3464 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3468 size_t count(CFArrayGetCount(packages_));
3469 MetaFile_->active_ = count;
3471 for (size_t index(0); index != count; ++index)
3472 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3479 @synchronized (self) {
3481 resolver_ = new pkgProblemResolver(cache_);
3483 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3484 if (!cache_[iterator].Keep())
3485 cache_->MarkKeep(iterator, false);
3486 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3487 cache_->SetReInstall(iterator, false);
3490 - (void) configure {
3491 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3493 system([dpkg UTF8String]);
3498 // XXX: I don't remember this condition
3503 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3505 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3507 if ([self popErrorWithTitle:title])
3511 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3513 CydiaLogCleaner cleaner;
3514 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3521 fetcher_->Shutdown();
3523 pkgRecords records(cache_);
3525 lock_ = new FileFd();
3526 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3528 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3530 if ([self popErrorWithTitle:title])
3534 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3537 manager_ = (_system->CreatePM(cache_));
3538 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3545 bool substrate(RestartSubstrate_);
3546 RestartSubstrate_ = false;
3548 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3550 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3552 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3554 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3555 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3558 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3560 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3562 [self popErrorWithTitle:title];
3566 bool failed = false;
3567 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3568 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3570 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3576 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3584 RestartSubstrate_ = true;
3587 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3589 if (_error->PendingError()) {
3594 if (result == pkgPackageManager::Failed) {
3599 if (result != pkgPackageManager::Completed) {
3604 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3606 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3608 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3609 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3612 if (![before isEqualToArray:after])
3617 NSString *title(UCLocalize("UPGRADE"));
3618 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3624 [self updateWithStatus:status_];
3627 - (void) updateWithStatus:(Status &)status {
3628 NSString *title(UCLocalize("REFRESHING_DATA"));
3631 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3635 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3636 if ([self popErrorWithTitle:title])
3639 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3641 bool success(ListUpdate(status, list, PulseInterval_));
3642 if (status.WasCancelled())
3645 [self popErrorWithTitle:title forOperation:success];
3646 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3650 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3653 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3654 delegate_ = delegate;
3657 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3658 progress_ = delegate;
3659 status_.setDelegate(delegate);
3662 - (NSObject<ProgressDelegate> *) progressDelegate {
3666 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3667 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3668 return i == sourceMap_.end() ? nil : i->second;
3671 - (NSString *) mappedSectionForPointer:(const char *)section {
3672 _H<NSString> *mapped;
3674 _profile(Database$mappedSectionForPointer$Cache)
3675 mapped = §ions_[section];
3678 if (*mapped == NULL) {
3679 size_t length(strlen(section));
3680 char spaced[length + 1];
3682 _profile(Database$mappedSectionForPointer$Replace)
3683 for (size_t index(0); index != length; ++index)
3684 spaced[index] = section[index] == '_' ? ' ' : section[index];
3685 spaced[length] = '\0';
3690 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3691 string = [NSString stringWithUTF8String:spaced];
3694 _profile(Database$mappedSectionForPointer$Map)
3695 string = [SectionMap_ objectForKey:string] ?: string;
3705 static _H<NSMutableSet> Diversions_;
3707 @interface Diversion : NSObject {
3710 _H<NSString> format_;
3715 @implementation Diversion
3717 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3718 if ((self = [super init]) != nil) {
3719 pattern_ = [from UTF8String];
3725 - (NSString *) divert:(NSString *)url {
3726 return !pattern_(url) ? nil : pattern_->*format_;
3729 + (NSURL *) divertURL:(NSURL *)url {
3731 NSString *href([url absoluteString]);
3733 for (Diversion *diversion in (id) Diversions_)
3734 if (NSString *diverted = [diversion divert:href]) {
3736 NSLog(@"div: %@", diverted);
3738 url = [NSURL URLWithString:diverted];
3745 - (NSString *) key {
3749 - (NSUInteger) hash {
3753 - (BOOL) isEqual:(Diversion *)object {
3754 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3759 @interface CydiaObject : NSObject {
3760 _H<IndirectDelegate> indirect_;
3761 _transient id delegate_;
3764 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3768 @interface CydiaWebViewController : CyteWebViewController {
3769 _H<CydiaObject> cydia_;
3772 + (void) addDiversion:(Diversion *)diversion;
3776 /* Web Scripting {{{ */
3777 @implementation CydiaObject
3779 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3780 if ((self = [super init]) != nil) {
3781 indirect_ = indirect;
3785 - (void) setDelegate:(id)delegate {
3786 delegate_ = delegate;
3789 + (NSArray *) _attributeKeys {
3790 return [NSArray arrayWithObjects:
3806 - (NSArray *) attributeKeys {
3807 return [[self class] _attributeKeys];
3810 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3811 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3814 - (NSString *) version {
3818 - (NSString *) device {
3819 return [[UIDevice currentDevice] uniqueIdentifier];
3822 - (NSString *) firmware {
3823 return [[UIDevice currentDevice] systemVersion];
3826 - (NSString *) hostname {
3827 return [[UIDevice currentDevice] name];
3830 - (NSString *) idiom {
3831 return (id) Idiom_ ?: [NSNull null];
3834 - (NSString *) plmn {
3835 return (id) PLMN_ ?: [NSNull null];
3838 - (NSString *) bbsnum {
3839 return (id) BBSNum_ ?: [NSNull null];
3842 - (NSString *) ecid {
3843 return (id) ChipID_ ?: [NSNull null];
3846 - (NSString *) serial {
3847 return SerialNumber_;
3850 - (NSString *) role {
3851 return (id) Role_ ?: [NSNull null];
3854 - (NSString *) model {
3855 return [NSString stringWithUTF8String:Machine_];
3858 - (NSString *) token {
3859 return (id) Token_ ?: [NSNull null];
3862 + (NSString *) webScriptNameForSelector:(SEL)selector {
3864 else if (selector == @selector(addBridgedHost:))
3865 return @"addBridgedHost";
3866 else if (selector == @selector(addInternalRedirect::))
3867 return @"addInternalRedirect";
3868 else if (selector == @selector(addPipelinedHost:scheme:))
3869 return @"addPipelinedHost";
3870 else if (selector == @selector(addTrivialSource:))
3871 return @"addTrivialSource";
3872 else if (selector == @selector(close))
3874 else if (selector == @selector(du:))
3876 else if (selector == @selector(stringWithFormat:arguments:))
3878 else if (selector == @selector(getAllSources))
3879 return @"getAllSourcs";
3880 else if (selector == @selector(getKernelNumber:))
3881 return @"getKernelNumber";
3882 else if (selector == @selector(getKernelString:))
3883 return @"getKernelString";
3884 else if (selector == @selector(getInstalledPackages))
3885 return @"getInstalledPackages";
3886 else if (selector == @selector(getIORegistryEntry::))
3887 return @"getIORegistryEntry";
3888 else if (selector == @selector(getLocaleIdentifier))
3889 return @"getLocaleIdentifier";
3890 else if (selector == @selector(getPreferredLanguages))
3891 return @"getPreferredLanguages";
3892 else if (selector == @selector(getPackageById:))
3893 return @"getPackageById";
3894 else if (selector == @selector(getSessionValue:))
3895 return @"getSessionValue";
3896 else if (selector == @selector(installPackages:))
3897 return @"installPackages";
3898 else if (selector == @selector(localizedStringForKey:value:table:))
3900 else if (selector == @selector(popViewController:))
3901 return @"popViewController";
3902 else if (selector == @selector(refreshSources))
3903 return @"refreshSources";
3904 else if (selector == @selector(removeButton))
3905 return @"removeButton";
3906 else if (selector == @selector(setSessionValue::))
3907 return @"setSessionValue";
3908 else if (selector == @selector(substitutePackageNames:))
3909 return @"substitutePackageNames";
3910 else if (selector == @selector(scrollToBottom:))
3911 return @"scrollToBottom";
3912 else if (selector == @selector(setAllowsNavigationAction:))
3913 return @"setAllowsNavigationAction";
3914 else if (selector == @selector(setBadgeValue:))
3915 return @"setBadgeValue";
3916 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3917 return @"setButtonImage";
3918 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3919 return @"setButtonTitle";
3920 else if (selector == @selector(setHidesBackButton:))
3921 return @"setHidesBackButton";
3922 else if (selector == @selector(setHidesNavigationBar:))
3923 return @"setHidesNavigationBar";
3924 else if (selector == @selector(setNavigationBarStyle:))
3925 return @"setNavigationBarStyle";
3926 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
3927 return @"setNavigationBarTintColor";
3928 else if (selector == @selector(setPasteboardString:))
3929 return @"setPasteboardString";
3930 else if (selector == @selector(setPasteboardURL:))
3931 return @"setPasteboardURL";
3932 else if (selector == @selector(setToken:))
3934 else if (selector == @selector(setViewportWidth:))
3935 return @"setViewportWidth";
3936 else if (selector == @selector(statfs:))
3938 else if (selector == @selector(supports:))
3944 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3945 return [self webScriptNameForSelector:selector] == nil;
3948 - (BOOL) supports:(NSString *)feature {
3949 return [feature isEqualToString:@"window.open"];
3952 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
3953 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
3956 - (NSNumber *) getKernelNumber:(NSString *)name {
3957 const char *string([name UTF8String]);
3960 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3961 return (id) [NSNull null];
3963 if (size != sizeof(int))
3964 return (id) [NSNull null];
3967 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3968 return (id) [NSNull null];
3970 return [NSNumber numberWithInt:value];
3973 - (NSString *) getKernelString:(NSString *)name {
3974 const char *string([name UTF8String]);
3977 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3978 return (id) [NSNull null];
3980 char value[size + 1];
3981 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3982 return (id) [NSNull null];
3984 // XXX: just in case you request something ludicrous
3987 return [NSString stringWithCString:value];
3990 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
3991 NSObject *value(CYIOGetValue([path UTF8String], entry));
3994 if ([value isKindOfClass:[NSData class]])
3995 value = CYHex((NSData *) value);
4000 - (id) getSessionValue:(NSString *)key {
4001 @synchronized (SessionData_) {
4002 return [SessionData_ objectForKey:key];
4005 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4006 @synchronized (SessionData_) {
4007 if (value == (id) [WebUndefined undefined])
4008 [SessionData_ removeObjectForKey:key];
4010 [SessionData_ setObject:value forKey:key];
4013 - (void) addBridgedHost:(NSString *)host {
4014 @synchronized (HostConfig_) {
4015 [BridgedHosts_ addObject:host];
4018 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4019 @synchronized (HostConfig_) {
4020 if (scheme != (id) [WebUndefined undefined])
4021 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4023 [PipelinedHosts_ addObject:host];
4026 - (void) popViewController:(NSNumber *)value {
4027 if (value == (id) [WebUndefined undefined])
4028 value = [NSNumber numberWithBool:YES];
4029 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4032 - (void) addTrivialSource:(NSString *)href {
4033 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4036 - (void) refreshSources {
4037 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4040 - (NSArray *) getAllSources {
4041 return [[Database sharedInstance] sources];
4044 - (NSArray *) getInstalledPackages {
4045 Database *database([Database sharedInstance]);
4046 @synchronized (database) {
4047 NSArray *packages([database packages]);
4048 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4049 for (Package *package in packages)
4050 if (![package uninstalled])
4051 [installed addObject:package];
4055 - (Package *) getPackageById:(NSString *)id {
4056 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4060 return (Package *) [NSNull null];
4063 - (NSString *) getLocaleIdentifier {
4064 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4067 - (NSArray *) getPreferredLanguages {
4071 - (NSArray *) statfs:(NSString *)path {
4074 if (path == nil || statfs([path UTF8String], &stat) == -1)
4077 return [NSArray arrayWithObjects:
4078 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4079 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4080 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4084 - (NSNumber *) du:(NSString *)path {
4085 NSNumber *value(nil);
4088 _assert(pipe(fds) != -1);
4090 pid_t pid(ExecFork());
4092 _assert(dup2(fds[1], 1) != -1);
4093 _assert(close(fds[0]) != -1);
4094 _assert(close(fds[1]) != -1);
4095 /* XXX: this should probably not use du */
4096 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4101 _assert(close(fds[1]) != -1);
4103 if (FILE *du = fdopen(fds[0], "r")) {
4105 while (fgets(line, sizeof(line), du) != NULL) {
4106 size_t length(strlen(line));
4107 while (length != 0 && line[length - 1] == '\n')
4108 line[--length] = '\0';
4109 if (char *tab = strchr(line, '\t')) {
4111 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4116 } else _assert(close(fds[0]));
4120 if (waitpid(pid, &status, 0) == -1)
4123 else _assert(false);
4129 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4132 - (void) installPackages:(NSArray *)packages {
4133 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4136 - (NSString *) substitutePackageNames:(NSString *)message {
4137 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4138 for (size_t i(0), e([words count]); i != e; ++i) {
4139 NSString *word([words objectAtIndex:i]);
4140 if (Package *package = [[Database sharedInstance] packageWithName:word])
4141 [words replaceObjectAtIndex:i withObject:[package name]];
4144 return [words componentsJoinedByString:@" "];
4147 - (void) removeButton {
4148 [indirect_ removeButton];
4151 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4152 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4155 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4156 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4159 - (void) setBadgeValue:(id)value {
4160 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4163 - (void) setAllowsNavigationAction:(NSString *)value {
4164 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4167 - (void) setHidesBackButton:(NSString *)value {
4168 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4171 - (void) setHidesNavigationBar:(NSString *)value {
4172 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4175 - (void) setNavigationBarStyle:(NSString *)value {
4176 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4179 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4180 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4181 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4182 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4185 - (void) setPasteboardString:(NSString *)value {
4186 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4189 - (void) setPasteboardURL:(NSString *)value {
4190 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4193 - (void) _setToken:(NSString *)token {
4197 [Metadata_ removeObjectForKey:@"Token"];
4199 [Metadata_ setObject:Token_ forKey:@"Token"];
4204 - (void) setToken:(NSString *)token {
4205 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4208 - (void) scrollToBottom:(NSNumber *)animated {
4209 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4212 - (void) setViewportWidth:(float)width {
4213 [indirect_ setViewportWidthOnMainThread:width];
4216 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4217 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4218 unsigned count([arguments count]);
4220 for (unsigned i(0); i != count; ++i)
4221 values[i] = [arguments objectAtIndex:i];
4222 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4225 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4226 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4228 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4230 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4236 /* @ Loading... Indicator {{{ */
4237 @interface CYLoadingIndicator : UIView {
4238 _H<UIActivityIndicatorView> spinner_;
4240 _H<UIView> container_;
4243 @property (readonly, nonatomic) UILabel *label;
4244 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4248 @implementation CYLoadingIndicator
4250 - (id) initWithFrame:(CGRect)frame {
4251 if ((self = [super initWithFrame:frame]) != nil) {
4252 container_ = [[[UIView alloc] init] autorelease];
4253 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4255 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4256 [spinner_ startAnimating];
4257 [container_ addSubview:spinner_];
4259 label_ = [[[UILabel alloc] init] autorelease];
4260 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4261 [label_ setBackgroundColor:[UIColor clearColor]];
4262 [label_ setTextColor:[UIColor blackColor]];
4263 [label_ setShadowColor:[UIColor whiteColor]];
4264 [label_ setShadowOffset:CGSizeMake(0, 1)];
4265 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4266 [container_ addSubview:label_];
4268 CGSize viewsize = frame.size;
4269 CGSize spinnersize = [spinner_ bounds].size;
4270 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4271 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4273 CGRect containrect = {
4274 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4275 CGSizeMake(bothwidth, spinnersize.height)
4278 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4286 [container_ setFrame:containrect];
4287 [spinner_ setFrame:spinrect];
4288 [label_ setFrame:textrect];
4289 [self addSubview:container_];
4293 - (UILabel *) label {
4297 - (UIActivityIndicatorView *) activityIndicatorView {
4303 /* Emulated Loading Controller {{{ */
4304 @interface CYEmulatedLoadingController : CyteViewController {
4305 _transient Database *database_;
4306 _H<CYLoadingIndicator> indicator_;
4307 _H<UITabBar> tabbar_;
4308 _H<UINavigationBar> navbar_;
4313 @implementation CYEmulatedLoadingController
4315 - (id) initWithDatabase:(Database *)database {
4316 if ((self = [super init]) != nil) {
4317 database_ = database;
4322 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4324 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4325 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4326 [[self view] addSubview:table];
4328 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4329 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4330 [[self view] addSubview:indicator_];
4332 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4333 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4334 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4335 [[self view] addSubview:tabbar_];
4337 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4338 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4339 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4340 [[self view] addSubview:navbar_];
4343 - (void) releaseSubviews {
4352 /* Cydia Browser Controller {{{ */
4353 @implementation CydiaWebViewController
4355 - (NSURL *) navigationURL {
4356 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4359 + (void) initialize {
4360 Diversions_ = [NSMutableSet setWithCapacity:0];
4363 + (void) addDiversion:(Diversion *)diversion {
4364 [Diversions_ addObject:diversion];
4367 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4368 [super webView:view didClearWindowObject:window forFrame:frame];
4370 WebDataSource *source([frame dataSource]);
4371 NSURLResponse *response([source response]);
4372 NSURL *url([response URL]);
4373 NSString *scheme([[url scheme] lowercaseString]);
4375 bool bridged(false);
4377 @synchronized (HostConfig_) {
4378 if ([scheme isEqualToString:@"file"])
4380 else if ([scheme isEqualToString:@"https"])
4381 if ([BridgedHosts_ containsObject:[url host]])
4386 [window setValue:cydia_ forKey:@"cydia"];
4389 - (NSURL *) URLWithURL:(NSURL *)url {
4390 return [Diversion divertURL:url];
4393 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4394 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4396 if (System_ != NULL)
4397 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4398 if (Machine_ != NULL)
4399 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4401 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4406 - (void) setDelegate:(id)delegate {
4407 [super setDelegate:delegate];
4408 [cydia_ setDelegate:delegate];
4412 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4413 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4415 WebView *webview([[webview_ _documentView] webView]);
4417 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4420 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4422 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4423 if (Product_ != nil)
4424 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4426 [webview setApplicationNameForUserAgent:application];
4434 @interface NSObject (CydiaScript)
4435 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4438 @implementation NSObject (CydiaScript)
4440 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4446 @implementation NSArray (CydiaScript)
4448 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4449 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4450 for (size_t i(0), e([self count]); i != e; ++i)
4451 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4457 @implementation NSDictionary (CydiaScript)
4459 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4460 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4462 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4469 /* Confirmation Controller {{{ */
4470 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4471 if (!iterator.end())
4472 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4473 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4475 pkgCache::PkgIterator package(dep.TargetPkg());
4478 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4485 @protocol ConfirmationControllerDelegate
4486 - (void) cancelAndClear:(bool)clear;
4487 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4491 @interface ConfirmationController : CydiaWebViewController {
4492 _transient Database *database_;
4494 _H<UIAlertView> essential_;
4496 _H<NSDictionary> changes_;
4497 _H<NSMutableArray> issues_;
4498 _H<NSDictionary> sizes_;
4503 - (id) initWithDatabase:(Database *)database;
4507 @implementation ConfirmationController
4511 RestartSubstrate_ = true;
4512 [delegate_ confirmWithNavigationController:[self navigationController]];
4515 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4516 NSString *context([alert context]);
4518 if ([context isEqualToString:@"remove"]) {
4519 if (button == [alert cancelButtonIndex])
4520 [self dismissModalViewControllerAnimated:YES];
4521 else if (button == [alert firstOtherButtonIndex]) {
4525 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4526 } else if ([context isEqualToString:@"unable"]) {
4527 [self dismissModalViewControllerAnimated:YES];
4528 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4530 [super alertView:alert clickedButtonAtIndex:button];
4534 - (void) _doContinue {
4535 [self dismissModalViewControllerAnimated:YES];
4536 [delegate_ cancelAndClear:NO];
4539 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4540 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4544 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4545 [super webView:view didClearWindowObject:window forFrame:frame];
4547 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4548 (id) changes_, @"changes",
4549 (id) issues_, @"issues",
4550 (id) sizes_, @"sizes",
4552 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4555 - (id) initWithDatabase:(Database *)database {
4556 if ((self = [super init]) != nil) {
4557 database_ = database;
4559 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4560 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4561 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4562 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4563 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4567 pkgCacheFile &cache([database_ cache]);
4568 NSArray *packages([database_ packages]);
4569 pkgDepCache::Policy *policy([database_ policy]);
4571 issues_ = [NSMutableArray arrayWithCapacity:4];
4573 for (Package *package in packages) {
4574 pkgCache::PkgIterator iterator([package iterator]);
4575 NSString *name([package id]);
4577 if ([package broken]) {
4578 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4580 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4582 reasons, @"reasons",
4585 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4589 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4590 pkgCache::DepIterator start;
4591 pkgCache::DepIterator end;
4592 dep.GlobOr(start, end); // ++dep
4594 if (!cache->IsImportantDep(end))
4596 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4599 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4601 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4602 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4603 clauses, @"clauses",
4607 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4609 pkgCache::PkgIterator target(start.TargetPkg());
4610 if (target->ProvidesList != 0)
4611 reason = @"missing";
4613 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4615 reason = @"installed";
4616 installed = [NSString stringWithUTF8String:ver.VerStr()];
4617 } else if (!cache[target].CandidateVerIter(cache).end())
4618 reason = @"uninstalled";
4619 else if (target->ProvidesList == 0)
4620 reason = @"uninstallable";
4622 reason = @"virtual";
4625 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4626 [NSString stringWithUTF8String:start.CompType()], @"operator",
4627 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4630 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4631 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4632 version, @"version",
4634 installed, @"installed",
4637 // yes, seriously. (wtf?)
4645 pkgDepCache::StateCache &state(cache[iterator]);
4647 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4649 if (state.NewInstall())
4650 [installs addObject:name];
4651 // XXX: else if (state.Install())
4652 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4653 [reinstalls addObject:name];
4654 // XXX: move before previous if
4655 else if (state.Upgrade())
4656 [upgrades addObject:name];
4657 else if (state.Downgrade())
4658 [downgrades addObject:name];
4659 else if (!state.Delete())
4660 // XXX: _assert(state.Keep());
4662 else if (special_r(name))
4663 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4664 [NSNull null], @"package",
4665 [NSArray arrayWithObjects:
4666 [NSDictionary dictionaryWithObjectsAndKeys:
4667 @"Conflicts", @"relationship",
4668 [NSArray arrayWithObjects:
4669 [NSDictionary dictionaryWithObjectsAndKeys:
4671 [NSNull null], @"version",
4672 @"installed", @"reason",
4679 if ([package essential])
4681 [removes addObject:name];
4684 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4685 substrate_ |= DepSubstrate(iterator.CurrentVer());
4690 else if (Advanced_) {
4691 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4693 essential_ = [[[UIAlertView alloc]
4694 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4695 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4697 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4699 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4703 [essential_ setContext:@"remove"];
4705 essential_ = [[[UIAlertView alloc]
4706 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4707 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4709 cancelButtonTitle:UCLocalize("OKAY")
4710 otherButtonTitles:nil
4713 [essential_ setContext:@"unable"];
4716 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4717 installs, @"installs",
4718 reinstalls, @"reinstalls",
4719 upgrades, @"upgrades",
4720 downgrades, @"downgrades",
4721 removes, @"removes",
4724 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4725 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4726 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4729 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4733 - (UIBarButtonItem *) leftButton {
4734 return [[[UIBarButtonItem alloc]
4735 initWithTitle:UCLocalize("CANCEL")
4736 style:UIBarButtonItemStylePlain
4738 action:@selector(cancelButtonClicked)
4743 - (void) applyRightButton {
4744 if ([issues_ count] == 0 && ![self isLoading])
4745 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4746 initWithTitle:UCLocalize("CONFIRM")
4747 style:UIBarButtonItemStyleDone
4749 action:@selector(confirmButtonClicked)
4752 [[self navigationItem] setRightBarButtonItem:nil];
4756 - (void) cancelButtonClicked {
4757 [self dismissModalViewControllerAnimated:YES];
4758 [delegate_ cancelAndClear:YES];
4762 - (void) confirmButtonClicked {
4763 if (essential_ != nil)
4773 /* Progress Data {{{ */
4774 @interface CydiaProgressData : NSObject {
4775 _transient id delegate_;
4784 _H<NSMutableArray> events_;
4785 _H<NSString> title_;
4787 _H<NSString> status_;
4788 _H<NSString> finish_;
4793 @implementation CydiaProgressData
4795 + (NSArray *) _attributeKeys {
4796 return [NSArray arrayWithObjects:
4808 - (NSArray *) attributeKeys {
4809 return [[self class] _attributeKeys];
4812 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4813 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4817 if ((self = [super init]) != nil) {
4818 events_ = [NSMutableArray arrayWithCapacity:32];
4822 - (void) setDelegate:(id)delegate {
4823 delegate_ = delegate;
4826 - (void) setPercent:(float)value {
4830 - (NSNumber *) percent {
4831 return [NSNumber numberWithFloat:percent_];
4834 - (void) setCurrent:(float)value {
4838 - (NSNumber *) current {
4839 return [NSNumber numberWithFloat:current_];
4842 - (void) setTotal:(float)value {
4846 - (NSNumber *) total {
4847 return [NSNumber numberWithFloat:total_];
4850 - (void) setSpeed:(float)value {
4854 - (NSNumber *) speed {
4855 return [NSNumber numberWithFloat:speed_];
4858 - (NSArray *) events {
4862 - (void) removeAllEvents {
4863 [events_ removeAllObjects];
4866 - (void) addEvent:(CydiaProgressEvent *)event {
4867 [events_ addObject:event];
4870 - (void) setTitle:(NSString *)text {
4874 - (NSString *) title {
4878 - (void) setFinish:(NSString *)text {
4882 - (NSString *) finish {
4883 return (id) finish_ ?: [NSNull null];
4886 - (void) setRunning:(bool)running {
4890 - (NSNumber *) running {
4891 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4896 /* Progress Controller {{{ */
4897 @interface ProgressController : CydiaWebViewController <
4900 _transient Database *database_;
4901 _H<CydiaProgressData> progress_;
4905 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4907 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4909 - (void) setTitle:(NSString *)title;
4910 - (void) setCancellable:(bool)cancellable;
4914 @implementation ProgressController
4917 [database_ setProgressDelegate:nil];
4918 [progress_ setDelegate:nil];
4922 - (UIBarButtonItem *) leftButton {
4923 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
4924 initWithTitle:UCLocalize("CANCEL")
4925 style:UIBarButtonItemStylePlain
4927 action:@selector(cancel)
4928 ] autorelease] : nil;
4931 - (void) updateCancel {
4932 [super applyLeftButton];
4935 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4936 if ((self = [super init]) != nil) {
4937 database_ = database;
4938 delegate_ = delegate;
4940 [database_ setProgressDelegate:self];
4942 progress_ = [[[CydiaProgressData alloc] init] autorelease];
4943 [progress_ setDelegate:self];
4945 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
4947 [scroller_ setBackgroundColor:[UIColor blackColor]];
4949 [[self navigationItem] setHidesBackButton:YES];
4951 [self updateCancel];
4955 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4956 [super webView:view didClearWindowObject:window forFrame:frame];
4957 [window setValue:progress_ forKey:@"cydiaProgress"];
4960 - (void) updateProgress {
4961 [self dispatchEvent:@"CydiaProgressUpdate"];
4964 - (void) viewWillAppear:(BOOL)animated {
4965 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4966 [super viewWillAppear:animated];
4970 UpdateExternalStatus(0);
4977 [delegate_ terminateWithSuccess];
4978 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4979 [delegate_ suspendWithAnimation:YES];
4981 [delegate_ suspend];*/
4993 system("/usr/bin/sbreload");
4999 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5000 SBReboot(SBSSpringBoardServerPort());
5002 reboot2(RB_AUTOBOOT);
5009 - (void) setTitle:(NSString *)title {
5010 [progress_ setTitle:title];
5011 [self updateProgress];
5014 - (UIBarButtonItem *) rightButton {
5015 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5016 initWithTitle:UCLocalize("CLOSE")
5017 style:UIBarButtonItemStylePlain
5019 action:@selector(close)
5023 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5024 UpdateExternalStatus(1);
5026 [progress_ setRunning:true];
5027 [self setTitle:title];
5028 // implicit updateProgress
5030 SHA1SumValue notifyconf; {
5032 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5035 MMap mmap(file, MMap::ReadOnly);
5037 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5038 notifyconf = sha1.Result();
5042 SHA1SumValue springlist; {
5044 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5047 MMap mmap(file, MMap::ReadOnly);
5049 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5050 springlist = sha1.Result();
5054 if (invocation != nil) {
5055 [invocation yieldToSelector:@selector(invoke)];
5056 [self setTitle:@"COMPLETE"];
5061 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5064 MMap mmap(file, MMap::ReadOnly);
5066 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5067 if (!(notifyconf == sha1.Result()))
5074 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5077 MMap mmap(file, MMap::ReadOnly);
5079 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5080 if (!(springlist == sha1.Result()))
5086 if (RestartSubstrate_)
5090 RestartSubstrate_ = false;
5093 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5094 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5095 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5096 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5097 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5101 system("su -c /usr/bin/uicache mobile");
5104 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5106 [progress_ setRunning:false];
5107 [self updateProgress];
5109 [self applyRightButton];
5112 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5113 [progress_ addEvent:event];
5114 [self updateProgress];
5117 - (bool) isProgressCancelled {
5118 return cancel_ == 2;
5123 [self updateCancel];
5126 - (void) setCancellable:(bool)cancellable {
5127 unsigned cancel(cancel_);
5131 else if (cancel_ == 0)
5134 if (cancel != cancel_)
5135 [self updateCancel];
5138 - (void) setProgressCancellable:(NSNumber *)cancellable {
5139 [self setCancellable:[cancellable boolValue]];
5142 - (void) setProgressPercent:(NSNumber *)percent {
5143 [progress_ setPercent:[percent floatValue]];
5144 [self updateProgress];
5147 - (void) setProgressStatus:(NSDictionary *)status {
5148 if (status == nil) {
5149 [progress_ setCurrent:0];
5150 [progress_ setTotal:0];
5151 [progress_ setSpeed:0];
5153 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5155 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5156 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5157 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5160 [self updateProgress];
5166 /* Package Cell {{{ */
5167 @interface PackageCell : CYTableViewCell <
5168 CyteTableViewCellDelegate
5172 _H<NSString> description_;
5174 _H<NSString> source_;
5176 _H<Package> package_;
5177 _H<UIImage> placard_;
5181 - (PackageCell *) init;
5182 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5184 - (void) drawContentRect:(CGRect)rect;
5188 @implementation PackageCell
5190 - (PackageCell *) init {
5191 CGRect frame(CGRectMake(0, 0, 320, 74));
5192 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5193 UIView *content([self contentView]);
5194 CGRect bounds([content bounds]);
5196 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5197 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5198 [content addSubview:content_];
5200 [content_ setDelegate:self];
5201 [content_ setOpaque:YES];
5205 - (NSString *) accessibilityLabel {
5206 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5209 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5210 summarized_ = summary;
5222 Source *source = [package source];
5224 icon_ = [package icon];
5225 name_ = [package name];
5228 description_ = [package longDescription];
5229 if (description_ == nil)
5230 description_ = [package shortDescription];
5232 commercial_ = [package isCommercial];
5236 NSString *label = nil;
5237 bool trusted = false;
5239 if (source != nil) {
5240 label = [source label];
5241 trusted = [source trusted];
5242 } else if ([[package id] isEqualToString:@"firmware"])
5243 label = UCLocalize("APPLE");
5245 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5247 NSString *from(label);
5249 NSString *section = [package simpleSection];
5250 if (section != nil && ![section isEqualToString:label]) {
5251 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5252 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5255 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5257 if (NSString *purpose = [package primaryPurpose])
5258 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5263 if (NSString *mode = [package_ mode]) {
5264 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5265 color = RemovingColor_;
5266 //placard = @"removing";
5268 color = InstallingColor_;
5269 //placard = @"installing";
5272 // XXX: the removing/installing placards are not @2x
5275 color = [UIColor whiteColor];
5277 if ([package installed] != nil)
5278 placard = @"installed";
5283 [content_ setBackgroundColor:color];
5286 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5288 [self setNeedsDisplay];
5289 [content_ setNeedsDisplay];
5292 - (void) drawSummaryContentRect:(CGRect)rect {
5293 bool highlighted(highlighted_);
5294 float width([self bounds].size.width);
5298 rect.size = [(UIImage *) icon_ size];
5300 rect.size.width /= 4;
5301 rect.size.height /= 4;
5303 rect.origin.x = 14 - rect.size.width / 4;
5304 rect.origin.y = 14 - rect.size.height / 4;
5306 [icon_ drawInRect:rect];
5309 if (badge_ != nil) {
5311 rect.size = [(UIImage *) badge_ size];
5313 rect.size.width /= 4;
5314 rect.size.height /= 4;
5316 rect.origin.x = 20 - rect.size.width / 4;
5317 rect.origin.y = 20 - rect.size.height / 4;
5319 [badge_ drawInRect:rect];
5326 UISetColor(commercial_ ? Purple_ : Black_);
5327 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5329 if (placard_ != nil)
5330 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5333 - (void) drawNormalContentRect:(CGRect)rect {
5334 bool highlighted(highlighted_);
5335 float width([self bounds].size.width);
5339 rect.size = [(UIImage *) icon_ size];
5341 rect.size.width /= 2;
5342 rect.size.height /= 2;
5344 rect.origin.x = 25 - rect.size.width / 2;
5345 rect.origin.y = 25 - rect.size.height / 2;
5347 [icon_ drawInRect:rect];
5350 if (badge_ != nil) {
5352 rect.size = [(UIImage *) badge_ size];
5354 rect.size.width /= 2;
5355 rect.size.height /= 2;
5357 rect.origin.x = 36 - rect.size.width / 2;
5358 rect.origin.y = 36 - rect.size.height / 2;
5360 [badge_ drawInRect:rect];
5367 UISetColor(commercial_ ? Purple_ : Black_);
5368 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5369 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5372 UISetColor(commercial_ ? Purplish_ : Gray_);
5373 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5375 if (placard_ != nil)
5376 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5379 - (void) drawContentRect:(CGRect)rect {
5381 [self drawSummaryContentRect:rect];
5383 [self drawNormalContentRect:rect];
5388 /* Section Cell {{{ */
5389 @interface SectionCell : CYTableViewCell <
5390 CyteTableViewCellDelegate
5392 _H<NSString> basic_;
5393 _H<NSString> section_;
5395 _H<NSString> count_;
5397 _H<UISwitch> switch_;
5401 - (void) setSection:(Section *)section editing:(BOOL)editing;
5405 @implementation SectionCell
5407 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5408 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5409 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5410 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5411 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5413 UIView *content([self contentView]);
5414 CGRect bounds([content bounds]);
5416 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5417 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5418 [content addSubview:content_];
5419 [content_ setBackgroundColor:[UIColor whiteColor]];
5421 [content_ setDelegate:self];
5425 - (void) onSwitch:(id)sender {
5426 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5427 if (metadata == nil) {
5428 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5429 [Sections_ setObject:metadata forKey:basic_];
5432 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5436 - (void) setSection:(Section *)section editing:(BOOL)editing {
5437 if (editing != editing_) {
5439 [switch_ removeFromSuperview];
5441 [self addSubview:switch_];
5450 if (section == nil) {
5451 name_ = UCLocalize("ALL_PACKAGES");
5454 basic_ = [section name];
5455 section_ = [section localized];
5457 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5458 count_ = [NSString stringWithFormat:@"%d", [section count]];
5461 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5464 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5465 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5467 [content_ setNeedsDisplay];
5470 - (void) setFrame:(CGRect)frame {
5471 [super setFrame:frame];
5473 CGRect rect([switch_ frame]);
5474 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5477 - (NSString *) accessibilityLabel {
5481 - (void) drawContentRect:(CGRect)rect {
5482 bool highlighted(highlighted_ && !editing_);
5484 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5489 float width(rect.size.width);
5495 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5497 CGSize size = [count_ sizeWithFont:Font14_];
5501 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5507 /* File Table {{{ */
5508 @interface FileTable : CyteViewController <
5509 UITableViewDataSource,
5512 _transient Database *database_;
5513 _H<Package> package_;
5515 _H<NSMutableArray> files_;
5516 _H<UITableView> list_;
5519 - (id) initWithDatabase:(Database *)database;
5520 - (void) setPackage:(Package *)package;
5524 @implementation FileTable
5527 [(UITableView *) list_ setDataSource:nil];
5528 [list_ setDelegate:nil];
5532 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5533 return files_ == nil ? 0 : [files_ count];
5536 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5540 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5541 static NSString *reuseIdentifier = @"Cell";
5543 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5545 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5546 [cell setFont:[UIFont systemFontOfSize:16]];
5548 [cell setText:[files_ objectAtIndex:indexPath.row]];
5549 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5554 - (NSURL *) navigationURL {
5555 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5559 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5561 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5562 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5563 [list_ setRowHeight:24.0f];
5564 [(UITableView *) list_ setDataSource:self];
5565 [list_ setDelegate:self];
5566 [[self view] addSubview:list_];
5569 - (void) viewDidLoad {
5570 [super viewDidLoad];
5572 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5575 - (void) releaseSubviews {
5579 - (id) initWithDatabase:(Database *)database {
5580 if ((self = [super init]) != nil) {
5581 database_ = database;
5583 files_ = [NSMutableArray arrayWithCapacity:32];
5587 - (void) setPackage:(Package *)package {
5591 [files_ removeAllObjects];
5593 if (package != nil) {
5595 name_ = [package id];
5597 if (NSArray *files = [package files])
5598 [files_ addObjectsFromArray:files];
5600 if ([files_ count] != 0) {
5601 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5602 [files_ removeObjectAtIndex:0];
5603 [files_ sortUsingSelector:@selector(compareByPath:)];
5605 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5606 [stack addObject:@"/"];
5608 for (int i(0), e([files_ count]); i != e; ++i) {
5609 NSString *file = [files_ objectAtIndex:i];
5610 while (![file hasPrefix:[stack lastObject]])
5611 [stack removeLastObject];
5612 NSString *directory = [stack lastObject];
5613 [stack addObject:[file stringByAppendingString:@"/"]];
5614 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5615 ([stack count] - 2) * 3, "",
5616 [file substringFromIndex:[directory length]]
5625 - (void) reloadData {
5628 [self setPackage:[database_ packageWithName:name_]];
5633 /* Package Controller {{{ */
5634 @interface CYPackageController : CydiaWebViewController <
5635 UIActionSheetDelegate
5637 _transient Database *database_;
5638 _H<Package> package_;
5641 _H<NSMutableArray> buttons_;
5642 _H<UIBarButtonItem> button_;
5645 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5649 @implementation CYPackageController
5651 - (NSURL *) navigationURL {
5652 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5655 /* XXX: this is not safe at all... localization of /fail/ */
5656 - (void) _clickButtonWithName:(NSString *)name {
5657 if ([name isEqualToString:UCLocalize("CLEAR")])
5658 [delegate_ clearPackage:package_];
5659 else if ([name isEqualToString:UCLocalize("INSTALL")])
5660 [delegate_ installPackage:package_];
5661 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5662 [delegate_ installPackage:package_];
5663 else if ([name isEqualToString:UCLocalize("REMOVE")])
5664 [delegate_ removePackage:package_];
5665 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5666 [delegate_ installPackage:package_];
5667 else _assert(false);
5670 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5671 NSString *context([sheet context]);
5673 if ([context isEqualToString:@"modify"]) {
5674 if (button != [sheet cancelButtonIndex]) {
5675 NSString *buttonName = [buttons_ objectAtIndex:button];
5676 [self _clickButtonWithName:buttonName];
5679 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5683 - (bool) _allowJavaScriptPanel {
5688 - (void) _customButtonClicked {
5689 int count([buttons_ count]);
5694 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5696 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5697 [buttons addObjectsFromArray:buttons_];
5699 UIActionSheet *sheet = [[[UIActionSheet alloc]
5702 cancelButtonTitle:nil
5703 destructiveButtonTitle:nil
5704 otherButtonTitles:nil
5707 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5709 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5710 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5712 [sheet setContext:@"modify"];
5714 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5718 // We don't want to allow non-commercial packages to do custom things to the install button,
5719 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5720 - (void) customButtonClicked {
5722 [super customButtonClicked];
5724 [self _customButtonClicked];
5727 - (void) reloadButtonClicked {
5728 // Don't reload a commerical package by tapping the loading button,
5729 // but if it's not an Install button, we should forward it on.
5730 if (![package_ uninstalled])
5731 [self _customButtonClicked];
5734 - (void) applyLoadingTitle {
5735 // Don't show "Loading" as the title. Ever.
5738 - (UIBarButtonItem *) rightButton {
5743 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5744 if ((self = [super init]) != nil) {
5745 database_ = database;
5746 buttons_ = [NSMutableArray arrayWithCapacity:4];
5747 name_ = [NSString stringWithString:name];
5748 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5752 - (void) reloadData {
5755 package_ = [database_ packageWithName:name_];
5757 [buttons_ removeAllObjects];
5759 if (package_ != nil) {
5760 [(Package *) package_ parse];
5762 commercial_ = [package_ isCommercial];
5764 if ([package_ mode] != nil)
5765 [buttons_ addObject:UCLocalize("CLEAR")];
5766 if ([package_ source] == nil);
5767 else if ([package_ upgradableAndEssential:NO])
5768 [buttons_ addObject:UCLocalize("UPGRADE")];
5769 else if ([package_ uninstalled])
5770 [buttons_ addObject:UCLocalize("INSTALL")];
5772 [buttons_ addObject:UCLocalize("REINSTALL")];
5773 if (![package_ uninstalled])
5774 [buttons_ addObject:UCLocalize("REMOVE")];
5778 switch ([buttons_ count]) {
5779 case 0: title = nil; break;
5780 case 1: title = [buttons_ objectAtIndex:0]; break;
5781 default: title = UCLocalize("MODIFY"); break;
5784 button_ = [[[UIBarButtonItem alloc]
5786 style:UIBarButtonItemStylePlain
5788 action:@selector(customButtonClicked)
5792 - (bool) isLoading {
5793 return commercial_ ? [super isLoading] : false;
5799 /* Package List Controller {{{ */
5800 @interface PackageListController : CyteViewController <
5801 UITableViewDataSource,
5804 _transient Database *database_;
5806 _H<NSMutableArray> packages_;
5807 _H<NSMutableArray> sections_;
5808 _H<UITableView> list_;
5809 _H<NSMutableArray> index_;
5810 _H<NSMutableDictionary> indices_;
5811 _H<NSString> title_;
5814 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5815 - (void) setDelegate:(id)delegate;
5816 - (void) resetCursor;
5821 @implementation PackageListController
5824 [list_ setDataSource:nil];
5825 [list_ setDelegate:nil];
5829 - (bool) isSummarized {
5833 - (void) deselectWithAnimation:(BOOL)animated {
5834 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5837 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5838 CGRect base = [[self view] bounds];
5839 base.size.height -= bounds.size.height;
5840 base.origin = [list_ frame].origin;
5842 [UIView beginAnimations:nil context:NULL];
5843 [UIView setAnimationBeginsFromCurrentState:YES];
5844 [UIView setAnimationCurve:curve];
5845 [UIView setAnimationDuration:duration];
5846 [list_ setFrame:base];
5847 [UIView commitAnimations];
5850 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5851 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5854 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5855 [self resizeForKeyboardBounds:bounds duration:0];
5858 - (void) keyboardWillShow:(NSNotification *)notification {
5861 NSTimeInterval duration;
5862 UIViewAnimationCurve curve;
5863 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5864 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5865 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5866 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5868 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);
5869 UIViewController *base = self;
5870 while ([base parentViewController] != nil)
5871 base = [base parentViewController];
5872 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5873 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5875 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5878 - (void) keyboardWillHide:(NSNotification *)notification {
5879 NSTimeInterval duration;
5880 UIViewAnimationCurve curve;
5881 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5882 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5884 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5887 - (void) viewWillAppear:(BOOL)animated {
5888 [super viewWillAppear:animated];
5890 [self resizeForKeyboardBounds:CGRectZero];
5891 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5892 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5895 - (void) viewWillDisappear:(BOOL)animated {
5896 [super viewWillDisappear:animated];
5898 [self resizeForKeyboardBounds:CGRectZero];
5899 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5900 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5903 - (void) viewDidAppear:(BOOL)animated {
5904 [super viewDidAppear:animated];
5905 [self deselectWithAnimation:animated];
5908 - (void) didSelectPackage:(Package *)package {
5909 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5910 [view setDelegate:delegate_];
5911 [[self navigationController] pushViewController:view animated:YES];
5914 #if TryIndexedCollation
5915 + (BOOL) hasIndexedCollation {
5916 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5920 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5921 NSInteger count([sections_ count]);
5922 return count == 0 ? 1 : count;
5925 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5926 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5928 return [[sections_ objectAtIndex:section] name];
5931 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5932 if ([sections_ count] == 0)
5934 return [[sections_ objectAtIndex:section] count];
5937 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5938 @synchronized (database_) {
5939 if ([database_ era] != era_)
5942 Section *section([sections_ objectAtIndex:[path section]]);
5943 NSInteger row([path row]);
5944 Package *package([packages_ objectAtIndex:([section row] + row)]);
5945 return [[package retain] autorelease];
5948 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5949 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5951 cell = [[[PackageCell alloc] init] autorelease];
5952 [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
5956 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5957 Package *package([self packageAtIndexPath:path]);
5958 package = [database_ packageWithName:[package id]];
5959 [self didSelectPackage:package];
5962 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5963 if ([self isSummarized])
5969 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5970 #if TryIndexedCollation
5971 if ([[self class] hasIndexedCollation]) {
5972 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5979 - (void) updateHeight {
5980 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
5983 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5984 if ((self = [super init]) != nil) {
5985 database_ = database;
5986 title_ = [title copy];
5987 [[self navigationItem] setTitle:title_];
5989 #if TryIndexedCollation
5990 if ([[self class] hasIndexedCollation])
5991 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
5994 index_ = [NSMutableArray arrayWithCapacity:32];
5996 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
5998 packages_ = [NSMutableArray arrayWithCapacity:16];
5999 sections_ = [NSMutableArray arrayWithCapacity:16];
6001 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6002 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6003 [[self view] addSubview:list_];
6005 // XXX: is 20 the most optimal number here?
6006 [list_ setSectionIndexMinimumDisplayRowCount:20];
6008 [(UITableView *) list_ setDataSource:self];
6009 [list_ setDelegate:self];
6011 [self updateHeight];
6015 - (void) setDelegate:(id)delegate {
6016 delegate_ = delegate;
6019 - (bool) hasPackage:(Package *)package {
6023 - (bool) shouldYield {
6027 - (void) _reloadPackages:(NSArray *)packages {
6028 [packages_ removeAllObjects];
6029 [sections_ removeAllObjects];
6031 _profile(PackageTable$reloadData$Filter)
6032 for (Package *package in packages)
6033 if ([self hasPackage:package])
6034 [packages_ addObject:package];
6038 - (void) _reloadData {
6039 era_ = [database_ era];
6040 NSArray *packages = [database_ packages];
6042 if ([self shouldYield]) {
6043 UIProgressHUD *hud([delegate_ addProgressHUD]);
6044 [hud setText:UCLocalize("LOADING")];
6045 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
6046 [delegate_ removeProgressHUD:hud];
6048 [self _reloadPackages:packages];
6051 [indices_ removeAllObjects];
6053 Section *section = nil;
6055 #if TryIndexedCollation
6056 if ([[self class] hasIndexedCollation]) {
6057 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6058 NSArray *titles = [collation sectionIndexTitles];
6061 _profile(PackageTable$reloadData$Section)
6062 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6066 _profile(PackageTable$reloadData$Section$Package)
6067 package = [packages_ objectAtIndex:offset];
6068 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6071 while (secidx < index) {
6074 _profile(PackageTable$reloadData$Section$Allocate)
6075 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6078 _profile(PackageTable$reloadData$Section$Add)
6079 [sections_ addObject:section];
6083 [section addToCount];
6089 [index_ removeAllObjects];
6091 bool summary([self isSummarized]);
6093 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6094 [sections_ addObject:section];
6097 _profile(PackageTable$reloadData$Section)
6098 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6102 _profile(PackageTable$reloadData$Section$Package)
6103 package = [packages_ objectAtIndex:offset];
6104 index = [package index];
6107 if (!summary && (section == nil || [section index] != index)) {
6108 _profile(PackageTable$reloadData$Section$Allocate)
6109 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6112 [index_ addObject:[section name]];
6113 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6115 _profile(PackageTable$reloadData$Section$Add)
6116 [sections_ addObject:section];
6120 [section addToCount];
6125 [self updateHeight];
6127 _profile(PackageTable$reloadData$List)
6128 [(UITableView *) list_ setDataSource:self];
6133 - (void) reloadData {
6135 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6138 - (void) resetCursor {
6139 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6142 - (void) clearData {
6143 [self updateHeight];
6145 [list_ setDataSource:nil];
6153 /* Filtered Package List Controller {{{ */
6154 @interface FilteredPackageListController : PackageListController {
6157 _H<NSObject> object_;
6160 - (void) setObject:(id)object;
6161 - (void) setObject:(id)object forFilter:(SEL)filter;
6164 - (void) setFilter:(SEL)filter;
6166 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6170 @implementation FilteredPackageListController
6176 - (void) setFilter:(SEL)filter {
6179 /* XXX: this is an unsafe optimization of doomy hell */
6180 Method method(class_getInstanceMethod([Package class], filter));
6181 _assert(method != NULL);
6182 imp_ = method_getImplementation(method);
6183 _assert(imp_ != NULL);
6186 - (void) setObject:(id)object {
6190 - (void) setObject:(id)object forFilter:(SEL)filter {
6191 [self setFilter:filter];
6192 [self setObject:object];
6195 - (bool) hasPackage:(Package *)package {
6196 _profile(FilteredPackageTable$hasPackage)
6197 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6201 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6202 if ((self = [super initWithDatabase:database title:title]) != nil) {
6203 [self setFilter:filter];
6204 [self setObject:object];
6211 /* Home Controller {{{ */
6212 @interface HomeController : CydiaWebViewController {
6217 @implementation HomeController
6220 if ((self = [super init]) != nil) {
6221 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6226 - (NSURL *) navigationURL {
6227 return [NSURL URLWithString:@"cydia://home"];
6230 - (void) aboutButtonClicked {
6231 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6233 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6234 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6235 [alert setCancelButtonIndex:0];
6238 @"Copyright \u00a9 2008-2011\n"
6241 "Jay Freeman (saurik)\n"
6242 "saurik@saurik.com\n"
6243 "http://www.saurik.com/"
6249 - (UIBarButtonItem *) leftButton {
6250 return [[[UIBarButtonItem alloc]
6251 initWithTitle:UCLocalize("ABOUT")
6252 style:UIBarButtonItemStylePlain
6254 action:@selector(aboutButtonClicked)
6258 - (void) unloadData {
6265 /* Manage Controller {{{ */
6266 @interface ManageController : CydiaWebViewController {
6269 - (void) queueStatusDidChange;
6273 @implementation ManageController
6276 if ((self = [super init]) != nil) {
6277 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6281 - (NSURL *) navigationURL {
6282 return [NSURL URLWithString:@"cydia://manage"];
6285 - (UIBarButtonItem *) leftButton {
6286 return [[[UIBarButtonItem alloc]
6287 initWithTitle:UCLocalize("SETTINGS")
6288 style:UIBarButtonItemStylePlain
6290 action:@selector(settingsButtonClicked)
6294 - (void) settingsButtonClicked {
6295 [delegate_ showSettings];
6298 - (void) queueButtonClicked {
6302 - (UIBarButtonItem *) customButton {
6303 return Queuing_ ? [[[UIBarButtonItem alloc]
6304 initWithTitle:UCLocalize("QUEUE")
6305 style:UIBarButtonItemStyleDone
6307 action:@selector(queueButtonClicked)
6308 ] autorelease] : [super customButton];
6311 - (void) queueStatusDidChange {
6312 [self applyRightButton];
6315 - (bool) isLoading {
6316 return !Queuing_ && [super isLoading];
6322 /* Refresh Bar {{{ */
6323 @interface RefreshBar : UINavigationBar {
6324 _H<UIProgressIndicator> indicator_;
6325 _H<UITextLabel> prompt_;
6326 _H<UIProgressBar> progress_;
6327 _H<UINavigationButton> cancel_;
6332 @implementation RefreshBar
6334 - (void) positionViews {
6335 CGRect frame = [cancel_ frame];
6336 frame.size = [cancel_ sizeThatFits:frame.size];
6337 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6338 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6339 [cancel_ setFrame:frame];
6341 CGSize prgsize = {75, 100};
6343 [self frame].size.width - prgsize.width - 10,
6344 ([self frame].size.height - prgsize.height) / 2
6346 [progress_ setFrame:prgrect];
6348 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6349 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6350 CGRect indrect = {{indoffset, indoffset}, indsize};
6351 [indicator_ setFrame:indrect];
6353 CGSize prmsize = {215, indsize.height + 4};
6355 indoffset * 2 + indsize.width,
6356 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6358 [prompt_ setFrame:prmrect];
6361 - (void) setFrame:(CGRect)frame {
6362 [super setFrame:frame];
6363 [self positionViews];
6366 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6367 if ((self = [super initWithFrame:frame]) != nil) {
6368 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6370 [self setBarStyle:UIBarStyleBlack];
6372 UIBarStyle barstyle([self _barStyle:NO]);
6373 bool ugly(barstyle == UIBarStyleDefault);
6375 UIProgressIndicatorStyle style = ugly ?
6376 UIProgressIndicatorStyleMediumBrown :
6377 UIProgressIndicatorStyleMediumWhite;
6379 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6380 [(UIProgressIndicator *) indicator_ setStyle:style];
6381 [indicator_ startAnimation];
6382 [self addSubview:indicator_];
6384 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6385 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6386 [prompt_ setBackgroundColor:[UIColor clearColor]];
6387 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6388 [self addSubview:prompt_];
6390 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6391 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6392 [(UIProgressBar *) progress_ setStyle:0];
6393 [self addSubview:progress_];
6395 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6396 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6397 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6398 [cancel_ setBarStyle:barstyle];
6400 [self positionViews];
6404 - (void) setCancellable:(bool)cancellable {
6406 [self addSubview:cancel_];
6408 [cancel_ removeFromSuperview];
6412 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6413 [progress_ setProgress:0];
6417 [self setCancellable:NO];
6420 - (void) setPrompt:(NSString *)prompt {
6421 [prompt_ setText:prompt];
6424 - (void) setProgress:(float)progress {
6425 [progress_ setProgress:progress];
6431 /* Cydia Navigation Controller Interface {{{ */
6432 @interface UINavigationController (Cydia)
6434 - (NSArray *) navigationURLCollection;
6435 - (void) unloadData;
6440 /* Cydia Tab Bar Controller {{{ */
6441 @interface CYTabBarController : UITabBarController <
6442 UITabBarControllerDelegate,
6445 _transient Database *database_;
6446 _H<RefreshBar> refreshbar_;
6450 // XXX: ok, "updatedelegate_"?...
6451 _transient NSObject<CydiaDelegate> *updatedelegate_;
6453 _H<UIViewController> remembered_;
6454 _transient UIViewController *transient_;
6457 - (NSArray *) navigationURLCollection;
6458 - (void) dropBar:(BOOL)animated;
6459 - (void) beginUpdate;
6460 - (void) raiseBar:(BOOL)animated;
6462 - (void) unloadData;
6466 @implementation CYTabBarController
6468 - (void) setUnselectedViewController:(UIViewController *)transient {
6469 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6470 if (transient != nil) {
6471 if (transient_ == nil)
6472 remembered_ = [controllers objectAtIndex:0];
6473 transient_ = transient;
6474 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6475 [controllers replaceObjectAtIndex:0 withObject:transient_];
6476 [self setSelectedIndex:0];
6477 [self setViewControllers:controllers];
6478 [self concealTabBarSelection];
6479 } else if (remembered_ != nil) {
6480 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6481 transient_ = transient;
6482 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6484 [self setViewControllers:controllers];
6485 [self revealTabBarSelection];
6489 - (UIViewController *) unselectedViewController {
6493 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6494 if ([self unselectedViewController])
6495 [self setUnselectedViewController:nil];
6498 - (NSArray *) navigationURLCollection {
6499 NSMutableArray *items([NSMutableArray array]);
6501 // XXX: Should this deal with transient view controllers?
6502 for (id navigation in [self viewControllers]) {
6503 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6505 [items addObject:stack];
6511 - (void) unloadData {
6512 UIViewController *selected([self selectedViewController]);
6513 for (UINavigationController *controller in [self viewControllers])
6514 [controller unloadData];
6516 [selected reloadData];
6518 if (UIViewController *unselected = [self unselectedViewController])
6519 [unselected reloadData];
6525 [refreshbar_ setDelegate:nil];
6526 [[NSNotificationCenter defaultCenter] removeObserver:self];
6531 - (id) initWithDatabase:(Database *)database {
6532 if ((self = [super init]) != nil) {
6533 database_ = database;
6534 [self setDelegate:self];
6536 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6537 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6539 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6543 - (void) setUpdate:(NSDate *)date {
6547 - (void) beginUpdate {
6548 [(RefreshBar *) refreshbar_ start];
6551 [updatedelegate_ retainNetworkActivityIndicator];
6555 detachNewThreadSelector:@selector(performUpdate)
6561 - (void) performUpdate {
6562 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6565 status.setDelegate(self);
6566 [database_ updateWithStatus:status];
6569 performSelectorOnMainThread:@selector(completeUpdate)
6577 - (void) stopUpdateWithSelector:(SEL)selector {
6579 [updatedelegate_ releaseNetworkActivityIndicator];
6581 [self raiseBar:YES];
6584 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6587 - (void) completeUpdate {
6590 [self stopUpdateWithSelector:@selector(reloadData)];
6593 - (void) cancelUpdate {
6594 [self stopUpdateWithSelector:@selector(updateData)];
6597 - (void) cancelPressed {
6598 [self cancelUpdate];
6605 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6606 [refreshbar_ setPrompt:[event compoundMessage]];
6609 - (bool) isProgressCancelled {
6613 - (void) setProgressCancellable:(NSNumber *)cancellable {
6614 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6617 - (void) setProgressPercent:(NSNumber *)percent {
6618 [refreshbar_ setProgress:[percent floatValue]];
6621 - (void) setProgressStatus:(NSDictionary *)status {
6623 [self setProgressPercent:[status objectForKey:@"Percent"]];
6626 - (void) setUpdateDelegate:(id)delegate {
6627 updatedelegate_ = delegate;
6630 - (CGFloat) statusBarHeight {
6631 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6632 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6634 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6638 - (UIView *) transitionView {
6639 if ([self respondsToSelector:@selector(_transitionView)])
6640 return [self _transitionView];
6642 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6645 - (void) dropBar:(BOOL)animated {
6650 UIView *transition([self transitionView]);
6651 [[self view] addSubview:refreshbar_];
6653 CGRect barframe([refreshbar_ frame]);
6655 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6656 barframe.origin.y = [self statusBarHeight];
6658 barframe.origin.y = 0;
6660 [refreshbar_ setFrame:barframe];
6663 [UIView beginAnimations:nil context:NULL];
6665 CGRect viewframe = [transition frame];
6666 viewframe.origin.y += barframe.size.height;
6667 viewframe.size.height -= barframe.size.height;
6668 [transition setFrame:viewframe];
6671 [UIView commitAnimations];
6673 // Ensure bar has the proper width for our view, it might have changed
6674 barframe.size.width = viewframe.size.width;
6675 [refreshbar_ setFrame:barframe];
6678 - (void) raiseBar:(BOOL)animated {
6683 UIView *transition([self transitionView]);
6684 [refreshbar_ removeFromSuperview];
6686 CGRect barframe([refreshbar_ frame]);
6689 [UIView beginAnimations:nil context:NULL];
6691 CGRect viewframe = [transition frame];
6692 viewframe.origin.y -= barframe.size.height;
6693 viewframe.size.height += barframe.size.height;
6694 [transition setFrame:viewframe];
6697 [UIView commitAnimations];
6700 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6701 bool dropped(dropped_);
6706 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6712 - (void) statusBarFrameChanged:(NSNotification *)notification {
6722 /* Cydia Navigation Controller Implementation {{{ */
6723 @implementation UINavigationController (Cydia)
6725 - (NSArray *) navigationURLCollection {
6726 NSMutableArray *stack([NSMutableArray array]);
6728 for (CyteViewController *controller in [self viewControllers]) {
6729 NSString *url = [[controller navigationURL] absoluteString];
6731 [stack addObject:url];
6737 - (void) reloadData {
6740 if (UIViewController *visible = [self visibleViewController])
6741 [visible reloadData];
6744 - (void) unloadData {
6745 for (CyteViewController *page in [self viewControllers])
6754 /* Cydia:// Protocol {{{ */
6755 @interface CydiaURLProtocol : NSURLProtocol {
6760 @implementation CydiaURLProtocol
6762 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6763 NSURL *url([request URL]);
6767 NSString *scheme([[url scheme] lowercaseString]);
6768 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6770 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6776 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6780 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6781 id<NSURLProtocolClient> client([self client]);
6783 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6785 NSData *data(UIImagePNGRepresentation(icon));
6787 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6788 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6789 [client URLProtocol:self didLoadData:data];
6790 [client URLProtocolDidFinishLoading:self];
6794 - (void) startLoading {
6795 id<NSURLProtocolClient> client([self client]);
6796 NSURLRequest *request([self request]);
6798 NSURL *url([request URL]);
6799 NSString *href([url absoluteString]);
6800 NSString *scheme([[url scheme] lowercaseString]);
6804 if ([scheme isEqualToString:@"cydia"])
6805 path = [href substringFromIndex:8];
6806 else if ([scheme isEqualToString:@"about"])
6807 path = [href substringFromIndex:12];
6808 else _assert(false);
6810 NSRange slash([path rangeOfString:@"/"]);
6813 if (slash.location == NSNotFound) {
6817 command = [path substringToIndex:slash.location];
6818 path = [path substringFromIndex:(slash.location + 1)];
6821 Database *database([Database sharedInstance]);
6823 if ([command isEqualToString:@"package-icon"]) {
6826 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6827 Package *package([database packageWithName:path]);
6831 UIImage *icon([package icon]);
6832 [self _returnPNGWithImage:icon forRequest:request];
6833 } else if ([command isEqualToString:@"source-icon"]) {
6836 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6837 NSString *source(Simplify(path));
6838 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6840 icon = [UIImage applicationImageNamed:@"unknown.png"];
6841 [self _returnPNGWithImage:icon forRequest:request];
6842 } else if ([command isEqualToString:@"uikit-image"]) {
6845 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6846 UIImage *icon(_UIImageWithName(path));
6847 [self _returnPNGWithImage:icon forRequest:request];
6848 } else if ([command isEqualToString:@"section-icon"]) {
6851 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6852 NSString *section(Simplify(path));
6853 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6855 icon = [UIImage applicationImageNamed:@"unknown.png"];
6856 [self _returnPNGWithImage:icon forRequest:request];
6858 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6862 - (void) stopLoading {
6868 /* Section Controller {{{ */
6869 @interface SectionController : FilteredPackageListController {
6870 _H<NSString> section_;
6873 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6877 @implementation SectionController
6879 - (NSURL *) navigationURL {
6880 NSString *name = section_;
6884 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6887 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6890 title = UCLocalize("ALL_PACKAGES");
6891 else if (![name isEqual:@""])
6892 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6894 title = UCLocalize("NO_SECTION");
6896 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6903 /* Sections Controller {{{ */
6904 @interface SectionsController : CyteViewController <
6905 UITableViewDataSource,
6908 _transient Database *database_;
6909 _H<NSMutableArray> sections_;
6910 _H<NSMutableArray> filtered_;
6911 _H<UITableView> list_;
6914 - (id) initWithDatabase:(Database *)database;
6915 - (void) editButtonClicked;
6919 @implementation SectionsController
6921 - (NSURL *) navigationURL {
6922 return [NSURL URLWithString:@"cydia://sections"];
6925 - (void) updateNavigationItem {
6926 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6927 if ([sections_ count] == 0) {
6928 [[self navigationItem] setRightBarButtonItem:nil];
6930 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6931 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6933 action:@selector(editButtonClicked)
6934 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6938 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6939 [super setEditing:editing animated:animated];
6944 [delegate_ updateData];
6946 [self updateNavigationItem];
6949 - (void) viewDidAppear:(BOOL)animated {
6950 [super viewDidAppear:animated];
6951 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6954 - (void) viewWillDisappear:(BOOL)animated {
6955 [super viewWillDisappear:animated];
6956 if ([self isEditing]) [self setEditing:NO];
6959 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6960 Section *section = nil;
6961 int index = [indexPath row];
6962 if (![self isEditing]) {
6965 section = [filtered_ objectAtIndex:index];
6967 section = [sections_ objectAtIndex:index];
6972 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6973 if ([self isEditing])
6974 return [sections_ count];
6976 return [filtered_ count] + 1;
6979 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6983 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6984 static NSString *reuseIdentifier = @"SectionCell";
6986 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6988 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6990 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6995 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6996 if ([self isEditing])
6999 Section *section = [self sectionAtIndexPath:indexPath];
7001 SectionController *controller = [[[SectionController alloc]
7002 initWithDatabase:database_
7003 section:[section name]
7005 [controller setDelegate:delegate_];
7007 [[self navigationController] pushViewController:controller animated:YES];
7011 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7013 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7014 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7015 [list_ setRowHeight:45.0f];
7016 [(UITableView *) list_ setDataSource:self];
7017 [list_ setDelegate:self];
7018 [[self view] addSubview:list_];
7021 - (void) viewDidLoad {
7022 [super viewDidLoad];
7024 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7027 - (void) releaseSubviews {
7031 - (id) initWithDatabase:(Database *)database {
7032 if ((self = [super init]) != nil) {
7033 database_ = database;
7035 sections_ = [NSMutableArray arrayWithCapacity:16];
7036 filtered_ = [NSMutableArray arrayWithCapacity:16];
7040 - (void) reloadData {
7043 NSArray *packages = [database_ packages];
7045 [sections_ removeAllObjects];
7046 [filtered_ removeAllObjects];
7048 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7051 for (Package *package in packages) {
7052 NSString *name([package section]);
7053 NSString *key(name == nil ? @"" : name);
7057 _profile(SectionsView$reloadData$Section)
7058 section = [sections objectForKey:key];
7059 if (section == nil) {
7060 _profile(SectionsView$reloadData$Section$Allocate)
7061 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7062 [sections setObject:section forKey:key];
7067 [section addToCount];
7069 _profile(SectionsView$reloadData$Filter)
7070 if (![package valid] || ![package visible])
7078 [sections_ addObjectsFromArray:[sections allValues]];
7080 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7082 for (Section *section in (id) sections_) {
7083 size_t count([section row]);
7087 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7088 [section setCount:count];
7089 [filtered_ addObject:section];
7092 [self updateNavigationItem];
7097 - (void) editButtonClicked {
7098 [self setEditing:![self isEditing] animated:YES];
7104 /* Changes Controller {{{ */
7105 @interface ChangesController : CyteViewController <
7106 UITableViewDataSource,
7109 _transient Database *database_;
7111 CFMutableArrayRef packages_;
7112 _H<NSMutableArray> sections_;
7113 _H<UITableView> list_;
7117 - (id) initWithDatabase:(Database *)database;
7121 @implementation ChangesController
7124 CFRelease(packages_);
7128 - (NSURL *) navigationURL {
7129 return [NSURL URLWithString:@"cydia://changes"];
7132 - (void) viewDidAppear:(BOOL)animated {
7133 [super viewDidAppear:animated];
7134 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7137 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7138 NSInteger count([sections_ count]);
7139 return count == 0 ? 1 : count;
7142 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7143 if ([sections_ count] == 0)
7145 return [[sections_ objectAtIndex:section] name];
7148 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7149 if ([sections_ count] == 0)
7151 return [[sections_ objectAtIndex:section] count];
7154 - (Package *) packageAtIndex:(NSUInteger)index {
7155 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7158 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7159 @synchronized (database_) {
7160 if ([database_ era] != era_)
7163 NSUInteger sectionIndex([path section]);
7164 if (sectionIndex >= [sections_ count])
7166 Section *section([sections_ objectAtIndex:sectionIndex]);
7167 NSInteger row([path row]);
7168 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7171 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7172 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7174 cell = [[[PackageCell alloc] init] autorelease];
7175 [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
7179 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7180 Package *package([self packageAtIndexPath:path]);
7181 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7182 [view setDelegate:delegate_];
7183 [[self navigationController] pushViewController:view animated:YES];
7187 - (void) refreshButtonClicked {
7188 [delegate_ beginUpdate];
7189 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7192 - (void) upgradeButtonClicked {
7193 [delegate_ distUpgrade];
7197 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7199 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7200 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7201 [list_ setRowHeight:73];
7202 [(UITableView *) list_ setDataSource:self];
7203 [list_ setDelegate:self];
7204 [[self view] addSubview:list_];
7207 - (void) viewDidLoad {
7208 [super viewDidLoad];
7210 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7213 - (void) releaseSubviews {
7217 - (id) initWithDatabase:(Database *)database {
7218 if ((self = [super init]) != nil) {
7219 database_ = database;
7221 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7222 sections_ = [NSMutableArray arrayWithCapacity:16];
7226 // this mostly works because reloadData (below) is @synchronized (database_)
7227 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7228 - (void) _reloadPackages:(NSArray *)packages {
7229 CFRelease(packages_);
7230 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7233 _profile(ChangesController$_reloadPackages$Filter)
7234 for (Package *package in packages)
7235 if ([package upgradableAndEssential:YES] || [package visible])
7236 CFArrayAppendValue(packages_, package);
7239 _profile(ChangesController$_reloadPackages$radixSort)
7240 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7245 - (void) _reloadData {
7246 @synchronized (database_) {
7247 era_ = [database_ era];
7248 NSArray *packages = [database_ packages];
7251 UIProgressHUD *hud([delegate_ addProgressHUD]);
7252 [hud setText:UCLocalize("LOADING")];
7253 //NSLog(@"HUD:%@::%@", delegate_, hud);
7254 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7255 [delegate_ removeProgressHUD:hud];
7257 [self _reloadPackages:packages];
7260 [sections_ removeAllObjects];
7262 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7263 Section *ignored = nil;
7264 Section *section = nil;
7268 bool unseens = false;
7270 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7272 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7273 Package *package = [self packageAtIndex:offset];
7275 BOOL uae = [package upgradableAndEssential:YES];
7279 time_t seen([package seen]);
7281 if (section == nil || last != seen) {
7285 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7288 _profile(ChangesController$reloadData$Allocate)
7289 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7290 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7291 [sections_ addObject:section];
7295 [section addToCount];
7296 } else if ([package ignored]) {
7297 if (ignored == nil) {
7298 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7300 [ignored addToCount];
7303 [upgradable addToCount];
7308 CFRelease(formatter);
7311 Section *last = [sections_ lastObject];
7312 size_t count = [last count];
7313 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7314 [sections_ removeLastObject];
7317 if ([ignored count] != 0)
7318 [sections_ insertObject:ignored atIndex:0];
7320 [sections_ insertObject:upgradable atIndex:0];
7325 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7326 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7327 style:UIBarButtonItemStylePlain
7329 action:@selector(upgradeButtonClicked)
7332 if (![delegate_ updating])
7333 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7334 initWithTitle:UCLocalize("REFRESH")
7335 style:UIBarButtonItemStylePlain
7337 action:@selector(refreshButtonClicked)
7343 - (void) reloadData {
7345 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7350 /* Search Controller {{{ */
7351 @interface SearchController : FilteredPackageListController <
7354 _H<UISearchBar> search_;
7358 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7359 - (void) reloadData;
7363 @implementation SearchController
7366 [search_ setDelegate:nil];
7370 - (NSURL *) navigationURL {
7371 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7372 return [NSURL URLWithString:@"cydia://search"];
7374 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7377 - (void) useSearch {
7378 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7383 - (void) viewWillAppear:(BOOL)animated {
7384 [super viewWillAppear:animated];
7386 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7390 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7391 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7396 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7397 [search_ resignFirstResponder];
7401 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7402 [search_ setText:@""];
7403 [self searchBarButtonClicked:searchBar];
7406 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7407 [self searchBarButtonClicked:searchBar];
7410 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7411 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7415 - (bool) shouldYield {
7416 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7419 - (bool) isSummarized {
7420 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7423 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7424 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:query])) {
7425 search_ = [[[UISearchBar alloc] init] autorelease];
7426 [search_ setDelegate:self];
7429 [search_ setText:query];
7433 - (void) viewDidAppear:(BOOL)animated {
7434 [super viewDidAppear:animated];
7436 if (!searchloaded_) {
7437 searchloaded_ = YES;
7438 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7439 [search_ layoutSubviews];
7440 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7442 UITextField *textField;
7443 if ([search_ respondsToSelector:@selector(searchField)])
7444 textField = [search_ searchField];
7446 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7448 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7449 [textField setEnablesReturnKeyAutomatically:NO];
7450 [[self navigationItem] setTitleView:textField];
7454 - (void) reloadData {
7455 [self setObject:[search_ text]];
7461 - (void) didSelectPackage:(Package *)package {
7462 [search_ resignFirstResponder];
7463 [super didSelectPackage:package];
7468 /* Package Settings Controller {{{ */
7469 @interface PackageSettingsController : CyteViewController <
7470 UITableViewDataSource,
7473 _transient Database *database_;
7475 _H<Package> package_;
7476 _H<UITableView> table_;
7477 _H<UISwitch> subscribedSwitch_;
7478 _H<UISwitch> ignoredSwitch_;
7479 _H<UITableViewCell> subscribedCell_;
7480 _H<UITableViewCell> ignoredCell_;
7483 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7487 @implementation PackageSettingsController
7489 - (NSURL *) navigationURL {
7490 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7493 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7494 if (package_ == nil)
7497 if ([package_ installed] == nil)
7503 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7504 if (package_ == nil)
7507 // both sections contain just one item right now.
7511 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7515 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7517 return UCLocalize("SHOW_ALL_CHANGES_EX");
7519 return UCLocalize("IGNORE_UPGRADES_EX");
7522 - (void) onSubscribed:(id)control {
7523 bool value([control isOn]);
7524 if (package_ == nil)
7526 if ([package_ setSubscribed:value])
7527 [delegate_ updateData];
7530 - (void) _updateIgnored {
7531 const char *package([name_ UTF8String]);
7532 bool on([ignoredSwitch_ isOn]);
7534 pid_t pid(ExecFork());
7536 FILE *dpkg(popen("dpkg --set-selections", "w"));
7537 fwrite(package, strlen(package), 1, dpkg);
7540 fwrite(" hold\n", 6, 1, dpkg);
7542 fwrite(" install\n", 9, 1, dpkg);
7552 int result(waitpid(pid, &status, 0));
7555 _assert(result == pid);
7561 - (void) onIgnored:(id)control {
7562 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7563 [invocation setTarget:self];
7564 [invocation setSelector:@selector(_updateIgnored)];
7566 [delegate_ reloadDataWithInvocation:invocation];
7569 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7570 if (package_ == nil)
7573 switch ([indexPath section]) {
7574 case 0: return subscribedCell_;
7575 case 1: return ignoredCell_;
7584 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7586 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7587 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7588 [(UITableView *) table_ setDataSource:self];
7589 [table_ setDelegate:self];
7590 [[self view] addSubview:table_];
7592 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7593 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7594 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7596 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7597 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7598 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7600 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7601 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7602 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7603 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7605 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7606 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7607 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7608 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7611 - (void) viewDidLoad {
7612 [super viewDidLoad];
7614 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7617 - (void) releaseSubviews {
7619 subscribedCell_ = nil;
7621 ignoredSwitch_ = nil;
7622 subscribedSwitch_ = nil;
7625 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7626 if ((self = [super init]) != nil) {
7627 database_ = database;
7632 - (void) reloadData {
7635 package_ = [database_ packageWithName:name_];
7637 if (package_ != nil) {
7638 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7639 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7640 } // XXX: what now, G?
7642 [table_ reloadData];
7648 /* Installed Controller {{{ */
7649 @interface InstalledController : FilteredPackageListController {
7653 - (id) initWithDatabase:(Database *)database;
7655 - (void) updateRoleButton;
7656 - (void) queueStatusDidChange;
7660 @implementation InstalledController
7666 - (NSURL *) navigationURL {
7667 return [NSURL URLWithString:@"cydia://installed"];
7670 - (id) initWithDatabase:(Database *)database {
7671 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7672 [self updateRoleButton];
7673 [self queueStatusDidChange];
7678 - (void) queueButtonClicked {
7683 - (void) queueStatusDidChange {
7687 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7688 initWithTitle:UCLocalize("QUEUE")
7689 style:UIBarButtonItemStyleDone
7691 action:@selector(queueButtonClicked)
7694 [[self navigationItem] setLeftBarButtonItem:nil];
7700 - (void) updateRoleButton {
7701 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7702 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7703 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7704 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7706 action:@selector(roleButtonClicked)
7710 - (void) roleButtonClicked {
7711 [self setObject:[NSNumber numberWithBool:expert_]];
7715 [self updateRoleButton];
7721 /* Source Cell {{{ */
7722 @interface SourceCell : CYTableViewCell <
7723 CyteTableViewCellDelegate
7726 _H<NSString> origin_;
7727 _H<NSString> label_;
7730 - (void) setSource:(Source *)source;
7734 @implementation SourceCell
7736 - (void) setSource:(Source *)source {
7739 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7741 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7743 origin_ = [source name];
7744 label_ = [source uri];
7746 [content_ setNeedsDisplay];
7749 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7750 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7751 UIView *content([self contentView]);
7752 CGRect bounds([content bounds]);
7754 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7755 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7756 [content_ setBackgroundColor:[UIColor whiteColor]];
7757 [content addSubview:content_];
7759 [content_ setDelegate:self];
7760 [content_ setOpaque:YES];
7764 - (NSString *) accessibilityLabel {
7768 - (void) drawContentRect:(CGRect)rect {
7769 bool highlighted(highlighted_);
7770 float width(rect.size.width);
7773 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7780 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7784 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7789 /* Source Controller {{{ */
7790 @interface SourceController : FilteredPackageListController {
7791 _transient Source *source_;
7795 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7799 @implementation SourceController
7801 - (NSURL *) navigationURL {
7802 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7805 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7806 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7808 key_ = [source key];
7812 - (void) reloadData {
7813 source_ = [database_ sourceWithKey:key_];
7814 key_ = [source_ key];
7815 [self setObject:source_];
7817 [[self navigationItem] setTitle:[source_ label]];
7824 /* Sources Controller {{{ */
7825 @interface SourcesController : CyteViewController <
7826 UITableViewDataSource,
7829 _transient Database *database_;
7830 _H<UITableView> list_;
7831 _H<NSMutableArray> sources_;
7835 _H<UIProgressHUD> hud_;
7838 //NSURLConnection *installer_;
7839 NSURLConnection *trivial_;
7840 NSURLConnection *trivial_bz2_;
7841 NSURLConnection *trivial_gz_;
7842 //NSURLConnection *automatic_;
7847 - (id) initWithDatabase:(Database *)database;
7848 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7852 @implementation SourcesController
7854 - (void) _releaseConnection:(NSURLConnection *)connection {
7855 if (connection != nil) {
7856 [connection cancel];
7857 //[connection setDelegate:nil];
7858 [connection release];
7863 //[self _releaseConnection:installer_];
7864 [self _releaseConnection:trivial_];
7865 [self _releaseConnection:trivial_gz_];
7866 [self _releaseConnection:trivial_bz2_];
7867 //[self _releaseConnection:automatic_];
7872 - (NSURL *) navigationURL {
7873 return [NSURL URLWithString:@"cydia://sources"];
7876 - (void) viewDidAppear:(BOOL)animated {
7877 [super viewDidAppear:animated];
7878 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7881 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7882 return offset_ == 0 ? 1 : 2;
7885 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7886 switch (section + (offset_ == 0 ? 1 : 0)) {
7887 case 0: return UCLocalize("ENTERED_BY_USER");
7888 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7894 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7895 int count = [sources_ count];
7897 case 0: return (offset_ == 0 ? count : offset_);
7898 case 1: return count - offset_;
7904 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7906 switch (indexPath.section) {
7907 case 0: idx = indexPath.row; break;
7908 case 1: idx = indexPath.row + offset_; break;
7912 return [sources_ objectAtIndex:idx];
7915 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7916 static NSString *cellIdentifier = @"SourceCell";
7918 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7919 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7920 [cell setSource:[self sourceAtIndexPath:indexPath]];
7921 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7926 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7927 Source *source = [self sourceAtIndexPath:indexPath];
7929 SourceController *controller = [[[SourceController alloc]
7930 initWithDatabase:database_
7934 [controller setDelegate:delegate_];
7936 [[self navigationController] pushViewController:controller animated:YES];
7939 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7940 Source *source = [self sourceAtIndexPath:indexPath];
7941 return [source record] != nil;
7944 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7945 if (editingStyle == UITableViewCellEditingStyleDelete) {
7946 Source *source = [self sourceAtIndexPath:indexPath];
7947 [Sources_ removeObjectForKey:[source key]];
7948 [delegate_ syncData];
7953 [delegate_ addTrivialSource:href_];
7954 [delegate_ syncData];
7957 - (NSString *) getWarning {
7958 NSString *href(href_);
7959 NSRange colon([href rangeOfString:@"://"]);
7960 if (colon.location != NSNotFound)
7961 href = [href substringFromIndex:(colon.location + 3)];
7962 href = [href stringByAddingPercentEscapes];
7963 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7964 href = [href stringByCachingURLWithCurrentCDN];
7966 NSURL *url([NSURL URLWithString:href]);
7968 NSStringEncoding encoding;
7969 NSError *error(nil);
7971 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7972 return [warning length] == 0 ? nil : warning;
7976 - (void) _endConnection:(NSURLConnection *)connection {
7977 // XXX: the memory management in this method is horribly awkward
7979 NSURLConnection **field = NULL;
7980 if (connection == trivial_)
7982 else if (connection == trivial_bz2_)
7983 field = &trivial_bz2_;
7984 else if (connection == trivial_gz_)
7985 field = &trivial_gz_;
7986 _assert(field != NULL);
7987 [connection release];
7992 trivial_bz2_ == nil &&
7995 [delegate_ releaseNetworkActivityIndicator];
7997 [delegate_ removeProgressHUD:hud_];
8003 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8006 UIAlertView *alert = [[[UIAlertView alloc]
8007 initWithTitle:UCLocalize("SOURCE_WARNING")
8010 cancelButtonTitle:UCLocalize("CANCEL")
8012 UCLocalize("ADD_ANYWAY"),
8016 [alert setContext:@"warning"];
8017 [alert setNumberOfRows:1];
8021 } else if (error_ != nil) {
8022 UIAlertView *alert = [[[UIAlertView alloc]
8023 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8024 message:[error_ localizedDescription]
8026 cancelButtonTitle:UCLocalize("OK")
8027 otherButtonTitles:nil
8030 [alert setContext:@"urlerror"];
8033 UIAlertView *alert = [[[UIAlertView alloc]
8034 initWithTitle:UCLocalize("NOT_REPOSITORY")
8035 message:UCLocalize("NOT_REPOSITORY_EX")
8037 cancelButtonTitle:UCLocalize("OK")
8038 otherButtonTitles:nil
8041 [alert setContext:@"trivial"];
8050 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8051 switch ([response statusCode]) {
8057 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8058 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8060 [self _endConnection:connection];
8063 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8064 [self _endConnection:connection];
8067 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8068 NSMutableURLRequest *request = [NSMutableURLRequest
8069 requestWithURL:[NSURL URLWithString:href]
8070 cachePolicy:NSURLRequestUseProtocolCachePolicy
8071 timeoutInterval:120.0
8074 [request setHTTPMethod:method];
8076 if (Machine_ != NULL)
8077 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8078 if (UniqueID_ != nil)
8079 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8081 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8084 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8085 NSString *context([alert context]);
8087 if ([context isEqualToString:@"source"]) {
8090 NSString *href = [[alert textField] text];
8092 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8094 if (![href hasSuffix:@"/"])
8095 href_ = [href stringByAppendingString:@"/"];
8099 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8100 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8101 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8102 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8106 // XXX: this is stupid
8107 hud_ = [delegate_ addProgressHUD];
8108 [hud_ setText:UCLocalize("VERIFYING_URL")];
8109 [delegate_ retainNetworkActivityIndicator];
8118 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8119 } else if ([context isEqualToString:@"trivial"])
8120 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8121 else if ([context isEqualToString:@"urlerror"])
8122 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8123 else if ([context isEqualToString:@"warning"]) {
8137 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8142 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8144 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8145 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8146 [list_ setRowHeight:56];
8147 [(UITableView *) list_ setDataSource:self];
8148 [list_ setDelegate:self];
8149 [[self view] addSubview:list_];
8152 - (void) viewDidLoad {
8153 [super viewDidLoad];
8155 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8156 [self updateButtonsForEditingStatus:NO animated:NO];
8159 - (void) releaseSubviews {
8163 - (id) initWithDatabase:(Database *)database {
8164 if ((self = [super init]) != nil) {
8165 database_ = database;
8166 sources_ = [NSMutableArray arrayWithCapacity:16];
8170 - (void) reloadData {
8174 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8177 [sources_ removeAllObjects];
8178 [sources_ addObjectsFromArray:[database_ sources]];
8180 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8183 int count([sources_ count]);
8185 for (int i = 0; i != count; i++) {
8186 if ([[sources_ objectAtIndex:i] record] == nil)
8191 [list_ setEditing:NO];
8192 [self updateButtonsForEditingStatus:NO animated:NO];
8196 - (void) showAddSourcePrompt {
8197 UIAlertView *alert = [[[UIAlertView alloc]
8198 initWithTitle:UCLocalize("ENTER_APT_URL")
8201 cancelButtonTitle:UCLocalize("CANCEL")
8203 UCLocalize("ADD_SOURCE"),
8207 [alert setContext:@"source"];
8209 [alert setNumberOfRows:1];
8210 [alert addTextFieldWithValue:@"http://" label:@""];
8212 UITextInputTraits *traits = [[alert textField] textInputTraits];
8213 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8214 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8215 [traits setKeyboardType:UIKeyboardTypeURL];
8216 // XXX: UIReturnKeyDone
8217 [traits setReturnKeyType:UIReturnKeyNext];
8222 - (void) addButtonClicked {
8223 [self showAddSourcePrompt];
8226 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8227 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8228 initWithTitle:UCLocalize("ADD")
8229 style:UIBarButtonItemStylePlain
8231 action:@selector(addButtonClicked)
8232 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8234 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8235 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8236 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8238 action:@selector(editButtonClicked)
8239 ] autorelease] animated:animated];
8241 if (IsWildcat_ && !editing)
8242 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8243 initWithTitle:UCLocalize("SETTINGS")
8244 style:UIBarButtonItemStylePlain
8246 action:@selector(settingsButtonClicked)
8250 - (void) settingsButtonClicked {
8251 [delegate_ showSettings];
8254 - (void) editButtonClicked {
8255 [list_ setEditing:![list_ isEditing] animated:YES];
8257 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8263 /* Settings Controller {{{ */
8264 @interface SettingsController : CyteViewController <
8265 UITableViewDataSource,
8268 _transient Database *database_;
8269 // XXX: ok, "roledelegate_"?...
8270 _transient id roledelegate_;
8271 _H<UITableView> table_;
8272 _H<UISegmentedControl> segment_;
8273 _H<UIView> container_;
8276 - (void) showDoneButton;
8277 - (void) resizeSegmentedControl;
8281 @implementation SettingsController
8284 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8286 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8287 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8288 [table_ setDelegate:self];
8289 [(UITableView *) table_ setDataSource:self];
8290 [[self view] addSubview:table_];
8292 NSArray *items = [NSArray arrayWithObjects:
8294 UCLocalize("HACKER"),
8295 UCLocalize("DEVELOPER"),
8297 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8298 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8299 [container_ addSubview:segment_];
8302 - (void) viewDidLoad {
8303 [super viewDidLoad];
8305 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8308 if ([Role_ isEqualToString:@"User"]) index = 0;
8309 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8310 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8312 [segment_ setSelectedSegmentIndex:index];
8313 [self showDoneButton];
8316 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8317 [self resizeSegmentedControl];
8320 - (void) releaseSubviews {
8326 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8327 if ((self = [super init]) != nil) {
8328 database_ = database;
8329 roledelegate_ = delegate;
8333 - (void) resizeSegmentedControl {
8334 CGFloat width = [[self view] frame].size.width;
8335 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8338 - (void) viewWillAppear:(BOOL)animated {
8339 [super viewWillAppear:animated];
8341 [self resizeSegmentedControl];
8344 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8345 [self resizeSegmentedControl];
8348 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8349 [self resizeSegmentedControl];
8353 NSString *role(nil);
8355 switch ([segment_ selectedSegmentIndex]) {
8356 case 0: role = @"User"; break;
8357 case 1: role = @"Hacker"; break;
8358 case 2: role = @"Developer"; break;
8363 if (![role isEqualToString:Role_]) {
8364 bool rolling(Role_ == nil);
8367 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8371 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8375 [roledelegate_ loadData];
8377 [roledelegate_ updateData];
8381 - (void) segmentChanged:(UISegmentedControl *)control {
8382 [self showDoneButton];
8385 - (void) saveAndClose {
8388 [[self navigationItem] setRightBarButtonItem:nil];
8389 [[self navigationController] dismissModalViewControllerAnimated:YES];
8392 - (void) doneButtonClicked {
8393 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8394 [spinner startAnimating];
8395 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8396 [[self navigationItem] setRightBarButtonItem:spinItem];
8398 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8401 - (void) showDoneButton {
8402 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8403 initWithTitle:UCLocalize("DONE")
8404 style:UIBarButtonItemStyleDone
8406 action:@selector(doneButtonClicked)
8407 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8410 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8411 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8415 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8419 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8420 return nil; // This method is required by the protocol.
8423 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8425 return UCLocalize("ROLE_EX");
8427 return [NSString stringWithFormat:
8428 @"%@: %@\n%@: %@\n%@: %@",
8429 UCLocalize("USER"), UCLocalize("USER_EX"),
8430 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8431 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8436 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8437 return section == 3 ? 44.0f : 0;
8440 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8441 return section == 3 ? container_ : nil;
8444 - (void) reloadData {
8447 [table_ reloadData];
8452 /* Stash Controller {{{ */
8453 @interface StashController : CyteViewController {
8454 _H<UIActivityIndicatorView> spinner_;
8455 _H<UILabel> status_;
8456 _H<UILabel> caption_;
8461 @implementation StashController
8464 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8465 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8467 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8468 CGRect spinrect = [spinner_ frame];
8469 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8470 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8471 [spinner_ setFrame:spinrect];
8472 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8473 [[self view] addSubview:spinner_];
8474 [spinner_ startAnimating];
8477 captrect.size.width = [[self view] frame].size.width;
8478 captrect.size.height = 40.0f;
8479 captrect.origin.x = 0;
8480 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8481 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8482 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8483 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8484 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8485 [caption_ setTextColor:[UIColor whiteColor]];
8486 [caption_ setBackgroundColor:[UIColor clearColor]];
8487 [caption_ setShadowColor:[UIColor blackColor]];
8488 [caption_ setTextAlignment:UITextAlignmentCenter];
8489 [[self view] addSubview:caption_];
8492 statusrect.size.width = [[self view] frame].size.width;
8493 statusrect.size.height = 30.0f;
8494 statusrect.origin.x = 0;
8495 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8496 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8497 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8498 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8499 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8500 [status_ setTextColor:[UIColor whiteColor]];
8501 [status_ setBackgroundColor:[UIColor clearColor]];
8502 [status_ setShadowColor:[UIColor blackColor]];
8503 [status_ setTextAlignment:UITextAlignmentCenter];
8504 [[self view] addSubview:status_];
8510 @interface CYURLCache : SDURLCache {
8515 @implementation CYURLCache
8517 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8520 else if ([event isEqualToString:@"no-cache"])
8522 else if ([event isEqualToString:@"store"])
8524 else if ([event isEqualToString:@"invalid"])
8526 else if ([event isEqualToString:@"memory"])
8528 else if ([event isEqualToString:@"disk"])
8530 else if ([event isEqualToString:@"miss"])
8533 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8539 @interface Cydia : UIApplication <
8540 ConfirmationControllerDelegate,
8543 UINavigationControllerDelegate,
8544 UITabBarControllerDelegate
8546 _H<UIWindow> window_;
8547 _H<CYTabBarController> tabbar_;
8548 _H<CYEmulatedLoadingController> emulated_;
8550 _H<NSMutableArray> essential_;
8551 _H<NSMutableArray> broken_;
8553 Database *database_;
8555 _H<NSURL> starturl_;
8560 _H<StashController> stash_;
8569 @implementation Cydia
8571 - (void) beginUpdate {
8572 [tabbar_ beginUpdate];
8576 return [tabbar_ updating];
8580 if ([broken_ count] != 0) {
8581 int count = [broken_ count];
8583 UIAlertView *alert = [[[UIAlertView alloc]
8584 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8585 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8587 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8589 UCLocalize("TEMPORARY_IGNORE"),
8593 [alert setContext:@"fixhalf"];
8594 [alert setNumberOfRows:2];
8596 } else if (!Ignored_ && [essential_ count] != 0) {
8597 int count = [essential_ count];
8599 UIAlertView *alert = [[[UIAlertView alloc]
8600 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8601 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8603 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8605 UCLocalize("UPGRADE_ESSENTIAL"),
8606 UCLocalize("COMPLETE_UPGRADE"),
8610 [alert setContext:@"upgrade"];
8615 - (void) _saveConfig {
8621 NSString *error(nil);
8623 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8625 NSError *error(nil);
8626 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8627 NSLog(@"failure to save metadata data: %@", error);
8632 NSLog(@"failure to serialize metadata: %@", error);
8637 // Navigation controller for the queuing badge.
8638 - (UINavigationController *) queueNavigationController {
8639 NSArray *controllers = [tabbar_ viewControllers];
8640 return [controllers objectAtIndex:3];
8643 - (void) unloadData {
8644 [tabbar_ unloadData];
8647 - (void) _updateData {
8652 UINavigationController *navigation = [self queueNavigationController];
8654 id queuedelegate = nil;
8655 if ([[navigation viewControllers] count] > 0)
8656 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8658 [queuedelegate queueStatusDidChange];
8659 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8662 - (void) _refreshIfPossible:(NSDate *)update {
8663 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8665 bool recently = false;
8666 if (update != nil) {
8667 NSTimeInterval interval([update timeIntervalSinceNow]);
8668 if (interval <= 0 && interval > -(15*60))
8672 // Don't automatic refresh if:
8673 // - We already refreshed recently.
8674 // - We already auto-refreshed this launch.
8675 // - Auto-refresh is disabled.
8676 if (recently || loaded_ || ManualRefresh) {
8677 // If we are cancelling, we need to make sure it knows it's already loaded.
8680 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8682 // We are going to load, so remember that.
8685 SCNetworkReachabilityFlags flags; {
8686 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8687 SCNetworkReachabilityGetFlags(reachability, &flags);
8688 CFRelease(reachability);
8691 // XXX: this elaborate mess is what Apple is using to determine this? :(
8692 // XXX: do we care if the user has to intervene? maybe that's ok?
8694 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8695 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8696 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8697 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8698 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8699 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8703 // If we can reach the server, auto-refresh!
8705 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8711 - (void) refreshIfPossible {
8712 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8715 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8716 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8717 [hud setText:UCLocalize("RELOADING_DATA")];
8719 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8722 [self removeProgressHUD:hud];
8726 [essential_ removeAllObjects];
8727 [broken_ removeAllObjects];
8729 NSArray *packages([database_ packages]);
8730 for (Package *package in packages) {
8732 [broken_ addObject:package];
8733 if ([package upgradableAndEssential:NO]) {
8734 if ([package essential])
8735 [essential_ addObject:package];
8740 NSLog(@"changes:#%u", changes);
8742 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8745 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8746 [changesItem setBadgeValue:badge];
8747 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8748 [self setApplicationIconBadgeNumber:changes];
8751 [changesItem setBadgeValue:nil];
8752 [changesItem setAnimatedBadge:NO];
8753 [self setApplicationIconBadgeNumber:0];
8758 [self refreshIfPossible];
8761 - (void) updateData {
8770 @synchronized (self) {
8771 [self _reloadDataWithInvocation:nil];
8775 - (void) disemulate {
8776 if (emulated_ == nil)
8779 [window_ addSubview:[tabbar_ view]];
8780 [[emulated_ view] removeFromSuperview];
8782 [window_ setUserInteractionEnabled:YES];
8785 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8786 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8788 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8790 UIViewController *parent;
8791 if (emulated_ == nil)
8800 [parent presentModalViewController:navigation animated:YES];
8803 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8804 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8806 if (navigation != nil)
8807 [navigation pushViewController:progress animated:YES];
8809 [self presentModalViewController:progress force:YES];
8811 [progress invoke:invocation withTitle:title];
8815 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8816 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8819 - (void) repairWithInvocation:(NSInvocation *)invocation {
8821 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8825 - (void) repairWithSelector:(SEL)selector {
8826 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8832 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8833 _assert(file != NULL);
8835 for (NSString *key in [Sources_ allKeys]) {
8836 NSDictionary *source([Sources_ objectForKey:key]);
8838 fprintf(file, "%s %s %s\n",
8839 [[source objectForKey:@"Type"] UTF8String],
8840 [[source objectForKey:@"URI"] UTF8String],
8841 [[source objectForKey:@"Distribution"] UTF8String]
8847 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8852 - (void) addTrivialSource:(NSString *)href {
8853 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8856 @"./", @"Distribution",
8857 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8862 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8863 @synchronized (self) {
8864 [self _reloadDataWithInvocation:invocation];
8868 - (void) reloadData {
8869 [self reloadDataWithInvocation:nil];
8873 pkgProblemResolver *resolver = [database_ resolver];
8875 resolver->InstallProtect();
8876 if (!resolver->Resolve(true))
8881 // XXX: this is a really crappy way of doing this.
8882 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8883 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8884 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8885 if ([tabbar_ updating])
8886 [tabbar_ cancelUpdate];
8888 if (![database_ prepare])
8891 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8892 [page setDelegate:self];
8893 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8896 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8897 [tabbar_ presentModalViewController:confirm_ animated:YES];
8903 @synchronized (self) {
8908 - (void) clearPackage:(Package *)package {
8909 @synchronized (self) {
8916 - (void) installPackages:(NSArray *)packages {
8917 @synchronized (self) {
8918 for (Package *package in packages)
8925 - (void) installPackage:(Package *)package {
8926 @synchronized (self) {
8933 - (void) removePackage:(Package *)package {
8934 @synchronized (self) {
8941 - (void) distUpgrade {
8942 @synchronized (self) {
8943 if (![database_ upgrade])
8949 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8952 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
8957 - (void) showSettings {
8958 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
8961 - (void) retainNetworkActivityIndicator {
8962 if (activity_++ == 0)
8963 [self setNetworkActivityIndicatorVisible:YES];
8966 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
8970 - (void) releaseNetworkActivityIndicator {
8971 if (--activity_ == 0)
8972 [self setNetworkActivityIndicatorVisible:NO];
8975 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
8980 - (void) cancelAndClear:(bool)clear {
8981 @synchronized (self) {
8993 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8994 NSString *context([alert context]);
8996 if ([context isEqualToString:@"conffile"]) {
8997 FILE *input = [database_ input];
8998 if (button == [alert cancelButtonIndex])
8999 fprintf(input, "N\n");
9000 else if (button == [alert firstOtherButtonIndex])
9001 fprintf(input, "Y\n");
9004 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9005 } else if ([context isEqualToString:@"fixhalf"]) {
9006 if (button == [alert cancelButtonIndex]) {
9007 @synchronized (self) {
9008 for (Package *broken in (id) broken_) {
9011 NSString *id = [broken id];
9012 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9013 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9014 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9015 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9021 } else if (button == [alert firstOtherButtonIndex]) {
9022 [broken_ removeAllObjects];
9026 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9027 } else if ([context isEqualToString:@"upgrade"]) {
9028 if (button == [alert firstOtherButtonIndex]) {
9029 @synchronized (self) {
9030 for (Package *essential in (id) essential_)
9031 [essential install];
9036 } else if (button == [alert firstOtherButtonIndex] + 1) {
9038 } else if (button == [alert cancelButtonIndex]) {
9042 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9046 - (void) system:(NSString *)command {
9047 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9050 system([command UTF8String]);
9056 - (void) applicationWillSuspend {
9058 [super applicationWillSuspend];
9061 - (BOOL) isSafeToSuspend {
9064 NSLog(@"isSafeToSuspend: locked_ != 0");
9069 // Use external process status API internally.
9070 // This is probably a really bad idea.
9071 // XXX: what is the point of this? does this solve anything at all?
9072 uint64_t status = 0;
9074 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9075 notify_get_state(notify_token, &status);
9076 notify_cancel(notify_token);
9081 NSLog(@"isSafeToSuspend: status != 0");
9087 NSLog(@"isSafeToSuspend: -> true");
9092 - (void) applicationSuspend:(__GSEvent *)event {
9093 if ([self isSafeToSuspend])
9094 [super applicationSuspend:event];
9097 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9098 if ([self isSafeToSuspend])
9099 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9102 - (void) _setSuspended:(BOOL)value {
9103 if ([self isSafeToSuspend])
9104 [super _setSuspended:value];
9107 - (UIProgressHUD *) addProgressHUD {
9108 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9109 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9111 [window_ setUserInteractionEnabled:NO];
9113 UIViewController *target(tabbar_);
9114 if (UIViewController *modal = [target modalViewController])
9117 UIView *view([target view]);
9118 [view addSubview:hud];
9126 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9129 [hud removeFromSuperview];
9130 [window_ setUserInteractionEnabled:YES];
9133 - (CyteViewController *) pageForPackage:(NSString *)name {
9134 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9137 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9138 NSString *scheme([[url scheme] lowercaseString]);
9139 if ([[url absoluteString] length] <= [scheme length] + 3)
9141 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9142 NSArray *components([path pathComponents]);
9144 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9145 return [self pageForPackage:[components objectAtIndex:1]];
9147 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9150 NSString *base([components objectAtIndex:0]);
9152 CyteViewController *controller = nil;
9154 if ([base isEqualToString:@"url"]) {
9155 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9156 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9157 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9158 } else if (!external && [components count] == 1) {
9159 if ([base isEqualToString:@"manage"]) {
9160 controller = [[[ManageController alloc] init] autorelease];
9163 if ([base isEqualToString:@"sources"]) {
9164 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9167 if ([base isEqualToString:@"home"]) {
9168 controller = [[[HomeController alloc] init] autorelease];
9171 if ([base isEqualToString:@"sections"]) {
9172 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9175 if ([base isEqualToString:@"search"]) {
9176 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9179 if ([base isEqualToString:@"changes"]) {
9180 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9183 if ([base isEqualToString:@"installed"]) {
9184 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9186 } else if ([components count] == 2) {
9187 NSString *argument = [components objectAtIndex:1];
9189 if ([base isEqualToString:@"package"]) {
9190 controller = [self pageForPackage:argument];
9193 if (!external && [base isEqualToString:@"search"]) {
9194 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9197 if (!external && [base isEqualToString:@"sections"]) {
9198 if ([argument isEqualToString:@"all"])
9200 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9203 if (!external && [base isEqualToString:@"sources"]) {
9204 if ([argument isEqualToString:@"add"]) {
9205 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9206 [(SourcesController *)controller showAddSourcePrompt];
9208 Source *source = [database_ sourceWithKey:argument];
9209 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9213 if (!external && [base isEqualToString:@"launch"]) {
9214 [self launchApplicationWithIdentifier:argument suspended:NO];
9217 } else if (!external && [components count] == 3) {
9218 NSString *arg1 = [components objectAtIndex:1];
9219 NSString *arg2 = [components objectAtIndex:2];
9221 if ([base isEqualToString:@"package"]) {
9222 if ([arg2 isEqualToString:@"settings"]) {
9223 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9224 } else if ([arg2 isEqualToString:@"files"]) {
9225 if (Package *package = [database_ packageWithName:arg1]) {
9226 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9227 [(FileTable *)controller setPackage:package];
9233 [controller setDelegate:self];
9237 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9238 CyteViewController *page([self pageForURL:url forExternal:external]);
9241 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9242 [nav setViewControllers:[NSArray arrayWithObject:page]];
9243 [tabbar_ setUnselectedViewController:nav];
9249 - (void) applicationOpenURL:(NSURL *)url {
9250 [super applicationOpenURL:url];
9255 [self openCydiaURL:url forExternal:YES];
9258 - (void) applicationWillResignActive:(UIApplication *)application {
9259 // Stop refreshing if you get a phone call or lock the device.
9260 if ([tabbar_ updating])
9261 [tabbar_ cancelUpdate];
9263 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9264 [super applicationWillResignActive:application];
9267 - (void) applicationWillTerminate:(UIApplication *)application {
9269 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9270 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9271 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9276 - (void) setConfigurationData:(NSString *)data {
9277 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9279 if (!conffile_r(data)) {
9280 lprintf("E:invalid conffile\n");
9284 NSString *ofile = conffile_r[1];
9285 //NSString *nfile = conffile_r[2];
9287 UIAlertView *alert = [[[UIAlertView alloc]
9288 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9289 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9291 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9293 UCLocalize("ACCEPT_NEW_COPY"),
9294 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9298 [alert setContext:@"conffile"];
9299 [alert setNumberOfRows:2];
9303 - (void) addStashController {
9305 stash_ = [[[StashController alloc] init] autorelease];
9306 [window_ addSubview:[stash_ view]];
9309 - (void) removeStashController {
9310 [[stash_ view] removeFromSuperview];
9316 [self setIdleTimerDisabled:YES];
9318 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9319 UpdateExternalStatus(1);
9320 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9321 UpdateExternalStatus(0);
9323 [self removeStashController];
9325 if (ExecFork() == 0) {
9326 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9327 perror("launchctl stop");
9331 - (void) setupViewControllers {
9332 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9334 NSMutableArray *items([NSMutableArray arrayWithObjects:
9335 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9336 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9337 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9338 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9342 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9343 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9345 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9348 NSMutableArray *controllers([NSMutableArray array]);
9349 for (UITabBarItem *item in items) {
9350 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9351 [controller setTabBarItem:item];
9352 [controllers addObject:controller];
9354 [tabbar_ setViewControllers:controllers];
9356 [tabbar_ setUpdateDelegate:self];
9359 - (void) applicationDidFinishLaunching:(id)unused {
9361 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9362 [self setApplicationSupportsShakeToEdit:NO];
9364 @synchronized (HostConfig_) {
9365 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9368 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9369 initWithMemoryCapacity:524288
9370 diskCapacity:10485760
9371 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9374 [CydiaWebViewController _initialize];
9376 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9378 // this would disallow http{,s} URLs from accessing this data
9379 //[WebView registerURLSchemeAsLocal:@"cydia"];
9381 Font12_ = [UIFont systemFontOfSize:12];
9382 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9383 Font14_ = [UIFont systemFontOfSize:14];
9384 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9385 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9387 essential_ = [NSMutableArray arrayWithCapacity:4];
9388 broken_ = [NSMutableArray arrayWithCapacity:4];
9390 // XXX: I really need this thing... like, seriously... I'm sorry
9391 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9393 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9394 [window_ orderFront:self];
9395 [window_ makeKey:self];
9396 [window_ setHidden:NO];
9399 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9400 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9401 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9402 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9403 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9404 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9405 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9406 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9407 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9410 [self addStashController];
9411 // XXX: this would be much cleaner as a yieldToSelector:
9412 // that way the removeStashController could happen right here inline
9413 // we also could no longer require the useless stash_ field anymore
9414 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9418 database_ = [Database sharedInstance];
9419 [database_ setDelegate:self];
9421 [window_ setUserInteractionEnabled:NO];
9422 [self setupViewControllers];
9424 emulated_ = [[[CYEmulatedLoadingController alloc] initWithDatabase:database_] autorelease];
9425 [window_ addSubview:[emulated_ view]];
9427 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9431 - (NSArray *) defaultStartPages {
9432 NSMutableArray *standard = [NSMutableArray array];
9433 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9434 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9435 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9437 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9439 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9440 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9442 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9449 [window_ setUserInteractionEnabled:YES];
9450 [self showSettings];
9453 if ([emulated_ modalViewController] != nil)
9454 [emulated_ dismissModalViewControllerAnimated:YES];
9455 [window_ setUserInteractionEnabled:NO];
9463 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9464 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9465 int standardIndex = 0;
9466 NSArray *standard = [self defaultStartPages];
9473 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9474 if (valid && closed != nil) {
9475 NSTimeInterval interval([closed timeIntervalSinceNow]);
9476 // XXX: Is 15 minutes the optimal time here?
9477 if (interval > 0 && interval <= -(15*60))
9481 if (valid && [saved count] != [standard count])
9485 for (unsigned int i = 0; i < [standard count]; i++) {
9486 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9487 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9488 // but it's good enough for now.
9489 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9496 NSArray *items = nil;
9498 [tabbar_ setSelectedIndex:savedIndex];
9501 [tabbar_ setSelectedIndex:standardIndex];
9505 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9506 NSArray *stack = [items objectAtIndex:tab];
9507 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9508 NSMutableArray *current = [NSMutableArray array];
9510 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9511 NSString *addr = [stack objectAtIndex:nav];
9512 NSURL *url = [NSURL URLWithString:addr];
9513 CyteViewController *page = [self pageForURL:url forExternal:NO];
9515 [current addObject:page];
9518 [navigation setViewControllers:current];
9521 // (Try to) show the startup URL.
9522 if (starturl_ != nil) {
9523 [self openCydiaURL:starturl_ forExternal:NO];
9528 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9529 if (item != nil && IsWildcat_) {
9530 [sheet showFromBarButtonItem:item animated:YES];
9532 [sheet showInView:window_];
9536 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9537 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9538 [progress setTitle:task];
9539 [progress addProgressEvent:event];
9542 - (void) addProgressEventForTask:(NSArray *)data {
9543 CydiaProgressEvent *event([data objectAtIndex:0]);
9544 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9545 [self addProgressEvent:event forTask:task];
9548 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9549 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9555 id Alloc_(id self, SEL selector) {
9556 id object = alloc_(self, selector);
9557 lprintf("[%s]A-%p\n", self->isa->name, object);
9562 id Dealloc_(id self, SEL selector) {
9563 id object = dealloc_(self, selector);
9564 lprintf("[%s]D-%p\n", self->isa->name, object);
9568 Class $WebDefaultUIKitDelegate;
9570 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9571 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9572 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9573 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9576 static NSSet *MobilizedFiles_;
9578 static NSURL *MobilizeURL(NSURL *url) {
9579 NSString *path([url path]);
9580 if ([path hasPrefix:@"/var/root/"]) {
9581 NSString *file([path substringFromIndex:10]);
9582 if ([MobilizedFiles_ containsObject:file])
9583 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9589 Class $CFXPreferencesPropertyListSource;
9590 @class CFXPreferencesPropertyListSource;
9592 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9593 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9594 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9595 url = MobilizeURL(url);
9596 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9597 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9603 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9604 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9605 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9606 url = MobilizeURL(url);
9607 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9608 //NSLog(@"%@ %@", [url absoluteString], value);
9614 Class $NSURLConnection;
9616 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9617 NSMutableURLRequest *copy([request mutableCopy]);
9619 NSURL *url([copy URL]);
9620 NSString *host([url host]);
9621 NSString *scheme([[url scheme] lowercaseString]);
9623 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9625 @synchronized (HostConfig_) {
9626 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9627 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9628 [copy setHTTPShouldUsePipelining:YES];
9631 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9635 int main(int argc, char *argv[]) {
9636 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9640 UpdateExternalStatus(0);
9642 if (Class $UIDevice = objc_getClass("UIDevice")) {
9643 UIDevice *device([$UIDevice currentDevice]);
9644 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9648 UIScreen *screen([UIScreen mainScreen]);
9649 if ([screen respondsToSelector:@selector(scale)])
9650 ScreenScale_ = [screen scale];
9654 UIDevice *device([UIDevice currentDevice]);
9655 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9658 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9659 if (idiom == UIUserInterfaceIdiomPhone)
9661 else if (idiom == UIUserInterfaceIdiomPad)
9664 NSLog(@"unknown UIUserInterfaceIdiom!");
9667 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9669 HostConfig_ = [[[NSObject alloc] init] autorelease];
9670 @synchronized (HostConfig_) {
9671 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9672 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9675 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9677 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9679 MobilizedFiles_ = [NSMutableSet setWithObjects:
9680 @"Library/Preferences/com.apple.Accessibility.plist",
9681 @"Library/Preferences/com.apple.preferences.sounds.plist",
9684 /* Library Hacks {{{ */
9685 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9687 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9689 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9690 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9691 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9692 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9695 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9696 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9697 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9698 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9701 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9702 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9703 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9704 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9705 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9708 $NSURLConnection = objc_getClass("NSURLConnection");
9709 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9710 if (NSURLConnection$init$ != NULL) {
9711 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9712 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9715 /* Set Locale {{{ */
9716 Locale_ = CFLocaleCopyCurrent();
9717 Languages_ = [NSLocale preferredLanguages];
9719 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9720 //NSLog(@"%@", [Languages_ description]);
9723 if (Locale_ != NULL)
9724 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9725 else if (Languages_ != nil && [Languages_ count] != 0)
9726 lang = [[Languages_ objectAtIndex:0] UTF8String];
9728 // XXX: consider just setting to C and then falling through?
9732 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9733 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9736 NSLog(@"Setting Language: %s", lang);
9739 setenv("LANG", lang, true);
9740 std::setlocale(LC_ALL, lang);
9744 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9746 /* Parse Arguments {{{ */
9747 bool substrate(false);
9753 for (int argi(1); argi != argc; ++argi)
9754 if (strcmp(argv[argi], "--") == 0) {
9756 argv[argi] = argv[0];
9762 for (int argi(1); argi != arge; ++argi)
9763 if (strcmp(args[argi], "--substrate") == 0)
9766 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9770 App_ = [[NSBundle mainBundle] bundlePath];
9776 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9777 alloc_ = alloc->method_imp;
9778 alloc->method_imp = (IMP) &Alloc_;*/
9780 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9781 dealloc_ = dealloc->method_imp;
9782 dealloc->method_imp = (IMP) &Dealloc_;*/
9784 /* System Information {{{ */
9788 size = sizeof(maxproc);
9789 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9790 perror("sysctlbyname(\"kern.maxproc\", ?)");
9791 else if (maxproc < 64) {
9793 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9794 perror("sysctlbyname(\"kern.maxproc\", #)");
9797 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9798 char *osversion = new char[size];
9799 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9800 perror("sysctlbyname(\"kern.osversion\", ?)");
9802 System_ = [NSString stringWithUTF8String:osversion];
9804 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9805 char *machine = new char[size];
9806 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9807 perror("sysctlbyname(\"hw.machine\", ?)");
9811 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
9812 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
9813 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
9815 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9817 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9818 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9819 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9821 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9822 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9823 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9825 if (mcc != NULL && mnc != NULL)
9826 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9833 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9834 Build_ = [system objectForKey:@"ProductBuildVersion"];
9835 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9836 Product_ = [info objectForKey:@"SafariProductVersion"];
9837 Safari_ = [info objectForKey:@"CFBundleVersion"];
9840 /* Load Database {{{ */
9842 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9844 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9846 if (Metadata_ == NULL)
9847 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9849 Settings_ = [Metadata_ objectForKey:@"Settings"];
9851 Packages_ = [Metadata_ objectForKey:@"Packages"];
9852 Sections_ = [Metadata_ objectForKey:@"Sections"];
9853 Sources_ = [Metadata_ objectForKey:@"Sources"];
9855 Token_ = [Metadata_ objectForKey:@"Token"];
9858 if (Settings_ != nil)
9859 Role_ = [Settings_ objectForKey:@"Role"];
9861 if (Sections_ == nil) {
9862 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9863 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9866 if (Sources_ == nil) {
9867 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9868 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9873 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9876 if (Packages_ != nil) {
9878 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9882 [Metadata_ removeObjectForKey:@"Packages"];
9888 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9890 #define MobileSubstrate_(name) \
9891 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
9892 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
9893 if (handle == NULL) \
9894 NSLog(@"%s", dlerror()); \
9897 MobileSubstrate_(Activator)
9898 MobileSubstrate_(libstatusbar)
9899 MobileSubstrate_(SimulatedKeyEvents)
9900 MobileSubstrate_(WinterBoard)
9902 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9903 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9905 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9907 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9908 unlink("/tmp/.cydia.fw");
9910 } else if (access("/User", F_OK) != 0 || version < 4) {
9913 system("/usr/libexec/cydia/firmware.sh");
9917 _assert([[NSFileManager defaultManager]
9918 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9919 withIntermediateDirectories:YES
9924 if (access("/tmp/cydia.chk", F_OK) == 0) {
9925 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9926 _assert(errno == ENOENT);
9927 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9928 _assert(errno == ENOENT);
9931 /* APT Initialization {{{ */
9932 _assert(pkgInitConfig(*_config));
9933 _assert(pkgInitSystem(*_config, _system));
9936 _config->Set("APT::Acquire::Translation", lang);
9938 // XXX: this timeout might be important :(
9939 //_config->Set("Acquire::http::Timeout", 15);
9941 _config->Set("Acquire::http::MaxParallel", 3);
9943 /* Color Choices {{{ */
9944 space_ = CGColorSpaceCreateDeviceRGB();
9946 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9947 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9948 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9949 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9950 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9951 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9952 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9953 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9954 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9956 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9957 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9959 /* UIKit Configuration {{{ */
9960 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9961 if ($GSFontSetUseLegacyFontMetrics != NULL)
9962 $GSFontSetUseLegacyFontMetrics(YES);
9964 // XXX: I have a feeling this was important
9965 //UIKeyboardDisableAutomaticAppearance();
9968 Colon_ = UCLocalize("COLON_DELIMITED");
9969 Elision_ = UCLocalize("ELISION");
9970 Error_ = UCLocalize("ERROR");
9971 Warning_ = UCLocalize("WARNING");
9974 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9976 CGColorSpaceRelease(space_);