1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2009 Jay Freeman (saurik)
6 * Redistribution and use in source and binary
7 * forms, with or without modification, are permitted
8 * provided that the following conditions are met:
10 * 1. Redistributions of source code must retain the
11 * above copyright notice, this list of conditions
12 * and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the
14 * above copyright notice, this list of conditions
15 * and the following disclaimer in the documentation
16 * and/or other materials provided with the
18 * 3. The name of the author may not be used to endorse
19 * or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
23 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
24 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
28 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
33 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 // XXX: wtf/FastMalloc.h... wtf?
39 #define USE_SYSTEM_MALLOC 1
41 /* #include Directives {{{ */
42 #import "UICaboodle/UCPlatform.h"
43 #import "UICaboodle/UCLocalize.h"
45 #include <objc/message.h>
46 #include <objc/objc.h>
47 #include <objc/runtime.h>
49 #include <CoreGraphics/CoreGraphics.h>
50 #include <GraphicsServices/GraphicsServices.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 #import <UIKit/UIKit.h>
64 #include <WebCore/WebCoreThread.h>
65 #import <WebKit/WebDefaultUIKitDelegate.h>
72 #include <ext/stdio_filebuf.h>
74 #include <apt-pkg/acquire.h>
75 #include <apt-pkg/acquire-item.h>
76 #include <apt-pkg/algorithms.h>
77 #include <apt-pkg/cachefile.h>
78 #include <apt-pkg/clean.h>
79 #include <apt-pkg/configuration.h>
80 #include <apt-pkg/debindexfile.h>
81 #include <apt-pkg/debmetaindex.h>
82 #include <apt-pkg/error.h>
83 #include <apt-pkg/init.h>
84 #include <apt-pkg/mmap.h>
85 #include <apt-pkg/pkgrecords.h>
86 #include <apt-pkg/sha1.h>
87 #include <apt-pkg/sourcelist.h>
88 #include <apt-pkg/sptr.h>
89 #include <apt-pkg/strutl.h>
90 #include <apt-pkg/tagfile.h>
92 #include <apr-1/apr_pools.h>
94 #include <sys/types.h>
96 #include <sys/sysctl.h>
97 #include <sys/param.h>
98 #include <sys/mount.h>
104 #include <mach-o/nlist.h>
114 #include <ext/hash_map>
116 #import "UICaboodle/BrowserView.h"
117 #import "UICaboodle/ResetView.h"
119 #import "substrate.h"
122 //#define _finline __attribute__((force_inline))
123 #define _finline inline
128 #define _limit(count) do { \
129 static size_t _count(0); \
130 if (++_count == count) \
135 #define _timestamp ({ \
137 gettimeofday(&tv, NULL); \
138 tv.tv_sec * 1000000 + tv.tv_usec; \
141 typedef std::vector<class ProfileTime *> TimeList;
151 ProfileTime(const char *name) :
155 times_.push_back(this);
158 void AddTime(uint64_t time) {
165 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
177 ProfileTimer(ProfileTime &time) :
184 time_.AddTime(_timestamp - start_);
189 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
191 std::cerr << "========" << std::endl;
194 #define _profile(name) { \
195 static ProfileTime name(#name); \
196 ProfileTimer _ ## name(name);
200 /* Objective-C Handle<> {{{ */
201 template <typename Type_>
203 typedef _H<Type_> This_;
208 _finline void Retain_() {
213 _finline void Clear_() {
219 _finline _H(const This_ &rhs) :
220 value_(rhs.value_ == nil ? nil : [rhs.value_ retain])
224 _finline _H(Type_ *value = NULL, bool mended = false) :
235 _finline operator Type_ *() const {
239 _finline This_ &operator =(Type_ *value) {
240 if (value_ != value) {
251 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
253 void NSLogPoint(const char *fix, const CGPoint &point) {
254 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
257 void NSLogRect(const char *fix, const CGRect &rect) {
258 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
261 @interface NSObject (Cydia)
262 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
263 - (id) yieldToSelector:(SEL)selector;
266 @implementation NSObject (Cydia)
271 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
272 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
273 id object([[context objectAtIndex:1] nonretainedObjectValue]);
274 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
276 /* XXX: deal with exceptions */
277 id value([self performSelector:selector withObject:object]);
279 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
280 [context removeAllObjects];
281 if ([signature methodReturnLength] != 0 && value != nil)
282 [context addObject:value];
287 performSelectorOnMainThread:@selector(doNothing)
293 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
294 /*return [self performSelector:selector withObject:object];*/
296 volatile bool stopped(false);
298 NSMutableArray *context([NSMutableArray arrayWithObjects:
299 [NSValue valueWithPointer:selector],
300 [NSValue valueWithNonretainedObject:object],
301 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
304 NSThread *thread([[[NSThread alloc]
306 selector:@selector(_yieldToContext:)
312 NSRunLoop *loop([NSRunLoop currentRunLoop]);
313 NSDate *future([NSDate distantFuture]);
315 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
317 return [context count] == 0 ? nil : [context objectAtIndex:0];
320 - (id) yieldToSelector:(SEL)selector {
321 return [self yieldToSelector:selector withObject:nil];
326 /* NSForcedOrderingSearch doesn't work on the iPhone */
327 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
328 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
329 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
331 /* iPhoneOS 2.0 Compatibility {{{ */
333 @interface UITextView (iPhoneOS)
334 - (void) setTextSize:(float)size;
337 @implementation UITextView (iPhoneOS)
339 - (void) setTextSize:(float)size {
340 [self setFont:[[self font] fontWithSize:size]];
347 /* Information Dictionaries {{{ */
348 @interface NSMutableArray (Cydia)
349 - (void) addInfoDictionary:(NSDictionary *)info;
352 @implementation NSMutableArray (Cydia)
354 - (void) addInfoDictionary:(NSDictionary *)info {
355 [self addObject:info];
360 @interface NSMutableDictionary (Cydia)
361 - (void) addInfoDictionary:(NSDictionary *)info;
364 @implementation NSMutableDictionary (Cydia)
366 - (void) addInfoDictionary:(NSDictionary *)info {
367 NSString *bundle = [info objectForKey:@"CFBundleIdentifier"];
368 [self setObject:info forKey:bundle];
373 /* Pop Transitions {{{ */
374 @interface PopTransitionView : UITransitionView {
379 @implementation PopTransitionView
381 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
382 if (from != nil && to == nil)
383 [self removeFromSuperview];
388 @implementation UIView (PopUpView)
390 - (void) popFromSuperviewAnimated:(BOOL)animated {
391 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
394 - (void) popSubview:(UIView *)view {
395 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
396 [transition setDelegate:transition];
397 [self addSubview:transition];
399 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
400 [transition transition:UITransitionNone toView:blank];
401 [transition transition:UITransitionPushFromBottom toView:view];
407 #define lprintf(args...) fprintf(stderr, args)
410 #define TraceLogging (1 && !ForRelease)
411 #define HistogramInsertionSort (0 && !ForRelease)
412 #define ProfileTimes (0 && !ForRelease)
413 #define ForSaurik (0 && !ForRelease)
414 #define LogBrowser (1 && !ForRelease)
415 #define TrackResize (0 && !ForRelease)
416 #define ManualRefresh (1 && !ForRelease)
417 #define ShowInternals (0 && !ForRelease)
418 #define IgnoreInstall (0 && !ForRelease)
419 #define RecycleWebViews 0
420 #define RecyclePackageViews 1
421 #define AlwaysReload (0 && !ForRelease)
425 #define _trace(args...)
430 #define _profile(name) {
433 #define PrintTimes() do {} while (false)
437 typedef uint32_t (*SKRadixFunction)(id, void *);
439 @interface NSMutableArray (Radix)
440 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
441 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
449 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
450 struct RadixItem_ *lhs(swap), *rhs(swap + count);
452 static const size_t width = 32;
453 static const size_t bits = 11;
454 static const size_t slots = 1 << bits;
455 static const size_t passes = (width + (bits - 1)) / bits;
457 size_t *hist(new size_t[slots]);
459 for (size_t pass(0); pass != passes; ++pass) {
460 memset(hist, 0, sizeof(size_t) * slots);
462 for (size_t i(0); i != count; ++i) {
463 uint32_t key(lhs[i].key);
465 key &= _not(uint32_t) >> width - bits;
470 for (size_t i(0); i != slots; ++i) {
471 size_t local(offset);
476 for (size_t i(0); i != count; ++i) {
477 uint32_t key(lhs[i].key);
479 key &= _not(uint32_t) >> width - bits;
480 rhs[hist[key]++] = lhs[i];
483 RadixItem_ *tmp(lhs);
490 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
491 for (size_t i(0); i != count; ++i)
492 [values addObject:[self objectAtIndex:lhs[i].index]];
493 [self setArray:values];
498 @implementation NSMutableArray (Radix)
500 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
501 size_t count([self count]);
506 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
507 [invocation setSelector:selector];
508 [invocation setArgument:&object atIndex:2];
510 /* XXX: this is an unsafe optimization of doomy hell */
511 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
512 _assert(method != NULL);
513 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
514 _assert(imp != NULL);
517 struct RadixItem_ *swap(new RadixItem_[count * 2]);
519 for (size_t i(0); i != count; ++i) {
520 RadixItem_ &item(swap[i]);
523 id object([self objectAtIndex:i]);
526 [invocation setTarget:object];
528 [invocation getReturnValue:&item.key];
530 item.key = imp(object, selector, object);
534 RadixSort_(self, count, swap);
537 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
538 size_t count([self count]);
539 struct RadixItem_ *swap(new RadixItem_[count * 2]);
541 for (size_t i(0); i != count; ++i) {
542 RadixItem_ &item(swap[i]);
545 id object([self objectAtIndex:i]);
546 item.key = function(object, argument);
549 RadixSort_(self, count, swap);
554 /* Insertion Sort {{{ */
556 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
557 const char *ptr = (const char *)list;
559 CFIndex half = count / 2;
560 const char *probe = ptr + elementSize * half;
561 CFComparisonResult cr = comparator(element, probe, context);
562 if (0 == cr) return (probe - (const char *)list) / elementSize;
563 ptr = (cr < 0) ? ptr : probe + elementSize;
564 count = (cr < 0) ? half : (half + (count & 1) - 1);
566 return (ptr - (const char *)list) / elementSize;
569 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
570 const char *ptr = (const char *)list;
572 CFIndex half = count / 2;
573 const char *probe = ptr + elementSize * half;
574 CFComparisonResult cr = comparator(element, probe, context);
575 if (0 == cr) return (probe - (const char *)list) / elementSize;
576 ptr = (cr < 0) ? ptr : probe + elementSize;
577 count = (cr < 0) ? half : (half + (count & 1) - 1);
579 return (ptr - (const char *)list) / elementSize;
582 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
583 if (range.length == 0)
585 const void **values(new const void *[range.length]);
586 CFArrayGetValues(array, range, values);
588 #if HistogramInsertionSort
589 uint32_t total(0), *offsets(new uint32_t[range.length]);
592 for (CFIndex index(1); index != range.length; ++index) {
593 const void *value(values[index]);
594 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
595 CFIndex correct(index);
596 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
599 if (correct != index) {
600 size_t offset(index - correct);
601 #if HistogramInsertionSort
605 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
607 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
608 values[correct] = value;
612 CFArrayReplaceValues(array, range, values, range.length);
615 #if HistogramInsertionSort
616 for (CFIndex index(0); index != range.length; ++index)
617 if (offsets[index] != 0)
618 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
619 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
626 /* Apple Bug Fixes {{{ */
627 @implementation UIWebDocumentView (Cydia)
629 - (void) _setScrollerOffset:(CGPoint)offset {
630 UIScroller *scroller([self _scroller]);
632 CGSize size([scroller contentSize]);
633 CGSize bounds([scroller bounds].size);
636 max.x = size.width - bounds.width;
637 max.y = size.height - bounds.height;
645 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
646 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
648 [scroller setOffset:offset];
655 kUIControlEventMouseDown = 1 << 0,
656 kUIControlEventMouseMovedInside = 1 << 2, // mouse moved inside control target
657 kUIControlEventMouseMovedOutside = 1 << 3, // mouse moved outside control target
658 kUIControlEventMouseUpInside = 1 << 6, // mouse up inside control target
659 kUIControlEventMouseUpOutside = 1 << 7, // mouse up outside control target
660 kUIControlAllEvents = (kUIControlEventMouseDown | kUIControlEventMouseMovedInside | kUIControlEventMouseMovedOutside | kUIControlEventMouseUpInside | kUIControlEventMouseUpOutside)
661 } UIControlEventMasks;
663 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
664 size_t length([self length] - state->state);
667 else if (length > count)
669 for (size_t i(0); i != length; ++i)
670 objects[i] = [self item:state->state++];
671 state->itemsPtr = objects;
672 state->mutationsPtr = (unsigned long *) self;
676 @interface NSString (UIKit)
677 - (NSString *) stringByAddingPercentEscapes;
678 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
681 @interface NSString (Cydia)
682 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
683 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
684 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
685 - (NSComparisonResult) compareByPath:(NSString *)other;
686 - (NSString *) stringByCachingURLWithCurrentCDN;
687 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
690 @implementation NSString (Cydia)
692 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
693 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
696 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
697 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
698 memcpy(data, bytes, length);
699 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
702 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
703 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
706 - (NSComparisonResult) compareByPath:(NSString *)other {
707 NSString *prefix = [self commonPrefixWithString:other options:0];
708 size_t length = [prefix length];
710 NSRange lrange = NSMakeRange(length, [self length] - length);
711 NSRange rrange = NSMakeRange(length, [other length] - length);
713 lrange = [self rangeOfString:@"/" options:0 range:lrange];
714 rrange = [other rangeOfString:@"/" options:0 range:rrange];
716 NSComparisonResult value;
718 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
719 value = NSOrderedSame;
720 else if (lrange.location == NSNotFound)
721 value = NSOrderedAscending;
722 else if (rrange.location == NSNotFound)
723 value = NSOrderedDescending;
725 value = NSOrderedSame;
727 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
728 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
729 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
730 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
732 NSComparisonResult result = [lpath compare:rpath];
733 return result == NSOrderedSame ? value : result;
736 - (NSString *) stringByCachingURLWithCurrentCDN {
738 stringByReplacingOccurrencesOfString:@"://"
739 withString:@"://ne.edgecastcdn.net/8003A4/"
741 /* XXX: this is somewhat inaccurate */
742 range:NSMakeRange(0, 10)
746 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
747 return [(id)CFURLCreateStringByAddingPercentEscapes(
752 kCFStringEncodingUTF8
764 _finline void clear_() {
765 if (cache_ != NULL) {
772 _finline bool empty() const {
776 _finline size_t size() const {
780 _finline char *data() const {
784 _finline void clear() {
789 _finline CYString() :
796 _finline ~CYString() {
800 void operator =(const CYString &rhs) {
804 if (rhs.cache_ == nil)
807 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
810 void set(apr_pool_t *pool, const char *data, size_t size) {
816 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
817 memcpy(temp, data, size);
824 _finline void set(apr_pool_t *pool, const char *data) {
825 set(pool, data, data == NULL ? 0 : strlen(data));
828 _finline void set(apr_pool_t *pool, const std::string &rhs) {
829 set(pool, rhs.data(), rhs.size());
832 bool operator ==(const CYString &rhs) const {
833 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
836 operator CFStringRef() {
837 if (cache_ == NULL) {
840 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
844 _finline operator id() {
845 return (NSString *) static_cast<CFStringRef>(*this);
850 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
853 struct NSStringMapHash :
854 std::unary_function<NSString *, size_t>
856 _finline size_t operator ()(NSString *value) const {
857 return CFStringHashNSString((CFStringRef) value);
861 struct NSStringMapLess :
862 std::binary_function<NSString *, NSString *, bool>
864 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
865 return [lhs compare:rhs] == NSOrderedAscending;
869 struct NSStringMapEqual :
870 std::binary_function<NSString *, NSString *, bool>
872 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
873 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
874 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
875 //[lhs isEqualToString:rhs];
879 /* Perl-Compatible RegEx {{{ */
889 Pcre(const char *regex) :
894 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
897 lprintf("%d:%s\n", offset, error);
901 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
902 matches_ = new int[(capture_ + 1) * 3];
910 NSString *operator [](size_t match) {
911 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
914 bool operator ()(NSString *data) {
915 // XXX: length is for characters, not for bytes
916 return operator ()([data UTF8String], [data length]);
919 bool operator ()(const char *data, size_t size) {
921 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
925 /* Mime Addresses {{{ */
926 @interface Address : NSObject {
932 - (NSString *) address;
934 - (void) setAddress:(NSString *)address;
936 + (Address *) addressWithString:(NSString *)string;
937 - (Address *) initWithString:(NSString *)string;
940 @implementation Address
949 - (NSString *) name {
953 - (NSString *) address {
957 - (void) setAddress:(NSString *)address {
959 [address_ autorelease];
963 address_ = [address retain];
966 + (Address *) addressWithString:(NSString *)string {
967 return [[[Address alloc] initWithString:string] autorelease];
970 + (NSArray *) _attributeKeys {
971 return [NSArray arrayWithObjects:@"address", @"name", nil];
974 - (NSArray *) attributeKeys {
975 return [[self class] _attributeKeys];
978 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
979 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
982 - (Address *) initWithString:(NSString *)string {
983 if ((self = [super init]) != nil) {
984 const char *data = [string UTF8String];
985 size_t size = [string length];
987 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
989 if (address_r(data, size)) {
990 name_ = [address_r[1] retain];
991 address_ = [address_r[2] retain];
993 name_ = [string retain];
1001 /* CoreGraphics Primitives {{{ */
1012 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
1015 Set(space, red, green, blue, alpha);
1020 CGColorRelease(color_);
1027 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1029 float color[] = {red, green, blue, alpha};
1030 color_ = CGColorCreate(space, color);
1033 operator CGColorRef() {
1039 extern "C" void UISetColor(CGColorRef color);
1041 /* Random Global Variables {{{ */
1042 static const int PulseInterval_ = 50000;
1043 static const int ButtonBarHeight_ = 48;
1044 static const float KeyboardTime_ = 0.3f;
1046 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1047 #define NotifyConfig_ "/etc/notify.conf"
1049 static bool Queuing_;
1051 static CGColor Blue_;
1052 static CGColor Blueish_;
1053 static CGColor Black_;
1054 static CGColor Off_;
1055 static CGColor White_;
1056 static CGColor Gray_;
1057 static CGColor Green_;
1058 static CGColor Purple_;
1059 static CGColor Purplish_;
1061 static UIColor *InstallingColor_;
1062 static UIColor *RemovingColor_;
1064 static NSString *App_;
1065 static NSString *Home_;
1066 static BOOL Sounds_Keyboard_;
1068 static BOOL Advanced_;
1069 static BOOL Loaded_;
1070 static BOOL Ignored_;
1072 static UIFont *Font12_;
1073 static UIFont *Font12Bold_;
1074 static UIFont *Font14_;
1075 static UIFont *Font18Bold_;
1076 static UIFont *Font22Bold_;
1078 static const char *Machine_ = NULL;
1079 static const NSString *UniqueID_ = nil;
1080 static const NSString *Build_ = nil;
1081 static const NSString *Product_ = nil;
1082 static const NSString *Safari_ = nil;
1084 CFLocaleRef Locale_;
1085 NSArray *Languages_;
1086 CGColorSpaceRef space_;
1091 static NSDictionary *SectionMap_;
1092 static NSMutableDictionary *Metadata_;
1093 static _transient NSMutableDictionary *Settings_;
1094 static _transient NSString *Role_;
1095 static _transient NSMutableDictionary *Packages_;
1096 static _transient NSMutableDictionary *Sections_;
1097 static _transient NSMutableDictionary *Sources_;
1098 static bool Changed_;
1099 static NSDate *now_;
1102 static NSMutableArray *Documents_;
1105 NSString *GetLastUpdate() {
1106 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1109 return UCLocalize("NEVER_OR_UNKNOWN");
1111 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1112 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1114 CFRelease(formatter);
1116 return [(NSString *) formatted autorelease];
1119 /* Display Helpers {{{ */
1120 inline float Interpolate(float begin, float end, float fraction) {
1121 return (end - begin) * fraction + begin;
1124 /* XXX: localize this! */
1125 NSString *SizeString(double size) {
1126 bool negative = size < 0;
1131 while (size > 1024) {
1136 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1138 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1141 static _finline CFStringRef CFCString(const char *value) {
1142 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1145 const char *StripVersion_(const char *version) {
1146 const char *colon(strchr(version, ':'));
1148 version = colon + 1;
1152 CFStringRef StripVersion(const char *version) {
1153 const char *colon(strchr(version, ':'));
1155 version = colon + 1;
1156 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1158 return CFCString(version);
1161 NSString *LocalizeSection(NSString *section) {
1162 static Pcre title_r("^(.*?) \\((.*)\\)$");
1163 if (title_r(section)) {
1164 NSString *parent(title_r[1]);
1165 NSString *child(title_r[2]);
1167 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1168 LocalizeSection(parent),
1169 LocalizeSection(child)
1173 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1176 NSString *Simplify(NSString *title) {
1177 const char *data = [title UTF8String];
1178 size_t size = [title length];
1180 static Pcre square_r("^\\[(.*)\\]$");
1181 if (square_r(data, size))
1182 return Simplify(square_r[1]);
1184 static Pcre paren_r("^\\((.*)\\)$");
1185 if (paren_r(data, size))
1186 return Simplify(paren_r[1]);
1188 static Pcre title_r("^(.*?) \\((.*)\\)$");
1189 if (title_r(data, size))
1190 return Simplify(title_r[1]);
1196 bool isSectionVisible(NSString *section) {
1197 NSDictionary *metadata([Sections_ objectForKey:section]);
1198 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1199 return hidden == nil || ![hidden boolValue];
1202 /* Delegate Prototypes {{{ */
1206 @interface NSObject (ProgressDelegate)
1209 @implementation NSObject(ProgressDelegate)
1211 - (void) _setProgressError:(NSArray *)args {
1212 [self performSelector:@selector(setProgressError:forPackage:)
1213 withObject:[args objectAtIndex:0]
1214 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1220 @protocol ProgressDelegate
1221 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1222 - (void) setProgressTitle:(NSString *)title;
1223 - (void) setProgressPercent:(float)percent;
1224 - (void) startProgress;
1225 - (void) addProgressOutput:(NSString *)output;
1226 - (bool) isCancelling:(size_t)received;
1229 @protocol ConfigurationDelegate
1230 - (void) repairWithSelector:(SEL)selector;
1231 - (void) setConfigurationData:(NSString *)data;
1236 @protocol CydiaDelegate
1237 - (void) setPackageView:(PackageView *)view;
1238 - (void) clearPackage:(Package *)package;
1239 - (void) installPackage:(Package *)package;
1240 - (void) removePackage:(Package *)package;
1241 - (void) slideUp:(UIActionSheet *)alert;
1242 - (void) distUpgrade;
1243 - (void) updateData;
1245 - (void) askForSettings;
1246 - (UIProgressHUD *) addProgressHUD;
1247 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1248 - (RVPage *) pageForPackage:(NSString *)name;
1249 - (PackageView *) packageView;
1253 /* Status Delegation {{{ */
1255 public pkgAcquireStatus
1258 _transient NSObject<ProgressDelegate> *delegate_;
1266 void setDelegate(id delegate) {
1267 delegate_ = delegate;
1270 virtual bool MediaChange(std::string media, std::string drive) {
1274 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1277 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1278 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1279 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
1282 virtual void Done(pkgAcquire::ItemDesc &item) {
1285 virtual void Fail(pkgAcquire::ItemDesc &item) {
1287 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1288 item.Owner->Status == pkgAcquire::Item::StatDone
1292 std::string &error(item.Owner->ErrorText);
1296 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1297 NSArray *fields([description componentsSeparatedByString:@" "]);
1298 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1300 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1301 withObject:[NSArray arrayWithObjects:
1302 [NSString stringWithUTF8String:error.c_str()],
1309 virtual bool Pulse(pkgAcquire *Owner) {
1310 bool value = pkgAcquireStatus::Pulse(Owner);
1313 double(CurrentBytes + CurrentItems) /
1314 double(TotalBytes + TotalItems)
1317 [delegate_ setProgressPercent:percent];
1318 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1321 virtual void Start() {
1322 [delegate_ startProgress];
1325 virtual void Stop() {
1329 /* Progress Delegation {{{ */
1334 _transient id<ProgressDelegate> delegate_;
1337 virtual void Update() {
1338 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1339 [delegate_ setProgressPercent:(Percent / 100)];*/
1348 void setDelegate(id delegate) {
1349 delegate_ = delegate;
1352 virtual void Done() {
1353 //[delegate_ setProgressPercent:1];
1358 /* Database Interface {{{ */
1359 typedef std::map< unsigned long, _H<Source> > SourceMap;
1361 @interface Database : NSObject {
1367 pkgCacheFile cache_;
1368 pkgDepCache::Policy *policy_;
1369 pkgRecords *records_;
1370 pkgProblemResolver *resolver_;
1371 pkgAcquire *fetcher_;
1373 SPtr<pkgPackageManager> manager_;
1374 pkgSourceList *list_;
1377 NSMutableArray *packages_;
1379 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1388 + (Database *) sharedInstance;
1391 - (void) _readCydia:(NSNumber *)fd;
1392 - (void) _readStatus:(NSNumber *)fd;
1393 - (void) _readOutput:(NSNumber *)fd;
1397 - (Package *) packageWithName:(NSString *)name;
1399 - (pkgCacheFile &) cache;
1400 - (pkgDepCache::Policy *) policy;
1401 - (pkgRecords *) records;
1402 - (pkgProblemResolver *) resolver;
1403 - (pkgAcquire &) fetcher;
1404 - (pkgSourceList &) list;
1405 - (NSArray *) packages;
1406 - (NSArray *) sources;
1407 - (void) reloadData;
1415 - (NSString *) updateWithStatus:(Status &)status;
1417 - (void) setDelegate:(id)delegate;
1418 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1422 /* Source Class {{{ */
1423 @interface Source : NSObject {
1424 CYString depiction_;
1425 CYString description_;
1431 CYString distribution_;
1437 CYString defaultIcon_;
1439 NSDictionary *record_;
1443 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1445 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1447 - (NSString *) depictionForPackage:(NSString *)package;
1448 - (NSString *) supportForPackage:(NSString *)package;
1450 - (NSDictionary *) record;
1454 - (NSString *) distribution;
1455 - (NSString *) type;
1457 - (NSString *) host;
1459 - (NSString *) name;
1460 - (NSString *) description;
1461 - (NSString *) label;
1462 - (NSString *) origin;
1463 - (NSString *) version;
1465 - (NSString *) defaultIcon;
1469 @implementation Source
1473 distribution_.clear();
1476 description_.clear();
1482 defaultIcon_.clear();
1484 if (record_ != nil) {
1500 + (NSArray *) _attributeKeys {
1501 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1504 - (NSArray *) attributeKeys {
1505 return [[self class] _attributeKeys];
1508 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1509 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1512 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1515 trusted_ = index->IsTrusted();
1517 uri_.set(pool, index->GetURI());
1518 distribution_.set(pool, index->GetDist());
1519 type_.set(pool, index->GetType());
1521 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1522 if (dindex != NULL) {
1524 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1527 pkgTagFile tags(&fd);
1529 pkgTagSection section;
1536 {"default-icon", &defaultIcon_},
1537 {"depiction", &depiction_},
1538 {"description", &description_},
1540 {"origin", &origin_},
1541 {"support", &support_},
1542 {"version", &version_},
1545 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1546 const char *start, *end;
1548 if (section.Find(names[i].name_, start, end)) {
1549 CYString &value(*names[i].value_);
1550 value.set(pool, start, end - start);
1556 record_ = [Sources_ objectForKey:[self key]];
1558 record_ = [record_ retain];
1560 host_ = [[[[NSURL URLWithString:uri_] host] lowercaseString] retain];
1563 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1564 if ((self = [super init]) != nil) {
1565 [self setMetaIndex:index inPool:pool];
1569 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1570 NSDictionary *lhr = [self record];
1571 NSDictionary *rhr = [source record];
1574 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1576 NSString *lhs = [self name];
1577 NSString *rhs = [source name];
1579 if ([lhs length] != 0 && [rhs length] != 0) {
1580 unichar lhc = [lhs characterAtIndex:0];
1581 unichar rhc = [rhs characterAtIndex:0];
1583 if (isalpha(lhc) && !isalpha(rhc))
1584 return NSOrderedAscending;
1585 else if (!isalpha(lhc) && isalpha(rhc))
1586 return NSOrderedDescending;
1589 return [lhs compare:rhs options:LaxCompareOptions_];
1592 - (NSString *) depictionForPackage:(NSString *)package {
1593 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1596 - (NSString *) supportForPackage:(NSString *)package {
1597 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1600 - (NSDictionary *) record {
1608 - (NSString *) uri {
1612 - (NSString *) distribution {
1613 return distribution_;
1616 - (NSString *) type {
1620 - (NSString *) key {
1621 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1624 - (NSString *) host {
1628 - (NSString *) name {
1629 return origin_.empty() ? host_ : origin_;
1632 - (NSString *) description {
1633 return description_;
1636 - (NSString *) label {
1637 return label_.empty() ? host_ : label_;
1640 - (NSString *) origin {
1644 - (NSString *) version {
1648 - (NSString *) defaultIcon {
1649 return defaultIcon_;
1654 /* Relationship Class {{{ */
1655 @interface Relationship : NSObject {
1660 - (NSString *) type;
1662 - (NSString *) name;
1666 @implementation Relationship
1674 - (NSString *) type {
1682 - (NSString *) name {
1689 /* Package Class {{{ */
1690 @interface Package : NSObject {
1694 pkgCache::VerIterator version_;
1695 pkgCache::PkgIterator iterator_;
1696 _transient Database *database_;
1697 pkgCache::VerFileIterator file_;
1704 NSString *section$_;
1709 CYString installed_;
1715 CYString depiction_;
1725 NSMutableArray *tags_;
1728 NSArray *relationships_;
1730 NSMutableDictionary *metadata_;
1731 _transient NSDate *firstSeen_;
1732 _transient NSDate *lastSeen_;
1736 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1737 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1739 - (pkgCache::PkgIterator) iterator;
1742 - (NSString *) section;
1743 - (NSString *) simpleSection;
1745 - (NSString *) longSection;
1746 - (NSString *) shortSection;
1750 - (Address *) maintainer;
1752 - (NSString *) longDescription;
1753 - (NSString *) shortDescription;
1756 - (NSMutableDictionary *) metadata;
1758 - (BOOL) subscribed;
1761 - (NSString *) latest;
1762 - (NSString *) installed;
1763 - (BOOL) uninstalled;
1766 - (BOOL) upgradableAndEssential:(BOOL)essential;
1769 - (BOOL) unfiltered;
1773 - (BOOL) halfConfigured;
1774 - (BOOL) halfInstalled;
1776 - (NSString *) mode;
1779 - (NSString *) name;
1781 - (NSString *) homepage;
1782 - (NSString *) depiction;
1783 - (Address *) author;
1785 - (NSString *) support;
1787 - (NSArray *) files;
1788 - (NSArray *) relationships;
1789 - (NSArray *) warnings;
1790 - (NSArray *) applications;
1792 - (Source *) source;
1793 - (NSString *) role;
1795 - (BOOL) matches:(NSString *)text;
1797 - (bool) hasSupportingRole;
1798 - (BOOL) hasTag:(NSString *)tag;
1799 - (NSString *) primaryPurpose;
1800 - (NSArray *) purposes;
1801 - (bool) isCommercial;
1803 - (CYString &) cyname;
1805 - (uint32_t) compareBySection:(NSArray *)sections;
1807 - (uint32_t) compareForChanges;
1812 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1813 - (bool) isInstalledAndVisible:(NSNumber *)number;
1814 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1815 - (bool) isVisibleInSource:(Source *)source;
1819 uint32_t PackageChangesRadix(Package *self, void *) {
1824 uint32_t timestamp : 30;
1825 uint32_t ignored : 1;
1826 uint32_t upgradable : 1;
1830 bool upgradable([self upgradableAndEssential:YES]);
1831 value.bits.upgradable = upgradable ? 1 : 0;
1834 value.bits.timestamp = 0;
1835 value.bits.ignored = [self ignored] ? 0 : 1;
1836 value.bits.upgradable = 1;
1838 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1839 value.bits.ignored = 0;
1840 value.bits.upgradable = 0;
1843 return _not(uint32_t) - value.key;
1846 _finline static void Stifle(uint8_t &value) {
1849 uint32_t PackagePrefixRadix(Package *self, void *context) {
1850 size_t offset(reinterpret_cast<size_t>(context));
1851 CYString &name([self cyname]);
1853 size_t size(name.size());
1856 char *text(name.data());
1859 if (!isdigit(text[0]))
1863 while (size != digits && isdigit(text[digits]))
1873 if (offset == 0 && zeros != 0) {
1874 memset(data, '0', zeros);
1875 memcpy(data + zeros, text, 4 - zeros);
1877 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1878 if (size <= offset - zeros)
1881 text += offset - zeros;
1882 size -= offset - zeros;
1885 memcpy(data, text, 4);
1887 memcpy(data, text, size);
1888 memset(data + size, 0, 4 - size);
1891 for (size_t i(0); i != 4; ++i)
1892 if (isalpha(data[i]))
1897 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1899 /* XXX: ntohl may be more honest */
1900 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1903 CYString &(*PackageName)(Package *self, SEL sel);
1905 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1906 _profile(PackageNameCompare)
1907 CYString &lhi(PackageName(lhs, @selector(cyname)));
1908 CYString &rhi(PackageName(rhs, @selector(cyname)));
1909 CFStringRef lhn(lhi), rhn(rhi);
1911 _profile(PackageNameCompare$NumbersLast)
1912 if (!lhi.empty() && !rhi.empty()) {
1913 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1914 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1915 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1916 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1917 return lha ? NSOrderedAscending : NSOrderedDescending;
1921 CFIndex length = CFStringGetLength(lhn);
1923 _profile(PackageNameCompare$Compare)
1924 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1929 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1930 return PackageNameCompare(*lhs, *rhs, context);
1933 struct PackageNameOrdering :
1934 std::binary_function<Package *, Package *, bool>
1936 _finline bool operator ()(Package *lhs, Package *rhs) const {
1937 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1941 @implementation Package
1943 - (NSString *) description {
1944 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1950 if (section$_ != nil)
1951 [section$_ release];
1956 if (sponsor$_ != nil)
1957 [sponsor$_ release];
1958 if (author$_ != nil)
1965 if (relationships_ != nil)
1966 [relationships_ release];
1967 if (metadata_ != nil)
1968 [metadata_ release];
1973 + (NSString *) webScriptNameForSelector:(SEL)selector {
1974 if (selector == @selector(hasTag:))
1980 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1981 return [self webScriptNameForSelector:selector] == nil;
1984 + (NSArray *) _attributeKeys {
1985 return [NSArray arrayWithObjects:@"applications", @"author", @"depiction", @"longDescription", @"essential", @"homepage", @"icon", @"id", @"installed", @"latest", @"longSection", @"maintainer", @"mode", @"name", @"purposes", @"section", @"shortDescription", @"shortSection", @"simpleSection", @"size", @"source", @"sponsor", @"support", @"warnings", nil];
1988 - (NSArray *) attributeKeys {
1989 return [[self class] _attributeKeys];
1992 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1993 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2003 _profile(Package$parse)
2004 pkgRecords::Parser *parser;
2006 _profile(Package$parse$Lookup)
2007 parser = &[database_ records]->Lookup(file_);
2012 _profile(Package$parse$Find)
2018 {"depiction", &depiction_},
2019 {"homepage", &homepage_},
2020 {"website", &website},
2021 {"support", &support_},
2022 {"sponsor", &sponsor_},
2023 {"author", &author_},
2026 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2027 const char *start, *end;
2029 if (parser->Find(names[i].name_, start, end)) {
2030 CYString &value(*names[i].value_);
2031 _profile(Package$parse$Value)
2032 value.set(pool_, start, end - start);
2038 _profile(Package$parse$Tagline)
2039 const char *start, *end;
2040 if (parser->ShortDesc(start, end)) {
2041 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2044 while (stop != start && stop[-1] == '\r')
2046 tagline_.set(pool_, start, stop - start);
2050 _profile(Package$parse$Retain)
2051 if (!homepage_.empty())
2052 homepage_ = website;
2053 if (homepage_ == depiction_)
2059 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2060 if ((self = [super init]) != nil) {
2061 _profile(Package$initWithVersion)
2062 @synchronized (database) {
2063 era_ = [database era];
2067 iterator_ = version.ParentPkg();
2068 database_ = database;
2070 _profile(Package$initWithVersion$Latest)
2071 latest_ = (NSString *) StripVersion(version_.VerStr());
2074 pkgCache::VerIterator current;
2075 _profile(Package$initWithVersion$Versions)
2076 current = iterator_.CurrentVer();
2078 installed_.set(pool_, StripVersion_(current.VerStr()));
2080 if (!version_.end())
2081 file_ = version_.FileList();
2083 pkgCache &cache([database_ cache]);
2084 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2088 _profile(Package$initWithVersion$Name)
2089 id_.set(pool_, iterator_.Name());
2090 name_.set(pool, iterator_.Display());
2094 _profile(Package$initWithVersion$Source)
2095 source_ = [database_ getSource:file_.File()];
2104 _profile(Package$initWithVersion$Tags)
2105 pkgCache::TagIterator tag(iterator_.TagList());
2107 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2109 const char *name(tag.Name());
2110 [tags_ addObject:(NSString *)CFCString(name)];
2111 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2112 role_ = (NSString *) CFCString(name + 6);
2113 if (visible_ && strncmp(name, "require::", 9) == 0 && (
2118 } while (!tag.end());
2122 bool changed(false);
2123 NSString *key([id_ lowercaseString]);
2125 _profile(Package$initWithVersion$Metadata)
2126 metadata_ = [Packages_ objectForKey:key];
2128 if (metadata_ == nil) {
2131 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2132 firstSeen_, @"FirstSeen",
2133 latest_, @"LastVersion",
2138 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2139 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2141 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2142 subscribed_ = [subscribed boolValue];
2144 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2146 if (firstSeen_ == nil) {
2147 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2148 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2152 if (version == nil) {
2153 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2156 if (![version isEqualToString:latest_]) {
2157 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2159 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2164 metadata_ = [metadata_ retain];
2167 [Packages_ setObject:metadata_ forKey:key];
2172 _profile(Package$initWithVersion$Section)
2173 section_.set(pool_, iterator_.Section());
2176 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2177 visible_ = visible_ && [self hasSupportingRole] && [self unfiltered];
2178 } _end } return self;
2181 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2182 @synchronized ([Database class]) {
2183 pkgCache::VerIterator version;
2185 _profile(Package$packageWithIterator$GetCandidateVer)
2186 version = [database policy]->GetCandidateVer(iterator);
2192 return [[[Package alloc]
2193 initWithVersion:version
2200 - (pkgCache::PkgIterator) iterator {
2204 - (NSString *) section {
2205 if (section$_ == nil) {
2206 if (section_.empty())
2209 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2210 NSString *name(section_);
2213 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2214 if (NSString *rename = [value objectForKey:@"Rename"]) {
2219 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2223 - (NSString *) simpleSection {
2224 if (NSString *section = [self section])
2225 return Simplify(section);
2230 - (NSString *) longSection {
2231 return LocalizeSection([self section]);
2234 - (NSString *) shortSection {
2235 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2238 - (NSString *) uri {
2241 pkgIndexFile *index;
2242 pkgCache::PkgFileIterator file(file_.File());
2243 if (![database_ list].FindIndex(file, index))
2245 return [NSString stringWithUTF8String:iterator_->Path];
2246 //return [NSString stringWithUTF8String:file.Site()];
2247 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2251 - (Address *) maintainer {
2254 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2255 const std::string &maintainer(parser->Maintainer());
2256 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2260 return version_.end() ? 0 : version_->InstalledSize;
2263 - (NSString *) longDescription {
2266 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2267 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2269 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2270 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2271 if ([lines count] < 2)
2274 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2275 for (size_t i(1), e([lines count]); i != e; ++i) {
2276 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2277 [trimmed addObject:trim];
2280 return [trimmed componentsJoinedByString:@"\n"];
2283 - (NSString *) shortDescription {
2288 _profile(Package$index)
2289 CFStringRef name((CFStringRef) [self name]);
2290 if (CFStringGetLength(name) == 0)
2292 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2293 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2295 return toupper(character);
2299 - (NSMutableDictionary *) metadata {
2304 if (subscribed_ && lastSeen_ != nil)
2309 - (BOOL) subscribed {
2314 NSDictionary *metadata([self metadata]);
2315 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2316 return [ignored boolValue];
2321 - (NSString *) latest {
2325 - (NSString *) installed {
2329 - (BOOL) uninstalled {
2330 return installed_.empty();
2334 return !version_.end();
2337 - (BOOL) upgradableAndEssential:(BOOL)essential {
2338 _profile(Package$upgradableAndEssential)
2339 pkgCache::VerIterator current(iterator_.CurrentVer());
2341 return essential && essential_ && visible_;
2343 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2347 - (BOOL) essential {
2352 return [database_ cache][iterator_].InstBroken();
2355 - (BOOL) unfiltered {
2356 NSString *section([self section]);
2357 return section == nil || isSectionVisible(section);
2365 unsigned char current(iterator_->CurrentState);
2366 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2369 - (BOOL) halfConfigured {
2370 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2373 - (BOOL) halfInstalled {
2374 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2378 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2379 return state.Mode != pkgDepCache::ModeKeep;
2382 - (NSString *) mode {
2383 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2385 switch (state.Mode) {
2386 case pkgDepCache::ModeDelete:
2387 if ((state.iFlags & pkgDepCache::Purge) != 0)
2391 case pkgDepCache::ModeKeep:
2392 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2393 return @"REINSTALL";
2394 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2398 case pkgDepCache::ModeInstall:
2399 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2400 return @"REINSTALL";
2401 else*/ switch (state.Status) {
2403 return @"DOWNGRADE";
2409 return @"NEW_INSTALL";
2422 - (NSString *) name {
2423 return name_.empty() ? id_ : name_;
2426 - (UIImage *) icon {
2427 NSString *section = [self simpleSection];
2431 if ([icon_ hasPrefix:@"file:///"])
2432 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2433 if (icon == nil) if (section != nil)
2434 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2435 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2436 if ([dicon hasPrefix:@"file:///"])
2437 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2439 icon = [UIImage applicationImageNamed:@"unknown.png"];
2443 - (NSString *) homepage {
2447 - (NSString *) depiction {
2448 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2451 - (Address *) sponsor {
2452 if (sponsor$_ == nil) {
2453 if (sponsor_.empty())
2455 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2459 - (Address *) author {
2460 if (author$_ == nil) {
2461 if (author_.empty())
2463 author$_ = [[Address addressWithString:author_] retain];
2467 - (NSString *) support {
2468 return !support_.empty() ? support_ : [[self source] supportForPackage:id_];
2471 - (NSArray *) files {
2472 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2473 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2476 fin.open([path UTF8String]);
2481 while (std::getline(fin, line))
2482 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2487 - (NSArray *) relationships {
2488 return relationships_;
2491 - (NSArray *) warnings {
2492 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2493 const char *name(iterator_.Name());
2495 size_t length(strlen(name));
2496 if (length < 2) invalid:
2497 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2498 else for (size_t i(0); i != length; ++i)
2500 /* XXX: technically this is not allowed */
2501 (name[i] < 'A' || name[i] > 'Z') &&
2502 (name[i] < 'a' || name[i] > 'z') &&
2503 (name[i] < '0' || name[i] > '9') &&
2504 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2507 if (strcmp(name, "cydia") != 0) {
2509 bool _private = false;
2512 bool repository = [[self section] isEqualToString:@"Repositories"];
2514 if (NSArray *files = [self files])
2515 for (NSString *file in files)
2516 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2518 else if (!_private && [file isEqualToString:@"/private"])
2520 else if (!stash && [file isEqualToString:@"/var/stash"])
2523 /* XXX: this is not sensitive enough. only some folders are valid. */
2524 if (cydia && !repository)
2525 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2527 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2529 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2532 return [warnings count] == 0 ? nil : warnings;
2535 - (NSArray *) applications {
2536 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2538 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2540 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2541 if (NSArray *files = [self files])
2542 for (NSString *file in files)
2543 if (application_r(file)) {
2544 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2545 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2546 if ([id isEqualToString:me])
2549 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2551 display = application_r[1];
2553 NSString *bundle([file stringByDeletingLastPathComponent]);
2554 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2555 if (icon == nil || [icon length] == 0)
2557 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2559 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2560 [applications addObject:application];
2562 [application addObject:id];
2563 [application addObject:display];
2564 [application addObject:url];
2567 return [applications count] == 0 ? nil : applications;
2570 - (Source *) source {
2572 @synchronized (database_) {
2573 if ([database_ era] != era_ || file_.end())
2576 source_ = [database_ getSource:file_.File()];
2588 - (NSString *) role {
2592 - (BOOL) matches:(NSString *)text {
2598 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2599 if (range.location != NSNotFound)
2602 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2603 if (range.location != NSNotFound)
2606 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2607 if (range.location != NSNotFound)
2613 - (bool) hasSupportingRole {
2616 if ([role_ isEqualToString:@"enduser"])
2618 if ([Role_ isEqualToString:@"User"])
2620 if ([role_ isEqualToString:@"hacker"])
2622 if ([Role_ isEqualToString:@"Hacker"])
2624 if ([role_ isEqualToString:@"developer"])
2626 if ([Role_ isEqualToString:@"Developer"])
2631 - (BOOL) hasTag:(NSString *)tag {
2632 return tags_ == nil ? NO : [tags_ containsObject:tag];
2635 - (NSString *) primaryPurpose {
2636 for (NSString *tag in tags_)
2637 if ([tag hasPrefix:@"purpose::"])
2638 return [tag substringFromIndex:9];
2642 - (NSArray *) purposes {
2643 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2644 for (NSString *tag in tags_)
2645 if ([tag hasPrefix:@"purpose::"])
2646 [purposes addObject:[tag substringFromIndex:9]];
2647 return [purposes count] == 0 ? nil : purposes;
2650 - (bool) isCommercial {
2651 return [self hasTag:@"cydia::commercial"];
2654 - (CYString &) cyname {
2655 return name_.empty() ? id_ : name_;
2658 - (uint32_t) compareBySection:(NSArray *)sections {
2659 NSString *section([self section]);
2660 for (size_t i(0), e([sections count]); i != e; ++i) {
2661 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2665 return _not(uint32_t);
2668 - (uint32_t) compareForChanges {
2673 uint32_t timestamp : 30;
2674 uint32_t ignored : 1;
2675 uint32_t upgradable : 1;
2679 bool upgradable([self upgradableAndEssential:YES]);
2680 value.bits.upgradable = upgradable ? 1 : 0;
2683 value.bits.timestamp = 0;
2684 value.bits.ignored = [self ignored] ? 0 : 1;
2685 value.bits.upgradable = 1;
2687 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2688 value.bits.ignored = 0;
2689 value.bits.upgradable = 0;
2692 return _not(uint32_t) - value.key;
2696 pkgProblemResolver *resolver = [database_ resolver];
2697 resolver->Clear(iterator_);
2698 resolver->Protect(iterator_);
2702 pkgProblemResolver *resolver = [database_ resolver];
2703 resolver->Clear(iterator_);
2704 resolver->Protect(iterator_);
2705 pkgCacheFile &cache([database_ cache]);
2706 cache->MarkInstall(iterator_, false);
2707 pkgDepCache::StateCache &state((*cache)[iterator_]);
2708 if (!state.Install())
2709 cache->SetReInstall(iterator_, true);
2713 pkgProblemResolver *resolver = [database_ resolver];
2714 resolver->Clear(iterator_);
2715 resolver->Protect(iterator_);
2716 resolver->Remove(iterator_);
2717 [database_ cache]->MarkDelete(iterator_, true);
2720 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2721 _profile(Package$isUnfilteredAndSearchedForBy)
2724 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2725 value &= [self unfiltered];
2728 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2729 value &= [self matches:search];
2736 - (bool) isInstalledAndVisible:(NSNumber *)number {
2737 return (![number boolValue] || [self visible]) && ![self uninstalled];
2740 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2741 NSString *section = [self section];
2745 [self uninstalled] && (
2747 section == nil && [name length] == 0 ||
2748 [name isEqualToString:section]
2752 - (bool) isVisibleInSource:(Source *)source {
2753 return [self source] == source && [self visible];
2758 /* Section Class {{{ */
2759 @interface Section : NSObject {
2764 NSString *localized_;
2767 - (NSComparisonResult) compareByLocalized:(Section *)section;
2768 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2769 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2770 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2771 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2772 - (NSString *) name;
2779 - (void) addToCount;
2781 - (void) setCount:(size_t)count;
2782 - (NSString *) localized;
2786 @implementation Section
2790 if (localized_ != nil)
2791 [localized_ release];
2795 - (NSComparisonResult) compareByLocalized:(Section *)section {
2796 NSString *lhs(localized_);
2797 NSString *rhs([section localized]);
2799 /*if ([lhs length] != 0 && [rhs length] != 0) {
2800 unichar lhc = [lhs characterAtIndex:0];
2801 unichar rhc = [rhs characterAtIndex:0];
2803 if (isalpha(lhc) && !isalpha(rhc))
2804 return NSOrderedAscending;
2805 else if (!isalpha(lhc) && isalpha(rhc))
2806 return NSOrderedDescending;
2809 return [lhs compare:rhs options:LaxCompareOptions_];
2812 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2813 if ((self = [self initWithName:name localize:NO]) != nil) {
2814 if (localized != nil)
2815 localized_ = [localized retain];
2819 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2820 return [self initWithName:name row:0 localize:localize];
2823 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2824 if ((self = [super init]) != nil) {
2825 name_ = [name retain];
2829 localized_ = [LocalizeSection(name_) retain];
2833 /* XXX: localize the index thingees */
2834 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2835 if ((self = [super init]) != nil) {
2836 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2842 - (NSString *) name {
2862 - (void) addToCount {
2866 - (void) setCount:(size_t)count {
2870 - (NSString *) localized {
2878 static NSArray *Finishes_;
2880 /* Database Implementation {{{ */
2881 @implementation Database
2883 + (Database *) sharedInstance {
2884 static Database *instance;
2885 if (instance == nil)
2886 instance = [[Database alloc] init];
2896 NSRecycleZone(zone_);
2897 // XXX: malloc_destroy_zone(zone_);
2898 apr_pool_destroy(pool_);
2902 - (void) _readCydia:(NSNumber *)fd { _pooled
2903 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2904 std::istream is(&ib);
2907 static Pcre finish_r("^finish:([^:]*)$");
2909 while (std::getline(is, line)) {
2910 const char *data(line.c_str());
2911 size_t size = line.size();
2912 lprintf("C:%s\n", data);
2914 if (finish_r(data, size)) {
2915 NSString *finish = finish_r[1];
2916 int index = [Finishes_ indexOfObject:finish];
2917 if (index != INT_MAX && index > Finish_)
2925 - (void) _readStatus:(NSNumber *)fd { _pooled
2926 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2927 std::istream is(&ib);
2930 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2931 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2933 while (std::getline(is, line)) {
2934 const char *data(line.c_str());
2935 size_t size = line.size();
2936 lprintf("S:%s\n", data);
2938 if (conffile_r(data, size)) {
2939 [delegate_ setConfigurationData:conffile_r[1]];
2940 } else if (strncmp(data, "status: ", 8) == 0) {
2941 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2942 [delegate_ setProgressTitle:string];
2943 } else if (pmstatus_r(data, size)) {
2944 std::string type([pmstatus_r[1] UTF8String]);
2945 NSString *id = pmstatus_r[2];
2947 float percent([pmstatus_r[3] floatValue]);
2948 [delegate_ setProgressPercent:(percent / 100)];
2950 NSString *string = pmstatus_r[4];
2952 if (type == "pmerror")
2953 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2954 withObject:[NSArray arrayWithObjects:string, id, nil]
2957 else if (type == "pmstatus") {
2958 [delegate_ setProgressTitle:string];
2959 } else if (type == "pmconffile")
2960 [delegate_ setConfigurationData:string];
2961 else _assert(false);
2962 } else _assert(false);
2968 - (void) _readOutput:(NSNumber *)fd { _pooled
2969 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2970 std::istream is(&ib);
2973 while (std::getline(is, line)) {
2974 lprintf("O:%s\n", line.c_str());
2975 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2985 - (Package *) packageWithName:(NSString *)name {
2986 @synchronized ([Database class]) {
2987 if (static_cast<pkgDepCache *>(cache_) == NULL)
2989 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2990 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
2993 - (Database *) init {
2994 if ((self = [super init]) != nil) {
3001 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3002 apr_pool_create(&pool_, NULL);
3004 packages_ = [[NSMutableArray alloc] init];
3008 _assert(pipe(fds) != -1);
3011 _config->Set("APT::Keep-Fds::", cydiafd_);
3012 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3015 detachNewThreadSelector:@selector(_readCydia:)
3017 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3020 _assert(pipe(fds) != -1);
3024 detachNewThreadSelector:@selector(_readStatus:)
3026 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3029 _assert(pipe(fds) != -1);
3030 _assert(dup2(fds[0], 0) != -1);
3031 _assert(close(fds[0]) != -1);
3033 input_ = fdopen(fds[1], "a");
3035 _assert(pipe(fds) != -1);
3036 _assert(dup2(fds[1], 1) != -1);
3037 _assert(close(fds[1]) != -1);
3040 detachNewThreadSelector:@selector(_readOutput:)
3042 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3047 - (pkgCacheFile &) cache {
3051 - (pkgDepCache::Policy *) policy {
3055 - (pkgRecords *) records {
3059 - (pkgProblemResolver *) resolver {
3063 - (pkgAcquire &) fetcher {
3067 - (pkgSourceList &) list {
3071 - (NSArray *) packages {
3075 - (NSArray *) sources {
3076 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3077 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3078 [sources addObject:i->second];
3082 - (NSArray *) issues {
3083 if (cache_->BrokenCount() == 0)
3086 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3088 for (Package *package in packages_) {
3089 if (![package broken])
3091 pkgCache::PkgIterator pkg([package iterator]);
3093 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3094 [entry addObject:[package name]];
3095 [issues addObject:entry];
3097 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3101 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3102 pkgCache::DepIterator start;
3103 pkgCache::DepIterator end;
3104 dep.GlobOr(start, end); // ++dep
3106 if (!cache_->IsImportantDep(end))
3108 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3111 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3112 [entry addObject:failure];
3113 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3115 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3116 if (Package *package = [self packageWithName:name])
3117 name = [package name];
3118 [failure addObject:name];
3120 pkgCache::PkgIterator target(start.TargetPkg());
3121 if (target->ProvidesList != 0)
3122 [failure addObject:@"?"];
3124 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3126 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3127 else if (!cache_[target].CandidateVerIter(cache_).end())
3128 [failure addObject:@"-"];
3129 else if (target->ProvidesList == 0)
3130 [failure addObject:@"!"];
3132 [failure addObject:@"%"];
3136 if (start.TargetVer() != 0)
3137 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3148 - (void) reloadData { _pooled
3149 @synchronized ([Database class]) {
3151 @synchronized (self) {
3155 [packages_ removeAllObjects];
3181 apr_pool_clear(pool_);
3182 NSRecycleZone(zone_);
3184 int chk(creat("/tmp/cydia.chk", 0644));
3189 if (!cache_.Open(progress_, true)) {
3191 if (!_error->PopMessage(error))
3194 lprintf("cache_.Open():[%s]\n", error.c_str());
3196 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3197 [delegate_ repairWithSelector:@selector(configure)];
3198 else if (error == "The package lists or status file could not be parsed or opened.")
3199 [delegate_ repairWithSelector:@selector(update)];
3200 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3201 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3202 // else if (error == "The list of sources could not be read.")
3203 else _assert(false);
3209 unlink("/tmp/cydia.chk");
3211 now_ = [[NSDate date] retain];
3213 policy_ = new pkgDepCache::Policy();
3214 records_ = new pkgRecords(cache_);
3215 resolver_ = new pkgProblemResolver(cache_);
3216 fetcher_ = new pkgAcquire(&status_);
3219 list_ = new pkgSourceList();
3220 _assert(list_->ReadMainList());
3222 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3223 _assert(pkgApplyStatus(cache_));
3225 if (cache_->BrokenCount() != 0) {
3226 _assert(pkgFixBroken(cache_));
3227 _assert(cache_->BrokenCount() == 0);
3228 _assert(pkgMinimizeUpgrade(cache_));
3233 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3234 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3235 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3236 // XXX: this could be more intelligent
3237 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3238 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3240 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3247 /*std::vector<Package *> packages;
3248 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3249 [packages_ release];
3254 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3255 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3256 //packages.push_back(package);
3257 [packages_ addObject:package];
3261 /*if (packages.empty())
3262 packages_ = [[NSArray alloc] init];
3264 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3267 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3268 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3269 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3277 /*if (!packages.empty())
3278 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3279 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3281 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3283 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3285 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3291 - (void) configure {
3292 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3293 system([dpkg UTF8String]);
3301 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3302 _assert(!_error->PendingError());
3305 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3308 public pkgArchiveCleaner
3311 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3316 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3318 while (_error->PopMessage(error))
3319 lprintf("ArchiveCleaner: %s\n", error.c_str());
3324 fetcher_->Shutdown();
3326 pkgRecords records(cache_);
3328 lock_ = new FileFd();
3329 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3330 _assert(!_error->PendingError());
3333 // XXX: explain this with an error message
3334 _assert(list.ReadMainList());
3336 manager_ = (_system->CreatePM(cache_));
3337 _assert(manager_->GetArchives(fetcher_, &list, &records));
3338 _assert(!_error->PendingError());
3342 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3344 _assert(list.ReadMainList());
3345 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3346 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3349 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3354 bool failed = false;
3355 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3356 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3358 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3361 std::string uri = (*item)->DescURI();
3362 std::string error = (*item)->ErrorText;
3364 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3367 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3368 withObject:[NSArray arrayWithObjects:
3369 [NSString stringWithUTF8String:error.c_str()],
3381 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3383 if (_error->PendingError()) {
3388 if (result == pkgPackageManager::Failed) {
3393 if (result != pkgPackageManager::Completed) {
3398 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3400 _assert(list.ReadMainList());
3401 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3402 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3405 if (![before isEqualToArray:after])
3410 _assert(pkgDistUpgrade(cache_));
3414 [self updateWithStatus:status_];
3417 - (NSString *) updateWithStatus:(Status &)status {
3419 _assert(list.ReadMainList());
3422 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3424 if (_error->PendingError()) {
3426 if (!_error->PopMessage(error))
3429 return [NSString stringWithUTF8String:error.c_str()];
3432 pkgAcquire fetcher(&status);
3433 _assert(list.GetIndexes(&fetcher));
3435 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3436 bool failed = false;
3437 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3438 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3439 (*item)->Finished();
3443 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3444 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3445 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3448 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3455 - (void) setDelegate:(id)delegate {
3456 delegate_ = delegate;
3457 status_.setDelegate(delegate);
3458 progress_.setDelegate(delegate);
3461 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3462 SourceMap::const_iterator i(sources_.find(file->ID));
3463 return i == sources_.end() ? nil : i->second;
3469 /* PopUp Windows {{{ */
3470 @interface PopUpView : UIView {
3471 _transient id delegate_;
3472 UITransitionView *transition_;
3477 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3481 @implementation PopUpView
3484 [transition_ setDelegate:nil];
3485 [transition_ release];
3491 [transition_ transition:UITransitionPushFromTop toView:nil];
3494 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3495 if (from != nil && to == nil)
3496 [self removeFromSuperview];
3499 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3500 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3501 delegate_ = delegate;
3503 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3504 [self addSubview:transition_];
3506 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3508 [view addSubview:self];
3510 [transition_ setDelegate:self];
3512 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3513 [transition_ transition:UITransitionNone toView:blank];
3514 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3521 /* Confirmation View {{{ */
3522 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3523 if (!iterator.end())
3524 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3525 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3527 pkgCache::PkgIterator package(dep.TargetPkg());
3530 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3537 /* Web Scripting {{{ */
3538 @interface CydiaObject : NSObject {
3542 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3545 @implementation CydiaObject
3548 [indirect_ release];
3552 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3553 if ((self = [super init]) != nil) {
3554 indirect_ = [indirect retain];
3558 + (NSArray *) _attributeKeys {
3559 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3562 - (NSArray *) attributeKeys {
3563 return [[self class] _attributeKeys];
3566 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3567 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3570 - (NSString *) device {
3571 return [[UIDevice currentDevice] uniqueIdentifier];
3574 #if 0 // XXX: implement!
3575 - (NSString *) mac {
3576 if (![indirect_ promptForSensitive:@"Mac Address"])
3580 - (NSString *) serial {
3581 if (![indirect_ promptForSensitive:@"Serial #"])
3585 - (NSString *) firewire {
3586 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3590 - (NSString *) imei {
3591 if (![indirect_ promptForSensitive:@"IMEI"])
3596 + (NSString *) webScriptNameForSelector:(SEL)selector {
3597 if (selector == @selector(close))
3599 else if (selector == @selector(getPackageById:))
3600 return @"getPackageById";
3601 else if (selector == @selector(setAutoPopup:))
3602 return @"setAutoPopup";
3603 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3604 return @"setButtonImage";
3605 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3606 return @"setButtonTitle";
3607 else if (selector == @selector(setFinishHook:))
3608 return @"setFinishHook";
3609 else if (selector == @selector(setPopupHook:))
3610 return @"setPopupHook";
3611 else if (selector == @selector(setSpecial:))
3612 return @"setSpecial";
3613 else if (selector == @selector(setViewportWidth:))
3614 return @"setViewportWidth";
3615 else if (selector == @selector(supports:))
3617 else if (selector == @selector(stringWithFormat:arguments:))
3619 else if (selector == @selector(localizedStringForKey:value:table:))
3621 else if (selector == @selector(du:))
3623 else if (selector == @selector(statfs:))
3629 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3630 return [self webScriptNameForSelector:selector] == nil;
3633 - (BOOL) supports:(NSString *)feature {
3634 return [feature isEqualToString:@"window.open"];
3637 - (Package *) getPackageById:(NSString *)id {
3638 Package *package([[Database sharedInstance] packageWithName:id]);
3643 - (NSArray *) statfs:(NSString *)path {
3646 if (path == nil || statfs([path UTF8String], &stat) == -1)
3649 return [NSArray arrayWithObjects:
3650 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3651 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3652 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3656 - (NSNumber *) du:(NSString *)path {
3657 NSNumber *value(nil);
3660 _assert(pipe(fds) != -1);
3662 pid_t pid(ExecFork());
3664 _assert(dup2(fds[1], 1) != -1);
3665 _assert(close(fds[0]) != -1);
3666 _assert(close(fds[1]) != -1);
3667 /* XXX: this should probably not use du */
3668 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3673 _assert(close(fds[1]) != -1);
3675 if (FILE *du = fdopen(fds[0], "r")) {
3677 while (fgets(line, sizeof(line), du) != NULL) {
3678 size_t length(strlen(line));
3679 while (length != 0 && line[length - 1] == '\n')
3680 line[--length] = '\0';
3681 if (char *tab = strchr(line, '\t')) {
3683 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3688 } else _assert(close(fds[0]));
3692 if (waitpid(pid, &status, 0) == -1)
3695 else _assert(false);
3704 - (void) setAutoPopup:(BOOL)popup {
3705 [indirect_ setAutoPopup:popup];
3708 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3709 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3712 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3713 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3716 - (void) setSpecial:(id)function {
3717 [indirect_ setSpecial:function];
3720 - (void) setFinishHook:(id)function {
3721 [indirect_ setFinishHook:function];
3724 - (void) setPopupHook:(id)function {
3725 [indirect_ setPopupHook:function];
3728 - (void) setViewportWidth:(float)width {
3729 [indirect_ setViewportWidth:width];
3732 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3733 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3734 unsigned count([arguments count]);
3736 for (unsigned i(0); i != count; ++i)
3737 values[i] = [arguments objectAtIndex:i];
3738 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3741 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3742 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3744 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3746 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3752 @interface CydiaBrowserView : BrowserView {
3753 CydiaObject *cydia_;
3758 @implementation CydiaBrowserView
3765 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3766 [super webView:sender didClearWindowObject:window forFrame:frame];
3767 [window setValue:cydia_ forKey:@"cydia"];
3770 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3771 NSMutableURLRequest *copy = [request mutableCopy];
3773 if (Machine_ != NULL)
3774 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3775 if (UniqueID_ != nil)
3776 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
3779 [copy setValue:Role_ forHTTPHeaderField:@"X-Role"];
3784 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
3785 if ((self = [super initWithBook:book forWidth:width ofClass:[CydiaBrowserView class]]) != nil) {
3786 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3788 WebView *webview([webview_ webView]);
3790 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3791 NSString *application = package == nil ? @"Cydia" : [NSString
3792 stringWithFormat:@"Cydia/%@",
3796 if (Product_ != nil)
3797 application = [NSString stringWithFormat:@"%@ Version/%@", application, Product_];
3799 application = [NSString stringWithFormat:@"%@ Mobile/%@", application, Build_];
3801 application = [NSString stringWithFormat:@"%@ Safari/%@", application, Safari_];
3803 [webview setApplicationNameForUserAgent:application];
3809 @protocol ConfirmationViewDelegate
3815 @interface ConfirmationView : CydiaBrowserView {
3816 _transient Database *database_;
3817 UIActionSheet *essential_;
3824 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3828 @implementation ConfirmationView
3835 if (essential_ != nil)
3836 [essential_ release];
3842 [book_ popFromSuperviewAnimated:YES];
3845 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3846 NSString *context([sheet context]);
3848 if ([context isEqualToString:@"remove"]) {
3856 [delegate_ confirm];
3863 } else if ([context isEqualToString:@"unable"]) {
3867 [super alertSheet:sheet buttonClicked:button];
3870 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3871 [super webView:sender didClearWindowObject:window forFrame:frame];
3872 [window setValue:changes_ forKey:@"changes"];
3873 [window setValue:issues_ forKey:@"issues"];
3874 [window setValue:sizes_ forKey:@"sizes"];
3877 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3878 if ((self = [super initWithBook:book]) != nil) {
3879 database_ = database;
3881 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3882 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3883 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3884 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3885 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3889 pkgDepCache::Policy *policy([database_ policy]);
3891 pkgCacheFile &cache([database_ cache]);
3892 NSArray *packages = [database_ packages];
3893 for (Package *package in packages) {
3894 pkgCache::PkgIterator iterator = [package iterator];
3895 pkgDepCache::StateCache &state(cache[iterator]);
3897 NSString *name([package name]);
3899 if (state.NewInstall())
3900 [installing addObject:name];
3901 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3902 [reinstalling addObject:name];
3903 else if (state.Upgrade())
3904 [upgrading addObject:name];
3905 else if (state.Downgrade())
3906 [downgrading addObject:name];
3907 else if (state.Delete()) {
3908 if ([package essential])
3910 [removing addObject:name];
3913 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3914 substrate_ |= DepSubstrate(iterator.CurrentVer());
3919 else if (Advanced_ || true) {
3920 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
3922 essential_ = [[UIActionSheet alloc]
3923 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
3924 buttons:[NSArray arrayWithObjects:
3925 [NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")],
3926 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
3928 defaultButtonIndex:0
3934 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3936 [essential_ setBodyText:UCLocalize("REMOVING_ESSENTIALS_EX")];
3938 essential_ = [[UIActionSheet alloc]
3939 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
3940 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
3941 defaultButtonIndex:0
3946 [essential_ setBodyText:UCLocalize("UNABLE_TO_COMPLY_EX")];
3949 changes_ = [[NSArray alloc] initWithObjects:
3957 issues_ = [database_ issues];
3959 issues_ = [issues_ retain];
3961 sizes_ = [[NSArray alloc] initWithObjects:
3962 SizeString([database_ fetcher].FetchNeeded()),
3963 SizeString([database_ fetcher].PartialPresent()),
3964 SizeString([database_ cache]->UsrSize()),
3967 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3971 - (NSString *) backButtonTitle {
3972 return UCLocalize("CONFIRM");
3975 - (NSString *) leftButtonTitle {
3976 return [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")];
3979 - (id) rightButtonTitle {
3980 return issues_ != nil ? nil : [super rightButtonTitle];
3983 - (id) _rightButtonTitle {
3984 #if AlwaysReload || IgnoreInstall
3985 return [super _rightButtonTitle];
3987 return UCLocalize("CONFIRM");
3991 - (void) _leftButtonClicked {
3996 - (void) _rightButtonClicked {
3998 return [super _rightButtonClicked];
4000 if (essential_ != nil)
4001 [essential_ popupAlertAnimated:YES];
4005 [delegate_ confirm];
4013 /* Progress Data {{{ */
4014 @interface ProgressData : NSObject {
4020 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4027 @implementation ProgressData
4029 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4030 if ((self = [super init]) != nil) {
4031 selector_ = selector;
4051 /* Progress View {{{ */
4052 @interface ProgressView : UIView <
4053 ConfigurationDelegate,
4056 _transient Database *database_;
4058 UIView *background_;
4059 UITransitionView *transition_;
4061 UINavigationBar *navbar_;
4062 UIProgressBar *progress_;
4063 UITextView *output_;
4064 UITextLabel *status_;
4065 UIPushButton *close_;
4068 SHA1SumValue springlist_;
4069 SHA1SumValue notifyconf_;
4070 SHA1SumValue sandplate_;
4073 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
4075 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
4076 - (void) setContentView:(UIView *)view;
4079 - (void) _retachThread;
4080 - (void) _detachNewThreadData:(ProgressData *)data;
4081 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4087 @protocol ProgressViewDelegate
4088 - (void) progressViewIsComplete:(ProgressView *)sender;
4091 @implementation ProgressView
4094 [transition_ setDelegate:nil];
4095 [navbar_ setDelegate:nil];
4098 if (background_ != nil)
4099 [background_ release];
4100 [transition_ release];
4103 [progress_ release];
4110 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
4111 if (bootstrap_ && from == overlay_ && to == view_)
4115 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
4116 if ((self = [super initWithFrame:frame]) != nil) {
4117 database_ = database;
4118 delegate_ = delegate;
4120 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
4121 [transition_ setDelegate:self];
4123 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
4126 [overlay_ setBackgroundColor:[UIColor blackColor]];
4128 background_ = [[UIView alloc] initWithFrame:[self bounds]];
4129 [background_ setBackgroundColor:[UIColor blackColor]];
4130 [self addSubview:background_];
4133 [self addSubview:transition_];
4135 CGSize navsize = [UINavigationBar defaultSize];
4136 CGRect navrect = {{0, 0}, navsize};
4138 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
4139 [overlay_ addSubview:navbar_];
4141 [navbar_ setBarStyle:1];
4142 [navbar_ setDelegate:self];
4144 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
4145 [navbar_ pushNavigationItem:navitem];
4147 CGRect bounds = [overlay_ bounds];
4148 CGSize prgsize = [UIProgressBar defaultSize];
4151 (bounds.size.width - prgsize.width) / 2,
4152 bounds.size.height - prgsize.height - 20
4155 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
4156 [progress_ setStyle:0];
4158 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
4160 bounds.size.height - prgsize.height - 50,
4161 bounds.size.width - 20,
4165 [status_ setColor:[UIColor whiteColor]];
4166 [status_ setBackgroundColor:[UIColor clearColor]];
4168 [status_ setCentersHorizontally:YES];
4169 //[status_ setFont:font];
4172 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
4174 navrect.size.height + 20,
4175 bounds.size.width - 20,
4176 bounds.size.height - navsize.height - 62 - navrect.size.height
4180 //[output_ setTextFont:@"Courier New"];
4181 [output_ setTextSize:12];
4183 [output_ setTextColor:[UIColor whiteColor]];
4184 [output_ setBackgroundColor:[UIColor clearColor]];
4186 [output_ setMarginTop:0];
4187 [output_ setAllowsRubberBanding:YES];
4188 [output_ setEditable:NO];
4190 [overlay_ addSubview:output_];
4192 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
4194 bounds.size.height - prgsize.height - 50,
4195 bounds.size.width - 20,
4199 [close_ setAutosizesToFit:NO];
4200 [close_ setDrawsShadow:YES];
4201 [close_ setStretchBackground:YES];
4202 [close_ setEnabled:YES];
4204 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4205 [close_ setTitleFont:bold];
4207 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
4208 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4209 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4213 - (void) setContentView:(UIView *)view {
4214 view_ = [view retain];
4217 - (void) resetView {
4218 [transition_ transition:6 toView:view_];
4221 - (void) _checkError {
4222 if (_error->PendingError()) {
4224 if (!_error->PopMessage(error))
4227 UIActionSheet *sheet = [[[UIActionSheet alloc]
4228 initWithTitle:UCLocalize("ERROR")
4229 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4230 defaultButtonIndex:0
4235 [sheet setBodyText:[NSString stringWithUTF8String:error.c_str()]];
4236 [sheet popupAlertAnimated:YES];
4241 [delegate_ progressViewIsComplete:self];
4245 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4248 MMap mmap(file, MMap::ReadOnly);
4250 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4251 if (!(notifyconf_ == sha1.Result()))
4258 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4261 MMap mmap(file, MMap::ReadOnly);
4263 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4264 if (!(springlist_ == sha1.Result()))
4270 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break;
4271 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4272 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4273 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4274 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4277 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4279 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
4280 [cache autorelease];
4282 NSFileManager *manager = [NSFileManager defaultManager];
4283 NSError *error = nil;
4285 id system = [cache objectForKey:@"System"];
4290 if (stat(Cache_, &info) == -1)
4293 [system removeAllObjects];
4295 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4296 for (NSString *app in apps)
4297 if ([app hasSuffix:@".app"]) {
4298 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4299 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4300 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4302 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4303 [info setObject:path forKey:@"Path"];
4304 [info setObject:@"System" forKey:@"ApplicationType"];
4305 [system addInfoDictionary:info];
4311 [cache writeToFile:@Cache_ atomically:YES];
4313 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
4315 if (chmod(Cache_, info.st_mode) == -1)
4319 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4322 notify_post("com.apple.mobile.application_installed");
4324 [delegate_ setStatusBarShowsProgress:NO];
4327 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4328 NSString *context([sheet context]);
4330 if ([context isEqualToString:@"error"])
4332 else if ([context isEqualToString:@"_error"]) {
4335 } else if ([context isEqualToString:@"conffile"]) {
4336 FILE *input = [database_ input];
4340 fprintf(input, "N\n");
4344 fprintf(input, "Y\n");
4355 - (void) closeButtonPushed {
4364 [delegate_ suspendWithAnimation:YES];
4368 system("launchctl stop com.apple.SpringBoard");
4372 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4381 - (void) _retachThread {
4382 UINavigationItem *item = [navbar_ topItem];
4383 [item setTitle:UCLocalize("COMPLETE")];
4385 [overlay_ addSubview:close_];
4386 [progress_ removeFromSuperview];
4387 [status_ removeFromSuperview];
4392 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4393 [[data target] performSelector:[data selector] withObject:[data object]];
4396 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4399 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4400 UINavigationItem *item = [navbar_ topItem];
4401 [item setTitle:title];
4403 [status_ setText:nil];
4404 [output_ setText:@""];
4405 [progress_ setProgress:0];
4407 [close_ removeFromSuperview];
4408 [overlay_ addSubview:progress_];
4409 [overlay_ addSubview:status_];
4411 [delegate_ setStatusBarShowsProgress:YES];
4416 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4419 MMap mmap(file, MMap::ReadOnly);
4421 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4422 notifyconf_ = sha1.Result();
4428 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4431 MMap mmap(file, MMap::ReadOnly);
4433 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4434 springlist_ = sha1.Result();
4438 [transition_ transition:6 toView:overlay_];
4441 detachNewThreadSelector:@selector(_detachNewThreadData:)
4443 withObject:[[ProgressData alloc]
4444 initWithSelector:selector
4451 - (void) repairWithSelector:(SEL)selector {
4453 detachNewThreadSelector:selector
4456 title:UCLocalize("REPAIRING")
4460 - (void) setConfigurationData:(NSString *)data {
4462 performSelectorOnMainThread:@selector(_setConfigurationData:)
4468 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4469 Package *package = id == nil ? nil : [database_ packageWithName:id];
4471 UIActionSheet *sheet = [[[UIActionSheet alloc]
4472 initWithTitle:(package == nil ? id : [package name])
4473 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4474 defaultButtonIndex:0
4479 [sheet setBodyText:error];
4480 [sheet popupAlertAnimated:YES];
4483 - (void) setProgressTitle:(NSString *)title {
4485 performSelectorOnMainThread:@selector(_setProgressTitle:)
4491 - (void) setProgressPercent:(float)percent {
4493 performSelectorOnMainThread:@selector(_setProgressPercent:)
4494 withObject:[NSNumber numberWithFloat:percent]
4499 - (void) startProgress {
4502 - (void) addProgressOutput:(NSString *)output {
4504 performSelectorOnMainThread:@selector(_addProgressOutput:)
4510 - (bool) isCancelling:(size_t)received {
4514 - (void) _setConfigurationData:(NSString *)data {
4515 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4517 _assert(conffile_r(data));
4519 NSString *ofile = conffile_r[1];
4520 //NSString *nfile = conffile_r[2];
4522 UIActionSheet *sheet = [[[UIActionSheet alloc]
4523 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4524 buttons:[NSArray arrayWithObjects:
4525 UCLocalize("KEEP_OLD_COPY"),
4526 UCLocalize("ACCEPT_NEW_COPY"),
4527 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4529 defaultButtonIndex:0
4534 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4535 [sheet popupAlertAnimated:YES];
4538 - (void) _setProgressTitle:(NSString *)title {
4539 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4540 for (size_t i(0), e([words count]); i != e; ++i) {
4541 NSString *word([words objectAtIndex:i]);
4542 if (Package *package = [database_ packageWithName:word])
4543 [words replaceObjectAtIndex:i withObject:[package name]];
4546 [status_ setText:[words componentsJoinedByString:@" "]];
4549 - (void) _setProgressPercent:(NSNumber *)percent {
4550 [progress_ setProgress:[percent floatValue]];
4553 - (void) _addProgressOutput:(NSString *)output {
4554 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4555 CGSize size = [output_ contentSize];
4556 CGRect rect = {{0, size.height}, {size.width, 0}};
4557 [output_ scrollRectToVisible:rect animated:YES];
4560 - (BOOL) isRunning {
4567 /* Package Cell {{{ */
4568 @interface PackageCell : UITableCell {
4571 NSString *description_;
4578 UITextLabel *status_;
4582 - (PackageCell *) init;
4583 - (void) setPackage:(Package *)package;
4585 + (int) heightForPackage:(Package *)package;
4589 @implementation PackageCell
4591 - (void) clearPackage {
4602 if (description_ != nil) {
4603 [description_ release];
4607 if (source_ != nil) {
4612 if (badge_ != nil) {
4622 [self clearPackage];
4629 - (PackageCell *) init {
4630 if ((self = [super init]) != nil) {
4632 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4633 [status_ setBackgroundColor:[UIColor clearColor]];
4634 [status_ setFont:small];
4639 - (void) setPackage:(Package *)package {
4640 [self clearPackage];
4643 Source *source = [package source];
4645 icon_ = [[package icon] retain];
4646 name_ = [[package name] retain];
4647 description_ = [[package shortDescription] retain];
4648 commercial_ = [package isCommercial];
4650 package_ = [package retain];
4652 NSString *label = nil;
4653 bool trusted = false;
4655 if (source != nil) {
4656 label = [source label];
4657 trusted = [source trusted];
4658 } else if ([[package id] isEqualToString:@"firmware"])
4659 label = UCLocalize("APPLE");
4661 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4663 NSString *from(label);
4665 NSString *section = [package simpleSection];
4666 if (section != nil && ![section isEqualToString:label]) {
4667 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4668 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4671 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4672 source_ = [from retain];
4674 if (NSString *purpose = [package primaryPurpose])
4675 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4676 badge_ = [badge_ retain];
4679 if (NSString *mode = [package mode]) {
4680 [badge_ setImage:[UIImage applicationImageNamed:
4681 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4684 [status_ setText:[NSString stringWithFormat:UCLocalize("QUEUED_FOR"), UCLocalize(mode)]];
4685 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4686 } else if ([package half]) {
4687 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4688 [status_ setText:UCLocalize("PACKAGE_DAMAGED")];
4689 [status_ setColor:[UIColor redColor]];
4691 [badge_ setImage:nil];
4692 [status_ setText:nil];
4699 - (void) drawRect:(CGRect)rect {
4703 if (NSString *mode = [package_ mode]) {
4704 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4705 color = remove ? RemovingColor_ : InstallingColor_;
4707 color = [UIColor whiteColor];
4709 [self setBackgroundColor:color];
4713 [super drawRect:rect];
4716 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4718 CGContextRef context(UIGraphicsGetCurrentContext());
4719 [[self backgroundColor] set];
4721 back.size.height -= 1;
4722 CGContextFillRect(context, back);
4725 [super drawBackgroundInRect:rect withFade:fade];
4728 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4731 rect.size = [icon_ size];
4733 rect.size.width /= 2;
4734 rect.size.height /= 2;
4736 rect.origin.x = 25 - rect.size.width / 2;
4737 rect.origin.y = 25 - rect.size.height / 2;
4739 [icon_ drawInRect:rect];
4742 if (badge_ != nil) {
4743 CGSize size = [badge_ size];
4745 [badge_ drawAtPoint:CGPointMake(
4746 36 - size.width / 2,
4747 36 - size.height / 2
4755 UISetColor(commercial_ ? Purple_ : Black_);
4756 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4757 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4760 UISetColor(commercial_ ? Purplish_ : Gray_);
4761 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4763 [super drawContentInRect:rect selected:selected];
4766 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4768 [super setSelected:selected withFade:fade];
4771 + (int) heightForPackage:(Package *)package {
4777 /* Section Cell {{{ */
4778 @interface SectionCell : UISimpleTableCell {
4783 _UISwitchSlider *switch_;
4788 - (void) setSection:(Section *)section editing:(BOOL)editing;
4792 @implementation SectionCell
4794 - (void) clearSection {
4795 if (section_ != nil) {
4805 if (count_ != nil) {
4812 [self clearSection];
4819 if ((self = [super init]) != nil) {
4820 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4822 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4823 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4827 - (void) onSwitch:(id)sender {
4828 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4829 if (metadata == nil) {
4830 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4831 [Sections_ setObject:metadata forKey:section_];
4835 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4838 - (void) setSection:(Section *)section editing:(BOOL)editing {
4839 if (editing != editing_) {
4841 [switch_ removeFromSuperview];
4843 [self addSubview:switch_];
4847 [self clearSection];
4849 if (section == nil) {
4850 name_ = [UCLocalize("ALL_PACKAGES") retain];
4853 section_ = [section localized];
4854 if (section_ != nil)
4855 section_ = [section_ retain];
4856 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4857 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4860 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4864 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4865 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4872 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4874 CGSize size = [count_ sizeWithFont:Font14_];
4878 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4880 [super drawContentInRect:rect selected:selected];
4886 /* File Table {{{ */
4887 @interface FileTable : RVPage {
4888 _transient Database *database_;
4891 NSMutableArray *files_;
4895 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4896 - (void) setPackage:(Package *)package;
4900 @implementation FileTable
4903 if (package_ != nil)
4912 - (int) numberOfRowsInTable:(UITable *)table {
4913 return files_ == nil ? 0 : [files_ count];
4916 - (float) table:(UITable *)table heightForRow:(int)row {
4920 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4921 if (reusing == nil) {
4922 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4923 UIFont *font = [UIFont systemFontOfSize:16];
4924 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4926 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4930 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4934 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4935 if ((self = [super initWithBook:book]) != nil) {
4936 database_ = database;
4938 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4940 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4941 [self addSubview:list_];
4943 UITableColumn *column = [[[UITableColumn alloc]
4944 initWithTitle:UCLocalize("NAME")
4946 width:[self frame].size.width
4949 [list_ setDataSource:self];
4950 [list_ setSeparatorStyle:1];
4951 [list_ addTableColumn:column];
4952 [list_ setDelegate:self];
4953 [list_ setReusesTableCells:YES];
4957 - (void) setPackage:(Package *)package {
4958 if (package_ != nil) {
4959 [package_ autorelease];
4968 [files_ removeAllObjects];
4970 if (package != nil) {
4971 package_ = [package retain];
4972 name_ = [[package id] retain];
4974 if (NSArray *files = [package files])
4975 [files_ addObjectsFromArray:files];
4977 if ([files_ count] != 0) {
4978 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4979 [files_ removeObjectAtIndex:0];
4980 [files_ sortUsingSelector:@selector(compareByPath:)];
4982 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4983 [stack addObject:@"/"];
4985 for (int i(0), e([files_ count]); i != e; ++i) {
4986 NSString *file = [files_ objectAtIndex:i];
4987 while (![file hasPrefix:[stack lastObject]])
4988 [stack removeLastObject];
4989 NSString *directory = [stack lastObject];
4990 [stack addObject:[file stringByAppendingString:@"/"]];
4991 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4992 ([stack count] - 2) * 3, "",
4993 [file substringFromIndex:[directory length]]
5002 - (void) resetViewAnimated:(BOOL)animated {
5003 [list_ resetViewAnimated:animated];
5006 - (void) reloadData {
5007 [self setPackage:[database_ packageWithName:name_]];
5008 [self reloadButtons];
5011 - (NSString *) title {
5012 return UCLocalize("INSTALLED_FILES");
5015 - (NSString *) backButtonTitle {
5016 return UCLocalize("FILES");
5021 /* Package View {{{ */
5022 @interface PackageView : CydiaBrowserView {
5023 _transient Database *database_;
5027 NSMutableArray *buttons_;
5030 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5031 - (void) setPackage:(Package *)package;
5035 @implementation PackageView
5038 if (package_ != nil)
5047 if ([self retainCount] == 1)
5048 [delegate_ setPackageView:self];
5052 /* XXX: this is not safe at all... localization of /fail/ */
5053 - (void) _clickButtonWithName:(NSString *)name {
5054 if ([name isEqualToString:UCLocalize("CLEAR")])
5055 [delegate_ clearPackage:package_];
5056 else if ([name isEqualToString:UCLocalize("INSTALL")])
5057 [delegate_ installPackage:package_];
5058 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5059 [delegate_ installPackage:package_];
5060 else if ([name isEqualToString:UCLocalize("REMOVE")])
5061 [delegate_ removePackage:package_];
5062 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5063 [delegate_ installPackage:package_];
5064 else _assert(false);
5067 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5068 NSString *context([sheet context]);
5070 if ([context isEqualToString:@"modify"]) {
5071 int count = [buttons_ count];
5072 _assert(count != 0);
5073 _assert(button <= count + 1);
5075 if (count != button - 1)
5076 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
5080 [super alertSheet:sheet buttonClicked:button];
5083 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5084 return [super webView:sender didFinishLoadForFrame:frame];
5087 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5088 [super webView:sender didClearWindowObject:window forFrame:frame];
5089 [window setValue:package_ forKey:@"package"];
5092 - (bool) _allowJavaScriptPanel {
5097 - (void) __rightButtonClicked {
5098 int count = [buttons_ count];
5099 _assert(count != 0);
5102 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5104 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
5105 [buttons addObjectsFromArray:buttons_];
5106 [buttons addObject:UCLocalize("CANCEL")];
5108 [delegate_ slideUp:[[[UIActionSheet alloc]
5111 defaultButtonIndex:([buttons count] - 1)
5118 - (void) _rightButtonClicked {
5120 [super _rightButtonClicked];
5122 [self __rightButtonClicked];
5126 - (id) _rightButtonTitle {
5127 int count = [buttons_ count];
5128 return count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0];
5131 - (NSString *) backButtonTitle {
5135 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5136 if ((self = [super initWithBook:book]) != nil) {
5137 database_ = database;
5138 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5139 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5143 - (void) setPackage:(Package *)package {
5144 if (package_ != nil) {
5145 [package_ autorelease];
5154 [buttons_ removeAllObjects];
5156 if (package != nil) {
5159 package_ = [package retain];
5160 name_ = [[package id] retain];
5161 commercial_ = [package isCommercial];
5163 if ([package_ mode] != nil)
5164 [buttons_ addObject:UCLocalize("CLEAR")];
5165 if ([package_ source] == nil);
5166 else if ([package_ upgradableAndEssential:NO])
5167 [buttons_ addObject:UCLocalize("UPGRADE")];
5168 else if ([package_ uninstalled])
5169 [buttons_ addObject:UCLocalize("INSTALL")];
5171 [buttons_ addObject:UCLocalize("REINSTALL")];
5172 if (![package_ uninstalled])
5173 [buttons_ addObject:UCLocalize("REMOVE")];
5175 if (special_ != NULL) {
5176 CGRect frame([webview_ frame]);
5177 frame.size.width = 320;
5178 frame.size.height = 0;
5179 [webview_ setFrame:frame];
5181 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5184 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5186 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5188 [self setFinishHook:nil];
5189 [self setPopupHook:nil];
5192 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5193 [super callFunction:special_];
5197 [self reloadButtons];
5200 - (bool) isLoading {
5201 return commercial_ ? [super isLoading] : false;
5204 - (void) reloadData {
5205 [self setPackage:[database_ packageWithName:name_]];
5210 /* Package Table {{{ */
5211 @interface PackageTable : RVPage {
5212 _transient Database *database_;
5214 NSMutableArray *packages_;
5215 NSMutableArray *sections_;
5216 UISectionList *list_;
5219 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5221 - (void) setDelegate:(id)delegate;
5223 - (void) reloadData;
5224 - (void) resetCursor;
5226 - (UISectionList *) list;
5228 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5232 @implementation PackageTable
5235 [list_ setDataSource:nil];
5238 [packages_ release];
5239 [sections_ release];
5244 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5245 return [sections_ count];
5248 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5249 return [[sections_ objectAtIndex:section] name];
5252 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5253 return [[sections_ objectAtIndex:section] row];
5256 - (int) numberOfRowsInTable:(UITable *)table {
5257 return [packages_ count];
5260 - (float) table:(UITable *)table heightForRow:(int)row {
5261 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
5264 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
5266 reusing = [[[PackageCell alloc] init] autorelease];
5267 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
5271 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5275 - (void) tableRowSelected:(NSNotification *)notification {
5276 int row = [[notification object] selectedRow];
5280 Package *package = [packages_ objectAtIndex:row];
5281 package = [database_ packageWithName:[package id]];
5282 PackageView *view([delegate_ packageView]);
5283 [view setPackage:package];
5284 [view setDelegate:delegate_];
5285 [book_ pushPage:view];
5288 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5289 if ((self = [super initWithBook:book]) != nil) {
5290 database_ = database;
5291 title_ = [title retain];
5293 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5294 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5296 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
5297 [list_ setDataSource:self];
5299 UITableColumn *column = [[[UITableColumn alloc]
5300 initWithTitle:UCLocalize("NAME")
5302 width:[self frame].size.width
5305 UITable *table = [list_ table];
5306 [table setSeparatorStyle:1];
5307 [table addTableColumn:column];
5308 [table setDelegate:self];
5309 [table setReusesTableCells:YES];
5311 [self addSubview:list_];
5313 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5314 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5318 - (void) setDelegate:(id)delegate {
5319 delegate_ = delegate;
5322 - (bool) hasPackage:(Package *)package {
5326 - (void) reloadData {
5327 NSArray *packages = [database_ packages];
5329 [packages_ removeAllObjects];
5330 [sections_ removeAllObjects];
5332 _profile(PackageTable$reloadData$Filter)
5333 for (Package *package in packages)
5334 if ([self hasPackage:package])
5335 [packages_ addObject:package];
5338 Section *section = nil;
5340 _profile(PackageTable$reloadData$Section)
5341 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5345 _profile(PackageTable$reloadData$Section$Package)
5346 package = [packages_ objectAtIndex:offset];
5347 index = [package index];
5350 if (section == nil || [section index] != index) {
5351 _profile(PackageTable$reloadData$Section$Allocate)
5352 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5355 _profile(PackageTable$reloadData$Section$Add)
5356 [sections_ addObject:section];
5360 [section addToCount];
5364 _profile(PackageTable$reloadData$List)
5369 - (NSString *) title {
5373 - (void) resetViewAnimated:(BOOL)animated {
5374 [list_ resetViewAnimated:animated];
5377 - (void) resetCursor {
5378 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
5381 - (UISectionList *) list {
5385 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5386 [list_ setShouldHideHeaderInShortLists:hide];
5391 /* Filtered Package Table {{{ */
5392 @interface FilteredPackageTable : PackageTable {
5398 - (void) setObject:(id)object;
5400 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5404 @implementation FilteredPackageTable
5412 - (void) setObject:(id)object {
5418 object_ = [object retain];
5421 - (bool) hasPackage:(Package *)package {
5422 _profile(FilteredPackageTable$hasPackage)
5423 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5427 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5428 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5430 object_ = object == nil ? nil : [object retain];
5432 /* XXX: this is an unsafe optimization of doomy hell */
5433 Method method = class_getInstanceMethod([Package class], filter);
5434 _assert(method != NULL);
5435 imp_ = method_getImplementation(method);
5436 _assert(imp_ != NULL);
5445 /* Add Source View {{{ */
5446 @interface AddSourceView : RVPage {
5447 _transient Database *database_;
5450 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5454 @implementation AddSourceView
5456 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5457 if ((self = [super initWithBook:book]) != nil) {
5458 database_ = database;
5464 /* Source Cell {{{ */
5465 @interface SourceCell : UITableCell {
5468 NSString *description_;
5474 - (SourceCell *) initWithSource:(Source *)source;
5478 @implementation SourceCell
5483 [description_ release];
5488 - (SourceCell *) initWithSource:(Source *)source {
5489 if ((self = [super init]) != nil) {
5491 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5493 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5494 icon_ = [icon_ retain];
5496 origin_ = [[source name] retain];
5497 label_ = [[source uri] retain];
5498 description_ = [[source description] retain];
5502 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5504 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5511 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5515 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5519 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5521 [super drawContentInRect:rect selected:selected];
5526 /* Source Table {{{ */
5527 @interface SourceTable : RVPage {
5528 _transient Database *database_;
5529 UISectionList *list_;
5530 NSMutableArray *sources_;
5531 UIActionSheet *alert_;
5535 UIProgressHUD *hud_;
5538 //NSURLConnection *installer_;
5539 NSURLConnection *trivial_bz2_;
5540 NSURLConnection *trivial_gz_;
5541 //NSURLConnection *automatic_;
5546 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5550 @implementation SourceTable
5552 - (void) _deallocConnection:(NSURLConnection *)connection {
5553 if (connection != nil) {
5554 [connection cancel];
5555 //[connection setDelegate:nil];
5556 [connection release];
5561 [[list_ table] setDelegate:nil];
5562 [list_ setDataSource:nil];
5571 //[self _deallocConnection:installer_];
5572 [self _deallocConnection:trivial_gz_];
5573 [self _deallocConnection:trivial_bz2_];
5574 //[self _deallocConnection:automatic_];
5581 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5582 return offset_ == 0 ? 1 : 2;
5585 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5586 switch (section + (offset_ == 0 ? 1 : 0)) {
5587 case 0: return UCLocalize("ENTERED_BY_USER");
5588 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5596 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5597 switch (section + (offset_ == 0 ? 1 : 0)) {
5599 case 1: return offset_;
5607 - (int) numberOfRowsInTable:(UITable *)table {
5608 return [sources_ count];
5611 - (float) table:(UITable *)table heightForRow:(int)row {
5612 Source *source = [sources_ objectAtIndex:row];
5613 return [source description] == nil ? 56 : 73;
5616 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5617 Source *source = [sources_ objectAtIndex:row];
5618 // XXX: weird warning, stupid selectors ;P
5619 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5622 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5626 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5630 - (void) tableRowSelected:(NSNotification*)notification {
5631 UITable *table([list_ table]);
5632 int row([table selectedRow]);
5636 Source *source = [sources_ objectAtIndex:row];
5638 PackageTable *packages = [[[FilteredPackageTable alloc]
5641 title:[source label]
5642 filter:@selector(isVisibleInSource:)
5646 [packages setDelegate:delegate_];
5648 [book_ pushPage:packages];
5651 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5652 Source *source = [sources_ objectAtIndex:row];
5653 return [source record] != nil;
5656 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5657 [[list_ table] setDeleteConfirmationRow:row];
5660 - (void) table:(UITable *)table deleteRow:(int)row {
5661 Source *source = [sources_ objectAtIndex:row];
5662 [Sources_ removeObjectForKey:[source key]];
5663 [delegate_ syncData];
5667 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5670 @"./", @"Distribution",
5671 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5673 [delegate_ syncData];
5676 - (NSString *) getWarning {
5677 NSString *href(href_);
5678 NSRange colon([href rangeOfString:@"://"]);
5679 if (colon.location != NSNotFound)
5680 href = [href substringFromIndex:(colon.location + 3)];
5681 href = [href stringByAddingPercentEscapes];
5682 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5683 href = [href stringByCachingURLWithCurrentCDN];
5685 NSURL *url([NSURL URLWithString:href]);
5687 NSStringEncoding encoding;
5688 NSError *error(nil);
5690 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5691 return [warning length] == 0 ? nil : warning;
5695 - (void) _endConnection:(NSURLConnection *)connection {
5696 NSURLConnection **field = NULL;
5697 if (connection == trivial_bz2_)
5698 field = &trivial_bz2_;
5699 else if (connection == trivial_gz_)
5700 field = &trivial_gz_;
5701 _assert(field != NULL);
5702 [connection release];
5706 trivial_bz2_ == nil &&
5712 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5715 UIActionSheet *sheet = [[[UIActionSheet alloc]
5716 initWithTitle:UCLocalize("SOURCE_WARNING")
5717 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_ANYWAY"), UCLocalize("CANCEL"), nil]
5718 defaultButtonIndex:0
5723 [sheet setNumberOfRows:1];
5725 [sheet setBodyText:warning];
5726 [sheet popupAlertAnimated:YES];
5729 } else if (error_ != nil) {
5730 UIActionSheet *sheet = [[[UIActionSheet alloc]
5731 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5732 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5733 defaultButtonIndex:0
5738 [sheet setBodyText:[error_ localizedDescription]];
5739 [sheet popupAlertAnimated:YES];
5741 UIActionSheet *sheet = [[[UIActionSheet alloc]
5742 initWithTitle:UCLocalize("NOT_REPOSITORY")
5743 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5744 defaultButtonIndex:0
5749 [sheet setBodyText:UCLocalize("NOT_REPOSITORY_EX")];
5750 [sheet popupAlertAnimated:YES];
5753 [delegate_ setStatusBarShowsProgress:NO];
5754 [delegate_ removeProgressHUD:hud_];
5764 if (error_ != nil) {
5771 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5772 switch ([response statusCode]) {
5778 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5779 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5781 error_ = [error retain];
5782 [self _endConnection:connection];
5785 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5786 [self _endConnection:connection];
5789 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5790 NSMutableURLRequest *request = [NSMutableURLRequest
5791 requestWithURL:[NSURL URLWithString:href]
5792 cachePolicy:NSURLRequestUseProtocolCachePolicy
5793 timeoutInterval:20.0
5796 [request setHTTPMethod:method];
5798 if (Machine_ != NULL)
5799 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5800 if (UniqueID_ != nil)
5801 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5804 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5806 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5809 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5810 NSString *context([sheet context]);
5812 if ([context isEqualToString:@"source"]) {
5815 NSString *href = [[sheet textField] text];
5817 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5819 if (![href hasSuffix:@"/"])
5820 href_ = [href stringByAppendingString:@"/"];
5823 href_ = [href_ retain];
5825 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5826 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5827 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5831 hud_ = [[delegate_ addProgressHUD] retain];
5832 [hud_ setText:UCLocalize("VERIFYING_URL")];
5843 } else if ([context isEqualToString:@"trivial"])
5845 else if ([context isEqualToString:@"urlerror"])
5847 else if ([context isEqualToString:@"warning"]) {
5867 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5868 if ((self = [super initWithBook:book]) != nil) {
5869 database_ = database;
5870 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5872 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5873 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5874 [list_ setShouldHideHeaderInShortLists:NO];
5876 [self addSubview:list_];
5877 [list_ setDataSource:self];
5879 UITableColumn *column = [[UITableColumn alloc]
5880 initWithTitle:UCLocalize("NAME")
5882 width:[self frame].size.width
5885 UITable *table = [list_ table];
5886 [table setSeparatorStyle:1];
5887 [table addTableColumn:column];
5888 [table setDelegate:self];
5892 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5893 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5897 - (void) reloadData {
5899 _assert(list.ReadMainList());
5901 [sources_ removeAllObjects];
5902 [sources_ addObjectsFromArray:[database_ sources]];
5904 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5907 int count = [sources_ count];
5908 for (offset_ = 0; offset_ != count; ++offset_) {
5909 Source *source = [sources_ objectAtIndex:offset_];
5910 if ([source record] == nil)
5917 - (void) resetViewAnimated:(BOOL)animated {
5918 [list_ resetViewAnimated:animated];
5921 - (void) _leftButtonClicked {
5922 /*[book_ pushPage:[[[AddSourceView alloc]
5927 UIActionSheet *sheet = [[[UIActionSheet alloc]
5928 initWithTitle:UCLocalize("ENTER_APT_URL")
5929 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_SOURCE"), UCLocalize("CANCEL"), nil]
5930 defaultButtonIndex:0
5935 [sheet setNumberOfRows:1];
5937 [sheet addTextFieldWithValue:@"http://" label:@""];
5939 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5940 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5941 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5942 [traits setKeyboardType:UIKeyboardTypeURL];
5943 // XXX: UIReturnKeyDone
5944 [traits setReturnKeyType:UIReturnKeyNext];
5946 [sheet popupAlertAnimated:YES];
5949 - (void) _rightButtonClicked {
5950 UITable *table = [list_ table];
5951 BOOL editing = [table isRowDeletionEnabled];
5952 [table enableRowDeletion:!editing animated:YES];
5953 [book_ reloadButtonsForPage:self];
5956 - (NSString *) title {
5957 return UCLocalize("SOURCES");
5960 - (NSString *) leftButtonTitle {
5961 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("ADD") : nil;
5964 - (id) rightButtonTitle {
5965 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("DONE") : UCLocalize("EDIT");
5968 - (UINavigationButtonStyle) rightButtonStyle {
5969 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5975 /* Installed View {{{ */
5976 @interface InstalledView : RVPage {
5977 _transient Database *database_;
5978 FilteredPackageTable *packages_;
5982 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5986 @implementation InstalledView
5989 [packages_ release];
5993 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5994 if ((self = [super initWithBook:book]) != nil) {
5995 database_ = database;
5997 packages_ = [[FilteredPackageTable alloc]
6001 filter:@selector(isInstalledAndVisible:)
6002 with:[NSNumber numberWithBool:YES]
6005 [self addSubview:packages_];
6007 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6008 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6012 - (void) resetViewAnimated:(BOOL)animated {
6013 [packages_ resetViewAnimated:animated];
6016 - (void) reloadData {
6017 [packages_ reloadData];
6020 - (void) _rightButtonClicked {
6021 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6022 [packages_ reloadData];
6024 [book_ reloadButtonsForPage:self];
6027 - (NSString *) title {
6028 return UCLocalize("INSTALLED");
6031 - (NSString *) backButtonTitle {
6032 return UCLocalize("PACKAGES");
6035 - (id) rightButtonTitle {
6036 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
6039 - (UINavigationButtonStyle) rightButtonStyle {
6040 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6043 - (void) setDelegate:(id)delegate {
6044 [super setDelegate:delegate];
6045 [packages_ setDelegate:delegate];
6052 @interface HomeView : CydiaBrowserView {
6057 @implementation HomeView
6059 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6060 NSString *context([sheet context]);
6062 if ([context isEqualToString:@"about"])
6065 [super alertSheet:sheet buttonClicked:button];
6068 - (void) _leftButtonClicked {
6069 UIActionSheet *sheet = [[[UIActionSheet alloc]
6070 initWithTitle:UCLocalize("ABOUT_CYDIA")
6071 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
6072 defaultButtonIndex:0
6078 @"Copyright (C) 2008-2009\n"
6079 "Jay Freeman (saurik)\n"
6080 "saurik@saurik.com\n"
6081 "http://www.saurik.com/\n"
6084 "http://www.theokorigroup.com/\n"
6086 "College of Creative Studies,\n"
6087 "University of California,\n"
6089 "http://www.ccs.ucsb.edu/"
6092 [sheet popupAlertAnimated:YES];
6095 - (NSString *) leftButtonTitle {
6096 return UCLocalize("ABOUT");
6101 /* Manage View {{{ */
6102 @interface ManageView : CydiaBrowserView {
6107 @implementation ManageView
6109 - (NSString *) title {
6110 return UCLocalize("MANAGE");
6113 - (void) _leftButtonClicked {
6114 [delegate_ askForSettings];
6117 - (NSString *) leftButtonTitle {
6118 return UCLocalize("SETTINGS");
6122 - (id) _rightButtonTitle {
6123 return Queuing_ ? UCLocalize("QUEUE") : nil;
6126 - (UINavigationButtonStyle) rightButtonStyle {
6127 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6130 - (void) _rightButtonClicked {
6135 - (bool) isLoading {
6142 /* Cydia Book {{{ */
6143 @interface CYBook : RVBook <
6146 _transient Database *database_;
6147 UINavigationBar *overlay_;
6148 UINavigationBar *underlay_;
6149 UIProgressIndicator *indicator_;
6150 UITextLabel *prompt_;
6151 UIProgressBar *progress_;
6152 UINavigationButton *cancel_;
6156 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6162 @implementation CYBook
6166 [indicator_ release];
6168 [progress_ release];
6173 - (NSString *) getTitleForPage:(RVPage *)page {
6174 return [super getTitleForPage:page];
6182 [UIView beginAnimations:nil context:NULL];
6184 CGRect ovrframe = [overlay_ frame];
6185 ovrframe.origin.y = 0;
6186 [overlay_ setFrame:ovrframe];
6188 CGRect barframe = [navbar_ frame];
6189 barframe.origin.y += ovrframe.size.height;
6190 [navbar_ setFrame:barframe];
6192 CGRect trnframe = [transition_ frame];
6193 trnframe.origin.y += ovrframe.size.height;
6194 trnframe.size.height -= ovrframe.size.height;
6195 [transition_ setFrame:trnframe];
6197 [UIView endAnimations];
6199 [indicator_ startAnimation];
6200 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6201 [progress_ setProgress:0];
6204 [overlay_ addSubview:cancel_];
6207 detachNewThreadSelector:@selector(_update)
6213 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6214 NSString *context([sheet context]);
6216 if ([context isEqualToString:@"refresh"])
6220 - (void) _update_:(NSString *)error {
6223 [indicator_ stopAnimation];
6225 [UIView beginAnimations:nil context:NULL];
6227 CGRect ovrframe = [overlay_ frame];
6228 ovrframe.origin.y = -ovrframe.size.height;
6229 [overlay_ setFrame:ovrframe];
6231 CGRect barframe = [navbar_ frame];
6232 barframe.origin.y -= ovrframe.size.height;
6233 [navbar_ setFrame:barframe];
6235 CGRect trnframe = [transition_ frame];
6236 trnframe.origin.y -= ovrframe.size.height;
6237 trnframe.size.height += ovrframe.size.height;
6238 [transition_ setFrame:trnframe];
6240 [UIView commitAnimations];
6243 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6245 UIActionSheet *sheet = [[[UIActionSheet alloc]
6246 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6247 buttons:[NSArray arrayWithObjects:
6250 defaultButtonIndex:0
6255 [sheet setBodyText:error];
6256 [sheet popupAlertAnimated:YES];
6258 [self reloadButtons];
6262 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6263 if ((self = [super initWithFrame:frame]) != nil) {
6264 database_ = database;
6266 CGRect ovrrect = [navbar_ bounds];
6267 ovrrect.size.height = [UINavigationBar defaultSize].height;
6268 ovrrect.origin.y = -ovrrect.size.height;
6270 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6271 [self addSubview:overlay_];
6273 ovrrect.origin.y = frame.size.height;
6274 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6275 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6276 [self addSubview:underlay_];
6278 [overlay_ setBarStyle:1];
6279 [underlay_ setBarStyle:1];
6281 int barstyle = [overlay_ _barStyle:NO];
6282 bool ugly = barstyle == 0;
6284 UIProgressIndicatorStyle style = ugly ?
6285 UIProgressIndicatorStyleMediumBrown :
6286 UIProgressIndicatorStyleMediumWhite;
6288 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
6289 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6290 CGRect indrect = {{indoffset, indoffset}, indsize};
6292 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6293 [indicator_ setStyle:style];
6294 [overlay_ addSubview:indicator_];
6296 CGSize prmsize = {215, indsize.height + 4};
6299 indoffset * 2 + indsize.width,
6303 unsigned(ovrrect.size.height - prmsize.height) / 2
6306 UIFont *font = [UIFont systemFontOfSize:15];
6308 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6310 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6311 [prompt_ setBackgroundColor:[UIColor clearColor]];
6312 [prompt_ setFont:font];
6314 [overlay_ addSubview:prompt_];
6316 CGSize prgsize = {75, 100};
6319 ovrrect.size.width - prgsize.width - 10,
6320 (ovrrect.size.height - prgsize.height) / 2
6323 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6324 [progress_ setStyle:0];
6325 [overlay_ addSubview:progress_];
6327 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6328 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6330 CGRect frame = [cancel_ frame];
6331 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6332 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6333 [cancel_ setFrame:frame];
6335 [cancel_ setBarStyle:barstyle];
6339 - (void) _onCancel {
6341 [cancel_ removeFromSuperview];
6344 - (void) _update { _pooled
6346 status.setDelegate(self);
6348 NSString *error([database_ updateWithStatus:status]);
6351 performSelectorOnMainThread:@selector(_update_:)
6357 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6358 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6361 - (void) setProgressTitle:(NSString *)title {
6363 performSelectorOnMainThread:@selector(_setProgressTitle:)
6369 - (void) setProgressPercent:(float)percent {
6371 performSelectorOnMainThread:@selector(_setProgressPercent:)
6372 withObject:[NSNumber numberWithFloat:percent]
6377 - (void) startProgress {
6380 - (void) addProgressOutput:(NSString *)output {
6382 performSelectorOnMainThread:@selector(_addProgressOutput:)
6388 - (bool) isCancelling:(size_t)received {
6392 - (void) _setProgressTitle:(NSString *)title {
6393 [prompt_ setText:title];
6396 - (void) _setProgressPercent:(NSNumber *)percent {
6397 [progress_ setProgress:[percent floatValue]];
6400 - (void) _addProgressOutput:(NSString *)output {
6405 /* Cydia:// Protocol {{{ */
6406 @interface CydiaURLProtocol : NSURLProtocol {
6411 @implementation CydiaURLProtocol
6413 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6414 NSURL *url([request URL]);
6417 NSString *scheme([[url scheme] lowercaseString]);
6418 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6423 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6427 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6428 id<NSURLProtocolClient> client([self client]);
6430 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6432 NSData *data(UIImagePNGRepresentation(icon));
6434 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6435 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6436 [client URLProtocol:self didLoadData:data];
6437 [client URLProtocolDidFinishLoading:self];
6441 - (void) startLoading {
6442 id<NSURLProtocolClient> client([self client]);
6443 NSURLRequest *request([self request]);
6445 NSURL *url([request URL]);
6446 NSString *href([url absoluteString]);
6448 NSString *path([href substringFromIndex:8]);
6449 NSRange slash([path rangeOfString:@"/"]);
6452 if (slash.location == NSNotFound) {
6456 command = [path substringToIndex:slash.location];
6457 path = [path substringFromIndex:(slash.location + 1)];
6460 Database *database([Database sharedInstance]);
6462 if ([command isEqualToString:@"package-icon"]) {
6465 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6466 Package *package([database packageWithName:path]);
6469 UIImage *icon([package icon]);
6470 [self _returnPNGWithImage:icon forRequest:request];
6471 } else if ([command isEqualToString:@"source-icon"]) {
6474 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6475 NSString *source(Simplify(path));
6476 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6478 icon = [UIImage applicationImageNamed:@"unknown.png"];
6479 [self _returnPNGWithImage:icon forRequest:request];
6480 } else if ([command isEqualToString:@"uikit-image"]) {
6483 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6484 UIImage *icon(_UIImageWithName(path));
6485 [self _returnPNGWithImage:icon forRequest:request];
6486 } else if ([command isEqualToString:@"section-icon"]) {
6489 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6490 NSString *section(Simplify(path));
6491 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6493 icon = [UIImage applicationImageNamed:@"unknown.png"];
6494 [self _returnPNGWithImage:icon forRequest:request];
6496 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6500 - (void) stopLoading {
6506 /* Sections View {{{ */
6507 @interface SectionsView : RVPage {
6508 _transient Database *database_;
6509 NSMutableArray *sections_;
6510 NSMutableArray *filtered_;
6511 UITransitionView *transition_;
6517 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6518 - (void) reloadData;
6523 @implementation SectionsView
6526 [list_ setDataSource:nil];
6527 [list_ setDelegate:nil];
6529 [sections_ release];
6530 [filtered_ release];
6531 [transition_ release];
6533 [accessory_ release];
6537 - (int) numberOfRowsInTable:(UITable *)table {
6538 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6541 - (float) table:(UITable *)table heightForRow:(int)row {
6545 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6547 reusing = [[[SectionCell alloc] init] autorelease];
6548 [(SectionCell *)reusing setSection:(editing_ ?
6549 [sections_ objectAtIndex:row] :
6550 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6551 ) editing:editing_];
6555 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6559 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6563 - (void) tableRowSelected:(NSNotification *)notification {
6564 int row = [[notification object] selectedRow];
6575 title = UCLocalize("ALL_PACKAGES");
6577 section = [filtered_ objectAtIndex:(row - 1)];
6578 name = [section name];
6581 name = [NSString stringWithString:name];
6582 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6585 title = UCLocalize("NO_SECTION");
6589 PackageTable *table = [[[FilteredPackageTable alloc]
6593 filter:@selector(isVisiblyUninstalledInSection:)
6597 [table setDelegate:delegate_];
6599 [book_ pushPage:table];
6602 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6603 if ((self = [super initWithBook:book]) != nil) {
6604 database_ = database;
6606 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6607 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6609 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6610 [self addSubview:transition_];
6612 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6613 [transition_ transition:0 toView:list_];
6615 UITableColumn *column = [[[UITableColumn alloc]
6616 initWithTitle:UCLocalize("NAME")
6618 width:[self frame].size.width
6621 [list_ setDataSource:self];
6622 [list_ setSeparatorStyle:1];
6623 [list_ addTableColumn:column];
6624 [list_ setDelegate:self];
6625 [list_ setReusesTableCells:YES];
6629 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6630 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6634 - (void) reloadData {
6635 NSArray *packages = [database_ packages];
6637 [sections_ removeAllObjects];
6638 [filtered_ removeAllObjects];
6641 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6642 SectionMap sections;
6643 sections.resize(64);
6645 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6649 for (Package *package in packages) {
6650 NSString *name([package section]);
6651 NSString *key(name == nil ? @"" : name);
6656 _profile(SectionsView$reloadData$Section)
6657 section = §ions[key];
6658 if (*section == nil) {
6659 _profile(SectionsView$reloadData$Section$Allocate)
6660 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6665 [*section addToCount];
6667 _profile(SectionsView$reloadData$Filter)
6668 if (![package valid] || ![package uninstalled] || ![package visible])
6672 [*section addToRow];
6676 _profile(SectionsView$reloadData$Section)
6677 section = [sections objectForKey:key];
6678 if (section == nil) {
6679 _profile(SectionsView$reloadData$Section$Allocate)
6680 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6681 [sections setObject:section forKey:key];
6686 [section addToCount];
6688 _profile(SectionsView$reloadData$Filter)
6689 if (![package valid] || ![package uninstalled] || ![package visible])
6699 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6700 [sections_ addObject:i->second];
6702 [sections_ addObjectsFromArray:[sections allValues]];
6705 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6707 for (Section *section in sections_) {
6708 size_t count([section row]);
6712 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6713 [section setCount:count];
6714 [filtered_ addObject:section];
6721 - (void) resetView {
6723 [self _rightButtonClicked];
6726 - (void) resetViewAnimated:(BOOL)animated {
6727 [list_ resetViewAnimated:animated];
6730 - (void) _rightButtonClicked {
6731 if ((editing_ = !editing_))
6734 [delegate_ updateData];
6735 [book_ reloadTitleForPage:self];
6736 [book_ reloadButtonsForPage:self];
6739 - (NSString *) title {
6740 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("INSTALL_BY_SECTION");
6743 - (NSString *) backButtonTitle {
6744 return UCLocalize("SECTIONS");
6747 - (id) rightButtonTitle {
6748 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6751 - (UINavigationButtonStyle) rightButtonStyle {
6752 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6755 - (UIView *) accessoryView {
6761 /* Changes View {{{ */
6762 @interface ChangesView : RVPage {
6763 _transient Database *database_;
6764 NSMutableArray *packages_;
6765 NSMutableArray *sections_;
6766 UISectionList *list_;
6770 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6771 - (void) reloadData;
6775 @implementation ChangesView
6778 [[list_ table] setDelegate:nil];
6779 [list_ setDataSource:nil];
6781 [packages_ release];
6782 [sections_ release];
6787 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6788 return [sections_ count];
6791 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6792 return [[sections_ objectAtIndex:section] name];
6795 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6796 return [[sections_ objectAtIndex:section] row];
6799 - (int) numberOfRowsInTable:(UITable *)table {
6800 return [packages_ count];
6803 - (float) table:(UITable *)table heightForRow:(int)row {
6804 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6807 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6809 reusing = [[[PackageCell alloc] init] autorelease];
6810 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6814 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6818 - (void) tableRowSelected:(NSNotification *)notification {
6819 int row = [[notification object] selectedRow];
6822 Package *package = [packages_ objectAtIndex:row];
6823 PackageView *view([delegate_ packageView]);
6824 [view setDelegate:delegate_];
6825 [view setPackage:package];
6826 [book_ pushPage:view];
6829 - (void) _leftButtonClicked {
6830 [(CYBook *)book_ update];
6831 [self reloadButtons];
6834 - (void) _rightButtonClicked {
6835 [delegate_ distUpgrade];
6838 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6839 if ((self = [super initWithBook:book]) != nil) {
6840 database_ = database;
6842 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6843 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6845 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6846 [self addSubview:list_];
6848 [list_ setShouldHideHeaderInShortLists:NO];
6849 [list_ setDataSource:self];
6850 //[list_ setSectionListStyle:1];
6852 UITableColumn *column = [[[UITableColumn alloc]
6853 initWithTitle:UCLocalize("NAME")
6855 width:[self frame].size.width
6858 UITable *table = [list_ table];
6859 [table setSeparatorStyle:1];
6860 [table addTableColumn:column];
6861 [table setDelegate:self];
6862 [table setReusesTableCells:YES];
6866 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6867 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6871 - (void) reloadData {
6872 NSArray *packages = [database_ packages];
6874 [packages_ removeAllObjects];
6875 [sections_ removeAllObjects];
6878 for (Package *package in packages)
6880 [package uninstalled] && [package valid] && [package visible] ||
6881 [package upgradableAndEssential:YES]
6883 [packages_ addObject:package];
6886 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6889 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6890 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6891 Section *section = nil;
6895 bool unseens = false;
6897 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6899 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6900 Package *package = [packages_ objectAtIndex:offset];
6902 BOOL uae = [package upgradableAndEssential:YES];
6908 _profile(ChangesView$reloadData$Remember)
6909 seen = [package seen];
6912 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6917 name = UCLocalize("UNKNOWN");
6919 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6923 _profile(ChangesView$reloadData$Allocate)
6924 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
6925 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6926 [sections_ addObject:section];
6930 [section addToCount];
6931 } else if ([package ignored])
6932 [ignored addToCount];
6935 [upgradable addToCount];
6940 CFRelease(formatter);
6943 Section *last = [sections_ lastObject];
6944 size_t count = [last count];
6945 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6946 [sections_ removeLastObject];
6949 if ([ignored count] != 0)
6950 [sections_ insertObject:ignored atIndex:0];
6952 [sections_ insertObject:upgradable atIndex:0];
6955 [self reloadButtons];
6958 - (void) resetViewAnimated:(BOOL)animated {
6959 [list_ resetViewAnimated:animated];
6962 - (NSString *) leftButtonTitle {
6963 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
6966 - (id) rightButtonTitle {
6967 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6970 - (NSString *) title {
6971 return UCLocalize("CHANGES");
6976 /* Search View {{{ */
6977 @protocol SearchViewDelegate
6978 - (void) showKeyboard:(BOOL)show;
6981 @interface SearchView : RVPage {
6983 UISearchField *field_;
6984 UITransitionView *transition_;
6985 FilteredPackageTable *table_;
6986 UIPreferencesTable *advanced_;
6992 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6993 - (void) reloadData;
6997 @implementation SearchView
7000 [field_ setDelegate:nil];
7002 [accessory_ release];
7004 [transition_ release];
7006 [advanced_ release];
7011 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7015 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7017 case 0: return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("ADVANCED_SEARCH"), UCLocalize("COMING_SOON")];
7019 default: _assert(false);
7023 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7027 default: _assert(false);
7031 - (void) _showKeyboard:(BOOL)show {
7032 CGSize keysize = [UIKeyboard defaultSize];
7033 CGRect keydown = [book_ pageBounds];
7034 CGRect keyup = keydown;
7035 keyup.size.height -= keysize.height - ButtonBarHeight_;
7037 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
7039 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
7040 [animation setSignificantRectFields:8];
7043 [animation setStartFrame:keydown];
7044 [animation setEndFrame:keyup];
7046 [animation setStartFrame:keyup];
7047 [animation setEndFrame:keydown];
7050 UIAnimator *animator = [UIAnimator sharedAnimator];
7053 addAnimations:[NSArray arrayWithObjects:animation, nil]
7054 withDuration:(KeyboardTime_ - delay)
7059 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
7061 [delegate_ showKeyboard:show];
7064 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
7065 [self _showKeyboard:YES];
7068 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7069 [self _showKeyboard:NO];
7072 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7074 NSString *text([field_ text]);
7075 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7081 - (void) textFieldClearButtonPressed:(UITextField *)field {
7085 - (void) keyboardInputShouldDelete:(id)input {
7089 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7090 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7094 [field_ resignFirstResponder];
7099 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7100 if ((self = [super initWithBook:book]) != nil) {
7101 CGRect pageBounds = [book_ pageBounds];
7103 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
7104 [self addSubview:transition_];
7106 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
7108 [advanced_ setReusesTableCells:YES];
7109 [advanced_ setDataSource:self];
7110 [advanced_ reloadData];
7112 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
7113 CGColor dimmed(space_, 0, 0, 0, 0.5);
7114 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
7116 table_ = [[FilteredPackageTable alloc]
7120 filter:@selector(isUnfilteredAndSearchedForBy:)
7124 [table_ setShouldHideHeaderInShortLists:NO];
7125 [transition_ transition:0 toView:table_];
7134 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
7141 [self bounds].size.width - area.origin.x - 18;
7143 area.size.height = [UISearchField defaultHeight];
7145 field_ = [[UISearchField alloc] initWithFrame:area];
7147 UIFont *font = [UIFont systemFontOfSize:16];
7148 [field_ setFont:font];
7150 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7151 [field_ setDelegate:self];
7153 [field_ setPaddingTop:5];
7155 UITextInputTraits *traits([field_ textInputTraits]);
7156 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7157 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7158 [traits setReturnKeyType:UIReturnKeySearch];
7160 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7162 accessory_ = [[UIView alloc] initWithFrame:accrect];
7163 [accessory_ addSubview:field_];
7165 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
7166 [configure setShowPressFeedback:YES];
7167 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
7168 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
7169 [accessory_ addSubview:configure];*/
7171 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7172 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7178 LKAnimation *animation = [LKTransition animation];
7179 [animation setType:@"oglFlip"];
7180 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
7181 [animation setFillMode:@"extended"];
7182 [animation setTransitionFlags:3];
7183 [animation setDuration:10];
7184 [animation setSpeed:0.35];
7185 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
7186 [[transition_ _layer] addAnimation:animation forKey:0];
7187 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
7188 flipped_ = !flipped_;
7192 - (void) configurePushed {
7193 [field_ resignFirstResponder];
7197 - (void) resetViewAnimated:(BOOL)animated {
7200 [table_ resetViewAnimated:animated];
7203 - (void) _reloadData {
7206 - (void) reloadData {
7209 [table_ setObject:[field_ text]];
7210 _profile(SearchView$reloadData)
7211 [table_ reloadData];
7214 [table_ resetCursor];
7217 - (UIView *) accessoryView {
7221 - (NSString *) title {
7225 - (NSString *) backButtonTitle {
7226 return UCLocalize("SEARCH");
7229 - (void) setDelegate:(id)delegate {
7230 [table_ setDelegate:delegate];
7231 [super setDelegate:delegate];
7237 @interface SettingsView : RVPage {
7238 _transient Database *database_;
7241 UIPreferencesTable *table_;
7242 _UISwitchSlider *subscribedSwitch_;
7243 _UISwitchSlider *ignoredSwitch_;
7244 UIPreferencesControlTableCell *subscribedCell_;
7245 UIPreferencesControlTableCell *ignoredCell_;
7248 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7252 @implementation SettingsView
7255 [table_ setDataSource:nil];
7258 if (package_ != nil)
7261 [subscribedSwitch_ release];
7262 [ignoredSwitch_ release];
7263 [subscribedCell_ release];
7264 [ignoredCell_ release];
7268 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7269 if (package_ == nil)
7275 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7276 if (package_ == nil)
7283 default: _assert(false);
7289 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7290 if (package_ == nil)
7297 default: _assert(false);
7303 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7304 if (package_ == nil)
7311 default: _assert(false);
7317 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7318 if (package_ == nil)
7321 _UISwitchSlider *slider([cell control]);
7322 BOOL value([slider value] != 0);
7323 NSMutableDictionary *metadata([package_ metadata]);
7326 if (NSNumber *number = [metadata objectForKey:key])
7327 before = [number boolValue];
7331 if (value != before) {
7332 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7334 [delegate_ updateData];
7338 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7339 [self onSomething:cell withKey:@"IsSubscribed"];
7342 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7343 [self onSomething:cell withKey:@"IsIgnored"];
7346 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7347 if (package_ == nil)
7351 case 0: switch (row) {
7353 return subscribedCell_;
7355 return ignoredCell_;
7356 default: _assert(false);
7359 case 1: switch (row) {
7361 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7362 [cell setShowSelection:NO];
7363 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7367 default: _assert(false);
7370 default: _assert(false);
7376 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7377 if ((self = [super initWithBook:book])) {
7378 database_ = database;
7379 name_ = [package retain];
7381 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7382 [self addSubview:table_];
7384 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7385 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
7387 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7388 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
7390 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7391 [subscribedCell_ setShowSelection:NO];
7392 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7393 [subscribedCell_ setControl:subscribedSwitch_];
7395 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7396 [ignoredCell_ setShowSelection:NO];
7397 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7398 [ignoredCell_ setControl:ignoredSwitch_];
7400 [table_ setDataSource:self];
7405 - (void) resetViewAnimated:(BOOL)animated {
7406 [table_ resetViewAnimated:animated];
7409 - (void) reloadData {
7410 if (package_ != nil)
7411 [package_ autorelease];
7412 package_ = [database_ packageWithName:name_];
7413 if (package_ != nil) {
7415 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7416 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7419 [table_ reloadData];
7422 - (NSString *) title {
7423 return UCLocalize("SETTINGS");
7428 /* Signature View {{{ */
7429 @interface SignatureView : CydiaBrowserView {
7430 _transient Database *database_;
7434 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7438 @implementation SignatureView
7445 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7447 [super webView:sender didClearWindowObject:window forFrame:frame];
7450 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7451 if ((self = [super initWithBook:book]) != nil) {
7452 database_ = database;
7453 package_ = [package retain];
7458 - (void) resetViewAnimated:(BOOL)animated {
7461 - (void) reloadData {
7462 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7468 @interface Cydia : UIApplication <
7469 ConfirmationViewDelegate,
7470 ProgressViewDelegate,
7479 UIToolbar *buttonbar_;
7483 NSMutableArray *essential_;
7484 NSMutableArray *broken_;
7486 Database *database_;
7487 ProgressView *progress_;
7491 UIKeyboard *keyboard_;
7492 UIProgressHUD *hud_;
7494 SectionsView *sections_;
7495 ChangesView *changes_;
7496 ManageView *manage_;
7497 SearchView *search_;
7499 #if RecyclePackageViews
7500 NSMutableArray *details_;
7506 @implementation Cydia
7509 if ([broken_ count] != 0) {
7510 int count = [broken_ count];
7512 UIActionSheet *sheet = [[[UIActionSheet alloc]
7513 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7514 buttons:[NSArray arrayWithObjects:
7515 UCLocalize("FORCIBLY_CLEAR"),
7516 UCLocalize("TEMPORARY_IGNORE"),
7518 defaultButtonIndex:0
7523 [sheet setBodyText:UCLocalize("HALFINSTALLED_PACKAGE_EX")];
7524 [sheet popupAlertAnimated:YES];
7525 } else if (!Ignored_ && [essential_ count] != 0) {
7526 int count = [essential_ count];
7528 UIActionSheet *sheet = [[[UIActionSheet alloc]
7529 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7530 buttons:[NSArray arrayWithObjects:
7531 UCLocalize("UPGRADE_ESSENTIAL"),
7532 UCLocalize("COMPLETE_UPGRADE"),
7533 UCLocalize("TEMPORARY_IGNORE"),
7535 defaultButtonIndex:0
7540 [sheet setBodyText:UCLocalize("ESSENTIAL_UPGRADE_EX")];
7541 [sheet popupAlertAnimated:YES];
7545 - (void) _reloadData {
7548 static bool loaded(false);
7549 UIProgressHUD *hud([self addProgressHUD]);
7550 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7553 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7556 [self removeProgressHUD:hud];
7560 [essential_ removeAllObjects];
7561 [broken_ removeAllObjects];
7563 NSArray *packages = [database_ packages];
7564 for (Package *package in packages) {
7566 [broken_ addObject:package];
7567 if ([package upgradableAndEssential:NO]) {
7568 if ([package essential])
7569 [essential_ addObject:package];
7575 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7576 [buttonbar_ setBadgeValue:badge forButton:3];
7577 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7578 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7579 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7580 [self setApplicationBadge:badge];
7582 [self setApplicationBadgeString:badge];
7584 [buttonbar_ setBadgeValue:nil forButton:3];
7585 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7586 [buttonbar_ setBadgeAnimated:NO forButton:3];
7587 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7588 [self removeApplicationBadge];
7589 else // XXX: maybe use setApplicationBadgeString also?
7590 [self setApplicationIconBadgeNumber:0];
7594 [buttonbar_ setBadgeValue:nil forButton:4];
7598 // XXX: what is this line of code for?
7599 if ([packages count] == 0);
7600 else if (Loaded_ || ManualRefresh) loaded:
7605 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7606 NSTimeInterval interval([update timeIntervalSinceNow]);
7607 if (interval <= 0 && interval > -600)
7615 - (void) _saveConfig {
7618 NSString *error(nil);
7619 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7621 NSError *error(nil);
7622 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7623 NSLog(@"failure to save metadata data: %@", error);
7626 NSLog(@"failure to serialize metadata: %@", error);
7634 - (void) updateData {
7637 /* XXX: this is just stupid */
7638 if (tag_ != 2 && sections_ != nil)
7639 [sections_ reloadData];
7640 if (tag_ != 3 && changes_ != nil)
7641 [changes_ reloadData];
7642 if (tag_ != 5 && search_ != nil)
7643 [search_ reloadData];
7653 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7654 _assert(file != NULL);
7656 NSArray *keys = [Sources_ allKeys];
7658 for (NSString *key in keys) {
7659 NSDictionary *source = [Sources_ objectForKey:key];
7661 fprintf(file, "%s %s %s\n",
7662 [[source objectForKey:@"Type"] UTF8String],
7663 [[source objectForKey:@"URI"] UTF8String],
7664 [[source objectForKey:@"Distribution"] UTF8String]
7673 detachNewThreadSelector:@selector(update_)
7676 title:UCLocalize("UPDATING_SOURCES")
7680 - (void) reloadData {
7681 @synchronized (self) {
7682 if (confirm_ == nil)
7688 pkgProblemResolver *resolver = [database_ resolver];
7690 resolver->InstallProtect();
7691 if (!resolver->Resolve(true))
7695 - (void) popUpBook:(RVBook *)book {
7696 [underlay_ popSubview:book];
7699 - (CGRect) popUpBounds {
7700 return [underlay_ bounds];
7704 [database_ prepare];
7706 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7707 [confirm_ setDelegate:self];
7709 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7710 [page setDelegate:self];
7712 [confirm_ setPage:page];
7713 [self popUpBook:confirm_];
7717 @synchronized (self) {
7722 - (void) clearPackage:(Package *)package {
7723 @synchronized (self) {
7730 - (void) installPackage:(Package *)package {
7731 @synchronized (self) {
7738 - (void) removePackage:(Package *)package {
7739 @synchronized (self) {
7746 - (void) distUpgrade {
7747 @synchronized (self) {
7748 [database_ upgrade];
7754 [self slideUp:[[[UIActionSheet alloc]
7756 buttons:[NSArray arrayWithObjects:UCLocalize("CONTINUE_QUEUING"), UCLocalize("CANCEL_CLEAR"), nil]
7757 defaultButtonIndex:1
7764 @synchronized (self) {
7767 if (confirm_ != nil) {
7775 [overlay_ removeFromSuperview];
7779 detachNewThreadSelector:@selector(perform)
7782 title:UCLocalize("RUNNING")
7786 - (void) bootstrap_ {
7788 [database_ upgrade];
7789 [database_ prepare];
7790 [database_ perform];
7793 /* XXX: replace and localize */
7794 - (void) bootstrap {
7796 detachNewThreadSelector:@selector(bootstrap_)
7799 title:@"Bootstrap Install"
7803 - (void) progressViewIsComplete:(ProgressView *)progress {
7804 if (confirm_ != nil) {
7805 [underlay_ addSubview:overlay_];
7806 [confirm_ popFromSuperviewAnimated:NO];
7812 - (void) setPage:(RVPage *)page {
7813 [page resetViewAnimated:NO];
7814 [page setDelegate:self];
7815 [book_ setPage:page];
7818 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7819 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7820 [browser loadURL:url];
7824 - (void) _setHomePage {
7825 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7828 - (SectionsView *) sectionsView {
7829 if (sections_ == nil)
7830 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7834 - (void) buttonBarItemTapped:(id)sender {
7835 unsigned tag = [sender tag];
7837 [book_ resetViewAnimated:YES];
7839 } else if (tag_ == 2 && tag != 2)
7840 [[self sectionsView] resetView];
7843 case 1: [self _setHomePage]; break;
7845 case 2: [self setPage:[self sectionsView]]; break;
7846 case 3: [self setPage:changes_]; break;
7847 case 4: [self setPage:manage_]; break;
7848 case 5: [self setPage:search_]; break;
7850 default: _assert(false);
7856 - (void) applicationWillSuspend {
7858 [super applicationWillSuspend];
7861 - (void) askForSettings {
7862 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
7864 UIActionSheet *role = [[[UIActionSheet alloc]
7865 initWithTitle:UCLocalize("WHO_ARE_YOU")
7866 buttons:[NSArray arrayWithObjects:
7867 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
7868 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
7869 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
7871 defaultButtonIndex:-1
7876 [role setBodyText:UCLocalize("ROLE_EX")];
7877 [role popupAlertAnimated:YES];
7880 - (void) setPackageView:(PackageView *)view {
7882 [view setPackage:nil];
7883 #if RecyclePackageViews
7884 if ([details_ count] < 3)
7885 [details_ addObject:view];
7890 - (PackageView *) _packageView {
7891 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7894 - (PackageView *) packageView {
7895 #if RecyclePackageViews
7897 size_t count([details_ count]);
7900 view = [self _packageView];
7902 [details_ addObject:[self _packageView]];
7904 view = [[[details_ lastObject] retain] autorelease];
7905 [details_ removeLastObject];
7912 return [self _packageView];
7918 [self setStatusBarShowsProgress:NO];
7919 [self removeProgressHUD:hud_];
7924 pid_t pid = ExecFork();
7926 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7927 perror("launchctl stop");
7934 [self askForSettings];
7939 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7941 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7942 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7943 0, 0, screenrect.size.width, screenrect.size.height - 48
7944 ) database:database_];
7946 [book_ setDelegate:self];
7948 [overlay_ addSubview:book_];
7950 NSArray *buttonitems = [NSArray arrayWithObjects:
7951 [NSDictionary dictionaryWithObjectsAndKeys:
7952 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7953 @"home-up.png", kUIButtonBarButtonInfo,
7954 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7955 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7956 self, kUIButtonBarButtonTarget,
7957 @"Cydia", kUIButtonBarButtonTitle,
7958 @"0", kUIButtonBarButtonType,
7961 [NSDictionary dictionaryWithObjectsAndKeys:
7962 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7963 @"install-up.png", kUIButtonBarButtonInfo,
7964 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7965 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7966 self, kUIButtonBarButtonTarget,
7967 UCLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7968 @"0", kUIButtonBarButtonType,
7971 [NSDictionary dictionaryWithObjectsAndKeys:
7972 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7973 @"changes-up.png", kUIButtonBarButtonInfo,
7974 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7975 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7976 self, kUIButtonBarButtonTarget,
7977 UCLocalize("CHANGES"), kUIButtonBarButtonTitle,
7978 @"0", kUIButtonBarButtonType,
7981 [NSDictionary dictionaryWithObjectsAndKeys:
7982 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7983 @"manage-up.png", kUIButtonBarButtonInfo,
7984 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7985 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7986 self, kUIButtonBarButtonTarget,
7987 UCLocalize("MANAGE"), kUIButtonBarButtonTitle,
7988 @"0", kUIButtonBarButtonType,
7991 [NSDictionary dictionaryWithObjectsAndKeys:
7992 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7993 @"search-up.png", kUIButtonBarButtonInfo,
7994 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7995 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7996 self, kUIButtonBarButtonTarget,
7997 UCLocalize("SEARCH"), kUIButtonBarButtonTitle,
7998 @"0", kUIButtonBarButtonType,
8002 buttonbar_ = [[UIToolbar alloc]
8004 withFrame:CGRectMake(
8005 0, screenrect.size.height - ButtonBarHeight_,
8006 screenrect.size.width, ButtonBarHeight_
8008 withItemList:buttonitems
8011 [buttonbar_ setDelegate:self];
8012 [buttonbar_ setBarStyle:1];
8013 [buttonbar_ setButtonBarTrackingMode:2];
8015 int buttons[5] = {1, 2, 3, 4, 5};
8016 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
8017 [buttonbar_ showButtonGroup:0 withDuration:0];
8019 for (int i = 0; i != 5; ++i)
8020 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
8021 i * 64 + 2, 1, 60, ButtonBarHeight_
8024 [buttonbar_ showSelectionForButton:1];
8025 [overlay_ addSubview:buttonbar_];
8027 [UIKeyboard initImplementationNow];
8028 CGSize keysize = [UIKeyboard defaultSize];
8029 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
8030 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
8031 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
8032 [overlay_ addSubview:keyboard_];
8035 [underlay_ addSubview:overlay_];
8039 [self sectionsView];
8040 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
8041 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
8043 manage_ = (ManageView *) [[self
8044 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8045 withClass:[ManageView class]
8048 #if RecyclePackageViews
8049 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8050 [details_ addObject:[self _packageView]];
8051 [details_ addObject:[self _packageView]];
8059 [self _setHomePage];
8062 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
8063 NSString *context([sheet context]);
8065 if ([context isEqualToString:@"missing"])
8067 else if ([context isEqualToString:@"cancel"]) {
8085 @synchronized (self) {
8090 [buttonbar_ setBadgeValue:UCLocalize("Q_D") forButton:4];
8094 if (confirm_ != nil) {
8099 } else if ([context isEqualToString:@"fixhalf"]) {
8102 @synchronized (self) {
8103 for (Package *broken in broken_) {
8106 NSString *id = [broken id];
8107 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8108 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8109 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8110 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8119 [broken_ removeAllObjects];
8128 } else if ([context isEqualToString:@"role"]) {
8130 case 1: Role_ = @"User"; break;
8131 case 2: Role_ = @"Hacker"; break;
8132 case 3: Role_ = @"Developer"; break;
8139 bool reset = Settings_ != nil;
8141 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8145 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8155 } else if ([context isEqualToString:@"upgrade"]) {
8158 @synchronized (self) {
8159 for (Package *essential in essential_)
8160 [essential install];
8183 - (void) reorganize { _pooled
8184 system("/usr/libexec/cydia/free.sh");
8185 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
8188 - (void) applicationSuspend:(__GSEvent *)event {
8189 if (hud_ == nil && ![progress_ isRunning])
8190 [super applicationSuspend:event];
8193 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8195 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8198 - (void) _setSuspended:(BOOL)value {
8200 [super _setSuspended:value];
8203 - (UIProgressHUD *) addProgressHUD {
8204 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8205 [window_ setUserInteractionEnabled:NO];
8207 [progress_ addSubview:hud];
8211 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8213 [hud removeFromSuperview];
8214 [window_ setUserInteractionEnabled:YES];
8217 - (RVPage *) pageForPackage:(NSString *)name {
8218 if (Package *package = [database_ packageWithName:name]) {
8219 PackageView *view([self packageView]);
8220 [view setPackage:package];
8223 UIActionSheet *sheet = [[[UIActionSheet alloc]
8224 initWithTitle:UCLocalize("CANNOT_LOCATE_PACKAGE")
8225 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
8226 defaultButtonIndex:0
8231 [sheet setBodyText:[NSString stringWithFormat:UCLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
8233 [sheet popupAlertAnimated:YES];
8238 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8242 NSString *href([url absoluteString]);
8243 if ([href hasPrefix:@"apptapp://package/"])
8244 return [self pageForPackage:[href substringFromIndex:18]];
8246 NSString *scheme([[url scheme] lowercaseString]);
8247 if (![scheme isEqualToString:@"cydia"])
8249 NSString *path([url absoluteString]);
8250 if ([path length] < 8)
8252 path = [path substringFromIndex:8];
8253 if (![path hasPrefix:@"/"])
8254 path = [@"/" stringByAppendingString:path];
8256 if ([path isEqualToString:@"/add-source"])
8257 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8258 else if ([path isEqualToString:@"/storage"])
8259 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8260 else if ([path isEqualToString:@"/sources"])
8261 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8262 else if ([path isEqualToString:@"/packages"])
8263 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8264 else if ([path hasPrefix:@"/url/"])
8265 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8266 else if ([path hasPrefix:@"/launch/"])
8267 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8268 else if ([path hasPrefix:@"/package-settings/"])
8269 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8270 else if ([path hasPrefix:@"/package-signature/"])
8271 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8272 else if ([path hasPrefix:@"/package/"])
8273 return [self pageForPackage:[path substringFromIndex:9]];
8274 else if ([path hasPrefix:@"/files/"]) {
8275 NSString *name = [path substringFromIndex:7];
8277 if (Package *package = [database_ packageWithName:name]) {
8278 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8279 [files setPackage:package];
8287 - (void) applicationOpenURL:(NSURL *)url {
8288 [super applicationOpenURL:url];
8290 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8291 [self setPage:page];
8292 [buttonbar_ showSelectionForButton:tag];
8297 - (void) applicationDidFinishLaunching:(id)unused {
8298 [BrowserView _initialize];
8301 Font12_ = [[UIFont systemFontOfSize:12] retain];
8302 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8303 Font14_ = [[UIFont systemFontOfSize:14] retain];
8304 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8305 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8309 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8310 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8312 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8314 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8315 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
8317 [window_ orderFront:self];
8318 [window_ makeKey:self];
8319 [window_ setHidden:NO];
8321 database_ = [Database sharedInstance];
8322 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8323 [database_ setDelegate:progress_];
8324 [window_ setContentView:progress_];
8326 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8327 [progress_ setContentView:underlay_];
8329 [progress_ resetView];
8332 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8333 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8334 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL /*||
8335 readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL*/ ||
8336 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8337 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8338 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8339 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
8340 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
8342 [self setIdleTimerDisabled:YES];
8344 hud_ = [[self addProgressHUD] retain];
8345 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8347 [self setStatusBarShowsProgress:YES];
8350 detachNewThreadSelector:@selector(reorganize)
8358 - (void) showKeyboard:(BOOL)show {
8359 CGSize keysize = [UIKeyboard defaultSize];
8360 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8361 CGRect keyup = keydown;
8362 keyup.origin.y -= keysize.height;
8364 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
8365 [animation setSignificantRectFields:2];
8368 [animation setStartFrame:keydown];
8369 [animation setEndFrame:keyup];
8370 [keyboard_ activate];
8372 [animation setStartFrame:keyup];
8373 [animation setEndFrame:keydown];
8374 [keyboard_ deactivate];
8377 [[UIAnimator sharedAnimator]
8378 addAnimations:[NSArray arrayWithObjects:animation, nil]
8379 withDuration:KeyboardTime_
8384 - (void) slideUp:(UIActionSheet *)alert {
8386 [alert presentSheetFromButtonBar:buttonbar_];
8388 [alert presentSheetInView:overlay_];
8393 void AddPreferences(NSString *plist) { _pooled
8394 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
8395 _assert(settings != NULL);
8396 NSMutableArray *items = [settings objectForKey:@"items"];
8400 for (NSMutableDictionary *item in items) {
8401 NSString *label = [item objectForKey:@"label"];
8402 if (label != nil && [label isEqualToString:@"Cydia"]) {
8409 for (size_t i(0); i != [items count]; ++i) {
8410 NSDictionary *item([items objectAtIndex:i]);
8411 NSString *label = [item objectForKey:@"label"];
8412 if (label != nil && [label isEqualToString:@"General"]) {
8413 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
8414 @"CydiaSettings", @"bundle",
8415 @"PSLinkCell", @"cell",
8416 [NSNumber numberWithBool:YES], @"hasIcon",
8417 [NSNumber numberWithBool:YES], @"isController",
8419 nil] atIndex:(i + 1)];
8425 _assert([settings writeToFile:plist atomically:YES] == YES);
8430 id Alloc_(id self, SEL selector) {
8431 id object = alloc_(self, selector);
8432 lprintf("[%s]A-%p\n", self->isa->name, object);
8437 id Dealloc_(id self, SEL selector) {
8438 id object = dealloc_(self, selector);
8439 lprintf("[%s]D-%p\n", self->isa->name, object);
8443 Class $WebDefaultUIKitDelegate;
8445 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8447 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8448 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8449 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8450 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8453 int main(int argc, char *argv[]) { _pooled
8456 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8458 /* Library Hacks {{{ */
8459 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8461 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8462 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8463 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8464 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8465 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8468 /* Set Locale {{{ */
8469 Locale_ = CFLocaleCopyCurrent();
8470 Languages_ = [NSLocale preferredLanguages];
8471 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8472 //NSLog(@"%@", [Languages_ description]);
8474 if (Languages_ == nil || [Languages_ count] == 0)
8477 lang = [[Languages_ objectAtIndex:0] UTF8String];
8478 setenv("LANG", lang, true);
8479 //std::setlocale(LC_ALL, lang);
8480 NSLog(@"Setting Language: %s", lang);
8483 // XXX: apr_app_initialize?
8486 /* Parse Arguments {{{ */
8487 bool substrate(false);
8493 for (int argi(1); argi != argc; ++argi)
8494 if (strcmp(argv[argi], "--") == 0) {
8496 argv[argi] = argv[0];
8502 for (int argi(1); argi != arge; ++argi)
8503 if (strcmp(args[argi], "--bootstrap") == 0)
8505 else if (strcmp(args[argi], "--substrate") == 0)
8508 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8513 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8514 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8515 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8516 Sounds_Keyboard_ = [keyboard boolValue];
8519 App_ = [[NSBundle mainBundle] bundlePath];
8520 Home_ = NSHomeDirectory();
8525 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8526 alloc_ = alloc->method_imp;
8527 alloc->method_imp = (IMP) &Alloc_;*/
8529 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8530 dealloc_ = dealloc->method_imp;
8531 dealloc->method_imp = (IMP) &Dealloc_;*/
8536 size = sizeof(maxproc);
8537 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8538 perror("sysctlbyname(\"kern.maxproc\", ?)");
8539 else if (maxproc < 64) {
8541 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8542 perror("sysctlbyname(\"kern.maxproc\", #)");
8545 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8546 char *machine = new char[size];
8547 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8548 perror("sysctlbyname(\"hw.machine\", ?)");
8552 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8554 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8555 Build_ = [system objectForKey:@"ProductBuildVersion"];
8556 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8557 Product_ = [info objectForKey:@"SafariProductVersion"];
8558 Safari_ = [info objectForKey:@"CFBundleVersion"];
8561 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8562 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8564 /* Load Database {{{ */
8566 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8568 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8571 if (Metadata_ == NULL)
8572 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8574 Settings_ = [Metadata_ objectForKey:@"Settings"];
8576 Packages_ = [Metadata_ objectForKey:@"Packages"];
8577 Sections_ = [Metadata_ objectForKey:@"Sections"];
8578 Sources_ = [Metadata_ objectForKey:@"Sources"];
8581 if (Settings_ != nil)
8582 Role_ = [Settings_ objectForKey:@"Role"];
8584 if (Packages_ == nil) {
8585 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8586 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8589 if (Sections_ == nil) {
8590 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8591 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8594 if (Sources_ == nil) {
8595 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8596 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8601 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8604 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8605 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8606 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8607 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8609 if (access("/User", F_OK) != 0 || access("/tmp/.cydia.fw", F_OK) != 0) {
8610 unlink("/tmp/.cydia.fw");
8612 system("/usr/libexec/cydia/firmware.sh");
8616 _assert([[NSFileManager defaultManager]
8617 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8618 withIntermediateDirectories:YES
8623 if (access("/tmp/cydia.chk", F_OK) == 0) {
8624 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8625 _assert(errno == ENOENT);
8626 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8627 _assert(errno == ENOENT);
8630 _assert(pkgInitConfig(*_config));
8631 _assert(pkgInitSystem(*_config, _system));
8634 _config->Set("APT::Acquire::Translation", lang);
8635 _config->Set("Acquire::http::Timeout", 15);
8636 _config->Set("Acquire::http::MaxParallel", 4);
8638 /* Color Choices {{{ */
8639 space_ = CGColorSpaceCreateDeviceRGB();
8641 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8642 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8643 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8644 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8645 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8646 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8647 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8648 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8649 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8650 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8651 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8652 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8653 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8654 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8655 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8658 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8659 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8662 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8664 /* UIKit Configuration {{{ */
8665 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8666 if ($GSFontSetUseLegacyFontMetrics != NULL)
8667 $GSFontSetUseLegacyFontMetrics(YES);
8669 UIKeyboardDisableAutomaticAppearance();
8673 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8675 CGColorSpaceRelease(space_);