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/configuration.h>
65 #include <apt-pkg/debmetaindex.h>
66 #include <apt-pkg/error.h>
67 #include <apt-pkg/init.h>
68 #include <apt-pkg/pkgrecords.h>
69 #include <apt-pkg/sourcelist.h>
70 #include <apt-pkg/sptr.h>
72 #include <sys/sysctl.h>
76 #include <mach-o/nlist.h>
87 /* iPhoneOS 2.0 Compatibility {{{ */
89 @interface UICGColor : NSObject {
92 - (id) initWithCGColor:(CGColorRef)color;
98 - (UIFont *) fontWithSize:(CGFloat)size;
101 @interface NSObject (iPhoneOS)
102 - (CGColorRef) cgColor;
103 - (CGColorRef) CGColor;
107 @implementation NSObject (iPhoneOS)
109 - (CGColorRef) cgColor {
110 return [self CGColor];
113 - (CGColorRef) CGColor {
114 return (CGColorRef) self;
118 [[[[objc_getClass("UICGColor") alloc] initWithCGColor:[self CGColor]] autorelease] set];
123 @interface UITextView (iPhoneOS)
124 - (void) setTextSize:(float)size;
127 @implementation UITextView (iPhoneOS)
129 - (void) setTextSize:(float)size {
130 [self setFont:[[self font] fontWithSize:size]];
137 @interface NSString (UIKit)
138 - (NSString *) stringByAddingPercentEscapes;
139 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
142 @interface NSString (Cydia)
143 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
144 - (NSComparisonResult) compareByPath:(NSString *)other;
147 @implementation NSString (Cydia)
149 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
150 char data[length + 1];
151 memcpy(data, bytes, length);
153 return [NSString stringWithUTF8String:data];
156 - (NSComparisonResult) compareByPath:(NSString *)other {
157 NSString *prefix = [self commonPrefixWithString:other options:0];
158 size_t length = [prefix length];
160 NSRange lrange = NSMakeRange(length, [self length] - length);
161 NSRange rrange = NSMakeRange(length, [other length] - length);
163 lrange = [self rangeOfString:@"/" options:0 range:lrange];
164 rrange = [other rangeOfString:@"/" options:0 range:rrange];
166 NSComparisonResult value;
168 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
169 value = NSOrderedSame;
170 else if (lrange.location == NSNotFound)
171 value = NSOrderedAscending;
172 else if (rrange.location == NSNotFound)
173 value = NSOrderedDescending;
175 value = NSOrderedSame;
177 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
178 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
179 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
180 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
182 NSComparisonResult result = [lpath compare:rpath];
183 return result == NSOrderedSame ? value : result;
188 /* Perl-Compatible RegEx {{{ */
198 Pcre(const char *regex) :
203 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
206 fprintf(stderr, "%d:%s\n", offset, error);
210 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
211 matches_ = new int[(capture_ + 1) * 3];
219 NSString *operator [](size_t match) {
220 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
223 bool operator ()(const char *data, size_t size) {
225 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
229 /* Mime Addresses {{{ */
230 Pcre email_r("^\"?(.*)\"? <([^>]*)>$");
232 @interface Address : NSObject {
238 - (NSString *) email;
240 + (Address *) addressWithString:(NSString *)string;
241 - (Address *) initWithString:(NSString *)string;
244 @implementation Address
253 - (NSString *) name {
257 - (NSString *) email {
261 + (Address *) addressWithString:(NSString *)string {
262 return [[[Address alloc] initWithString:string] autorelease];
265 - (Address *) initWithString:(NSString *)string {
266 if ((self = [super init]) != nil) {
267 const char *data = [string UTF8String];
268 size_t size = [string length];
270 if (email_r(data, size)) {
271 name_ = [email_r[1] retain];
272 email_ = [email_r[2] retain];
274 name_ = [[NSString alloc]
277 encoding:kCFStringEncodingUTF8
287 /* CoreGraphics Primitives {{{ */
298 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
301 Set(space, red, green, blue, alpha);
306 CGColorRelease(color_);
313 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
315 float color[] = {red, green, blue, alpha};
316 color_ = CGColorCreate(space, color);
319 operator CGColorRef() {
334 /* Right Alignment {{{ */
335 @interface UIRightTextLabel : UITextLabel {
336 float _savedRightEdgeX;
337 BOOL _sizedtofit_flag;
340 - (void) setFrame:(CGRect)frame;
341 - (void) setText:(NSString *)text;
342 - (void) realignText;
345 @implementation UIRightTextLabel
347 - (void) setFrame:(CGRect)frame {
348 [super setFrame:frame];
349 if (_sizedtofit_flag == NO) {
350 _savedRightEdgeX = frame.origin.x;
355 - (void) setText:(NSString *)text {
356 [super setText:text];
360 - (void) realignText {
361 CGRect oldFrame = [self frame];
363 _sizedtofit_flag = YES;
364 [self sizeToFit]; // shrink down size so I can right align it
366 CGRect newFrame = [self frame];
368 oldFrame.origin.x = _savedRightEdgeX - newFrame.size.width;
369 oldFrame.size.width = newFrame.size.width;
370 [super setFrame:oldFrame];
371 _sizedtofit_flag = NO;
377 /* Random Global Variables {{{ */
378 static const int PulseInterval_ = 50000;
379 static const int ButtonBarHeight_ = 48;
380 static const float KeyboardTime_ = 0.4f;
382 static CGColor Black_;
383 static CGColor Clear_;
385 static CGColor White_;
387 static NSString *Home_;
388 static BOOL Sounds_Keyboard_;
390 static BOOL Advanced_;
392 static BOOL Ignored_;
394 const char *Firmware_ = NULL;
395 const char *Machine_ = NULL;
396 const char *SerialNumber_ = NULL;
402 CGColorSpaceRef space_;
404 #define FW_LEAST(major, minor, bugfix) \
405 (major < Major_ || major == Major_ && \
406 (minor < Minor_ || minor == Minor_ && \
412 static NSMutableDictionary *Metadata_;
413 static NSMutableDictionary *Packages_;
414 static bool Changed_;
417 NSString *GetLastUpdate() {
418 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
421 return @"Never or Unknown";
423 CFLocaleRef locale = CFLocaleCopyCurrent();
424 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, locale, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
425 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
427 CFRelease(formatter);
430 return [(NSString *) formatted autorelease];
433 /* Display Helpers {{{ */
434 inline float Interpolate(float begin, float end, float fraction) {
435 return (end - begin) * fraction + begin;
438 NSString *SizeString(double size) {
440 while (size > 1024) {
445 static const char *powers_[] = {"B", "kB", "MB", "GB"};
447 return [NSString stringWithFormat:@"%.1f%s", size, powers_[power]];
450 static const float TextViewOffset_ = 22;
452 UITextView *GetTextView(NSString *value, float left, bool html) {
453 UITextView *text([[[UITextView alloc] initWithFrame:CGRectMake(left, 3, 310 - left, 1000)] autorelease]);
454 [text setEditable:NO];
455 [text setTextSize:16];
457 [text setHTML:value];
459 [text setText:value];
460 [text setEnabled:NO];
462 [text setBackgroundColor:Clear_];
464 CGRect frame = [text frame];
465 [text setFrame:frame];
466 CGRect rect = [text visibleTextRect];
467 frame.size.height = rect.size.height;
468 [text setFrame:frame];
473 NSString *Simplify(NSString *title) {
474 const char *data = [title UTF8String];
475 size_t size = [title length];
477 Pcre title_r("^(.*?)( \\(.*\\))?$");
478 if (title_r(data, size))
485 /* Delegate Prototypes {{{ */
489 @protocol ProgressDelegate
490 - (void) setProgressError:(NSString *)error;
491 - (void) setProgressTitle:(NSString *)title;
492 - (void) setProgressPercent:(float)percent;
493 - (void) addProgressOutput:(NSString *)output;
496 @protocol CydiaDelegate
497 - (void) installPackage:(Package *)package;
498 - (void) removePackage:(Package *)package;
499 - (void) slideUp:(UIAlertSheet *)alert;
500 - (void) distUpgrade;
504 /* Status Delegation {{{ */
506 public pkgAcquireStatus
509 _transient id<ProgressDelegate> delegate_;
517 void setDelegate(id delegate) {
518 delegate_ = delegate;
521 virtual bool MediaChange(std::string media, std::string drive) {
525 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
528 virtual void Fetch(pkgAcquire::ItemDesc &item) {
529 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
532 virtual void Done(pkgAcquire::ItemDesc &item) {
535 virtual void Fail(pkgAcquire::ItemDesc &item) {
537 item.Owner->Status == pkgAcquire::Item::StatIdle ||
538 item.Owner->Status == pkgAcquire::Item::StatDone
542 [delegate_ setProgressError:[NSString stringWithUTF8String:item.Owner->ErrorText.c_str()]];
545 virtual bool Pulse(pkgAcquire *Owner) {
546 bool value = pkgAcquireStatus::Pulse(Owner);
549 double(CurrentBytes + CurrentItems) /
550 double(TotalBytes + TotalItems)
553 [delegate_ setProgressPercent:percent];
557 virtual void Start() {
560 virtual void Stop() {
564 /* Progress Delegation {{{ */
569 _transient id<ProgressDelegate> delegate_;
572 virtual void Update() {
573 [delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
574 [delegate_ setProgressPercent:(Percent / 100)];
583 void setDelegate(id delegate) {
584 delegate_ = delegate;
587 virtual void Done() {
588 [delegate_ setProgressPercent:1];
593 /* Database Interface {{{ */
594 @interface Database : NSObject {
596 pkgRecords *records_;
597 pkgProblemResolver *resolver_;
598 pkgAcquire *fetcher_;
600 SPtr<pkgPackageManager> manager_;
601 pkgSourceList *list_;
603 NSMutableDictionary *sources_;
604 NSMutableArray *packages_;
606 _transient id delegate_;
612 - (void) _readStatus:(NSNumber *)fd;
613 - (void) _readOutput:(NSNumber *)fd;
615 - (Package *) packageWithName:(NSString *)name;
618 - (pkgCacheFile &) cache;
619 - (pkgRecords *) records;
620 - (pkgProblemResolver *) resolver;
621 - (pkgAcquire &) fetcher;
622 - (NSArray *) packages;
630 - (void) updateWithStatus:(Status &)status;
632 - (void) setDelegate:(id)delegate;
633 - (Source *) getSource:(const pkgCache::PkgFileIterator &)file;
637 /* Source Class {{{ */
638 @interface Source : NSObject {
639 NSString *description_;
644 NSString *distribution_;
648 NSString *defaultIcon_;
653 - (Source *) initWithMetaIndex:(metaIndex *)index;
658 - (NSString *) distribution;
661 - (NSString *) description;
662 - (NSString *) label;
663 - (NSString *) origin;
664 - (NSString *) version;
666 - (NSString *) defaultIcon;
669 @implementation Source
673 [distribution_ release];
676 if (description_ != nil)
677 [description_ release];
684 if (defaultIcon_ != nil)
685 [defaultIcon_ release];
690 - (Source *) initWithMetaIndex:(metaIndex *)index {
691 if ((self = [super init]) != nil) {
692 trusted_ = index->IsTrusted();
694 uri_ = [[NSString stringWithUTF8String:index->GetURI().c_str()] retain];
695 distribution_ = [[NSString stringWithUTF8String:index->GetDist().c_str()] retain];
696 type_ = [[NSString stringWithUTF8String:index->GetType()] retain];
704 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
705 if (dindex != NULL) {
706 std::ifstream release(dindex->MetaIndexFile("Release").c_str());
708 while (std::getline(release, line)) {
709 std::string::size_type colon(line.find(':'));
710 if (colon == std::string::npos)
713 std::string name(line.substr(0, colon));
714 std::string value(line.substr(colon + 1));
715 while (!value.empty() && value[0] == ' ')
716 value = value.substr(1);
718 if (name == "Default-Icon")
719 defaultIcon_ = [[NSString stringWithUTF8String:value.c_str()] retain];
720 else if (name == "Description")
721 description_ = [[NSString stringWithUTF8String:value.c_str()] retain];
722 else if (name == "Label")
723 label_ = [[NSString stringWithUTF8String:value.c_str()] retain];
724 else if (name == "Origin")
725 origin_ = [[NSString stringWithUTF8String:value.c_str()] retain];
726 else if (name == "Version")
727 version_ = [[NSString stringWithUTF8String:value.c_str()] retain];
741 - (NSString *) distribution {
742 return distribution_;
745 - (NSString *) type {
749 - (NSString *) description {
753 - (NSString *) label {
757 - (NSString *) origin {
761 - (NSString *) version {
765 - (NSString *) defaultIcon {
771 /* Relationship Class {{{ */
772 @interface Relationship : NSObject {
783 @implementation Relationship
791 - (NSString *) type {
799 - (NSString *) name {
806 /* Package Class {{{ */
807 NSString *Scour(const char *field, const char *begin, const char *end) {
808 size_t i(0), l(strlen(field));
811 const char *name = begin + i;
812 const char *colon = name + l;
813 const char *value = colon + 1;
818 memcmp(name, field, l) == 0
820 while (value != end && value[0] == ' ')
822 const char *line = std::find(value, end, '\n');
823 while (line != value && line[-1] == ' ')
826 return [NSString stringWithUTF8Bytes:value length:(line - value)];
828 begin = std::find(begin, end, '\n');
836 @interface Package : NSObject {
837 pkgCache::PkgIterator iterator_;
838 _transient Database *database_;
839 pkgCache::VerIterator version_;
840 pkgCache::VerFileIterator file_;
846 NSString *installed_;
854 NSArray *relationships_;
857 - (Package *) initWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database version:(pkgCache::VerIterator)version file:(pkgCache::VerFileIterator)file;
858 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database;
860 - (pkgCache::PkgIterator) iterator;
862 - (NSString *) section;
863 - (Address *) maintainer;
865 - (NSString *) description;
866 - (NSString *) index;
870 - (NSString *) latest;
871 - (NSString *) installed;
878 - (NSString *) tagline;
880 - (NSString *) website;
882 - (NSArray *) relationships;
886 - (BOOL) matches:(NSString *)text;
888 - (NSComparisonResult) compareByName:(Package *)package;
889 - (NSComparisonResult) compareBySection:(Package *)package;
890 - (NSComparisonResult) compareBySectionAndName:(Package *)package;
891 - (NSComparisonResult) compareForChanges:(Package *)package;
896 - (NSNumber *) isSearchedForBy:(NSString *)search;
897 - (NSNumber *) isInstalledInSection:(NSString *)section;
898 - (NSNumber *) isUninstalledInSection:(NSString *)section;
902 @implementation Package
909 if (installed_ != nil)
910 [installed_ release];
921 if (relationships_ != nil)
922 [relationships_ release];
927 - (Package *) initWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database version:(pkgCache::VerIterator)version file:(pkgCache::VerFileIterator)file {
928 if ((self = [super init]) != nil) {
929 iterator_ = iterator;
930 database_ = database;
935 latest_ = [[NSString stringWithUTF8String:version_.VerStr()] retain];
936 installed_ = iterator_.CurrentVer().end() ? nil : [[NSString stringWithUTF8String:iterator_.CurrentVer().VerStr()] retain];
938 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
940 const char *begin, *end;
941 parser->GetRec(begin, end);
943 id_ = [[[NSString stringWithUTF8String:iterator_.Name()] lowercaseString] retain];
944 name_ = Scour("Name", begin, end);
946 name_ = [name_ retain];
947 tagline_ = [[NSString stringWithUTF8String:parser->ShortDesc().c_str()] retain];
948 icon_ = Scour("Icon", begin, end);
950 icon_ = [icon_ retain];
951 website_ = Scour("Website", begin, end);
953 website_ = [website_ retain];
955 NSMutableDictionary *metadata = [Packages_ objectForKey:id_];
956 if (metadata == nil || [metadata count] == 0) {
957 metadata = [NSMutableDictionary dictionaryWithObjectsAndKeys:
961 [Packages_ setObject:metadata forKey:id_];
967 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database {
968 for (pkgCache::VerIterator version = iterator.VersionList(); !version.end(); ++version)
969 for (pkgCache::VerFileIterator file = version.FileList(); !file.end(); ++file)
970 return [[[Package alloc]
971 initWithIterator:iterator
979 - (pkgCache::PkgIterator) iterator {
983 - (NSString *) section {
984 const char *section = iterator_.Section();
985 return section == NULL ? nil : [[NSString stringWithUTF8String:section] stringByReplacingCharacter:'_' withCharacter:' '];
988 - (Address *) maintainer {
989 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
990 return [Address addressWithString:[NSString stringWithUTF8String:parser->Maintainer().c_str()]];
994 return version_->InstalledSize;
997 - (NSString *) description {
998 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
999 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
1001 NSArray *lines = [description componentsSeparatedByString:@"\n"];
1002 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
1003 if ([lines count] < 2)
1006 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
1007 for (size_t i(1); i != [lines count]; ++i) {
1008 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
1009 [trimmed addObject:trim];
1012 return [trimmed componentsJoinedByString:@"\n"];
1015 - (NSString *) index {
1016 NSString *index = [[[self name] substringToIndex:1] uppercaseString];
1017 return [index length] != 0 && isalpha([index characterAtIndex:0]) ? index : @"123";
1021 return [[Packages_ objectForKey:id_] objectForKey:@"FirstSeen"];
1024 - (NSString *) latest {
1028 - (NSString *) installed {
1032 - (BOOL) upgradable {
1033 pkgCache::VerIterator current = iterator_.CurrentVer();
1036 return [self essential];
1038 pkgDepCache::Policy policy;
1039 pkgCache::VerIterator candidate = policy.GetCandidateVer(iterator_);
1040 return !candidate.end() && candidate != current;
1044 - (BOOL) essential {
1045 return (iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES;
1049 return (*[database_ cache])[iterator_].InstBroken();
1056 - (NSString *) name {
1057 return name_ == nil ? id_ : name_;
1060 - (NSString *) tagline {
1064 - (NSString *) icon {
1068 - (NSString *) website {
1072 - (NSArray *) relationships {
1073 return relationships_;
1076 - (Source *) source {
1078 source_ = [[database_ getSource:file_.File()] retain];
1085 - (BOOL) matches:(NSString *)text {
1091 range = [[self id] rangeOfString:text options:NSCaseInsensitiveSearch];
1092 if (range.location != NSNotFound)
1095 range = [[self name] rangeOfString:text options:NSCaseInsensitiveSearch];
1096 if (range.location != NSNotFound)
1099 range = [[self tagline] rangeOfString:text options:NSCaseInsensitiveSearch];
1100 if (range.location != NSNotFound)
1106 - (NSComparisonResult) compareByName:(Package *)package {
1107 NSString *lhs = [self name];
1108 NSString *rhs = [package name];
1110 if ([lhs length] != 0 && [rhs length] != 0) {
1111 unichar lhc = [lhs characterAtIndex:0];
1112 unichar rhc = [rhs characterAtIndex:0];
1114 if (isalpha(lhc) && !isalpha(rhc))
1115 return NSOrderedAscending;
1116 else if (!isalpha(lhc) && isalpha(rhc))
1117 return NSOrderedDescending;
1120 return [lhs caseInsensitiveCompare:rhs];
1123 - (NSComparisonResult) compareBySection:(Package *)package {
1124 NSString *lhs = [self section];
1125 NSString *rhs = [package section];
1127 if (lhs == NULL && rhs != NULL)
1128 return NSOrderedAscending;
1129 else if (lhs != NULL && rhs == NULL)
1130 return NSOrderedDescending;
1131 else if (lhs != NULL && rhs != NULL) {
1132 NSComparisonResult result = [lhs caseInsensitiveCompare:rhs];
1133 if (result != NSOrderedSame)
1137 return NSOrderedSame;
1140 - (NSComparisonResult) compareBySectionAndName:(Package *)package {
1141 NSString *lhs = [self section];
1142 NSString *rhs = [package section];
1144 if (lhs == NULL && rhs != NULL)
1145 return NSOrderedAscending;
1146 else if (lhs != NULL && rhs == NULL)
1147 return NSOrderedDescending;
1148 else if (lhs != NULL && rhs != NULL) {
1149 NSComparisonResult result = [lhs compare:rhs];
1150 if (result != NSOrderedSame)
1154 return [self compareByName:package];
1157 - (NSComparisonResult) compareForChanges:(Package *)package {
1158 BOOL lhs = [self upgradable];
1159 BOOL rhs = [package upgradable];
1162 return lhs ? NSOrderedAscending : NSOrderedDescending;
1164 switch ([[self seen] compare:[package seen]]) {
1165 case NSOrderedAscending:
1166 return NSOrderedDescending;
1169 case NSOrderedDescending:
1170 return NSOrderedAscending;
1176 return [self compareByName:package];
1180 pkgProblemResolver *resolver = [database_ resolver];
1181 resolver->Clear(iterator_);
1182 resolver->Protect(iterator_);
1183 pkgCacheFile &cache([database_ cache]);
1184 cache->MarkInstall(iterator_, false);
1185 pkgDepCache::StateCache &state((*cache)[iterator_]);
1186 if (!state.Install())
1187 cache->SetReInstall(iterator_, true);
1191 pkgProblemResolver *resolver = [database_ resolver];
1192 resolver->Clear(iterator_);
1193 resolver->Protect(iterator_);
1194 resolver->Remove(iterator_);
1195 [database_ cache]->MarkDelete(iterator_, true);
1198 - (NSNumber *) isSearchedForBy:(NSString *)search {
1199 return [NSNumber numberWithBool:[self matches:search]];
1202 - (NSNumber *) isInstalledInSection:(NSString *)section {
1203 return [NSNumber numberWithBool:([self installed] != nil && (section == nil || [section isEqualToString:[self section]]))];
1206 - (NSNumber *) isUninstalledInSection:(NSString *)section {
1207 return [NSNumber numberWithBool:([self installed] == nil && (section == nil || [section isEqualToString:[self section]]))];
1212 /* Section Class {{{ */
1213 @interface Section : NSObject {
1219 - (Section *) initWithName:(NSString *)name row:(size_t)row;
1220 - (NSString *) name;
1223 - (void) addToCount;
1227 @implementation Section
1234 - (Section *) initWithName:(NSString *)name row:(size_t)row {
1235 if ((self = [super init]) != nil) {
1236 name_ = [name retain];
1241 - (NSString *) name {
1253 - (void) addToCount {
1260 /* Database Implementation {{{ */
1261 @implementation Database
1268 - (void) _readStatus:(NSNumber *)fd {
1269 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1271 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
1272 std::istream is(&ib);
1277 pcre *code = pcre_compile("^([^:]*):([^:]*):([^:]*):(.*)$", 0, &error, &offset, NULL);
1279 pcre_extra *study = NULL;
1281 pcre_fullinfo(code, study, PCRE_INFO_CAPTURECOUNT, &capture);
1282 int matches[(capture + 1) * 3];
1284 while (std::getline(is, line)) {
1285 const char *data(line.c_str());
1287 _assert(pcre_exec(code, study, data, line.size(), 0, 0, matches, sizeof(matches) / sizeof(matches[0])) >= 0);
1289 std::istringstream buffer(line.substr(matches[6], matches[7] - matches[6]));
1292 [delegate_ setProgressPercent:(percent / 100)];
1294 NSString *string = [NSString stringWithUTF8Bytes:(data + matches[8]) length:(matches[9] - matches[8])];
1296 std::string type(line.substr(matches[2], matches[3] - matches[2]));
1298 if (type == "pmerror")
1299 [delegate_ setProgressError:string];
1300 else if (type == "pmstatus")
1301 [delegate_ setProgressTitle:string];
1302 else if (type == "pmconffile")
1304 else _assert(false);
1311 - (void) _readOutput:(NSNumber *)fd {
1312 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1314 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
1315 std::istream is(&ib);
1318 while (std::getline(is, line))
1319 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
1325 - (Package *) packageWithName:(NSString *)name {
1326 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
1327 return iterator.end() ? nil : [Package packageWithIterator:iterator database:self];
1330 - (Database *) init {
1331 if ((self = [super init]) != nil) {
1337 sources_ = [[NSMutableDictionary dictionaryWithCapacity:16] retain];
1338 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
1342 _assert(pipe(fds) != -1);
1346 detachNewThreadSelector:@selector(_readStatus:)
1348 withObject:[[NSNumber numberWithInt:fds[0]] retain]
1351 _assert(pipe(fds) != -1);
1352 _assert(dup2(fds[1], 1) != -1);
1353 _assert(close(fds[1]) != -1);
1356 detachNewThreadSelector:@selector(_readOutput:)
1358 withObject:[[NSNumber numberWithInt:fds[0]] retain]
1363 - (pkgCacheFile &) cache {
1367 - (pkgRecords *) records {
1371 - (pkgProblemResolver *) resolver {
1375 - (pkgAcquire &) fetcher {
1379 - (NSArray *) packages {
1383 - (void) reloadData {
1393 if (!cache_.Open(progress_, true)) {
1394 fprintf(stderr, "repairing corrupted database...\n");
1396 [self updateWithStatus:status_];
1397 _assert(cache_.Open(progress_, true));
1400 now_ = [[NSDate date] retain];
1402 records_ = new pkgRecords(cache_);
1403 resolver_ = new pkgProblemResolver(cache_);
1404 fetcher_ = new pkgAcquire(&status_);
1407 list_ = new pkgSourceList();
1408 _assert(list_->ReadMainList());
1410 [sources_ removeAllObjects];
1411 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
1412 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
1413 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
1415 setObject:[[[Source alloc] initWithMetaIndex:*source] autorelease]
1416 forKey:[NSNumber numberWithLong:reinterpret_cast<uintptr_t>(*index)]
1420 pkgDepCache::Policy policy;
1422 [packages_ removeAllObjects];
1423 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
1424 if (!policy.GetCandidateVer(iterator).end())
1425 if (Package *package = [Package packageWithIterator:iterator database:self])
1426 [packages_ addObject:package];
1428 [packages_ sortUsingSelector:@selector(compareByName:)];
1432 pkgRecords records(cache_);
1434 lock_ = new FileFd();
1435 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
1436 _assert(!_error->PendingError());
1439 // XXX: explain this with an error message
1440 _assert(list.ReadMainList());
1442 manager_ = (_system->CreatePM(cache_));
1443 _assert(manager_->GetArchives(fetcher_, &list, &records));
1444 _assert(!_error->PendingError());
1448 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
1450 _assert(list.ReadMainList());
1451 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
1452 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
1455 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue)
1459 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
1461 if (result == pkgPackageManager::Failed)
1463 if (_error->PendingError())
1465 if (result != pkgPackageManager::Completed)
1468 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
1470 _assert(list.ReadMainList());
1471 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
1472 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
1475 if (![before isEqualToArray:after])
1480 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
1481 _assert(pkgApplyStatus(cache_));
1483 if (cache_->BrokenCount() != 0) {
1484 _assert(pkgFixBroken(cache_));
1485 _assert(cache_->BrokenCount() == 0);
1486 _assert(pkgMinimizeUpgrade(cache_));
1489 _assert(pkgDistUpgrade(cache_));
1493 [self updateWithStatus:status_];
1496 - (void) updateWithStatus:(Status &)status {
1498 _assert(list.ReadMainList());
1501 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
1502 _assert(!_error->PendingError());
1504 pkgAcquire fetcher(&status);
1505 _assert(list.GetIndexes(&fetcher));
1507 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
1508 bool failed = false;
1509 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
1510 if ((*item)->Status != pkgAcquire::Item::StatDone) {
1511 (*item)->Finished();
1515 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
1516 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
1517 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
1520 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
1525 - (void) setDelegate:(id)delegate {
1526 delegate_ = delegate;
1527 status_.setDelegate(delegate);
1528 progress_.setDelegate(delegate);
1531 - (Source *) getSource:(const pkgCache::PkgFileIterator &)file {
1532 pkgIndexFile *index(NULL);
1533 list_->FindIndex(file, index);
1534 return [sources_ objectForKey:[NSNumber numberWithLong:reinterpret_cast<uintptr_t>(index)]];
1540 /* Confirmation View {{{ */
1541 void AddTextView(NSMutableDictionary *fields, NSMutableArray *packages, NSString *key) {
1542 if ([packages count] == 0)
1545 UITextView *text = GetTextView([packages count] == 0 ? @"n/a" : [packages componentsJoinedByString:@", "], 120, false);
1546 [fields setObject:text forKey:key];
1548 CGColor blue(space_, 0, 0, 0.4, 1);
1549 [text setTextColor:blue];
1552 @protocol ConfirmationViewDelegate
1557 @interface ConfirmationView : UIView {
1558 Database *database_;
1560 UITransitionView *transition_;
1562 UINavigationBar *navbar_;
1563 UIPreferencesTable *table_;
1564 NSMutableDictionary *fields_;
1565 UIAlertSheet *essential_;
1570 - (id) initWithView:(UIView *)view database:(Database *)database delegate:(id)delegate;
1574 @implementation ConfirmationView
1577 [navbar_ setDelegate:nil];
1578 [transition_ setDelegate:nil];
1579 [table_ setDataSource:nil];
1581 [transition_ release];
1586 if (essential_ != nil)
1587 [essential_ release];
1592 [transition_ transition:7 toView:nil];
1596 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
1597 if (from != nil && to == nil)
1598 [self removeFromSuperview];
1601 - (void) navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button {
1604 if (essential_ != nil)
1605 [essential_ popupAlertAnimated:YES];
1607 [delegate_ confirm];
1616 - (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
1617 [essential_ dismiss];
1621 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
1625 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
1627 case 0: return @"Statistics";
1628 case 1: return @"Modifications";
1630 default: _assert(false);
1634 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
1637 case 1: return [fields_ count];
1639 default: _assert(false);
1643 - (float) preferencesTable:(UIPreferencesTable *)table heightForRow:(int)row inGroup:(int)group withProposedHeight:(float)proposed {
1644 if (group != 1 || row == -1)
1647 _assert(size_t(row) < [fields_ count]);
1648 return [[[fields_ allValues] objectAtIndex:row] visibleTextRect].size.height + TextViewOffset_;
1652 - (UIPreferencesTableCell *) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
1653 UIPreferencesTableCell *cell = [[[UIPreferencesTableCell alloc] init] autorelease];
1654 [cell setShowSelection:NO];
1657 case 0: switch (row) {
1659 [cell setTitle:@"Downloading"];
1660 [cell setValue:SizeString([database_ fetcher].FetchNeeded())];
1664 [cell setTitle:@"Resuming At"];
1665 [cell setValue:SizeString([database_ fetcher].PartialPresent())];
1669 double size([database_ cache]->UsrSize());
1672 [cell setTitle:@"Disk Freeing"];
1673 [cell setValue:SizeString(-size)];
1675 [cell setTitle:@"Disk Using"];
1676 [cell setValue:SizeString(size)];
1680 default: _assert(false);
1684 _assert(size_t(row) < [fields_ count]);
1685 [cell setTitle:[[fields_ allKeys] objectAtIndex:row]];
1686 [cell addSubview:[[fields_ allValues] objectAtIndex:row]];
1689 default: _assert(false);
1695 - (id) initWithView:(UIView *)view database:(Database *)database delegate:(id)delegate {
1696 if ((self = [super initWithFrame:[view bounds]]) != nil) {
1697 database_ = database;
1698 delegate_ = delegate;
1700 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
1701 [self addSubview:transition_];
1703 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
1705 CGSize navsize = [UINavigationBar defaultSize];
1706 CGRect navrect = {{0, 0}, navsize};
1707 CGRect bounds = [overlay_ bounds];
1709 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
1710 [navbar_ setBarStyle:1];
1711 [navbar_ setDelegate:self];
1713 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:@"Confirm"] autorelease];
1714 [navbar_ pushNavigationItem:navitem];
1715 [navbar_ showButtonsWithLeftTitle:@"Cancel" rightTitle:@"Confirm"];
1717 fields_ = [[NSMutableDictionary dictionaryWithCapacity:16] retain];
1719 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
1720 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
1721 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
1722 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
1723 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
1727 pkgCacheFile &cache([database_ cache]);
1728 NSArray *packages = [database_ packages];
1729 for (size_t i(0), e = [packages count]; i != e; ++i) {
1730 Package *package = [packages objectAtIndex:i];
1731 pkgCache::PkgIterator iterator = [package iterator];
1732 pkgDepCache::StateCache &state(cache[iterator]);
1734 NSString *name([package name]);
1736 if (state.NewInstall())
1737 [installing addObject:name];
1738 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
1739 [reinstalling addObject:name];
1740 else if (state.Upgrade())
1741 [upgrading addObject:name];
1742 else if (state.Downgrade())
1743 [downgrading addObject:name];
1744 else if (state.Delete()) {
1745 if ([package essential])
1747 [removing addObject:name];
1754 essential_ = [[UIAlertSheet alloc]
1755 initWithTitle:@"Unable to Comply"
1756 buttons:[NSArray arrayWithObjects:@"Okay", nil]
1757 defaultButtonIndex:0
1762 [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."];
1765 AddTextView(fields_, installing, @"Installing");
1766 AddTextView(fields_, reinstalling, @"Reinstalling");
1767 AddTextView(fields_, upgrading, @"Upgrading");
1768 AddTextView(fields_, downgrading, @"Downgrading");
1769 AddTextView(fields_, removing, @"Removing");
1771 table_ = [[UIPreferencesTable alloc] initWithFrame:CGRectMake(
1772 0, navsize.height, bounds.size.width, bounds.size.height - navsize.height
1775 [table_ setReusesTableCells:YES];
1776 [table_ setDataSource:self];
1777 [table_ reloadData];
1779 [overlay_ addSubview:navbar_];
1780 [overlay_ addSubview:table_];
1782 [view addSubview:self];
1784 [transition_ setDelegate:self];
1786 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
1787 [transition_ transition:0 toView:blank];
1788 [transition_ transition:3 toView:overlay_];
1795 /* Progress Data {{{ */
1796 @interface ProgressData : NSObject {
1802 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
1809 @implementation ProgressData
1811 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
1812 if ((self = [super init]) != nil) {
1813 selector_ = selector;
1833 /* Progress View {{{ */
1834 @interface ProgressView : UIView <
1838 UIView *background_;
1839 UITransitionView *transition_;
1841 UINavigationBar *navbar_;
1842 UIProgressBar *progress_;
1843 UITextView *output_;
1844 UITextLabel *status_;
1848 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
1850 - (ProgressView *) initWithFrame:(struct CGRect)frame delegate:(id)delegate;
1851 - (void) setContentView:(UIView *)view;
1854 - (void) _retachThread;
1855 - (void) _detachNewThreadData:(ProgressData *)data;
1856 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
1860 @protocol ProgressViewDelegate
1861 - (void) progressViewIsComplete:(ProgressView *)sender;
1864 @implementation ProgressView
1867 [transition_ setDelegate:nil];
1868 [navbar_ setDelegate:nil];
1871 if (background_ != nil)
1872 [background_ release];
1873 [transition_ release];
1876 [progress_ release];
1882 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
1883 if (bootstrap_ && from == overlay_ && to == view_)
1887 - (ProgressView *) initWithFrame:(struct CGRect)frame delegate:(id)delegate {
1888 if ((self = [super initWithFrame:frame]) != nil) {
1889 delegate_ = delegate;
1891 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
1892 [transition_ setDelegate:self];
1894 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
1897 [overlay_ setBackgroundColor:Black_];
1899 background_ = [[UIView alloc] initWithFrame:[self bounds]];
1900 [background_ setBackgroundColor:Black_];
1901 [self addSubview:background_];
1904 [self addSubview:transition_];
1906 CGSize navsize = [UINavigationBar defaultSize];
1907 CGRect navrect = {{0, 0}, navsize};
1909 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
1910 [overlay_ addSubview:navbar_];
1912 [navbar_ setBarStyle:1];
1913 [navbar_ setDelegate:self];
1915 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
1916 [navbar_ pushNavigationItem:navitem];
1918 CGRect bounds = [overlay_ bounds];
1919 CGSize prgsize = [UIProgressBar defaultSize];
1922 (bounds.size.width - prgsize.width) / 2,
1923 bounds.size.height - prgsize.height - 20
1926 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
1927 [overlay_ addSubview:progress_];
1929 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
1931 bounds.size.height - prgsize.height - 50,
1932 bounds.size.width - 20,
1936 [status_ setColor:White_];
1937 [status_ setBackgroundColor:Clear_];
1939 [status_ setCentersHorizontally:YES];
1940 //[status_ setFont:font];
1942 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
1944 navrect.size.height + 20,
1945 bounds.size.width - 20,
1946 bounds.size.height - navsize.height - 62 - navrect.size.height
1949 //[output_ setTextFont:@"Courier New"];
1950 [output_ setTextSize:12];
1952 [output_ setTextColor:White_];
1953 [output_ setBackgroundColor:Clear_];
1955 [output_ setMarginTop:0];
1956 [output_ setAllowsRubberBanding:YES];
1958 [overlay_ addSubview:output_];
1959 [overlay_ addSubview:status_];
1961 [progress_ setStyle:0];
1965 - (void) setContentView:(UIView *)view {
1966 view_ = [view retain];
1969 - (void) resetView {
1970 [transition_ transition:6 toView:view_];
1973 - (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
1977 - (void) _retachThread {
1978 [delegate_ progressViewIsComplete:self];
1982 - (void) _detachNewThreadData:(ProgressData *)data {
1983 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1985 [[data target] performSelector:[data selector] withObject:[data object]];
1988 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
1993 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
1994 [navbar_ popNavigationItem];
1995 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:title] autorelease];
1996 [navbar_ pushNavigationItem:navitem];
1998 [status_ setText:nil];
1999 [output_ setText:@""];
2000 [progress_ setProgress:0];
2002 [transition_ transition:6 toView:overlay_];
2005 detachNewThreadSelector:@selector(_detachNewThreadData:)
2007 withObject:[[ProgressData alloc]
2008 initWithSelector:selector
2015 - (void) setProgressError:(NSString *)error {
2017 performSelectorOnMainThread:@selector(_setProgressError:)
2023 - (void) setProgressTitle:(NSString *)title {
2025 performSelectorOnMainThread:@selector(_setProgressTitle:)
2031 - (void) setProgressPercent:(float)percent {
2033 performSelectorOnMainThread:@selector(_setProgressPercent:)
2034 withObject:[NSNumber numberWithFloat:percent]
2039 - (void) addProgressOutput:(NSString *)output {
2041 performSelectorOnMainThread:@selector(_addProgressOutput:)
2047 - (void) _setProgressError:(NSString *)error {
2048 UIAlertSheet *sheet = [[[UIAlertSheet alloc]
2049 initWithTitle:@"Package Error"
2050 buttons:[NSArray arrayWithObjects:@"Okay", nil]
2051 defaultButtonIndex:0
2056 [sheet setBodyText:error];
2057 [sheet popupAlertAnimated:YES];
2060 - (void) _setProgressTitle:(NSString *)title {
2061 [status_ setText:[title stringByAppendingString:@"..."]];
2064 - (void) _setProgressPercent:(NSNumber *)percent {
2065 [progress_ setProgress:[percent floatValue]];
2068 - (void) _addProgressOutput:(NSString *)output {
2069 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
2070 CGSize size = [output_ contentSize];
2071 CGRect rect = {{0, size.height}, {size.width, 0}};
2072 [output_ scrollRectToVisible:rect animated:YES];
2078 /* Package Cell {{{ */
2079 @interface PackageCell : UITableCell {
2082 UITextLabel *description_;
2083 UITextLabel *source_;
2084 UIImageView *trusted_;
2087 - (PackageCell *) init;
2088 - (void) setPackage:(Package *)package;
2090 - (void) _setSelected:(float)fraction;
2091 - (void) setSelected:(BOOL)selected;
2092 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade;
2093 - (void) _setSelectionFadeFraction:(float)fraction;
2097 @implementation PackageCell
2102 [description_ release];
2108 - (PackageCell *) init {
2109 if ((self = [super init]) != nil) {
2110 GSFontRef bold = GSFontCreateWithName("Helvetica", kGSFontTraitBold, 20);
2111 GSFontRef large = GSFontCreateWithName("Helvetica", kGSFontTraitNone, 12);
2112 GSFontRef small = GSFontCreateWithName("Helvetica", kGSFontTraitNone, 14);
2114 icon_ = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
2116 name_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 8, 240, 25)];
2117 [name_ setBackgroundColor:Clear_];
2118 [name_ setFont:bold];
2120 source_ = [[UITextLabel alloc] initWithFrame:CGRectMake(58, 28, 225, 20)];
2121 [source_ setBackgroundColor:Clear_];
2122 [source_ setFont:large];
2124 description_ = [[UITextLabel alloc] initWithFrame:CGRectMake(12, 46, 280, 20)];
2125 [description_ setBackgroundColor:Clear_];
2126 [description_ setFont:small];
2128 trusted_ = [[UIImageView alloc] initWithFrame:CGRectMake(30, 30, 16, 16)];
2129 [trusted_ setImage:[UIImage applicationImageNamed:@"trusted.png"]];
2131 [self addSubview:icon_];
2132 [self addSubview:name_];
2133 [self addSubview:description_];
2134 [self addSubview:source_];
2142 - (void) setPackage:(Package *)package {
2143 Source *source = [package source];
2145 UIImage *image = nil;
2146 if (NSString *icon = [package icon])
2147 image = [UIImage imageAtPath:[icon substringFromIndex:6]];
2148 if (image == nil) if (NSString *icon = [source defaultIcon])
2149 image = [UIImage imageAtPath:[icon substringFromIndex:6]];
2151 image = [UIImage applicationImageNamed:@"unknown.png"];
2152 [icon_ setImage:image];
2155 CGSize size = [image size];
2156 float scale = 30 / std::max(size.width, size.height);
2157 [icon_ zoomToScale:scale];
2160 [icon_ setFrame:CGRectMake(10, 10, 30, 30)];
2162 [name_ setText:[package name]];
2163 [description_ setText:[package tagline]];
2165 NSString *label = nil;
2166 bool trusted = false;
2168 if (source != nil) {
2169 label = [source label];
2170 trusted = [source trusted];
2171 } else if ([[package id] isEqualToString:@"firmware"])
2175 label = @"Unknown/Local";
2177 NSString *from = [NSString stringWithFormat:@"from %@", label];
2179 NSString *section = Simplify([package section]);
2180 if (section != nil && ![section isEqualToString:label])
2181 from = [from stringByAppendingString:[NSString stringWithFormat:@" (%@)", section]];
2183 [source_ setText:from];
2186 [self addSubview:trusted_];
2188 [trusted_ removeFromSuperview];
2191 - (void) _setSelected:(float)fraction {
2192 CGColor black(space_,
2193 Interpolate(0.0, 1.0, fraction),
2194 Interpolate(0.0, 1.0, fraction),
2195 Interpolate(0.0, 1.0, fraction),
2198 CGColor gray(space_,
2199 Interpolate(0.4, 1.0, fraction),
2200 Interpolate(0.4, 1.0, fraction),
2201 Interpolate(0.4, 1.0, fraction),
2204 [name_ setColor:black];
2205 [description_ setColor:gray];
2206 [source_ setColor:black];
2209 - (void) setSelected:(BOOL)selected {
2210 [self _setSelected:(selected ? 1.0 : 0.0)];
2211 [super setSelected:selected];
2214 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
2216 [self _setSelected:(selected ? 1.0 : 0.0)];
2217 [super setSelected:selected withFade:fade];
2220 - (void) _setSelectionFadeFraction:(float)fraction {
2221 [self _setSelected:fraction];
2222 [super _setSelectionFadeFraction:fraction];
2227 /* Section Cell {{{ */
2228 @interface SectionCell : UITableCell {
2230 UITextLabel *count_;
2234 - (void) setSection:(Section *)section;
2236 - (void) _setSelected:(float)fraction;
2237 - (void) setSelected:(BOOL)selected;
2238 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade;
2239 - (void) _setSelectionFadeFraction:(float)fraction;
2243 @implementation SectionCell
2252 if ((self = [super init]) != nil) {
2253 GSFontRef bold = GSFontCreateWithName("Helvetica", kGSFontTraitBold, 22);
2254 GSFontRef small = GSFontCreateWithName("Helvetica", kGSFontTraitBold, 12);
2256 name_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 9, 250, 25)];
2257 [name_ setBackgroundColor:Clear_];
2258 [name_ setFont:bold];
2260 count_ = [[UITextLabel alloc] initWithFrame:CGRectMake(11, 7, 29, 32)];
2261 [count_ setCentersHorizontally:YES];
2262 [count_ setBackgroundColor:Clear_];
2263 [count_ setFont:small];
2264 [count_ setColor:White_];
2266 UIImageView *folder = [[[UIImageView alloc] initWithFrame:CGRectMake(8, 7, 32, 32)] autorelease];
2267 [folder setImage:[UIImage applicationImageNamed:@"folder.png"]];
2269 [self addSubview:folder];
2270 [self addSubview:name_];
2271 [self addSubview:count_];
2273 [self _setSelected:0];
2280 - (void) setSection:(Section *)section {
2281 if (section == nil) {
2282 [name_ setText:@"All Packages"];
2283 [count_ setText:nil];
2285 NSString *name = [section name];
2286 [name_ setText:(name == nil ? @"(No Section)" : name)];
2287 [count_ setText:[NSString stringWithFormat:@"%d", [section count]]];
2291 - (void) _setSelected:(float)fraction {
2292 CGColor black(space_,
2293 Interpolate(0.0, 1.0, fraction),
2294 Interpolate(0.0, 1.0, fraction),
2295 Interpolate(0.0, 1.0, fraction),
2298 [name_ setColor:black];
2301 - (void) setSelected:(BOOL)selected {
2302 [self _setSelected:(selected ? 1.0 : 0.0)];
2303 [super setSelected:selected];
2306 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
2308 [self _setSelected:(selected ? 1.0 : 0.0)];
2309 [super setSelected:selected withFade:fade];
2312 - (void) _setSelectionFadeFraction:(float)fraction {
2313 [self _setSelected:fraction];
2314 [super _setSelectionFadeFraction:fraction];
2320 /* File Table {{{ */
2321 @interface FileTable : RVPage {
2322 _transient Database *database_;
2325 NSMutableArray *files_;
2329 - (id) initWithBook:(RVBook *)book database:(Database *)database;
2330 - (void) setPackage:(Package *)package;
2334 @implementation FileTable
2337 if (package_ != nil)
2346 - (int) numberOfRowsInTable:(UITable *)table {
2347 return files_ == nil ? 0 : [files_ count];
2350 - (float) table:(UITable *)table heightForRow:(int)row {
2354 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
2355 if (reusing == nil) {
2356 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
2357 GSFontRef font = GSFontCreateWithName("Helvetica", kGSFontTraitNone, 16);
2358 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
2361 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
2365 - (BOOL) canSelectRow:(int)row {
2369 - (id) initWithBook:(RVBook *)book database:(Database *)database {
2370 if ((self = [super initWithBook:book]) != nil) {
2371 database_ = database;
2373 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
2375 list_ = [[UITable alloc] initWithFrame:[self bounds]];
2376 [self addSubview:list_];
2378 UITableColumn *column = [[[UITableColumn alloc]
2379 initWithTitle:@"Name"
2381 width:[self frame].size.width
2384 [list_ setDataSource:self];
2385 [list_ setSeparatorStyle:1];
2386 [list_ addTableColumn:column];
2387 [list_ setDelegate:self];
2388 [list_ setReusesTableCells:YES];
2392 - (void) setPackage:(Package *)package {
2393 if (package_ != nil) {
2394 [package_ autorelease];
2403 [files_ removeAllObjects];
2405 if (package != nil) {
2406 package_ = [package retain];
2407 name_ = [[package id] retain];
2409 NSString *list = [NSString
2410 stringWithContentsOfFile:[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", name_]
2411 encoding:kCFStringEncodingUTF8
2416 [files_ addObjectsFromArray:[list componentsSeparatedByString:@"\n"]];
2417 [files_ removeLastObject];
2418 [files_ removeObjectAtIndex:0];
2419 [files_ sortUsingSelector:@selector(compareByPath:)];
2421 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
2422 [stack addObject:@"/"];
2424 for (int i(0), e([files_ count]); i != e; ++i) {
2425 NSString *file = [files_ objectAtIndex:i];
2426 while (![file hasPrefix:[stack lastObject]])
2427 [stack removeLastObject];
2428 NSString *directory = [stack lastObject];
2429 [stack addObject:[file stringByAppendingString:@"/"]];
2430 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
2431 ([stack count] - 2) * 3, "",
2432 [file substringFromIndex:[directory length]]
2441 - (void) resetViewAnimated:(BOOL)animated {
2442 [list_ resetViewAnimated:animated];
2445 - (void) reloadData {
2446 [self setPackage:[database_ packageWithName:name_]];
2447 [self reloadButtons];
2450 - (NSString *) title {
2451 return @"Installed Files";
2454 - (NSString *) backButtonTitle {
2460 /* Package View {{{ */
2461 @protocol PackageViewDelegate
2462 - (void) performPackage:(Package *)package;
2465 @interface PackageView : RVPage {
2466 _transient Database *database_;
2467 UIPreferencesTable *table_;
2470 UITextView *description_;
2473 - (id) initWithBook:(RVBook *)book database:(Database *)database;
2474 - (void) setPackage:(Package *)package;
2478 @implementation PackageView
2481 [table_ setDataSource:nil];
2482 [table_ setDelegate:nil];
2484 if (package_ != nil)
2488 if (description_ != nil)
2489 [description_ release];
2494 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
2496 if ([package_ installed] != nil)
2498 if ([package_ source] != nil)
2503 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
2506 else if ([package_ installed] != nil && group-- == 0)
2507 return @"Installed Package";
2508 else if (group-- == 0)
2509 return @"Package Details";
2510 else if ([package_ source] != nil && group-- == 0)
2511 return @"Source Information";
2512 else _assert(false);
2515 - (float) preferencesTable:(UIPreferencesTable *)table heightForRow:(int)row inGroup:(int)group withProposedHeight:(float)proposed {
2516 if (group != 0 || row != 1)
2519 return [description_ visibleTextRect].size.height + TextViewOffset_;
2522 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
2525 if ([package_ website] != nil)
2527 if ([[package_ source] trusted])
2530 } else if ([package_ installed] != nil && group-- == 0)
2532 else if (group-- == 0) {
2534 if ([package_ relationships] != nil)
2537 } else if ([package_ source] != nil && group-- == 0) {
2538 Source *source = [package_ source];
2539 NSString *description = [source description];
2541 if (description != nil && ![description isEqualToString:[source label]])
2544 } else _assert(false);
2547 - (UIPreferencesTableCell *) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
2548 UIPreferencesTableCell *cell = [[[UIPreferencesTableCell alloc] init] autorelease];
2549 [cell setShowSelection:NO];
2553 [cell setTitle:[package_ name]];
2554 [cell setValue:[package_ latest]];
2555 } else if (row-- == 0) {
2556 [cell addSubview:description_];
2557 } else if ([package_ website] != nil && row-- == 0) {
2558 [cell setTitle:@"More Information"];
2559 [cell setShowDisclosure:YES];
2560 [cell setShowSelection:YES];
2561 } else if ([[package_ source] trusted] && row-- == 0) {
2562 [cell setIcon:[UIImage applicationImageNamed:@"trusted.png"]];
2563 [cell setValue:@"This package has been signed."];
2564 } else _assert(false);
2565 } else if ([package_ installed] != nil && group-- == 0) {
2567 [cell setTitle:@"Version"];
2568 NSString *installed([package_ installed]);
2569 [cell setValue:(installed == nil ? @"n/a" : installed)];
2570 } else if (row-- == 0) {
2571 [cell setTitle:@"Filesystem Content"];
2572 [cell setShowDisclosure:YES];
2573 [cell setShowSelection:YES];
2574 } else _assert(false);
2575 } else if (group-- == 0) {
2577 [cell setTitle:@"Identifier"];
2578 [cell setValue:[package_ id]];
2579 } else if (row-- == 0) {
2580 [cell setTitle:@"Section"];
2581 NSString *section([package_ section]);
2582 [cell setValue:(section == nil ? @"n/a" : section)];
2583 } else if (row-- == 0) {
2584 [cell setTitle:@"Expanded Size"];
2585 [cell setValue:SizeString([package_ size])];
2586 } else if (row-- == 0) {
2587 [cell setTitle:@"Maintainer"];
2588 [cell setValue:[[package_ maintainer] name]];
2589 [cell setShowDisclosure:YES];
2590 [cell setShowSelection:YES];
2591 } else if ([package_ relationships] != nil && row-- == 0) {
2592 [cell setTitle:@"Package Relationships"];
2593 [cell setShowDisclosure:YES];
2594 [cell setShowSelection:YES];
2595 } else _assert(false);
2596 } else if ([package_ source] != nil && group-- == 0) {
2597 Source *source = [package_ source];
2598 NSString *description = [source description];
2601 [cell setTitle:[source label]];
2602 [cell setValue:[source version]];
2603 } else if (description != nil && ![description isEqualToString:[source label]] && row-- == 0) {
2604 [cell setValue:description];
2605 } else if (row-- == 0) {
2606 [cell setTitle:@"Origin"];
2607 [cell setValue:[source origin]];
2608 } else _assert(false);
2609 } else _assert(false);
2614 - (BOOL) canSelectRow:(int)row {
2618 - (void) tableRowSelected:(NSNotification *)notification {
2619 int row = [table_ selectedRow];
2620 NSString *website = [package_ website];
2621 BOOL trusted = [[package_ source] trusted];
2622 NSString *installed = [package_ installed];
2625 + (website == nil ? 0 : 1)
2627 + (installed == nil ? 0 : 3)
2629 [delegate_ openURL:[NSURL URLWithString:[NSString stringWithFormat:@"mailto:%@?subject=%@",
2630 [[package_ maintainer] email],
2631 [[NSString stringWithFormat:@"regarding apt package \"%@\"", [package_ name]] stringByAddingPercentEscapes]
2633 else if (installed && row == 5
2634 + (website == nil ? 0 : 1)
2637 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
2638 [files setDelegate:delegate_];
2639 [files setPackage:package_];
2640 [book_ pushPage:files];
2641 } else if (website != nil && row == 3) {
2642 NSURL *url = [NSURL URLWithString:website];
2643 BrowserView *browser = [[[BrowserView alloc] initWithBook:book_ database:database_] autorelease];
2644 [browser setDelegate:delegate_];
2645 [book_ pushPage:browser];
2646 [browser loadURL:url];
2650 - (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
2652 case 1: [delegate_ installPackage:package_]; break;
2653 case 2: [delegate_ removePackage:package_]; break;
2659 - (void) _rightButtonClicked {
2660 if ([package_ installed] == nil)
2661 [delegate_ installPackage:package_];
2663 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:6];
2665 if ([package_ upgradable])
2666 [buttons addObject:@"Upgrade"];
2668 [buttons addObject:@"Reinstall"];
2670 [buttons addObject:@"Remove"];
2671 [buttons addObject:@"Cancel"];
2673 [delegate_ slideUp:[[[UIAlertSheet alloc]
2674 initWithTitle:@"Manage Package"
2676 defaultButtonIndex:2
2683 - (NSString *) rightButtonTitle {
2684 _assert(package_ != nil);
2685 return [package_ installed] == nil ? @"Install" : @"Modify";
2688 - (NSString *) title {
2692 - (id) initWithBook:(RVBook *)book database:(Database *)database {
2693 if ((self = [super initWithBook:book]) != nil) {
2694 database_ = database;
2696 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
2697 [self addSubview:table_];
2699 [table_ setDataSource:self];
2700 [table_ setDelegate:self];
2704 - (void) setPackage:(Package *)package {
2705 if (package_ != nil) {
2706 [package_ autorelease];
2715 if (description_ != nil) {
2716 [description_ release];
2720 if (package != nil) {
2721 package_ = [package retain];
2722 name_ = [[package id] retain];
2724 NSString *description([package description]);
2725 if (description == nil)
2726 description = [package tagline];
2727 description_ = [GetTextView(description, 12, true) retain];
2729 [description_ setTextColor:Black_];
2731 [table_ reloadData];
2735 - (void) resetViewAnimated:(BOOL)animated {
2736 [table_ resetViewAnimated:animated];
2739 - (void) reloadData {
2740 [self setPackage:[database_ packageWithName:name_]];
2741 [self reloadButtons];
2746 /* Package Table {{{ */
2747 @interface PackageTable : RVPage {
2748 _transient Database *database_;
2752 NSMutableArray *packages_;
2753 NSMutableArray *sections_;
2754 UISectionList *list_;
2757 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
2759 - (void) setDelegate:(id)delegate;
2760 - (void) setObject:(id)object;
2762 - (void) reloadData;
2763 - (void) resetCursor;
2765 - (UISectionList *) list;
2767 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
2771 @implementation PackageTable
2774 [list_ setDataSource:nil];
2779 [packages_ release];
2780 [sections_ release];
2785 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
2786 return [sections_ count];
2789 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
2790 return [[sections_ objectAtIndex:section] name];
2793 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
2794 return [[sections_ objectAtIndex:section] row];
2797 - (int) numberOfRowsInTable:(UITable *)table {
2798 return [packages_ count];
2801 - (float) table:(UITable *)table heightForRow:(int)row {
2805 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
2807 reusing = [[[PackageCell alloc] init] autorelease];
2808 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
2812 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
2816 - (void) tableRowSelected:(NSNotification *)notification {
2817 int row = [[notification object] selectedRow];
2821 Package *package = [packages_ objectAtIndex:row];
2822 PackageView *view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
2823 [view setDelegate:delegate_];
2824 [view setPackage:package];
2825 [book_ pushPage:view];
2828 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
2829 if ((self = [super initWithBook:book]) != nil) {
2830 database_ = database;
2831 title_ = [title retain];
2833 object_ = object == nil ? nil : [object retain];
2835 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
2836 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
2838 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
2839 [list_ setDataSource:self];
2841 UITableColumn *column = [[[UITableColumn alloc]
2842 initWithTitle:@"Name"
2844 width:[self frame].size.width
2847 UITable *table = [list_ table];
2848 [table setSeparatorStyle:1];
2849 [table addTableColumn:column];
2850 [table setDelegate:self];
2851 [table setReusesTableCells:YES];
2853 [self addSubview:list_];
2858 - (void) setDelegate:(id)delegate {
2859 delegate_ = delegate;
2862 - (void) setObject:(id)object {
2868 object_ = [object retain];
2871 - (void) reloadData {
2872 NSArray *packages = [database_ packages];
2874 [packages_ removeAllObjects];
2875 [sections_ removeAllObjects];
2877 for (size_t i(0); i != [packages count]; ++i) {
2878 Package *package([packages objectAtIndex:i]);
2879 if ([[package performSelector:filter_ withObject:object_] boolValue])
2880 [packages_ addObject:package];
2883 Section *section = nil;
2885 for (size_t offset(0); offset != [packages_ count]; ++offset) {
2886 Package *package = [packages_ objectAtIndex:offset];
2887 NSString *name = [package index];
2889 if (section == nil || ![[section name] isEqualToString:name]) {
2890 section = [[[Section alloc] initWithName:name row:offset] autorelease];
2891 [sections_ addObject:section];
2894 [section addToCount];
2900 - (NSString *) title {
2904 - (void) resetViewAnimated:(BOOL)animated {
2905 [list_ resetViewAnimated:animated];
2908 - (void) resetCursor {
2909 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
2912 - (UISectionList *) list {
2916 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
2917 [list_ setShouldHideHeaderInShortLists:hide];
2923 /* Browser Implementation {{{ */
2924 @implementation BrowserView
2927 WebView *webview = [webview_ webView];
2928 [webview setFrameLoadDelegate:nil];
2929 [webview setResourceLoadDelegate:nil];
2930 [webview setUIDelegate:nil];
2932 [scroller_ setDelegate:nil];
2933 [webview_ setDelegate:nil];
2935 [scroller_ release];
2938 [indicator_ release];
2944 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
2945 NSMutableURLRequest *request = [NSMutableURLRequest
2948 timeoutInterval:30.0
2951 [request addValue:[NSString stringWithUTF8String:Firmware_] forHTTPHeaderField:@"X-Firmware"];
2952 [request addValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
2953 [request addValue:[NSString stringWithUTF8String:SerialNumber_] forHTTPHeaderField:@"X-Serial-Number"];
2955 [self loadRequest:request];
2959 - (void) loadURL:(NSURL *)url {
2960 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
2963 // XXX: this needs to add the headers
2964 - (NSURLRequest *) _addHeadersToRequest:(NSURLRequest *)request {
2968 - (void) loadRequest:(NSURLRequest *)request {
2969 [webview_ loadRequest:request];
2972 - (void) reloadURL {
2973 NSURL *url = [[[urls_ lastObject] retain] autorelease];
2974 [urls_ removeLastObject];
2975 [self loadURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData];
2978 - (WebView *) webView {
2979 return [webview_ webView];
2982 - (void) view:(UIView *)sender didSetFrame:(CGRect)frame {
2983 [scroller_ setContentSize:frame.size];
2986 - (void) view:(UIView *)sender didSetFrame:(CGRect)frame oldFrame:(CGRect)old {
2987 [self view:sender didSetFrame:frame];
2990 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)dataSource {
2991 return [self _addHeadersToRequest:request];
2994 - (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request {
2995 if ([[[request URL] scheme] isEqualToString:@"apptapp"])
2997 [self setBackButtonTitle:title_];
2998 BrowserView *browser = [[[BrowserView alloc] initWithBook:book_ database:database_] autorelease];
2999 [browser setDelegate:delegate_];
3000 [book_ pushPage:browser];
3001 [browser loadRequest:[self _addHeadersToRequest:request]];
3002 return [browser webView];
3005 - (void) webView:(WebView *)sender willClickElement:(id)element {
3006 if (![element respondsToSelector:@selector(href)])
3008 NSString *href = [element href];
3011 if ([href hasPrefix:@"apptapp://package/"]) {
3012 NSString *name = [href substringFromIndex:18];
3013 Package *package = [database_ packageWithName:name];
3014 if (package == nil) {
3015 UIAlertSheet *sheet = [[[UIAlertSheet alloc]
3016 initWithTitle:@"Cannot Locate Package"
3017 buttons:[NSArray arrayWithObjects:@"Close", nil]
3018 defaultButtonIndex:0
3023 [sheet setBodyText:[NSString stringWithFormat:
3024 @"The package %@ cannot be found in your current sources. I might recommend installing more sources."
3027 [sheet popupAlertAnimated:YES];
3029 [self setBackButtonTitle:title_];
3030 PackageView *view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
3031 [view setDelegate:delegate_];
3032 [view setPackage:package];
3033 [book_ pushPage:view];
3038 - (void) webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
3039 title_ = [title retain];
3040 [self setTitle:title];
3043 - (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
3044 if ([frame parentFrame] != nil)
3049 [indicator_ startAnimation];
3050 [self reloadButtons];
3052 if (title_ != nil) {
3057 [self setTitle:@"Loading..."];
3059 WebView *webview = [webview_ webView];
3060 NSString *href = [webview mainFrameURL];
3061 [urls_ addObject:[NSURL URLWithString:href]];
3063 CGRect webrect = [scroller_ frame];
3064 webrect.size.height = 0;
3065 [webview_ setFrame:webrect];
3068 - (void) _finishLoading {
3071 [indicator_ stopAnimation];
3072 [self reloadButtons];
3076 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
3077 if ([frame parentFrame] != nil)
3079 [self _finishLoading];
3082 - (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
3083 if ([frame parentFrame] != nil)
3085 [self setTitle:[error localizedDescription]];
3086 [self _finishLoading];
3089 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3090 if ((self = [super initWithBook:book]) != nil) {
3091 database_ = database;
3094 struct CGRect bounds = [self bounds];
3096 UIImageView *pinstripe = [[[UIImageView alloc] initWithFrame:bounds] autorelease];
3097 [pinstripe setImage:[UIImage applicationImageNamed:@"pinstripe.png"]];
3098 [self addSubview:pinstripe];
3100 scroller_ = [[UIScroller alloc] initWithFrame:bounds];
3101 [self addSubview:scroller_];
3103 [scroller_ setScrollingEnabled:YES];
3104 [scroller_ setAdjustForContentSizeChange:YES];
3105 [scroller_ setClipsSubviews:YES];
3106 [scroller_ setAllowsRubberBanding:YES];
3107 [scroller_ setScrollDecelerationFactor:0.99];
3108 [scroller_ setDelegate:self];
3110 CGRect webrect = [scroller_ bounds];
3111 webrect.size.height = 0;
3113 webview_ = [[UIWebView alloc] initWithFrame:webrect];
3114 [scroller_ addSubview:webview_];
3116 [webview_ setTilingEnabled:YES];
3117 [webview_ setTileSize:CGSizeMake(webrect.size.width, 500)];
3118 [webview_ setAutoresizes:YES];
3119 [webview_ setDelegate:self];
3120 //[webview_ setEnabledGestures:2];
3122 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:0];
3123 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(281, 42, indsize.width, indsize.height)];
3124 [indicator_ setStyle:0];
3126 Package *package([database_ packageWithName:@"cydia"]);
3127 NSString *application = package == nil ? @"Cydia" : [NSString
3128 stringWithFormat:@"Cydia/%@",
3132 WebView *webview = [webview_ webView];
3133 [webview setApplicationNameForUserAgent:application];
3134 [webview setFrameLoadDelegate:self];
3135 [webview setResourceLoadDelegate:self];
3136 [webview setUIDelegate:self];
3138 urls_ = [[NSMutableArray alloc] initWithCapacity:16];
3142 - (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
3146 - (void) _leftButtonClicked {
3147 UIAlertSheet *sheet = [[[UIAlertSheet alloc]
3148 initWithTitle:@"About Cydia Packager"
3149 buttons:[NSArray arrayWithObjects:@"Close", nil]
3150 defaultButtonIndex:0
3156 @"Copyright (C) 2008\n"
3157 "Jay Freeman (saurik)\n"
3158 "saurik@saurik.com\n"
3159 "http://www.saurik.com/\n"
3162 "http://www.theokorigroup.com/\n"
3164 "College of Creative Studies,\n"
3165 "University of California,\n"
3167 "http://www.ccs.ucsb.edu/"
3170 [sheet popupAlertAnimated:YES];
3173 - (void) _rightButtonClicked {
3178 - (NSString *) leftButtonTitle {
3182 - (NSString *) rightButtonTitle {
3183 return loading_ ? @"" : @"Reload";
3186 - (NSString *) title {
3190 - (NSString *) backButtonTitle {
3194 - (void) setPageActive:(BOOL)active {
3196 [book_ addSubview:indicator_];
3198 [indicator_ removeFromSuperview];
3201 - (void) resetViewAnimated:(BOOL)animated {
3207 @interface CYBook : RVBook <
3210 _transient Database *database_;
3212 UIProgressIndicator *indicator_;
3213 UITextLabel *prompt_;
3214 UIProgressBar *progress_;
3218 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
3224 /* Install View {{{ */
3225 @interface InstallView : RVPage {
3226 _transient Database *database_;
3227 NSMutableArray *packages_;
3228 NSMutableArray *sections_;
3233 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3234 - (void) reloadData;
3238 @implementation InstallView
3241 [list_ setDataSource:nil];
3242 [list_ setDelegate:nil];
3244 [packages_ release];
3245 [sections_ release];
3247 [accessory_ release];
3251 - (int) numberOfRowsInTable:(UITable *)table {
3252 return [sections_ count] + 1;
3255 - (float) table:(UITable *)table heightForRow:(int)row {
3259 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
3261 reusing = [[[SectionCell alloc] init] autorelease];
3262 [(SectionCell *)reusing setSection:(row == 0 ? nil : [sections_ objectAtIndex:(row - 1)])];
3266 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
3270 - (void) tableRowSelected:(NSNotification *)notification {
3271 int row = [[notification object] selectedRow];
3280 title = @"All Packages";
3282 section = [sections_ objectAtIndex:(row - 1)];
3283 title = [section name];
3286 PackageTable *table = [[[PackageTable alloc]
3290 filter:@selector(isUninstalledInSection:)
3291 with:(section == nil ? nil : [section name])
3294 [table setDelegate:delegate_];
3296 [book_ pushPage:table];
3299 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3300 if ((self = [super initWithBook:book]) != nil) {
3301 database_ = database;
3303 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
3304 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
3306 list_ = [[UITable alloc] initWithFrame:[self bounds]];
3307 [self addSubview:list_];
3309 UITableColumn *column = [[[UITableColumn alloc]
3310 initWithTitle:@"Name"
3312 width:[self frame].size.width
3315 [list_ setDataSource:self];
3316 [list_ setSeparatorStyle:1];
3317 [list_ addTableColumn:column];
3318 [list_ setDelegate:self];
3319 [list_ setReusesTableCells:YES];
3325 - (void) reloadData {
3326 NSArray *packages = [database_ packages];
3328 [packages_ removeAllObjects];
3329 [sections_ removeAllObjects];
3331 for (size_t i(0); i != [packages count]; ++i) {
3332 Package *package([packages objectAtIndex:i]);
3333 if ([package installed] == nil)
3334 [packages_ addObject:package];
3337 [packages_ sortUsingSelector:@selector(compareBySection:)];
3339 Section *section = nil;
3340 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
3341 Package *package = [packages_ objectAtIndex:offset];
3342 NSString *name = [package section];
3344 if (section == nil || name != nil && ![[section name] isEqualToString:name]) {
3345 section = [[[Section alloc] initWithName:name row:offset] autorelease];
3346 [sections_ addObject:section];
3349 [section addToCount];
3355 - (void) resetViewAnimated:(BOOL)animated {
3356 [list_ resetViewAnimated:animated];
3359 - (NSString *) title {
3363 - (NSString *) backButtonTitle {
3367 - (UIView *) accessoryView {
3373 /* Changes View {{{ */
3374 @interface ChangesView : RVPage {
3375 _transient Database *database_;
3376 NSMutableArray *packages_;
3377 NSMutableArray *sections_;
3378 UISectionList *list_;
3382 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3383 - (void) reloadData;
3387 @implementation ChangesView
3390 [[list_ table] setDelegate:nil];
3391 [list_ setDataSource:nil];
3393 [packages_ release];
3394 [sections_ release];
3399 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
3400 return [sections_ count];
3403 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
3404 return [[sections_ objectAtIndex:section] name];
3407 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
3408 return [[sections_ objectAtIndex:section] row];
3411 - (int) numberOfRowsInTable:(UITable *)table {
3412 return [packages_ count];
3415 - (float) table:(UITable *)table heightForRow:(int)row {
3419 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
3421 reusing = [[[PackageCell alloc] init] autorelease];
3422 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
3426 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
3430 - (void) tableRowSelected:(NSNotification *)notification {
3431 int row = [[notification object] selectedRow];
3434 Package *package = [packages_ objectAtIndex:row];
3435 PackageView *view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
3436 [view setDelegate:delegate_];
3437 [view setPackage:package];
3438 [book_ pushPage:view];
3441 - (void) _leftButtonClicked {
3442 [(CYBook *)book_ update];
3443 [self reloadButtons];
3446 - (void) _rightButtonClicked {
3447 [delegate_ distUpgrade];
3450 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3451 if ((self = [super initWithBook:book]) != nil) {
3452 database_ = database;
3454 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
3455 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
3457 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
3458 [self addSubview:list_];
3460 [list_ setShouldHideHeaderInShortLists:NO];
3461 [list_ setDataSource:self];
3462 //[list_ setSectionListStyle:1];
3464 UITableColumn *column = [[[UITableColumn alloc]
3465 initWithTitle:@"Name"
3467 width:[self frame].size.width
3470 UITable *table = [list_ table];
3471 [table setSeparatorStyle:1];
3472 [table addTableColumn:column];
3473 [table setDelegate:self];
3474 [table setReusesTableCells:YES];
3480 - (void) reloadData {
3481 NSArray *packages = [database_ packages];
3483 [packages_ removeAllObjects];
3484 [sections_ removeAllObjects];
3486 for (size_t i(0); i != [packages count]; ++i) {
3487 Package *package([packages objectAtIndex:i]);
3488 if ([package installed] == nil || [package upgradable])
3489 [packages_ addObject:package];
3492 [packages_ sortUsingSelector:@selector(compareForChanges:)];
3494 Section *upgradable = [[[Section alloc] initWithName:@"Available Upgrades" row:0] autorelease];
3495 Section *section = nil;
3498 bool unseens = false;
3500 CFLocaleRef locale = CFLocaleCopyCurrent();
3501 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, locale, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
3503 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
3504 Package *package = [packages_ objectAtIndex:offset];
3506 if ([package upgradable]) {
3508 [upgradable addToCount];
3511 NSDate *seen = [package seen];
3516 name = [@"n/a ?" retain];
3518 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
3521 if (section == nil || ![[section name] isEqualToString:name]) {
3522 section = [[[Section alloc] initWithName:name row:offset] autorelease];
3523 [sections_ addObject:section];
3527 [section addToCount];
3531 CFRelease(formatter);
3535 Section *last = [sections_ lastObject];
3536 size_t count = [last count];
3537 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
3538 [sections_ removeLastObject];
3542 [sections_ insertObject:upgradable atIndex:0];
3545 [self reloadButtons];
3548 - (void) resetViewAnimated:(BOOL)animated {
3549 [list_ resetViewAnimated:animated];
3552 - (NSString *) leftButtonTitle {
3553 return [(CYBook *)book_ updating] ? nil : @"Refresh";
3556 - (NSString *) rightButtonTitle {
3557 return upgrades_ == 0 ? nil : [NSString stringWithFormat:@"Upgrade All (%u)", upgrades_];
3560 - (NSString *) title {
3566 /* Manage View {{{ */
3567 @interface ManageView : PackageTable {
3570 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3574 @implementation ManageView
3576 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3581 filter:@selector(isInstalledInSection:)
3587 - (NSString *) title {
3588 return @"Installed Packages";
3591 - (NSString *) backButtonTitle {
3592 return @"All Packages";
3597 /* Search View {{{ */
3598 @protocol SearchViewDelegate
3599 - (void) showKeyboard:(BOOL)show;
3602 @interface SearchView : RVPage {
3604 UISearchField *field_;
3605 UITransitionView *transition_;
3606 PackageTable *table_;
3607 UIPreferencesTable *advanced_;
3613 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3614 - (void) reloadData;
3618 @implementation SearchView
3622 [[field_ textTraits] setEditingDelegate:nil];
3624 [field_ setDelegate:nil];
3626 [accessory_ release];
3628 [transition_ release];
3630 [advanced_ release];
3635 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
3639 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
3641 case 0: return @"Advanced Search (Coming Soon!)";
3643 default: _assert(false);
3647 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
3651 default: _assert(false);
3655 - (void) _showKeyboard:(BOOL)show {
3656 CGSize keysize = [UIKeyboard defaultSize];
3657 CGRect keydown = [book_ pageBounds];
3658 CGRect keyup = keydown;
3659 keyup.size.height -= keysize.height - ButtonBarHeight_;
3661 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
3663 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
3664 [animation setSignificantRectFields:8];
3667 [animation setStartFrame:keydown];
3668 [animation setEndFrame:keyup];
3670 [animation setStartFrame:keyup];
3671 [animation setEndFrame:keydown];
3674 UIAnimator *animator = [UIAnimator sharedAnimator];
3677 addAnimations:[NSArray arrayWithObjects:animation, nil]
3678 withDuration:(KeyboardTime_ - delay)
3683 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
3685 [delegate_ showKeyboard:show];
3688 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
3689 [self _showKeyboard:YES];
3692 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
3693 [self _showKeyboard:NO];
3696 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
3698 NSString *text([field_ text]);
3699 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
3705 - (void) textFieldClearButtonPressed:(UITextField *)field {
3709 - (void) keyboardInputShouldDelete:(id)input {
3713 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
3714 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
3718 [field_ resignFirstResponder];
3723 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3724 if ((self = [super initWithBook:book]) != nil) {
3725 CGRect pageBounds = [book_ pageBounds];
3727 /*UIImageView *pinstripe = [[[UIImageView alloc] initWithFrame:pageBounds] autorelease];
3728 [pinstripe setImage:[UIImage applicationImageNamed:@"pinstripe.png"]];
3729 [self addSubview:pinstripe];*/
3731 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
3732 [self addSubview:transition_];
3734 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
3736 [advanced_ setReusesTableCells:YES];
3737 [advanced_ setDataSource:self];
3738 [advanced_ reloadData];
3740 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
3741 CGColor dimmed(space_, 0, 0, 0, 0.5);
3742 [dimmed_ setBackgroundColor:dimmed];
3744 table_ = [[PackageTable alloc]
3748 filter:@selector(isSearchedForBy:)
3752 [table_ setShouldHideHeaderInShortLists:NO];
3753 [transition_ transition:0 toView:table_];
3755 CGRect cnfrect = {{1, 38}, {17, 18}};
3758 area.origin.x = cnfrect.size.width + 15;
3760 area.size.width = [self bounds].size.width - area.origin.x - 18;
3761 area.size.height = [UISearchField defaultHeight];
3763 field_ = [[UISearchField alloc] initWithFrame:area];
3765 GSFontRef font = GSFontCreateWithName("Helvetica", kGSFontTraitNone, 16);
3766 [field_ setFont:font];
3769 [field_ setPlaceholder:@"Package Names & Descriptions"];
3770 [field_ setPaddingTop:5];
3771 [field_ setDelegate:self];
3774 UITextTraits *traits = [field_ textTraits];
3775 [traits setEditingDelegate:self];
3776 [traits setReturnKeyType:6];
3777 [traits setAutoCapsType:0];
3778 [traits setAutoCorrectionType:1];
3781 UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
3782 [configure setShowPressFeedback:YES];
3783 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
3784 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
3786 accessory_ = [[UIView alloc] initWithFrame:CGRectMake(0, 6, cnfrect.size.width + area.size.width + 6 * 3, area.size.height + 30)];
3787 [accessory_ addSubview:field_];
3788 [accessory_ addSubview:configure];
3793 LKAnimation *animation = [LKTransition animation];
3794 [animation setType:@"oglFlip"];
3795 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
3796 [animation setFillMode:@"extended"];
3797 [animation setTransitionFlags:3];
3798 [animation setDuration:10];
3799 [animation setSpeed:0.35];
3800 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
3801 [[transition_ _layer] addAnimation:animation forKey:0];
3802 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
3803 flipped_ = !flipped_;
3806 - (void) configurePushed {
3807 [field_ resignFirstResponder];
3811 - (void) resetViewAnimated:(BOOL)animated {
3814 [table_ resetViewAnimated:animated];
3817 - (void) reloadData {
3820 [table_ setObject:[field_ text]];
3821 [table_ reloadData];
3822 [table_ resetCursor];
3825 - (UIView *) accessoryView {
3829 - (NSString *) title {
3833 - (NSString *) backButtonTitle {
3837 - (void) setDelegate:(id)delegate {
3838 [table_ setDelegate:delegate];
3839 [super setDelegate:delegate];
3845 @implementation CYBook
3849 [indicator_ release];
3851 [progress_ release];
3855 - (NSString *) getTitleForPage:(RVPage *)page {
3856 return Simplify([super getTitleForPage:page]);
3864 [navbar_ setPrompt:@""];
3865 [navbar_ addSubview:overlay_];
3866 [indicator_ startAnimation];
3867 [prompt_ setText:@"Updating Database..."];
3868 [progress_ setProgress:0];
3873 detachNewThreadSelector:@selector(_update)
3882 [overlay_ removeFromSuperview];
3883 [indicator_ stopAnimation];
3884 [delegate_ reloadData];
3886 [self setPrompt:[NSString stringWithFormat:@"Last Updated: %@", GetLastUpdate()]];
3889 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
3890 if ((self = [super initWithFrame:frame]) != nil) {
3891 database_ = database;
3894 [navbar_ setBarStyle:1];
3896 CGRect ovrrect = [navbar_ bounds];
3897 ovrrect.size.height = [UINavigationBar defaultSizeWithPrompt].height - [UINavigationBar defaultSize].height;
3899 overlay_ = [[UIView alloc] initWithFrame:ovrrect];
3901 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:2];
3902 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
3903 CGRect indrect = {{indoffset, indoffset}, indsize};
3905 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
3906 [indicator_ setStyle:(Advanced_ ? 2 : 3)];
3907 [overlay_ addSubview:indicator_];
3909 CGSize prmsize = {200, indsize.width};
3912 indoffset * 2 + indsize.width,
3913 (ovrrect.size.height - prmsize.height) / 2
3916 GSFontRef font = GSFontCreateWithName("Helvetica", kGSFontTraitNone, 12);
3918 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
3920 [prompt_ setColor:(Advanced_ ? White_ : Black_)];
3921 [prompt_ setBackgroundColor:Clear_];
3922 [prompt_ setFont:font];
3926 [overlay_ addSubview:prompt_];
3928 CGSize prgsize = {75, 100};
3931 ovrrect.size.width - prgsize.width - 10,
3932 (ovrrect.size.height - prgsize.height) / 2
3935 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3936 [progress_ setStyle:0];
3937 [overlay_ addSubview:progress_];
3942 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
3945 status.setDelegate(self);
3947 [database_ updateWithStatus:status];
3950 performSelectorOnMainThread:@selector(_update_)
3958 - (void) setProgressError:(NSString *)error {
3960 performSelectorOnMainThread:@selector(_setProgressError:)
3966 - (void) setProgressTitle:(NSString *)title {
3968 performSelectorOnMainThread:@selector(_setProgressTitle:)
3974 - (void) setProgressPercent:(float)percent {
3977 - (void) addProgressOutput:(NSString *)output {
3979 performSelectorOnMainThread:@selector(_addProgressOutput:)
3985 - (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
3989 - (void) _setProgressError:(NSString *)error {
3990 [prompt_ setText:[NSString stringWithFormat:@"Error: %@", error]];
3993 - (void) _setProgressTitle:(NSString *)title {
3994 [prompt_ setText:[title stringByAppendingString:@"..."]];
3997 - (void) _addProgressOutput:(NSString *)output {
4002 @interface Cydia : UIApplication <
4003 ConfirmationViewDelegate,
4004 ProgressViewDelegate,
4013 UIButtonBar *buttonbar_;
4015 ConfirmationView *confirm_;
4016 NSMutableArray *essential_;
4018 Database *database_;
4019 ProgressView *progress_;
4023 UIKeyboard *keyboard_;
4025 InstallView *install_;
4026 ChangesView *changes_;
4027 ManageView *manage_;
4028 SearchView *search_;
4033 @implementation Cydia
4035 - (void) _reloadData {
4036 /*UIProgressHUD *hud = [[UIProgressHUD alloc] initWithWindow:window_];
4037 [hud setText:@"Reloading Data"];
4038 [overlay_ addSubview:hud];
4041 [database_ reloadData];
4043 if (Packages_ == nil) {
4044 Packages_ = [[NSMutableDictionary alloc] initWithCapacity:128];
4045 [Metadata_ setObject:Packages_ forKey:@"Packages"];
4049 [essential_ removeAllObjects];
4051 NSArray *packages = [database_ packages];
4052 for (int i(0), e([packages count]); i != e; ++i) {
4053 Package *package = [packages objectAtIndex:i];
4054 if ([package upgradable]) {
4055 if ([package essential])
4056 [essential_ addObject:package];
4062 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
4063 [buttonbar_ setBadgeValue:badge forButton:3];
4064 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
4065 [buttonbar_ setBadgeAnimated:YES forButton:3];
4066 [self setApplicationBadge:badge];
4068 [buttonbar_ setBadgeValue:nil forButton:3];
4069 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
4070 [buttonbar_ setBadgeAnimated:NO forButton:3];
4071 [self removeApplicationBadge];
4075 _assert([Metadata_ writeToFile:@"/var/lib/cydia/metadata.plist" atomically:YES] == YES);
4079 /* XXX: this is just stupid */
4081 [install_ reloadData];
4083 [changes_ reloadData];
4085 [manage_ reloadData];
4087 [search_ reloadData];
4093 else if (!Ignored_ && [essential_ count] != 0) {
4094 int count = [essential_ count];
4096 UIAlertSheet *sheet = [[[UIAlertSheet alloc]
4097 initWithTitle:[NSString stringWithFormat:@"%d Essential Upgrade%@", count, (count == 1 ? @"" : @"s")]
4098 buttons:[NSArray arrayWithObjects:@"Upgrade Essential", @"Ignore (Temporary)", nil]
4099 defaultButtonIndex:0
4104 [sheet setBodyText:@"One or more essential packages are currently out of date. If these packages are not upgraded you are likely to encounter errors."];
4105 [sheet popupAlertAnimated:YES];
4109 [hud removeFromSuperview];*/
4112 - (void) reloadData {
4113 @synchronized (self) {
4114 if (confirm_ == nil)
4120 pkgProblemResolver *resolver = [database_ resolver];
4122 resolver->InstallProtect();
4123 if (!resolver->Resolve(true))
4128 [database_ prepare];
4130 if ([database_ cache]->BrokenCount() == 0)
4131 confirm_ = [[ConfirmationView alloc] initWithView:underlay_ database:database_ delegate:self];
4133 NSMutableArray *broken = [NSMutableArray arrayWithCapacity:16];
4134 NSArray *packages = [database_ packages];
4136 for (size_t i(0); i != [packages count]; ++i) {
4137 Package *package = [packages objectAtIndex:i];
4138 if ([package broken])
4139 [broken addObject:[package name]];
4142 UIAlertSheet *sheet = [[[UIAlertSheet alloc]
4143 initWithTitle:[NSString stringWithFormat:@"%d Broken Packages", [database_ cache]->BrokenCount()]
4144 buttons:[NSArray arrayWithObjects:@"Okay", nil]
4145 defaultButtonIndex:0
4150 [sheet setBodyText:[NSString stringWithFormat:@"The following packages have unmet dependencies:\n\n%@", [broken componentsJoinedByString:@"\n"]]];
4151 [sheet popupAlertAnimated:YES];
4157 - (void) installPackage:(Package *)package {
4158 @synchronized (self) {
4165 - (void) removePackage:(Package *)package {
4166 @synchronized (self) {
4173 - (void) distUpgrade {
4174 @synchronized (self) {
4175 [database_ upgrade];
4181 @synchronized (self) {
4189 [overlay_ removeFromSuperview];
4193 detachNewThreadSelector:@selector(perform)
4200 - (void) bootstrap_ {
4202 [database_ upgrade];
4203 [database_ prepare];
4204 [database_ perform];
4207 - (void) bootstrap {
4209 detachNewThreadSelector:@selector(bootstrap_)
4212 title:@"Bootstrap Install..."
4216 - (void) progressViewIsComplete:(ProgressView *)progress {
4217 @synchronized (self) {
4220 if (confirm_ != nil) {
4221 [underlay_ addSubview:overlay_];
4222 [confirm_ removeFromSuperview];
4229 - (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
4230 NSString *context = [sheet context];
4231 if ([context isEqualToString:@"upgrade"])
4234 @synchronized (self) {
4235 for (int i = 0, e = [essential_ count]; i != e; ++i) {
4236 Package *essential = [essential_ objectAtIndex:i];
4237 [essential install];
4249 default: _assert(false);
4255 - (void) setPage:(RVPage *)page {
4256 [page resetViewAnimated:NO];
4257 [page setDelegate:self];
4258 [book_ setPage:page];
4261 - (RVPage *) _setHomePage {
4262 BrowserView *browser = [[[BrowserView alloc] initWithBook:book_ database:database_] autorelease];
4263 [self setPage:browser];
4264 [browser loadURL:[NSURL URLWithString:@"http://cydia.saurik.com/"]];
4268 - (void) buttonBarItemTapped:(id)sender {
4269 unsigned tag = [sender tag];
4271 [book_ resetViewAnimated:YES];
4276 case 1: [self _setHomePage]; break;
4278 case 2: [self setPage:install_]; break;
4279 case 3: [self setPage:changes_]; break;
4280 case 4: [self setPage:manage_]; break;
4281 case 5: [self setPage:search_]; break;
4283 default: _assert(false);
4289 - (void) applicationWillSuspend {
4290 [super applicationWillSuspend];
4293 if (FW_LEAST(1,1,3))
4294 notify_post("com.apple.language.changed");
4296 system("launchctl stop com.apple.SpringBoard");
4299 - (void) applicationDidFinishLaunching:(id)unused {
4300 _assert(pkgInitConfig(*_config));
4301 _assert(pkgInitSystem(*_config, _system));
4306 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
4308 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
4309 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
4311 [window_ orderFront: self];
4312 [window_ makeKey: self];
4313 [window_ _setHidden: NO];
4315 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] delegate:self];
4316 [window_ setContentView:progress_];
4318 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
4319 [progress_ setContentView:underlay_];
4321 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
4324 [underlay_ addSubview:overlay_];
4326 database_ = [[Database alloc] init];
4327 [database_ setDelegate:progress_];
4329 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
4330 0, 0, screenrect.size.width, screenrect.size.height - 48
4331 ) database:database_];
4333 [book_ setDelegate:self];
4335 [overlay_ addSubview:book_];
4337 NSArray *buttonitems = [NSArray arrayWithObjects:
4338 [NSDictionary dictionaryWithObjectsAndKeys:
4339 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
4340 @"home-up.png", kUIButtonBarButtonInfo,
4341 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
4342 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
4343 self, kUIButtonBarButtonTarget,
4344 @"Home", kUIButtonBarButtonTitle,
4345 @"0", kUIButtonBarButtonType,
4348 [NSDictionary dictionaryWithObjectsAndKeys:
4349 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
4350 @"install-up.png", kUIButtonBarButtonInfo,
4351 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
4352 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
4353 self, kUIButtonBarButtonTarget,
4354 @"Install", kUIButtonBarButtonTitle,
4355 @"0", kUIButtonBarButtonType,
4358 [NSDictionary dictionaryWithObjectsAndKeys:
4359 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
4360 @"changes-up.png", kUIButtonBarButtonInfo,
4361 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
4362 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
4363 self, kUIButtonBarButtonTarget,
4364 @"Changes", kUIButtonBarButtonTitle,
4365 @"0", kUIButtonBarButtonType,
4368 [NSDictionary dictionaryWithObjectsAndKeys:
4369 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
4370 @"manage-up.png", kUIButtonBarButtonInfo,
4371 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
4372 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
4373 self, kUIButtonBarButtonTarget,
4374 @"Manage", kUIButtonBarButtonTitle,
4375 @"0", kUIButtonBarButtonType,
4378 [NSDictionary dictionaryWithObjectsAndKeys:
4379 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
4380 @"search-up.png", kUIButtonBarButtonInfo,
4381 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
4382 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
4383 self, kUIButtonBarButtonTarget,
4384 @"Search", kUIButtonBarButtonTitle,
4385 @"0", kUIButtonBarButtonType,
4389 buttonbar_ = [[UIButtonBar alloc]
4391 withFrame:CGRectMake(
4392 0, screenrect.size.height - ButtonBarHeight_,
4393 screenrect.size.width, ButtonBarHeight_
4395 withItemList:buttonitems
4398 [buttonbar_ setDelegate:self];
4399 [buttonbar_ setBarStyle:1];
4400 [buttonbar_ setButtonBarTrackingMode:2];
4402 int buttons[5] = {1, 2, 3, 4, 5};
4403 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
4404 [buttonbar_ showButtonGroup:0 withDuration:0];
4406 for (int i = 0; i != 5; ++i)
4407 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
4408 i * 64 + 2, 1, 60, ButtonBarHeight_
4411 [buttonbar_ showSelectionForButton:1];
4412 [overlay_ addSubview:buttonbar_];
4414 [UIKeyboard initImplementationNow];
4415 CGSize keysize = [UIKeyboard defaultSize];
4416 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
4417 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
4418 [[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
4419 [overlay_ addSubview:keyboard_];
4421 install_ = [[InstallView alloc] initWithBook:book_ database:database_];
4422 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
4423 manage_ = [[ManageView alloc] initWithBook:book_ database:database_];
4424 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
4429 [progress_ resetView];
4434 [self _setHomePage];
4437 - (void) showKeyboard:(BOOL)show {
4438 CGSize keysize = [UIKeyboard defaultSize];
4439 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
4440 CGRect keyup = keydown;
4441 keyup.origin.y -= keysize.height;
4443 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
4444 [animation setSignificantRectFields:2];
4447 [animation setStartFrame:keydown];
4448 [animation setEndFrame:keyup];
4449 [keyboard_ activate];
4451 [animation setStartFrame:keyup];
4452 [animation setEndFrame:keydown];
4453 [keyboard_ deactivate];
4456 [[UIAnimator sharedAnimator]
4457 addAnimations:[NSArray arrayWithObjects:animation, nil]
4458 withDuration:KeyboardTime_
4463 - (void) slideUp:(UIAlertSheet *)alert {
4464 [alert presentSheetFromButtonBar:buttonbar_];
4469 void AddPreferences(NSString *plist) {
4470 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4472 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
4473 _assert(settings != NULL);
4474 NSMutableArray *items = [settings objectForKey:@"items"];
4478 for (size_t i(0); i != [items count]; ++i) {
4479 NSMutableDictionary *item([items objectAtIndex:i]);
4480 NSString *label = [item objectForKey:@"label"];
4481 if (label != nil && [label isEqualToString:@"Cydia"]) {
4488 for (size_t i(0); i != [items count]; ++i) {
4489 NSDictionary *item([items objectAtIndex:i]);
4490 NSString *label = [item objectForKey:@"label"];
4491 if (label != nil && [label isEqualToString:@"General"]) {
4492 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
4493 @"CydiaSettings", @"bundle",
4494 @"PSLinkCell", @"cell",
4495 [NSNumber numberWithBool:YES], @"hasIcon",
4496 [NSNumber numberWithBool:YES], @"isController",
4498 nil] atIndex:(i + 1)];
4504 _assert([settings writeToFile:plist atomically:YES] == YES);
4511 id Alloc_(id self, SEL selector) {
4512 id object = alloc_(self, selector);
4513 fprintf(stderr, "[%s]A-%p\n", self->isa->name, object);
4518 id Dealloc_(id self, SEL selector) {
4519 id object = dealloc_(self, selector);
4520 fprintf(stderr, "[%s]D-%p\n", self->isa->name, object);
4524 int main(int argc, char *argv[]) {
4525 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4527 bootstrap_ = argc > 1 && strcmp(argv[1], "--bootstrap") == 0;
4529 Home_ = NSHomeDirectory();
4532 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
4533 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
4534 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
4535 Sounds_Keyboard_ = [keyboard boolValue];
4541 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
4542 alloc_ = alloc->method_imp;
4543 alloc->method_imp = (IMP) &Alloc_;*/
4545 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
4546 dealloc_ = dealloc->method_imp;
4547 dealloc->method_imp = (IMP) &Dealloc_;*/
4549 if (NSDictionary *sysver = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"]) {
4550 if (NSString *prover = [sysver valueForKey:@"ProductVersion"]) {
4551 Firmware_ = strdup([prover UTF8String]);
4552 NSArray *versions = [prover componentsSeparatedByString:@"."];
4553 int count = [versions count];
4554 Major_ = count > 0 ? [[versions objectAtIndex:0] intValue] : 0;
4555 Minor_ = count > 1 ? [[versions objectAtIndex:1] intValue] : 0;
4556 BugFix_ = count > 2 ? [[versions objectAtIndex:2] intValue] : 0;
4561 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
4562 char *machine = new char[size];
4563 sysctlbyname("hw.machine", machine, &size, NULL, 0);
4566 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice"))
4567 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
4568 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
4569 SerialNumber_ = strdup(CFStringGetCStringPtr((CFStringRef) serial, CFStringGetSystemEncoding()));
4573 IOObjectRelease(service);
4576 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
4577 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
4579 if ((Metadata_ = [[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"]) == NULL)
4580 Metadata_ = [[NSMutableDictionary alloc] initWithCapacity:2];
4582 Packages_ = [Metadata_ objectForKey:@"Packages"];
4584 setenv("CYDIA", "", _not(int));
4585 if (access("/User", F_OK) != 0)
4586 system("/usr/libexec/cydia/firmware.sh");
4587 system("dpkg --configure -a");
4589 space_ = CGColorSpaceCreateDeviceRGB();
4591 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
4592 Clear_.Set(space_, 0.0, 0.0, 0.0, 0.0);
4593 Red_.Set(space_, 1.0, 0.0, 0.0, 1.0);
4594 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
4596 int value = UIApplicationMain(argc, argv, [Cydia class]);
4598 CGColorSpaceRelease(space_);