1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008 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 /* #include Directives {{{ */
39 #import "UICaboodle.h"
41 #include <objc/objc.h>
42 #include <objc/runtime.h>
44 #include <CoreGraphics/CoreGraphics.h>
45 #include <GraphicsServices/GraphicsServices.h>
46 #include <Foundation/Foundation.h>
48 #import <QuartzCore/CALayer.h>
50 #import <UIKit/UIKit.h>
53 #import <MessageUI/MailComposeController.h>
55 #import <WebCore/WebScriptObject.h>
56 //#include <WebCore/DOMHTML.h>
58 #include <WebKit/WebFrame.h>
59 #include <WebKit/WebPolicyDelegate.h>
60 #include <WebKit/WebView.h>
62 #import <WebKit/WebView-WebPrivate.h>
67 #include <ext/stdio_filebuf.h>
69 #include <apt-pkg/acquire.h>
70 #include <apt-pkg/acquire-item.h>
71 #include <apt-pkg/algorithms.h>
72 #include <apt-pkg/cachefile.h>
73 #include <apt-pkg/clean.h>
74 #include <apt-pkg/configuration.h>
75 #include <apt-pkg/debmetaindex.h>
76 #include <apt-pkg/error.h>
77 #include <apt-pkg/init.h>
78 #include <apt-pkg/mmap.h>
79 #include <apt-pkg/pkgrecords.h>
80 #include <apt-pkg/sha1.h>
81 #include <apt-pkg/sourcelist.h>
82 #include <apt-pkg/sptr.h>
83 #include <apt-pkg/strutl.h>
85 #include <sys/types.h>
87 #include <sys/sysctl.h>
93 #include <mach-o/nlist.h>
103 #import "BrowserView.h"
104 #import "ResetView.h"
107 //#define _finline __attribute__((force_inline))
108 #define _finline inline
113 #define _limit(count) do { \
114 static size_t _count(0); \
115 if (++_count == count) \
119 static uint64_t profile_;
121 #define _timestamp ({ \
123 gettimeofday(&tv, NULL); \
124 tv.tv_sec * 1000000 + tv.tv_usec; \
127 /* Objective-C Handle<> {{{ */
128 template <typename Type_>
130 typedef _H<Type_> This_;
135 _finline void Retain_() {
140 _finline void Clear_() {
146 _finline _H(Type_ *value = NULL, bool mended = false) :
157 _finline This_ &operator =(Type_ *value) {
158 if (value_ != value) {
167 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
169 void NSLogPoint(const char *fix, const CGPoint &point) {
170 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
173 void NSLogRect(const char *fix, const CGRect &rect) {
174 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
177 static const NSStringCompareOptions CompareOptions_ = NSCaseInsensitiveSearch | NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSForcedOrderingSearch;
179 /* iPhoneOS 2.0 Compatibility {{{ */
181 @interface UITextView (iPhoneOS)
182 - (void) setTextSize:(float)size;
185 @implementation UITextView (iPhoneOS)
187 - (void) setTextSize:(float)size {
188 [self setFont:[[self font] fontWithSize:size]];
195 extern NSString * const kCAFilterNearest;
197 /* Information Dictionaries {{{ */
198 @interface NSMutableArray (Cydia)
199 - (void) addInfoDictionary:(NSDictionary *)info;
202 @implementation NSMutableArray (Cydia)
204 - (void) addInfoDictionary:(NSDictionary *)info {
205 [self addObject:info];
210 @interface NSMutableDictionary (Cydia)
211 - (void) addInfoDictionary:(NSDictionary *)info;
214 @implementation NSMutableDictionary (Cydia)
216 - (void) addInfoDictionary:(NSDictionary *)info {
217 NSString *bundle = [info objectForKey:@"CFBundleIdentifier"];
218 [self setObject:info forKey:bundle];
223 /* Pop Transitions {{{ */
224 @interface PopTransitionView : UITransitionView {
229 @implementation PopTransitionView
231 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
232 if (from != nil && to == nil)
233 [self removeFromSuperview];
238 @interface UIView (PopUpView)
239 - (void) popFromSuperviewAnimated:(BOOL)animated;
240 - (void) popSubview:(UIView *)view;
243 @implementation UIView (PopUpView)
245 - (void) popFromSuperviewAnimated:(BOOL)animated {
246 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
249 - (void) popSubview:(UIView *)view {
250 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
251 [transition setDelegate:transition];
252 [self addSubview:transition];
254 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
255 [transition transition:UITransitionNone toView:blank];
256 [transition transition:UITransitionPushFromBottom toView:view];
262 #define lprintf(args...) fprintf(stderr, args)
265 #define ForSaurik 1 && !ForRelease
266 #define RecycleWebViews 0
267 #define AlwaysReload 0 && !ForRelease
270 @interface NSMutableArray (Radix)
271 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
274 @implementation NSMutableArray (Radix)
276 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
277 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
278 [invocation setSelector:selector];
279 [invocation setArgument:&object atIndex:2];
281 size_t count([self count]);
286 } *swap(new RadixItem[count * 2]), *lhs(swap), *rhs(swap + count);
288 for (size_t i(0); i != count; ++i) {
289 RadixItem &item(lhs[i]);
292 id object([self objectAtIndex:i]);
293 [invocation setTarget:object];
296 [invocation getReturnValue:&item.key];
299 static const size_t width = 32;
300 static const size_t bits = 11;
301 static const size_t slots = 1 << bits;
302 static const size_t passes = (width + (bits - 1)) / bits;
304 size_t *hist(new size_t[slots]);
306 for (size_t pass(0); pass != passes; ++pass) {
307 memset(hist, 0, sizeof(size_t) * slots);
309 for (size_t i(0); i != count; ++i) {
310 uint32_t key(lhs[i].key);
312 key &= _not(uint32_t) >> width - bits;
317 for (size_t i(0); i != slots; ++i) {
318 size_t local(offset);
323 for (size_t i(0); i != count; ++i) {
324 uint32_t key(lhs[i].key);
326 key &= _not(uint32_t) >> width - bits;
327 rhs[hist[key]++] = lhs[i];
337 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
338 for (size_t i(0); i != count; ++i)
339 [values addObject:[self objectAtIndex:lhs[i].index]];
340 [self setArray:values];
348 /* Apple Bug Fixes {{{ */
349 @implementation UIWebDocumentView (Cydia)
351 - (void) _setScrollerOffset:(CGPoint)offset {
352 UIScroller *scroller([self _scroller]);
354 CGSize size([scroller contentSize]);
355 CGSize bounds([scroller bounds].size);
358 max.x = size.width - bounds.width;
359 max.y = size.height - bounds.height;
367 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
368 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
370 [scroller setOffset:offset];
377 kUIControlEventMouseDown = 1 << 0,
378 kUIControlEventMouseMovedInside = 1 << 2, // mouse moved inside control target
379 kUIControlEventMouseMovedOutside = 1 << 3, // mouse moved outside control target
380 kUIControlEventMouseUpInside = 1 << 6, // mouse up inside control target
381 kUIControlEventMouseUpOutside = 1 << 7, // mouse up outside control target
382 kUIControlAllEvents = (kUIControlEventMouseDown | kUIControlEventMouseMovedInside | kUIControlEventMouseMovedOutside | kUIControlEventMouseUpInside | kUIControlEventMouseUpOutside)
383 } UIControlEventMasks;
385 @interface NSString (UIKit)
386 - (NSString *) stringByAddingPercentEscapes;
387 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
390 @interface NSString (Cydia)
391 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
392 - (NSComparisonResult) compareByPath:(NSString *)other;
395 @implementation NSString (Cydia)
397 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
398 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
401 - (NSComparisonResult) compareByPath:(NSString *)other {
402 NSString *prefix = [self commonPrefixWithString:other options:0];
403 size_t length = [prefix length];
405 NSRange lrange = NSMakeRange(length, [self length] - length);
406 NSRange rrange = NSMakeRange(length, [other length] - length);
408 lrange = [self rangeOfString:@"/" options:0 range:lrange];
409 rrange = [other rangeOfString:@"/" options:0 range:rrange];
411 NSComparisonResult value;
413 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
414 value = NSOrderedSame;
415 else if (lrange.location == NSNotFound)
416 value = NSOrderedAscending;
417 else if (rrange.location == NSNotFound)
418 value = NSOrderedDescending;
420 value = NSOrderedSame;
422 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
423 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
424 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
425 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
427 NSComparisonResult result = [lpath compare:rpath];
428 return result == NSOrderedSame ? value : result;
433 /* Perl-Compatible RegEx {{{ */
443 Pcre(const char *regex) :
448 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
451 lprintf("%d:%s\n", offset, error);
455 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
456 matches_ = new int[(capture_ + 1) * 3];
464 NSString *operator [](size_t match) {
465 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
468 bool operator ()(NSString *data) {
469 // XXX: length is for characters, not for bytes
470 return operator ()([data UTF8String], [data length]);
473 bool operator ()(const char *data, size_t size) {
475 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
479 /* Mime Addresses {{{ */
480 @interface Address : NSObject {
486 - (NSString *) address;
488 + (Address *) addressWithString:(NSString *)string;
489 - (Address *) initWithString:(NSString *)string;
492 @implementation Address
501 - (NSString *) name {
505 - (NSString *) address {
509 + (Address *) addressWithString:(NSString *)string {
510 return [[[Address alloc] initWithString:string] autorelease];
513 + (NSArray *) _attributeKeys {
514 return [NSArray arrayWithObjects:@"address", @"name", nil];
517 - (NSArray *) attributeKeys {
518 return [[self class] _attributeKeys];
521 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
522 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
525 - (Address *) initWithString:(NSString *)string {
526 if ((self = [super init]) != nil) {
527 const char *data = [string UTF8String];
528 size_t size = [string length];
530 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
532 if (address_r(data, size)) {
533 name_ = [address_r[1] retain];
534 address_ = [address_r[2] retain];
536 name_ = [string retain];
544 /* CoreGraphics Primitives {{{ */
555 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
558 Set(space, red, green, blue, alpha);
563 CGColorRelease(color_);
570 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
572 float color[] = {red, green, blue, alpha};
573 color_ = CGColorCreate(space, color);
576 operator CGColorRef() {
582 extern "C" void UISetColor(CGColorRef color);
584 /* Random Global Variables {{{ */
585 static const int PulseInterval_ = 50000;
586 static const int ButtonBarHeight_ = 48;
587 static const float KeyboardTime_ = 0.3f;
589 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
590 #define SandboxTemplate_ "/usr/share/sandbox/SandboxTemplate.sb"
592 static CGColor Blue_;
593 static CGColor Blueish_;
594 static CGColor Black_;
596 static CGColor White_;
597 static CGColor Gray_;
599 static NSString *App_;
600 static NSString *Home_;
601 static BOOL Sounds_Keyboard_;
603 static BOOL Advanced_;
607 static BOOL Ignored_;
609 static UIFont *Font12_;
610 static UIFont *Font12Bold_;
611 static UIFont *Font14_;
612 static UIFont *Font18Bold_;
613 static UIFont *Font22Bold_;
615 static const char *Machine_ = NULL;
616 static const NSString *UniqueID_ = NULL;
623 CGColorSpaceRef space_;
625 #define FW_LEAST(major, minor, bugfix) \
626 (major < Major_ || major == Major_ && \
627 (minor < Minor_ || minor == Minor_ && \
633 static NSDictionary *SectionMap_;
634 static NSMutableDictionary *Metadata_;
635 static _transient NSMutableDictionary *Settings_;
636 static _transient NSString *Role_;
637 static _transient NSMutableDictionary *Packages_;
638 static _transient NSMutableDictionary *Sections_;
639 static _transient NSMutableDictionary *Sources_;
640 static bool Changed_;
644 static NSMutableArray *Documents_;
647 NSString *GetLastUpdate() {
648 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
651 return @"Never or Unknown";
653 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
654 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
656 CFRelease(formatter);
658 return [(NSString *) formatted autorelease];
661 /* Display Helpers {{{ */
662 inline float Interpolate(float begin, float end, float fraction) {
663 return (end - begin) * fraction + begin;
666 NSString *SizeString(double size) {
667 bool negative = size < 0;
672 while (size > 1024) {
677 static const char *powers_[] = {"B", "kB", "MB", "GB"};
679 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
682 NSString *StripVersion(NSString *version) {
683 NSRange colon = [version rangeOfString:@":"];
684 if (colon.location != NSNotFound)
685 version = [version substringFromIndex:(colon.location + 1)];
689 NSString *Simplify(NSString *title) {
690 const char *data = [title UTF8String];
691 size_t size = [title length];
693 static Pcre square_r("^\\[(.*)\\]$");
694 if (square_r(data, size))
695 return Simplify(square_r[1]);
697 static Pcre paren_r("^\\((.*)\\)$");
698 if (paren_r(data, size))
699 return Simplify(paren_r[1]);
701 static Pcre title_r("^(.*?) \\(.*\\)$");
702 if (title_r(data, size))
703 return Simplify(title_r[1]);
709 bool isSectionVisible(NSString *section) {
710 NSDictionary *metadata = [Sections_ objectForKey:section];
711 NSNumber *hidden = metadata == nil ? nil : [metadata objectForKey:@"Hidden"];
712 return hidden == nil || ![hidden boolValue];
715 /* Delegate Prototypes {{{ */
719 @interface NSObject (ProgressDelegate)
722 @implementation NSObject(ProgressDelegate)
724 - (void) _setProgressError:(NSArray *)args {
725 [self performSelector:@selector(setProgressError:forPackage:)
726 withObject:[args objectAtIndex:0]
727 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
733 @protocol ProgressDelegate
734 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
735 - (void) setProgressTitle:(NSString *)title;
736 - (void) setProgressPercent:(float)percent;
737 - (void) startProgress;
738 - (void) addProgressOutput:(NSString *)output;
739 - (bool) isCancelling:(size_t)received;
742 @protocol ConfigurationDelegate
743 - (void) repairWithSelector:(SEL)selector;
744 - (void) setConfigurationData:(NSString *)data;
747 @protocol CydiaDelegate
748 - (void) installPackage:(Package *)package;
749 - (void) removePackage:(Package *)package;
750 - (void) slideUp:(UIActionSheet *)alert;
751 - (void) distUpgrade;
754 - (void) askForSettings;
755 - (UIProgressHUD *) addProgressHUD;
756 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag;
757 - (RVPage *) pageForPackage:(NSString *)name;
758 - (void) openMailToURL:(NSURL *)url;
762 /* Status Delegation {{{ */
764 public pkgAcquireStatus
767 _transient NSObject<ProgressDelegate> *delegate_;
775 void setDelegate(id delegate) {
776 delegate_ = delegate;
779 virtual bool MediaChange(std::string media, std::string drive) {
783 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
786 virtual void Fetch(pkgAcquire::ItemDesc &item) {
787 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
788 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
791 virtual void Done(pkgAcquire::ItemDesc &item) {
794 virtual void Fail(pkgAcquire::ItemDesc &item) {
796 item.Owner->Status == pkgAcquire::Item::StatIdle ||
797 item.Owner->Status == pkgAcquire::Item::StatDone
801 std::string &error(item.Owner->ErrorText);
805 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
806 NSArray *fields([description componentsSeparatedByString:@" "]);
807 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
809 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
810 withObject:[NSArray arrayWithObjects:
811 [NSString stringWithUTF8String:error.c_str()],
818 virtual bool Pulse(pkgAcquire *Owner) {
819 bool value = pkgAcquireStatus::Pulse(Owner);
822 double(CurrentBytes + CurrentItems) /
823 double(TotalBytes + TotalItems)
826 [delegate_ setProgressPercent:percent];
827 return [delegate_ isCancelling:CurrentBytes] ? false : value;
830 virtual void Start() {
831 [delegate_ startProgress];
834 virtual void Stop() {
838 /* Progress Delegation {{{ */
843 _transient id<ProgressDelegate> delegate_;
846 virtual void Update() {
847 [delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
848 [delegate_ setProgressPercent:(Percent / 100)];
857 void setDelegate(id delegate) {
858 delegate_ = delegate;
861 virtual void Done() {
862 [delegate_ setProgressPercent:1];
867 /* Database Interface {{{ */
868 @interface Database : NSObject {
870 pkgDepCache::Policy *policy_;
871 pkgRecords *records_;
872 pkgProblemResolver *resolver_;
873 pkgAcquire *fetcher_;
875 SPtr<pkgPackageManager> manager_;
876 pkgSourceList *list_;
878 NSMutableDictionary *sources_;
879 NSMutableArray *packages_;
881 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
890 + (Database *) sharedInstance;
892 - (void) _readCydia:(NSNumber *)fd;
893 - (void) _readStatus:(NSNumber *)fd;
894 - (void) _readOutput:(NSNumber *)fd;
898 - (Package *) packageWithName:(NSString *)name;
900 - (pkgCacheFile &) cache;
901 - (pkgDepCache::Policy *) policy;
902 - (pkgRecords *) records;
903 - (pkgProblemResolver *) resolver;
904 - (pkgAcquire &) fetcher;
905 - (NSArray *) packages;
906 - (NSArray *) sources;
915 - (void) updateWithStatus:(Status &)status;
917 - (void) setDelegate:(id)delegate;
918 - (Source *) getSource:(const pkgCache::PkgFileIterator &)file;
922 /* Source Class {{{ */
923 @interface Source : NSObject {
924 NSString *description_;
929 NSString *distribution_;
933 NSString *defaultIcon_;
935 NSDictionary *record_;
939 - (Source *) initWithMetaIndex:(metaIndex *)index;
941 - (NSComparisonResult) compareByNameAndType:(Source *)source;
943 - (NSDictionary *) record;
947 - (NSString *) distribution;
953 - (NSString *) description;
954 - (NSString *) label;
955 - (NSString *) origin;
956 - (NSString *) version;
958 - (NSString *) defaultIcon;
962 @implementation Source
966 [distribution_ release];
969 if (description_ != nil)
970 [description_ release];
977 if (defaultIcon_ != nil)
978 [defaultIcon_ release];
985 + (NSArray *) _attributeKeys {
986 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
989 - (NSArray *) attributeKeys {
990 return [[self class] _attributeKeys];
993 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
994 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
997 - (Source *) initWithMetaIndex:(metaIndex *)index {
998 if ((self = [super init]) != nil) {
999 trusted_ = index->IsTrusted();
1001 uri_ = [[NSString stringWithUTF8String:index->GetURI().c_str()] retain];
1002 distribution_ = [[NSString stringWithUTF8String:index->GetDist().c_str()] retain];
1003 type_ = [[NSString stringWithUTF8String:index->GetType()] retain];
1005 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1006 if (dindex != NULL) {
1007 std::ifstream release(dindex->MetaIndexFile("Release").c_str());
1009 while (std::getline(release, line)) {
1010 std::string::size_type colon(line.find(':'));
1011 if (colon == std::string::npos)
1014 std::string name(line.substr(0, colon));
1015 std::string value(line.substr(colon + 1));
1016 while (!value.empty() && value[0] == ' ')
1017 value = value.substr(1);
1019 if (name == "Default-Icon")
1020 defaultIcon_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1021 else if (name == "Description")
1022 description_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1023 else if (name == "Label")
1024 label_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1025 else if (name == "Origin")
1026 origin_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1027 else if (name == "Version")
1028 version_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1032 record_ = [Sources_ objectForKey:[self key]];
1034 record_ = [record_ retain];
1038 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1039 NSDictionary *lhr = [self record];
1040 NSDictionary *rhr = [source record];
1043 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1045 NSString *lhs = [self name];
1046 NSString *rhs = [source name];
1048 if ([lhs length] != 0 && [rhs length] != 0) {
1049 unichar lhc = [lhs characterAtIndex:0];
1050 unichar rhc = [rhs characterAtIndex:0];
1052 if (isalpha(lhc) && !isalpha(rhc))
1053 return NSOrderedAscending;
1054 else if (!isalpha(lhc) && isalpha(rhc))
1055 return NSOrderedDescending;
1058 return [lhs compare:rhs options:CompareOptions_];
1061 - (NSDictionary *) record {
1069 - (NSString *) uri {
1073 - (NSString *) distribution {
1074 return distribution_;
1077 - (NSString *) type {
1081 - (NSString *) key {
1082 return [NSString stringWithFormat:@"%@:%@:%@", type_, uri_, distribution_];
1085 - (NSString *) host {
1086 return [[[NSURL URLWithString:[self uri]] host] lowercaseString];
1089 - (NSString *) name {
1090 return origin_ == nil ? [self host] : origin_;
1093 - (NSString *) description {
1094 return description_;
1097 - (NSString *) label {
1098 return label_ == nil ? [self host] : label_;
1101 - (NSString *) origin {
1105 - (NSString *) version {
1109 - (NSString *) defaultIcon {
1110 return defaultIcon_;
1115 /* Relationship Class {{{ */
1116 @interface Relationship : NSObject {
1121 - (NSString *) type;
1123 - (NSString *) name;
1127 @implementation Relationship
1135 - (NSString *) type {
1143 - (NSString *) name {
1150 /* Package Class {{{ */
1151 @interface Package : NSObject {
1152 pkgCache::PkgIterator iterator_;
1153 _transient Database *database_;
1154 pkgCache::VerIterator version_;
1155 pkgCache::VerFileIterator file_;
1163 NSString *installed_;
1169 NSString *depiction_;
1170 NSString *homepage_;
1176 NSArray *relationships_;
1179 - (Package *) initWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database;
1180 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database;
1182 - (pkgCache::PkgIterator) iterator;
1184 - (NSString *) section;
1185 - (NSString *) simpleSection;
1187 - (Address *) maintainer;
1189 - (NSString *) description;
1190 - (NSString *) index;
1192 - (NSMutableDictionary *) metadata;
1194 - (BOOL) subscribed;
1197 - (NSString *) latest;
1198 - (NSString *) installed;
1201 - (BOOL) upgradableAndEssential:(BOOL)essential;
1204 - (BOOL) unfiltered;
1208 - (BOOL) halfConfigured;
1209 - (BOOL) halfInstalled;
1211 - (NSString *) mode;
1214 - (NSString *) name;
1215 - (NSString *) tagline;
1217 - (NSString *) homepage;
1218 - (NSString *) depiction;
1219 - (Address *) author;
1221 - (NSArray *) files;
1222 - (NSArray *) relationships;
1223 - (NSArray *) warnings;
1224 - (NSArray *) applications;
1226 - (Source *) source;
1227 - (NSString *) role;
1229 - (BOOL) matches:(NSString *)text;
1231 - (bool) hasSupportingRole;
1232 - (BOOL) hasTag:(NSString *)tag;
1233 - (NSString *) primaryPurpose;
1234 - (NSArray *) purposes;
1236 - (NSComparisonResult) compareByName:(Package *)package;
1237 - (NSComparisonResult) compareBySection:(Package *)package;
1239 - (uint32_t) compareForChanges;
1244 - (NSNumber *) isUnfilteredAndSearchedForBy:(NSString *)search;
1245 - (NSNumber *) isInstalledAndVisible:(NSNumber *)number;
1246 - (NSNumber *) isVisiblyUninstalledInSection:(NSString *)section;
1247 - (NSNumber *) isVisibleInSource:(Source *)source;
1251 @implementation Package
1257 if (section_ != nil)
1261 if (installed_ != nil)
1262 [installed_ release];
1270 if (depiction_ != nil)
1271 [depiction_ release];
1272 if (homepage_ != nil)
1273 [homepage_ release];
1274 if (sponsor_ != nil)
1283 if (relationships_ != nil)
1284 [relationships_ release];
1289 + (NSArray *) _attributeKeys {
1290 return [NSArray arrayWithObjects:@"applications", @"author", @"depiction", @"description", @"essential", @"homepage", @"icon", @"id", @"installed", @"latest", @"maintainer", @"name", @"purposes", @"section", @"size", @"source", @"sponsor", @"tagline", @"warnings", nil];
1293 - (NSArray *) attributeKeys {
1294 return [[self class] _attributeKeys];
1297 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1298 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1301 - (Package *) initWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database {
1302 if ((self = [super init]) != nil) {
1303 iterator_ = iterator;
1304 database_ = database;
1306 version_ = [database_ policy]->GetCandidateVer(iterator_);
1307 NSString *latest = version_.end() ? nil : [NSString stringWithUTF8String:version_.VerStr()];
1308 latest_ = latest == nil ? nil : [StripVersion(latest) retain];
1310 pkgCache::VerIterator current = iterator_.CurrentVer();
1311 NSString *installed = current.end() ? nil : [NSString stringWithUTF8String:current.VerStr()];
1312 installed_ = [StripVersion(installed) retain];
1314 if (!version_.end())
1315 file_ = version_.FileList();
1317 pkgCache &cache([database_ cache]);
1318 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
1321 id_ = [[NSString stringWithUTF8String:iterator_.Name()] retain];
1324 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
1326 const char *begin, *end;
1327 parser->GetRec(begin, end);
1329 NSString *website(nil);
1330 NSString *sponsor(nil);
1331 NSString *author(nil);
1340 {"depiction", &depiction_},
1341 {"homepage", &homepage_},
1342 {"website", &website},
1343 {"sponsor", &sponsor},
1344 {"author", &author},
1348 while (begin != end)
1349 if (*begin == '\n') {
1352 } else if (isblank(*begin)) next: {
1353 begin = static_cast<char *>(memchr(begin + 1, '\n', end - begin - 1));
1356 } else if (const char *colon = static_cast<char *>(memchr(begin, ':', end - begin))) {
1357 const char *name(begin);
1358 size_t size(colon - begin);
1360 begin = static_cast<char *>(memchr(begin, '\n', end - begin));
1363 const char *stop(begin == NULL ? end : begin);
1364 while (stop[-1] == '\r')
1366 while (++colon != stop && isblank(*colon));
1368 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i)
1369 if (strncasecmp(names[i].name_, name, size) == 0) {
1370 NSString *value([NSString stringWithUTF8Bytes:colon length:(stop - colon)]);
1371 *names[i].value_ = value;
1382 name_ = [name_ retain];
1383 tagline_ = [[NSString stringWithUTF8String:parser->ShortDesc().c_str()] retain];
1385 icon_ = [icon_ retain];
1386 if (depiction_ != nil)
1387 depiction_ = [depiction_ retain];
1388 if (homepage_ == nil)
1389 homepage_ = website;
1390 if ([homepage_ isEqualToString:depiction_])
1392 if (homepage_ != nil)
1393 homepage_ = [homepage_ retain];
1395 sponsor_ = [[Address addressWithString:sponsor] retain];
1397 author_ = [[Address addressWithString:author] retain];
1399 tags_ = [[tag componentsSeparatedByString:@", "] retain];
1403 for (int i(0), e([tags_ count]); i != e; ++i) {
1404 NSString *tag = [tags_ objectAtIndex:i];
1405 if ([tag hasPrefix:@"role::"]) {
1406 role_ = [[tag substringFromIndex:6] retain];
1411 NSString *solid(latest == nil ? installed : latest);
1412 bool changed(false);
1414 NSString *key([id_ lowercaseString]);
1416 NSMutableDictionary *metadata = [Packages_ objectForKey:key];
1417 if (metadata == nil) {
1418 metadata = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
1423 [metadata setObject:solid forKey:@"LastVersion"];
1426 NSDate *first([metadata objectForKey:@"FirstSeen"]);
1427 NSDate *last([metadata objectForKey:@"LastSeen"]);
1428 NSString *version([metadata objectForKey:@"LastVersion"]);
1431 first = last == nil ? now_ : last;
1432 [metadata setObject:first forKey:@"FirstSeen"];
1437 if (version == nil) {
1438 [metadata setObject:solid forKey:@"LastVersion"];
1440 } else if (![version isEqualToString:solid]) {
1441 [metadata setObject:solid forKey:@"LastVersion"];
1443 [metadata setObject:last forKey:@"LastSeen"];
1449 [Packages_ setObject:metadata forKey:key];
1455 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database {
1456 return [[[Package alloc]
1457 initWithIterator:iterator
1462 - (pkgCache::PkgIterator) iterator {
1466 - (NSString *) section {
1467 if (section_ != nil)
1470 const char *section = iterator_.Section();
1471 if (section == NULL)
1474 NSString *name = [[NSString stringWithUTF8String:section] stringByReplacingCharacter:' ' withCharacter:'_'];
1477 if (NSDictionary *value = [SectionMap_ objectForKey:name])
1478 if (NSString *rename = [value objectForKey:@"Rename"]) {
1483 section_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
1487 - (NSString *) simpleSection {
1488 if (NSString *section = [self section])
1489 return Simplify(section);
1495 - (Address *) maintainer {
1498 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
1499 return [Address addressWithString:[NSString stringWithUTF8String:parser->Maintainer().c_str()]];
1503 return version_.end() ? 0 : version_->InstalledSize;
1506 - (NSString *) description {
1509 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
1510 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
1512 NSArray *lines = [description componentsSeparatedByString:@"\n"];
1513 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
1514 if ([lines count] < 2)
1517 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
1518 for (size_t i(1); i != [lines count]; ++i) {
1519 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
1520 [trimmed addObject:trim];
1523 return [trimmed componentsJoinedByString:@"\n"];
1526 - (NSString *) index {
1527 NSString *index = [[[self name] substringToIndex:1] uppercaseString];
1528 return [index length] != 0 && isalpha([index characterAtIndex:0]) ? index : @"123";
1531 - (NSMutableDictionary *) metadata {
1532 return [Packages_ objectForKey:[id_ lowercaseString]];
1536 NSDictionary *metadata([self metadata]);
1537 if ([self subscribed])
1538 if (NSDate *last = [metadata objectForKey:@"LastSeen"])
1540 return [metadata objectForKey:@"FirstSeen"];
1543 - (BOOL) subscribed {
1544 NSDictionary *metadata([self metadata]);
1545 if (NSNumber *subscribed = [metadata objectForKey:@"IsSubscribed"])
1546 return [subscribed boolValue];
1552 NSDictionary *metadata([self metadata]);
1553 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
1554 return [ignored boolValue];
1559 - (NSString *) latest {
1563 - (NSString *) installed {
1568 return !version_.end();
1571 - (BOOL) upgradableAndEssential:(BOOL)essential {
1572 pkgCache::VerIterator current = iterator_.CurrentVer();
1575 return essential && [self essential];
1577 return !version_.end() && version_ != current;
1580 - (BOOL) essential {
1581 return (iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES;
1585 return [database_ cache][iterator_].InstBroken();
1588 - (BOOL) unfiltered {
1589 NSString *section = [self section];
1590 return section == nil || isSectionVisible(section);
1594 return [self hasSupportingRole] && [self unfiltered];
1598 unsigned char current = iterator_->CurrentState;
1599 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
1602 - (BOOL) halfConfigured {
1603 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
1606 - (BOOL) halfInstalled {
1607 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
1611 pkgDepCache::StateCache &state([database_ cache][iterator_]);
1612 return state.Mode != pkgDepCache::ModeKeep;
1615 - (NSString *) mode {
1616 pkgDepCache::StateCache &state([database_ cache][iterator_]);
1618 switch (state.Mode) {
1619 case pkgDepCache::ModeDelete:
1620 if ((state.iFlags & pkgDepCache::Purge) != 0)
1624 case pkgDepCache::ModeKeep:
1625 if ((state.iFlags & pkgDepCache::AutoKept) != 0)
1629 case pkgDepCache::ModeInstall:
1630 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
1631 return @"Reinstall";
1632 else switch (state.Status) {
1634 return @"Downgrade";
1640 return @"New Install";
1653 - (NSString *) name {
1654 return name_ == nil ? id_ : name_;
1657 - (NSString *) tagline {
1661 - (UIImage *) icon {
1662 NSString *section = [self simpleSection];
1665 if (NSString *icon = icon_)
1666 icon = [UIImage imageAtPath:[icon_ substringFromIndex:6]];
1667 if (icon == nil) if (section != nil)
1668 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
1669 if (icon == nil) if (source_ != nil) if (NSString *icon = [source_ defaultIcon])
1670 icon = [UIImage imageAtPath:[icon substringFromIndex:6]];
1672 icon = [UIImage applicationImageNamed:@"unknown.png"];
1676 - (NSString *) homepage {
1680 - (NSString *) depiction {
1684 - (Address *) sponsor {
1688 - (Address *) author {
1692 - (NSArray *) files {
1693 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", id_];
1694 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
1697 fin.open([path UTF8String]);
1702 while (std::getline(fin, line))
1703 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
1708 - (NSArray *) relationships {
1709 return relationships_;
1712 - (NSArray *) warnings {
1713 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
1714 const char *name(iterator_.Name());
1716 size_t length(strlen(name));
1717 if (length < 2) invalid:
1718 [warnings addObject:@"illegal package identifier"];
1719 else for (size_t i(0); i != length; ++i)
1721 (name[i] < 'a' || name[i] > 'z') &&
1722 (name[i] < '0' || name[i] > '9') &&
1723 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
1726 if (strcmp(name, "cydia") != 0) {
1730 if (NSArray *files = [self files])
1731 for (NSString *file in files)
1732 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
1734 else if (!stash && [file isEqualToString:@"/var/stash"])
1738 [warnings addObject:@"files installed into Cydia.app"];
1740 [warnings addObject:@"files installed to /var/stash"];
1743 return [warnings count] == 0 ? nil : warnings;
1746 - (NSArray *) applications {
1747 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
1749 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
1751 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
1752 if (NSArray *files = [self files])
1753 for (NSString *file in files)
1754 if (application_r(file)) {
1755 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
1756 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
1757 if ([id isEqualToString:me])
1760 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
1762 display = application_r[1];
1764 NSString *bundle([file stringByDeletingLastPathComponent]);
1765 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
1766 if (icon == nil || [icon length] == 0)
1768 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
1770 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
1771 [applications addObject:application];
1773 [application addObject:id];
1774 [application addObject:display];
1775 [application addObject:url];
1778 return [applications count] == 0 ? nil : applications;
1781 - (Source *) source {
1783 source_ = file_.end() ? nil : [[database_ getSource:file_.File()] retain];
1790 - (NSString *) role {
1794 - (BOOL) matches:(NSString *)text {
1800 range = [[self id] rangeOfString:text options:NSCaseInsensitiveSearch];
1801 if (range.location != NSNotFound)
1804 range = [[self name] rangeOfString:text options:NSCaseInsensitiveSearch];
1805 if (range.location != NSNotFound)
1808 range = [[self tagline] rangeOfString:text options:NSCaseInsensitiveSearch];
1809 if (range.location != NSNotFound)
1815 - (bool) hasSupportingRole {
1818 if ([role_ isEqualToString:@"enduser"])
1820 if ([Role_ isEqualToString:@"User"])
1822 if ([role_ isEqualToString:@"hacker"])
1824 if ([Role_ isEqualToString:@"Hacker"])
1826 if ([role_ isEqualToString:@"developer"])
1828 if ([Role_ isEqualToString:@"Developer"])
1833 - (BOOL) hasTag:(NSString *)tag {
1834 return tags_ == nil ? NO : [tags_ containsObject:tag];
1837 - (NSString *) primaryPurpose {
1838 for (NSString *tag in tags_)
1839 if ([tag hasPrefix:@"purpose::"])
1840 return [tag substringFromIndex:9];
1844 - (NSArray *) purposes {
1845 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
1846 for (NSString *tag in tags_)
1847 if ([tag hasPrefix:@"purpose::"])
1848 [purposes addObject:[tag substringFromIndex:9]];
1849 return [purposes count] == 0 ? nil : purposes;
1852 - (NSComparisonResult) compareByName:(Package *)package {
1853 NSString *lhs = [self name];
1854 NSString *rhs = [package name];
1856 if ([lhs length] != 0 && [rhs length] != 0) {
1857 unichar lhc = [lhs characterAtIndex:0];
1858 unichar rhc = [rhs characterAtIndex:0];
1860 if (isalpha(lhc) && !isalpha(rhc))
1861 return NSOrderedAscending;
1862 else if (!isalpha(lhc) && isalpha(rhc))
1863 return NSOrderedDescending;
1866 return [lhs compare:rhs options:CompareOptions_];
1869 - (NSComparisonResult) compareBySection:(Package *)package {
1870 NSString *lhs = [self section];
1871 NSString *rhs = [package section];
1873 if (lhs == NULL && rhs != NULL)
1874 return NSOrderedAscending;
1875 else if (lhs != NULL && rhs == NULL)
1876 return NSOrderedDescending;
1877 else if (lhs != NULL && rhs != NULL) {
1878 NSComparisonResult result = [lhs compare:rhs options:CompareOptions_];
1879 if (result != NSOrderedSame)
1883 return NSOrderedSame;
1886 - (uint32_t) compareForChanges {
1891 uint32_t timestamp : 30;
1892 uint32_t ignored : 1;
1893 uint32_t upgradable : 1;
1897 value.bits.upgradable = [self upgradableAndEssential:YES] ? 1 : 0;
1899 if ([self upgradableAndEssential:YES]) {
1900 value.bits.timestamp = 0;
1901 value.bits.ignored = [self ignored] ? 0 : 1;
1902 value.bits.upgradable = 1;
1904 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1905 value.bits.ignored = 0;
1906 value.bits.upgradable = 0;
1909 return _not(uint32_t) - value.key;
1913 pkgProblemResolver *resolver = [database_ resolver];
1914 resolver->Clear(iterator_);
1915 resolver->Protect(iterator_);
1916 pkgCacheFile &cache([database_ cache]);
1917 cache->MarkInstall(iterator_, false);
1918 pkgDepCache::StateCache &state((*cache)[iterator_]);
1919 if (!state.Install())
1920 cache->SetReInstall(iterator_, true);
1924 pkgProblemResolver *resolver = [database_ resolver];
1925 resolver->Clear(iterator_);
1926 resolver->Protect(iterator_);
1927 resolver->Remove(iterator_);
1928 [database_ cache]->MarkDelete(iterator_, true);
1931 - (NSNumber *) isUnfilteredAndSearchedForBy:(NSString *)search {
1932 return [NSNumber numberWithBool:(
1933 [self unfiltered] && [self matches:search]
1937 - (NSNumber *) isInstalledAndVisible:(NSNumber *)number {
1938 return [NSNumber numberWithBool:(
1939 (![number boolValue] || [self visible]) && [self installed] != nil
1943 - (NSNumber *) isVisiblyUninstalledInSection:(NSString *)name {
1944 NSString *section = [self section];
1946 return [NSNumber numberWithBool:(
1948 [self installed] == nil && (
1950 section == nil && [name length] == 0 ||
1951 [name isEqualToString:section]
1956 - (NSNumber *) isVisibleInSource:(Source *)source {
1957 return [NSNumber numberWithBool:([self source] == source && [self visible])];
1962 /* Section Class {{{ */
1963 @interface Section : NSObject {
1969 - (NSComparisonResult) compareByName:(Section *)section;
1970 - (Section *) initWithName:(NSString *)name;
1971 - (Section *) initWithName:(NSString *)name row:(size_t)row;
1972 - (NSString *) name;
1975 - (void) addToCount;
1979 @implementation Section
1986 - (NSComparisonResult) compareByName:(Section *)section {
1987 NSString *lhs = [self name];
1988 NSString *rhs = [section name];
1990 if ([lhs length] != 0 && [rhs length] != 0) {
1991 unichar lhc = [lhs characterAtIndex:0];
1992 unichar rhc = [rhs characterAtIndex:0];
1994 if (isalpha(lhc) && !isalpha(rhc))
1995 return NSOrderedAscending;
1996 else if (!isalpha(lhc) && isalpha(rhc))
1997 return NSOrderedDescending;
2000 return [lhs compare:rhs options:CompareOptions_];
2003 - (Section *) initWithName:(NSString *)name {
2004 return [self initWithName:name row:0];
2007 - (Section *) initWithName:(NSString *)name row:(size_t)row {
2008 if ((self = [super init]) != nil) {
2009 name_ = [name retain];
2014 - (NSString *) name {
2026 - (void) addToCount {
2034 static NSArray *Finishes_;
2036 /* Database Implementation {{{ */
2037 @implementation Database
2039 + (Database *) sharedInstance {
2040 static Database *instance;
2041 if (instance == nil)
2042 instance = [[Database alloc] init];
2051 - (void) _readCydia:(NSNumber *)fd { _pooled
2052 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2053 std::istream is(&ib);
2056 static Pcre finish_r("^finish:([^:]*)$");
2058 while (std::getline(is, line)) {
2059 const char *data(line.c_str());
2060 size_t size = line.size();
2061 lprintf("C:%s\n", data);
2063 if (finish_r(data, size)) {
2064 NSString *finish = finish_r[1];
2065 int index = [Finishes_ indexOfObject:finish];
2066 if (index != INT_MAX && index > Finish_)
2074 - (void) _readStatus:(NSNumber *)fd { _pooled
2075 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2076 std::istream is(&ib);
2079 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2080 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2082 while (std::getline(is, line)) {
2083 const char *data(line.c_str());
2084 size_t size = line.size();
2085 lprintf("S:%s\n", data);
2087 if (conffile_r(data, size)) {
2088 [delegate_ setConfigurationData:conffile_r[1]];
2089 } else if (strncmp(data, "status: ", 8) == 0) {
2090 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2091 [delegate_ setProgressTitle:string];
2092 } else if (pmstatus_r(data, size)) {
2093 std::string type([pmstatus_r[1] UTF8String]);
2094 NSString *id = pmstatus_r[2];
2096 float percent([pmstatus_r[3] floatValue]);
2097 [delegate_ setProgressPercent:(percent / 100)];
2099 NSString *string = pmstatus_r[4];
2101 if (type == "pmerror")
2102 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2103 withObject:[NSArray arrayWithObjects:string, id, nil]
2106 else if (type == "pmstatus") {
2107 [delegate_ setProgressTitle:string];
2108 } else if (type == "pmconffile")
2109 [delegate_ setConfigurationData:string];
2110 else _assert(false);
2111 } else _assert(false);
2117 - (void) _readOutput:(NSNumber *)fd { _pooled
2118 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2119 std::istream is(&ib);
2122 while (std::getline(is, line)) {
2123 lprintf("O:%s\n", line.c_str());
2124 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2134 - (Package *) packageWithName:(NSString *)name {
2135 if (static_cast<pkgDepCache *>(cache_) == NULL)
2137 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2138 return iterator.end() ? nil : [Package packageWithIterator:iterator database:self];
2141 - (Database *) init {
2142 if ((self = [super init]) != nil) {
2149 sources_ = [[NSMutableDictionary dictionaryWithCapacity:16] retain];
2150 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
2154 _assert(pipe(fds) != -1);
2157 _config->Set("APT::Keep-Fds::", cydiafd_);
2158 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
2161 detachNewThreadSelector:@selector(_readCydia:)
2163 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2166 _assert(pipe(fds) != -1);
2170 detachNewThreadSelector:@selector(_readStatus:)
2172 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2175 _assert(pipe(fds) != -1);
2176 _assert(dup2(fds[0], 0) != -1);
2177 _assert(close(fds[0]) != -1);
2179 input_ = fdopen(fds[1], "a");
2181 _assert(pipe(fds) != -1);
2182 _assert(dup2(fds[1], 1) != -1);
2183 _assert(close(fds[1]) != -1);
2186 detachNewThreadSelector:@selector(_readOutput:)
2188 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2193 - (pkgCacheFile &) cache {
2197 - (pkgDepCache::Policy *) policy {
2201 - (pkgRecords *) records {
2205 - (pkgProblemResolver *) resolver {
2209 - (pkgAcquire &) fetcher {
2213 - (NSArray *) packages {
2217 - (NSArray *) sources {
2218 return [sources_ allValues];
2221 - (NSArray *) issues {
2222 if (cache_->BrokenCount() == 0)
2225 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
2227 for (Package *package in packages_) {
2228 if (![package broken])
2230 pkgCache::PkgIterator pkg([package iterator]);
2232 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
2233 [entry addObject:[package name]];
2234 [issues addObject:entry];
2236 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
2240 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
2241 pkgCache::DepIterator start;
2242 pkgCache::DepIterator end;
2243 dep.GlobOr(start, end); // ++dep
2245 if (!cache_->IsImportantDep(end))
2247 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
2250 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
2251 [entry addObject:failure];
2252 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
2254 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
2255 [failure addObject:[package name]];
2257 pkgCache::PkgIterator target(start.TargetPkg());
2258 if (target->ProvidesList != 0)
2259 [failure addObject:@"?"];
2261 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
2263 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
2264 else if (!cache_[target].CandidateVerIter(cache_).end())
2265 [failure addObject:@"-"];
2266 else if (target->ProvidesList == 0)
2267 [failure addObject:@"!"];
2269 [failure addObject:@"%"];
2273 if (start.TargetVer() != 0)
2274 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
2285 - (void) reloadData {
2305 if (!cache_.Open(progress_, true)) {
2307 if (!_error->PopMessage(error))
2310 lprintf("cache_.Open():[%s]\n", error.c_str());
2312 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
2313 [delegate_ repairWithSelector:@selector(configure)];
2314 else if (error == "The package lists or status file could not be parsed or opened.")
2315 [delegate_ repairWithSelector:@selector(update)];
2316 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
2317 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
2318 // else if (error == "The list of sources could not be read.")
2319 else _assert(false);
2325 now_ = [[NSDate date] retain];
2327 policy_ = new pkgDepCache::Policy();
2328 records_ = new pkgRecords(cache_);
2329 resolver_ = new pkgProblemResolver(cache_);
2330 fetcher_ = new pkgAcquire(&status_);
2333 list_ = new pkgSourceList();
2334 _assert(list_->ReadMainList());
2336 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
2337 _assert(pkgApplyStatus(cache_));
2339 if (cache_->BrokenCount() != 0) {
2340 _assert(pkgFixBroken(cache_));
2341 _assert(cache_->BrokenCount() == 0);
2342 _assert(pkgMinimizeUpgrade(cache_));
2345 [sources_ removeAllObjects];
2346 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
2347 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
2348 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
2350 setObject:[[[Source alloc] initWithMetaIndex:*source] autorelease]
2351 forKey:[NSNumber numberWithLong:reinterpret_cast<uintptr_t>(*index)]
2355 [packages_ removeAllObjects];
2358 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
2359 if (Package *package = [Package packageWithIterator:iterator database:self])
2360 [packages_ addObject:package];
2362 [packages_ sortUsingSelector:@selector(compareByName:)];
2366 - (void) configure {
2367 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
2368 system([dpkg UTF8String]);
2376 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
2377 _assert(!_error->PendingError());
2380 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
2383 public pkgArchiveCleaner
2386 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
2391 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
2393 while (_error->PopMessage(error))
2394 lprintf("ArchiveCleaner: %s\n", error.c_str());
2399 pkgRecords records(cache_);
2401 lock_ = new FileFd();
2402 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
2403 _assert(!_error->PendingError());
2406 // XXX: explain this with an error message
2407 _assert(list.ReadMainList());
2409 manager_ = (_system->CreatePM(cache_));
2410 _assert(manager_->GetArchives(fetcher_, &list, &records));
2411 _assert(!_error->PendingError());
2415 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
2417 _assert(list.ReadMainList());
2418 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
2419 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
2422 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
2427 bool failed = false;
2428 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
2429 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
2432 std::string uri = (*item)->DescURI();
2433 std::string error = (*item)->ErrorText;
2435 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
2438 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2439 withObject:[NSArray arrayWithObjects:[NSString stringWithUTF8String:error.c_str()], nil]
2450 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
2452 if (_error->PendingError()) {
2457 if (result == pkgPackageManager::Failed) {
2462 if (result != pkgPackageManager::Completed) {
2467 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
2469 _assert(list.ReadMainList());
2470 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
2471 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
2474 if (![before isEqualToArray:after])
2479 _assert(pkgDistUpgrade(cache_));
2483 [self updateWithStatus:status_];
2486 - (void) updateWithStatus:(Status &)status {
2488 _assert(list.ReadMainList());
2491 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
2492 _assert(!_error->PendingError());
2494 pkgAcquire fetcher(&status);
2495 _assert(list.GetIndexes(&fetcher));
2497 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
2498 bool failed = false;
2499 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
2500 if ((*item)->Status != pkgAcquire::Item::StatDone) {
2501 (*item)->Finished();
2505 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
2506 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
2507 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
2510 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
2515 - (void) setDelegate:(id)delegate {
2516 delegate_ = delegate;
2517 status_.setDelegate(delegate);
2518 progress_.setDelegate(delegate);
2521 - (Source *) getSource:(const pkgCache::PkgFileIterator &)file {
2522 pkgIndexFile *index(NULL);
2523 list_->FindIndex(file, index);
2524 return [sources_ objectForKey:[NSNumber numberWithLong:reinterpret_cast<uintptr_t>(index)]];
2530 /* PopUp Windows {{{ */
2531 @interface PopUpView : UIView {
2532 _transient id delegate_;
2533 UITransitionView *transition_;
2538 - (id) initWithView:(UIView *)view delegate:(id)delegate;
2542 @implementation PopUpView
2545 [transition_ setDelegate:nil];
2546 [transition_ release];
2552 [transition_ transition:UITransitionPushFromTop toView:nil];
2555 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
2556 if (from != nil && to == nil)
2557 [self removeFromSuperview];
2560 - (id) initWithView:(UIView *)view delegate:(id)delegate {
2561 if ((self = [super initWithFrame:[view bounds]]) != nil) {
2562 delegate_ = delegate;
2564 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
2565 [self addSubview:transition_];
2567 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
2569 [view addSubview:self];
2571 [transition_ setDelegate:self];
2573 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
2574 [transition_ transition:UITransitionNone toView:blank];
2575 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
2582 /* Mail Composition {{{ */
2583 @interface MailToView : PopUpView {
2584 MailComposeController *controller_;
2587 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
2591 @implementation MailToView
2594 [controller_ release];
2598 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
2602 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
2603 NSLog(@"did:%@", delivery);
2604 // [UIApp setStatusBarShowsProgress:NO];
2605 if ([controller error]){
2606 NSArray *buttons = [NSArray arrayWithObjects:@"OK", nil];
2607 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:@"Error" buttons:buttons defaultButtonIndex:0 delegate:self context:self];
2608 [mailAlertSheet setBodyText:[controller error]];
2609 [mailAlertSheet popupAlertAnimated:YES];
2613 - (void) showError {
2614 NSLog(@"%@", [controller_ error]);
2615 NSArray *buttons = [NSArray arrayWithObjects:@"OK", nil];
2616 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:@"Error" buttons:buttons defaultButtonIndex:0 delegate:self context:self];
2617 [mailAlertSheet setBodyText:[controller_ error]];
2618 [mailAlertSheet popupAlertAnimated:YES];
2621 - (void) deliverMessage { _pooled
2625 if (![controller_ deliverMessage])
2626 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
2629 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
2630 if ([controller_ needsDelivery])
2631 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
2636 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
2637 if ((self = [super initWithView:view delegate:delegate]) != nil) {
2638 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
2639 [controller_ setDelegate:self];
2640 [controller_ initializeUI];
2641 [controller_ setupForURL:url];
2643 UIView *view([controller_ view]);
2644 [overlay_ addSubview:view];
2650 /* Confirmation View {{{ */
2651 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
2652 if (!iterator.end())
2653 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
2654 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
2656 pkgCache::PkgIterator package(dep.TargetPkg());
2659 if (strcmp(package.Name(), "mobilesubstrate") == 0)
2666 @protocol ConfirmationViewDelegate
2671 @interface ConfirmationView : BrowserView {
2672 _transient Database *database_;
2673 UIActionSheet *essential_;
2680 - (id) initWithBook:(RVBook *)book database:(Database *)database;
2684 @implementation ConfirmationView
2691 if (essential_ != nil)
2692 [essential_ release];
2698 [book_ popFromSuperviewAnimated:YES];
2701 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
2702 NSString *context([sheet context]);
2704 if ([context isEqualToString:@"remove"]) {
2712 [delegate_ confirm];
2719 } else if ([context isEqualToString:@"unable"]) {
2723 [super alertSheet:sheet buttonClicked:button];
2726 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
2727 [window setValue:changes_ forKey:@"changes"];
2728 [window setValue:issues_ forKey:@"issues"];
2729 [window setValue:sizes_ forKey:@"sizes"];
2730 [super webView:sender didClearWindowObject:window forFrame:frame];
2733 - (id) initWithBook:(RVBook *)book database:(Database *)database {
2734 if ((self = [super initWithBook:book]) != nil) {
2735 database_ = database;
2737 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
2738 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
2739 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
2740 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
2741 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
2745 pkgDepCache::Policy *policy([database_ policy]);
2747 pkgCacheFile &cache([database_ cache]);
2748 NSArray *packages = [database_ packages];
2749 for (size_t i(0), e = [packages count]; i != e; ++i) {
2750 Package *package = [packages objectAtIndex:i];
2751 pkgCache::PkgIterator iterator = [package iterator];
2752 pkgDepCache::StateCache &state(cache[iterator]);
2754 NSString *name([package name]);
2756 if (state.NewInstall())
2757 [installing addObject:name];
2758 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
2759 [reinstalling addObject:name];
2760 else if (state.Upgrade())
2761 [upgrading addObject:name];
2762 else if (state.Downgrade())
2763 [downgrading addObject:name];
2764 else if (state.Delete()) {
2765 if ([package essential])
2767 [removing addObject:name];
2770 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
2771 substrate_ |= DepSubstrate(iterator.CurrentVer());
2776 else if (Advanced_ || true) {
2777 essential_ = [[UIActionSheet alloc]
2778 initWithTitle:@"Removing Essentials"
2779 buttons:[NSArray arrayWithObjects:
2780 @"Cancel Operation (Safe)",
2781 @"Force Removal (Unsafe)",
2783 defaultButtonIndex:0
2789 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
2791 [essential_ setBodyText:@"This operation involves the removal of one or more packages that are required for the continued operation of either Cydia or iPhoneOS. If you continue, you may not be able to use Cydia to repair any damage."];
2793 essential_ = [[UIActionSheet alloc]
2794 initWithTitle:@"Unable to Comply"
2795 buttons:[NSArray arrayWithObjects:@"Okay", nil]
2796 defaultButtonIndex:0
2801 [essential_ setBodyText:@"This operation requires the removal of one or more packages that are required for the continued operation of either Cydia or iPhoneOS. In order to continue and force this operation you will need to be activate the Advanced mode under to continue and force this operation you will need to be activate the Advanced mode under Settings."];
2804 changes_ = [[NSArray alloc] initWithObjects:
2812 issues_ = [database_ issues];
2814 issues_ = [issues_ retain];
2816 sizes_ = [[NSArray alloc] initWithObjects:
2817 SizeString([database_ fetcher].FetchNeeded()),
2818 SizeString([database_ fetcher].PartialPresent()),
2819 SizeString([database_ cache]->UsrSize()),
2822 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
2826 - (NSString *) backButtonTitle {
2830 - (NSString *) leftButtonTitle {
2834 - (NSString *) _rightButtonTitle {
2835 return issues_ == nil ? @"Confirm" : nil;
2838 - (void) _leftButtonClicked {
2843 - (void) _rightButtonClicked {
2844 if (essential_ != nil)
2845 [essential_ popupAlertAnimated:YES];
2849 [delegate_ confirm];
2857 /* Progress Data {{{ */
2858 @interface ProgressData : NSObject {
2864 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
2871 @implementation ProgressData
2873 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
2874 if ((self = [super init]) != nil) {
2875 selector_ = selector;
2895 /* Progress View {{{ */
2896 @interface ProgressView : UIView <
2897 ConfigurationDelegate,
2900 _transient Database *database_;
2902 UIView *background_;
2903 UITransitionView *transition_;
2905 UINavigationBar *navbar_;
2906 UIProgressBar *progress_;
2907 UITextView *output_;
2908 UITextLabel *status_;
2909 UIPushButton *close_;
2912 SHA1SumValue springlist_;
2913 SHA1SumValue sandplate_;
2915 NSTimeInterval last_;
2918 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
2920 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
2921 - (void) setContentView:(UIView *)view;
2924 - (void) _retachThread;
2925 - (void) _detachNewThreadData:(ProgressData *)data;
2926 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
2932 @protocol ProgressViewDelegate
2933 - (void) progressViewIsComplete:(ProgressView *)sender;
2936 @implementation ProgressView
2939 [transition_ setDelegate:nil];
2940 [navbar_ setDelegate:nil];
2943 if (background_ != nil)
2944 [background_ release];
2945 [transition_ release];
2948 [progress_ release];
2955 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
2956 if (bootstrap_ && from == overlay_ && to == view_)
2960 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
2961 if ((self = [super initWithFrame:frame]) != nil) {
2962 database_ = database;
2963 delegate_ = delegate;
2965 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
2966 [transition_ setDelegate:self];
2968 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
2971 [overlay_ setBackgroundColor:[UIColor blackColor]];
2973 background_ = [[UIView alloc] initWithFrame:[self bounds]];
2974 [background_ setBackgroundColor:[UIColor blackColor]];
2975 [self addSubview:background_];
2978 [self addSubview:transition_];
2980 CGSize navsize = [UINavigationBar defaultSize];
2981 CGRect navrect = {{0, 0}, navsize};
2983 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
2984 [overlay_ addSubview:navbar_];
2986 [navbar_ setBarStyle:1];
2987 [navbar_ setDelegate:self];
2989 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
2990 [navbar_ pushNavigationItem:navitem];
2992 CGRect bounds = [overlay_ bounds];
2993 CGSize prgsize = [UIProgressBar defaultSize];
2996 (bounds.size.width - prgsize.width) / 2,
2997 bounds.size.height - prgsize.height - 20
3000 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3001 [progress_ setStyle:0];
3003 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3005 bounds.size.height - prgsize.height - 50,
3006 bounds.size.width - 20,
3010 [status_ setColor:[UIColor whiteColor]];
3011 [status_ setBackgroundColor:[UIColor clearColor]];
3013 [status_ setCentersHorizontally:YES];
3014 //[status_ setFont:font];
3016 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3018 navrect.size.height + 20,
3019 bounds.size.width - 20,
3020 bounds.size.height - navsize.height - 62 - navrect.size.height
3023 //[output_ setTextFont:@"Courier New"];
3024 [output_ setTextSize:12];
3026 [output_ setTextColor:[UIColor whiteColor]];
3027 [output_ setBackgroundColor:[UIColor clearColor]];
3029 [output_ setMarginTop:0];
3030 [output_ setAllowsRubberBanding:YES];
3031 [output_ setEditable:NO];
3033 [overlay_ addSubview:output_];
3035 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3037 bounds.size.height - prgsize.height - 50,
3038 bounds.size.width - 20,
3042 [close_ setAutosizesToFit:NO];
3043 [close_ setDrawsShadow:YES];
3044 [close_ setStretchBackground:YES];
3045 [close_ setEnabled:YES];
3047 UIFont *bold = [UIFont boldSystemFontOfSize:22];
3048 [close_ setTitleFont:bold];
3050 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3051 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3052 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
3056 - (void) setContentView:(UIView *)view {
3057 view_ = [view retain];
3060 - (void) resetView {
3061 [transition_ transition:6 toView:view_];
3064 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3065 NSString *context([sheet context]);
3067 if ([context isEqualToString:@"conffile"]) {
3068 FILE *input = [database_ input];
3072 fprintf(input, "N\n");
3076 fprintf(input, "Y\n");
3087 - (void) closeButtonPushed {
3096 [delegate_ suspendWithAnimation:YES];
3100 system("launchctl stop com.apple.SpringBoard");
3104 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
3113 - (void) _retachThread {
3114 UINavigationItem *item = [navbar_ topItem];
3115 [item setTitle:@"Complete"];
3117 [overlay_ addSubview:close_];
3118 [progress_ removeFromSuperview];
3119 [status_ removeFromSuperview];
3121 [delegate_ progressViewIsComplete:self];
3124 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
3125 MMap mmap(file, MMap::ReadOnly);
3127 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3128 if (!(sandplate_ == sha1.Result()))
3133 FileFd file(SpringBoard_, FileFd::ReadOnly);
3134 MMap mmap(file, MMap::ReadOnly);
3136 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3137 if (!(springlist_ == sha1.Result()))
3142 case 0: [close_ setTitle:@"Return to Cydia"]; break;
3143 case 1: [close_ setTitle:@"Close Cydia (Restart)"]; break;
3144 case 2: [close_ setTitle:@"Restart SpringBoard"]; break;
3145 case 3: [close_ setTitle:@"Reload SpringBoard"]; break;
3146 case 4: [close_ setTitle:@"Reboot Device"]; break;
3149 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
3151 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
3152 [cache autorelease];
3154 NSFileManager *manager = [NSFileManager defaultManager];
3155 NSError *error = nil;
3157 id system = [cache objectForKey:@"System"];
3162 if (stat(Cache_, &info) == -1)
3165 [system removeAllObjects];
3167 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
3168 for (NSString *app in apps)
3169 if ([app hasSuffix:@".app"]) {
3170 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
3171 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
3172 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
3174 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
3175 [info setObject:path forKey:@"Path"];
3176 [info setObject:@"System" forKey:@"ApplicationType"];
3177 [system addInfoDictionary:info];
3183 [cache writeToFile:@Cache_ atomically:YES];
3185 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
3187 if (chmod(Cache_, info.st_mode) == -1)
3191 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
3194 notify_post("com.apple.mobile.application_installed");
3196 [delegate_ setStatusBarShowsProgress:NO];
3199 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
3200 [[data target] performSelector:[data selector] withObject:[data object]];
3203 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
3206 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
3207 UINavigationItem *item = [navbar_ topItem];
3208 [item setTitle:title];
3210 [status_ setText:nil];
3211 [output_ setText:@""];
3212 [progress_ setProgress:0];
3215 last_ = 0;//[NSDate timeIntervalSinceReferenceDate];
3217 [close_ removeFromSuperview];
3218 [overlay_ addSubview:progress_];
3219 [overlay_ addSubview:status_];
3221 [delegate_ setStatusBarShowsProgress:YES];
3225 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
3226 MMap mmap(file, MMap::ReadOnly);
3228 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3229 sandplate_ = sha1.Result();
3233 FileFd file(SpringBoard_, FileFd::ReadOnly);
3234 MMap mmap(file, MMap::ReadOnly);
3236 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3237 springlist_ = sha1.Result();
3240 [transition_ transition:6 toView:overlay_];
3243 detachNewThreadSelector:@selector(_detachNewThreadData:)
3245 withObject:[[ProgressData alloc]
3246 initWithSelector:selector
3253 - (void) repairWithSelector:(SEL)selector {
3255 detachNewThreadSelector:selector
3262 - (void) setConfigurationData:(NSString *)data {
3264 performSelectorOnMainThread:@selector(_setConfigurationData:)
3270 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
3271 Package *package = id == nil ? nil : [database_ packageWithName:id];
3273 UIActionSheet *sheet = [[[UIActionSheet alloc]
3274 initWithTitle:(package == nil ? id : [package name])
3275 buttons:[NSArray arrayWithObjects:@"Okay", nil]
3276 defaultButtonIndex:0
3281 [sheet setBodyText:error];
3282 [sheet popupAlertAnimated:YES];
3285 - (void) setProgressTitle:(NSString *)title {
3287 performSelectorOnMainThread:@selector(_setProgressTitle:)
3293 - (void) setProgressPercent:(float)percent {
3295 performSelectorOnMainThread:@selector(_setProgressPercent:)
3296 withObject:[NSNumber numberWithFloat:percent]
3301 - (void) startProgress {
3302 last_ = [NSDate timeIntervalSinceReferenceDate];
3305 - (void) addProgressOutput:(NSString *)output {
3307 performSelectorOnMainThread:@selector(_addProgressOutput:)
3313 - (bool) isCancelling:(size_t)received {
3315 NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate];
3316 if (received_ != received) {
3317 received_ = received;
3319 } else if (now - last_ > 30)
3326 - (void) _setConfigurationData:(NSString *)data {
3327 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
3329 _assert(conffile_r(data));
3331 NSString *ofile = conffile_r[1];
3332 //NSString *nfile = conffile_r[2];
3334 UIActionSheet *sheet = [[[UIActionSheet alloc]
3335 initWithTitle:@"Configuration Upgrade"
3336 buttons:[NSArray arrayWithObjects:
3337 @"Keep My Old Copy",
3338 @"Accept The New Copy",
3339 // XXX: @"See What Changed",
3341 defaultButtonIndex:0
3346 [sheet setBodyText:[NSString stringWithFormat:
3347 @"The following file has been changed by both the package maintainer and by you (or for you by a script).\n\n%@"
3350 [sheet popupAlertAnimated:YES];
3353 - (void) _setProgressTitle:(NSString *)title {
3354 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
3355 for (size_t i(0), e([words count]); i != e; ++i) {
3356 NSString *word([words objectAtIndex:i]);
3357 if (Package *package = [database_ packageWithName:word])
3358 [words replaceObjectAtIndex:i withObject:[package name]];
3361 [status_ setText:[words componentsJoinedByString:@" "]];
3364 - (void) _setProgressPercent:(NSNumber *)percent {
3365 [progress_ setProgress:[percent floatValue]];
3368 - (void) _addProgressOutput:(NSString *)output {
3369 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
3370 CGSize size = [output_ contentSize];
3371 CGRect rect = {{0, size.height}, {size.width, 0}};
3372 [output_ scrollRectToVisible:rect animated:YES];
3375 - (BOOL) isRunning {
3382 /* Package Cell {{{ */
3383 @interface PackageCell : UISimpleTableCell {
3386 NSString *description_;
3390 UITextLabel *status_;
3394 - (PackageCell *) init;
3395 - (void) setPackage:(Package *)package;
3397 + (int) heightForPackage:(Package *)package;
3401 @implementation PackageCell
3403 - (void) clearPackage {
3414 if (description_ != nil) {
3415 [description_ release];
3419 if (source_ != nil) {
3424 if (badge_ != nil) {
3431 [self clearPackage];
3438 - (PackageCell *) init {
3439 if ((self = [super init]) != nil) {
3441 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
3442 [status_ setBackgroundColor:[UIColor clearColor]];
3443 [status_ setFont:small];
3448 - (void) setPackage:(Package *)package {
3449 [self clearPackage];
3451 Source *source = [package source];
3452 NSString *section = [package simpleSection];
3454 icon_ = [[package icon] retain];
3456 name_ = [[package name] retain];
3457 description_ = [[package tagline] retain];
3459 NSString *label = nil;
3460 bool trusted = false;
3462 if (source != nil) {
3463 label = [source label];
3464 trusted = [source trusted];
3465 } else if ([[package id] isEqualToString:@"firmware"])
3468 label = @"Unknown/Local";
3470 NSString *from = [NSString stringWithFormat:@"from %@", label];
3472 if (section != nil && ![section isEqualToString:label])
3473 from = [from stringByAppendingString:[NSString stringWithFormat:@" (%@)", section]];
3475 source_ = [from retain];
3477 if (NSString *purpose = [package primaryPurpose])
3478 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
3479 badge_ = [badge_ retain];
3482 if (NSString *mode = [package mode]) {
3483 [badge_ setImage:[UIImage applicationImageNamed:
3484 [mode isEqualToString:@"Remove"] || [mode isEqualToString:@"Purge"] ? @"removing.png" : @"installing.png"
3487 [status_ setText:[NSString stringWithFormat:@"Queued for %@", mode]];
3488 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
3489 } else if ([package half]) {
3490 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
3491 [status_ setText:@"Package Damaged"];
3492 [status_ setColor:[UIColor redColor]];
3494 [badge_ setImage:nil];
3495 [status_ setText:nil];
3500 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
3503 rect.size = [icon_ size];
3505 rect.size.width /= 2;
3506 rect.size.height /= 2;
3508 rect.origin.x = 25 - rect.size.width / 2;
3509 rect.origin.y = 25 - rect.size.height / 2;
3511 [icon_ drawInRect:rect];
3514 if (badge_ != nil) {
3515 CGSize size = [badge_ size];
3517 [badge_ drawAtPoint:CGPointMake(
3518 36 - size.width / 2,
3519 36 - size.height / 2
3528 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
3529 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
3533 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
3535 [super drawContentInRect:rect selected:selected];
3538 + (int) heightForPackage:(Package *)package {
3539 NSString *tagline([package tagline]);
3540 int height = tagline == nil || [tagline length] == 0 ? -17 : 0;
3542 if ([package hasMode] || [package half])
3551 /* Section Cell {{{ */
3552 @interface SectionCell : UISimpleTableCell {
3557 _UISwitchSlider *switch_;
3562 - (void) setSection:(Section *)section editing:(BOOL)editing;
3566 @implementation SectionCell
3568 - (void) clearSection {
3569 if (section_ != nil) {
3579 if (count_ != nil) {
3586 [self clearSection];
3593 if ((self = [super init]) != nil) {
3594 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
3596 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
3597 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
3601 - (void) onSwitch:(id)sender {
3602 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
3603 if (metadata == nil) {
3604 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
3605 [Sections_ setObject:metadata forKey:section_];
3609 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
3612 - (void) setSection:(Section *)section editing:(BOOL)editing {
3613 if (editing != editing_) {
3615 [switch_ removeFromSuperview];
3617 [self addSubview:switch_];
3621 [self clearSection];
3623 if (section == nil) {
3624 name_ = [@"All Packages" retain];
3627 section_ = [section name];
3628 if (section_ != nil)
3629 section_ = [section_ retain];
3630 name_ = [(section_ == nil ? @"(No Section)" : section_) retain];
3631 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
3634 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
3638 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
3639 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
3646 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
3648 CGSize size = [count_ sizeWithFont:Font14_];
3652 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
3654 [super drawContentInRect:rect selected:selected];
3660 /* File Table {{{ */
3661 @interface FileTable : RVPage {
3662 _transient Database *database_;
3665 NSMutableArray *files_;
3669 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3670 - (void) setPackage:(Package *)package;
3674 @implementation FileTable
3677 if (package_ != nil)
3686 - (int) numberOfRowsInTable:(UITable *)table {
3687 return files_ == nil ? 0 : [files_ count];
3690 - (float) table:(UITable *)table heightForRow:(int)row {
3694 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
3695 if (reusing == nil) {
3696 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
3697 UIFont *font = [UIFont systemFontOfSize:16];
3698 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
3700 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
3704 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
3708 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3709 if ((self = [super initWithBook:book]) != nil) {
3710 database_ = database;
3712 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
3714 list_ = [[UITable alloc] initWithFrame:[self bounds]];
3715 [self addSubview:list_];
3717 UITableColumn *column = [[[UITableColumn alloc]
3718 initWithTitle:@"Name"
3720 width:[self frame].size.width
3723 [list_ setDataSource:self];
3724 [list_ setSeparatorStyle:1];
3725 [list_ addTableColumn:column];
3726 [list_ setDelegate:self];
3727 [list_ setReusesTableCells:YES];
3731 - (void) setPackage:(Package *)package {
3732 if (package_ != nil) {
3733 [package_ autorelease];
3742 [files_ removeAllObjects];
3744 if (package != nil) {
3745 package_ = [package retain];
3746 name_ = [[package id] retain];
3748 if (NSArray *files = [package files])
3749 [files_ addObjectsFromArray:files];
3751 if ([files_ count] != 0) {
3752 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
3753 [files_ removeObjectAtIndex:0];
3754 [files_ sortUsingSelector:@selector(compareByPath:)];
3756 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
3757 [stack addObject:@"/"];
3759 for (int i(0), e([files_ count]); i != e; ++i) {
3760 NSString *file = [files_ objectAtIndex:i];
3761 while (![file hasPrefix:[stack lastObject]])
3762 [stack removeLastObject];
3763 NSString *directory = [stack lastObject];
3764 [stack addObject:[file stringByAppendingString:@"/"]];
3765 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
3766 ([stack count] - 2) * 3, "",
3767 [file substringFromIndex:[directory length]]
3776 - (void) resetViewAnimated:(BOOL)animated {
3777 [list_ resetViewAnimated:animated];
3780 - (void) reloadData {
3781 [self setPackage:[database_ packageWithName:name_]];
3782 [self reloadButtons];
3785 - (NSString *) title {
3786 return @"Installed Files";
3789 - (NSString *) backButtonTitle {
3795 /* Package View {{{ */
3796 @interface PackageView : BrowserView {
3797 _transient Database *database_;
3800 NSMutableArray *buttons_;
3803 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3804 - (void) setPackage:(Package *)package;
3808 @implementation PackageView
3811 if (package_ != nil)
3819 - (void) _clickButtonWithName:(NSString *)name {
3820 if ([name isEqualToString:@"Install"])
3821 [delegate_ installPackage:package_];
3822 else if ([name isEqualToString:@"Reinstall"])
3823 [delegate_ installPackage:package_];
3824 else if ([name isEqualToString:@"Remove"])
3825 [delegate_ removePackage:package_];
3826 else if ([name isEqualToString:@"Upgrade"])
3827 [delegate_ installPackage:package_];
3828 else _assert(false);
3831 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3832 NSString *context([sheet context]);
3834 if ([context isEqualToString:@"modify"]) {
3835 int count = [buttons_ count];
3836 _assert(count != 0);
3837 _assert(button <= count + 1);
3839 if (count != button - 1)
3840 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
3844 [super alertSheet:sheet buttonClicked:button];
3847 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
3848 [[frame windowObject] evaluateWebScript:@"document.base.target = '_top'"];
3849 return [super webView:sender didFinishLoadForFrame:frame];
3852 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3853 [window setValue:package_ forKey:@"package"];
3854 [super webView:sender didClearWindowObject:window forFrame:frame];
3858 - (void) _rightButtonClicked {
3859 /*[super _rightButtonClicked];
3862 int count = [buttons_ count];
3863 _assert(count != 0);
3866 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
3868 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
3869 [buttons addObjectsFromArray:buttons_];
3870 [buttons addObject:@"Cancel"];
3872 [delegate_ slideUp:[[[UIActionSheet alloc]
3875 defaultButtonIndex:2
3883 - (NSString *) _rightButtonTitle {
3884 int count = [buttons_ count];
3885 return count == 0 ? nil : count != 1 ? @"Modify" : [buttons_ objectAtIndex:0];
3888 - (NSString *) backButtonTitle {
3892 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3893 if ((self = [super initWithBook:book]) != nil) {
3894 database_ = database;
3895 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
3899 - (void) setPackage:(Package *)package {
3900 if (package_ != nil) {
3901 [package_ autorelease];
3910 [buttons_ removeAllObjects];
3912 if (package != nil) {
3913 package_ = [package retain];
3914 name_ = [[package id] retain];
3916 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
3918 if ([package_ source] == nil);
3919 else if ([package_ upgradableAndEssential:NO])
3920 [buttons_ addObject:@"Upgrade"];
3921 else if ([package_ installed] == nil)
3922 [buttons_ addObject:@"Install"];
3924 [buttons_ addObject:@"Reinstall"];
3925 if ([package_ installed] != nil)
3926 [buttons_ addObject:@"Remove"];
3930 - (void) reloadData {
3931 [self setPackage:[database_ packageWithName:name_]];
3932 [self reloadButtons];
3937 /* Package Table {{{ */
3938 @interface PackageTable : RVPage {
3939 _transient Database *database_;
3943 NSMutableArray *packages_;
3944 NSMutableArray *sections_;
3945 UISectionList *list_;
3948 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
3950 - (void) setDelegate:(id)delegate;
3951 - (void) setObject:(id)object;
3953 - (void) reloadData;
3954 - (void) resetCursor;
3956 - (UISectionList *) list;
3958 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
3962 @implementation PackageTable
3965 [list_ setDataSource:nil];
3970 [packages_ release];
3971 [sections_ release];
3976 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
3977 return [sections_ count];
3980 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
3981 return [[sections_ objectAtIndex:section] name];
3984 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
3985 return [[sections_ objectAtIndex:section] row];
3988 - (int) numberOfRowsInTable:(UITable *)table {
3989 return [packages_ count];
3992 - (float) table:(UITable *)table heightForRow:(int)row {
3993 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
3996 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
3998 reusing = [[[PackageCell alloc] init] autorelease];
3999 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
4003 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
4007 - (void) tableRowSelected:(NSNotification *)notification {
4008 int row = [[notification object] selectedRow];
4012 Package *package = [packages_ objectAtIndex:row];
4013 PackageView *view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
4014 [view setDelegate:delegate_];
4015 [view setPackage:package];
4016 [book_ pushPage:view];
4019 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
4020 if ((self = [super initWithBook:book]) != nil) {
4021 database_ = database;
4022 title_ = [title retain];
4024 object_ = object == nil ? nil : [object retain];
4026 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
4027 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
4029 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
4030 [list_ setDataSource:self];
4032 UITableColumn *column = [[[UITableColumn alloc]
4033 initWithTitle:@"Name"
4035 width:[self frame].size.width
4038 UITable *table = [list_ table];
4039 [table setSeparatorStyle:1];
4040 [table addTableColumn:column];
4041 [table setDelegate:self];
4042 [table setReusesTableCells:YES];
4044 [self addSubview:list_];
4047 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4048 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4052 - (void) setDelegate:(id)delegate {
4053 delegate_ = delegate;
4056 - (void) setObject:(id)object {
4062 object_ = [object retain];
4065 - (void) reloadData {
4066 NSArray *packages = [database_ packages];
4068 [packages_ removeAllObjects];
4069 [sections_ removeAllObjects];
4071 for (size_t i(0); i != [packages count]; ++i) {
4072 Package *package([packages objectAtIndex:i]);
4073 if ([package valid] && [[package performSelector:filter_ withObject:object_] boolValue])
4074 [packages_ addObject:package];
4077 Section *section = nil;
4079 for (size_t offset(0); offset != [packages_ count]; ++offset) {
4080 Package *package = [packages_ objectAtIndex:offset];
4081 NSString *name = [package index];
4083 if (section == nil || ![[section name] isEqualToString:name]) {
4084 section = [[[Section alloc] initWithName:name row:offset] autorelease];
4085 [sections_ addObject:section];
4088 [section addToCount];
4094 - (NSString *) title {
4098 - (void) resetViewAnimated:(BOOL)animated {
4099 [list_ resetViewAnimated:animated];
4102 - (void) resetCursor {
4103 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
4106 - (UISectionList *) list {
4110 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
4111 [list_ setShouldHideHeaderInShortLists:hide];
4117 /* Add Source View {{{ */
4118 @interface AddSourceView : RVPage {
4119 _transient Database *database_;
4122 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4126 @implementation AddSourceView
4128 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4129 if ((self = [super initWithBook:book]) != nil) {
4130 database_ = database;
4136 /* Source Cell {{{ */
4137 @interface SourceCell : UITableCell {
4140 NSString *description_;
4146 - (SourceCell *) initWithSource:(Source *)source;
4150 @implementation SourceCell
4155 [description_ release];
4160 - (SourceCell *) initWithSource:(Source *)source {
4161 if ((self = [super init]) != nil) {
4163 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
4165 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
4166 icon_ = [icon_ retain];
4168 origin_ = [[source name] retain];
4169 label_ = [[source uri] retain];
4170 description_ = [[source description] retain];
4174 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4176 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
4183 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4187 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4191 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4193 [super drawContentInRect:rect selected:selected];
4198 /* Source Table {{{ */
4199 @interface SourceTable : RVPage {
4200 _transient Database *database_;
4201 UISectionList *list_;
4202 NSMutableArray *sources_;
4203 UIActionSheet *alert_;
4207 UIProgressHUD *hud_;
4210 //NSURLConnection *installer_;
4211 NSURLConnection *trivial_bz2_;
4212 NSURLConnection *trivial_gz_;
4213 //NSURLConnection *automatic_;
4218 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4222 @implementation SourceTable
4224 - (void) _deallocConnection:(NSURLConnection *)connection {
4225 if (connection != nil) {
4226 [connection cancel];
4227 //[connection setDelegate:nil];
4228 [connection release];
4233 [[list_ table] setDelegate:nil];
4234 [list_ setDataSource:nil];
4243 //[self _deallocConnection:installer_];
4244 [self _deallocConnection:trivial_gz_];
4245 [self _deallocConnection:trivial_bz2_];
4246 //[self _deallocConnection:automatic_];
4253 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
4254 return offset_ == 0 ? 1 : 2;
4257 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
4258 switch (section + (offset_ == 0 ? 1 : 0)) {
4259 case 0: return @"Entered by User";
4260 case 1: return @"Installed by Packages";
4268 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
4269 switch (section + (offset_ == 0 ? 1 : 0)) {
4271 case 1: return offset_;
4279 - (int) numberOfRowsInTable:(UITable *)table {
4280 return [sources_ count];
4283 - (float) table:(UITable *)table heightForRow:(int)row {
4284 Source *source = [sources_ objectAtIndex:row];
4285 return [source description] == nil ? 56 : 73;
4288 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
4289 Source *source = [sources_ objectAtIndex:row];
4290 // XXX: weird warning, stupid selectors ;P
4291 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
4294 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
4298 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4302 - (void) tableRowSelected:(NSNotification*)notification {
4303 UITable *table([list_ table]);
4304 int row([table selectedRow]);
4308 Source *source = [sources_ objectAtIndex:row];
4310 PackageTable *packages = [[[PackageTable alloc]
4313 title:[source label]
4314 filter:@selector(isVisibleInSource:)
4318 [packages setDelegate:delegate_];
4320 [book_ pushPage:packages];
4323 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
4324 Source *source = [sources_ objectAtIndex:row];
4325 return [source record] != nil;
4328 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
4329 [[list_ table] setDeleteConfirmationRow:row];
4332 - (void) table:(UITable *)table deleteRow:(int)row {
4333 Source *source = [sources_ objectAtIndex:row];
4334 [Sources_ removeObjectForKey:[source key]];
4335 [delegate_ syncData];
4338 - (void) _endConnection:(NSURLConnection *)connection {
4339 NSURLConnection **field = NULL;
4340 if (connection == trivial_bz2_)
4341 field = &trivial_bz2_;
4342 else if (connection == trivial_gz_)
4343 field = &trivial_gz_;
4344 _assert(field != NULL);
4345 [connection release];
4349 trivial_bz2_ == nil &&
4352 [delegate_ setStatusBarShowsProgress:NO];
4355 [hud_ removeFromSuperview];
4360 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
4363 @"./", @"Distribution",
4364 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
4366 [delegate_ syncData];
4367 } else if (error_ != nil) {
4368 UIActionSheet *sheet = [[[UIActionSheet alloc]
4369 initWithTitle:@"Verification Error"
4370 buttons:[NSArray arrayWithObjects:@"OK", nil]
4371 defaultButtonIndex:0
4376 [sheet setBodyText:[error_ localizedDescription]];
4377 [sheet popupAlertAnimated:YES];
4379 UIActionSheet *sheet = [[[UIActionSheet alloc]
4380 initWithTitle:@"Did not Find Repository"
4381 buttons:[NSArray arrayWithObjects:@"OK", nil]
4382 defaultButtonIndex:0
4387 [sheet setBodyText:@"The indicated repository could not be found. This could be because you are trying to add a legacy Installer repository (these are not supported). Also, this interface is only capable of working with exact repository URLs. If you host a repository and are having issues please contact the author of Cydia with any questions you have."];
4388 [sheet popupAlertAnimated:YES];
4394 if (error_ != nil) {
4401 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
4402 switch ([response statusCode]) {
4408 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
4409 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
4411 error_ = [error retain];
4412 [self _endConnection:connection];
4415 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
4416 [self _endConnection:connection];
4419 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
4420 NSMutableURLRequest *request = [NSMutableURLRequest
4421 requestWithURL:[NSURL URLWithString:href]
4422 cachePolicy:NSURLRequestUseProtocolCachePolicy
4423 timeoutInterval:20.0
4426 [request setHTTPMethod:method];
4428 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
4431 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4432 NSString *context([sheet context]);
4434 if ([context isEqualToString:@"source"]) {
4437 NSString *href = [[sheet textField] text];
4439 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
4441 if (![href hasSuffix:@"/"])
4442 href_ = [href stringByAppendingString:@"/"];
4445 href_ = [href_ retain];
4447 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
4448 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
4449 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
4453 hud_ = [delegate_ addProgressHUD];
4454 [hud_ setText:@"Verifying URL"];
4468 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4469 if ((self = [super initWithBook:book]) != nil) {
4470 database_ = database;
4471 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
4473 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
4474 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
4475 [list_ setShouldHideHeaderInShortLists:NO];
4477 [self addSubview:list_];
4478 [list_ setDataSource:self];
4480 UITableColumn *column = [[UITableColumn alloc]
4481 initWithTitle:@"Name"
4483 width:[self frame].size.width
4486 UITable *table = [list_ table];
4487 [table setSeparatorStyle:1];
4488 [table addTableColumn:column];
4489 [table setDelegate:self];
4493 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4494 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4498 - (void) reloadData {
4500 _assert(list.ReadMainList());
4502 [sources_ removeAllObjects];
4503 [sources_ addObjectsFromArray:[database_ sources]];
4505 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
4508 int count = [sources_ count];
4509 for (offset_ = 0; offset_ != count; ++offset_) {
4510 Source *source = [sources_ objectAtIndex:offset_];
4511 if ([source record] == nil)
4518 - (void) resetViewAnimated:(BOOL)animated {
4519 [list_ resetViewAnimated:animated];
4522 - (void) _leftButtonClicked {
4523 /*[book_ pushPage:[[[AddSourceView alloc]
4528 UIActionSheet *sheet = [[[UIActionSheet alloc]
4529 initWithTitle:@"Enter Cydia/APT URL"
4530 buttons:[NSArray arrayWithObjects:@"Add Source", @"Cancel", nil]
4531 defaultButtonIndex:0
4536 [sheet setNumberOfRows:1];
4538 [sheet addTextFieldWithValue:@"http://" label:@""];
4540 UITextInputTraits *traits = [[sheet textField] textInputTraits];
4541 [traits setAutocapitalizationType:0];
4542 [traits setKeyboardType:UIKeyboardTypeURL];
4543 [traits setAutocorrectionType:1];
4545 [sheet popupAlertAnimated:YES];
4548 - (void) _rightButtonClicked {
4549 UITable *table = [list_ table];
4550 BOOL editing = [table isRowDeletionEnabled];
4551 [table enableRowDeletion:!editing animated:YES];
4552 [book_ reloadButtonsForPage:self];
4555 - (NSString *) title {
4559 - (NSString *) leftButtonTitle {
4560 return [[list_ table] isRowDeletionEnabled] ? @"Add" : nil;
4563 - (NSString *) rightButtonTitle {
4564 return [[list_ table] isRowDeletionEnabled] ? @"Done" : @"Edit";
4567 - (UINavigationButtonStyle) rightButtonStyle {
4568 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
4574 /* Installed View {{{ */
4575 @interface InstalledView : RVPage {
4576 _transient Database *database_;
4577 PackageTable *packages_;
4581 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4585 @implementation InstalledView
4588 [packages_ release];
4592 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4593 if ((self = [super initWithBook:book]) != nil) {
4594 database_ = database;
4596 packages_ = [[PackageTable alloc]
4600 filter:@selector(isInstalledAndVisible:)
4601 with:[NSNumber numberWithBool:YES]
4604 [self addSubview:packages_];
4606 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4607 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4611 - (void) resetViewAnimated:(BOOL)animated {
4612 [packages_ resetViewAnimated:animated];
4615 - (void) reloadData {
4616 [packages_ reloadData];
4619 - (void) _rightButtonClicked {
4620 [packages_ setObject:[NSNumber numberWithBool:expert_]];
4621 [packages_ reloadData];
4623 [book_ reloadButtonsForPage:self];
4626 - (NSString *) title {
4627 return @"Installed";
4630 - (NSString *) backButtonTitle {
4634 - (NSString *) rightButtonTitle {
4635 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? @"Expert" : @"Simple";
4638 - (UINavigationButtonStyle) rightButtonStyle {
4639 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
4642 - (void) setDelegate:(id)delegate {
4643 [super setDelegate:delegate];
4644 [packages_ setDelegate:delegate];
4651 @interface HomeView : BrowserView {
4656 @implementation HomeView
4658 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4659 NSString *context([sheet context]);
4661 if ([context isEqualToString:@"about"])
4664 [super alertSheet:sheet buttonClicked:button];
4667 - (void) _leftButtonClicked {
4668 UIActionSheet *sheet = [[[UIActionSheet alloc]
4669 initWithTitle:@"About Cydia Installer"
4670 buttons:[NSArray arrayWithObjects:@"Close", nil]
4671 defaultButtonIndex:0
4677 @"Copyright (C) 2008\n"
4678 "Jay Freeman (saurik)\n"
4679 "saurik@saurik.com\n"
4680 "http://www.saurik.com/\n"
4683 "http://www.theokorigroup.com/\n"
4685 "College of Creative Studies,\n"
4686 "University of California,\n"
4688 "http://www.ccs.ucsb.edu/"
4691 [sheet popupAlertAnimated:YES];
4694 - (NSString *) leftButtonTitle {
4700 /* Manage View {{{ */
4701 @interface ManageView : BrowserView {
4706 @implementation ManageView
4708 - (NSString *) title {
4712 - (void) _leftButtonClicked {
4713 [delegate_ askForSettings];
4716 - (NSString *) leftButtonTitle {
4721 - (NSString *) _rightButtonTitle {
4729 @interface WebView (Cydia)
4730 - (void) setScriptDebugDelegate:(id)delegate;
4731 - (void) _setFormDelegate:(id)delegate;
4732 - (void) _setUIKitDelegate:(id)delegate;
4733 - (void) setWebMailDelegate:(id)delegate;
4734 - (void) _setLayoutInterval:(float)interval;
4737 /* Indirect Delegate {{{ */
4738 @interface IndirectDelegate : NSProxy {
4739 _transient volatile id delegate_;
4742 - (void) setDelegate:(id)delegate;
4743 - (id) initWithDelegate:(id)delegate;
4746 @implementation IndirectDelegate
4748 - (void) setDelegate:(id)delegate {
4749 delegate_ = delegate;
4752 - (id) initWithDelegate:(id)delegate {
4753 delegate_ = delegate;
4757 - (NSMethodSignature*) methodSignatureForSelector:(SEL)sel {
4758 if (delegate_ != nil)
4759 if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
4761 // XXX: I fucking hate Apple so very very bad
4762 return [NSMethodSignature signatureWithObjCTypes:"v@:"];
4765 - (void) forwardInvocation:(NSInvocation *)inv {
4766 SEL sel = [inv selector];
4767 if (delegate_ != nil && [delegate_ respondsToSelector:sel])
4768 [inv invokeWithTarget:delegate_];
4773 /* Browser Implementation {{{ */
4774 @implementation BrowserView
4777 if (challenge_ != nil)
4778 [challenge_ release];
4780 WebView *webview = [webview_ webView];
4781 [webview setFrameLoadDelegate:nil];
4782 [webview setResourceLoadDelegate:nil];
4783 [webview setUIDelegate:nil];
4784 [webview setScriptDebugDelegate:nil];
4785 [webview setPolicyDelegate:nil];
4787 [webview setDownloadDelegate:nil];
4789 [webview _setFormDelegate:nil];
4790 [webview _setUIKitDelegate:nil];
4791 [webview setWebMailDelegate:nil];
4792 [webview setEditingDelegate:nil];
4794 [webview_ setDelegate:nil];
4795 [webview_ setGestureDelegate:nil];
4797 //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
4802 [webview_ removeFromSuperview];
4803 [Documents_ addObject:[webview_ autorelease]];
4808 [indirect_ setDelegate:nil];
4809 [indirect_ release];
4811 [scroller_ setDelegate:nil];
4813 [scroller_ release];
4815 [indicator_ release];
4821 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
4822 [self loadRequest:[NSURLRequest
4825 timeoutInterval:30.0
4829 - (void) loadURL:(NSURL *)url {
4830 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
4833 - (NSURLRequest *) _addHeadersToRequest:(NSURLRequest *)request {
4834 NSMutableURLRequest *copy = [request mutableCopy];
4836 if (Machine_ != NULL)
4837 [copy addValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4838 if (UniqueID_ != nil)
4839 [copy addValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
4842 [copy addValue:Role_ forHTTPHeaderField:@"X-Role"];
4847 - (void) loadRequest:(NSURLRequest *)request {
4849 [webview_ loadRequest:request];
4852 - (void) reloadURL {
4853 if ([urls_ count] == 0)
4855 NSURL *url = [[[urls_ lastObject] retain] autorelease];
4856 [urls_ removeLastObject];
4857 [self loadURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData];
4860 - (WebView *) webView {
4861 return [webview_ webView];
4864 - (void) view:(UIView *)sender didSetFrame:(CGRect)frame {
4865 [scroller_ setContentSize:frame.size];
4868 - (void) view:(UIView *)sender didSetFrame:(CGRect)frame oldFrame:(CGRect)old {
4869 [self view:sender didSetFrame:frame];
4872 - (void) pushPage:(RVPage *)page {
4873 [self setBackButtonTitle:title_];
4874 [page setDelegate:delegate_];
4875 [book_ pushPage:page];
4878 - (BOOL) getSpecial:(NSURL *)url {
4879 NSString *href([url absoluteString]);
4880 NSString *scheme([[url scheme] lowercaseString]);
4884 if ([href hasPrefix:@"apptapp://package/"])
4885 page = [delegate_ pageForPackage:[href substringFromIndex:18]];
4886 else if ([scheme isEqualToString:@"cydia"]) {
4887 page = [delegate_ pageForURL:url hasTag:NULL];
4890 } else if (![scheme isEqualToString:@"apptapp"])
4894 [self pushPage:page];
4898 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4899 [window setValue:delegate_ forKey:@"cydia"];
4902 - (void) webView:(WebView *)sender decidePolicyForNewWindowAction:(NSDictionary *)dictionary request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
4903 if (NSURL *url = [request URL]) {
4904 if (![self getSpecial:url]) {
4905 NSString *scheme([[url scheme] lowercaseString]);
4906 if ([scheme isEqualToString:@"mailto"])
4907 [delegate_ openMailToURL:url];
4916 - (void) webView:(WebView *)webView decidePolicyForMIMEType:(NSString *)type request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
4917 if ([WebView canShowMIMEType:type])
4920 // XXX: handle more mime types!
4922 if (frame == [webView mainFrame])
4923 [UIApp openURL:[request URL]];
4927 - (void) webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
4928 NSURL *url([request URL]);
4930 if (url == nil) use: {
4935 const NSArray *capability(reinterpret_cast<const NSArray *>(GSSystemGetCapability(kGSDisplayIdentifiersCapability)));
4938 [capability containsObject:@"com.apple.Maps"] && [url mapsURL] ||
4939 [capability containsObject:@"com.apple.youtube"] && [url youTubeURL]
4942 [UIApp openURL:url];
4948 int store(_not(int));
4949 if (NSURL *itms = [url itmsURL:&store]) {
4950 NSLog(@"itms#%@#%u#%@", url, store, itms);
4952 store == 1 && [capability containsObject:@"com.apple.MobileStore"] ||
4953 store == 2 && [capability containsObject:@"com.apple.AppStore"]
4960 NSString *scheme([[url scheme] lowercaseString]);
4962 if ([scheme isEqualToString:@"tel"]) {
4963 // XXX: intelligence
4967 if ([scheme isEqualToString:@"mailto"]) {
4968 [delegate_ openMailToURL:url];
4972 if ([self getSpecial:url])
4974 else if ([WebView _canHandleRequest:request])
4976 else if ([url isSpringboardHandledURL])
4982 - (void) webView:(WebView *)sender setStatusText:(NSString *)text {
4983 //lprintf("Status:%s\n", [text UTF8String]);
4986 - (void) _pushPage {
4990 [book_ pushPage:self];
4993 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4994 NSString *context([sheet context]);
4996 if ([context isEqualToString:@"challenge"]) {
4997 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
5001 NSString *username([[sheet textFieldAtIndex:0] text]);
5002 NSString *password([[sheet textFieldAtIndex:1] text]);
5004 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
5006 [sender useCredential:credential forAuthenticationChallenge:challenge_];
5010 [sender cancelAuthenticationChallenge:challenge_];
5017 [challenge_ release];
5024 - (void) webView:(WebView *)sender resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
5025 challenge_ = [challenge retain];
5027 NSURLProtectionSpace *space([challenge protectionSpace]);
5028 NSString *realm([space realm]);
5032 UIActionSheet *sheet = [[[UIActionSheet alloc]
5034 buttons:[NSArray arrayWithObjects:@"Login", @"Cancel", nil]
5035 defaultButtonIndex:0
5037 context:@"challenge"
5040 [sheet setNumberOfRows:1];
5042 [sheet addTextFieldWithValue:@"" label:@"username"];
5043 [sheet addTextFieldWithValue:@"" label:@"password"];
5045 UITextField *username([sheet textFieldAtIndex:0]); {
5046 UITextInputTraits *traits([username textInputTraits]);
5047 [traits setAutocapitalizationType:0];
5048 [traits setAutocorrectionType:1];
5051 UITextField *password([sheet textFieldAtIndex:1]); {
5052 UITextInputTraits *traits([password textInputTraits]);
5053 [traits setAutocapitalizationType:0];
5054 [traits setAutocorrectionType:1];
5055 [traits setSecureTextEntry:YES];
5058 [sheet popupAlertAnimated:YES];
5061 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
5062 NSURL *url = [request URL];
5063 if ([self getSpecial:url])
5066 return [self _addHeadersToRequest:request];
5069 - (WebView *) _createWebViewWithRequest:(NSURLRequest *)request pushed:(BOOL)pushed {
5070 [self setBackButtonTitle:title_];
5072 BrowserView *browser = [[[BrowserView alloc] initWithBook:book_] autorelease];
5073 [browser setDelegate:delegate_];
5076 [browser loadRequest:[self _addHeadersToRequest:request]];
5077 [book_ pushPage:browser];
5080 return [browser webView];
5083 - (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request {
5084 return [self _createWebViewWithRequest:request pushed:(request != nil)];
5087 - (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request windowFeatures:(NSDictionary *)features {
5088 return [self _createWebViewWithRequest:request pushed:YES];
5091 - (void) webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
5092 if ([frame parentFrame] != nil)
5095 title_ = [title retain];
5096 [book_ reloadTitleForPage:self];
5099 - (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
5100 if ([frame parentFrame] != nil)
5105 [indicator_ startAnimation];
5106 [self reloadButtons];
5108 if (title_ != nil) {
5113 [book_ reloadTitleForPage:self];
5115 WebView *webview = [webview_ webView];
5116 NSString *href = [webview mainFrameURL];
5117 [urls_ addObject:[NSURL URLWithString:href]];
5119 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5121 CGRect webrect = [scroller_ bounds];
5122 webrect.size.height = 0;
5123 [webview_ setFrame:webrect];
5126 - (void) _finishLoading {
5129 [indicator_ stopAnimation];
5130 [self reloadButtons];
5134 - (BOOL) webView:(WebView *)sender shouldScrollToPoint:(struct CGPoint)point forFrame:(WebFrame *)frame {
5135 return [webview_ webView:sender shouldScrollToPoint:point forFrame:frame];
5138 - (void) webView:(WebView *)sender didReceiveViewportArguments:(id)arguments forFrame:(WebFrame *)frame {
5139 return [webview_ webView:sender didReceiveViewportArguments:arguments forFrame:frame];
5142 - (void) webView:(WebView *)sender needsScrollNotifications:(id)notifications forFrame:(WebFrame *)frame {
5143 return [webview_ webView:sender needsScrollNotifications:notifications forFrame:frame];
5146 - (void) webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame {
5147 return [webview_ webView:sender didCommitLoadForFrame:frame];
5150 - (void) webView:(WebView *)sender didReceiveDocTypeForFrame:(WebFrame *)frame {
5151 return [webview_ webView:sender didReceiveDocTypeForFrame:frame];
5154 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5155 if ([frame parentFrame] == nil)
5156 [self _finishLoading];
5157 return [webview_ webView:sender didFinishLoadForFrame:frame];
5160 - (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
5161 if ([frame parentFrame] != nil)
5163 [self _finishLoading];
5165 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
5166 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
5167 [[error localizedDescription] stringByAddingPercentEscapes]
5171 - (void) webView:(WebView *)sender addMessageToConsole:(NSDictionary *)dictionary {
5173 lprintf("Console:%s\n", [[dictionary description] UTF8String]);
5177 - (id) initWithBook:(RVBook *)book {
5178 if ((self = [super initWithBook:book]) != nil) {
5181 struct CGRect bounds = [self bounds];
5183 UIImageView *pinstripe = [[[UIImageView alloc] initWithFrame:bounds] autorelease];
5184 [pinstripe setImage:[UIImage applicationImageNamed:@"pinstripe.png"]];
5185 [self addSubview:pinstripe];
5187 scroller_ = [[UIScroller alloc] initWithFrame:bounds];
5188 [self addSubview:scroller_];
5190 [scroller_ setScrollingEnabled:YES];
5191 [scroller_ setAdjustForContentSizeChange:YES];
5192 [scroller_ setClipsSubviews:YES];
5193 [scroller_ setAllowsRubberBanding:YES];
5194 [scroller_ setScrollDecelerationFactor:0.99];
5195 [scroller_ setDelegate:self];
5197 CGRect webrect = [scroller_ bounds];
5198 webrect.size.height = 0;
5203 webview_ = [Documents_ lastObject];
5204 if (webview_ != nil) {
5205 webview_ = [webview_ retain];
5206 webview = [webview_ webView];
5207 [Documents_ removeLastObject];
5208 [webview_ setFrame:webrect];
5213 webview_ = [[UIWebDocumentView alloc] initWithFrame:webrect];
5214 webview = [webview_ webView];
5216 [webview_ setTileSize:CGSizeMake(webrect.size.width, 500)];
5218 [webview_ setAllowsMessaging:YES];
5220 [webview_ setTilingEnabled:YES];
5221 [webview_ setDrawsGrid:NO];
5222 [webview_ setLogsTilingChanges:NO];
5223 [webview_ setTileMinificationFilter:kCAFilterNearest];
5224 [webview_ setDetectsPhoneNumbers:NO];
5225 [webview_ setAutoresizes:YES];
5227 [webview_ setViewportSize:CGSizeMake(980, -1) forDocumentTypes:0x10];
5228 [webview_ setViewportSize:CGSizeMake(320, -1) forDocumentTypes:0x2];
5229 [webview_ setViewportSize:CGSizeMake(320, -1) forDocumentTypes:0x8];
5231 [webview_ _setDocumentType:0x4];
5233 [webview_ setZoomsFocusedFormControl:YES];
5234 [webview_ setContentsPosition:7];
5235 [webview_ setEnabledGestures:0xa];
5236 [webview_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeIsZoomRubberBandEnabled];
5237 [webview_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeUpdatesScroller];
5239 [webview_ setSmoothsFonts:YES];
5241 [webview _setUsesLoaderCache:YES];
5242 [webview setGroupName:@"Cydia"];
5243 //[webview _setLayoutInterval:0.5];
5246 [webview_ setDelegate:self];
5247 [webview_ setGestureDelegate:self];
5248 [scroller_ addSubview:webview_];
5250 //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
5252 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:UIProgressIndicatorStyleMediumWhite];
5253 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(281, 12, indsize.width, indsize.height)];
5254 [indicator_ setStyle:UIProgressIndicatorStyleMediumWhite];
5256 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
5257 NSString *application = package == nil ? @"Cydia" : [NSString
5258 stringWithFormat:@"Cydia/%@",
5260 ]; [webview setApplicationNameForUserAgent:application];
5262 indirect_ = [[IndirectDelegate alloc] initWithDelegate:self];
5264 [webview setFrameLoadDelegate:self];
5265 [webview setResourceLoadDelegate:indirect_];
5266 [webview setUIDelegate:self];
5267 [webview setScriptDebugDelegate:self];
5268 [webview setPolicyDelegate:self];
5270 urls_ = [[NSMutableArray alloc] initWithCapacity:16];
5272 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5273 [scroller_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5274 [pinstripe setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5278 - (void) didFinishGesturesInView:(UIView *)view forEvent:(id)event {
5279 [webview_ redrawScaledDocument];
5282 - (void) _rightButtonClicked {
5287 - (NSString *) _rightButtonTitle {
5291 - (NSString *) rightButtonTitle {
5292 return loading_ ? @"" : [self _rightButtonTitle];
5295 - (NSString *) title {
5296 return title_ == nil ? @"Loading" : title_;
5299 - (NSString *) backButtonTitle {
5303 - (void) setPageActive:(BOOL)active {
5305 [indicator_ removeFromSuperview];
5307 [[book_ navigationBar] addSubview:indicator_];
5310 - (void) resetViewAnimated:(BOOL)animated {
5313 - (void) setPushed:(bool)pushed {
5320 /* Cydia Book {{{ */
5321 @interface CYBook : RVBook <
5324 _transient Database *database_;
5325 UINavigationBar *overlay_;
5326 UINavigationBar *underlay_;
5327 UIProgressIndicator *indicator_;
5328 UITextLabel *prompt_;
5329 UIProgressBar *progress_;
5330 UINavigationButton *cancel_;
5333 NSTimeInterval last_;
5336 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5342 @implementation CYBook
5346 [indicator_ release];
5348 [progress_ release];
5353 - (NSString *) getTitleForPage:(RVPage *)page {
5354 return Simplify([super getTitleForPage:page]);
5362 [UIView beginAnimations:nil context:NULL];
5364 CGRect ovrframe = [overlay_ frame];
5365 ovrframe.origin.y = 0;
5366 [overlay_ setFrame:ovrframe];
5368 CGRect barframe = [navbar_ frame];
5369 barframe.origin.y += ovrframe.size.height;
5370 [navbar_ setFrame:barframe];
5372 CGRect trnframe = [transition_ frame];
5373 trnframe.origin.y += ovrframe.size.height;
5374 trnframe.size.height -= ovrframe.size.height;
5375 [transition_ setFrame:trnframe];
5377 [UIView endAnimations];
5379 [indicator_ startAnimation];
5380 [prompt_ setText:@"Updating Database"];
5381 [progress_ setProgress:0];
5384 last_ = [NSDate timeIntervalSinceReferenceDate];
5386 [overlay_ addSubview:cancel_];
5389 detachNewThreadSelector:@selector(_update)
5398 [indicator_ stopAnimation];
5400 [UIView beginAnimations:nil context:NULL];
5402 CGRect ovrframe = [overlay_ frame];
5403 ovrframe.origin.y = -ovrframe.size.height;
5404 [overlay_ setFrame:ovrframe];
5406 CGRect barframe = [navbar_ frame];
5407 barframe.origin.y -= ovrframe.size.height;
5408 [navbar_ setFrame:barframe];
5410 CGRect trnframe = [transition_ frame];
5411 trnframe.origin.y -= ovrframe.size.height;
5412 trnframe.size.height += ovrframe.size.height;
5413 [transition_ setFrame:trnframe];
5415 [UIView commitAnimations];
5417 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
5420 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
5421 if ((self = [super initWithFrame:frame]) != nil) {
5422 database_ = database;
5424 CGRect ovrrect = [navbar_ bounds];
5425 ovrrect.size.height = [UINavigationBar defaultSize].height;
5426 ovrrect.origin.y = -ovrrect.size.height;
5428 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5429 [self addSubview:overlay_];
5431 ovrrect.origin.y = frame.size.height;
5432 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5433 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
5434 [self addSubview:underlay_];
5436 [overlay_ setBarStyle:1];
5437 [underlay_ setBarStyle:1];
5439 int barstyle = [overlay_ _barStyle:NO];
5440 bool ugly = barstyle == 0;
5442 UIProgressIndicatorStyle style = ugly ?
5443 UIProgressIndicatorStyleMediumBrown :
5444 UIProgressIndicatorStyleMediumWhite;
5446 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
5447 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
5448 CGRect indrect = {{indoffset, indoffset}, indsize};
5450 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
5451 [indicator_ setStyle:style];
5452 [overlay_ addSubview:indicator_];
5454 CGSize prmsize = {215, indsize.height + 4};
5457 indoffset * 2 + indsize.width,
5461 unsigned(ovrrect.size.height - prmsize.height) / 2
5464 UIFont *font = [UIFont systemFontOfSize:15];
5466 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
5468 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
5469 [prompt_ setBackgroundColor:[UIColor clearColor]];
5470 [prompt_ setFont:font];
5472 [overlay_ addSubview:prompt_];
5474 CGSize prgsize = {75, 100};
5477 ovrrect.size.width - prgsize.width - 10,
5478 (ovrrect.size.height - prgsize.height) / 2
5481 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
5482 [progress_ setStyle:0];
5483 [overlay_ addSubview:progress_];
5485 cancel_ = [[UINavigationButton alloc] initWithTitle:@"Cancel" style:UINavigationButtonStyleHighlighted];
5486 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
5488 CGRect frame = [cancel_ frame];
5489 frame.size.width = 65;
5490 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
5491 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
5492 [cancel_ setFrame:frame];
5494 [cancel_ setBarStyle:barstyle];
5498 - (void) _onCancel {
5500 [cancel_ removeFromSuperview];
5503 - (void) _update { _pooled
5505 status.setDelegate(self);
5507 [database_ updateWithStatus:status];
5510 performSelectorOnMainThread:@selector(_update_)
5516 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
5517 [prompt_ setText:[NSString stringWithFormat:@"Error: %@", error]];
5520 - (void) setProgressTitle:(NSString *)title {
5522 performSelectorOnMainThread:@selector(_setProgressTitle:)
5528 - (void) setProgressPercent:(float)percent {
5530 performSelectorOnMainThread:@selector(_setProgressPercent:)
5531 withObject:[NSNumber numberWithFloat:percent]
5536 - (void) startProgress {
5539 - (void) addProgressOutput:(NSString *)output {
5541 performSelectorOnMainThread:@selector(_addProgressOutput:)
5547 - (bool) isCancelling:(size_t)received {
5548 NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate];
5549 if (received_ != received) {
5550 received_ = received;
5552 } else if (now - last_ > 15)
5557 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5561 - (void) _setProgressTitle:(NSString *)title {
5562 [prompt_ setText:title];
5565 - (void) _setProgressPercent:(NSNumber *)percent {
5566 [progress_ setProgress:[percent floatValue]];
5569 - (void) _addProgressOutput:(NSString *)output {
5574 /* Cydia:// Protocol {{{ */
5575 @interface CydiaURLProtocol : NSURLProtocol {
5580 @implementation CydiaURLProtocol
5582 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
5583 NSURL *url([request URL]);
5586 NSString *scheme([[url scheme] lowercaseString]);
5587 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
5592 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
5596 - (void) startLoading {
5597 id<NSURLProtocolClient> client([self client]);
5598 NSURLRequest *request([self request]);
5600 NSURL *url([request URL]);
5601 NSString *href([url absoluteString]);
5603 NSString *path([href substringFromIndex:8]);
5604 NSRange slash([path rangeOfString:@"/"]);
5607 if (slash.location == NSNotFound) {
5611 command = [path substringToIndex:slash.location];
5612 path = [path substringFromIndex:(slash.location + 1)];
5615 Database *database([Database sharedInstance]);
5617 if ([command isEqualToString:@"package-icon"]) {
5620 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5621 Package *package([database packageWithName:path]);
5625 UIImage *icon([package icon]);
5627 NSData *data(UIImagePNGRepresentation(icon));
5629 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
5630 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
5631 [client URLProtocol:self didLoadData:data];
5632 [client URLProtocolDidFinishLoading:self];
5633 } else if ([command isEqualToString:@"section-icon"]) {
5636 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5637 NSString *section(Simplify(path));
5639 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
5641 icon = [UIImage applicationImageNamed:@"unknown.png"];
5643 NSData *data(UIImagePNGRepresentation(icon));
5645 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
5646 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
5647 [client URLProtocol:self didLoadData:data];
5648 [client URLProtocolDidFinishLoading:self];
5650 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
5654 - (void) stopLoading {
5660 /* Install View {{{ */
5661 @interface InstallView : RVPage {
5662 _transient Database *database_;
5663 NSMutableArray *sections_;
5664 NSMutableArray *filtered_;
5665 UITransitionView *transition_;
5671 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5672 - (void) reloadData;
5677 @implementation InstallView
5680 [list_ setDataSource:nil];
5681 [list_ setDelegate:nil];
5683 [sections_ release];
5684 [filtered_ release];
5685 [transition_ release];
5687 [accessory_ release];
5691 - (int) numberOfRowsInTable:(UITable *)table {
5692 return editing_ ? [sections_ count] : [filtered_ count] + 1;
5695 - (float) table:(UITable *)table heightForRow:(int)row {
5699 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
5701 reusing = [[[SectionCell alloc] init] autorelease];
5702 [(SectionCell *)reusing setSection:(editing_ ?
5703 [sections_ objectAtIndex:row] :
5704 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
5705 ) editing:editing_];
5709 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5713 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5717 - (void) tableRowSelected:(NSNotification *)notification {
5718 int row = [[notification object] selectedRow];
5729 title = @"All Packages";
5731 section = [filtered_ objectAtIndex:(row - 1)];
5732 name = [section name];
5738 title = @"(No Section)";
5742 PackageTable *table = [[[PackageTable alloc]
5746 filter:@selector(isVisiblyUninstalledInSection:)
5750 [table setDelegate:delegate_];
5752 [book_ pushPage:table];
5755 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5756 if ((self = [super initWithBook:book]) != nil) {
5757 database_ = database;
5759 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5760 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
5762 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
5763 [self addSubview:transition_];
5765 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
5766 [transition_ transition:0 toView:list_];
5768 UITableColumn *column = [[[UITableColumn alloc]
5769 initWithTitle:@"Name"
5771 width:[self frame].size.width
5774 [list_ setDataSource:self];
5775 [list_ setSeparatorStyle:1];
5776 [list_ addTableColumn:column];
5777 [list_ setDelegate:self];
5778 [list_ setReusesTableCells:YES];
5782 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5783 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5787 - (void) reloadData {
5788 NSArray *packages = [database_ packages];
5790 [sections_ removeAllObjects];
5791 [filtered_ removeAllObjects];
5793 NSMutableArray *filtered = [NSMutableArray arrayWithCapacity:[packages count]];
5794 NSMutableDictionary *sections = [NSMutableDictionary dictionaryWithCapacity:32];
5797 for (size_t i(0); i != [packages count]; ++i) {
5798 Package *package([packages objectAtIndex:i]);
5799 NSString *name([package section]);
5802 Section *section([sections objectForKey:name]);
5803 if (section == nil) {
5804 section = [[[Section alloc] initWithName:name] autorelease];
5805 [sections setObject:section forKey:name];
5809 if ([package valid] && [package installed] == nil && [package visible])
5810 [filtered addObject:package];
5814 [sections_ addObjectsFromArray:[sections allValues]];
5815 [sections_ sortUsingSelector:@selector(compareByName:)];
5818 [filtered sortUsingSelector:@selector(compareBySection:)];
5821 Section *section = nil;
5822 for (size_t offset = 0, count = [filtered count]; offset != count; ++offset) {
5823 Package *package = [filtered objectAtIndex:offset];
5824 NSString *name = [package section];
5826 if (section == nil || name != nil && ![[section name] isEqualToString:name]) {
5827 section = name == nil ?
5828 [[[Section alloc] initWithName:nil] autorelease] :
5829 [sections objectForKey:name];
5830 [filtered_ addObject:section];
5833 [section addToCount];
5841 - (void) resetView {
5843 [self _rightButtonClicked];
5846 - (void) resetViewAnimated:(BOOL)animated {
5847 [list_ resetViewAnimated:animated];
5850 - (void) _rightButtonClicked {
5851 if ((editing_ = !editing_))
5854 [delegate_ updateData];
5855 [book_ reloadTitleForPage:self];
5856 [book_ reloadButtonsForPage:self];
5859 - (NSString *) title {
5860 return editing_ ? @"Section Visibility" : @"Install by Section";
5863 - (NSString *) backButtonTitle {
5867 - (NSString *) rightButtonTitle {
5868 return [sections_ count] == 0 ? nil : editing_ ? @"Done" : @"Edit";
5871 - (UINavigationButtonStyle) rightButtonStyle {
5872 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5875 - (UIView *) accessoryView {
5881 /* Changes View {{{ */
5882 @interface ChangesView : RVPage {
5883 _transient Database *database_;
5884 NSMutableArray *packages_;
5885 NSMutableArray *sections_;
5886 UISectionList *list_;
5890 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5891 - (void) reloadData;
5895 @implementation ChangesView
5898 [[list_ table] setDelegate:nil];
5899 [list_ setDataSource:nil];
5901 [packages_ release];
5902 [sections_ release];
5907 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5908 return [sections_ count];
5911 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5912 return [[sections_ objectAtIndex:section] name];
5915 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5916 return [[sections_ objectAtIndex:section] row];
5919 - (int) numberOfRowsInTable:(UITable *)table {
5920 return [packages_ count];
5923 - (float) table:(UITable *)table heightForRow:(int)row {
5924 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
5927 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
5929 reusing = [[[PackageCell alloc] init] autorelease];
5930 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
5934 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5938 - (void) tableRowSelected:(NSNotification *)notification {
5939 int row = [[notification object] selectedRow];
5942 Package *package = [packages_ objectAtIndex:row];
5943 PackageView *view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
5944 [view setDelegate:delegate_];
5945 [view setPackage:package];
5946 [book_ pushPage:view];
5949 - (void) _leftButtonClicked {
5950 [(CYBook *)book_ update];
5951 [self reloadButtons];
5954 - (void) _rightButtonClicked {
5955 [delegate_ distUpgrade];
5958 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5959 if ((self = [super initWithBook:book]) != nil) {
5960 database_ = database;
5962 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5963 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5965 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5966 [self addSubview:list_];
5968 [list_ setShouldHideHeaderInShortLists:NO];
5969 [list_ setDataSource:self];
5970 //[list_ setSectionListStyle:1];
5972 UITableColumn *column = [[[UITableColumn alloc]
5973 initWithTitle:@"Name"
5975 width:[self frame].size.width
5978 UITable *table = [list_ table];
5979 [table setSeparatorStyle:1];
5980 [table addTableColumn:column];
5981 [table setDelegate:self];
5982 [table setReusesTableCells:YES];
5986 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5987 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5991 - (void) reloadData {
5992 NSArray *packages = [database_ packages];
5994 [packages_ removeAllObjects];
5995 [sections_ removeAllObjects];
5998 for (size_t i(0); i != [packages count]; ++i) {
5999 Package *package([packages objectAtIndex:i]);
6002 [package installed] == nil && [package valid] && [package visible] ||
6003 [package upgradableAndEssential:NO]
6005 [packages_ addObject:package];
6009 [packages_ radixSortUsingSelector:@selector(compareForChanges) withObject:nil];
6012 Section *upgradable = [[[Section alloc] initWithName:@"Available Upgrades"] autorelease];
6013 Section *ignored = [[[Section alloc] initWithName:@"Ignored Upgrades"] autorelease];
6014 Section *section = nil;
6018 bool unseens = false;
6020 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
6023 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6024 Package *package = [packages_ objectAtIndex:offset];
6026 if (![package upgradableAndEssential:YES]) {
6028 NSDate *seen = [package seen];
6030 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6033 NSString *name(seen == nil ? [@"n/a ?" retain] : (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen));
6034 section = [[[Section alloc] initWithName:name row:offset] autorelease];
6035 [sections_ addObject:section];
6039 [section addToCount];
6040 } else if ([package ignored])
6041 [ignored addToCount];
6044 [upgradable addToCount];
6049 CFRelease(formatter);
6052 Section *last = [sections_ lastObject];
6053 size_t count = [last count];
6054 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6055 [sections_ removeLastObject];
6058 if ([ignored count] != 0)
6059 [sections_ insertObject:ignored atIndex:0];
6061 [sections_ insertObject:upgradable atIndex:0];
6064 [self reloadButtons];
6067 - (void) resetViewAnimated:(BOOL)animated {
6068 [list_ resetViewAnimated:animated];
6071 - (NSString *) leftButtonTitle {
6072 return [(CYBook *)book_ updating] ? nil : @"Refresh";
6075 - (NSString *) rightButtonTitle {
6076 return upgrades_ == 0 ? nil : [NSString stringWithFormat:@"Upgrade (%u)", upgrades_];
6079 - (NSString *) title {
6085 /* Search View {{{ */
6086 @protocol SearchViewDelegate
6087 - (void) showKeyboard:(BOOL)show;
6090 @interface SearchView : RVPage {
6092 UISearchField *field_;
6093 UITransitionView *transition_;
6094 PackageTable *table_;
6095 UIPreferencesTable *advanced_;
6101 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6102 - (void) reloadData;
6106 @implementation SearchView
6109 [field_ setDelegate:nil];
6111 [accessory_ release];
6113 [transition_ release];
6115 [advanced_ release];
6120 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6124 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6126 case 0: return @"Advanced Search (Coming Soon!)";
6128 default: _assert(false);
6132 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6136 default: _assert(false);
6140 - (void) _showKeyboard:(BOOL)show {
6141 CGSize keysize = [UIKeyboard defaultSize];
6142 CGRect keydown = [book_ pageBounds];
6143 CGRect keyup = keydown;
6144 keyup.size.height -= keysize.height - ButtonBarHeight_;
6146 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6148 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6149 [animation setSignificantRectFields:8];
6152 [animation setStartFrame:keydown];
6153 [animation setEndFrame:keyup];
6155 [animation setStartFrame:keyup];
6156 [animation setEndFrame:keydown];
6159 UIAnimator *animator = [UIAnimator sharedAnimator];
6162 addAnimations:[NSArray arrayWithObjects:animation, nil]
6163 withDuration:(KeyboardTime_ - delay)
6168 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6170 [delegate_ showKeyboard:show];
6173 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6174 [self _showKeyboard:YES];
6177 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6178 [self _showKeyboard:NO];
6181 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6183 NSString *text([field_ text]);
6184 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6190 - (void) textFieldClearButtonPressed:(UITextField *)field {
6194 - (void) keyboardInputShouldDelete:(id)input {
6198 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6199 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6203 [field_ resignFirstResponder];
6208 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6209 if ((self = [super initWithBook:book]) != nil) {
6210 CGRect pageBounds = [book_ pageBounds];
6212 /*UIImageView *pinstripe = [[[UIImageView alloc] initWithFrame:pageBounds] autorelease];
6213 [pinstripe setImage:[UIImage applicationImageNamed:@"pinstripe.png"]];
6214 [self addSubview:pinstripe];*/
6216 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6217 [self addSubview:transition_];
6219 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6221 [advanced_ setReusesTableCells:YES];
6222 [advanced_ setDataSource:self];
6223 [advanced_ reloadData];
6225 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6226 CGColor dimmed(space_, 0, 0, 0, 0.5);
6227 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6229 table_ = [[PackageTable alloc]
6233 filter:@selector(isUnfilteredAndSearchedForBy:)
6237 [table_ setShouldHideHeaderInShortLists:NO];
6238 [transition_ transition:0 toView:table_];
6247 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6254 [self bounds].size.width - area.origin.x - 18;
6256 area.size.height = [UISearchField defaultHeight];
6258 field_ = [[UISearchField alloc] initWithFrame:area];
6260 UIFont *font = [UIFont systemFontOfSize:16];
6261 [field_ setFont:font];
6263 [field_ setPlaceholder:@"Package Names & Descriptions"];
6264 [field_ setDelegate:self];
6266 [field_ setPaddingTop:5];
6268 UITextInputTraits *traits = [field_ textInputTraits];
6269 [traits setAutocapitalizationType:0];
6270 [traits setAutocorrectionType:1];
6271 [traits setReturnKeyType:6];
6273 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6275 accessory_ = [[UIView alloc] initWithFrame:accrect];
6276 [accessory_ addSubview:field_];
6278 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6279 [configure setShowPressFeedback:YES];
6280 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6281 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6282 [accessory_ addSubview:configure];*/
6284 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6285 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6291 LKAnimation *animation = [LKTransition animation];
6292 [animation setType:@"oglFlip"];
6293 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6294 [animation setFillMode:@"extended"];
6295 [animation setTransitionFlags:3];
6296 [animation setDuration:10];
6297 [animation setSpeed:0.35];
6298 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6299 [[transition_ _layer] addAnimation:animation forKey:0];
6300 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6301 flipped_ = !flipped_;
6305 - (void) configurePushed {
6306 [field_ resignFirstResponder];
6310 - (void) resetViewAnimated:(BOOL)animated {
6313 [table_ resetViewAnimated:animated];
6316 - (void) _reloadData {
6319 - (void) reloadData {
6322 [table_ setObject:[field_ text]];
6323 [table_ reloadData];
6324 [table_ resetCursor];
6327 - (UIView *) accessoryView {
6331 - (NSString *) title {
6335 - (NSString *) backButtonTitle {
6339 - (void) setDelegate:(id)delegate {
6340 [table_ setDelegate:delegate];
6341 [super setDelegate:delegate];
6347 @interface SettingsView : RVPage {
6348 _transient Database *database_;
6351 UIPreferencesTable *table_;
6352 _UISwitchSlider *subscribedSwitch_;
6353 _UISwitchSlider *ignoredSwitch_;
6354 UIPreferencesControlTableCell *subscribedCell_;
6355 UIPreferencesControlTableCell *ignoredCell_;
6358 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6362 @implementation SettingsView
6365 [table_ setDataSource:nil];
6368 if (package_ != nil)
6371 [subscribedSwitch_ release];
6372 [ignoredSwitch_ release];
6373 [subscribedCell_ release];
6374 [ignoredCell_ release];
6378 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6379 if (package_ == nil)
6385 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6386 if (package_ == nil)
6393 default: _assert(false);
6399 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
6400 if (package_ == nil)
6407 default: _assert(false);
6413 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6414 if (package_ == nil)
6421 default: _assert(false);
6427 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
6428 if (package_ == nil)
6431 _UISwitchSlider *slider([cell control]);
6432 BOOL value([slider value] != 0);
6433 NSMutableDictionary *metadata([package_ metadata]);
6436 if (NSNumber *number = [metadata objectForKey:key])
6437 before = [number boolValue];
6441 if (value != before) {
6442 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
6444 [delegate_ updateData];
6448 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
6449 [self onSomething:cell withKey:@"IsSubscribed"];
6452 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
6453 [self onSomething:cell withKey:@"IsIgnored"];
6456 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
6457 if (package_ == nil)
6461 case 0: switch (row) {
6463 return subscribedCell_;
6465 return ignoredCell_;
6466 default: _assert(false);
6469 case 1: switch (row) {
6471 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
6472 [cell setShowSelection:NO];
6473 [cell setTitle:@"Changes only shows upgrades to installed packages so as to minimize spam from packagers. Activate this to see upgrades to this package even when it is not installed."];
6477 default: _assert(false);
6480 default: _assert(false);
6486 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
6487 if ((self = [super initWithBook:book])) {
6488 database_ = database;
6489 name_ = [package retain];
6491 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
6492 [self addSubview:table_];
6494 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
6495 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
6497 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
6498 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
6500 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
6501 [subscribedCell_ setShowSelection:NO];
6502 [subscribedCell_ setTitle:@"Show All Changes"];
6503 [subscribedCell_ setControl:subscribedSwitch_];
6505 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
6506 [ignoredCell_ setShowSelection:NO];
6507 [ignoredCell_ setTitle:@"Ignore Upgrades"];
6508 [ignoredCell_ setControl:ignoredSwitch_];
6510 [table_ setDataSource:self];
6515 - (void) resetViewAnimated:(BOOL)animated {
6516 [table_ resetViewAnimated:animated];
6519 - (void) reloadData {
6520 if (package_ != nil)
6521 [package_ autorelease];
6522 package_ = [database_ packageWithName:name_];
6523 if (package_ != nil) {
6525 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
6526 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
6529 [table_ reloadData];
6532 - (NSString *) title {
6538 /* Signature View {{{ */
6539 @interface SignatureView : BrowserView {
6540 _transient Database *database_;
6544 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6548 @implementation SignatureView
6555 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
6557 [super webView:sender didClearWindowObject:window forFrame:frame];
6560 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
6561 if ((self = [super initWithBook:book]) != nil) {
6562 database_ = database;
6563 package_ = [package retain];
6568 - (void) resetViewAnimated:(BOOL)animated {
6571 - (void) reloadData {
6572 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
6578 @interface Cydia : UIApplication <
6579 ConfirmationViewDelegate,
6580 ProgressViewDelegate,
6589 UIToolbar *buttonbar_;
6593 NSMutableArray *essential_;
6594 NSMutableArray *broken_;
6596 Database *database_;
6597 ProgressView *progress_;
6601 UIKeyboard *keyboard_;
6602 UIProgressHUD *hud_;
6604 InstallView *install_;
6605 ChangesView *changes_;
6606 ManageView *manage_;
6607 SearchView *search_;
6612 @implementation Cydia
6615 if ([broken_ count] != 0) {
6616 int count = [broken_ count];
6618 UIActionSheet *sheet = [[[UIActionSheet alloc]
6619 initWithTitle:[NSString stringWithFormat:@"%d Half-Installed Package%@", count, (count == 1 ? @"" : @"s")]
6620 buttons:[NSArray arrayWithObjects:
6622 @"Ignore (Temporary)",
6624 defaultButtonIndex:0
6629 [sheet setBodyText:@"When the shell scripts associated with packages fail, they are left in a bad state known as either half-configured or half-installed. These errors don't go away and instead continue to cause issues. These scripts can be deleted and the packages forcibly removed."];
6630 [sheet popupAlertAnimated:YES];
6631 } else if (!Ignored_ && [essential_ count] != 0) {
6632 int count = [essential_ count];
6634 UIActionSheet *sheet = [[[UIActionSheet alloc]
6635 initWithTitle:[NSString stringWithFormat:@"%d Essential Upgrade%@", count, (count == 1 ? @"" : @"s")]
6636 buttons:[NSArray arrayWithObjects:
6637 @"Upgrade Essential",
6638 @"Complete Upgrade",
6639 @"Ignore (Temporary)",
6641 defaultButtonIndex:0
6646 [sheet setBodyText:@"One or more essential packages are currently out of date. If these upgrades are not performed you are likely to encounter errors."];
6647 [sheet popupAlertAnimated:YES];
6651 - (void) _reloadData {
6652 /*UIProgressHUD *hud = [[UIProgressHUD alloc] initWithWindow:window_];
6653 [hud setText:@"Reloading Data"];
6654 [overlay_ addSubview:hud];
6657 [database_ reloadData];
6661 [essential_ removeAllObjects];
6662 [broken_ removeAllObjects];
6664 NSArray *packages = [database_ packages];
6665 for (Package *package in packages) {
6667 [broken_ addObject:package];
6668 if ([package upgradableAndEssential:NO]) {
6669 if ([package essential])
6670 [essential_ addObject:package];
6676 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
6677 [buttonbar_ setBadgeValue:badge forButton:3];
6678 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
6679 [buttonbar_ setBadgeAnimated:YES forButton:3];
6680 [self setApplicationBadge:badge];
6682 [buttonbar_ setBadgeValue:nil forButton:3];
6683 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
6684 [buttonbar_ setBadgeAnimated:NO forButton:3];
6685 [self removeApplicationBadge];
6691 if ([packages count] == 0);
6703 [hud removeFromSuperview];*/
6706 - (void) _saveConfig {
6709 _assert([Metadata_ writeToFile:@"/var/lib/cydia/metadata.plist" atomically:YES] == YES);
6715 - (void) updateData {
6718 /* XXX: this is just stupid */
6719 if (tag_ != 2 && install_ != nil)
6720 [install_ reloadData];
6721 if (tag_ != 3 && changes_ != nil)
6722 [changes_ reloadData];
6723 if (tag_ != 5 && search_ != nil)
6724 [search_ reloadData];
6734 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
6735 _assert(file != NULL);
6737 NSArray *keys = [Sources_ allKeys];
6739 for (int i(0), e([keys count]); i != e; ++i) {
6740 NSString *key = [keys objectAtIndex:i];
6741 NSDictionary *source = [Sources_ objectForKey:key];
6743 fprintf(file, "%s %s %s\n",
6744 [[source objectForKey:@"Type"] UTF8String],
6745 [[source objectForKey:@"URI"] UTF8String],
6746 [[source objectForKey:@"Distribution"] UTF8String]
6755 detachNewThreadSelector:@selector(update_)
6758 title:@"Updating Sources"
6762 - (void) reloadData {
6763 @synchronized (self) {
6764 if (confirm_ == nil)
6770 pkgProblemResolver *resolver = [database_ resolver];
6772 resolver->InstallProtect();
6773 if (!resolver->Resolve(true))
6778 [database_ prepare];
6780 confirm_ = [[RVBook alloc] initWithFrame:[underlay_ bounds]];
6781 [confirm_ setDelegate:self];
6783 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
6784 [page setDelegate:self];
6786 [confirm_ setPage:page];
6787 [underlay_ popSubview:confirm_];
6790 - (void) installPackage:(Package *)package {
6791 @synchronized (self) {
6798 - (void) removePackage:(Package *)package {
6799 @synchronized (self) {
6806 - (void) distUpgrade {
6807 @synchronized (self) {
6808 [database_ upgrade];
6814 @synchronized (self) {
6816 if (confirm_ != nil) {
6824 [overlay_ removeFromSuperview];
6828 detachNewThreadSelector:@selector(perform)
6835 - (void) bootstrap_ {
6837 [database_ upgrade];
6838 [database_ prepare];
6839 [database_ perform];
6842 - (void) bootstrap {
6844 detachNewThreadSelector:@selector(bootstrap_)
6847 title:@"Bootstrap Install"
6851 - (void) progressViewIsComplete:(ProgressView *)progress {
6852 if (confirm_ != nil) {
6853 [underlay_ addSubview:overlay_];
6854 [confirm_ popFromSuperviewAnimated:NO];
6860 - (void) setPage:(RVPage *)page {
6861 [page resetViewAnimated:NO];
6862 [page setDelegate:self];
6863 [book_ setPage:page];
6866 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
6867 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
6868 [browser loadURL:url];
6872 - (void) _setHomePage {
6873 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
6876 - (void) buttonBarItemTapped:(id)sender {
6877 unsigned tag = [sender tag];
6879 [book_ resetViewAnimated:YES];
6881 } else if (tag_ == 2 && tag != 2)
6882 [install_ resetView];
6885 case 1: [self _setHomePage]; break;
6887 case 2: [self setPage:install_]; break;
6888 case 3: [self setPage:changes_]; break;
6889 case 4: [self setPage:manage_]; break;
6890 case 5: [self setPage:search_]; break;
6892 default: _assert(false);
6898 - (void) applicationWillSuspend {
6900 [super applicationWillSuspend];
6903 - (void) askForSettings {
6904 UIActionSheet *role = [[[UIActionSheet alloc]
6905 initWithTitle:@"Who Are You?"
6906 buttons:[NSArray arrayWithObjects:
6907 @"User (Graphical Only)",
6908 @"Hacker (+ Command Line)",
6909 @"Developer (No Filters)",
6911 defaultButtonIndex:-1
6916 [role setBodyText:@"Not all of the packages available via Cydia are designed to be used by all users. Please categorize yourself so that Cydia can apply helpful filters.\n\nThis choice can be changed from \"Settings\" under the \"Manage\" tab."];
6917 [role popupAlertAnimated:YES];
6922 [self setStatusBarShowsProgress:NO];
6925 [hud_ removeFromSuperview];
6929 pid_t pid = ExecFork();
6931 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
6932 perror("launchctl stop");
6939 [self askForSettings];
6943 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
6945 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
6946 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
6947 0, 0, screenrect.size.width, screenrect.size.height - 48
6948 ) database:database_];
6950 [book_ setDelegate:self];
6952 [overlay_ addSubview:book_];
6954 NSArray *buttonitems = [NSArray arrayWithObjects:
6955 [NSDictionary dictionaryWithObjectsAndKeys:
6956 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
6957 @"home-up.png", kUIButtonBarButtonInfo,
6958 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
6959 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
6960 self, kUIButtonBarButtonTarget,
6961 @"Home", kUIButtonBarButtonTitle,
6962 @"0", kUIButtonBarButtonType,
6965 [NSDictionary dictionaryWithObjectsAndKeys:
6966 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
6967 @"install-up.png", kUIButtonBarButtonInfo,
6968 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
6969 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
6970 self, kUIButtonBarButtonTarget,
6971 @"Sections", kUIButtonBarButtonTitle,
6972 @"0", kUIButtonBarButtonType,
6975 [NSDictionary dictionaryWithObjectsAndKeys:
6976 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
6977 @"changes-up.png", kUIButtonBarButtonInfo,
6978 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
6979 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
6980 self, kUIButtonBarButtonTarget,
6981 @"Changes", kUIButtonBarButtonTitle,
6982 @"0", kUIButtonBarButtonType,
6985 [NSDictionary dictionaryWithObjectsAndKeys:
6986 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
6987 @"manage-up.png", kUIButtonBarButtonInfo,
6988 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
6989 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
6990 self, kUIButtonBarButtonTarget,
6991 @"Manage", kUIButtonBarButtonTitle,
6992 @"0", kUIButtonBarButtonType,
6995 [NSDictionary dictionaryWithObjectsAndKeys:
6996 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
6997 @"search-up.png", kUIButtonBarButtonInfo,
6998 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
6999 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7000 self, kUIButtonBarButtonTarget,
7001 @"Search", kUIButtonBarButtonTitle,
7002 @"0", kUIButtonBarButtonType,
7006 buttonbar_ = [[UIToolbar alloc]
7008 withFrame:CGRectMake(
7009 0, screenrect.size.height - ButtonBarHeight_,
7010 screenrect.size.width, ButtonBarHeight_
7012 withItemList:buttonitems
7015 [buttonbar_ setDelegate:self];
7016 [buttonbar_ setBarStyle:1];
7017 [buttonbar_ setButtonBarTrackingMode:2];
7019 int buttons[5] = {1, 2, 3, 4, 5};
7020 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7021 [buttonbar_ showButtonGroup:0 withDuration:0];
7023 for (int i = 0; i != 5; ++i)
7024 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7025 i * 64 + 2, 1, 60, ButtonBarHeight_
7028 [buttonbar_ showSelectionForButton:1];
7029 [overlay_ addSubview:buttonbar_];
7031 [UIKeyboard initImplementationNow];
7032 CGSize keysize = [UIKeyboard defaultSize];
7033 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7034 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7035 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7036 [overlay_ addSubview:keyboard_];
7039 [underlay_ addSubview:overlay_];
7043 install_ = [[InstallView alloc] initWithBook:book_ database:database_];
7044 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7045 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7047 manage_ = (ManageView *) [[self
7048 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7049 withClass:[ManageView class]
7055 [self _setHomePage];
7058 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7059 NSString *context([sheet context]);
7061 if ([context isEqualToString:@"fixhalf"]) {
7064 @synchronized (self) {
7065 for (int i = 0, e = [broken_ count]; i != e; ++i) {
7066 Package *broken = [broken_ objectAtIndex:i];
7069 NSString *id = [broken id];
7070 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7071 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7072 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7073 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7082 [broken_ removeAllObjects];
7091 } else if ([context isEqualToString:@"role"]) {
7093 case 1: Role_ = @"User"; break;
7094 case 2: Role_ = @"Hacker"; break;
7095 case 3: Role_ = @"Developer"; break;
7102 bool reset = Settings_ != nil;
7104 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7108 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7118 } else if ([context isEqualToString:@"upgrade"]) {
7121 @synchronized (self) {
7122 for (int i = 0, e = [essential_ count]; i != e; ++i) {
7123 Package *essential = [essential_ objectAtIndex:i];
7124 [essential install];
7148 - (void) reorganize { _pooled
7149 system("/usr/libexec/cydia/free.sh");
7150 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7153 - (void) applicationSuspend:(__GSEvent *)event {
7154 if (hud_ == nil && ![progress_ isRunning])
7155 [super applicationSuspend:event];
7158 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7160 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7163 - (void) _setSuspended:(BOOL)value {
7165 [super _setSuspended:value];
7168 - (UIProgressHUD *) addProgressHUD {
7169 UIProgressHUD *hud = [[UIProgressHUD alloc] initWithWindow:window_];
7171 [underlay_ addSubview:hud];
7175 - (void) openMailToURL:(NSURL *)url {
7176 // XXX: this makes me sad
7178 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
7180 [UIApp openURL:url];
7184 - (RVPage *) pageForPackage:(NSString *)name {
7185 if (Package *package = [database_ packageWithName:name]) {
7186 PackageView *view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7187 [view setPackage:package];
7190 UIActionSheet *sheet = [[[UIActionSheet alloc]
7191 initWithTitle:@"Cannot Locate Package"
7192 buttons:[NSArray arrayWithObjects:@"Close", nil]
7193 defaultButtonIndex:0
7198 [sheet setBodyText:[NSString stringWithFormat:
7199 @"The package %@ cannot be found in your current sources. I might recommend installing more sources."
7202 [sheet popupAlertAnimated:YES];
7207 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
7208 NSString *href = [url absoluteString];
7213 if ([href isEqualToString:@"cydia://add-source"])
7214 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
7215 else if ([href isEqualToString:@"cydia://sources"])
7216 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
7217 else if ([href isEqualToString:@"cydia://packages"])
7218 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
7219 else if ([href hasPrefix:@"cydia://url/"])
7220 return [self _pageForURL:[NSURL URLWithString:[href substringFromIndex:12]] withClass:[BrowserView class]];
7221 else if ([href hasPrefix:@"cydia://launch/"])
7222 [self launchApplicationWithIdentifier:[href substringFromIndex:15] suspended:NO];
7223 else if ([href hasPrefix:@"cydia://package-settings/"])
7224 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[href substringFromIndex:25]] autorelease];
7225 else if ([href hasPrefix:@"cydia://package-signature/"])
7226 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[href substringFromIndex:26]] autorelease];
7227 else if ([href hasPrefix:@"cydia://package/"])
7228 return [self pageForPackage:[href substringFromIndex:16]];
7229 else if ([href hasPrefix:@"cydia://files/"]) {
7230 NSString *name = [href substringFromIndex:14];
7232 if (Package *package = [database_ packageWithName:name]) {
7233 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
7234 [files setPackage:package];
7242 - (void) applicationOpenURL:(NSURL *)url {
7243 [super applicationOpenURL:url];
7245 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
7246 [self setPage:page];
7247 [buttonbar_ showSelectionForButton:tag];
7252 - (void) applicationDidFinishLaunching:(id)unused {
7253 Font12_ = [[UIFont systemFontOfSize:12] retain];
7254 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
7255 Font14_ = [[UIFont systemFontOfSize:14] retain];
7256 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
7257 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
7259 _assert(pkgInitConfig(*_config));
7260 _assert(pkgInitSystem(*_config, _system));
7264 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
7265 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
7267 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
7269 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7270 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
7272 [window_ orderFront:self];
7273 [window_ makeKey:self];
7274 [window_ setHidden:NO];
7276 database_ = [Database sharedInstance];
7277 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
7278 [database_ setDelegate:progress_];
7279 [window_ setContentView:progress_];
7281 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
7282 [progress_ setContentView:underlay_];
7284 [progress_ resetView];
7287 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
7288 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
7289 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
7290 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
7291 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
7292 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
7293 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
7295 [self setIdleTimerDisabled:YES];
7297 hud_ = [self addProgressHUD];
7298 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
7300 [self setStatusBarShowsProgress:YES];
7303 detachNewThreadSelector:@selector(reorganize)
7311 /* Web Scripting {{{ */
7312 + (NSString *) webScriptNameForSelector:(SEL)selector {
7313 if (selector == @selector(supports:))
7318 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
7319 return selector != @selector(supports:);
7322 - (BOOL) supports:(NSString *)feature {
7323 return [feature isEqualToString:@"window.open"];
7327 - (void) showKeyboard:(BOOL)show {
7328 CGSize keysize = [UIKeyboard defaultSize];
7329 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
7330 CGRect keyup = keydown;
7331 keyup.origin.y -= keysize.height;
7333 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
7334 [animation setSignificantRectFields:2];
7337 [animation setStartFrame:keydown];
7338 [animation setEndFrame:keyup];
7339 [keyboard_ activate];
7341 [animation setStartFrame:keyup];
7342 [animation setEndFrame:keydown];
7343 [keyboard_ deactivate];
7346 [[UIAnimator sharedAnimator]
7347 addAnimations:[NSArray arrayWithObjects:animation, nil]
7348 withDuration:KeyboardTime_
7353 - (void) slideUp:(UIActionSheet *)alert {
7355 [alert presentSheetFromButtonBar:buttonbar_];
7357 [alert presentSheetInView:overlay_];
7362 void AddPreferences(NSString *plist) { _pooled
7363 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
7364 _assert(settings != NULL);
7365 NSMutableArray *items = [settings objectForKey:@"items"];
7369 for (size_t i(0); i != [items count]; ++i) {
7370 NSMutableDictionary *item([items objectAtIndex:i]);
7371 NSString *label = [item objectForKey:@"label"];
7372 if (label != nil && [label isEqualToString:@"Cydia"]) {
7379 for (size_t i(0); i != [items count]; ++i) {
7380 NSDictionary *item([items objectAtIndex:i]);
7381 NSString *label = [item objectForKey:@"label"];
7382 if (label != nil && [label isEqualToString:@"General"]) {
7383 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
7384 @"CydiaSettings", @"bundle",
7385 @"PSLinkCell", @"cell",
7386 [NSNumber numberWithBool:YES], @"hasIcon",
7387 [NSNumber numberWithBool:YES], @"isController",
7389 nil] atIndex:(i + 1)];
7395 _assert([settings writeToFile:plist atomically:YES] == YES);
7400 id Alloc_(id self, SEL selector) {
7401 id object = alloc_(self, selector);
7402 lprintf("[%s]A-%p\n", self->isa->name, object);
7407 id Dealloc_(id self, SEL selector) {
7408 id object = dealloc_(self, selector);
7409 lprintf("[%s]D-%p\n", self->isa->name, object);
7413 int main(int argc, char *argv[]) { _pooled
7414 bool substrate(false);
7420 for (int argi(1); argi != argc; ++argi)
7421 if (strcmp(argv[argi], "--") == 0) {
7423 argv[argi] = argv[0];
7429 for (int argi(1); argi != arge; ++argi)
7430 if (strcmp(args[argi], "--bootstrap") == 0)
7432 else if (strcmp(args[argi], "--substrate") == 0)
7435 fprintf(stderr, "unknown argument: %s\n", args[argi]);
7438 App_ = [[NSBundle mainBundle] bundlePath];
7439 Home_ = NSHomeDirectory();
7440 Locale_ = CFLocaleCopyCurrent();
7443 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
7444 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
7445 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
7446 Sounds_Keyboard_ = [keyboard boolValue];
7452 #if 1 /* XXX: this costs 1.4s of startup performance */
7453 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
7454 _assert(errno == ENOENT);
7455 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
7456 _assert(errno == ENOENT);
7459 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
7460 alloc_ = alloc->method_imp;
7461 alloc->method_imp = (IMP) &Alloc_;*/
7463 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
7464 dealloc_ = dealloc->method_imp;
7465 dealloc->method_imp = (IMP) &Dealloc_;*/
7470 size = sizeof(maxproc);
7471 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
7472 perror("sysctlbyname(\"kern.maxproc\", ?)");
7473 else if (maxproc < 64) {
7475 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
7476 perror("sysctlbyname(\"kern.maxproc\", #)");
7479 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
7480 char *machine = new char[size];
7481 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
7482 perror("sysctlbyname(\"hw.machine\", ?)");
7486 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
7488 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
7489 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
7491 if ((Metadata_ = [[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"]) == NULL)
7492 Metadata_ = [[NSMutableDictionary alloc] initWithCapacity:2];
7494 Settings_ = [Metadata_ objectForKey:@"Settings"];
7496 Packages_ = [Metadata_ objectForKey:@"Packages"];
7497 Sections_ = [Metadata_ objectForKey:@"Sections"];
7498 Sources_ = [Metadata_ objectForKey:@"Sources"];
7501 if (Settings_ != nil)
7502 Role_ = [Settings_ objectForKey:@"Role"];
7504 if (Packages_ == nil) {
7505 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
7506 [Metadata_ setObject:Packages_ forKey:@"Packages"];
7509 if (Sections_ == nil) {
7510 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
7511 [Metadata_ setObject:Sections_ forKey:@"Sections"];
7514 if (Sources_ == nil) {
7515 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
7516 [Metadata_ setObject:Sources_ forKey:@"Sources"];
7520 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
7523 if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
7524 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);
7526 if (access("/User", F_OK) != 0)
7527 system("/usr/libexec/cydia/firmware.sh");
7529 _assert([[NSFileManager defaultManager]
7530 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
7531 withIntermediateDirectories:YES
7536 space_ = CGColorSpaceCreateDeviceRGB();
7538 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
7539 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
7540 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
7541 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
7542 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
7543 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
7545 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
7547 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
7549 UIApplicationUseLegacyEvents(YES);
7550 UIKeyboardDisableAutomaticAppearance();
7552 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
7554 CGColorSpaceRelease(space_);