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 /* Miscellaneous Messages {{{ */
88 @interface NSString (Cydia)
89 - (NSString *) stringByAddingPercentEscapes;
90 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
93 /* iPhoneOS 2.0 Compatibility {{{ */
95 @interface UICGColor : NSObject {
98 - (id) initWithCGColor:(CGColorRef)color;
104 - (UIFont *) fontWithSize:(CGFloat)size;
107 @interface NSObject (iPhoneOS)
108 - (CGColorRef) cgColor;
109 - (CGColorRef) CGColor;
113 @implementation NSObject (iPhoneOS)
115 - (CGColorRef) cgColor {
116 return [self CGColor];
119 - (CGColorRef) CGColor {
120 return (CGColorRef) self;
124 [[[[objc_getClass("UICGColor") alloc] initWithCGColor:[self CGColor]] autorelease] set];
129 @interface UITextView (iPhoneOS)
130 - (void) setTextSize:(float)size;
133 @implementation UITextView (iPhoneOS)
135 - (void) setTextSize:(float)size {
136 [self setFont:[[self font] fontWithSize:size]];
143 /* Perl-Compatible RegEx {{{ */
153 Pcre(const char *regex) :
158 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
161 fprintf(stderr, "%d:%s\n", offset, error);
165 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
166 matches_ = new int[(capture_ + 1) * 3];
174 NSString *operator [](size_t match) {
176 stringWithCString:(data_ + matches_[match * 2])
177 length:(matches_[match * 2 + 1] - matches_[match * 2])
181 bool operator ()(const char *data, size_t size) {
183 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
187 /* Mime Addresses {{{ */
188 Pcre email_r("^\"?(.*)\"? <([^>]*)>$");
190 @interface Address : NSObject {
196 - (NSString *) email;
198 + (Address *) addressWithString:(NSString *)string;
199 - (Address *) initWithString:(NSString *)string;
202 @implementation Address
211 - (NSString *) name {
215 - (NSString *) email {
219 + (Address *) addressWithString:(NSString *)string {
220 return [[[Address alloc] initWithString:string] autorelease];
223 - (Address *) initWithString:(NSString *)string {
224 if ((self = [super init]) != nil) {
225 const char *data = [string UTF8String];
226 size_t size = [string length];
228 if (email_r(data, size)) {
229 name_ = [email_r[1] retain];
230 email_ = [email_r[2] retain];
232 name_ = [[NSString stringWithCString:data length:size] retain];
240 /* CoreGraphics Primitives {{{ */
251 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
254 Set(space, red, green, blue, alpha);
259 CGColorRelease(color_);
266 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
268 float color[] = {red, green, blue, alpha};
269 color_ = CGColorCreate(space, color);
272 operator CGColorRef() {
287 /* Right Alignment {{{ */
288 @interface UIRightTextLabel : UITextLabel {
289 float _savedRightEdgeX;
290 BOOL _sizedtofit_flag;
293 - (void) setFrame:(CGRect)frame;
294 - (void) setText:(NSString *)text;
295 - (void) realignText;
298 @implementation UIRightTextLabel
300 - (void) setFrame:(CGRect)frame {
301 [super setFrame:frame];
302 if (_sizedtofit_flag == NO) {
303 _savedRightEdgeX = frame.origin.x;
308 - (void) setText:(NSString *)text {
309 [super setText:text];
313 - (void) realignText {
314 CGRect oldFrame = [self frame];
316 _sizedtofit_flag = YES;
317 [self sizeToFit]; // shrink down size so I can right align it
319 CGRect newFrame = [self frame];
321 oldFrame.origin.x = _savedRightEdgeX - newFrame.size.width;
322 oldFrame.size.width = newFrame.size.width;
323 [super setFrame:oldFrame];
324 _sizedtofit_flag = NO;
330 /* Random Global Variables {{{ */
331 static const int PulseInterval_ = 50000;
333 static CGColor Black_;
334 static CGColor Clear_;
336 static CGColor White_;
338 static NSString *Home_;
339 static BOOL Sounds_Keyboard_;
341 const char *Firmware_ = NULL;
342 const char *Machine_ = NULL;
343 const char *SerialNumber_ = NULL;
349 CGColorSpaceRef space_;
351 #define FW_LEAST(major, minor, bugfix) \
352 (major < Major_ || major == Major_ && \
353 (minor < Minor_ || minor == Minor_ && \
359 static NSMutableDictionary *Metadata_;
360 static NSMutableDictionary *Packages_;
363 NSString *GetLastUpdate() {
364 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
367 return @"Never or Unknown";
369 CFLocaleRef locale = CFLocaleCopyCurrent();
370 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, locale, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
371 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
373 CFRelease(formatter);
376 return [(NSString *) formatted autorelease];
379 /* Display Helpers {{{ */
380 inline float Interpolate(float begin, float end, float fraction) {
381 return (end - begin) * fraction + begin;
384 NSString *SizeString(double size) {
386 while (size > 1024) {
391 static const char *powers_[] = {"B", "kB", "MB", "GB"};
393 return [NSString stringWithFormat:@"%.1f%s", size, powers_[power]];
396 static const float TextViewOffset_ = 22;
398 UITextView *GetTextView(NSString *value, float left, bool html) {
399 UITextView *text([[[UITextView alloc] initWithFrame:CGRectMake(left, 3, 310 - left, 1000)] autorelease]);
400 [text setEditable:NO];
401 [text setTextSize:16];
403 [text setHTML:value];
405 [text setText:value];
406 [text setEnabled:NO];
408 [text setBackgroundColor:Clear_];
410 CGRect frame = [text frame];
411 [text setFrame:frame];
412 CGRect rect = [text visibleTextRect];
413 frame.size.height = rect.size.height;
414 [text setFrame:frame];
419 NSString *Simplify(NSString *title) {
420 const char *data = [title UTF8String];
421 size_t size = [title length];
423 Pcre title_r("^(.*?)( \\(.*\\))?$");
424 if (title_r(data, size))
431 /* Delegate Prototypes {{{ */
435 @protocol ProgressDelegate
436 - (void) setProgressError:(NSString *)error;
437 - (void) setProgressTitle:(NSString *)title;
438 - (void) setProgressPercent:(float)percent;
439 - (void) addProgressOutput:(NSString *)output;
442 @protocol CydiaDelegate
443 - (void) installPackage:(Package *)package;
444 - (void) removePackage:(Package *)package;
445 - (void) slideUp:(UIAlertSheet *)alert;
446 - (void) distUpgrade;
450 /* Status Delegation {{{ */
452 public pkgAcquireStatus
455 _transient id<ProgressDelegate> delegate_;
463 void setDelegate(id delegate) {
464 delegate_ = delegate;
467 virtual bool MediaChange(std::string media, std::string drive) {
471 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
474 virtual void Fetch(pkgAcquire::ItemDesc &item) {
475 [delegate_ setProgressTitle:[NSString stringWithCString:("Downloading " + item.ShortDesc).c_str()]];
478 virtual void Done(pkgAcquire::ItemDesc &item) {
481 virtual void Fail(pkgAcquire::ItemDesc &item) {
483 item.Owner->Status == pkgAcquire::Item::StatIdle ||
484 item.Owner->Status == pkgAcquire::Item::StatDone
488 [delegate_ setProgressError:[NSString stringWithCString:item.Owner->ErrorText.c_str()]];
491 virtual bool Pulse(pkgAcquire *Owner) {
492 bool value = pkgAcquireStatus::Pulse(Owner);
495 double(CurrentBytes + CurrentItems) /
496 double(TotalBytes + TotalItems)
499 [delegate_ setProgressPercent:percent];
503 virtual void Start() {
506 virtual void Stop() {
510 /* Progress Delegation {{{ */
515 _transient id<ProgressDelegate> delegate_;
518 virtual void Update() {
519 [delegate_ setProgressTitle:[NSString stringWithCString:Op.c_str()]];
520 [delegate_ setProgressPercent:(Percent / 100)];
529 void setDelegate(id delegate) {
530 delegate_ = delegate;
533 virtual void Done() {
534 [delegate_ setProgressPercent:1];
539 /* Database Interface {{{ */
540 @interface Database : NSObject {
542 pkgRecords *records_;
543 pkgProblemResolver *resolver_;
544 pkgAcquire *fetcher_;
546 SPtr<pkgPackageManager> manager_;
547 pkgSourceList *list_;
549 NSMutableDictionary *sources_;
550 NSMutableArray *packages_;
552 _transient id delegate_;
558 - (void) _readStatus:(NSNumber *)fd;
559 - (void) _readOutput:(NSNumber *)fd;
561 - (Package *) packageWithName:(NSString *)name;
564 - (pkgCacheFile &) cache;
565 - (pkgRecords *) records;
566 - (pkgProblemResolver *) resolver;
567 - (pkgAcquire &) fetcher;
568 - (NSArray *) packages;
576 - (void) updateWithStatus:(Status &)status;
578 - (void) setDelegate:(id)delegate;
579 - (Source *) getSource:(const pkgCache::PkgFileIterator &)file;
583 /* Source Class {{{ */
584 @interface Source : NSObject {
585 NSString *description_;
590 NSString *distribution_;
594 NSString *defaultIcon_;
599 - (Source *) initWithMetaIndex:(metaIndex *)index;
604 - (NSString *) distribution;
607 - (NSString *) description;
608 - (NSString *) label;
609 - (NSString *) origin;
610 - (NSString *) version;
612 - (NSString *) defaultIcon;
615 @implementation Source
619 [distribution_ release];
622 if (description_ != nil)
623 [description_ release];
630 if (defaultIcon_ != nil)
631 [defaultIcon_ release];
636 - (Source *) initWithMetaIndex:(metaIndex *)index {
637 if ((self = [super init]) != nil) {
638 trusted_ = index->IsTrusted();
640 uri_ = [[NSString stringWithCString:index->GetURI().c_str()] retain];
641 distribution_ = [[NSString stringWithCString:index->GetDist().c_str()] retain];
642 type_ = [[NSString stringWithCString:index->GetType()] retain];
650 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
651 if (dindex != NULL) {
652 std::ifstream release(dindex->MetaIndexFile("Release").c_str());
654 while (std::getline(release, line)) {
655 std::string::size_type colon(line.find(':'));
656 if (colon == std::string::npos)
659 std::string name(line.substr(0, colon));
660 std::string value(line.substr(colon + 1));
661 while (!value.empty() && value[0] == ' ')
662 value = value.substr(1);
664 if (name == "Default-Icon")
665 defaultIcon_ = [[NSString stringWithCString:value.c_str()] retain];
666 else if (name == "Description")
667 description_ = [[NSString stringWithCString:value.c_str()] retain];
668 else if (name == "Label")
669 label_ = [[NSString stringWithCString:value.c_str()] retain];
670 else if (name == "Origin")
671 origin_ = [[NSString stringWithCString:value.c_str()] retain];
672 else if (name == "Version")
673 version_ = [[NSString stringWithCString:value.c_str()] retain];
687 - (NSString *) distribution {
688 return distribution_;
691 - (NSString *) type {
695 - (NSString *) description {
699 - (NSString *) label {
703 - (NSString *) origin {
707 - (NSString *) version {
711 - (NSString *) defaultIcon {
717 /* Package Class {{{ */
718 NSString *Scour(const char *field, const char *begin, const char *end) {
719 size_t i(0), l(strlen(field));
722 const char *name = begin + i;
723 const char *colon = name + l;
724 const char *value = colon + 1;
729 memcmp(name, field, l) == 0
731 while (value != end && value[0] == ' ')
733 const char *line = std::find(value, end, '\n');
734 while (line != value && line[-1] == ' ')
736 return [NSString stringWithCString:value length:(line - value)];
738 begin = std::find(begin, end, '\n');
746 @interface Package : NSObject {
747 pkgCache::PkgIterator iterator_;
748 _transient Database *database_;
749 pkgCache::VerIterator version_;
750 pkgCache::VerFileIterator file_;
754 NSString *installed_;
763 - (Package *) initWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database version:(pkgCache::VerIterator)version file:(pkgCache::VerFileIterator)file;
764 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database;
766 - (NSString *) section;
767 - (Address *) maintainer;
769 - (NSString *) description;
770 - (NSString *) index;
774 - (NSString *) latest;
775 - (NSString *) installed;
782 - (NSString *) tagline;
784 - (NSString *) website;
788 - (BOOL) matches:(NSString *)text;
790 - (NSComparisonResult) compareByName:(Package *)package;
791 - (NSComparisonResult) compareBySection:(Package *)package;
792 - (NSComparisonResult) compareBySectionAndName:(Package *)package;
793 - (NSComparisonResult) compareForChanges:(Package *)package;
798 - (NSNumber *) isSearchedForBy:(NSString *)search;
799 - (NSNumber *) isInstalledInSection:(NSString *)section;
800 - (NSNumber *) isUninstalledInSection:(NSString *)section;
804 @implementation Package
808 if (installed_ != nil)
809 [installed_ release];
825 - (Package *) initWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database version:(pkgCache::VerIterator)version file:(pkgCache::VerFileIterator)file {
826 if ((self = [super init]) != nil) {
827 iterator_ = iterator;
828 database_ = database;
833 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
835 const char *begin, *end;
836 parser->GetRec(begin, end);
838 latest_ = [[NSString stringWithCString:version_.VerStr()] retain];
839 installed_ = iterator_.CurrentVer().end() ? nil : [[NSString stringWithCString:iterator_.CurrentVer().VerStr()] retain];
841 id_ = [[[NSString stringWithCString:iterator_.Name()] lowercaseString] retain];
842 name_ = Scour("Name", begin, end);
844 name_ = [name_ retain];
845 tagline_ = [[NSString stringWithCString:parser->ShortDesc().c_str()] retain];
846 icon_ = Scour("Icon", begin, end);
848 icon_ = [icon_ retain];
849 website_ = Scour("Website", begin, end);
851 website_ = [website_ retain];
853 source_ = [[database_ getSource:file_.File()] retain];
855 NSMutableDictionary *metadata = [Packages_ objectForKey:id_];
856 if (metadata == nil || [metadata count] == 0) {
857 metadata = [NSMutableDictionary dictionaryWithObjectsAndKeys:
861 [Packages_ setObject:metadata forKey:id_];
866 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database {
867 for (pkgCache::VerIterator version = iterator.VersionList(); !version.end(); ++version)
868 for (pkgCache::VerFileIterator file = version.FileList(); !file.end(); ++file)
869 return [[[Package alloc]
870 initWithIterator:iterator
878 - (NSString *) section {
879 const char *section = iterator_.Section();
880 return section == NULL ? nil : [[NSString stringWithCString:section] stringByReplacingCharacter:'_' withCharacter:' '];
883 - (Address *) maintainer {
884 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
885 return [Address addressWithString:[NSString stringWithCString:parser->Maintainer().c_str()]];
889 return version_->InstalledSize;
892 - (NSString *) description {
893 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
894 NSString *description([NSString stringWithCString:parser->LongDesc().c_str()]);
896 NSArray *lines = [description componentsSeparatedByString:@"\n"];
897 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
898 if ([lines count] < 2)
901 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
902 for (size_t i(1); i != [lines count]; ++i) {
903 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
904 [trimmed addObject:trim];
907 return [trimmed componentsJoinedByString:@"\n"];
910 - (NSString *) index {
911 NSString *index = [[[self name] substringToIndex:1] uppercaseString];
912 return [index length] != 0 && isalpha([index characterAtIndex:0]) ? index : @"123";
916 return [[Packages_ objectForKey:id_] objectForKey:@"FirstSeen"];
919 - (NSString *) latest {
923 - (NSString *) installed {
927 - (BOOL) upgradable {
928 if (NSString *installed = [self installed])
929 return [[self latest] compare:installed] != NSOrderedSame ? YES : NO;
931 return [self essential];
935 return (iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES;
939 return (*[database_ cache])[iterator_].InstBroken();
946 - (NSString *) name {
947 return name_ == nil ? id_ : name_;
950 - (NSString *) tagline {
954 - (NSString *) icon {
958 - (NSString *) website {
962 - (Source *) source {
966 - (BOOL) matches:(NSString *)text {
972 range = [[self id] rangeOfString:text options:NSCaseInsensitiveSearch];
973 if (range.location != NSNotFound)
976 range = [[self name] rangeOfString:text options:NSCaseInsensitiveSearch];
977 if (range.location != NSNotFound)
980 range = [[self tagline] rangeOfString:text options:NSCaseInsensitiveSearch];
981 if (range.location != NSNotFound)
987 - (NSComparisonResult) compareByName:(Package *)package {
988 NSString *lhs = [self name];
989 NSString *rhs = [package name];
991 if ([lhs length] != 0 && [rhs length] != 0) {
992 unichar lhc = [lhs characterAtIndex:0];
993 unichar rhc = [rhs characterAtIndex:0];
995 if (isalpha(lhc) && !isalpha(rhc))
996 return NSOrderedAscending;
997 else if (!isalpha(lhc) && isalpha(rhc))
998 return NSOrderedDescending;
1001 return [lhs caseInsensitiveCompare:rhs];
1004 - (NSComparisonResult) compareBySection:(Package *)package {
1005 NSString *lhs = [self section];
1006 NSString *rhs = [package section];
1008 if (lhs == NULL && rhs != NULL)
1009 return NSOrderedAscending;
1010 else if (lhs != NULL && rhs == NULL)
1011 return NSOrderedDescending;
1012 else if (lhs != NULL && rhs != NULL) {
1013 NSComparisonResult result = [lhs caseInsensitiveCompare:rhs];
1014 if (result != NSOrderedSame)
1018 return NSOrderedSame;
1021 - (NSComparisonResult) compareBySectionAndName:(Package *)package {
1022 NSString *lhs = [self section];
1023 NSString *rhs = [package section];
1025 if (lhs == NULL && rhs != NULL)
1026 return NSOrderedAscending;
1027 else if (lhs != NULL && rhs == NULL)
1028 return NSOrderedDescending;
1029 else if (lhs != NULL && rhs != NULL) {
1030 NSComparisonResult result = [lhs compare:rhs];
1031 if (result != NSOrderedSame)
1035 return [self compareByName:package];
1038 - (NSComparisonResult) compareForChanges:(Package *)package {
1039 BOOL lhs = [self upgradable];
1040 BOOL rhs = [package upgradable];
1043 return lhs ? NSOrderedAscending : NSOrderedDescending;
1045 switch ([[self seen] compare:[package seen]]) {
1046 case NSOrderedAscending:
1047 return NSOrderedDescending;
1050 case NSOrderedDescending:
1051 return NSOrderedAscending;
1057 return [self compareByName:package];
1061 pkgProblemResolver *resolver = [database_ resolver];
1062 resolver->Clear(iterator_);
1063 resolver->Protect(iterator_);
1064 pkgCacheFile &cache([database_ cache]);
1065 cache->MarkInstall(iterator_, false);
1066 pkgDepCache::StateCache &state((*cache)[iterator_]);
1067 if (!state.Install())
1068 cache->SetReInstall(iterator_, true);
1072 pkgProblemResolver *resolver = [database_ resolver];
1073 resolver->Clear(iterator_);
1074 resolver->Protect(iterator_);
1075 resolver->Remove(iterator_);
1076 [database_ cache]->MarkDelete(iterator_, true);
1079 - (NSNumber *) isSearchedForBy:(NSString *)search {
1080 return [NSNumber numberWithBool:[self matches:search]];
1083 - (NSNumber *) isInstalledInSection:(NSString *)section {
1084 return [NSNumber numberWithBool:([self installed] != nil && (section == nil || [section isEqualToString:[self section]]))];
1087 - (NSNumber *) isUninstalledInSection:(NSString *)section {
1088 return [NSNumber numberWithBool:([self installed] == nil && (section == nil || [section isEqualToString:[self section]]))];
1093 /* Section Class {{{ */
1094 @interface Section : NSObject {
1100 - (Section *) initWithName:(NSString *)name row:(size_t)row;
1101 - (NSString *) name;
1104 - (void) addToCount;
1108 @implementation Section
1115 - (Section *) initWithName:(NSString *)name row:(size_t)row {
1116 if ((self = [super init]) != nil) {
1117 name_ = [name retain];
1122 - (NSString *) name {
1134 - (void) addToCount {
1141 /* Database Implementation {{{ */
1142 @implementation Database
1149 - (void) _readStatus:(NSNumber *)fd {
1150 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1152 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
1153 std::istream is(&ib);
1158 pcre *code = pcre_compile("^([^:]*):([^:]*):([^:]*):(.*)$", 0, &error, &offset, NULL);
1160 pcre_extra *study = NULL;
1162 pcre_fullinfo(code, study, PCRE_INFO_CAPTURECOUNT, &capture);
1163 int matches[(capture + 1) * 3];
1165 while (std::getline(is, line)) {
1166 const char *data(line.c_str());
1168 _assert(pcre_exec(code, study, data, line.size(), 0, 0, matches, sizeof(matches) / sizeof(matches[0])) >= 0);
1170 std::istringstream buffer(line.substr(matches[6], matches[7] - matches[6]));
1173 [delegate_ setProgressPercent:(percent / 100)];
1175 NSString *string = [NSString stringWithCString:(data + matches[8]) length:(matches[9] - matches[8])];
1176 std::string type(line.substr(matches[2], matches[3] - matches[2]));
1178 if (type == "pmerror")
1179 [delegate_ setProgressError:string];
1180 else if (type == "pmstatus")
1181 [delegate_ setProgressTitle:string];
1182 else if (type == "pmconffile")
1184 else _assert(false);
1191 - (void) _readOutput:(NSNumber *)fd {
1192 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1194 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
1195 std::istream is(&ib);
1198 while (std::getline(is, line))
1199 [delegate_ addProgressOutput:[NSString stringWithCString:line.c_str()]];
1205 - (Package *) packageWithName:(NSString *)name {
1206 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
1207 return iterator.end() ? nil : [Package packageWithIterator:iterator database:self];
1210 - (Database *) init {
1211 if ((self = [super init]) != nil) {
1217 sources_ = [[NSMutableDictionary dictionaryWithCapacity:16] retain];
1218 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
1222 _assert(pipe(fds) != -1);
1226 detachNewThreadSelector:@selector(_readStatus:)
1228 withObject:[[NSNumber numberWithInt:fds[0]] retain]
1231 _assert(pipe(fds) != -1);
1232 _assert(dup2(fds[1], 1) != -1);
1233 _assert(close(fds[1]) != -1);
1236 detachNewThreadSelector:@selector(_readOutput:)
1238 withObject:[[NSNumber numberWithInt:fds[0]] retain]
1243 - (pkgCacheFile &) cache {
1247 - (pkgRecords *) records {
1251 - (pkgProblemResolver *) resolver {
1255 - (pkgAcquire &) fetcher {
1259 - (NSArray *) packages {
1263 - (void) reloadData {
1273 if (!cache_.Open(progress_, true)) {
1274 fprintf(stderr, "repairing corrupted database...\n");
1276 [self updateWithStatus:status_];
1277 _assert(cache_.Open(progress_, true));
1280 now_ = [[NSDate date] retain];
1282 records_ = new pkgRecords(cache_);
1283 resolver_ = new pkgProblemResolver(cache_);
1284 fetcher_ = new pkgAcquire(&status_);
1287 list_ = new pkgSourceList();
1288 _assert(list_->ReadMainList());
1290 [sources_ removeAllObjects];
1291 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
1292 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
1293 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
1295 setObject:[[[Source alloc] initWithMetaIndex:*source] autorelease]
1296 forKey:[NSNumber numberWithLong:reinterpret_cast<uintptr_t>(*index)]
1300 [packages_ removeAllObjects];
1301 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
1302 if (Package *package = [Package packageWithIterator:iterator database:self])
1303 if ([package source] != nil || [package installed] != nil)
1304 [packages_ addObject:package];
1306 [packages_ sortUsingSelector:@selector(compareByName:)];
1310 pkgRecords records(cache_);
1312 lock_ = new FileFd();
1313 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
1314 _assert(!_error->PendingError());
1317 // XXX: explain this with an error message
1318 _assert(list.ReadMainList());
1320 manager_ = (_system->CreatePM(cache_));
1321 _assert(manager_->GetArchives(fetcher_, &list, &records));
1322 _assert(!_error->PendingError());
1326 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
1328 _assert(list.ReadMainList());
1329 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
1330 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
1333 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue)
1337 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
1339 if (result == pkgPackageManager::Failed)
1341 if (_error->PendingError())
1343 if (result != pkgPackageManager::Completed)
1346 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
1348 _assert(list.ReadMainList());
1349 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
1350 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
1353 if (![before isEqualToArray:after])
1358 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
1359 _assert(pkgApplyStatus(cache_));
1361 if (cache_->BrokenCount() != 0) {
1362 _assert(pkgFixBroken(cache_));
1363 _assert(cache_->BrokenCount() == 0);
1364 _assert(pkgMinimizeUpgrade(cache_));
1367 _assert(pkgDistUpgrade(cache_));
1371 [self updateWithStatus:status_];
1374 - (void) updateWithStatus:(Status &)status {
1376 _assert(list.ReadMainList());
1379 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
1380 _assert(!_error->PendingError());
1382 pkgAcquire fetcher(&status);
1383 _assert(list.GetIndexes(&fetcher));
1385 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
1386 bool failed = false;
1387 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
1388 if ((*item)->Status != pkgAcquire::Item::StatDone) {
1389 (*item)->Finished();
1393 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
1394 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
1395 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
1398 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
1402 - (void) setDelegate:(id)delegate {
1403 delegate_ = delegate;
1404 status_.setDelegate(delegate);
1405 progress_.setDelegate(delegate);
1408 - (Source *) getSource:(const pkgCache::PkgFileIterator &)file {
1409 pkgIndexFile *index(NULL);
1410 list_->FindIndex(file, index);
1411 return [sources_ objectForKey:[NSNumber numberWithLong:reinterpret_cast<uintptr_t>(index)]];
1417 /* Confirmation View {{{ */
1418 void AddTextView(NSMutableDictionary *fields, NSMutableArray *packages, NSString *key) {
1419 if ([packages count] == 0)
1422 UITextView *text = GetTextView([packages count] == 0 ? @"n/a" : [packages componentsJoinedByString:@", "], 120, false);
1423 [fields setObject:text forKey:key];
1425 CGColor blue(space_, 0, 0, 0.4, 1);
1426 [text setTextColor:blue];
1429 @protocol ConfirmationViewDelegate
1434 @interface ConfirmationView : UIView {
1435 Database *database_;
1437 UITransitionView *transition_;
1439 UINavigationBar *navbar_;
1440 UIPreferencesTable *table_;
1441 NSMutableDictionary *fields_;
1442 UIAlertSheet *essential_;
1447 - (id) initWithView:(UIView *)view database:(Database *)database delegate:(id)delegate;
1451 @implementation ConfirmationView
1454 [navbar_ setDelegate:nil];
1455 [transition_ setDelegate:nil];
1456 [table_ setDataSource:nil];
1458 [transition_ release];
1463 if (essential_ != nil)
1464 [essential_ release];
1469 [transition_ transition:7 toView:nil];
1473 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
1474 if (from != nil && to == nil)
1475 [self removeFromSuperview];
1478 - (void) navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button {
1481 if (essential_ != nil)
1482 [essential_ popupAlertAnimated:YES];
1484 [delegate_ confirm];
1493 - (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
1494 [essential_ dismiss];
1498 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
1502 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
1504 case 0: return @"Statistics";
1505 case 1: return @"Modifications";
1507 default: _assert(false);
1511 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
1514 case 1: return [fields_ count];
1516 default: _assert(false);
1520 - (float) preferencesTable:(UIPreferencesTable *)table heightForRow:(int)row inGroup:(int)group withProposedHeight:(float)proposed {
1521 if (group != 1 || row == -1)
1524 _assert(size_t(row) < [fields_ count]);
1525 return [[[fields_ allValues] objectAtIndex:row] visibleTextRect].size.height + TextViewOffset_;
1529 - (UIPreferencesTableCell *) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
1530 UIPreferencesTableCell *cell = [[[UIPreferencesTableCell alloc] init] autorelease];
1531 [cell setShowSelection:NO];
1534 case 0: switch (row) {
1536 [cell setTitle:@"Downloading"];
1537 [cell setValue:SizeString([database_ fetcher].FetchNeeded())];
1541 [cell setTitle:@"Resuming At"];
1542 [cell setValue:SizeString([database_ fetcher].PartialPresent())];
1546 double size([database_ cache]->UsrSize());
1549 [cell setTitle:@"Disk Freeing"];
1550 [cell setValue:SizeString(-size)];
1552 [cell setTitle:@"Disk Using"];
1553 [cell setValue:SizeString(size)];
1557 default: _assert(false);
1561 _assert(size_t(row) < [fields_ count]);
1562 [cell setTitle:[[fields_ allKeys] objectAtIndex:row]];
1563 [cell addSubview:[[fields_ allValues] objectAtIndex:row]];
1566 default: _assert(false);
1572 - (id) initWithView:(UIView *)view database:(Database *)database delegate:(id)delegate {
1573 if ((self = [super initWithFrame:[view bounds]]) != nil) {
1574 database_ = database;
1575 delegate_ = delegate;
1577 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
1578 [self addSubview:transition_];
1580 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
1582 CGSize navsize = [UINavigationBar defaultSize];
1583 CGRect navrect = {{0, 0}, navsize};
1584 CGRect bounds = [overlay_ bounds];
1586 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
1587 [navbar_ setBarStyle:1];
1588 [navbar_ setDelegate:self];
1590 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:@"Confirm"] autorelease];
1591 [navbar_ pushNavigationItem:navitem];
1592 [navbar_ showButtonsWithLeftTitle:@"Cancel" rightTitle:@"Confirm"];
1594 fields_ = [[NSMutableDictionary dictionaryWithCapacity:16] retain];
1596 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
1597 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
1598 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
1599 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
1600 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
1604 pkgCacheFile &cache([database_ cache]);
1605 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
1606 Package *package([Package packageWithIterator:iterator database:database_]);
1607 NSString *name([package name]);
1608 bool essential((iterator->Flags & pkgCache::Flag::Essential) != 0);
1609 pkgDepCache::StateCache &state(cache[iterator]);
1611 if (state.NewInstall())
1612 [installing addObject:name];
1613 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
1614 [reinstalling addObject:name];
1615 else if (state.Upgrade())
1616 [upgrading addObject:name];
1617 else if (state.Downgrade())
1618 [downgrading addObject:name];
1619 else if (state.Delete()) {
1622 [removing addObject:name];
1629 essential_ = [[UIAlertSheet alloc]
1630 initWithTitle:@"Unable to Comply"
1631 buttons:[NSArray arrayWithObjects:@"Okay", nil]
1632 defaultButtonIndex:0
1637 [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."];
1640 AddTextView(fields_, installing, @"Installing");
1641 AddTextView(fields_, reinstalling, @"Reinstalling");
1642 AddTextView(fields_, upgrading, @"Upgrading");
1643 AddTextView(fields_, downgrading, @"Downgrading");
1644 AddTextView(fields_, removing, @"Removing");
1646 table_ = [[UIPreferencesTable alloc] initWithFrame:CGRectMake(
1647 0, navsize.height, bounds.size.width, bounds.size.height - navsize.height
1650 [table_ setReusesTableCells:YES];
1651 [table_ setDataSource:self];
1652 [table_ reloadData];
1654 [overlay_ addSubview:navbar_];
1655 [overlay_ addSubview:table_];
1657 [view addSubview:self];
1659 [transition_ setDelegate:self];
1661 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
1662 [transition_ transition:0 toView:blank];
1663 [transition_ transition:3 toView:overlay_];
1670 /* Progress Data {{{ */
1671 @interface ProgressData : NSObject {
1677 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
1684 @implementation ProgressData
1686 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
1687 if ((self = [super init]) != nil) {
1688 selector_ = selector;
1708 /* Progress View {{{ */
1709 @interface ProgressView : UIView <
1713 UIView *background_;
1714 UITransitionView *transition_;
1716 UINavigationBar *navbar_;
1717 UIProgressBar *progress_;
1718 UITextView *output_;
1719 UITextLabel *status_;
1723 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
1725 - (ProgressView *) initWithFrame:(struct CGRect)frame delegate:(id)delegate;
1726 - (void) setContentView:(UIView *)view;
1729 - (void) _retachThread;
1730 - (void) _detachNewThreadData:(ProgressData *)data;
1731 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
1735 @protocol ProgressViewDelegate
1736 - (void) progressViewIsComplete:(ProgressView *)sender;
1739 @implementation ProgressView
1742 [transition_ setDelegate:nil];
1743 [navbar_ setDelegate:nil];
1746 if (background_ != nil)
1747 [background_ release];
1748 [transition_ release];
1751 [progress_ release];
1757 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
1758 if (bootstrap_ && from == overlay_ && to == view_)
1762 - (ProgressView *) initWithFrame:(struct CGRect)frame delegate:(id)delegate {
1763 if ((self = [super initWithFrame:frame]) != nil) {
1764 delegate_ = delegate;
1766 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
1767 [transition_ setDelegate:self];
1769 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
1772 [overlay_ setBackgroundColor:Black_];
1774 background_ = [[UIView alloc] initWithFrame:[self bounds]];
1775 [background_ setBackgroundColor:Black_];
1776 [self addSubview:background_];
1779 [self addSubview:transition_];
1781 CGSize navsize = [UINavigationBar defaultSize];
1782 CGRect navrect = {{0, 0}, navsize};
1784 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
1785 [overlay_ addSubview:navbar_];
1787 [navbar_ setBarStyle:1];
1788 [navbar_ setDelegate:self];
1790 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
1791 [navbar_ pushNavigationItem:navitem];
1793 CGRect bounds = [overlay_ bounds];
1794 CGSize prgsize = [UIProgressBar defaultSize];
1797 (bounds.size.width - prgsize.width) / 2,
1798 bounds.size.height - prgsize.height - 20
1801 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
1802 [overlay_ addSubview:progress_];
1804 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
1806 bounds.size.height - prgsize.height - 50,
1807 bounds.size.width - 20,
1811 [status_ setColor:White_];
1812 [status_ setBackgroundColor:Clear_];
1814 [status_ setCentersHorizontally:YES];
1815 //[status_ setFont:font];
1817 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
1819 navrect.size.height + 20,
1820 bounds.size.width - 20,
1821 bounds.size.height - navsize.height - 62 - navrect.size.height
1824 //[output_ setTextFont:@"Courier New"];
1825 [output_ setTextSize:12];
1827 [output_ setTextColor:White_];
1828 [output_ setBackgroundColor:Clear_];
1830 [output_ setMarginTop:0];
1831 [output_ setAllowsRubberBanding:YES];
1833 [overlay_ addSubview:output_];
1834 [overlay_ addSubview:status_];
1836 [progress_ setStyle:0];
1840 - (void) setContentView:(UIView *)view {
1841 view_ = [view retain];
1844 - (void) resetView {
1845 [transition_ transition:6 toView:view_];
1848 - (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
1852 - (void) _retachThread {
1853 [delegate_ progressViewIsComplete:self];
1857 - (void) _detachNewThreadData:(ProgressData *)data {
1858 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1860 [[data target] performSelector:[data selector] withObject:[data object]];
1863 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
1868 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
1869 [navbar_ popNavigationItem];
1870 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:title] autorelease];
1871 [navbar_ pushNavigationItem:navitem];
1873 [status_ setText:nil];
1874 [output_ setText:@""];
1875 [progress_ setProgress:0];
1877 [transition_ transition:6 toView:overlay_];
1880 detachNewThreadSelector:@selector(_detachNewThreadData:)
1882 withObject:[[ProgressData alloc]
1883 initWithSelector:selector
1890 - (void) setProgressError:(NSString *)error {
1892 performSelectorOnMainThread:@selector(_setProgressError:)
1898 - (void) setProgressTitle:(NSString *)title {
1900 performSelectorOnMainThread:@selector(_setProgressTitle:)
1906 - (void) setProgressPercent:(float)percent {
1908 performSelectorOnMainThread:@selector(_setProgressPercent:)
1909 withObject:[NSNumber numberWithFloat:percent]
1914 - (void) addProgressOutput:(NSString *)output {
1916 performSelectorOnMainThread:@selector(_addProgressOutput:)
1922 - (void) _setProgressError:(NSString *)error {
1923 UIAlertSheet *sheet = [[[UIAlertSheet alloc]
1924 initWithTitle:@"Package Error"
1925 buttons:[NSArray arrayWithObjects:@"Okay", nil]
1926 defaultButtonIndex:0
1931 [sheet setBodyText:error];
1932 [sheet popupAlertAnimated:YES];
1935 - (void) _setProgressTitle:(NSString *)title {
1936 [status_ setText:[title stringByAppendingString:@"..."]];
1939 - (void) _setProgressPercent:(NSNumber *)percent {
1940 [progress_ setProgress:[percent floatValue]];
1943 - (void) _addProgressOutput:(NSString *)output {
1944 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
1945 CGSize size = [output_ contentSize];
1946 CGRect rect = {{0, size.height}, {size.width, 0}};
1947 [output_ scrollRectToVisible:rect animated:YES];
1953 /* Package Cell {{{ */
1954 @interface PackageCell : UITableCell {
1957 UITextLabel *description_;
1958 UITextLabel *source_;
1959 UIImageView *trusted_;
1962 - (PackageCell *) init;
1963 - (void) setPackage:(Package *)package;
1965 - (void) _setSelected:(float)fraction;
1966 - (void) setSelected:(BOOL)selected;
1967 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade;
1968 - (void) _setSelectionFadeFraction:(float)fraction;
1972 @implementation PackageCell
1977 [description_ release];
1983 - (PackageCell *) init {
1984 if ((self = [super init]) != nil) {
1985 GSFontRef bold = GSFontCreateWithName("Helvetica", kGSFontTraitBold, 20);
1986 GSFontRef large = GSFontCreateWithName("Helvetica", kGSFontTraitNone, 12);
1987 GSFontRef small = GSFontCreateWithName("Helvetica", kGSFontTraitNone, 14);
1989 icon_ = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
1991 name_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 8, 240, 25)];
1992 [name_ setBackgroundColor:Clear_];
1993 [name_ setFont:bold];
1995 source_ = [[UITextLabel alloc] initWithFrame:CGRectMake(58, 28, 225, 20)];
1996 [source_ setBackgroundColor:Clear_];
1997 [source_ setFont:large];
1999 description_ = [[UITextLabel alloc] initWithFrame:CGRectMake(12, 46, 280, 20)];
2000 [description_ setBackgroundColor:Clear_];
2001 [description_ setFont:small];
2003 trusted_ = [[UIImageView alloc] initWithFrame:CGRectMake(30, 30, 16, 16)];
2004 [trusted_ setImage:[UIImage applicationImageNamed:@"trusted.png"]];
2006 [self addSubview:icon_];
2007 [self addSubview:name_];
2008 [self addSubview:description_];
2009 [self addSubview:source_];
2017 - (void) setPackage:(Package *)package {
2018 Source *source = [package source];
2020 UIImage *image = nil;
2021 if (NSString *icon = [package icon])
2022 image = [UIImage imageAtPath:[icon substringFromIndex:6]];
2023 if (image == nil) if (NSString *icon = [source defaultIcon])
2024 image = [UIImage imageAtPath:[icon substringFromIndex:6]];
2026 image = [UIImage applicationImageNamed:@"unknown.png"];
2027 [icon_ setImage:image];
2030 CGSize size = [image size];
2031 float scale = 30 / std::max(size.width, size.height);
2032 [icon_ zoomToScale:scale];
2035 [icon_ setFrame:CGRectMake(10, 10, 30, 30)];
2037 [name_ setText:[package name]];
2038 [description_ setText:[package tagline]];
2043 if (source != nil) {
2044 label = [source label];
2045 trusted = [source trusted];
2046 } else if ([[package id] isEqualToString:@"firmware"]) {
2050 label = @"Unknown/Local";
2054 [source_ setText:[NSString stringWithFormat:@"from %@ (%@)", label, Simplify([package section])]];
2057 [self addSubview:trusted_];
2059 [trusted_ removeFromSuperview];
2062 - (void) _setSelected:(float)fraction {
2063 CGColor black(space_,
2064 Interpolate(0.0, 1.0, fraction),
2065 Interpolate(0.0, 1.0, fraction),
2066 Interpolate(0.0, 1.0, fraction),
2069 CGColor gray(space_,
2070 Interpolate(0.4, 1.0, fraction),
2071 Interpolate(0.4, 1.0, fraction),
2072 Interpolate(0.4, 1.0, fraction),
2075 [name_ setColor:black];
2076 [description_ setColor:gray];
2077 [source_ setColor:black];
2080 - (void) setSelected:(BOOL)selected {
2081 [self _setSelected:(selected ? 1.0 : 0.0)];
2082 [super setSelected:selected];
2085 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
2087 [self _setSelected:(selected ? 1.0 : 0.0)];
2088 [super setSelected:selected withFade:fade];
2091 - (void) _setSelectionFadeFraction:(float)fraction {
2092 [self _setSelected:fraction];
2093 [super _setSelectionFadeFraction:fraction];
2098 /* Section Cell {{{ */
2099 @interface SectionCell : UITableCell {
2101 UITextLabel *count_;
2105 - (void) setSection:(Section *)section;
2107 - (void) _setSelected:(float)fraction;
2108 - (void) setSelected:(BOOL)selected;
2109 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade;
2110 - (void) _setSelectionFadeFraction:(float)fraction;
2114 @implementation SectionCell
2123 if ((self = [super init]) != nil) {
2124 GSFontRef bold = GSFontCreateWithName("Helvetica", kGSFontTraitBold, 22);
2125 GSFontRef small = GSFontCreateWithName("Helvetica", kGSFontTraitBold, 12);
2127 name_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 9, 250, 25)];
2128 [name_ setBackgroundColor:Clear_];
2129 [name_ setFont:bold];
2131 count_ = [[UITextLabel alloc] initWithFrame:CGRectMake(11, 7, 29, 32)];
2132 [count_ setCentersHorizontally:YES];
2133 [count_ setBackgroundColor:Clear_];
2134 [count_ setFont:small];
2135 [count_ setColor:White_];
2137 UIImageView *folder = [[[UIImageView alloc] initWithFrame:CGRectMake(8, 7, 32, 32)] autorelease];
2138 [folder setImage:[UIImage applicationImageNamed:@"folder.png"]];
2140 [self addSubview:folder];
2141 [self addSubview:name_];
2142 [self addSubview:count_];
2144 [self _setSelected:0];
2151 - (void) setSection:(Section *)section {
2152 if (section == nil) {
2153 [name_ setText:@"All Packages"];
2154 [count_ setText:nil];
2156 NSString *name = [section name];
2157 [name_ setText:(name == nil ? @"(No Section)" : name)];
2158 [count_ setText:[NSString stringWithFormat:@"%d", [section count]]];
2162 - (void) _setSelected:(float)fraction {
2163 CGColor black(space_,
2164 Interpolate(0.0, 1.0, fraction),
2165 Interpolate(0.0, 1.0, fraction),
2166 Interpolate(0.0, 1.0, fraction),
2169 [name_ setColor:black];
2172 - (void) setSelected:(BOOL)selected {
2173 [self _setSelected:(selected ? 1.0 : 0.0)];
2174 [super setSelected:selected];
2177 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
2179 [self _setSelected:(selected ? 1.0 : 0.0)];
2180 [super setSelected:selected withFade:fade];
2183 - (void) _setSelectionFadeFraction:(float)fraction {
2184 [self _setSelected:fraction];
2185 [super _setSelectionFadeFraction:fraction];
2191 /* File Table {{{ */
2192 @interface FileTable : RVPage {
2193 _transient Database *database_;
2196 NSMutableArray *files_;
2200 - (id) initWithBook:(RVBook *)book database:(Database *)database;
2201 - (void) setPackage:(Package *)package;
2205 @implementation FileTable
2208 if (package_ != nil)
2217 - (int) numberOfRowsInTable:(UITable *)table {
2218 return files_ == nil ? 0 : [files_ count];
2221 - (float) table:(UITable *)table heightForRow:(int)row {
2225 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
2226 if (reusing == nil) {
2227 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
2228 GSFontRef font = GSFontCreateWithName("Helvetica", kGSFontTraitNone, 16);
2229 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
2232 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
2236 - (BOOL) canSelectRow:(int)row {
2240 - (id) initWithBook:(RVBook *)book database:(Database *)database {
2241 if ((self = [super initWithBook:book]) != nil) {
2242 database_ = database;
2244 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
2246 list_ = [[UITable alloc] initWithFrame:[self bounds]];
2247 [self addSubview:list_];
2249 UITableColumn *column = [[[UITableColumn alloc]
2250 initWithTitle:@"Name"
2252 width:[self frame].size.width
2255 [list_ setDataSource:self];
2256 [list_ setSeparatorStyle:1];
2257 [list_ addTableColumn:column];
2258 [list_ setDelegate:self];
2259 [list_ setReusesTableCells:YES];
2263 - (void) setPackage:(Package *)package {
2264 if (package_ != nil) {
2265 [package_ autorelease];
2274 [files_ removeAllObjects];
2276 if (package != nil) {
2277 package_ = [package retain];
2278 name_ = [[package id] retain];
2280 NSString *list = [NSString
2281 stringWithContentsOfFile:[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", name_]
2282 encoding:kCFStringEncodingUTF8
2287 [files_ addObjectsFromArray:[list componentsSeparatedByString:@"\n"]];
2288 [files_ removeLastObject];
2295 - (void) resetViewAnimated:(BOOL)animated {
2296 [list_ resetViewAnimated:animated];
2299 - (void) reloadData {
2300 [self setPackage:[database_ packageWithName:name_]];
2301 [self reloadButtons];
2304 - (NSString *) title {
2305 return @"File Contents";
2310 /* Package View {{{ */
2311 @protocol PackageViewDelegate
2312 - (void) performPackage:(Package *)package;
2315 @interface PackageView : RVPage {
2316 _transient Database *database_;
2317 UIPreferencesTable *table_;
2320 UITextView *description_;
2323 - (id) initWithBook:(RVBook *)book database:(Database *)database;
2324 - (void) setPackage:(Package *)package;
2328 @implementation PackageView
2331 [table_ setDataSource:nil];
2332 [table_ setDelegate:nil];
2334 if (package_ != nil)
2338 if (description_ != nil)
2339 [description_ release];
2344 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
2346 if ([package_ installed] != nil)
2348 if ([package_ source] != nil)
2353 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
2356 else if ([package_ installed] != nil && group-- == 0)
2357 return @"Installed Package";
2358 else if (group-- == 0)
2359 return @"Package Details";
2360 else if ([package_ source] != nil && group-- == 0)
2361 return @"Source Information";
2362 else _assert(false);
2365 - (float) preferencesTable:(UIPreferencesTable *)table heightForRow:(int)row inGroup:(int)group withProposedHeight:(float)proposed {
2366 if (group != 0 || row != 1)
2369 return [description_ visibleTextRect].size.height + TextViewOffset_;
2372 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
2375 if ([package_ website] != nil)
2377 if ([[package_ source] trusted])
2380 } else if ([package_ installed] != nil && group-- == 0)
2382 else if (group-- == 0)
2384 else if ([package_ source] != nil && group-- == 0)
2386 else _assert(false);
2389 - (UIPreferencesTableCell *) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
2390 UIPreferencesTableCell *cell = [[[UIPreferencesTableCell alloc] init] autorelease];
2391 [cell setShowSelection:NO];
2396 [cell setTitle:[package_ name]];
2397 [cell setValue:[package_ latest]];
2401 [cell addSubview:description_];
2405 if ([package_ website] != nil) {
2406 [cell setTitle:@"More Information"];
2407 [cell setShowDisclosure:YES];
2408 [cell setShowSelection:YES];
2412 [cell setIcon:[UIImage applicationImageNamed:@"trusted.png"]];
2413 [cell setValue:@"This package has been signed."];
2416 default: _assert(false);
2418 else if ([package_ installed] != nil && group-- == 0)
2421 [cell setTitle:@"Version"];
2422 NSString *installed([package_ installed]);
2423 [cell setValue:(installed == nil ? @"n/a" : installed)];
2427 [cell setTitle:@"File Content"];
2428 [cell setShowDisclosure:YES];
2429 [cell setShowSelection:YES];
2432 default: _assert(false);
2434 else if (group-- == 0)
2437 [cell setTitle:@"Identifier"];
2438 [cell setValue:[package_ id]];
2442 [cell setTitle:@"Section"];
2443 NSString *section([package_ section]);
2444 [cell setValue:(section == nil ? @"n/a" : section)];
2448 [cell setTitle:@"Expanded Size"];
2449 [cell setValue:SizeString([package_ size])];
2453 [cell setTitle:@"Maintainer"];
2454 [cell setValue:[[package_ maintainer] name]];
2455 [cell setShowDisclosure:YES];
2456 [cell setShowSelection:YES];
2459 default: _assert(false);
2461 else if ([package_ source] != nil && group-- == 0)
2464 [cell setTitle:[[package_ source] label]];
2465 [cell setValue:[[package_ source] version]];
2469 [cell setValue:[[package_ source] description]];
2473 [cell setTitle:@"Origin"];
2474 [cell setValue:[[package_ source] origin]];
2477 default: _assert(false);
2479 else _assert(false);
2484 - (BOOL) canSelectRow:(int)row {
2488 - (void) tableRowSelected:(NSNotification *)notification {
2489 int row = [table_ selectedRow];
2490 NSString *website = [package_ website];
2491 BOOL trusted = [[package_ source] trusted];
2492 NSString *installed = [package_ installed];
2495 + (website == nil ? 0 : 1)
2497 + (installed == nil ? 0 : 3)
2499 [delegate_ openURL:[NSURL URLWithString:[NSString stringWithFormat:@"mailto:%@?subject=%@",
2500 [[package_ maintainer] email],
2501 [[NSString stringWithFormat:@"regarding apt package \"%@\"", [package_ name]] stringByAddingPercentEscapes]
2503 else if (installed && row == 5
2504 + (website == nil ? 0 : 1)
2507 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
2508 [files setDelegate:delegate_];
2509 [files setPackage:package_];
2510 [book_ pushPage:files];
2511 } else if (website != nil && row == 3) {
2512 NSURL *url = [NSURL URLWithString:website];
2513 BrowserView *browser = [[[BrowserView alloc] initWithBook:book_ database:database_] autorelease];
2514 [browser setDelegate:delegate_];
2515 [book_ pushPage:browser];
2516 [browser loadURL:url];
2520 - (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
2522 case 1: [delegate_ installPackage:package_]; break;
2523 case 2: [delegate_ removePackage:package_]; break;
2529 - (void) _rightButtonClicked {
2530 if ([package_ installed] == nil)
2531 [delegate_ installPackage:package_];
2533 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:6];
2535 if ([package_ upgradable])
2536 [buttons addObject:@"Upgrade"];
2538 [buttons addObject:@"Reinstall"];
2540 [buttons addObject:@"Remove"];
2541 [buttons addObject:@"Cancel"];
2543 [delegate_ slideUp:[[[UIAlertSheet alloc]
2544 initWithTitle:@"Manage Package"
2546 defaultButtonIndex:2
2553 - (NSString *) rightButtonTitle {
2554 _assert(package_ != nil);
2555 return [package_ installed] == nil ? @"Install" : @"Modify";
2558 - (NSString *) title {
2562 - (id) initWithBook:(RVBook *)book database:(Database *)database {
2563 if ((self = [super initWithBook:book]) != nil) {
2564 database_ = database;
2566 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
2567 [self addSubview:table_];
2569 [table_ setDataSource:self];
2570 [table_ setDelegate:self];
2574 - (void) setPackage:(Package *)package {
2575 if (package_ != nil) {
2576 [package_ autorelease];
2585 if (description_ != nil) {
2586 [description_ release];
2590 if (package != nil) {
2591 package_ = [package retain];
2592 name_ = [[package id] retain];
2594 NSString *description([package description]);
2595 if (description == nil)
2596 description = [package tagline];
2597 description_ = [GetTextView(description, 12, true) retain];
2599 [description_ setTextColor:Black_];
2601 [table_ reloadData];
2605 - (void) resetViewAnimated:(BOOL)animated {
2606 [table_ resetViewAnimated:animated];
2609 - (void) reloadData {
2610 [self setPackage:[database_ packageWithName:name_]];
2611 [self reloadButtons];
2616 /* Package Table {{{ */
2617 @interface PackageTable : RVPage {
2618 _transient Database *database_;
2622 NSMutableArray *packages_;
2623 NSMutableArray *sections_;
2624 UISectionList *list_;
2627 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
2629 - (void) setDelegate:(id)delegate;
2630 - (void) setObject:(id)object;
2632 - (void) reloadData;
2633 - (void) resetCursor;
2635 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
2639 @implementation PackageTable
2642 [list_ setDataSource:nil];
2647 [packages_ release];
2648 [sections_ release];
2653 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
2654 return [sections_ count];
2657 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
2658 return [[sections_ objectAtIndex:section] name];
2661 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
2662 return [[sections_ objectAtIndex:section] row];
2665 - (int) numberOfRowsInTable:(UITable *)table {
2666 return [packages_ count];
2669 - (float) table:(UITable *)table heightForRow:(int)row {
2673 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
2675 reusing = [[[PackageCell alloc] init] autorelease];
2676 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
2680 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
2684 - (void) tableRowSelected:(NSNotification *)notification {
2685 int row = [[notification object] selectedRow];
2689 Package *package = [packages_ objectAtIndex:row];
2690 PackageView *view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
2691 [view setDelegate:delegate_];
2692 [view setPackage:package];
2693 [book_ pushPage:view];
2696 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
2697 if ((self = [super initWithBook:book]) != nil) {
2698 database_ = database;
2699 title_ = [title retain];
2701 object_ = object == nil ? nil : [object retain];
2703 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
2704 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
2706 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
2707 [list_ setDataSource:self];
2709 UITableColumn *column = [[[UITableColumn alloc]
2710 initWithTitle:@"Name"
2712 width:[self frame].size.width
2715 UITable *table = [list_ table];
2716 [table setSeparatorStyle:1];
2717 [table addTableColumn:column];
2718 [table setDelegate:self];
2719 [table setReusesTableCells:YES];
2721 [self addSubview:list_];
2726 - (void) setDelegate:(id)delegate {
2727 delegate_ = delegate;
2730 - (void) setObject:(id)object {
2736 object_ = [object retain];
2739 - (void) reloadData {
2740 NSArray *packages = [database_ packages];
2742 [packages_ removeAllObjects];
2743 [sections_ removeAllObjects];
2745 for (size_t i(0); i != [packages count]; ++i) {
2746 Package *package([packages objectAtIndex:i]);
2747 if ([[package performSelector:filter_ withObject:object_] boolValue])
2748 [packages_ addObject:package];
2751 Section *section = nil;
2753 for (size_t offset(0); offset != [packages_ count]; ++offset) {
2754 Package *package = [packages_ objectAtIndex:offset];
2755 NSString *name = [package index];
2757 if (section == nil || ![[section name] isEqualToString:name]) {
2758 section = [[[Section alloc] initWithName:name row:offset] autorelease];
2759 [sections_ addObject:section];
2762 [section addToCount];
2768 - (NSString *) title {
2772 - (void) resetViewAnimated:(BOOL)animated {
2773 [list_ resetViewAnimated:animated];
2776 - (void) resetCursor {
2777 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
2780 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
2781 [list_ setShouldHideHeaderInShortLists:hide];
2787 /* Browser Implementation {{{ */
2788 @implementation BrowserView
2791 WebView *webview = [webview_ webView];
2792 [webview setFrameLoadDelegate:nil];
2793 [webview setResourceLoadDelegate:nil];
2794 [webview setUIDelegate:nil];
2796 [scroller_ setDelegate:nil];
2797 [webview_ setDelegate:nil];
2799 [scroller_ release];
2802 [indicator_ release];
2808 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
2809 NSMutableURLRequest *request = [NSMutableURLRequest
2812 timeoutInterval:30.0
2815 [request addValue:[NSString stringWithCString:Firmware_] forHTTPHeaderField:@"X-Firmware"];
2816 [request addValue:[NSString stringWithCString:Machine_] forHTTPHeaderField:@"X-Machine"];
2817 [request addValue:[NSString stringWithCString:SerialNumber_] forHTTPHeaderField:@"X-Serial-Number"];
2819 [self loadRequest:request];
2823 - (void) loadURL:(NSURL *)url {
2824 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
2827 // XXX: this needs to add the headers
2828 - (NSURLRequest *) _addHeadersToRequest:(NSURLRequest *)request {
2832 - (void) loadRequest:(NSURLRequest *)request {
2833 [webview_ loadRequest:request];
2836 - (void) reloadURL {
2837 NSURL *url = [[[urls_ lastObject] retain] autorelease];
2838 [urls_ removeLastObject];
2839 [self loadURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData];
2842 - (WebView *) webView {
2843 return [webview_ webView];
2846 - (void) view:(UIView *)sender didSetFrame:(CGRect)frame {
2847 [scroller_ setContentSize:frame.size];
2850 - (void) view:(UIView *)sender didSetFrame:(CGRect)frame oldFrame:(CGRect)old {
2851 [self view:sender didSetFrame:frame];
2854 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)dataSource {
2855 return [self _addHeadersToRequest:request];
2858 - (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request {
2859 if ([[[request URL] scheme] isEqualToString:@"apptapp"])
2861 [self setBackButtonTitle:title_];
2862 BrowserView *browser = [[[BrowserView alloc] initWithBook:book_ database:database_] autorelease];
2863 [browser setDelegate:delegate_];
2864 [book_ pushPage:browser];
2865 [browser loadRequest:[self _addHeadersToRequest:request]];
2866 return [browser webView];
2869 - (void) webView:(WebView *)sender willClickElement:(id)element {
2870 if (![element respondsToSelector:@selector(href)])
2872 NSString *href = [element href];
2875 if ([href hasPrefix:@"apptapp://package/"]) {
2876 NSString *name = [href substringFromIndex:18];
2877 Package *package = [database_ packageWithName:name];
2878 if (package == nil) {
2879 UIAlertSheet *sheet = [[[UIAlertSheet alloc]
2880 initWithTitle:@"Cannot Locate Package"
2881 buttons:[NSArray arrayWithObjects:@"Close", nil]
2882 defaultButtonIndex:0
2887 [sheet setBodyText:[NSString stringWithFormat:
2888 @"The package %@ cannot be found in your current sources. I might recommend installing more sources."
2891 [sheet popupAlertAnimated:YES];
2893 [self setBackButtonTitle:title_];
2894 PackageView *view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
2895 [view setDelegate:delegate_];
2896 [view setPackage:package];
2897 [book_ pushPage:view];
2902 - (void) webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
2903 title_ = [title retain];
2904 [self setTitle:title];
2907 - (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
2908 if ([frame parentFrame] != nil)
2913 [indicator_ startAnimation];
2914 [self reloadButtons];
2916 if (title_ != nil) {
2921 [self setTitle:@"Loading..."];
2923 WebView *webview = [webview_ webView];
2924 NSString *href = [webview mainFrameURL];
2925 [urls_ addObject:[NSURL URLWithString:href]];
2927 CGRect webrect = [scroller_ frame];
2928 webrect.size.height = 0;
2929 [webview_ setFrame:webrect];
2932 - (void) _finishLoading {
2935 [indicator_ stopAnimation];
2936 [self reloadButtons];
2940 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
2941 if ([frame parentFrame] != nil)
2943 [self _finishLoading];
2946 - (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
2947 if ([frame parentFrame] != nil)
2949 [self setTitle:[error localizedDescription]];
2950 [self _finishLoading];
2953 - (id) initWithBook:(RVBook *)book database:(Database *)database {
2954 if ((self = [super initWithBook:book]) != nil) {
2955 database_ = database;
2958 struct CGRect bounds = [self bounds];
2960 UIImageView *pinstripe = [[[UIImageView alloc] initWithFrame:bounds] autorelease];
2961 [pinstripe setImage:[UIImage applicationImageNamed:@"pinstripe.png"]];
2962 [self addSubview:pinstripe];
2964 scroller_ = [[UIScroller alloc] initWithFrame:bounds];
2965 [self addSubview:scroller_];
2967 [scroller_ setScrollingEnabled:YES];
2968 [scroller_ setAdjustForContentSizeChange:YES];
2969 [scroller_ setClipsSubviews:YES];
2970 [scroller_ setAllowsRubberBanding:YES];
2971 [scroller_ setScrollDecelerationFactor:0.99];
2972 [scroller_ setDelegate:self];
2974 CGRect webrect = [scroller_ bounds];
2975 webrect.size.height = 0;
2977 webview_ = [[UIWebView alloc] initWithFrame:webrect];
2978 [scroller_ addSubview:webview_];
2980 [webview_ setTilingEnabled:YES];
2981 [webview_ setTileSize:CGSizeMake(webrect.size.width, 500)];
2982 [webview_ setAutoresizes:YES];
2983 [webview_ setDelegate:self];
2984 //[webview_ setEnabledGestures:2];
2986 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:0];
2987 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(281, 43, indsize.width, indsize.height)];
2988 [indicator_ setStyle:0];
2990 Package *package([database_ packageWithName:@"cydia"]);
2991 NSString *application = package == nil ? @"Cydia" : [NSString
2992 stringWithFormat:@"Cydia/%@",
2996 WebView *webview = [webview_ webView];
2997 [webview setApplicationNameForUserAgent:application];
2998 [webview setFrameLoadDelegate:self];
2999 [webview setResourceLoadDelegate:self];
3000 [webview setUIDelegate:self];
3002 urls_ = [[NSMutableArray alloc] initWithCapacity:16];
3006 - (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
3010 - (void) _leftButtonClicked {
3011 UIAlertSheet *sheet = [[[UIAlertSheet alloc]
3012 initWithTitle:@"About Cydia Packager"
3013 buttons:[NSArray arrayWithObjects:@"Close", nil]
3014 defaultButtonIndex:0
3020 @"Copyright (C) 2008\n"
3021 "Jay Freeman (saurik)\n"
3022 "saurik@saurik.com\n"
3023 "http://www.saurik.com/\n"
3026 "http://www.theokorigroup.com/\n"
3028 "College of Creative Studies,\n"
3029 "University of California,\n"
3031 "http://www.ccs.ucsb.edu/"
3034 [sheet popupAlertAnimated:YES];
3037 - (void) _rightButtonClicked {
3042 - (NSString *) leftButtonTitle {
3046 - (NSString *) rightButtonTitle {
3047 return loading_ ? @"" : @"Reload";
3050 - (NSString *) title {
3054 - (NSString *) backButtonTitle {
3058 - (void) setPageActive:(BOOL)active {
3060 [book_ addSubview:indicator_];
3062 [indicator_ removeFromSuperview];
3065 - (void) resetViewAnimated:(BOOL)animated {
3071 @interface CYBook : RVBook <
3074 _transient Database *database_;
3076 UIProgressIndicator *indicator_;
3077 UITextLabel *prompt_;
3078 UIProgressBar *progress_;
3082 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
3088 /* Install View {{{ */
3089 @interface InstallView : RVPage {
3090 _transient Database *database_;
3091 NSMutableArray *packages_;
3092 NSMutableArray *sections_;
3096 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3097 - (void) reloadData;
3101 @implementation InstallView
3104 [list_ setDataSource:nil];
3105 [list_ setDelegate:nil];
3107 [packages_ release];
3108 [sections_ release];
3113 - (int) numberOfRowsInTable:(UITable *)table {
3114 return [sections_ count] + 1;
3117 - (float) table:(UITable *)table heightForRow:(int)row {
3121 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
3123 reusing = [[[SectionCell alloc] init] autorelease];
3124 [(SectionCell *)reusing setSection:(row == 0 ? nil : [sections_ objectAtIndex:(row - 1)])];
3128 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
3132 - (void) tableRowSelected:(NSNotification *)notification {
3133 int row = [[notification object] selectedRow];
3142 title = @"All Packages";
3144 section = [sections_ objectAtIndex:(row - 1)];
3145 title = [section name];
3148 PackageTable *table = [[[PackageTable alloc]
3152 filter:@selector(isUninstalledInSection:)
3153 with:(section == nil ? nil : [section name])
3156 [table setDelegate:delegate_];
3158 [book_ pushPage:table];
3161 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3162 if ((self = [super initWithBook:book]) != nil) {
3163 database_ = database;
3165 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
3166 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
3168 list_ = [[UITable alloc] initWithFrame:[self bounds]];
3169 [self addSubview:list_];
3171 UITableColumn *column = [[[UITableColumn alloc]
3172 initWithTitle:@"Name"
3174 width:[self frame].size.width
3177 [list_ setDataSource:self];
3178 [list_ setSeparatorStyle:1];
3179 [list_ addTableColumn:column];
3180 [list_ setDelegate:self];
3181 [list_ setReusesTableCells:YES];
3187 - (void) reloadData {
3188 NSArray *packages = [database_ packages];
3190 [packages_ removeAllObjects];
3191 [sections_ removeAllObjects];
3193 for (size_t i(0); i != [packages count]; ++i) {
3194 Package *package([packages objectAtIndex:i]);
3195 if ([package installed] == nil)
3196 [packages_ addObject:package];
3199 [packages_ sortUsingSelector:@selector(compareBySection:)];
3201 Section *section = nil;
3202 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
3203 Package *package = [packages_ objectAtIndex:offset];
3204 NSString *name = [package section];
3206 if (section == nil || name != nil && ![[section name] isEqualToString:name]) {
3207 section = [[[Section alloc] initWithName:name row:offset] autorelease];
3208 [sections_ addObject:section];
3211 [section addToCount];
3217 - (void) resetViewAnimated:(BOOL)animated {
3218 [list_ resetViewAnimated:animated];
3221 - (NSString *) title {
3225 - (NSString *) backButtonTitle {
3231 /* Changes View {{{ */
3232 @interface ChangesView : RVPage {
3233 _transient Database *database_;
3234 NSMutableArray *packages_;
3235 NSMutableArray *sections_;
3236 UISectionList *list_;
3240 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3241 - (void) reloadData;
3245 @implementation ChangesView
3248 [[list_ table] setDelegate:nil];
3249 [list_ setDataSource:nil];
3251 [packages_ release];
3252 [sections_ release];
3257 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
3258 return [sections_ count];
3261 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
3262 return [[sections_ objectAtIndex:section] name];
3265 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
3266 return [[sections_ objectAtIndex:section] row];
3269 - (int) numberOfRowsInTable:(UITable *)table {
3270 return [packages_ count];
3273 - (float) table:(UITable *)table heightForRow:(int)row {
3277 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
3279 reusing = [[[PackageCell alloc] init] autorelease];
3280 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
3284 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
3288 - (void) tableRowSelected:(NSNotification *)notification {
3289 int row = [[notification object] selectedRow];
3292 Package *package = [packages_ objectAtIndex:row];
3293 PackageView *view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
3294 [view setDelegate:delegate_];
3295 [view setPackage:package];
3296 [book_ pushPage:view];
3299 - (void) _leftButtonClicked {
3300 [(CYBook *)book_ update];
3301 [self reloadButtons];
3304 - (void) _rightButtonClicked {
3305 [delegate_ distUpgrade];
3308 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3309 if ((self = [super initWithBook:book]) != nil) {
3310 database_ = database;
3312 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
3313 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
3315 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
3316 [self addSubview:list_];
3318 [list_ setShouldHideHeaderInShortLists:NO];
3319 [list_ setDataSource:self];
3320 //[list_ setSectionListStyle:1];
3322 UITableColumn *column = [[[UITableColumn alloc]
3323 initWithTitle:@"Name"
3325 width:[self frame].size.width
3328 UITable *table = [list_ table];
3329 [table setSeparatorStyle:1];
3330 [table addTableColumn:column];
3331 [table setDelegate:self];
3332 [table setReusesTableCells:YES];
3338 - (void) reloadData {
3339 NSArray *packages = [database_ packages];
3341 [packages_ removeAllObjects];
3342 [sections_ removeAllObjects];
3344 for (size_t i(0); i != [packages count]; ++i) {
3345 Package *package([packages objectAtIndex:i]);
3346 if ([package installed] == nil || [package upgradable])
3347 [packages_ addObject:package];
3350 [packages_ sortUsingSelector:@selector(compareForChanges:)];
3352 Section *upgradable = [[[Section alloc] initWithName:@"Available Upgrades" row:0] autorelease];
3353 Section *section = nil;
3356 bool unseens = false;
3358 CFLocaleRef locale = CFLocaleCopyCurrent();
3359 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, locale, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
3361 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
3362 Package *package = [packages_ objectAtIndex:offset];
3364 if ([package upgradable]) {
3366 [upgradable addToCount];
3369 NSDate *seen = [package seen];
3374 name = [@"n/a ?" retain];
3376 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
3379 if (section == nil || ![[section name] isEqualToString:name]) {
3380 section = [[[Section alloc] initWithName:name row:offset] autorelease];
3381 [sections_ addObject:section];
3385 [section addToCount];
3389 CFRelease(formatter);
3393 Section *last = [sections_ lastObject];
3394 size_t count = [last count];
3395 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
3396 [sections_ removeLastObject];
3400 [sections_ insertObject:upgradable atIndex:0];
3403 [self reloadButtons];
3406 - (void) resetViewAnimated:(BOOL)animated {
3407 [list_ resetViewAnimated:animated];
3410 - (NSString *) leftButtonTitle {
3411 return [(CYBook *)book_ updating] ? nil : @"Refresh";
3414 - (NSString *) rightButtonTitle {
3415 return upgrades_ == 0 ? nil : [NSString stringWithFormat:@"Upgrade All (%u)", upgrades_];
3418 - (NSString *) title {
3424 /* Manage View {{{ */
3425 @interface ManageView : PackageTable {
3428 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3432 @implementation ManageView
3434 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3439 filter:@selector(isInstalledInSection:)
3445 - (NSString *) title {
3446 return @"Installed Packages";
3449 - (NSString *) backButtonTitle {
3450 return @"All Packages";
3455 /* Search View {{{ */
3456 @protocol SearchViewDelegate
3457 - (void) showKeyboard:(BOOL)show;
3460 @interface SearchView : RVPage {
3462 UISearchField *field_;
3463 UITransitionView *transition_;
3464 PackageTable *table_;
3465 UIPreferencesTable *advanced_;
3471 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3472 - (void) reloadData;
3476 @implementation SearchView
3480 [[field_ textTraits] setEditingDelegate:nil];
3482 [field_ setDelegate:nil];
3484 [accessory_ release];
3486 [transition_ release];
3488 [advanced_ release];
3493 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
3497 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
3499 case 0: return @"Advanced Search (Coming Soon!)";
3501 default: _assert(false);
3505 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
3509 default: _assert(false);
3513 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
3514 [delegate_ showKeyboard:YES];
3517 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
3518 [delegate_ showKeyboard:NO];
3521 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
3523 NSString *text([field_ text]);
3524 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
3530 - (void) textFieldClearButtonPressed:(UITextField *)field {
3534 - (void) keyboardInputShouldDelete:(id)input {
3538 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
3539 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
3543 [field_ resignFirstResponder];
3548 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3549 if ((self = [super initWithBook:book]) != nil) {
3550 CGRect pageBounds = [book_ pageBounds];
3552 /*UIImageView *pinstripe = [[[UIImageView alloc] initWithFrame:pageBounds] autorelease];
3553 [pinstripe setImage:[UIImage applicationImageNamed:@"pinstripe.png"]];
3554 [self addSubview:pinstripe];*/
3556 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
3557 [self addSubview:transition_];
3559 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
3561 [advanced_ setReusesTableCells:YES];
3562 [advanced_ setDataSource:self];
3563 [advanced_ reloadData];
3565 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
3566 CGColor dimmed(space_, 0, 0, 0, 0.5);
3567 [dimmed_ setBackgroundColor:dimmed];
3569 table_ = [[PackageTable alloc]
3573 filter:@selector(isSearchedForBy:)
3577 [table_ setShouldHideHeaderInShortLists:NO];
3578 [transition_ transition:0 toView:table_];
3580 CGRect cnfrect = {{1, 38}, {17, 18}};
3583 area.origin.x = cnfrect.size.width + 15;
3585 area.size.width = [self bounds].size.width - area.origin.x - 18;
3586 area.size.height = [UISearchField defaultHeight];
3588 field_ = [[UISearchField alloc] initWithFrame:area];
3590 GSFontRef font = GSFontCreateWithName("Helvetica", kGSFontTraitNone, 16);
3591 [field_ setFont:font];
3594 [field_ setPlaceholder:@"Package Names & Descriptions"];
3595 [field_ setPaddingTop:5];
3596 [field_ setDelegate:self];
3599 UITextTraits *traits = [field_ textTraits];
3600 [traits setEditingDelegate:self];
3601 [traits setReturnKeyType:6];
3602 [traits setAutoCapsType:0];
3603 [traits setAutoCorrectionType:1];
3606 UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
3607 [configure setShowPressFeedback:YES];
3608 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
3609 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
3611 accessory_ = [[UIView alloc] initWithFrame:CGRectMake(0, 6, cnfrect.size.width + area.size.width + 6 * 3, area.size.height + 30)];
3612 [accessory_ addSubview:field_];
3613 [accessory_ addSubview:configure];
3618 LKAnimation *animation = [LKTransition animation];
3619 [animation setType:@"oglFlip"];
3620 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
3621 [animation setFillMode:@"extended"];
3622 [animation setTransitionFlags:3];
3623 [animation setDuration:10];
3624 [animation setSpeed:0.35];
3625 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
3626 [[transition_ _layer] addAnimation:animation forKey:0];
3627 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
3628 flipped_ = !flipped_;
3631 - (void) configurePushed {
3632 [field_ resignFirstResponder];
3636 - (void) resetViewAnimated:(BOOL)animated {
3639 [table_ resetViewAnimated:animated];
3642 - (void) reloadData {
3645 [table_ setObject:[field_ text]];
3646 [table_ reloadData];
3647 [table_ resetCursor];
3650 - (UIView *) accessoryView {
3654 - (NSString *) title {
3658 - (NSString *) backButtonTitle {
3662 - (void) setDelegate:(id)delegate {
3663 [table_ setDelegate:delegate];
3664 [super setDelegate:delegate];
3670 @implementation CYBook
3674 [indicator_ release];
3676 [progress_ release];
3680 - (NSString *) getTitleForPage:(RVPage *)page {
3681 return Simplify([super getTitleForPage:page]);
3689 [navbar_ setPrompt:@""];
3690 [navbar_ addSubview:overlay_];
3691 [indicator_ startAnimation];
3692 [prompt_ setText:@"Updating Database..."];
3693 [progress_ setProgress:0];
3698 detachNewThreadSelector:@selector(_update)
3707 [overlay_ removeFromSuperview];
3708 [indicator_ stopAnimation];
3709 [delegate_ reloadData];
3711 [self setPrompt:[NSString stringWithFormat:@"Last Updated: %@", GetLastUpdate()]];
3714 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
3715 if ((self = [super initWithFrame:frame]) != nil) {
3716 database_ = database;
3718 CGRect ovrrect = [navbar_ bounds];
3719 ovrrect.size.height = [UINavigationBar defaultSizeWithPrompt].height - [UINavigationBar defaultSize].height;
3721 overlay_ = [[UIView alloc] initWithFrame:ovrrect];
3723 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:2];
3724 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
3725 CGRect indrect = {{indoffset, indoffset}, indsize};
3727 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
3728 [indicator_ setStyle:2];
3729 [overlay_ addSubview:indicator_];
3731 CGSize prmsize = {200, indsize.width};
3734 indoffset * 2 + indsize.width,
3735 (ovrrect.size.height - prmsize.height) / 2
3738 GSFontRef font = GSFontCreateWithName("Helvetica", kGSFontTraitNone, 12);
3740 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
3742 [prompt_ setColor:White_];
3743 [prompt_ setBackgroundColor:Clear_];
3744 [prompt_ setFont:font];
3748 [overlay_ addSubview:prompt_];
3750 CGSize prgsize = {75, 100};
3753 ovrrect.size.width - prgsize.width - 10,
3754 (ovrrect.size.height - prgsize.height) / 2
3757 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3758 [progress_ setStyle:0];
3759 [overlay_ addSubview:progress_];
3764 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
3767 status.setDelegate(self);
3769 [database_ updateWithStatus:status];
3772 performSelectorOnMainThread:@selector(_update_)
3780 - (void) setProgressError:(NSString *)error {
3782 performSelectorOnMainThread:@selector(_setProgressError:)
3788 - (void) setProgressTitle:(NSString *)title {
3790 performSelectorOnMainThread:@selector(_setProgressTitle:)
3796 - (void) setProgressPercent:(float)percent {
3799 - (void) addProgressOutput:(NSString *)output {
3801 performSelectorOnMainThread:@selector(_addProgressOutput:)
3807 - (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
3811 - (void) _setProgressError:(NSString *)error {
3812 [prompt_ setText:[NSString stringWithFormat:@"Error: %@", error]];
3815 - (void) _setProgressTitle:(NSString *)title {
3816 [prompt_ setText:[title stringByAppendingString:@"..."]];
3819 - (void) _addProgressOutput:(NSString *)output {
3824 @interface Cydia : UIApplication <
3825 ConfirmationViewDelegate,
3826 ProgressViewDelegate,
3835 UIButtonBar *buttonbar_;
3837 ConfirmationView *confirm_;
3839 Database *database_;
3840 ProgressView *progress_;
3844 UIKeyboard *keyboard_;
3846 InstallView *install_;
3847 ChangesView *changes_;
3848 ManageView *manage_;
3849 SearchView *search_;
3854 @implementation Cydia
3856 - (void) _reloadData {
3857 /*UIProgressHUD *hud = [[UIProgressHUD alloc] initWithWindow:window_];
3858 [hud setText:@"Reloading Data"];
3859 [overlay_ addSubview:hud];
3862 [database_ reloadData];
3866 if (Packages_ == nil) {
3867 Packages_ = [[NSMutableDictionary alloc] initWithCapacity:count];
3868 [Metadata_ setObject:Packages_ forKey:@"Packages"];
3873 NSArray *packages = [database_ packages];
3874 for (int i(0), e([packages count]); i != e; ++i) {
3875 Package *package = [packages objectAtIndex:i];
3876 if ([package upgradable])
3881 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
3882 [buttonbar_ setBadgeValue:badge forButton:3];
3883 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
3884 [buttonbar_ setBadgeAnimated:YES forButton:3];
3885 [self setApplicationBadge:badge];
3887 [buttonbar_ setBadgeValue:nil forButton:3];
3888 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
3889 [buttonbar_ setBadgeAnimated:NO forButton:3];
3890 [self removeApplicationBadge];
3893 _assert([Metadata_ writeToFile:@"/var/lib/cydia/metadata.plist" atomically:YES] == YES);
3895 /* XXX: this is just stupid */
3897 [install_ reloadData];
3899 [changes_ reloadData];
3901 [manage_ reloadData];
3903 [search_ reloadData];
3907 [hud removeFromSuperview];*/
3910 - (void) reloadData {
3911 @synchronized (self) {
3912 if (confirm_ == nil)
3918 pkgProblemResolver *resolver = [database_ resolver];
3920 resolver->InstallProtect();
3921 if (!resolver->Resolve(true))
3926 [database_ prepare];
3928 if ([database_ cache]->BrokenCount() == 0)
3929 confirm_ = [[ConfirmationView alloc] initWithView:underlay_ database:database_ delegate:self];
3931 NSMutableArray *broken = [NSMutableArray arrayWithCapacity:16];
3932 NSArray *packages = [database_ packages];
3934 for (size_t i(0); i != [packages count]; ++i) {
3935 Package *package = [packages objectAtIndex:i];
3936 if ([package broken])
3937 [broken addObject:[package name]];
3940 UIAlertSheet *sheet = [[[UIAlertSheet alloc]
3941 initWithTitle:[NSString stringWithFormat:@"%d Broken Packages", [database_ cache]->BrokenCount()]
3942 buttons:[NSArray arrayWithObjects:@"Okay", nil]
3943 defaultButtonIndex:0
3948 [sheet setBodyText:[NSString stringWithFormat:@"The following packages have unmet dependencies:\n\n%@", [broken componentsJoinedByString:@"\n"]]];
3949 [sheet popupAlertAnimated:YES];
3955 - (void) installPackage:(Package *)package {
3956 @synchronized (self) {
3963 - (void) removePackage:(Package *)package {
3964 @synchronized (self) {
3971 - (void) distUpgrade {
3972 @synchronized (self) {
3973 [database_ upgrade];
3979 @synchronized (self) {
3987 [overlay_ removeFromSuperview];
3991 detachNewThreadSelector:@selector(perform)
3998 - (void) bootstrap_ {
4000 [database_ upgrade];
4001 [database_ prepare];
4002 [database_ perform];
4005 - (void) bootstrap {
4007 detachNewThreadSelector:@selector(bootstrap_)
4010 title:@"Bootstrap Install..."
4014 - (void) progressViewIsComplete:(ProgressView *)progress {
4015 @synchronized (self) {
4018 if (confirm_ != nil) {
4019 [underlay_ addSubview:overlay_];
4020 [confirm_ removeFromSuperview];
4027 - (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
4031 - (void) setPage:(RVPage *)page {
4032 [page resetViewAnimated:NO];
4033 [page setDelegate:self];
4034 [book_ setPage:page];
4037 - (RVPage *) _setHomePage {
4038 BrowserView *browser = [[[BrowserView alloc] initWithBook:book_ database:database_] autorelease];
4039 [self setPage:browser];
4040 [browser loadURL:[NSURL URLWithString:@"http://cydia.saurik.com/"]];
4044 - (void) buttonBarItemTapped:(id)sender {
4045 unsigned tag = [sender tag];
4047 [book_ resetViewAnimated:YES];
4053 [self _setHomePage];
4057 [self setPage:install_];
4061 [self setPage:changes_];
4065 [self setPage:manage_];
4069 [self setPage:search_];
4079 - (void) applicationWillSuspend {
4080 [super applicationWillSuspend];
4083 if (FW_LEAST(1,1,3))
4084 notify_post("com.apple.language.changed");
4086 system("launchctl stop com.apple.SpringBoard");
4089 - (void) applicationDidFinishLaunching:(id)unused {
4090 _assert(pkgInitConfig(*_config));
4091 _assert(pkgInitSystem(*_config, _system));
4096 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
4097 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
4099 [window_ orderFront: self];
4100 [window_ makeKey: self];
4101 [window_ _setHidden: NO];
4103 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] delegate:self];
4104 [window_ setContentView:progress_];
4106 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
4107 [progress_ setContentView:underlay_];
4109 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
4112 [underlay_ addSubview:overlay_];
4114 database_ = [[Database alloc] init];
4115 [database_ setDelegate:progress_];
4117 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
4118 0, 0, screenrect.size.width, screenrect.size.height - 48
4119 ) database:database_];
4121 [book_ setDelegate:self];
4123 [overlay_ addSubview:book_];
4125 NSArray *buttonitems = [NSArray arrayWithObjects:
4126 [NSDictionary dictionaryWithObjectsAndKeys:
4127 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
4128 @"home-up.png", kUIButtonBarButtonInfo,
4129 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
4130 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
4131 self, kUIButtonBarButtonTarget,
4132 @"Home", kUIButtonBarButtonTitle,
4133 @"0", kUIButtonBarButtonType,
4136 [NSDictionary dictionaryWithObjectsAndKeys:
4137 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
4138 @"install-up.png", kUIButtonBarButtonInfo,
4139 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
4140 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
4141 self, kUIButtonBarButtonTarget,
4142 @"Install", kUIButtonBarButtonTitle,
4143 @"0", kUIButtonBarButtonType,
4146 [NSDictionary dictionaryWithObjectsAndKeys:
4147 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
4148 @"changes-up.png", kUIButtonBarButtonInfo,
4149 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
4150 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
4151 self, kUIButtonBarButtonTarget,
4152 @"Changes", kUIButtonBarButtonTitle,
4153 @"0", kUIButtonBarButtonType,
4156 [NSDictionary dictionaryWithObjectsAndKeys:
4157 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
4158 @"manage-up.png", kUIButtonBarButtonInfo,
4159 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
4160 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
4161 self, kUIButtonBarButtonTarget,
4162 @"Manage", kUIButtonBarButtonTitle,
4163 @"0", kUIButtonBarButtonType,
4166 [NSDictionary dictionaryWithObjectsAndKeys:
4167 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
4168 @"search-up.png", kUIButtonBarButtonInfo,
4169 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
4170 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
4171 self, kUIButtonBarButtonTarget,
4172 @"Search", kUIButtonBarButtonTitle,
4173 @"0", kUIButtonBarButtonType,
4177 buttonbar_ = [[UIButtonBar alloc]
4179 withFrame:CGRectMake(
4180 0, screenrect.size.height - 48,
4181 screenrect.size.width, 48
4183 withItemList:buttonitems
4186 [buttonbar_ setDelegate:self];
4187 [buttonbar_ setBarStyle:1];
4188 [buttonbar_ setButtonBarTrackingMode:2];
4190 int buttons[5] = {1, 2, 3, 4, 5};
4191 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
4192 [buttonbar_ showButtonGroup:0 withDuration:0];
4194 for (int i = 0; i != 5; ++i)
4195 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
4196 i * 64 + 2, 1, 60, 48
4199 [buttonbar_ showSelectionForButton:1];
4200 [overlay_ addSubview:buttonbar_];
4202 [UIKeyboard initImplementationNow];
4203 CGSize keysize = [UIKeyboard defaultSize];
4204 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
4205 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
4206 [[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
4207 [overlay_ addSubview:keyboard_];
4209 install_ = [[InstallView alloc] initWithBook:book_ database:database_];
4210 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
4211 manage_ = [[ManageView alloc] initWithBook:book_ database:database_];
4212 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
4217 [progress_ resetView];
4222 [self _setHomePage];
4225 - (void) showKeyboard:(BOOL)show {
4226 CGSize keysize = [UIKeyboard defaultSize];
4227 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
4228 CGRect keyup = keydown;
4229 keyup.origin.y -= keysize.height;
4231 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
4232 [animation setSignificantRectFields:2];
4235 [animation setStartFrame:keydown];
4236 [animation setEndFrame:keyup];
4237 [keyboard_ activate];
4239 [animation setStartFrame:keyup];
4240 [animation setEndFrame:keydown];
4241 [keyboard_ deactivate];
4244 [[UIAnimator sharedAnimator]
4245 addAnimations:[NSArray arrayWithObjects:animation, nil]
4251 - (void) slideUp:(UIAlertSheet *)alert {
4252 [alert presentSheetFromButtonBar:buttonbar_];
4257 void AddPreferences(NSString *plist) {
4258 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4260 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
4261 _assert(settings != NULL);
4262 NSMutableArray *items = [settings objectForKey:@"items"];
4266 for (size_t i(0); i != [items count]; ++i) {
4267 NSMutableDictionary *item([items objectAtIndex:i]);
4268 NSString *label = [item objectForKey:@"label"];
4269 if (label != nil && [label isEqualToString:@"Cydia"]) {
4276 for (size_t i(0); i != [items count]; ++i) {
4277 NSDictionary *item([items objectAtIndex:i]);
4278 NSString *label = [item objectForKey:@"label"];
4279 if (label != nil && [label isEqualToString:@"General"]) {
4280 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
4281 @"CydiaSettings", @"bundle",
4282 @"PSLinkCell", @"cell",
4283 [NSNumber numberWithBool:YES], @"hasIcon",
4284 [NSNumber numberWithBool:YES], @"isController",
4286 nil] atIndex:(i + 1)];
4292 _assert([settings writeToFile:plist atomically:YES] == YES);
4299 id Alloc_(id self, SEL selector) {
4300 id object = alloc_(self, selector);
4301 fprintf(stderr, "[%s]A-%p\n", self->isa->name, object);
4306 id Dealloc_(id self, SEL selector) {
4307 id object = dealloc_(self, selector);
4308 fprintf(stderr, "[%s]D-%p\n", self->isa->name, object);
4312 int main(int argc, char *argv[]) {
4313 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4315 bootstrap_ = argc > 1 && strcmp(argv[1], "--bootstrap") == 0;
4317 Home_ = NSHomeDirectory();
4320 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
4321 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
4322 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
4323 Sounds_Keyboard_ = [keyboard boolValue];
4329 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
4330 alloc_ = alloc->method_imp;
4331 alloc->method_imp = (IMP) &Alloc_;*/
4333 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
4334 dealloc_ = dealloc->method_imp;
4335 dealloc->method_imp = (IMP) &Dealloc_;*/
4337 if (NSDictionary *sysver = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"]) {
4338 if (NSString *prover = [sysver valueForKey:@"ProductVersion"]) {
4339 Firmware_ = strdup([prover UTF8String]);
4340 NSArray *versions = [prover componentsSeparatedByString:@"."];
4341 int count = [versions count];
4342 Major_ = count > 0 ? [[versions objectAtIndex:0] intValue] : 0;
4343 Minor_ = count > 1 ? [[versions objectAtIndex:1] intValue] : 0;
4344 BugFix_ = count > 2 ? [[versions objectAtIndex:2] intValue] : 0;
4349 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
4350 char *machine = new char[size];
4351 sysctlbyname("hw.machine", machine, &size, NULL, 0);
4354 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice"))
4355 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
4356 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
4357 SerialNumber_ = strdup(CFStringGetCStringPtr((CFStringRef) serial, CFStringGetSystemEncoding()));
4361 IOObjectRelease(service);
4364 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
4365 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
4367 if ((Metadata_ = [[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"]) == NULL)
4368 Metadata_ = [[NSMutableDictionary alloc] initWithCapacity:2];
4370 Packages_ = [Metadata_ objectForKey:@"Packages"];
4372 setenv("CYDIA", "", _not(int));
4373 if (access("/User", F_OK) != 0)
4374 system("/usr/libexec/cydia/firmware.sh");
4375 system("dpkg --configure -a");
4377 space_ = CGColorSpaceCreateDeviceRGB();
4379 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
4380 Clear_.Set(space_, 0.0, 0.0, 0.0, 0.0);
4381 Red_.Set(space_, 1.0, 0.0, 0.0, 1.0);
4382 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
4384 int value = UIApplicationMain(argc, argv, [Cydia class]);
4386 CGColorSpaceRelease(space_);