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 #include <objc/objc.h>
40 #include <objc/runtime.h>
42 #include <CoreGraphics/CoreGraphics.h>
43 #include <GraphicsServices/GraphicsServices.h>
44 #include <Foundation/Foundation.h>
45 #include <UIKit/UIKit.h>
46 #include <WebCore/DOMHTML.h>
48 #import "BrowserView.h"
50 #import "UICaboodle.h"
52 #include <WebKit/WebFrame.h>
53 #include <WebKit/WebView.h>
58 #include <ext/stdio_filebuf.h>
60 #include <apt-pkg/acquire.h>
61 #include <apt-pkg/acquire-item.h>
62 #include <apt-pkg/algorithms.h>
63 #include <apt-pkg/cachefile.h>
64 #include <apt-pkg/clean.h>
65 #include <apt-pkg/configuration.h>
66 #include <apt-pkg/debmetaindex.h>
67 #include <apt-pkg/error.h>
68 #include <apt-pkg/init.h>
69 #include <apt-pkg/pkgrecords.h>
70 #include <apt-pkg/sourcelist.h>
71 #include <apt-pkg/sptr.h>
73 #include <sys/sysctl.h>
77 #include <mach-o/nlist.h>
88 /* iPhoneOS 2.0 Compatibility {{{ */
90 @interface UICGColor : NSObject {
93 - (id) initWithCGColor:(CGColorRef)color;
99 - (UIFont *) fontWithSize:(CGFloat)size;
102 @interface NSObject (iPhoneOS)
103 - (CGColorRef) cgColor;
104 - (CGColorRef) CGColor;
108 @implementation NSObject (iPhoneOS)
110 - (CGColorRef) cgColor {
111 return [self CGColor];
114 - (CGColorRef) CGColor {
115 return (CGColorRef) self;
119 [[[[objc_getClass("UICGColor") alloc] initWithCGColor:[self CGColor]] autorelease] set];
124 @interface UITextView (iPhoneOS)
125 - (void) setTextSize:(float)size;
128 @implementation UITextView (iPhoneOS)
130 - (void) setTextSize:(float)size {
131 [self setFont:[[self font] fontWithSize:size]];
138 @interface NSString (UIKit)
139 - (NSString *) stringByAddingPercentEscapes;
140 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
143 @interface NSString (Cydia)
144 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
145 - (NSComparisonResult) compareByPath:(NSString *)other;
148 @implementation NSString (Cydia)
150 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
151 char data[length + 1];
152 memcpy(data, bytes, length);
154 return [NSString stringWithUTF8String:data];
157 - (NSComparisonResult) compareByPath:(NSString *)other {
158 NSString *prefix = [self commonPrefixWithString:other options:0];
159 size_t length = [prefix length];
161 NSRange lrange = NSMakeRange(length, [self length] - length);
162 NSRange rrange = NSMakeRange(length, [other length] - length);
164 lrange = [self rangeOfString:@"/" options:0 range:lrange];
165 rrange = [other rangeOfString:@"/" options:0 range:rrange];
167 NSComparisonResult value;
169 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
170 value = NSOrderedSame;
171 else if (lrange.location == NSNotFound)
172 value = NSOrderedAscending;
173 else if (rrange.location == NSNotFound)
174 value = NSOrderedDescending;
176 value = NSOrderedSame;
178 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
179 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
180 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
181 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
183 NSComparisonResult result = [lpath compare:rpath];
184 return result == NSOrderedSame ? value : result;
189 /* Perl-Compatible RegEx {{{ */
199 Pcre(const char *regex) :
204 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
207 fprintf(stderr, "%d:%s\n", offset, error);
211 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
212 matches_ = new int[(capture_ + 1) * 3];
220 NSString *operator [](size_t match) {
221 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
224 bool operator ()(NSString *data) {
225 // XXX: length is for characters, not for bytes
226 return operator ()([data UTF8String], [data length]);
229 bool operator ()(const char *data, size_t size) {
231 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
235 /* Mime Addresses {{{ */
236 Pcre email_r("^\"?(.*)\"? <([^>]*)>$");
238 @interface Address : NSObject {
244 - (NSString *) email;
246 + (Address *) addressWithString:(NSString *)string;
247 - (Address *) initWithString:(NSString *)string;
250 @implementation Address
259 - (NSString *) name {
263 - (NSString *) email {
267 + (Address *) addressWithString:(NSString *)string {
268 return [[[Address alloc] initWithString:string] autorelease];
271 - (Address *) initWithString:(NSString *)string {
272 if ((self = [super init]) != nil) {
273 const char *data = [string UTF8String];
274 size_t size = [string length];
276 if (email_r(data, size)) {
277 name_ = [email_r[1] retain];
278 email_ = [email_r[2] retain];
280 name_ = [[NSString alloc]
283 encoding:kCFStringEncodingUTF8
293 /* CoreGraphics Primitives {{{ */
304 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
307 Set(space, red, green, blue, alpha);
312 CGColorRelease(color_);
319 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
321 float color[] = {red, green, blue, alpha};
322 color_ = CGColorCreate(space, color);
325 operator CGColorRef() {
340 /* Right Alignment {{{ */
341 @interface UIRightTextLabel : UITextLabel {
342 float _savedRightEdgeX;
343 BOOL _sizedtofit_flag;
346 - (void) setFrame:(CGRect)frame;
347 - (void) setText:(NSString *)text;
348 - (void) realignText;
351 @implementation UIRightTextLabel
353 - (void) setFrame:(CGRect)frame {
354 [super setFrame:frame];
355 if (_sizedtofit_flag == NO) {
356 _savedRightEdgeX = frame.origin.x;
361 - (void) setText:(NSString *)text {
362 [super setText:text];
366 - (void) realignText {
367 CGRect oldFrame = [self frame];
369 _sizedtofit_flag = YES;
370 [self sizeToFit]; // shrink down size so I can right align it
372 CGRect newFrame = [self frame];
374 oldFrame.origin.x = _savedRightEdgeX - newFrame.size.width;
375 oldFrame.size.width = newFrame.size.width;
376 [super setFrame:oldFrame];
377 _sizedtofit_flag = NO;
383 /* Random Global Variables {{{ */
384 static const int PulseInterval_ = 50000;
385 static const int ButtonBarHeight_ = 48;
386 static const float KeyboardTime_ = 0.4f;
392 static CGColor Blueish_;
393 static CGColor Black_;
394 static CGColor Clear_;
396 static CGColor White_;
398 static NSString *Home_;
399 static BOOL Sounds_Keyboard_;
401 static BOOL Advanced_;
403 static BOOL Ignored_;
405 const char *Firmware_ = NULL;
406 const char *Machine_ = NULL;
407 const char *SerialNumber_ = NULL;
413 CGColorSpaceRef space_;
415 #define FW_LEAST(major, minor, bugfix) \
416 (major < Major_ || major == Major_ && \
417 (minor < Minor_ || minor == Minor_ && \
423 static NSMutableDictionary *Metadata_;
424 static NSMutableDictionary *Packages_;
425 static bool Changed_;
428 NSString *GetLastUpdate() {
429 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
432 return @"Never or Unknown";
434 CFLocaleRef locale = CFLocaleCopyCurrent();
435 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, locale, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
436 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
438 CFRelease(formatter);
441 return [(NSString *) formatted autorelease];
444 /* Display Helpers {{{ */
445 inline float Interpolate(float begin, float end, float fraction) {
446 return (end - begin) * fraction + begin;
449 NSString *SizeString(double size) {
451 while (size > 1024) {
456 static const char *powers_[] = {"B", "kB", "MB", "GB"};
458 return [NSString stringWithFormat:@"%.1f%s", size, powers_[power]];
461 static const float TextViewOffset_ = 22;
463 UITextView *GetTextView(NSString *value, float left, bool html) {
464 UITextView *text([[[UITextView alloc] initWithFrame:CGRectMake(left, 3, 310 - left, 1000)] autorelease]);
465 [text setEditable:NO];
466 [text setTextSize:16];
468 [text setHTML:value];
470 [text setText:value];
471 [text setEnabled:NO];
473 [text setBackgroundColor:Clear_];
475 CGRect frame = [text frame];
476 [text setFrame:frame];
477 CGRect rect = [text visibleTextRect];
478 frame.size.height = rect.size.height;
479 [text setFrame:frame];
484 NSString *Simplify(NSString *title) {
485 const char *data = [title UTF8String];
486 size_t size = [title length];
488 Pcre title_r("^(.*?)( \\(.*\\))?$");
489 if (title_r(data, size))
496 /* Delegate Prototypes {{{ */
500 @protocol ProgressDelegate
501 - (void) setProgressError:(NSString *)error;
502 - (void) setProgressTitle:(NSString *)title;
503 - (void) setProgressPercent:(float)percent;
504 - (void) addProgressOutput:(NSString *)output;
507 @protocol ConfigurationDelegate
508 - (void) repairWithSelector:(SEL)selector;
509 - (void) setConfigurationData:(NSString *)data;
512 @protocol CydiaDelegate
513 - (void) installPackage:(Package *)package;
514 - (void) removePackage:(Package *)package;
515 - (void) slideUp:(UIAlertSheet *)alert;
516 - (void) distUpgrade;
520 /* Status Delegation {{{ */
522 public pkgAcquireStatus
525 _transient id<ProgressDelegate> delegate_;
533 void setDelegate(id delegate) {
534 delegate_ = delegate;
537 virtual bool MediaChange(std::string media, std::string drive) {
541 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
544 virtual void Fetch(pkgAcquire::ItemDesc &item) {
545 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
548 virtual void Done(pkgAcquire::ItemDesc &item) {
551 virtual void Fail(pkgAcquire::ItemDesc &item) {
553 item.Owner->Status == pkgAcquire::Item::StatIdle ||
554 item.Owner->Status == pkgAcquire::Item::StatDone
558 [delegate_ setProgressError:[NSString stringWithUTF8String:item.Owner->ErrorText.c_str()]];
561 virtual bool Pulse(pkgAcquire *Owner) {
562 bool value = pkgAcquireStatus::Pulse(Owner);
565 double(CurrentBytes + CurrentItems) /
566 double(TotalBytes + TotalItems)
569 [delegate_ setProgressPercent:percent];
573 virtual void Start() {
576 virtual void Stop() {
580 /* Progress Delegation {{{ */
585 _transient id<ProgressDelegate> delegate_;
588 virtual void Update() {
589 [delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
590 [delegate_ setProgressPercent:(Percent / 100)];
599 void setDelegate(id delegate) {
600 delegate_ = delegate;
603 virtual void Done() {
604 [delegate_ setProgressPercent:1];
609 /* Database Interface {{{ */
610 @interface Database : NSObject {
612 pkgDepCache::Policy *policy_;
613 pkgRecords *records_;
614 pkgProblemResolver *resolver_;
615 pkgAcquire *fetcher_;
617 SPtr<pkgPackageManager> manager_;
618 pkgSourceList *list_;
620 NSMutableDictionary *sources_;
621 NSMutableArray *packages_;
623 _transient id<ConfigurationDelegate, ProgressDelegate> delegate_;
632 - (void) _readCydia:(NSNumber *)fd;
633 - (void) _readStatus:(NSNumber *)fd;
634 - (void) _readOutput:(NSNumber *)fd;
638 - (Package *) packageWithName:(NSString *)name;
641 - (pkgCacheFile &) cache;
642 - (pkgDepCache::Policy *) policy;
643 - (pkgRecords *) records;
644 - (pkgProblemResolver *) resolver;
645 - (pkgAcquire &) fetcher;
646 - (NSArray *) packages;
655 - (void) updateWithStatus:(Status &)status;
657 - (void) setDelegate:(id)delegate;
658 - (Source *) getSource:(const pkgCache::PkgFileIterator &)file;
662 /* Source Class {{{ */
663 @interface Source : NSObject {
664 NSString *description_;
669 NSString *distribution_;
673 NSString *defaultIcon_;
678 - (Source *) initWithMetaIndex:(metaIndex *)index;
683 - (NSString *) distribution;
686 - (NSString *) description;
687 - (NSString *) label;
688 - (NSString *) origin;
689 - (NSString *) version;
691 - (NSString *) defaultIcon;
694 @implementation Source
698 [distribution_ release];
701 if (description_ != nil)
702 [description_ release];
709 if (defaultIcon_ != nil)
710 [defaultIcon_ release];
715 - (Source *) initWithMetaIndex:(metaIndex *)index {
716 if ((self = [super init]) != nil) {
717 trusted_ = index->IsTrusted();
719 uri_ = [[NSString stringWithUTF8String:index->GetURI().c_str()] retain];
720 distribution_ = [[NSString stringWithUTF8String:index->GetDist().c_str()] retain];
721 type_ = [[NSString stringWithUTF8String:index->GetType()] retain];
729 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
730 if (dindex != NULL) {
731 std::ifstream release(dindex->MetaIndexFile("Release").c_str());
733 while (std::getline(release, line)) {
734 std::string::size_type colon(line.find(':'));
735 if (colon == std::string::npos)
738 std::string name(line.substr(0, colon));
739 std::string value(line.substr(colon + 1));
740 while (!value.empty() && value[0] == ' ')
741 value = value.substr(1);
743 if (name == "Default-Icon")
744 defaultIcon_ = [[NSString stringWithUTF8String:value.c_str()] retain];
745 else if (name == "Description")
746 description_ = [[NSString stringWithUTF8String:value.c_str()] retain];
747 else if (name == "Label")
748 label_ = [[NSString stringWithUTF8String:value.c_str()] retain];
749 else if (name == "Origin")
750 origin_ = [[NSString stringWithUTF8String:value.c_str()] retain];
751 else if (name == "Version")
752 version_ = [[NSString stringWithUTF8String:value.c_str()] retain];
766 - (NSString *) distribution {
767 return distribution_;
770 - (NSString *) type {
774 - (NSString *) description {
778 - (NSString *) label {
782 - (NSString *) origin {
786 - (NSString *) version {
790 - (NSString *) defaultIcon {
796 /* Relationship Class {{{ */
797 @interface Relationship : NSObject {
808 @implementation Relationship
816 - (NSString *) type {
824 - (NSString *) name {
831 /* Package Class {{{ */
832 NSString *Scour(const char *field, const char *begin, const char *end) {
833 size_t i(0), l(strlen(field));
836 const char *name = begin + i;
837 const char *colon = name + l;
838 const char *value = colon + 1;
843 memcmp(name, field, l) == 0
845 while (value != end && value[0] == ' ')
847 const char *line = std::find(value, end, '\n');
848 while (line != value && line[-1] == ' ')
851 return [NSString stringWithUTF8Bytes:value length:(line - value)];
853 begin = std::find(begin, end, '\n');
861 @interface Package : NSObject {
862 pkgCache::PkgIterator iterator_;
863 _transient Database *database_;
864 pkgCache::VerIterator version_;
865 pkgCache::VerFileIterator file_;
871 NSString *installed_;
880 NSArray *relationships_;
883 - (Package *) initWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database;
884 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database;
886 - (pkgCache::PkgIterator) iterator;
888 - (NSString *) section;
889 - (Address *) maintainer;
891 - (NSString *) description;
892 - (NSString *) index;
896 - (NSString *) latest;
897 - (NSString *) installed;
906 - (NSString *) tagline;
908 - (NSString *) website;
909 - (Address *) author;
911 - (NSArray *) relationships;
915 - (BOOL) matches:(NSString *)text;
917 - (NSComparisonResult) compareByName:(Package *)package;
918 - (NSComparisonResult) compareBySection:(Package *)package;
919 - (NSComparisonResult) compareBySectionAndName:(Package *)package;
920 - (NSComparisonResult) compareForChanges:(Package *)package;
925 - (NSNumber *) isSearchedForBy:(NSString *)search;
926 - (NSNumber *) isInstalledInSection:(NSString *)section;
927 - (NSNumber *) isUninstalledInSection:(NSString *)section;
931 @implementation Package
938 if (installed_ != nil)
939 [installed_ release];
952 if (relationships_ != nil)
953 [relationships_ release];
958 - (Package *) initWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database {
959 if ((self = [super init]) != nil) {
960 iterator_ = iterator;
961 database_ = database;
963 version_ = [database_ policy]->GetCandidateVer(iterator_);
964 latest_ = version_.end() ? nil : [[NSString stringWithUTF8String:version_.VerStr()] retain];
967 file_ = version_.FileList();
969 pkgCache &cache([database_ cache]);
970 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
973 pkgCache::VerIterator current = iterator_.CurrentVer();
974 installed_ = current.end() ? nil : [[NSString stringWithUTF8String:current.VerStr()] retain];
976 id_ = [[[NSString stringWithUTF8String:iterator_.Name()] lowercaseString] retain];
979 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
981 const char *begin, *end;
982 parser->GetRec(begin, end);
984 name_ = Scour("Name", begin, end);
986 name_ = [name_ retain];
987 tagline_ = [[NSString stringWithUTF8String:parser->ShortDesc().c_str()] retain];
988 icon_ = Scour("Icon", begin, end);
990 icon_ = [icon_ retain];
991 website_ = Scour("Homepage", begin, end);
993 website_ = Scour("Website", begin, end);
995 website_ = [website_ retain];
996 NSString *author = Scour("Author", begin, end);
998 author_ = [Address addressWithString:author];
1001 NSMutableDictionary *metadata = [Packages_ objectForKey:id_];
1002 if (metadata == nil || [metadata count] == 0) {
1003 metadata = [NSMutableDictionary dictionaryWithObjectsAndKeys:
1007 [Packages_ setObject:metadata forKey:id_];
1013 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database {
1014 return [[[Package alloc]
1015 initWithIterator:iterator
1020 - (pkgCache::PkgIterator) iterator {
1024 - (NSString *) section {
1025 const char *section = iterator_.Section();
1026 return section == NULL ? nil : [[NSString stringWithUTF8String:section] stringByReplacingCharacter:'_' withCharacter:' '];
1029 - (Address *) maintainer {
1032 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
1033 return [Address addressWithString:[NSString stringWithUTF8String:parser->Maintainer().c_str()]];
1037 return version_.end() ? 0 : version_->InstalledSize;
1040 - (NSString *) description {
1043 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
1044 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
1046 NSArray *lines = [description componentsSeparatedByString:@"\n"];
1047 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
1048 if ([lines count] < 2)
1051 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
1052 for (size_t i(1); i != [lines count]; ++i) {
1053 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
1054 [trimmed addObject:trim];
1057 return [trimmed componentsJoinedByString:@"\n"];
1060 - (NSString *) index {
1061 NSString *index = [[[self name] substringToIndex:1] uppercaseString];
1062 return [index length] != 0 && isalpha([index characterAtIndex:0]) ? index : @"123";
1066 return [[Packages_ objectForKey:id_] objectForKey:@"FirstSeen"];
1069 - (NSString *) latest {
1073 - (NSString *) installed {
1078 return !version_.end();
1081 - (BOOL) upgradable {
1082 pkgCache::VerIterator current = iterator_.CurrentVer();
1085 return [self essential];
1087 pkgCache::VerIterator candidate = [database_ policy]->GetCandidateVer(iterator_);
1088 return !candidate.end() && candidate != current;
1092 - (BOOL) essential {
1093 return (iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES;
1097 return (*[database_ cache])[iterator_].InstBroken();
1104 - (NSString *) name {
1105 return name_ == nil ? id_ : name_;
1108 - (NSString *) tagline {
1112 - (NSString *) icon {
1116 - (NSString *) website {
1120 - (Address *) author {
1124 - (NSArray *) relationships {
1125 return relationships_;
1128 - (Source *) source {
1130 source_ = file_.end() ? nil : [[database_ getSource:file_.File()] retain];
1137 - (BOOL) matches:(NSString *)text {
1143 range = [[self id] rangeOfString:text options:NSCaseInsensitiveSearch];
1144 if (range.location != NSNotFound)
1147 range = [[self name] rangeOfString:text options:NSCaseInsensitiveSearch];
1148 if (range.location != NSNotFound)
1151 range = [[self tagline] rangeOfString:text options:NSCaseInsensitiveSearch];
1152 if (range.location != NSNotFound)
1158 - (NSComparisonResult) compareByName:(Package *)package {
1159 NSString *lhs = [self name];
1160 NSString *rhs = [package name];
1162 if ([lhs length] != 0 && [rhs length] != 0) {
1163 unichar lhc = [lhs characterAtIndex:0];
1164 unichar rhc = [rhs characterAtIndex:0];
1166 if (isalpha(lhc) && !isalpha(rhc))
1167 return NSOrderedAscending;
1168 else if (!isalpha(lhc) && isalpha(rhc))
1169 return NSOrderedDescending;
1172 return [lhs caseInsensitiveCompare:rhs];
1175 - (NSComparisonResult) compareBySection:(Package *)package {
1176 NSString *lhs = [self section];
1177 NSString *rhs = [package section];
1179 if (lhs == NULL && rhs != NULL)
1180 return NSOrderedAscending;
1181 else if (lhs != NULL && rhs == NULL)
1182 return NSOrderedDescending;
1183 else if (lhs != NULL && rhs != NULL) {
1184 NSComparisonResult result = [lhs caseInsensitiveCompare:rhs];
1185 if (result != NSOrderedSame)
1189 return NSOrderedSame;
1192 - (NSComparisonResult) compareBySectionAndName:(Package *)package {
1193 NSString *lhs = [self section];
1194 NSString *rhs = [package section];
1196 if (lhs == NULL && rhs != NULL)
1197 return NSOrderedAscending;
1198 else if (lhs != NULL && rhs == NULL)
1199 return NSOrderedDescending;
1200 else if (lhs != NULL && rhs != NULL) {
1201 NSComparisonResult result = [lhs compare:rhs];
1202 if (result != NSOrderedSame)
1206 return [self compareByName:package];
1209 - (NSComparisonResult) compareForChanges:(Package *)package {
1210 BOOL lhs = [self upgradable];
1211 BOOL rhs = [package upgradable];
1214 return lhs ? NSOrderedAscending : NSOrderedDescending;
1216 switch ([[self seen] compare:[package seen]]) {
1217 case NSOrderedAscending:
1218 return NSOrderedDescending;
1221 case NSOrderedDescending:
1222 return NSOrderedAscending;
1228 return [self compareByName:package];
1232 pkgProblemResolver *resolver = [database_ resolver];
1233 resolver->Clear(iterator_);
1234 resolver->Protect(iterator_);
1235 pkgCacheFile &cache([database_ cache]);
1236 cache->MarkInstall(iterator_, false);
1237 pkgDepCache::StateCache &state((*cache)[iterator_]);
1238 if (!state.Install())
1239 cache->SetReInstall(iterator_, true);
1243 pkgProblemResolver *resolver = [database_ resolver];
1244 resolver->Clear(iterator_);
1245 resolver->Protect(iterator_);
1246 resolver->Remove(iterator_);
1247 [database_ cache]->MarkDelete(iterator_, true);
1250 - (NSNumber *) isSearchedForBy:(NSString *)search {
1251 return [NSNumber numberWithBool:([self valid] && [self matches:search])];
1254 - (NSNumber *) isInstalledInSection:(NSString *)section {
1255 return [NSNumber numberWithBool:([self installed] != nil && (section == nil || [section isEqualToString:[self section]]))];
1258 - (NSNumber *) isUninstalledInSection:(NSString *)name {
1259 NSString *section = [self section];
1261 return [NSNumber numberWithBool:([self valid] && [self installed] == nil && (
1263 section == nil && [name length] == 0 ||
1264 [name isEqualToString:section])
1270 /* Section Class {{{ */
1271 @interface Section : NSObject {
1277 - (Section *) initWithName:(NSString *)name row:(size_t)row;
1278 - (NSString *) name;
1281 - (void) addToCount;
1285 @implementation Section
1292 - (Section *) initWithName:(NSString *)name row:(size_t)row {
1293 if ((self = [super init]) != nil) {
1294 name_ = [name retain];
1299 - (NSString *) name {
1311 - (void) addToCount {
1318 /* Database Implementation {{{ */
1319 @implementation Database
1326 - (void) _readCydia:(NSNumber *)fd {
1327 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1329 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
1330 std::istream is(&ib);
1333 while (std::getline(is, line)) {
1334 const char *data(line.c_str());
1335 //size_t size = line.size();
1336 fprintf(stderr, "C:%s\n", data);
1343 - (void) _readStatus:(NSNumber *)fd {
1344 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1346 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
1347 std::istream is(&ib);
1350 Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
1351 Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
1353 while (std::getline(is, line)) {
1354 const char *data(line.c_str());
1355 size_t size = line.size();
1356 fprintf(stderr, "S:%s\n", data);
1358 if (conffile_r(data, size)) {
1359 [delegate_ setConfigurationData:conffile_r[1]];
1360 } else if (strncmp(data, "status: ", 8) == 0) {
1361 NSString *string = [NSString stringWithUTF8String:(data + 8)];
1362 [delegate_ setProgressTitle:string];
1363 } else if (pmstatus_r(data, size)) {
1364 float percent([pmstatus_r[3] floatValue]);
1365 [delegate_ setProgressPercent:(percent / 100)];
1367 NSString *string = pmstatus_r[4];
1368 std::string type([pmstatus_r[1] UTF8String]);
1370 if (type == "pmerror")
1371 [delegate_ setProgressError:string];
1372 else if (type == "pmstatus")
1373 [delegate_ setProgressTitle:string];
1374 else if (type == "pmconffile")
1375 [delegate_ setConfigurationData:string];
1376 else _assert(false);
1377 } else _assert(false);
1384 - (void) _readOutput:(NSNumber *)fd {
1385 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1387 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
1388 std::istream is(&ib);
1391 while (std::getline(is, line)) {
1392 fprintf(stderr, "O:%s\n", line.c_str());
1393 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
1404 - (Package *) packageWithName:(NSString *)name {
1405 if (static_cast<pkgDepCache *>(cache_) == NULL)
1407 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
1408 return iterator.end() ? nil : [Package packageWithIterator:iterator database:self];
1411 - (Database *) init {
1412 if ((self = [super init]) != nil) {
1419 sources_ = [[NSMutableDictionary dictionaryWithCapacity:16] retain];
1420 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
1424 _assert(pipe(fds) != -1);
1427 _config->Set("APT::Keep-Fds::", cydiafd_);
1428 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 0"] UTF8String], _not(int));
1431 detachNewThreadSelector:@selector(_readCydia:)
1433 withObject:[[NSNumber numberWithInt:fds[0]] retain]
1436 _assert(pipe(fds) != -1);
1440 detachNewThreadSelector:@selector(_readStatus:)
1442 withObject:[[NSNumber numberWithInt:fds[0]] retain]
1445 _assert(pipe(fds) != -1);
1446 _assert(dup2(fds[0], 0) != -1);
1447 _assert(close(fds[0]) != -1);
1449 input_ = fdopen(fds[1], "a");
1451 _assert(pipe(fds) != -1);
1452 _assert(dup2(fds[1], 1) != -1);
1453 _assert(close(fds[1]) != -1);
1456 detachNewThreadSelector:@selector(_readOutput:)
1458 withObject:[[NSNumber numberWithInt:fds[0]] retain]
1463 - (pkgCacheFile &) cache {
1467 - (pkgDepCache::Policy *) policy {
1471 - (pkgRecords *) records {
1475 - (pkgProblemResolver *) resolver {
1479 - (pkgAcquire &) fetcher {
1483 - (NSArray *) packages {
1487 - (void) reloadData {
1506 if (!cache_.Open(progress_, true)) {
1508 if (!_error->PopMessage(error))
1511 fprintf(stderr, "cache_.Open():[%s]\n", error.c_str());
1513 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
1514 [delegate_ repairWithSelector:@selector(configure)];
1515 else if (error == "The package lists or status file could not be parsed or opened.")
1516 [delegate_ repairWithSelector:@selector(update)];
1517 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
1518 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
1519 // else if (error == "The list of sources could not be read.")
1520 else _assert(false);
1525 now_ = [[NSDate date] retain];
1527 policy_ = new pkgDepCache::Policy();
1528 records_ = new pkgRecords(cache_);
1529 resolver_ = new pkgProblemResolver(cache_);
1530 fetcher_ = new pkgAcquire(&status_);
1533 list_ = new pkgSourceList();
1534 _assert(list_->ReadMainList());
1536 [sources_ removeAllObjects];
1537 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
1538 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
1539 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
1541 setObject:[[[Source alloc] initWithMetaIndex:*source] autorelease]
1542 forKey:[NSNumber numberWithLong:reinterpret_cast<uintptr_t>(*index)]
1546 [packages_ removeAllObjects];
1547 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
1548 if (Package *package = [Package packageWithIterator:iterator database:self])
1549 [packages_ addObject:package];
1551 [packages_ sortUsingSelector:@selector(compareByName:)];
1554 - (void) configure {
1555 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
1556 system([dpkg UTF8String]);
1564 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
1565 _assert(!_error->PendingError());
1568 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
1570 class LogCleaner : public pkgArchiveCleaner {
1572 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
1577 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
1579 while (_error->PopMessage(error))
1580 fprintf(stderr, "ArchiveCleaner: %s\n", error.c_str());
1585 pkgRecords records(cache_);
1587 lock_ = new FileFd();
1588 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
1589 _assert(!_error->PendingError());
1592 // XXX: explain this with an error message
1593 _assert(list.ReadMainList());
1595 manager_ = (_system->CreatePM(cache_));
1596 _assert(manager_->GetArchives(fetcher_, &list, &records));
1597 _assert(!_error->PendingError());
1601 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
1603 _assert(list.ReadMainList());
1604 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
1605 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
1608 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue)
1612 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
1614 if (result == pkgPackageManager::Failed)
1616 if (_error->PendingError())
1618 if (result != pkgPackageManager::Completed)
1621 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
1623 _assert(list.ReadMainList());
1624 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
1625 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
1628 if (![before isEqualToArray:after])
1633 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
1634 _assert(pkgApplyStatus(cache_));
1636 if (cache_->BrokenCount() != 0) {
1637 _assert(pkgFixBroken(cache_));
1638 _assert(cache_->BrokenCount() == 0);
1639 _assert(pkgMinimizeUpgrade(cache_));
1642 _assert(pkgDistUpgrade(cache_));
1646 [self updateWithStatus:status_];
1649 - (void) updateWithStatus:(Status &)status {
1651 _assert(list.ReadMainList());
1654 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
1655 _assert(!_error->PendingError());
1657 pkgAcquire fetcher(&status);
1658 _assert(list.GetIndexes(&fetcher));
1660 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
1661 bool failed = false;
1662 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
1663 if ((*item)->Status != pkgAcquire::Item::StatDone) {
1664 (*item)->Finished();
1668 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
1669 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
1670 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
1673 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
1678 - (void) setDelegate:(id)delegate {
1679 delegate_ = delegate;
1680 status_.setDelegate(delegate);
1681 progress_.setDelegate(delegate);
1684 - (Source *) getSource:(const pkgCache::PkgFileIterator &)file {
1685 pkgIndexFile *index(NULL);
1686 list_->FindIndex(file, index);
1687 return [sources_ objectForKey:[NSNumber numberWithLong:reinterpret_cast<uintptr_t>(index)]];
1693 /* Confirmation View {{{ */
1694 void AddTextView(NSMutableDictionary *fields, NSMutableArray *packages, NSString *key) {
1695 if ([packages count] == 0)
1698 UITextView *text = GetTextView([packages count] == 0 ? @"n/a" : [packages componentsJoinedByString:@", "], 120, false);
1699 [fields setObject:text forKey:key];
1701 CGColor blue(space_, 0, 0, 0.4, 1);
1702 [text setTextColor:blue];
1705 @protocol ConfirmationViewDelegate
1710 @interface ConfirmationView : UIView {
1711 Database *database_;
1713 UITransitionView *transition_;
1715 UINavigationBar *navbar_;
1716 UIPreferencesTable *table_;
1717 NSMutableDictionary *fields_;
1718 UIAlertSheet *essential_;
1723 - (id) initWithView:(UIView *)view database:(Database *)database delegate:(id)delegate;
1727 @implementation ConfirmationView
1730 [navbar_ setDelegate:nil];
1731 [transition_ setDelegate:nil];
1732 [table_ setDataSource:nil];
1734 [transition_ release];
1739 if (essential_ != nil)
1740 [essential_ release];
1745 [transition_ transition:7 toView:nil];
1749 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
1750 if (from != nil && to == nil)
1751 [self removeFromSuperview];
1754 - (void) navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button {
1757 if (essential_ != nil)
1758 [essential_ popupAlertAnimated:YES];
1760 [delegate_ confirm];
1769 - (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
1770 [essential_ dismiss];
1774 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
1778 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
1780 case 0: return @"Statistics";
1781 case 1: return @"Modifications";
1783 default: _assert(false);
1787 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
1790 case 1: return [fields_ count];
1792 default: _assert(false);
1796 - (float) preferencesTable:(UIPreferencesTable *)table heightForRow:(int)row inGroup:(int)group withProposedHeight:(float)proposed {
1797 if (group != 1 || row == -1)
1800 _assert(size_t(row) < [fields_ count]);
1801 return [[[fields_ allValues] objectAtIndex:row] visibleTextRect].size.height + TextViewOffset_;
1805 - (UIPreferencesTableCell *) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
1806 UIPreferencesTableCell *cell = [[[UIPreferencesTableCell alloc] init] autorelease];
1807 [cell setShowSelection:NO];
1810 case 0: switch (row) {
1812 [cell setTitle:@"Downloading"];
1813 [cell setValue:SizeString([database_ fetcher].FetchNeeded())];
1817 [cell setTitle:@"Resuming At"];
1818 [cell setValue:SizeString([database_ fetcher].PartialPresent())];
1822 double size([database_ cache]->UsrSize());
1825 [cell setTitle:@"Disk Freeing"];
1826 [cell setValue:SizeString(-size)];
1828 [cell setTitle:@"Disk Using"];
1829 [cell setValue:SizeString(size)];
1833 default: _assert(false);
1837 _assert(size_t(row) < [fields_ count]);
1838 [cell setTitle:[[fields_ allKeys] objectAtIndex:row]];
1839 [cell addSubview:[[fields_ allValues] objectAtIndex:row]];
1842 default: _assert(false);
1848 - (id) initWithView:(UIView *)view database:(Database *)database delegate:(id)delegate {
1849 if ((self = [super initWithFrame:[view bounds]]) != nil) {
1850 database_ = database;
1851 delegate_ = delegate;
1853 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
1854 [self addSubview:transition_];
1856 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
1858 CGSize navsize = [UINavigationBar defaultSize];
1859 CGRect navrect = {{0, 0}, navsize};
1860 CGRect bounds = [overlay_ bounds];
1862 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
1864 [navbar_ setBarStyle:1];
1865 [navbar_ setDelegate:self];
1867 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:@"Confirm"] autorelease];
1868 [navbar_ pushNavigationItem:navitem];
1869 [navbar_ showButtonsWithLeftTitle:@"Cancel" rightTitle:@"Confirm"];
1871 fields_ = [[NSMutableDictionary dictionaryWithCapacity:16] retain];
1873 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
1874 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
1875 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
1876 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
1877 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
1881 pkgCacheFile &cache([database_ cache]);
1882 NSArray *packages = [database_ packages];
1883 for (size_t i(0), e = [packages count]; i != e; ++i) {
1884 Package *package = [packages objectAtIndex:i];
1885 pkgCache::PkgIterator iterator = [package iterator];
1886 pkgDepCache::StateCache &state(cache[iterator]);
1888 NSString *name([package name]);
1890 if (state.NewInstall())
1891 [installing addObject:name];
1892 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
1893 [reinstalling addObject:name];
1894 else if (state.Upgrade())
1895 [upgrading addObject:name];
1896 else if (state.Downgrade())
1897 [downgrading addObject:name];
1898 else if (state.Delete()) {
1899 if ([package essential])
1901 [removing addObject:name];
1908 essential_ = [[UIAlertSheet alloc]
1909 initWithTitle:@"Unable to Comply"
1910 buttons:[NSArray arrayWithObjects:@"Okay", nil]
1911 defaultButtonIndex:0
1916 [essential_ setBodyText:@"One or more of the packages you are about to remove are marked 'Essential' and cannot be removed by Cydia. Please use apt-get."];
1919 AddTextView(fields_, installing, @"Installing");
1920 AddTextView(fields_, reinstalling, @"Reinstalling");
1921 AddTextView(fields_, upgrading, @"Upgrading");
1922 AddTextView(fields_, downgrading, @"Downgrading");
1923 AddTextView(fields_, removing, @"Removing");
1925 table_ = [[UIPreferencesTable alloc] initWithFrame:CGRectMake(
1926 0, navsize.height, bounds.size.width, bounds.size.height - navsize.height
1929 [table_ setReusesTableCells:YES];
1930 [table_ setDataSource:self];
1931 [table_ reloadData];
1933 [overlay_ addSubview:navbar_];
1934 [overlay_ addSubview:table_];
1936 [view addSubview:self];
1938 [transition_ setDelegate:self];
1940 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
1941 [transition_ transition:0 toView:blank];
1942 [transition_ transition:3 toView:overlay_];
1949 /* Progress Data {{{ */
1950 @interface ProgressData : NSObject {
1956 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
1963 @implementation ProgressData
1965 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
1966 if ((self = [super init]) != nil) {
1967 selector_ = selector;
1987 /* Progress View {{{ */
1988 Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
1990 @interface ProgressView : UIView <
1991 ConfigurationDelegate,
1994 _transient Database *database_;
1996 UIView *background_;
1997 UITransitionView *transition_;
1999 UINavigationBar *navbar_;
2000 UIProgressBar *progress_;
2001 UITextView *output_;
2002 UITextLabel *status_;
2006 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
2008 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
2009 - (void) setContentView:(UIView *)view;
2012 - (void) _retachThread;
2013 - (void) _detachNewThreadData:(ProgressData *)data;
2014 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
2018 @protocol ProgressViewDelegate
2019 - (void) progressViewIsComplete:(ProgressView *)sender;
2022 @implementation ProgressView
2025 [transition_ setDelegate:nil];
2026 [navbar_ setDelegate:nil];
2029 if (background_ != nil)
2030 [background_ release];
2031 [transition_ release];
2034 [progress_ release];
2040 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
2041 if (bootstrap_ && from == overlay_ && to == view_)
2045 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
2046 if ((self = [super initWithFrame:frame]) != nil) {
2047 database_ = database;
2048 delegate_ = delegate;
2050 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
2051 [transition_ setDelegate:self];
2053 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
2056 [overlay_ setBackgroundColor:Black_];
2058 background_ = [[UIView alloc] initWithFrame:[self bounds]];
2059 [background_ setBackgroundColor:Black_];
2060 [self addSubview:background_];
2063 [self addSubview:transition_];
2065 CGSize navsize = [UINavigationBar defaultSize];
2066 CGRect navrect = {{0, 0}, navsize};
2068 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
2069 [overlay_ addSubview:navbar_];
2071 [navbar_ setBarStyle:1];
2072 [navbar_ setDelegate:self];
2074 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
2075 [navbar_ pushNavigationItem:navitem];
2077 CGRect bounds = [overlay_ bounds];
2078 CGSize prgsize = [UIProgressBar defaultSize];
2081 (bounds.size.width - prgsize.width) / 2,
2082 bounds.size.height - prgsize.height - 20
2085 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
2086 [overlay_ addSubview:progress_];
2088 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
2090 bounds.size.height - prgsize.height - 50,
2091 bounds.size.width - 20,
2095 [status_ setColor:White_];
2096 [status_ setBackgroundColor:Clear_];
2098 [status_ setCentersHorizontally:YES];
2099 //[status_ setFont:font];
2101 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
2103 navrect.size.height + 20,
2104 bounds.size.width - 20,
2105 bounds.size.height - navsize.height - 62 - navrect.size.height
2108 //[output_ setTextFont:@"Courier New"];
2109 [output_ setTextSize:12];
2111 [output_ setTextColor:White_];
2112 [output_ setBackgroundColor:Clear_];
2114 [output_ setMarginTop:0];
2115 [output_ setAllowsRubberBanding:YES];
2117 [overlay_ addSubview:output_];
2118 [overlay_ addSubview:status_];
2120 [progress_ setStyle:0];
2124 - (void) setContentView:(UIView *)view {
2125 view_ = [view retain];
2128 - (void) resetView {
2129 [transition_ transition:6 toView:view_];
2132 - (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
2133 NSString *context = [sheet context];
2134 if ([context isEqualToString:@"conffile"]) {
2135 FILE *input = [database_ input];
2139 fprintf(input, "N\n");
2144 fprintf(input, "Y\n");
2148 default: _assert(false);
2155 - (void) _retachThread {
2156 [delegate_ progressViewIsComplete:self];
2160 - (void) _detachNewThreadData:(ProgressData *)data {
2161 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2163 [[data target] performSelector:[data selector] withObject:[data object]];
2166 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
2171 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
2172 UINavigationItem *item = [navbar_ topItem];
2173 [item setTitle:title];
2175 [status_ setText:nil];
2176 [output_ setText:@""];
2177 [progress_ setProgress:0];
2179 [transition_ transition:6 toView:overlay_];
2182 detachNewThreadSelector:@selector(_detachNewThreadData:)
2184 withObject:[[ProgressData alloc]
2185 initWithSelector:selector
2192 - (void) repairWithSelector:(SEL)selector {
2194 detachNewThreadSelector:selector
2197 title:@"Repairing..."
2201 - (void) setConfigurationData:(NSString *)data {
2203 performSelectorOnMainThread:@selector(_setConfigurationData:)
2209 - (void) setProgressError:(NSString *)error {
2211 performSelectorOnMainThread:@selector(_setProgressError:)
2217 - (void) setProgressTitle:(NSString *)title {
2219 performSelectorOnMainThread:@selector(_setProgressTitle:)
2225 - (void) setProgressPercent:(float)percent {
2227 performSelectorOnMainThread:@selector(_setProgressPercent:)
2228 withObject:[NSNumber numberWithFloat:percent]
2233 - (void) addProgressOutput:(NSString *)output {
2235 performSelectorOnMainThread:@selector(_addProgressOutput:)
2241 - (void) _setConfigurationData:(NSString *)data {
2242 _assert(conffile_r(data));
2244 NSString *ofile = conffile_r[1];
2245 //NSString *nfile = conffile_r[2];
2247 UIAlertSheet *sheet = [[[UIAlertSheet alloc]
2248 initWithTitle:@"Configuration Upgrade"
2249 buttons:[NSArray arrayWithObjects:
2250 @"Keep My Old Copy",
2251 @"Accept The New Copy",
2252 // XXX: @"See What Changed",
2254 defaultButtonIndex:0
2259 [sheet setBodyText:[NSString stringWithFormat:
2260 @"The following file has been changed by both the package maintainer and by you (or for you by a script).\n\n%@"
2263 [sheet popupAlertAnimated:YES];
2266 - (void) _setProgressError:(NSString *)error {
2267 UIAlertSheet *sheet = [[[UIAlertSheet alloc]
2268 initWithTitle:@"Package Error"
2269 buttons:[NSArray arrayWithObjects:@"Okay", nil]
2270 defaultButtonIndex:0
2275 [sheet setBodyText:error];
2276 [sheet popupAlertAnimated:YES];
2279 - (void) _setProgressTitle:(NSString *)title {
2280 [status_ setText:[title stringByAppendingString:@"..."]];
2283 - (void) _setProgressPercent:(NSNumber *)percent {
2284 [progress_ setProgress:[percent floatValue]];
2287 - (void) _addProgressOutput:(NSString *)output {
2288 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
2289 CGSize size = [output_ contentSize];
2290 CGRect rect = {{0, size.height}, {size.width, 0}};
2291 [output_ scrollRectToVisible:rect animated:YES];
2297 /* Package Cell {{{ */
2298 @interface PackageCell : UITableCell {
2301 UITextLabel *description_;
2302 UITextLabel *source_;
2303 UIImageView *trusted_;
2306 - (PackageCell *) init;
2307 - (void) setPackage:(Package *)package;
2309 - (void) _setSelected:(float)fraction;
2310 - (void) setSelected:(BOOL)selected;
2311 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade;
2312 - (void) _setSelectionFadeFraction:(float)fraction;
2316 @implementation PackageCell
2321 [description_ release];
2327 - (PackageCell *) init {
2328 if ((self = [super init]) != nil) {
2329 GSFontRef bold = GSFontCreateWithName("Helvetica", kGSFontTraitBold, 20);
2330 GSFontRef large = GSFontCreateWithName("Helvetica", kGSFontTraitNone, 12);
2331 GSFontRef small = GSFontCreateWithName("Helvetica", kGSFontTraitNone, 14);
2333 icon_ = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
2335 name_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 8, 240, 25)];
2336 [name_ setBackgroundColor:Clear_];
2337 [name_ setFont:bold];
2339 source_ = [[UITextLabel alloc] initWithFrame:CGRectMake(58, 28, 225, 20)];
2340 [source_ setBackgroundColor:Clear_];
2341 [source_ setFont:large];
2343 description_ = [[UITextLabel alloc] initWithFrame:CGRectMake(12, 46, 280, 20)];
2344 [description_ setBackgroundColor:Clear_];
2345 [description_ setFont:small];
2347 trusted_ = [[UIImageView alloc] initWithFrame:CGRectMake(30, 30, 16, 16)];
2348 [trusted_ setImage:[UIImage applicationImageNamed:@"trusted.png"]];
2350 [self addSubview:icon_];
2351 [self addSubview:name_];
2352 [self addSubview:description_];
2353 [self addSubview:source_];
2361 - (void) setPackage:(Package *)package {
2362 Source *source = [package source];
2364 UIImage *image = nil;
2365 if (NSString *icon = [package icon])
2366 image = [UIImage imageAtPath:[icon substringFromIndex:6]];
2367 if (image == nil) if (NSString *icon = [source defaultIcon])
2368 image = [UIImage imageAtPath:[icon substringFromIndex:6]];
2370 image = [UIImage applicationImageNamed:@"unknown.png"];
2371 [icon_ setImage:image];
2374 CGSize size = [image size];
2375 float scale = 30 / std::max(size.width, size.height);
2376 [icon_ zoomToScale:scale];
2379 [icon_ setFrame:CGRectMake(10, 10, 30, 30)];
2381 [name_ setText:[package name]];
2382 [description_ setText:[package tagline]];
2384 NSString *label = nil;
2385 bool trusted = false;
2387 if (source != nil) {
2388 label = [source label];
2389 trusted = [source trusted];
2390 } else if ([[package id] isEqualToString:@"firmware"])
2394 label = @"Unknown/Local";
2396 NSString *from = [NSString stringWithFormat:@"from %@", label];
2398 NSString *section = Simplify([package section]);
2399 if (section != nil && ![section isEqualToString:label])
2400 from = [from stringByAppendingString:[NSString stringWithFormat:@" (%@)", section]];
2402 [source_ setText:from];
2405 [self addSubview:trusted_];
2407 [trusted_ removeFromSuperview];
2410 - (void) _setSelected:(float)fraction {
2411 CGColor black(space_,
2412 Interpolate(0.0, 1.0, fraction),
2413 Interpolate(0.0, 1.0, fraction),
2414 Interpolate(0.0, 1.0, fraction),
2417 CGColor gray(space_,
2418 Interpolate(0.4, 1.0, fraction),
2419 Interpolate(0.4, 1.0, fraction),
2420 Interpolate(0.4, 1.0, fraction),
2423 [name_ setColor:black];
2424 [description_ setColor:gray];
2425 [source_ setColor:black];
2428 - (void) setSelected:(BOOL)selected {
2429 [self _setSelected:(selected ? 1.0 : 0.0)];
2430 [super setSelected:selected];
2433 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
2435 [self _setSelected:(selected ? 1.0 : 0.0)];
2436 [super setSelected:selected withFade:fade];
2439 - (void) _setSelectionFadeFraction:(float)fraction {
2440 [self _setSelected:fraction];
2441 [super _setSelectionFadeFraction:fraction];
2446 /* Section Cell {{{ */
2447 @interface SectionCell : UITableCell {
2449 UITextLabel *count_;
2453 - (void) setSection:(Section *)section;
2455 - (void) _setSelected:(float)fraction;
2456 - (void) setSelected:(BOOL)selected;
2457 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade;
2458 - (void) _setSelectionFadeFraction:(float)fraction;
2462 @implementation SectionCell
2471 if ((self = [super init]) != nil) {
2472 GSFontRef bold = GSFontCreateWithName("Helvetica", kGSFontTraitBold, 22);
2473 GSFontRef small = GSFontCreateWithName("Helvetica", kGSFontTraitBold, 12);
2475 name_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 9, 250, 25)];
2476 [name_ setBackgroundColor:Clear_];
2477 [name_ setFont:bold];
2479 count_ = [[UITextLabel alloc] initWithFrame:CGRectMake(11, 7, 29, 32)];
2480 [count_ setCentersHorizontally:YES];
2481 [count_ setBackgroundColor:Clear_];
2482 [count_ setFont:small];
2483 [count_ setColor:White_];
2485 UIImageView *folder = [[[UIImageView alloc] initWithFrame:CGRectMake(8, 7, 32, 32)] autorelease];
2486 [folder setImage:[UIImage applicationImageNamed:@"folder.png"]];
2488 [self addSubview:folder];
2489 [self addSubview:name_];
2490 [self addSubview:count_];
2492 [self _setSelected:0];
2499 - (void) setSection:(Section *)section {
2500 if (section == nil) {
2501 [name_ setText:@"All Packages"];
2502 [count_ setText:nil];
2504 NSString *name = [section name];
2505 [name_ setText:(name == nil ? @"(No Section)" : name)];
2506 [count_ setText:[NSString stringWithFormat:@"%d", [section count]]];
2510 - (void) _setSelected:(float)fraction {
2511 CGColor black(space_,
2512 Interpolate(0.0, 1.0, fraction),
2513 Interpolate(0.0, 1.0, fraction),
2514 Interpolate(0.0, 1.0, fraction),
2517 [name_ setColor:black];
2520 - (void) setSelected:(BOOL)selected {
2521 [self _setSelected:(selected ? 1.0 : 0.0)];
2522 [super setSelected:selected];
2525 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
2527 [self _setSelected:(selected ? 1.0 : 0.0)];
2528 [super setSelected:selected withFade:fade];
2531 - (void) _setSelectionFadeFraction:(float)fraction {
2532 [self _setSelected:fraction];
2533 [super _setSelectionFadeFraction:fraction];
2539 /* File Table {{{ */
2540 @interface FileTable : RVPage {
2541 _transient Database *database_;
2544 NSMutableArray *files_;
2548 - (id) initWithBook:(RVBook *)book database:(Database *)database;
2549 - (void) setPackage:(Package *)package;
2553 @implementation FileTable
2556 if (package_ != nil)
2565 - (int) numberOfRowsInTable:(UITable *)table {
2566 return files_ == nil ? 0 : [files_ count];
2569 - (float) table:(UITable *)table heightForRow:(int)row {
2573 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
2574 if (reusing == nil) {
2575 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
2576 GSFontRef font = GSFontCreateWithName("Helvetica", kGSFontTraitNone, 16);
2577 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
2580 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
2584 - (BOOL) canSelectRow:(int)row {
2588 - (id) initWithBook:(RVBook *)book database:(Database *)database {
2589 if ((self = [super initWithBook:book]) != nil) {
2590 database_ = database;
2592 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
2594 list_ = [[UITable alloc] initWithFrame:[self bounds]];
2595 [self addSubview:list_];
2597 UITableColumn *column = [[[UITableColumn alloc]
2598 initWithTitle:@"Name"
2600 width:[self frame].size.width
2603 [list_ setDataSource:self];
2604 [list_ setSeparatorStyle:1];
2605 [list_ addTableColumn:column];
2606 [list_ setDelegate:self];
2607 [list_ setReusesTableCells:YES];
2611 - (void) setPackage:(Package *)package {
2612 if (package_ != nil) {
2613 [package_ autorelease];
2622 [files_ removeAllObjects];
2624 if (package != nil) {
2625 package_ = [package retain];
2626 name_ = [[package id] retain];
2628 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", name_];
2631 std::ifstream fin([path UTF8String]);
2633 while (std::getline(fin, line))
2634 [files_ addObject:[NSString stringWithUTF8String:line.c_str()]];
2637 if ([files_ count] != 0) {
2638 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
2639 [files_ removeObjectAtIndex:0];
2640 [files_ sortUsingSelector:@selector(compareByPath:)];
2642 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
2643 [stack addObject:@"/"];
2645 for (int i(0), e([files_ count]); i != e; ++i) {
2646 NSString *file = [files_ objectAtIndex:i];
2647 while (![file hasPrefix:[stack lastObject]])
2648 [stack removeLastObject];
2649 NSString *directory = [stack lastObject];
2650 [stack addObject:[file stringByAppendingString:@"/"]];
2651 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
2652 ([stack count] - 2) * 3, "",
2653 [file substringFromIndex:[directory length]]
2662 - (void) resetViewAnimated:(BOOL)animated {
2663 [list_ resetViewAnimated:animated];
2666 - (void) reloadData {
2667 [self setPackage:[database_ packageWithName:name_]];
2668 [self reloadButtons];
2671 - (NSString *) title {
2672 return @"Installed Files";
2675 - (NSString *) backButtonTitle {
2681 /* Package View {{{ */
2682 @protocol PackageViewDelegate
2683 - (void) performPackage:(Package *)package;
2686 @interface PackageView : RVPage {
2687 _transient Database *database_;
2688 UIPreferencesTable *table_;
2691 UITextView *description_;
2692 NSMutableArray *buttons_;
2695 - (id) initWithBook:(RVBook *)book database:(Database *)database;
2696 - (void) setPackage:(Package *)package;
2700 @implementation PackageView
2703 [table_ setDataSource:nil];
2704 [table_ setDelegate:nil];
2706 if (package_ != nil)
2710 if (description_ != nil)
2711 [description_ release];
2717 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
2719 if ([package_ installed] != nil)
2721 if ([package_ source] != nil)
2726 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
2729 else if ([package_ installed] != nil && group-- == 0)
2730 return @"Installed Package";
2731 else if (group-- == 0)
2732 return @"Package Details";
2733 else if ([package_ source] != nil && group-- == 0)
2734 return @"Source Information";
2735 else _assert(false);
2738 - (float) preferencesTable:(UIPreferencesTable *)table heightForRow:(int)row inGroup:(int)group withProposedHeight:(float)proposed {
2739 if (description_ == nil || group != 0 || row != 1)
2742 return [description_ visibleTextRect].size.height + TextViewOffset_;
2745 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
2748 if (description_ != nil)
2750 if ([package_ website] != nil)
2752 if ([package_ author] != nil)
2754 if ([[package_ source] trusted])
2757 } else if ([package_ installed] != nil && group-- == 0)
2759 else if (group-- == 0) {
2761 if ([package_ size] != 0)
2763 if ([package_ maintainer] != nil)
2765 if ([package_ relationships] != nil)
2768 } else if ([package_ source] != nil && group-- == 0) {
2769 Source *source = [package_ source];
2770 NSString *description = [source description];
2772 if (description != nil && ![description isEqualToString:[source label]])
2774 if ([source origin] != nil)
2777 } else _assert(false);
2780 - (UIPreferencesTableCell *) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
2781 UIPreferencesTableCell *cell = [[[UIPreferencesTableCell alloc] init] autorelease];
2782 [cell setShowSelection:NO];
2786 [cell setTitle:[package_ name]];
2787 [cell setValue:[package_ latest]];
2788 } else if (description_ != nil && row-- == 0) {
2789 [cell addSubview:description_];
2790 } else if ([package_ website] != nil && row-- == 0) {
2791 [cell setTitle:@"More Information"];
2792 [cell setShowDisclosure:YES];
2793 [cell setShowSelection:YES];
2794 } else if ([package_ author] != nil && row-- == 0) {
2795 [cell setTitle:@"Author"];
2796 [cell setValue:[[package_ author] name]];
2797 [cell setShowDisclosure:YES];
2798 [cell setShowSelection:YES];
2799 } else if ([[package_ source] trusted] && row-- == 0) {
2800 [cell setIcon:[UIImage applicationImageNamed:@"trusted.png"]];
2801 [cell setValue:@"This package has been signed."];
2802 } else _assert(false);
2803 } else if ([package_ installed] != nil && group-- == 0) {
2805 [cell setTitle:@"Version"];
2806 NSString *installed([package_ installed]);
2807 [cell setValue:(installed == nil ? @"n/a" : installed)];
2808 } else if (row-- == 0) {
2809 [cell setTitle:@"Filesystem Content"];
2810 [cell setShowDisclosure:YES];
2811 [cell setShowSelection:YES];
2812 } else _assert(false);
2813 } else if (group-- == 0) {
2815 [cell setTitle:@"Identifier"];
2816 [cell setValue:[package_ id]];
2817 } else if (row-- == 0) {
2818 [cell setTitle:@"Section"];
2819 NSString *section([package_ section]);
2820 [cell setValue:(section == nil ? @"n/a" : section)];
2821 } else if ([package_ size] != 0 && row-- == 0) {
2822 [cell setTitle:@"Expanded Size"];
2823 [cell setValue:SizeString([package_ size])];
2824 } else if ([package_ maintainer] != nil && row-- == 0) {
2825 [cell setTitle:@"Maintainer"];
2826 [cell setValue:[[package_ maintainer] name]];
2827 [cell setShowDisclosure:YES];
2828 [cell setShowSelection:YES];
2829 } else if ([package_ relationships] != nil && row-- == 0) {
2830 [cell setTitle:@"Package Relationships"];
2831 [cell setShowDisclosure:YES];
2832 [cell setShowSelection:YES];
2833 } else _assert(false);
2834 } else if ([package_ source] != nil && group-- == 0) {
2835 Source *source = [package_ source];
2836 NSString *description = [source description];
2839 NSString *label = [source label];
2841 label = [source uri];
2842 [cell setTitle:label];
2843 [cell setValue:[source version]];
2844 } else if (description != nil && ![description isEqualToString:[source label]] && row-- == 0) {
2845 [cell setValue:description];
2846 } else if ([source origin] != nil && row-- == 0) {
2847 [cell setTitle:@"Origin"];
2848 [cell setValue:[source origin]];
2849 } else _assert(false);
2850 } else _assert(false);
2855 - (BOOL) canSelectRow:(int)row {
2859 // XXX: this is now unmaintainable
2860 - (void) tableRowSelected:(NSNotification *)notification {
2861 int row = [table_ selectedRow];
2862 NSString *website = [package_ website];
2863 Address *author = [package_ author];
2864 BOOL trusted = [[package_ source] trusted];
2865 NSString *installed = [package_ installed];
2866 Address *maintainer = [package_ maintainer];
2868 if (maintainer != nil && row == 7
2869 + (website == nil ? 0 : 1)
2870 + (author == nil ? 0 : 1)
2872 + (installed == nil ? 0 : 3)
2874 [delegate_ openURL:[NSURL URLWithString:[NSString stringWithFormat:@"mailto:%@?subject=%@",
2876 [[NSString stringWithFormat:@"regarding apt package \"%@\"", [package_ name]] stringByAddingPercentEscapes]
2878 } else if (installed && row == 5
2879 + (website == nil ? 0 : 1)
2880 + (author == nil ? 0 : 1)
2883 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
2884 [files setDelegate:delegate_];
2885 [files setPackage:package_];
2886 [book_ pushPage:files];
2887 } else if (author != nil && row == (website == nil ? 3 : 4)) {
2888 [delegate_ openURL:[NSURL URLWithString:[NSString stringWithFormat:@"mailto:%@?subject=%@",
2890 [[NSString stringWithFormat:@"regarding apt package \"%@\"", [package_ name]] stringByAddingPercentEscapes]
2892 } else if (website != nil && row == 3) {
2893 NSURL *url = [NSURL URLWithString:website];
2894 BrowserView *browser = [[[BrowserView alloc] initWithBook:book_ database:database_] autorelease];
2895 [browser setDelegate:delegate_];
2896 [book_ pushPage:browser];
2897 [browser loadURL:url];
2901 - (void) _clickButtonWithName:(NSString *)name {
2902 if ([name isEqualToString:@"Install"])
2903 [delegate_ installPackage:package_];
2904 else if ([name isEqualToString:@"Reinstall"])
2905 [delegate_ installPackage:package_];
2906 else if ([name isEqualToString:@"Remove"])
2907 [delegate_ removePackage:package_];
2908 else if ([name isEqualToString:@"Upgrade"])
2909 [delegate_ installPackage:package_];
2910 else _assert(false);
2913 - (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
2914 int count = [buttons_ count];
2915 _assert(count != 0);
2916 _assert(button <= count + 1);
2918 if (count != button - 1)
2919 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
2924 - (void) _rightButtonClicked {
2925 int count = [buttons_ count];
2926 _assert(count != 0);
2929 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
2931 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
2932 [buttons addObjectsFromArray:buttons_];
2933 [buttons addObject:@"Cancel"];
2935 [delegate_ slideUp:[[[UIAlertSheet alloc]
2938 defaultButtonIndex:2
2945 - (NSString *) rightButtonTitle {
2946 int count = [buttons_ count];
2947 return count == 0 ? nil : count != 1 ? @"Modify" : [buttons_ objectAtIndex:0];
2950 - (NSString *) title {
2954 - (id) initWithBook:(RVBook *)book database:(Database *)database {
2955 if ((self = [super initWithBook:book]) != nil) {
2956 database_ = database;
2958 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
2959 [self addSubview:table_];
2961 [table_ setDataSource:self];
2962 [table_ setDelegate:self];
2964 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
2968 - (void) setPackage:(Package *)package {
2969 if (package_ != nil) {
2970 [package_ autorelease];
2979 if (description_ != nil) {
2980 [description_ release];
2984 [buttons_ removeAllObjects];
2986 if (package != nil) {
2987 package_ = [package retain];
2988 name_ = [[package id] retain];
2990 NSString *description([package description]);
2991 if (description == nil)
2992 description = [package tagline];
2993 if (description != nil) {
2994 description_ = [GetTextView(description, 12, true) retain];
2995 [description_ setTextColor:Black_];
2998 [table_ reloadData];
3000 if ([package_ source] == nil);
3001 else if ([package_ installed] == nil)
3002 [buttons_ addObject:@"Install"];
3003 else if ([package_ upgradable])
3004 [buttons_ addObject:@"Upgrade"];
3006 [buttons_ addObject:@"Reinstall"];
3007 if ([package_ installed] != nil)
3008 [buttons_ addObject:@"Remove"];
3012 - (void) resetViewAnimated:(BOOL)animated {
3013 [table_ resetViewAnimated:animated];
3016 - (void) reloadData {
3017 [self setPackage:[database_ packageWithName:name_]];
3018 [self reloadButtons];
3023 /* Package Table {{{ */
3024 @interface PackageTable : RVPage {
3025 _transient Database *database_;
3029 NSMutableArray *packages_;
3030 NSMutableArray *sections_;
3031 UISectionList *list_;
3034 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
3036 - (void) setDelegate:(id)delegate;
3037 - (void) setObject:(id)object;
3039 - (void) reloadData;
3040 - (void) resetCursor;
3042 - (UISectionList *) list;
3044 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
3048 @implementation PackageTable
3051 [list_ setDataSource:nil];
3056 [packages_ release];
3057 [sections_ release];
3062 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
3063 return [sections_ count];
3066 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
3067 return [[sections_ objectAtIndex:section] name];
3070 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
3071 return [[sections_ objectAtIndex:section] row];
3074 - (int) numberOfRowsInTable:(UITable *)table {
3075 return [packages_ count];
3078 - (float) table:(UITable *)table heightForRow:(int)row {
3082 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
3084 reusing = [[[PackageCell alloc] init] autorelease];
3085 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
3089 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
3093 - (void) tableRowSelected:(NSNotification *)notification {
3094 int row = [[notification object] selectedRow];
3098 Package *package = [packages_ objectAtIndex:row];
3099 PackageView *view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
3100 [view setDelegate:delegate_];
3101 [view setPackage:package];
3102 [book_ pushPage:view];
3105 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
3106 if ((self = [super initWithBook:book]) != nil) {
3107 database_ = database;
3108 title_ = [title retain];
3110 object_ = object == nil ? nil : [object retain];
3112 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
3113 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
3115 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
3116 [list_ setDataSource:self];
3118 UITableColumn *column = [[[UITableColumn alloc]
3119 initWithTitle:@"Name"
3121 width:[self frame].size.width
3124 UITable *table = [list_ table];
3125 [table setSeparatorStyle:1];
3126 [table addTableColumn:column];
3127 [table setDelegate:self];
3128 [table setReusesTableCells:YES];
3130 [self addSubview:list_];
3135 - (void) setDelegate:(id)delegate {
3136 delegate_ = delegate;
3139 - (void) setObject:(id)object {
3145 object_ = [object retain];
3148 - (void) reloadData {
3149 NSArray *packages = [database_ packages];
3151 [packages_ removeAllObjects];
3152 [sections_ removeAllObjects];
3154 for (size_t i(0); i != [packages count]; ++i) {
3155 Package *package([packages objectAtIndex:i]);
3156 if ([[package performSelector:filter_ withObject:object_] boolValue])
3157 [packages_ addObject:package];
3160 Section *section = nil;
3162 for (size_t offset(0); offset != [packages_ count]; ++offset) {
3163 Package *package = [packages_ objectAtIndex:offset];
3164 NSString *name = [package index];
3166 if (section == nil || ![[section name] isEqualToString:name]) {
3167 section = [[[Section alloc] initWithName:name row:offset] autorelease];
3168 [sections_ addObject:section];
3171 [section addToCount];
3177 - (NSString *) title {
3181 - (void) resetViewAnimated:(BOOL)animated {
3182 [list_ resetViewAnimated:animated];
3185 - (void) resetCursor {
3186 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
3189 - (UISectionList *) list {
3193 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
3194 [list_ setShouldHideHeaderInShortLists:hide];
3200 /* Browser Implementation {{{ */
3201 @implementation BrowserView
3204 WebView *webview = [webview_ webView];
3205 [webview setFrameLoadDelegate:nil];
3206 [webview setResourceLoadDelegate:nil];
3207 [webview setUIDelegate:nil];
3209 [scroller_ setDelegate:nil];
3210 [webview_ setDelegate:nil];
3212 [scroller_ release];
3215 [indicator_ release];
3221 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
3222 NSMutableURLRequest *request = [NSMutableURLRequest
3225 timeoutInterval:30.0
3228 [request addValue:[NSString stringWithUTF8String:Firmware_] forHTTPHeaderField:@"X-Firmware"];
3229 [request addValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3230 [request addValue:[NSString stringWithUTF8String:SerialNumber_] forHTTPHeaderField:@"X-Serial-Number"];
3232 [self loadRequest:request];
3236 - (void) loadURL:(NSURL *)url {
3237 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
3240 // XXX: this needs to add the headers
3241 - (NSURLRequest *) _addHeadersToRequest:(NSURLRequest *)request {
3245 - (void) loadRequest:(NSURLRequest *)request {
3246 [webview_ loadRequest:request];
3249 - (void) reloadURL {
3250 NSURL *url = [[[urls_ lastObject] retain] autorelease];
3251 [urls_ removeLastObject];
3252 [self loadURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData];
3255 - (WebView *) webView {
3256 return [webview_ webView];
3259 - (void) view:(UIView *)sender didSetFrame:(CGRect)frame {
3260 [scroller_ setContentSize:frame.size];
3263 - (void) view:(UIView *)sender didSetFrame:(CGRect)frame oldFrame:(CGRect)old {
3264 [self view:sender didSetFrame:frame];
3267 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)dataSource {
3268 return [self _addHeadersToRequest:request];
3271 - (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request {
3272 if ([[[request URL] scheme] isEqualToString:@"apptapp"])
3274 [self setBackButtonTitle:title_];
3275 BrowserView *browser = [[[BrowserView alloc] initWithBook:book_ database:database_] autorelease];
3276 [browser setDelegate:delegate_];
3277 [book_ pushPage:browser];
3278 [browser loadRequest:[self _addHeadersToRequest:request]];
3279 return [browser webView];
3282 - (void) webView:(WebView *)sender willClickElement:(id)element {
3283 if (![element respondsToSelector:@selector(href)])
3285 NSString *href = [element href];
3288 if ([href hasPrefix:@"apptapp://package/"]) {
3289 NSString *name = [href substringFromIndex:18];
3290 Package *package = [database_ packageWithName:name];
3291 if (package == nil) {
3292 UIAlertSheet *sheet = [[[UIAlertSheet alloc]
3293 initWithTitle:@"Cannot Locate Package"
3294 buttons:[NSArray arrayWithObjects:@"Close", nil]
3295 defaultButtonIndex:0
3300 [sheet setBodyText:[NSString stringWithFormat:
3301 @"The package %@ cannot be found in your current sources. I might recommend installing more sources."
3304 [sheet popupAlertAnimated:YES];
3306 [self setBackButtonTitle:title_];
3307 PackageView *view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
3308 [view setDelegate:delegate_];
3309 [view setPackage:package];
3310 [book_ pushPage:view];
3315 - (void) webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
3316 title_ = [title retain];
3317 [self setTitle:title];
3320 - (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
3321 if ([frame parentFrame] != nil)
3326 [indicator_ startAnimation];
3327 [self reloadButtons];
3329 if (title_ != nil) {
3334 [self setTitle:@"Loading..."];
3336 WebView *webview = [webview_ webView];
3337 NSString *href = [webview mainFrameURL];
3338 [urls_ addObject:[NSURL URLWithString:href]];
3340 CGRect webrect = [scroller_ frame];
3341 webrect.size.height = 0;
3342 [webview_ setFrame:webrect];
3345 - (void) _finishLoading {
3348 [indicator_ stopAnimation];
3349 [self reloadButtons];
3353 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
3354 if ([frame parentFrame] != nil)
3356 [self _finishLoading];
3359 - (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
3360 if ([frame parentFrame] != nil)
3362 [self setTitle:[error localizedDescription]];
3363 [self _finishLoading];
3366 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3367 if ((self = [super initWithBook:book]) != nil) {
3368 database_ = database;
3371 struct CGRect bounds = [self bounds];
3373 UIImageView *pinstripe = [[[UIImageView alloc] initWithFrame:bounds] autorelease];
3374 [pinstripe setImage:[UIImage applicationImageNamed:@"pinstripe.png"]];
3375 [self addSubview:pinstripe];
3377 scroller_ = [[UIScroller alloc] initWithFrame:bounds];
3378 [self addSubview:scroller_];
3380 [scroller_ setScrollingEnabled:YES];
3381 [scroller_ setAdjustForContentSizeChange:YES];
3382 [scroller_ setClipsSubviews:YES];
3383 [scroller_ setAllowsRubberBanding:YES];
3384 [scroller_ setScrollDecelerationFactor:0.99];
3385 [scroller_ setDelegate:self];
3387 CGRect webrect = [scroller_ bounds];
3388 webrect.size.height = 0;
3390 webview_ = [[UIWebView alloc] initWithFrame:webrect];
3391 [scroller_ addSubview:webview_];
3393 [webview_ setTilingEnabled:YES];
3394 [webview_ setTileSize:CGSizeMake(webrect.size.width, 500)];
3395 [webview_ setAutoresizes:YES];
3396 [webview_ setDelegate:self];
3397 //[webview_ setEnabledGestures:2];
3399 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:0];
3400 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(281, 42, indsize.width, indsize.height)];
3401 [indicator_ setStyle:0];
3403 Package *package([database_ packageWithName:@"cydia"]);
3404 NSString *application = package == nil ? @"Cydia" : [NSString
3405 stringWithFormat:@"Cydia/%@",
3409 WebView *webview = [webview_ webView];
3410 [webview setApplicationNameForUserAgent:application];
3411 [webview setFrameLoadDelegate:self];
3412 [webview setResourceLoadDelegate:self];
3413 [webview setUIDelegate:self];
3415 urls_ = [[NSMutableArray alloc] initWithCapacity:16];
3419 - (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
3423 - (void) _leftButtonClicked {
3424 UIAlertSheet *sheet = [[[UIAlertSheet alloc]
3425 initWithTitle:@"About Cydia Packager"
3426 buttons:[NSArray arrayWithObjects:@"Close", nil]
3427 defaultButtonIndex:0
3433 @"Copyright (C) 2008\n"
3434 "Jay Freeman (saurik)\n"
3435 "saurik@saurik.com\n"
3436 "http://www.saurik.com/\n"
3439 "http://www.theokorigroup.com/\n"
3441 "College of Creative Studies,\n"
3442 "University of California,\n"
3444 "http://www.ccs.ucsb.edu/"
3447 [sheet popupAlertAnimated:YES];
3450 - (void) _rightButtonClicked {
3455 - (NSString *) leftButtonTitle {
3459 - (NSString *) rightButtonTitle {
3460 return loading_ ? @"" : @"Reload";
3463 - (NSString *) title {
3467 - (NSString *) backButtonTitle {
3471 - (void) setPageActive:(BOOL)active {
3473 [book_ addSubview:indicator_];
3475 [indicator_ removeFromSuperview];
3478 - (void) resetViewAnimated:(BOOL)animated {
3484 @interface CYBook : RVBook <
3487 _transient Database *database_;
3489 UIProgressIndicator *indicator_;
3490 UITextLabel *prompt_;
3491 UIProgressBar *progress_;
3495 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
3501 /* Install View {{{ */
3502 @interface InstallView : RVPage {
3503 _transient Database *database_;
3504 NSMutableArray *packages_;
3505 NSMutableArray *sections_;
3510 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3511 - (void) reloadData;
3515 @implementation InstallView
3518 [list_ setDataSource:nil];
3519 [list_ setDelegate:nil];
3521 [packages_ release];
3522 [sections_ release];
3524 [accessory_ release];
3528 - (int) numberOfRowsInTable:(UITable *)table {
3529 return [sections_ count] + 1;
3532 - (float) table:(UITable *)table heightForRow:(int)row {
3536 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
3538 reusing = [[[SectionCell alloc] init] autorelease];
3539 [(SectionCell *)reusing setSection:(row == 0 ? nil : [sections_ objectAtIndex:(row - 1)])];
3543 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
3547 - (void) tableRowSelected:(NSNotification *)notification {
3548 int row = [[notification object] selectedRow];
3559 title = @"All Packages";
3561 section = [sections_ objectAtIndex:(row - 1)];
3562 name = [section name];
3568 title = @"(No Section)";
3572 PackageTable *table = [[[PackageTable alloc]
3576 filter:@selector(isUninstalledInSection:)
3580 [table setDelegate:delegate_];
3582 [book_ pushPage:table];
3585 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3586 if ((self = [super initWithBook:book]) != nil) {
3587 database_ = database;
3589 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
3590 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
3592 list_ = [[UITable alloc] initWithFrame:[self bounds]];
3593 [self addSubview:list_];
3595 UITableColumn *column = [[[UITableColumn alloc]
3596 initWithTitle:@"Name"
3598 width:[self frame].size.width
3601 [list_ setDataSource:self];
3602 [list_ setSeparatorStyle:1];
3603 [list_ addTableColumn:column];
3604 [list_ setDelegate:self];
3605 [list_ setReusesTableCells:YES];
3611 - (void) reloadData {
3612 NSArray *packages = [database_ packages];
3614 [packages_ removeAllObjects];
3615 [sections_ removeAllObjects];
3617 for (size_t i(0); i != [packages count]; ++i) {
3618 Package *package([packages objectAtIndex:i]);
3619 if ([package valid] && [package installed] == nil)
3620 [packages_ addObject:package];
3623 [packages_ sortUsingSelector:@selector(compareBySection:)];
3625 Section *section = nil;
3626 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
3627 Package *package = [packages_ objectAtIndex:offset];
3628 NSString *name = [package section];
3630 if (section == nil || name != nil && ![[section name] isEqualToString:name]) {
3631 section = [[[Section alloc] initWithName:name row:offset] autorelease];
3632 [sections_ addObject:section];
3635 [section addToCount];
3641 - (void) resetViewAnimated:(BOOL)animated {
3642 [list_ resetViewAnimated:animated];
3645 - (NSString *) title {
3649 - (NSString *) backButtonTitle {
3653 - (UIView *) accessoryView {
3659 /* Changes View {{{ */
3660 @interface ChangesView : RVPage {
3661 _transient Database *database_;
3662 NSMutableArray *packages_;
3663 NSMutableArray *sections_;
3664 UISectionList *list_;
3668 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3669 - (void) reloadData;
3673 @implementation ChangesView
3676 [[list_ table] setDelegate:nil];
3677 [list_ setDataSource:nil];
3679 [packages_ release];
3680 [sections_ release];
3685 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
3686 return [sections_ count];
3689 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
3690 return [[sections_ objectAtIndex:section] name];
3693 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
3694 return [[sections_ objectAtIndex:section] row];
3697 - (int) numberOfRowsInTable:(UITable *)table {
3698 return [packages_ count];
3701 - (float) table:(UITable *)table heightForRow:(int)row {
3705 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
3707 reusing = [[[PackageCell alloc] init] autorelease];
3708 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
3712 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
3716 - (void) tableRowSelected:(NSNotification *)notification {
3717 int row = [[notification object] selectedRow];
3720 Package *package = [packages_ objectAtIndex:row];
3721 PackageView *view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
3722 [view setDelegate:delegate_];
3723 [view setPackage:package];
3724 [book_ pushPage:view];
3727 - (void) _leftButtonClicked {
3728 [(CYBook *)book_ update];
3729 [self reloadButtons];
3732 - (void) _rightButtonClicked {
3733 [delegate_ distUpgrade];
3736 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3737 if ((self = [super initWithBook:book]) != nil) {
3738 database_ = database;
3740 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
3741 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
3743 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
3744 [self addSubview:list_];
3746 [list_ setShouldHideHeaderInShortLists:NO];
3747 [list_ setDataSource:self];
3748 //[list_ setSectionListStyle:1];
3750 UITableColumn *column = [[[UITableColumn alloc]
3751 initWithTitle:@"Name"
3753 width:[self frame].size.width
3756 UITable *table = [list_ table];
3757 [table setSeparatorStyle:1];
3758 [table addTableColumn:column];
3759 [table setDelegate:self];
3760 [table setReusesTableCells:YES];
3766 - (void) reloadData {
3767 NSArray *packages = [database_ packages];
3769 [packages_ removeAllObjects];
3770 [sections_ removeAllObjects];
3772 for (size_t i(0); i != [packages count]; ++i) {
3773 Package *package([packages objectAtIndex:i]);
3774 if ([package installed] == nil && [package valid] || [package upgradable])
3775 [packages_ addObject:package];
3778 [packages_ sortUsingSelector:@selector(compareForChanges:)];
3780 Section *upgradable = [[[Section alloc] initWithName:@"Available Upgrades" row:0] autorelease];
3781 Section *section = nil;
3784 bool unseens = false;
3786 CFLocaleRef locale = CFLocaleCopyCurrent();
3787 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, locale, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
3789 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
3790 Package *package = [packages_ objectAtIndex:offset];
3792 if ([package upgradable]) {
3794 [upgradable addToCount];
3797 NSDate *seen = [package seen];
3802 name = [@"n/a ?" retain];
3804 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
3807 if (section == nil || ![[section name] isEqualToString:name]) {
3808 section = [[[Section alloc] initWithName:name row:offset] autorelease];
3809 [sections_ addObject:section];
3813 [section addToCount];
3817 CFRelease(formatter);
3821 Section *last = [sections_ lastObject];
3822 size_t count = [last count];
3823 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
3824 [sections_ removeLastObject];
3828 [sections_ insertObject:upgradable atIndex:0];
3831 [self reloadButtons];
3834 - (void) resetViewAnimated:(BOOL)animated {
3835 [list_ resetViewAnimated:animated];
3838 - (NSString *) leftButtonTitle {
3839 return [(CYBook *)book_ updating] ? nil : @"Refresh";
3842 - (NSString *) rightButtonTitle {
3843 return upgrades_ == 0 ? nil : [NSString stringWithFormat:@"Upgrade All (%u)", upgrades_];
3846 - (NSString *) title {
3852 /* Manage View {{{ */
3853 @interface ManageView : PackageTable {
3856 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3860 @implementation ManageView
3862 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3867 filter:@selector(isInstalledInSection:)
3873 - (NSString *) title {
3874 return @"Installed Packages";
3877 - (NSString *) backButtonTitle {
3878 return @"All Packages";
3883 /* Search View {{{ */
3884 @protocol SearchViewDelegate
3885 - (void) showKeyboard:(BOOL)show;
3888 @interface SearchView : RVPage {
3890 UISearchField *field_;
3891 UITransitionView *transition_;
3892 PackageTable *table_;
3893 UIPreferencesTable *advanced_;
3899 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3900 - (void) reloadData;
3904 @implementation SearchView
3908 [[field_ textTraits] setEditingDelegate:nil];
3910 [field_ setDelegate:nil];
3912 [accessory_ release];
3914 [transition_ release];
3916 [advanced_ release];
3921 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
3925 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
3927 case 0: return @"Advanced Search (Coming Soon!)";
3929 default: _assert(false);
3933 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
3937 default: _assert(false);
3941 - (void) _showKeyboard:(BOOL)show {
3942 CGSize keysize = [UIKeyboard defaultSize];
3943 CGRect keydown = [book_ pageBounds];
3944 CGRect keyup = keydown;
3945 keyup.size.height -= keysize.height - ButtonBarHeight_;
3947 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
3949 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
3950 [animation setSignificantRectFields:8];
3953 [animation setStartFrame:keydown];
3954 [animation setEndFrame:keyup];
3956 [animation setStartFrame:keyup];
3957 [animation setEndFrame:keydown];
3960 UIAnimator *animator = [UIAnimator sharedAnimator];
3963 addAnimations:[NSArray arrayWithObjects:animation, nil]
3964 withDuration:(KeyboardTime_ - delay)
3969 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
3971 [delegate_ showKeyboard:show];
3974 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
3975 [self _showKeyboard:YES];
3978 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
3979 [self _showKeyboard:NO];
3982 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
3984 NSString *text([field_ text]);
3985 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
3991 - (void) textFieldClearButtonPressed:(UITextField *)field {
3995 - (void) keyboardInputShouldDelete:(id)input {
3999 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
4000 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
4004 [field_ resignFirstResponder];
4009 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4010 if ((self = [super initWithBook:book]) != nil) {
4011 CGRect pageBounds = [book_ pageBounds];
4013 /*UIImageView *pinstripe = [[[UIImageView alloc] initWithFrame:pageBounds] autorelease];
4014 [pinstripe setImage:[UIImage applicationImageNamed:@"pinstripe.png"]];
4015 [self addSubview:pinstripe];*/
4017 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
4018 [self addSubview:transition_];
4020 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
4022 [advanced_ setReusesTableCells:YES];
4023 [advanced_ setDataSource:self];
4024 [advanced_ reloadData];
4026 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
4027 CGColor dimmed(space_, 0, 0, 0, 0.5);
4028 [dimmed_ setBackgroundColor:dimmed];
4030 table_ = [[PackageTable alloc]
4034 filter:@selector(isSearchedForBy:)
4038 [table_ setShouldHideHeaderInShortLists:NO];
4039 [transition_ transition:0 toView:table_];
4041 CGRect cnfrect = {{1, 38}, {17, 18}};
4044 area.origin.x = cnfrect.size.width + 15;
4046 area.size.width = [self bounds].size.width - area.origin.x - 18;
4047 area.size.height = [UISearchField defaultHeight];
4049 field_ = [[UISearchField alloc] initWithFrame:area];
4051 GSFontRef font = GSFontCreateWithName("Helvetica", kGSFontTraitNone, 16);
4052 [field_ setFont:font];
4055 [field_ setPlaceholder:@"Package Names & Descriptions"];
4056 [field_ setPaddingTop:5];
4057 [field_ setDelegate:self];
4060 UITextTraits *traits = [field_ textTraits];
4061 [traits setEditingDelegate:self];
4062 [traits setReturnKeyType:6];
4063 [traits setAutoCapsType:0];
4064 [traits setAutoCorrectionType:1];
4067 UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
4068 [configure setShowPressFeedback:YES];
4069 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
4070 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
4072 accessory_ = [[UIView alloc] initWithFrame:CGRectMake(0, 6, cnfrect.size.width + area.size.width + 6 * 3, area.size.height + 30)];
4073 [accessory_ addSubview:field_];
4074 [accessory_ addSubview:configure];
4079 LKAnimation *animation = [LKTransition animation];
4080 [animation setType:@"oglFlip"];
4081 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
4082 [animation setFillMode:@"extended"];
4083 [animation setTransitionFlags:3];
4084 [animation setDuration:10];
4085 [animation setSpeed:0.35];
4086 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
4087 [[transition_ _layer] addAnimation:animation forKey:0];
4088 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
4089 flipped_ = !flipped_;
4092 - (void) configurePushed {
4093 [field_ resignFirstResponder];
4097 - (void) resetViewAnimated:(BOOL)animated {
4100 [table_ resetViewAnimated:animated];
4103 - (void) reloadData {
4106 [table_ setObject:[field_ text]];
4107 [table_ reloadData];
4108 [table_ resetCursor];
4111 - (UIView *) accessoryView {
4115 - (NSString *) title {
4119 - (NSString *) backButtonTitle {
4123 - (void) setDelegate:(id)delegate {
4124 [table_ setDelegate:delegate];
4125 [super setDelegate:delegate];
4131 @implementation CYBook
4135 [indicator_ release];
4137 [progress_ release];
4141 - (NSString *) getTitleForPage:(RVPage *)page {
4142 return Simplify([super getTitleForPage:page]);
4150 [navbar_ setPrompt:@""];
4151 [navbar_ addSubview:overlay_];
4152 [indicator_ startAnimation];
4153 [prompt_ setText:@"Updating Database..."];
4154 [progress_ setProgress:0];
4159 detachNewThreadSelector:@selector(_update)
4168 [overlay_ removeFromSuperview];
4169 [indicator_ stopAnimation];
4170 [delegate_ reloadData];
4172 [self setPrompt:[NSString stringWithFormat:@"Last Updated: %@", GetLastUpdate()]];
4175 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
4176 if ((self = [super initWithFrame:frame]) != nil) {
4177 database_ = database;
4180 [navbar_ setBarStyle:1];
4182 CGRect ovrrect = [navbar_ bounds];
4183 ovrrect.size.height = [UINavigationBar defaultSizeWithPrompt].height - [UINavigationBar defaultSize].height;
4185 overlay_ = [[UIView alloc] initWithFrame:ovrrect];
4187 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:2];
4188 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
4189 CGRect indrect = {{indoffset, indoffset}, indsize};
4191 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
4192 [indicator_ setStyle:(Advanced_ ? 2 : 3)];
4193 [overlay_ addSubview:indicator_];
4195 CGSize prmsize = {200, indsize.width};
4198 indoffset * 2 + indsize.width,
4199 (ovrrect.size.height - prmsize.height) / 2
4202 GSFontRef font = GSFontCreateWithName("Helvetica", kGSFontTraitNone, 12);
4204 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
4206 [prompt_ setColor:(Advanced_ ? White_ : Blueish_)];
4207 [prompt_ setBackgroundColor:Clear_];
4208 [prompt_ setFont:font];
4212 [overlay_ addSubview:prompt_];
4214 CGSize prgsize = {75, 100};
4217 ovrrect.size.width - prgsize.width - 10,
4218 (ovrrect.size.height - prgsize.height) / 2
4221 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
4222 [progress_ setStyle:0];
4223 [overlay_ addSubview:progress_];
4228 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4231 status.setDelegate(self);
4233 [database_ updateWithStatus:status];
4236 performSelectorOnMainThread:@selector(_update_)
4244 - (void) setProgressError:(NSString *)error {
4246 performSelectorOnMainThread:@selector(_setProgressError:)
4252 - (void) setProgressTitle:(NSString *)title {
4254 performSelectorOnMainThread:@selector(_setProgressTitle:)
4260 - (void) setProgressPercent:(float)percent {
4263 - (void) addProgressOutput:(NSString *)output {
4265 performSelectorOnMainThread:@selector(_addProgressOutput:)
4271 - (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
4275 - (void) _setProgressError:(NSString *)error {
4276 [prompt_ setText:[NSString stringWithFormat:@"Error: %@", error]];
4279 - (void) _setProgressTitle:(NSString *)title {
4280 [prompt_ setText:[title stringByAppendingString:@"..."]];
4283 - (void) _addProgressOutput:(NSString *)output {
4288 @interface Cydia : UIApplication <
4289 ConfirmationViewDelegate,
4290 ProgressViewDelegate,
4299 UIButtonBar *buttonbar_;
4301 ConfirmationView *confirm_;
4302 NSMutableArray *essential_;
4304 Database *database_;
4305 ProgressView *progress_;
4309 UIKeyboard *keyboard_;
4311 InstallView *install_;
4312 ChangesView *changes_;
4313 ManageView *manage_;
4314 SearchView *search_;
4319 @implementation Cydia
4321 - (void) _reloadData {
4322 /*UIProgressHUD *hud = [[UIProgressHUD alloc] initWithWindow:window_];
4323 [hud setText:@"Reloading Data"];
4324 [overlay_ addSubview:hud];
4327 [database_ reloadData];
4329 if (Packages_ == nil) {
4330 Packages_ = [[NSMutableDictionary alloc] initWithCapacity:128];
4331 [Metadata_ setObject:Packages_ forKey:@"Packages"];
4335 [essential_ removeAllObjects];
4337 NSArray *packages = [database_ packages];
4338 for (int i(0), e([packages count]); i != e; ++i) {
4339 Package *package = [packages objectAtIndex:i];
4340 if ([package upgradable]) {
4341 if ([package essential])
4342 [essential_ addObject:package];
4348 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
4349 [buttonbar_ setBadgeValue:badge forButton:3];
4350 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
4351 [buttonbar_ setBadgeAnimated:YES forButton:3];
4352 [self setApplicationBadge:badge];
4354 [buttonbar_ setBadgeValue:nil forButton:3];
4355 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
4356 [buttonbar_ setBadgeAnimated:NO forButton:3];
4357 [self removeApplicationBadge];
4361 _assert([Metadata_ writeToFile:@"/var/lib/cydia/metadata.plist" atomically:YES] == YES);
4365 /* XXX: this is just stupid */
4367 [install_ reloadData];
4369 [changes_ reloadData];
4371 [manage_ reloadData];
4373 [search_ reloadData];
4377 if ([packages count] == 0);
4378 else if (!Loaded_) {
4381 } else if (!Ignored_ && [essential_ count] != 0) {
4382 int count = [essential_ count];
4384 UIAlertSheet *sheet = [[[UIAlertSheet alloc]
4385 initWithTitle:[NSString stringWithFormat:@"%d Essential Upgrade%@", count, (count == 1 ? @"" : @"s")]
4386 buttons:[NSArray arrayWithObjects:@"Upgrade Essential", @"Ignore (Temporary)", nil]
4387 defaultButtonIndex:0
4392 [sheet setBodyText:@"One or more essential packages are currently out of date. If these packages are not upgraded you are likely to encounter errors."];
4393 [sheet popupAlertAnimated:YES];
4397 [hud removeFromSuperview];*/
4400 - (void) reloadData {
4401 @synchronized (self) {
4402 if (confirm_ == nil)
4408 pkgProblemResolver *resolver = [database_ resolver];
4410 resolver->InstallProtect();
4411 if (!resolver->Resolve(true))
4416 [database_ prepare];
4418 if ([database_ cache]->BrokenCount() == 0)
4419 confirm_ = [[ConfirmationView alloc] initWithView:underlay_ database:database_ delegate:self];
4421 NSMutableArray *broken = [NSMutableArray arrayWithCapacity:16];
4422 NSArray *packages = [database_ packages];
4424 for (size_t i(0); i != [packages count]; ++i) {
4425 Package *package = [packages objectAtIndex:i];
4426 if ([package broken])
4427 [broken addObject:[package name]];
4430 UIAlertSheet *sheet = [[[UIAlertSheet alloc]
4431 initWithTitle:[NSString stringWithFormat:@"%d Broken Packages", [database_ cache]->BrokenCount()]
4432 buttons:[NSArray arrayWithObjects:@"Okay", nil]
4433 defaultButtonIndex:0
4438 [sheet setBodyText:[NSString stringWithFormat:@"The following packages have unmet dependencies:\n\n%@", [broken componentsJoinedByString:@"\n"]]];
4439 [sheet popupAlertAnimated:YES];
4445 - (void) installPackage:(Package *)package {
4446 @synchronized (self) {
4453 - (void) removePackage:(Package *)package {
4454 @synchronized (self) {
4461 - (void) distUpgrade {
4462 @synchronized (self) {
4463 [database_ upgrade];
4469 @synchronized (self) {
4477 [overlay_ removeFromSuperview];
4481 detachNewThreadSelector:@selector(perform)
4488 - (void) bootstrap_ {
4490 [database_ upgrade];
4491 [database_ prepare];
4492 [database_ perform];
4495 - (void) bootstrap {
4497 detachNewThreadSelector:@selector(bootstrap_)
4500 title:@"Bootstrap Install..."
4504 - (void) progressViewIsComplete:(ProgressView *)progress {
4505 @synchronized (self) {
4508 if (confirm_ != nil) {
4509 [underlay_ addSubview:overlay_];
4510 [confirm_ removeFromSuperview];
4517 - (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
4518 NSString *context = [sheet context];
4519 if ([context isEqualToString:@"upgrade"])
4522 @synchronized (self) {
4523 for (int i = 0, e = [essential_ count]; i != e; ++i) {
4524 Package *essential = [essential_ objectAtIndex:i];
4525 [essential install];
4537 default: _assert(false);
4543 - (void) setPage:(RVPage *)page {
4544 [page resetViewAnimated:NO];
4545 [page setDelegate:self];
4546 [book_ setPage:page];
4549 - (RVPage *) _setHomePage {
4550 BrowserView *browser = [[[BrowserView alloc] initWithBook:book_ database:database_] autorelease];
4551 [self setPage:browser];
4552 [browser loadURL:[NSURL URLWithString:@"http://cydia.saurik.com/"]];
4556 - (void) buttonBarItemTapped:(id)sender {
4557 unsigned tag = [sender tag];
4559 [book_ resetViewAnimated:YES];
4564 case 1: [self _setHomePage]; break;
4566 case 2: [self setPage:install_]; break;
4567 case 3: [self setPage:changes_]; break;
4568 case 4: [self setPage:manage_]; break;
4569 case 5: [self setPage:search_]; break;
4571 default: _assert(false);
4577 - (void) applicationWillSuspend {
4578 [super applicationWillSuspend];
4583 pid_t pid = ExecFork();
4586 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
4592 - (void) applicationDidFinishLaunching:(id)unused {
4593 _assert(pkgInitConfig(*_config));
4594 _assert(pkgInitSystem(*_config, _system));
4599 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
4601 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
4602 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
4604 [window_ orderFront: self];
4605 [window_ makeKey: self];
4606 [window_ _setHidden: NO];
4608 database_ = [[Database alloc] init];
4609 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
4610 [database_ setDelegate:progress_];
4611 [window_ setContentView:progress_];
4613 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
4614 [progress_ setContentView:underlay_];
4616 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
4619 [underlay_ addSubview:overlay_];
4621 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
4622 0, 0, screenrect.size.width, screenrect.size.height - 48
4623 ) database:database_];
4625 [book_ setDelegate:self];
4627 [overlay_ addSubview:book_];
4629 NSArray *buttonitems = [NSArray arrayWithObjects:
4630 [NSDictionary dictionaryWithObjectsAndKeys:
4631 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
4632 @"home-up.png", kUIButtonBarButtonInfo,
4633 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
4634 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
4635 self, kUIButtonBarButtonTarget,
4636 @"Home", kUIButtonBarButtonTitle,
4637 @"0", kUIButtonBarButtonType,
4640 [NSDictionary dictionaryWithObjectsAndKeys:
4641 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
4642 @"install-up.png", kUIButtonBarButtonInfo,
4643 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
4644 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
4645 self, kUIButtonBarButtonTarget,
4646 @"Install", kUIButtonBarButtonTitle,
4647 @"0", kUIButtonBarButtonType,
4650 [NSDictionary dictionaryWithObjectsAndKeys:
4651 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
4652 @"changes-up.png", kUIButtonBarButtonInfo,
4653 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
4654 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
4655 self, kUIButtonBarButtonTarget,
4656 @"Changes", kUIButtonBarButtonTitle,
4657 @"0", kUIButtonBarButtonType,
4660 [NSDictionary dictionaryWithObjectsAndKeys:
4661 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
4662 @"manage-up.png", kUIButtonBarButtonInfo,
4663 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
4664 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
4665 self, kUIButtonBarButtonTarget,
4666 @"Manage", kUIButtonBarButtonTitle,
4667 @"0", kUIButtonBarButtonType,
4670 [NSDictionary dictionaryWithObjectsAndKeys:
4671 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
4672 @"search-up.png", kUIButtonBarButtonInfo,
4673 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
4674 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
4675 self, kUIButtonBarButtonTarget,
4676 @"Search", kUIButtonBarButtonTitle,
4677 @"0", kUIButtonBarButtonType,
4681 buttonbar_ = [[UIButtonBar alloc]
4683 withFrame:CGRectMake(
4684 0, screenrect.size.height - ButtonBarHeight_,
4685 screenrect.size.width, ButtonBarHeight_
4687 withItemList:buttonitems
4690 [buttonbar_ setDelegate:self];
4691 [buttonbar_ setBarStyle:1];
4692 [buttonbar_ setButtonBarTrackingMode:2];
4694 int buttons[5] = {1, 2, 3, 4, 5};
4695 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
4696 [buttonbar_ showButtonGroup:0 withDuration:0];
4698 for (int i = 0; i != 5; ++i)
4699 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
4700 i * 64 + 2, 1, 60, ButtonBarHeight_
4703 [buttonbar_ showSelectionForButton:1];
4704 [overlay_ addSubview:buttonbar_];
4706 [UIKeyboard initImplementationNow];
4707 CGSize keysize = [UIKeyboard defaultSize];
4708 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
4709 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
4710 [[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
4711 [overlay_ addSubview:keyboard_];
4713 install_ = [[InstallView alloc] initWithBook:book_ database:database_];
4714 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
4715 manage_ = [[ManageView alloc] initWithBook:book_ database:database_];
4716 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
4718 [progress_ resetView];
4724 [self _setHomePage];
4727 - (void) showKeyboard:(BOOL)show {
4728 CGSize keysize = [UIKeyboard defaultSize];
4729 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
4730 CGRect keyup = keydown;
4731 keyup.origin.y -= keysize.height;
4733 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
4734 [animation setSignificantRectFields:2];
4737 [animation setStartFrame:keydown];
4738 [animation setEndFrame:keyup];
4739 [keyboard_ activate];
4741 [animation setStartFrame:keyup];
4742 [animation setEndFrame:keydown];
4743 [keyboard_ deactivate];
4746 [[UIAnimator sharedAnimator]
4747 addAnimations:[NSArray arrayWithObjects:animation, nil]
4748 withDuration:KeyboardTime_
4753 - (void) slideUp:(UIAlertSheet *)alert {
4755 [alert presentSheetFromButtonBar:buttonbar_];
4757 [alert presentSheetInView:overlay_];
4762 void AddPreferences(NSString *plist) {
4763 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4765 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
4766 _assert(settings != NULL);
4767 NSMutableArray *items = [settings objectForKey:@"items"];
4771 for (size_t i(0); i != [items count]; ++i) {
4772 NSMutableDictionary *item([items objectAtIndex:i]);
4773 NSString *label = [item objectForKey:@"label"];
4774 if (label != nil && [label isEqualToString:@"Cydia"]) {
4781 for (size_t i(0); i != [items count]; ++i) {
4782 NSDictionary *item([items objectAtIndex:i]);
4783 NSString *label = [item objectForKey:@"label"];
4784 if (label != nil && [label isEqualToString:@"General"]) {
4785 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
4786 @"CydiaSettings", @"bundle",
4787 @"PSLinkCell", @"cell",
4788 [NSNumber numberWithBool:YES], @"hasIcon",
4789 [NSNumber numberWithBool:YES], @"isController",
4791 nil] atIndex:(i + 1)];
4797 _assert([settings writeToFile:plist atomically:YES] == YES);
4804 id Alloc_(id self, SEL selector) {
4805 id object = alloc_(self, selector);
4806 fprintf(stderr, "[%s]A-%p\n", self->isa->name, object);
4811 id Dealloc_(id self, SEL selector) {
4812 id object = dealloc_(self, selector);
4813 fprintf(stderr, "[%s]D-%p\n", self->isa->name, object);
4817 int main(int argc, char *argv[]) {
4818 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4820 bootstrap_ = argc > 1 && strcmp(argv[1], "--bootstrap") == 0;
4822 Home_ = NSHomeDirectory();
4825 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
4826 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
4827 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
4828 Sounds_Keyboard_ = [keyboard boolValue];
4834 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
4835 alloc_ = alloc->method_imp;
4836 alloc->method_imp = (IMP) &Alloc_;*/
4838 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
4839 dealloc_ = dealloc->method_imp;
4840 dealloc->method_imp = (IMP) &Dealloc_;*/
4842 if (NSDictionary *sysver = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"]) {
4843 if (NSString *prover = [sysver valueForKey:@"ProductVersion"]) {
4844 Firmware_ = strdup([prover UTF8String]);
4845 NSArray *versions = [prover componentsSeparatedByString:@"."];
4846 int count = [versions count];
4847 Major_ = count > 0 ? [[versions objectAtIndex:0] intValue] : 0;
4848 Minor_ = count > 1 ? [[versions objectAtIndex:1] intValue] : 0;
4849 BugFix_ = count > 2 ? [[versions objectAtIndex:2] intValue] : 0;
4854 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
4855 char *machine = new char[size];
4856 sysctlbyname("hw.machine", machine, &size, NULL, 0);
4859 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice"))
4860 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
4861 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
4862 SerialNumber_ = strdup(CFStringGetCStringPtr((CFStringRef) serial, CFStringGetSystemEncoding()));
4866 IOObjectRelease(service);
4869 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
4870 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
4872 if ((Metadata_ = [[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"]) == NULL)
4873 Metadata_ = [[NSMutableDictionary alloc] initWithCapacity:2];
4875 Packages_ = [Metadata_ objectForKey:@"Packages"];
4877 if (access("/User", F_OK) != 0)
4878 system("/usr/libexec/cydia/firmware.sh");
4880 space_ = CGColorSpaceCreateDeviceRGB();
4882 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
4883 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
4884 Clear_.Set(space_, 0.0, 0.0, 0.0, 0.0);
4885 Red_.Set(space_, 1.0, 0.0, 0.0, 1.0);
4886 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
4888 int value = UIApplicationMain(argc, argv, [Cydia class]);
4890 CGColorSpaceRelease(space_);