X-Git-Url: https://git.saurik.com/cydia.git/blobdiff_plain/bb6bb6d60bf7e9c0bd5acb102bed9e3f4417dae8..1b1d445bc087b7d185fb0ec63c8c96d17704c954:/MobileCydia.mm diff --git a/MobileCydia.mm b/MobileCydia.mm index 970ffa3d..afd02875 100644 --- a/MobileCydia.mm +++ b/MobileCydia.mm @@ -102,6 +102,7 @@ #include #include #include +#include #include #include @@ -121,6 +122,7 @@ extern "C" { #include #include "UICaboodle/BrowserView.h" +#include "SDURLCache/SDURLCache.h" #include "substrate.h" /* }}} */ @@ -276,8 +278,6 @@ static _finline void UpdateExternalStatus(uint64_t newStatus) { } - (id) yieldToSelector:(SEL)selector withObject:(id)object { - /*return [self performSelector:selector withObject:object];*/ - volatile bool stopped(false); NSMutableArray *context([NSMutableArray arrayWithObjects: @@ -1012,9 +1012,6 @@ class CYColor { /* Random Global Variables {{{ */ static const int PulseInterval_ = 50000; -static const int ButtonBarWidth_ = 60; -static const int ButtonBarHeight_ = 48; -static const float KeyboardTime_ = 0.3f; static int Finish_; static NSArray *Finishes_; @@ -1101,9 +1098,7 @@ NSString *SizeString(double size) { static _finline const char *StripVersion_(const char *version) { const char *colon(strchr(version, ':')); - if (colon != NULL) - version = colon + 1; - return version; + return colon == NULL ? version : colon + 1; } NSString *LocalizeSection(NSString *section) { @@ -1187,6 +1182,8 @@ bool isSectionVisible(NSString *section) { @class PackageController; @protocol CydiaDelegate +- (void) retainNetworkActivityIndicator; +- (void) releaseNetworkActivityIndicator; - (void) setPackageController:(PackageController *)view; - (void) clearPackage:(Package *)package; - (void) installPackage:(Package *)package; @@ -1200,12 +1197,13 @@ bool isSectionVisible(NSString *section) { - (void) syncData; - (void) showSettings; - (UIProgressHUD *) addProgressHUD; -- (BOOL) hudIsShowing; - (void) removeProgressHUD:(UIProgressHUD *)hud; - (CYViewController *) pageForPackage:(NSString *)name; - (PackageController *) packageController; - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item; @end + +static id CydiaApp; /* }}} */ /* Status Delegation {{{ */ @@ -1348,6 +1346,7 @@ typedef std::map< unsigned long, _H > SourceMap; pkgSourceList *list_; SourceMap sources_; + CFMutableArrayRef deadSources_; CFMutableArrayRef packages_; _transient NSObject *delegate_; @@ -1357,6 +1356,8 @@ typedef std::map< unsigned long, _H > SourceMap; int cydiafd_; int statusfd_; FILE *input_; + + std::map > sections_; } + (Database *) sharedInstance; @@ -1390,6 +1391,9 @@ typedef std::map< unsigned long, _H > SourceMap; - (void) setDelegate:(id)delegate; - (Source *) getSource:(pkgCache::PkgFileIterator)file; + +- (NSString *) mappedSectionForPointer:(const char *)pointer; + @end /* }}} */ /* Delegate Helpers {{{ */ @@ -1432,7 +1436,6 @@ typedef std::map< unsigned long, _H > SourceMap; struct PackageValue : Cytore::Block { - Cytore::Offset reserved_; Cytore::Offset next_; uint32_t index_ : 23; @@ -1452,7 +1455,7 @@ struct PackageValue : struct MetaValue : Cytore::Block { - Cytore::Offset reserved_; + uint32_t active_; Cytore::Offset packages_[1 << 16]; }; @@ -1494,7 +1497,7 @@ static void PackageImport(const void *key, const void *value, void *context) { NSDictionary *package((NSDictionary *) value); if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"]) - if ([subscribed boolValue]) + if ([subscribed boolValue] && !metadata->subscribed_) metadata->subscribed_ = true; if (NSDate *date = [package objectForKey:@"FirstSeen"]) { @@ -1503,24 +1506,24 @@ static void PackageImport(const void *key, const void *value, void *context) { metadata->first_ = time; } - if (NSDate *date = [package objectForKey:@"LastSeen"]) { + NSDate *date([package objectForKey:@"LastSeen"]); + NSString *version([package objectForKey:@"LastVersion"]); + + if (date != nil && version != nil) { time_t time([date timeIntervalSince1970]); - if (metadata->last_ < time || metadata->last_ == 0) { - metadata->last_ = time; - goto last; - } - } else if (metadata->last_ == 0) last: { - NSString *version([package objectForKey:@"LastVersion"]); - if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) { - size_t length(strlen(buffer)); - uint16_t vhash(hashlittle(buffer, length)); + if (metadata->last_ < time || metadata->last_ == 0) + if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) { + size_t length(strlen(buffer)); + uint16_t vhash(hashlittle(buffer, length)); - size_t capped(std::min(8, length)); - char *latest(buffer + length - capped); + size_t capped(std::min(8, length)); + char *latest(buffer + length - capped); - strncpy(metadata->version_, latest, sizeof(metadata->version_)); - metadata->vhash_ = vhash; - } + strncpy(metadata->version_, latest, sizeof(metadata->version_)); + metadata->vhash_ = vhash; + + metadata->last_ = time; + } } } // }}} @@ -1828,34 +1831,35 @@ struct ParsedPackage { }; @interface Package : NSObject { - unsigned era_; + uint32_t era_ : 26; + uint32_t role_ : 3; + uint32_t essential_ : 1; + uint32_t obsolete_ : 1; + uint32_t ignored_ : 1; + apr_pool_t *pool_; + _transient Database *database_; + pkgCache::VerIterator version_; pkgCache::PkgIterator iterator_; - _transient Database *database_; pkgCache::VerFileIterator file_; - Source *source_; - ParsedPackage *parsed_; - - CYString section_; - _transient NSString *section$_; - bool essential_; - bool obsolete_; + CYString id_; + CYString name_; CYString latest_; CYString installed_; - CYString id_; - CYString name_; + const char *section_; + _transient NSString *section$_; - NSMutableArray *tags_; - NSString *role_; + Source *source_; PackageValue *metadata_; + ParsedPackage *parsed_; - bool ignored_; + NSMutableArray *tags_; } - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database; @@ -1917,7 +1921,6 @@ struct ParsedPackage { - (NSArray *) applications; - (Source *) source; -- (NSString *) role; - (BOOL) matches:(NSString *)text; @@ -1927,6 +1930,8 @@ struct ParsedPackage { - (NSArray *) purposes; - (bool) isCommercial; +- (void) setIndex:(size_t)index; + - (CYString &) cyname; - (uint32_t) compareBySection:(NSArray *)sections; @@ -1969,9 +1974,6 @@ uint32_t PackageChangesRadix(Package *self, void *) { return _not(uint32_t) - value.key; } -_finline static void Stifle(uint8_t &value) { -} - uint32_t PackagePrefixRadix(Package *self, void *context) { size_t offset(reinterpret_cast(context)); CYString &name([self cyname]); @@ -1994,8 +1996,6 @@ uint32_t PackagePrefixRadix(Package *self, void *context) { uint8_t data[4]; - // 0.607997 - if (offset == 0 && zeros != 0) { memset(data, '0', zeros); memcpy(data + zeros, text, 4 - zeros); @@ -2081,15 +2081,10 @@ struct PackageNameOrdering : - (void) dealloc { if (parsed_ != NULL) delete parsed_; - if (source_ != nil) [source_ release]; - if (tags_ != nil) [tags_ release]; - if (role_ != nil) - [role_ release]; - [super dealloc]; } @@ -2186,27 +2181,17 @@ struct PackageNameOrdering : - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database { if ((self = [super init]) != nil) { _profile(Package$initWithVersion) - era_ = [database era]; pool_ = pool; - version_ = version; - - _profile(Package$initWithVersion$ParentPkg) - iterator_ = version.ParentPkg(); - _end - database_ = database; + era_ = [database era]; - _profile(Package$initWithVersion$Latest) - latest_.set(NULL, StripVersion_(version_.VerStr())); - _end + version_ = version; - pkgCache::VerIterator current; - _profile(Package$initWithVersion$Versions) - current = iterator_.CurrentVer(); - if (!current.end()) - installed_.set(NULL, StripVersion_(current.VerStr())); + pkgCache::PkgIterator iterator(version.ParentPkg()); + iterator_ = iterator; + _profile(Package$initWithVersion$Version) if (!version_.end()) file_ = version_.FileList(); else { @@ -2215,34 +2200,36 @@ struct PackageNameOrdering : } _end - _profile(Package$initWithVersion$Name) - id_.set(NULL, iterator_.Name()); - name_.set(NULL, iterator_.Display()); - _end + _profile(Package$initWithVersion$Cache) + name_.set(NULL, iterator.Display()); - _profile(Package$initWithVersion$lowercaseString) - // XXX: do not use tolower() as this is not locale-specific? :( - char *data(id_.data()); - for (size_t i(0), e(id_.size()); i != e; ++i) - if ((data[i] & 0x20) == 0) { - id_.copy(pool); - data = id_.data(); - for (; i != e; ++i) - data[i] |= 0x20; - break; - } + latest_.set(NULL, StripVersion_(version_.VerStr())); + + pkgCache::VerIterator current(iterator.CurrentVer()); + if (!current.end()) + installed_.set(NULL, StripVersion_(current.VerStr())); _end _profile(Package$initWithVersion$Tags) - pkgCache::TagIterator tag(iterator_.TagList()); + pkgCache::TagIterator tag(iterator.TagList()); if (!tag.end()) { tags_ = [[NSMutableArray alloc] initWithCapacity:8]; do { const char *name(tag.Name()); [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]]; - if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) - role_ = (NSString *) CYStringCreate(name + 6); + if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) { + if (strcmp(name + 6, "enduser") == 0) + role_ = 1; + else if (strcmp(name + 6, "hacker") == 0) + role_ = 2; + else if (strcmp(name + 6, "developer") == 0) + role_ = 3; + else if (strcmp(name + 6, "cydia") == 0) + role_ = 7; + else + role_ = 4; + } if (strncmp(name, "cydia::", 7) == 0) { if (strcmp(name + 7, "essential") == 0) @@ -2257,9 +2244,19 @@ struct PackageNameOrdering : _end _profile(Package$initWithVersion$Metadata) - PackageValue *metadata(PackageFind(id_.data(), id_.size())); + const char *mixed(iterator.Name()); + size_t size(strlen(mixed)); + char lower[size + 1]; + + for (size_t i(0); i != size; ++i) + lower[i] = mixed[i] | 0x20; + lower[size] = '\0'; + + PackageValue *metadata(PackageFind(lower, size)); metadata_ = metadata; + id_.set(NULL, metadata->name_, size); + const char *latest(version_.VerStr()); size_t length(strlen(latest)); @@ -2272,22 +2269,21 @@ struct PackageNameOrdering : metadata->first_ = now_; if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) { - metadata->last_ = now_; strncpy(metadata->version_, latest, sizeof(metadata->version_)); metadata->vhash_ = vhash; + metadata->last_ = now_; } else if (metadata->last_ == 0) metadata->last_ = metadata->first_; _end _profile(Package$initWithVersion$Section) - section_.set(NULL, iterator_.Section()); + section_ = iterator.Section(); _end - _profile(Package$initWithVersion$hasTag) - essential_ |= ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES); + _profile(Package$initWithVersion$Flags) + essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES); + ignored_ = iterator->SelectedState == pkgCache::State::Hold; _end - - ignored_ = iterator_->SelectedState == pkgCache::State::Hold; _end } return self; } @@ -2301,12 +2297,26 @@ struct PackageNameOrdering : if (version.end()) return nil; - return [[[Package alloc] - initWithVersion:version - withZone:zone - inPool:pool - database:database - ] autorelease]; + Package *package; + + _profile(Package$packageWithIterator$Allocate) + package = [Package allocWithZone:zone]; + _end + + _profile(Package$packageWithIterator$Initialize) + package = [package + initWithVersion:version + withZone:zone + inPool:pool + database:database + ]; + _end + + _profile(Package$packageWithIterator$Autorelease) + package = [package autorelease]; + _end + + return package; } - (pkgCache::PkgIterator) iterator { @@ -2315,13 +2325,11 @@ struct PackageNameOrdering : - (NSString *) section { if (section$_ == nil) { - if (section_.empty()) + if (section_ == NULL) return nil; - _profile(Package$section) - std::replace(section_.data(), section_.data() + section_.size(), '_', ' '); - NSString *name(section_); - section$_ = [SectionMap_ objectForKey:name] ?: name; + _profile(Package$section$mappedSectionForPointer) + section$_ = [database_ mappedSectionForPointer:section_]; _end } return section$_; } @@ -2471,12 +2479,12 @@ struct PackageNameOrdering : - (BOOL) unfiltered { _profile(Package$unfiltered$obsolete) - if (obsolete_) + if (_unlikely(obsolete_)) return false; _end _profile(Package$unfiltered$hasSupportingRole) - if (![self hasSupportingRole]) + if (_unlikely(![self hasSupportingRole])) return false; _end @@ -2487,7 +2495,11 @@ struct PackageNameOrdering : if (![self unfiltered]) return false; - NSString *section([self section]); + NSString *section; + + _profile(Package$visible$section) + section = [self section]; + _end _profile(Package$visible$isSectionVisible) if (section != nil && !isSectionVisible(section)) @@ -2710,10 +2722,6 @@ struct PackageNameOrdering : return source_ == (Source *) [NSNull null] ? nil : source_; } -- (NSString *) role { - return role_; -} - - (BOOL) matches:(NSString *)text { if (text == nil) return NO; @@ -2736,17 +2744,17 @@ struct PackageNameOrdering : } - (bool) hasSupportingRole { - if (role_ == nil) + if (role_ == 0) return true; - if ([role_ isEqualToString:@"enduser"]) + if (role_ == 1) return true; if ([Role_ isEqualToString:@"User"]) return false; - if ([role_ isEqualToString:@"hacker"]) + if (role_ == 2) return true; if ([Role_ isEqualToString:@"Hacker"]) return false; - if ([role_ isEqualToString:@"developer"]) + if (role_ == 3) return true; if ([Role_ isEqualToString:@"Developer"]) return false; @@ -2776,6 +2784,11 @@ struct PackageNameOrdering : return [self hasTag:@"cydia::commercial"]; } +- (void) setIndex:(size_t)index { + if (metadata_->index_ != index) + metadata_->index_ = index; +} + - (CYString &) cyname { return name_.empty() ? id_ : name_; } @@ -2863,7 +2876,7 @@ struct PackageNameOrdering : } - (bool) isInstalledAndUnfiltered:(NSNumber *)number { - return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]); + return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]); } - (bool) isVisibleInSection:(NSString *)name { @@ -3028,6 +3041,8 @@ static NSString *Warning_; - (void) dealloc { // XXX: actually implement this thing _assert(false); + if (deadSources_) + CFRelease(deadSources_); [self releasePackages]; apr_pool_destroy(pool_); NSRecycleZone(zone_); @@ -3138,7 +3153,14 @@ static NSString *Warning_; zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO); apr_pool_create(&pool_, NULL); - packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL); + size_t capacity(MetaFile_->active_); + if (capacity == 0) + capacity = 16384; + else + capacity += 1024; + + packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL); + deadSources_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); int fds[2]; @@ -3213,6 +3235,7 @@ static NSString *Warning_; NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]); for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i) [sources addObject:i->second]; + [sources addObjectsFromArray:(NSArray *)deadSources_]; return sources; } @@ -3319,7 +3342,9 @@ static NSString *Warning_; ++era_; [self releasePackages]; + sources_.clear(); + CFArrayRemoveAllValues(deadSources_); _error->Discard(); @@ -3340,7 +3365,9 @@ static NSString *Warning_; cache_.Close(); apr_pool_clear(pool_); + NSRecycleZone(zone_); + zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO); int chk(creat("/tmp/cydia.chk", 0644)); if (chk != -1) @@ -3407,14 +3434,19 @@ static NSString *Warning_; } for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) { + bool found = false; std::vector *indices = (*source)->GetIndexFiles(); for (std::vector::const_iterator index = indices->begin(); index != indices->end(); ++index) // XXX: this could be more intelligent if (dynamic_cast(*index) != NULL) { pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_)); - if (!cached.end()) + if (!cached.end()) { sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]; + found = true; + } } + if (!found) + CFArrayAppendValue(deadSources_, [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]); } { @@ -3459,6 +3491,14 @@ static NSString *Warning_; //[packages_ sortUsingFunction:reinterpret_cast(&PackageNameCompare) context:NULL]; _trace(); + + size_t count(CFArrayGetCount(packages_)); + MetaFile_->active_ = count; + + for (size_t index(0); index != count; ++index) + [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index]; + + _trace(); } } } CYPoolEnd() _trace(); } @@ -3477,7 +3517,9 @@ static NSString *Warning_; - (void) configure { NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_]; + _trace(); system([dpkg UTF8String]); + _trace(); } - (bool) clean { @@ -3551,6 +3593,8 @@ static NSString *Warning_; return; } + [CydiaApp retainNetworkActivityIndicator]; + bool failed = false; for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) { if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete) @@ -3572,6 +3616,8 @@ static NSString *Warning_; ]; } + [CydiaApp releaseNetworkActivityIndicator]; + if (failed) { _trace(); return; @@ -3650,6 +3696,37 @@ static NSString *Warning_; return i == sources_.end() ? nil : i->second; } +- (NSString *) mappedSectionForPointer:(const char *)section { + _H *mapped; + + _profile(Database$mappedSectionForPointer$Cache) + mapped = §ions_[section]; + _end + + if (*mapped == NULL) { + size_t length(strlen(section)); + char spaced[length + 1]; + + _profile(Database$mappedSectionForPointer$Replace) + for (size_t index(0); index != length; ++index) + spaced[index] = section[index] == '_' ? ' ' : section[index]; + spaced[length] = '\0'; + _end + + NSString *string; + + _profile(Database$mappedSectionForPointer$stringWithUTF8String) + string = [NSString stringWithUTF8String:spaced]; + _end + + _profile(Database$mappedSectionForPointer$Map) + string = [SectionMap_ objectForKey:string] ?: string; + _end + + *mapped = string; + } return *mapped; +} + @end /* }}} */ @@ -3906,6 +3983,71 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { @end /* }}} */ +/* @ Loading... Indicator {{{ */ +@interface CYLoadingIndicator : UIView { + UIActivityIndicatorView *spinner_; + UILabel *label_; + UIView *container_; +} + +@property (readonly, nonatomic) UILabel *label; +@property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView; + +@end + +@implementation CYLoadingIndicator + +- (id)initWithFrame:(CGRect)frame { + if ((self = [super initWithFrame:frame])) { + container_ = [[[UIView alloc] init] autorelease]; + [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin]; + + spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease]; + [spinner_ startAnimating]; + [container_ addSubview:spinner_]; + + label_ = [[[UILabel alloc] init] autorelease]; + [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]]; + [label_ setBackgroundColor:[UIColor clearColor]]; + [label_ setTextColor:[UIColor blackColor]]; + [label_ setShadowColor:[UIColor whiteColor]]; + [label_ setShadowOffset:CGSizeMake(0, 1)]; + [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]]; + [container_ addSubview:label_]; + + CGSize viewsize = frame.size; + CGSize spinnersize = [spinner_ bounds].size; + CGSize textsize = [[label_ text] sizeWithFont:[label_ font]]; + float bothwidth = spinnersize.width + textsize.width + 5.0f; + + CGRect containrect = { + CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))), + CGSizeMake(bothwidth, spinnersize.height) + }; + CGRect textrect = { + CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))), + textsize + }; + CGRect spinrect = { + CGPointZero, + spinnersize + }; + + [container_ setFrame:containrect]; + [spinner_ setFrame:spinrect]; + [label_ setFrame:textrect]; + [self addSubview:container_]; + } + + return self; +} + +- (UILabel *)label { return label_; } +- (UIActivityIndicatorView *)activityIndicatorView { return spinner_; } + +@end +/* }}} */ + /* Cydia Browser Controller {{{ */ @interface CYBrowserController : BrowserController { CydiaObject *cydia_; @@ -4407,15 +4549,24 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { break; case 2: - system("launchctl stop com.apple.SpringBoard"); - break; + _trace(); + goto reload; case 3: - system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_); + _trace(); + goto reload; + + reload: + system("/usr/bin/sbreload"); + _trace(); break; case 4: - system("reboot"); + _trace(); + if (void (*SBReboot)(mach_port_t) = reinterpret_cast(dlsym(RTLD_DEFAULT, "SBReboot"))) + SBReboot(SBSSpringBoardServerPort()); + else + reboot2(RB_AUTOBOOT); break; } } @@ -4464,7 +4615,9 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break; } + _trace(); system("su -c /usr/bin/uicache mobile"); + _trace(); UpdateExternalStatus(Finish_ == 0 ? 2 : 0); @@ -4637,8 +4790,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { - (void) _addProgressOutput:(NSString *)output { [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]]; CGSize size = [output_ contentSize]; - CGRect rect = {{0, size.height}, {size.width, 0}}; - [output_ scrollRectToVisible:rect animated:YES]; + CGPoint offset = [output_ contentOffset]; + if (size.height - offset.y < [output_ frame].size.height + 20.f) { + CGRect rect = {{0, size.height-1}, {size.width, 1}}; + [output_ scrollRectToVisible:rect animated:YES]; + } } - (BOOL) isRunning { @@ -4731,7 +4887,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { - (PackageCell *) init; - (void) setPackage:(Package *)package; -+ (int) heightForPackage:(Package *)package; - (void) drawContentRect:(CGRect)rect; @end @@ -4883,12 +5038,16 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { } if (badge_ != nil) { - CGSize size = [badge_ size]; + CGRect rect; + rect.size = [badge_ size]; + + rect.size.width /= 2; + rect.size.height /= 2; + + rect.origin.x = 36 - rect.size.width / 2; + rect.origin.y = 36 - rect.size.height / 2; - [badge_ drawAtPoint:CGPointMake( - 36 - size.width / 2, - 36 - size.height / 2 - )]; + [badge_ drawInRect:rect]; } if (highlighted) @@ -4907,10 +5066,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { [placard_ drawAtPoint:CGPointMake(width - 52, 9)]; } -+ (int) heightForPackage:(Package *)package { - return 73; -} - @end /* }}} */ /* Section Cell {{{ */ @@ -4980,14 +5135,14 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { } - (void) onSwitch:(id)sender { - NSMutableDictionary *metadata = [Sections_ objectForKey:basic_]; + NSMutableDictionary *metadata([Sections_ objectForKey:basic_]); if (metadata == nil) { metadata = [NSMutableDictionary dictionaryWithCapacity:2]; [Sections_ setObject:metadata forKey:basic_]; } - Changed_ = true; [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"]; + Changed_ = true; } - (void) setSection:(Section *)section editing:(BOOL)editing { @@ -5034,7 +5189,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { } - (void) drawContentRect:(CGRect)rect { - bool highlighted(highlighted_); + bool highlighted(highlighted_ && !editing_); [icon_ drawInRect:CGRectMake(8, 7, 32, 32)]; @@ -5296,7 +5451,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { } - (void) reloadButtonClicked { - // Don't reload a package view by clicking the button. + // Don't reload a commerical package by tapping the loading button, + // but if it's not an Install button, we should forward it on. + if (![package_ uninstalled]) + [self _customButtonClicked]; } - (void) applyLoadingTitle { @@ -5385,6 +5543,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { UITableViewDelegate > { _transient Database *database_; + unsigned era_; NSMutableArray *packages_; NSMutableArray *sections_; UITableView *list_; @@ -5424,13 +5583,17 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { [super dealloc]; } ++ (BOOL) hasIndexedCollation { + return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil; +} + - (NSInteger) numberOfSectionsInTableView:(UITableView *)list { NSInteger count([sections_ count]); return count == 0 ? 1 : count; } - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section { - if ([sections_ count] == 0) + if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0) return nil; return [[sections_ objectAtIndex:section] name]; } @@ -5442,11 +5605,15 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { } - (Package *) packageAtIndexPath:(NSIndexPath *)path { +@synchronized (database_) { + if ([database_ era] != era_) + return nil; + Section *section([sections_ objectAtIndex:[path section]]); NSInteger row([path row]); Package *package([packages_ objectAtIndex:([section row] + row)]); - return package; -} + return [[package retain] autorelease]; +} } - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path { PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]); @@ -5460,10 +5627,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; } -/*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path { - return [PackageCell heightForPackage:[self packageAtIndexPath:path]]; -}*/ - - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path { Package *package([self packageAtIndexPath:path]); package = [database_ packageWithName:[package id]]; @@ -5472,10 +5635,15 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { } - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView { + // XXX: is 20 the most optimal number here? return [packages_ count] > 20 ? index_ : nil; } -- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { +- (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { + if ([[self class] hasIndexedCollation]) { + return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index]; + } + return index; } @@ -5486,7 +5654,9 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { target_ = target; action_ = action; - index_ = [[NSMutableArray alloc] initWithCapacity:32]; + index_ = [[self class] hasIndexedCollation] + ? [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain] + : [[NSMutableArray alloc] initWithCapacity:32]; indices_ = [[NSMutableDictionary alloc] initWithCapacity:32]; packages_ = [[NSMutableArray arrayWithCapacity:16] retain]; @@ -5494,7 +5664,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain]; [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; - [list_ setRowHeight:73.0f]; + [list_ setRowHeight:73]; [self addSubview:list_]; [list_ setDataSource:self]; @@ -5511,6 +5681,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { } - (void) reloadData { + era_ = [database_ era]; NSArray *packages = [database_ packages]; [packages_ removeAllObjects]; @@ -5522,37 +5693,70 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { [packages_ addObject:package]; _end - [index_ removeAllObjects]; [indices_ removeAllObjects]; Section *section = nil; - _profile(PackageTable$reloadData$Section) - for (size_t offset(0), end([packages_ count]); offset != end; ++offset) { - Package *package; - unichar index; + if ([[self class] hasIndexedCollation]) { + id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation]; + NSArray *titles = [collation sectionIndexTitles]; + int secidx = -1; - _profile(PackageTable$reloadData$Section$Package) - package = [packages_ objectAtIndex:offset]; - index = [package index]; - _end + _profile(PackageTable$reloadData$Section) + for (size_t offset(0), end([packages_ count]); offset != end; ++offset) { + Package *package; + int index; - if (section == nil || [section index] != index) { - _profile(PackageTable$reloadData$Section$Allocate) - section = [[[Section alloc] initWithIndex:index row:offset] autorelease]; + _profile(PackageTable$reloadData$Section$Package) + package = [packages_ objectAtIndex:offset]; + index = [collation sectionForObject:package collationStringSelector:@selector(name)]; _end - [index_ addObject:[section name]]; - //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index]; + while (secidx < index) { + secidx += 1; - _profile(PackageTable$reloadData$Section$Add) - [sections_ addObject:section]; - _end + _profile(PackageTable$reloadData$Section$Allocate) + section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease]; + _end + + _profile(PackageTable$reloadData$Section$Add) + [sections_ addObject:section]; + _end + } + + [section addToCount]; } + _end + } else { + [index_ removeAllObjects]; - [section addToCount]; - } - _end + _profile(PackageTable$reloadData$Section) + for (size_t offset(0), end([packages_ count]); offset != end; ++offset) { + Package *package; + unichar index; + + _profile(PackageTable$reloadData$Section$Package) + package = [packages_ objectAtIndex:offset]; + index = [package index]; + _end + + if (section == nil || [section index] != index) { + _profile(PackageTable$reloadData$Section$Allocate) + section = [[[Section alloc] initWithIndex:index row:offset] autorelease]; + _end + + [index_ addObject:[section name]]; + //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index]; + + _profile(PackageTable$reloadData$Section$Add) + [sections_ addObject:section]; + _end + } + + [section addToCount]; + } + _end + } _profile(PackageTable$reloadData$List) [list_ reloadData]; @@ -5703,1430 +5907,1136 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { /* }}} */ -/* Add Source Controller {{{ */ -@interface AddSourceController : CYViewController { - _transient Database *database_; +/* Installed Controller {{{ */ +@interface InstalledController : FilteredPackageController { + BOOL expert_; } - (id) initWithDatabase:(Database *)database; +- (void) updateRoleButton; +- (void) queueStatusDidChange; + @end -@implementation AddSourceController +@implementation InstalledController + +- (void) dealloc { + [super dealloc]; +} + +- (NSString *) title { return UCLocalize("INSTALLED"); } - (id) initWithDatabase:(Database *)database { - if ((self = [super init]) != nil) { - database_ = database; + if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) { + [self updateRoleButton]; + [self queueStatusDidChange]; } return self; } -@end -/* }}} */ -/* Source Cell {{{ */ -@interface SourceCell : CYTableViewCell < - ContentDelegate -> { - UIImage *icon_; - NSString *origin_; - NSString *description_; - NSString *label_; +#if !AlwaysReload +- (void) queueButtonClicked { + [delegate_ queue]; } +#endif -- (void) setSource:(Source *)source; - -@end - -@implementation SourceCell - -- (void) clearSource { - [icon_ release]; - [origin_ release]; - [description_ release]; - [label_ release]; - - icon_ = nil; - origin_ = nil; - description_ = nil; - label_ = nil; +- (void) queueStatusDidChange { +#if !AlwaysReload + if (IsWildcat_) { + if (Queuing_) { + [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] + initWithTitle:UCLocalize("QUEUE") + style:UIBarButtonItemStyleDone + target:self + action:@selector(queueButtonClicked) + ] autorelease]]; + } else { + [[self navigationItem] setLeftBarButtonItem:nil]; + } + } +#endif } -- (void) setSource:(Source *)source { - [self clearSource]; +- (void) reloadData { + [packages_ reloadData]; +} - if (icon_ == nil) - icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]]; - if (icon_ == nil) - icon_ = [UIImage applicationImageNamed:@"unknown.png"]; - icon_ = [icon_ retain]; +- (void) updateRoleButton { + if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) + [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] + initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")) + style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain) + target:self + action:@selector(roleButtonClicked) + ] autorelease]]; +} - origin_ = [[source name] retain]; - label_ = [[source uri] retain]; - description_ = [[source description] retain]; +- (void) roleButtonClicked { + [packages_ setObject:[NSNumber numberWithBool:expert_]]; + [packages_ reloadData]; + expert_ = !expert_; - [content_ setNeedsDisplay]; + [self updateRoleButton]; } -- (void) dealloc { - [self clearSource]; - [super dealloc]; +- (void) setDelegate:(id)delegate { + [super setDelegate:delegate]; + [packages_ setDelegate:delegate]; } -- (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier { - if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) { - UIView *content([self contentView]); - CGRect bounds([content bounds]); - - content_ = [[ContentView alloc] initWithFrame:bounds]; - [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; - [content_ setBackgroundColor:[UIColor whiteColor]]; - [content addSubview:content_]; +@end +/* }}} */ - [content_ setDelegate:self]; - [content_ setOpaque:YES]; - } return self; +/* Home Controller {{{ */ +@interface HomeController : CYBrowserController { } -- (void) drawContentRect:(CGRect)rect { - bool highlighted(highlighted_); - float width(rect.size.width); - - if (icon_ != nil) - [icon_ drawInRect:CGRectMake(10, 10, 30, 30)]; +@end - if (highlighted) - UISetColor(White_); +@implementation HomeController - if (!highlighted) - UISetColor(Black_); - [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation]; ++ (BOOL)shouldHideNavigationBar { + return NO; +} - if (!highlighted) - UISetColor(Blue_); - [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation]; +- (void) _setMoreHeaders:(NSMutableURLRequest *)request { + [super _setMoreHeaders:request]; - if (!highlighted) - UISetColor(Gray_); - [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation]; + if (ChipID_ != nil) + [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"]; + if (UniqueID_ != nil) + [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"]; + if (PLMN_ != nil) + [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"]; } -@end -/* }}} */ -/* Source Table {{{ */ -@interface SourceTable : CYViewController < - UITableViewDataSource, - UITableViewDelegate -> { - _transient Database *database_; - UITableView *list_; - NSMutableArray *sources_; - int offset_; +- (void) aboutButtonClicked { + UIAlertView *alert([[[UIAlertView alloc] init] autorelease]); - NSString *href_; - UIProgressHUD *hud_; - NSError *error_; + [alert setTitle:UCLocalize("ABOUT_CYDIA")]; + [alert addButtonWithTitle:UCLocalize("CLOSE")]; + [alert setCancelButtonIndex:0]; - //NSURLConnection *installer_; - NSURLConnection *trivial_; - NSURLConnection *trivial_bz2_; - NSURLConnection *trivial_gz_; - //NSURLConnection *automatic_; + [alert setMessage: + @"Copyright (C) 2008-2010\n" + "Jay Freeman (saurik)\n" + "saurik@saurik.com\n" + "http://www.saurik.com/" + ]; - BOOL cydia_; + [alert show]; } -- (id) initWithDatabase:(Database *)database; - -- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated; - -@end - -@implementation SourceTable +- (void) viewWillAppear:(BOOL)animated { + [super viewWillAppear:animated]; -- (void) _releaseConnection:(NSURLConnection *)connection { - if (connection != nil) { - [connection cancel]; - //[connection setDelegate:nil]; - [connection release]; - } + if ([[self class] shouldHideNavigationBar]) + [[self navigationController] setNavigationBarHidden:YES animated:animated]; } -- (void) dealloc { - if (href_ != nil) - [href_ release]; - if (hud_ != nil) - [hud_ release]; - if (error_ != nil) - [error_ release]; - - //[self _releaseConnection:installer_]; - [self _releaseConnection:trivial_]; - [self _releaseConnection:trivial_gz_]; - [self _releaseConnection:trivial_bz2_]; - //[self _releaseConnection:automatic_]; +- (void) viewWillDisappear:(BOOL)animated { + [super viewWillDisappear:animated]; - [sources_ release]; - [list_ release]; - [super dealloc]; + if ([[self class] shouldHideNavigationBar]) + [[self navigationController] setNavigationBarHidden:NO animated:animated]; } -- (void) viewDidAppear:(BOOL)animated { - [super viewDidAppear:animated]; - [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; +- (id) init { + if ((self = [super init]) != nil) { + [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] + initWithTitle:UCLocalize("ABOUT") + style:UIBarButtonItemStylePlain + target:self + action:@selector(aboutButtonClicked) + ] autorelease]]; + } return self; } -- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { - return offset_ == 0 ? 1 : 2; +@end +/* }}} */ +/* Manage Controller {{{ */ +@interface ManageController : CYBrowserController { } -- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { - switch (section + (offset_ == 0 ? 1 : 0)) { - case 0: return UCLocalize("ENTERED_BY_USER"); - case 1: return UCLocalize("INSTALLED_BY_PACKAGE"); +- (void) queueStatusDidChange; +@end - _nodefault - } -} +@implementation ManageController -- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { - int count = [sources_ count]; - switch (section) { - case 0: return (offset_ == 0 ? count : offset_); - case 1: return count - offset_; +- (id) init { + if ((self = [super init]) != nil) { + [[self navigationItem] setTitle:UCLocalize("MANAGE")]; - _nodefault - } -} + [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] + initWithTitle:UCLocalize("SETTINGS") + style:UIBarButtonItemStylePlain + target:self + action:@selector(settingsButtonClicked) + ] autorelease]]; -- (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath { - unsigned idx = 0; - switch (indexPath.section) { - case 0: idx = indexPath.row; break; - case 1: idx = indexPath.row + offset_; break; + [self queueStatusDidChange]; + } return self; +} - _nodefault - } - return [sources_ objectAtIndex:idx]; +- (void) settingsButtonClicked { + [delegate_ showSettings]; } -- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { - Source *source = [self sourceAtIndexPath:indexPath]; - return [source description] == nil ? 56 : 73; +#if !AlwaysReload +- (void) queueButtonClicked { + [delegate_ queue]; } -- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { - static NSString *cellIdentifier = @"SourceCell"; +- (void) applyLoadingTitle { + // No "Loading" title. +} - SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; - if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease]; - [cell setSource:[self sourceAtIndexPath:indexPath]]; +- (void) applyRightButton { + // No right button. +} +#endif - return cell; +- (void) queueStatusDidChange { +#if !AlwaysReload + if (!IsWildcat_ && Queuing_) { + [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] + initWithTitle:UCLocalize("QUEUE") + style:UIBarButtonItemStyleDone + target:self + action:@selector(queueButtonClicked) + ] autorelease]]; + } else { + [[self navigationItem] setRightBarButtonItem:nil]; + } +#endif } -- (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath { - return UITableViewCellAccessoryDisclosureIndicator; +- (bool) isLoading { + return false; } -- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { - Source *source = [self sourceAtIndexPath:indexPath]; +@end +/* }}} */ - FilteredPackageController *packages = [[[FilteredPackageController alloc] - initWithDatabase:database_ - title:[source label] - filter:@selector(isVisibleInSource:) - with:source - ] autorelease]; +/* Refresh Bar {{{ */ +@interface RefreshBar : UINavigationBar { + UIProgressIndicator *indicator_; + UITextLabel *prompt_; + UIProgressBar *progress_; + UINavigationButton *cancel_; +} - [packages setDelegate:delegate_]; +@end - [[self navigationController] pushViewController:packages animated:YES]; -} +@implementation RefreshBar -- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { - Source *source = [self sourceAtIndexPath:indexPath]; - return [source record] != nil; +- (void) dealloc { + [indicator_ release]; + [prompt_ release]; + [progress_ release]; + [cancel_ release]; + [super dealloc]; } -- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { - Source *source = [self sourceAtIndexPath:indexPath]; - [Sources_ removeObjectForKey:[source key]]; - [delegate_ syncData]; -} - -- (void) complete { - [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys: - @"deb", @"Type", - href_, @"URI", - @"./", @"Distribution", - nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]]; +- (void) positionViews { + CGRect frame = [cancel_ frame]; + frame.size = [cancel_ sizeThatFits:frame.size]; + frame.origin.x = [self frame].size.width - frame.size.width - 5; + frame.origin.y = ([self frame].size.height - frame.size.height) / 2; + [cancel_ setFrame:frame]; - [delegate_ syncData]; -} + CGSize prgsize = {75, 100}; + CGRect prgrect = {{ + [self frame].size.width - prgsize.width - 10, + ([self frame].size.height - prgsize.height) / 2 + } , prgsize}; + [progress_ setFrame:prgrect]; -- (NSString *) getWarning { - NSString *href(href_); - NSRange colon([href rangeOfString:@"://"]); - if (colon.location != NSNotFound) - href = [href substringFromIndex:(colon.location + 3)]; - href = [href stringByAddingPercentEscapes]; - href = [CydiaURL(@"api/repotag/") stringByAppendingString:href]; - href = [href stringByCachingURLWithCurrentCDN]; + CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]); + unsigned indoffset = ([self frame].size.height - indsize.height) / 2; + CGRect indrect = {{indoffset, indoffset}, indsize}; + [indicator_ setFrame:indrect]; - NSURL *url([NSURL URLWithString:href]); + CGSize prmsize = {215, indsize.height + 4}; + CGRect prmrect = {{ + indoffset * 2 + indsize.width, + unsigned([self frame].size.height - prmsize.height) / 2 - 1 + }, prmsize}; + [prompt_ setFrame:prmrect]; +} - NSStringEncoding encoding; - NSError *error(nil); +- (void)setFrame:(CGRect)frame { + [super setFrame:frame]; - if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error]) - return [warning length] == 0 ? nil : warning; - return nil; + [self positionViews]; } -- (void) _endConnection:(NSURLConnection *)connection { - // XXX: the memory management in this method is horribly awkward - - NSURLConnection **field = NULL; - if (connection == trivial_) - field = &trivial_; - else if (connection == trivial_bz2_) - field = &trivial_bz2_; - else if (connection == trivial_gz_) - field = &trivial_gz_; - _assert(field != NULL); - [connection release]; - *field = nil; +- (id) initWithFrame:(CGRect)frame delegate:(id)delegate { + if ((self = [super initWithFrame:frame])) { + [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth]; - if ( - trivial_ == nil && - trivial_bz2_ == nil && - trivial_gz_ == nil - ) { - bool defer(false); + [self setBarStyle:UIBarStyleBlack]; - if (cydia_) { - if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) { - defer = true; + UIBarStyle barstyle([self _barStyle:NO]); + bool ugly(barstyle == UIBarStyleDefault); - UIAlertView *alert = [[[UIAlertView alloc] - initWithTitle:UCLocalize("SOURCE_WARNING") - message:warning - delegate:self - cancelButtonTitle:UCLocalize("CANCEL") - otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil - ] autorelease]; + UIProgressIndicatorStyle style = ugly ? + UIProgressIndicatorStyleMediumBrown : + UIProgressIndicatorStyleMediumWhite; - [alert setContext:@"warning"]; - [alert setNumberOfRows:1]; - [alert show]; - } else - [self complete]; - } else if (error_ != nil) { - UIAlertView *alert = [[[UIAlertView alloc] - initWithTitle:UCLocalize("VERIFICATION_ERROR") - message:[error_ localizedDescription] - delegate:self - cancelButtonTitle:UCLocalize("OK") - otherButtonTitles:nil - ] autorelease]; + indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero]; + [indicator_ setStyle:style]; + [indicator_ startAnimation]; + [self addSubview:indicator_]; - [alert setContext:@"urlerror"]; - [alert show]; - } else { - UIAlertView *alert = [[[UIAlertView alloc] - initWithTitle:UCLocalize("NOT_REPOSITORY") - message:UCLocalize("NOT_REPOSITORY_EX") - delegate:self - cancelButtonTitle:UCLocalize("OK") - otherButtonTitles:nil - ] autorelease]; + prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero]; + [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]]; + [prompt_ setBackgroundColor:[UIColor clearColor]]; + [prompt_ setFont:[UIFont systemFontOfSize:15]]; + [self addSubview:prompt_]; - [alert setContext:@"trivial"]; - [alert show]; - } + progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero]; + [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin]; + [progress_ setStyle:0]; + [self addSubview:progress_]; - [delegate_ setStatusBarShowsProgress:NO]; - [delegate_ removeProgressHUD:hud_]; + cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted]; + [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; + [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside]; + [cancel_ setBarStyle:barstyle]; - [hud_ autorelease]; - hud_ = nil; + [self positionViews]; + } return self; +} - if (!defer) { - [href_ release]; - href_ = nil; - } +- (void) cancel { + [cancel_ removeFromSuperview]; +} - if (error_ != nil) { - [error_ release]; - error_ = nil; - } - } +- (void) start { + [prompt_ setText:UCLocalize("UPDATING_DATABASE")]; + [progress_ setProgress:0]; + [self addSubview:cancel_]; } -- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response { - switch ([response statusCode]) { - case 200: - cydia_ = YES; - } +- (void) stop { + [cancel_ removeFromSuperview]; } -- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { - lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]); - if (error_ != nil) - error_ = [error retain]; - [self _endConnection:connection]; +- (void) setPrompt:(NSString *)prompt { + [prompt_ setText:prompt]; } -- (void) connectionDidFinishLoading:(NSURLConnection *)connection { - [self _endConnection:connection]; +- (void) setProgress:(float)progress { + [progress_ setProgress:progress]; } -- (NSString *) title { return UCLocalize("SOURCES"); } +@end +/* }}} */ -- (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method { - NSMutableURLRequest *request = [NSMutableURLRequest - requestWithURL:[NSURL URLWithString:href] - cachePolicy:NSURLRequestUseProtocolCachePolicy - timeoutInterval:120.0 - ]; +@class CYNavigationController; - [request setHTTPMethod:method]; +/* Cydia Tab Bar Controller {{{ */ +@interface CYTabBarController : UITabBarController < + ProgressDelegate +> { + _transient Database *database_; + RefreshBar *refreshbar_; - if (Machine_ != NULL) - [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"]; - if (UniqueID_ != nil) - [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"]; - if (Role_ != nil) - [request setValue:Role_ forHTTPHeaderField:@"X-Role"]; + bool dropped_; + bool updating_; + // XXX: ok, "updatedelegate_"?... + _transient NSObject *updatedelegate_; - return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease]; + id root_; } -- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button { - NSString *context([alert context]); +- (void) dropBar:(BOOL)animated; +- (void) beginUpdate; +- (void) raiseBar:(BOOL)animated; +- (BOOL) updating; - if ([context isEqualToString:@"source"]) { - switch (button) { - case 1: { - NSString *href = [[alert textField] text]; +@end - //installer_ = [[self _requestHRef:href method:@"GET"] retain]; +@implementation CYTabBarController - if (![href hasSuffix:@"/"]) - href_ = [href stringByAppendingString:@"/"]; - else - href_ = href; - href_ = [href_ retain]; +/* XXX: some logic should probably go here related to +freeing the view controllers on tab change */ - trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain]; - trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain]; - trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain]; - //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain]; +- (void) reloadData { + size_t count([[self viewControllers] count]); + for (size_t i(0); i != count; ++i) { + CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]); + [page reloadData]; + } +} - cydia_ = false; +- (id) initWithDatabase:(Database *)database { + if ((self = [super init]) != nil) { + database_ = database; - // XXX: this is stupid - hud_ = [[delegate_ addProgressHUD] retain]; - [hud_ setText:UCLocalize("VERIFYING_URL")]; - } break; + [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil]; - case 0: - break; + refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self]; + } return self; +} - _nodefault - } +- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation { + return IsWildcat_ || orientation == UIInterfaceOrientationPortrait; +} - [alert dismissWithClickedButtonIndex:-1 animated:YES]; - } else if ([context isEqualToString:@"trivial"]) - [alert dismissWithClickedButtonIndex:-1 animated:YES]; - else if ([context isEqualToString:@"urlerror"]) - [alert dismissWithClickedButtonIndex:-1 animated:YES]; - else if ([context isEqualToString:@"warning"]) { - switch (button) { - case 1: - [self complete]; - break; - - case 0: - break; +- (void) setUpdate:(NSDate *)date { + [self beginUpdate]; +} - _nodefault - } +- (void) beginUpdate { + [refreshbar_ start]; + [self dropBar:YES]; - [href_ release]; - href_ = nil; + [updatedelegate_ retainNetworkActivityIndicator]; + updating_ = true; - [alert dismissWithClickedButtonIndex:-1 animated:YES]; - } + [NSThread + detachNewThreadSelector:@selector(performUpdate) + toTarget:self + withObject:nil + ]; } -- (id) initWithDatabase:(Database *)database { - if ((self = [super init]) != nil) { - [[self navigationItem] setTitle:UCLocalize("SOURCES")]; - [self updateButtonsForEditingStatus:NO animated:NO]; +- (void) performUpdate { _pooled + Status status; + status.setDelegate(self); + [database_ updateWithStatus:status]; - database_ = database; - sources_ = [[NSMutableArray arrayWithCapacity:16] retain]; + [self + performSelectorOnMainThread:@selector(completeUpdate) + withObject:nil + waitUntilDone:NO + ]; +} - list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain]; - [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; - [[self view] addSubview:list_]; +- (void) stopUpdateWithSelector:(SEL)selector { + updating_ = false; + [updatedelegate_ releaseNetworkActivityIndicator]; - [list_ setDataSource:self]; - [list_ setDelegate:self]; + [self raiseBar:YES]; + [refreshbar_ stop]; - [self reloadData]; - } return self; + [updatedelegate_ performSelector:selector withObject:nil afterDelay:0]; } -- (void) reloadData { - pkgSourceList list; - if (!list.ReadMainList()) +- (void) completeUpdate { + if (!updating_) return; + [self stopUpdateWithSelector:@selector(reloadData)]; +} - [sources_ removeAllObjects]; - [sources_ addObjectsFromArray:[database_ sources]]; - _trace(); - [sources_ sortUsingSelector:@selector(compareByNameAndType:)]; - _trace(); +- (void) cancelUpdate { + [self stopUpdateWithSelector:@selector(updateData)]; +} - int count([sources_ count]); - offset_ = 0; - for (int i = 0; i != count; i++) { - if ([[sources_ objectAtIndex:i] record] == nil) - break; - offset_++; - } +- (void) cancelPressed { + [self cancelUpdate]; +} - [list_ setEditing:NO]; - [self updateButtonsForEditingStatus:NO animated:NO]; - [list_ reloadData]; +- (BOOL) updating { + return updating_; } -- (void) addButtonClicked { - /*[book_ pushPage:[[[AddSourceController alloc] - initWithBook:book_ - database:database_ - ] autorelease]];*/ +- (void) setProgressError:(NSString *)error withTitle:(NSString *)title { + [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]]; +} - UIAlertView *alert = [[[UIAlertView alloc] - initWithTitle:UCLocalize("ENTER_APT_URL") - message:nil - delegate:self - cancelButtonTitle:UCLocalize("CANCEL") - otherButtonTitles:UCLocalize("ADD_SOURCE"), nil - ] autorelease]; +- (void) startProgress { +} - [alert setContext:@"source"]; - [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)]; +- (void) setProgressTitle:(NSString *)title { + [self + performSelectorOnMainThread:@selector(_setProgressTitle:) + withObject:title + waitUntilDone:YES + ]; +} - [alert setNumberOfRows:1]; - [alert addTextFieldWithValue:@"http://" label:@""]; +- (bool) isCancelling:(size_t)received { + return !updating_; +} - UITextInputTraits *traits = [[alert textField] textInputTraits]; - [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone]; - [traits setAutocorrectionType:UITextAutocorrectionTypeNo]; - [traits setKeyboardType:UIKeyboardTypeURL]; - // XXX: UIReturnKeyDone - [traits setReturnKeyType:UIReturnKeyNext]; +- (void) setProgressPercent:(float)percent { + [self + performSelectorOnMainThread:@selector(_setProgressPercent:) + withObject:[NSNumber numberWithFloat:percent] + waitUntilDone:YES + ]; +} - [alert show]; +- (void) addProgressOutput:(NSString *)output { + [self + performSelectorOnMainThread:@selector(_addProgressOutput:) + withObject:output + waitUntilDone:YES + ]; } -- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated { - [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc] - initWithTitle:UCLocalize("ADD") - style:UIBarButtonItemStylePlain - target:self - action:@selector(addButtonClicked) - ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated]; +- (void) _setProgressTitle:(NSString *)title { + [refreshbar_ setPrompt:title]; +} - [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] - initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT")) - style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain) - target:self - action:@selector(editButtonClicked) - ] autorelease] animated:animated]; +- (void) _setProgressPercent:(NSNumber *)percent { + [refreshbar_ setProgress:[percent floatValue]]; +} - if (IsWildcat_ && !editing) - [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] - initWithTitle:UCLocalize("SETTINGS") - style:UIBarButtonItemStylePlain - target:self - action:@selector(settingsButtonClicked) - ] autorelease]]; +- (void) _addProgressOutput:(NSString *)output { } -- (void) settingsButtonClicked { - [delegate_ showSettings]; +- (void) setUpdateDelegate:(id)delegate { + updatedelegate_ = delegate; } -- (void) editButtonClicked { - [list_ setEditing:![list_ isEditing] animated:YES]; +- (CGFloat) statusBarHeight { + if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) { + return [[UIApplication sharedApplication] statusBarFrame].size.height; + } else { + return [[UIApplication sharedApplication] statusBarFrame].size.width; + } +} - [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES]; +- (UIView *) transitionView { + if ([self respondsToSelector:@selector(_transitionView)]) + return [self _transitionView]; + else + return MSHookIvar(self, "_viewControllerTransitionView"); } -@end -/* }}} */ +- (void) dropBar:(BOOL)animated { + if (dropped_) + return; + dropped_ = true; -/* Installed Controller {{{ */ -@interface InstalledController : FilteredPackageController { - BOOL expert_; -} + UIView *transition([self transitionView]); + [[self view] addSubview:refreshbar_]; -- (id) initWithDatabase:(Database *)database; + CGRect barframe([refreshbar_ frame]); -- (void) updateRoleButton; -- (void) queueStatusDidChange; + if (false) // XXX: _UIApplicationLinkedOnOrAfter(4) + barframe.origin.y = [self statusBarHeight]; + else + barframe.origin.y = 0; -@end + [refreshbar_ setFrame:barframe]; -@implementation InstalledController + if (animated) + [UIView beginAnimations:nil context:NULL]; -- (void) dealloc { - [super dealloc]; -} + CGRect viewframe = [transition frame]; + viewframe.origin.y += barframe.size.height; + viewframe.size.height -= barframe.size.height; + [transition setFrame:viewframe]; -- (NSString *) title { return UCLocalize("INSTALLED"); } + if (animated) + [UIView commitAnimations]; -- (id) initWithDatabase:(Database *)database { - if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) { - [self updateRoleButton]; - [self queueStatusDidChange]; - } return self; -} + // Ensure bar has the proper width for our view, it might have changed + barframe.size.width = viewframe.size.width; + [refreshbar_ setFrame:barframe]; -#if !AlwaysReload -- (void) queueButtonClicked { - [delegate_ queue]; + // XXX: fix Apple's layout bug + [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; } -#endif -- (void) queueStatusDidChange { -#if !AlwaysReload - if (IsWildcat_) { - if (Queuing_) { - [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] - initWithTitle:UCLocalize("QUEUE") - style:UIBarButtonItemStyleDone - target:self - action:@selector(queueButtonClicked) - ] autorelease]]; - } else { - [[self navigationItem] setLeftBarButtonItem:nil]; - } - } -#endif -} +- (void) raiseBar:(BOOL)animated { + if (!dropped_) + return; + dropped_ = false; -- (void) reloadData { - [packages_ reloadData]; -} + UIView *transition([self transitionView]); + [refreshbar_ removeFromSuperview]; -- (void) updateRoleButton { - if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) - [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] - initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")) - style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain) - target:self - action:@selector(roleButtonClicked) - ] autorelease]]; -} + CGRect barframe([refreshbar_ frame]); -- (void) roleButtonClicked { - [packages_ setObject:[NSNumber numberWithBool:expert_]]; - [packages_ reloadData]; - expert_ = !expert_; + if (animated) + [UIView beginAnimations:nil context:NULL]; - [self updateRoleButton]; -} + CGRect viewframe = [transition frame]; + viewframe.origin.y -= barframe.size.height; + viewframe.size.height += barframe.size.height; + [transition setFrame:viewframe]; -- (void) setDelegate:(id)delegate { - [super setDelegate:delegate]; - [packages_ setDelegate:delegate]; + if (animated) + [UIView commitAnimations]; + + // XXX: fix Apple's layout bug + // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; } -@end -/* }}} */ +#if 0 +- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration { + // XXX: fix Apple's layout bug + // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; +} +#endif -/* Home Controller {{{ */ -@interface HomeController : CYBrowserController { +- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { + bool dropped(dropped_); + + if (dropped) + [self raiseBar:NO]; + + [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; + + if (dropped) + [self dropBar:NO]; + + // XXX: fix Apple's layout bug + // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; } -@end +- (void) statusBarFrameChanged:(NSNotification *)notification { + if (dropped_) { + [self raiseBar:NO]; + [self dropBar:NO]; + } +} -@implementation HomeController +- (void) dealloc { + [refreshbar_ release]; + [[NSNotificationCenter defaultCenter] removeObserver:self]; + [super dealloc]; +} -- (void) _setMoreHeaders:(NSMutableURLRequest *)request { - [super _setMoreHeaders:request]; +@end +/* }}} */ - if (ChipID_ != nil) - [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"]; - if (UniqueID_ != nil) - [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"]; - if (PLMN_ != nil) - [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"]; +/* Cydia Navigation Controller {{{ */ +@interface CYNavigationController : UINavigationController { + _transient Database *database_; + _transient id delegate_; } -- (void) aboutButtonClicked { - UIAlertView *alert([[[UIAlertView alloc] init] autorelease]); +- (id) initWithDatabase:(Database *)database; +- (void) reloadData; - [alert setTitle:UCLocalize("ABOUT_CYDIA")]; - [alert addButtonWithTitle:UCLocalize("CLOSE")]; - [alert setCancelButtonIndex:0]; +@end - [alert setMessage: - @"Copyright (C) 2008-2010\n" - "Jay Freeman (saurik)\n" - "saurik@saurik.com\n" - "http://www.saurik.com/" - ]; - [alert show]; +@implementation CYNavigationController + +- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation { + // Inherit autorotation settings for modal parents. + if ([self parentViewController] && [[self parentViewController] modalViewController] == self) { + return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation]; + } else if ([self parentViewController]) { + return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation]; + } else { + return [super shouldAutorotateToInterfaceOrientation:orientation]; + } } -- (void) viewWillAppear:(BOOL)animated { - [super viewWillAppear:animated]; - //[[self navigationController] setNavigationBarHidden:YES animated:animated]; +- (void) dealloc { + [super dealloc]; } -- (void) viewWillDisappear:(BOOL)animated { - [super viewWillDisappear:animated]; - //[[self navigationController] setNavigationBarHidden:NO animated:animated]; +- (void) reloadData { + size_t count([[self viewControllers] count]); + for (size_t i(0); i != count; ++i) { + CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]); + [page reloadData]; + } } -- (id) init { +- (void) setDelegate:(id)delegate { + delegate_ = delegate; +} + +- (id) initWithDatabase:(Database *)database { if ((self = [super init]) != nil) { - [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] - initWithTitle:UCLocalize("ABOUT") - style:UIBarButtonItemStylePlain - target:self - action:@selector(aboutButtonClicked) - ] autorelease]]; + database_ = database; } return self; } @end /* }}} */ -/* Manage Controller {{{ */ -@interface ManageController : CYBrowserController { +/* Cydia:// Protocol {{{ */ +@interface CydiaURLProtocol : NSURLProtocol { } -- (void) queueStatusDidChange; @end -@implementation ManageController - -- (id) init { - if ((self = [super init]) != nil) { - [[self navigationItem] setTitle:UCLocalize("MANAGE")]; - - [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] - initWithTitle:UCLocalize("SETTINGS") - style:UIBarButtonItemStylePlain - target:self - action:@selector(settingsButtonClicked) - ] autorelease]]; +@implementation CydiaURLProtocol - [self queueStatusDidChange]; - } return self; ++ (BOOL) canInitWithRequest:(NSURLRequest *)request { + NSURL *url([request URL]); + if (url == nil) + return NO; + NSString *scheme([[url scheme] lowercaseString]); + if (scheme == nil || ![scheme isEqualToString:@"cydia"]) + return NO; + return YES; } -- (void) settingsButtonClicked { - [delegate_ showSettings]; ++ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request { + return request; } -#if !AlwaysReload -- (void) queueButtonClicked { - [delegate_ queue]; -} +- (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request { + id client([self client]); + if (icon == nil) + [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]]; + else { + NSData *data(UIImagePNGRepresentation(icon)); -- (void) applyLoadingTitle { - // No "Loading" title. + NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]); + [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; + [client URLProtocol:self didLoadData:data]; + [client URLProtocolDidFinishLoading:self]; + } } -- (void) applyRightButton { - // No right button. -} -#endif +- (void) startLoading { + id client([self client]); + NSURLRequest *request([self request]); -- (void) queueStatusDidChange { -#if !AlwaysReload - if (!IsWildcat_ && Queuing_) { - [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] - initWithTitle:UCLocalize("QUEUE") - style:UIBarButtonItemStyleDone - target:self - action:@selector(queueButtonClicked) - ] autorelease]]; + NSURL *url([request URL]); + NSString *href([url absoluteString]); + + NSString *path([href substringFromIndex:8]); + NSRange slash([path rangeOfString:@"/"]); + + NSString *command; + if (slash.location == NSNotFound) { + command = path; + path = nil; } else { - [[self navigationItem] setRightBarButtonItem:nil]; + command = [path substringToIndex:slash.location]; + path = [path substringFromIndex:(slash.location + 1)]; + } + + Database *database([Database sharedInstance]); + + if ([command isEqualToString:@"package-icon"]) { + if (path == nil) + goto fail; + path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + Package *package([database packageWithName:path]); + if (package == nil) + goto fail; + UIImage *icon([package icon]); + [self _returnPNGWithImage:icon forRequest:request]; + } else if ([command isEqualToString:@"source-icon"]) { + if (path == nil) + goto fail; + path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + NSString *source(Simplify(path)); + UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]); + if (icon == nil) + icon = [UIImage applicationImageNamed:@"unknown.png"]; + [self _returnPNGWithImage:icon forRequest:request]; + } else if ([command isEqualToString:@"uikit-image"]) { + if (path == nil) + goto fail; + path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + UIImage *icon(_UIImageWithName(path)); + [self _returnPNGWithImage:icon forRequest:request]; + } else if ([command isEqualToString:@"section-icon"]) { + if (path == nil) + goto fail; + path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + NSString *section(Simplify(path)); + UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]); + if (icon == nil) + icon = [UIImage applicationImageNamed:@"unknown.png"]; + [self _returnPNGWithImage:icon forRequest:request]; + } else fail: { + [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]]; } -#endif } -- (bool) isLoading { - return false; +- (void) stopLoading { } @end /* }}} */ -/* Refresh Bar {{{ */ -@interface RefreshBar : UINavigationBar { - UIProgressIndicator *indicator_; - UITextLabel *prompt_; - UIProgressBar *progress_; - UINavigationButton *cancel_; +/* Sections Controller {{{ */ +@interface CYSectionsController : CYViewController < + UITableViewDataSource, + UITableViewDelegate +> { + _transient Database *database_; + NSMutableArray *sections_; + NSMutableArray *filtered_; + UITableView *list_; + UIView *accessory_; + BOOL editing_; } +- (id) initWithDatabase:(Database *)database; +- (void) reloadData; +- (void) resetView; + +- (void) editButtonClicked; + @end -@implementation RefreshBar +@implementation CYSectionsController - (void) dealloc { - [indicator_ release]; - [prompt_ release]; - [progress_ release]; - [cancel_ release]; + [list_ setDataSource:nil]; + [list_ setDelegate:nil]; + + [sections_ release]; + [filtered_ release]; + [list_ release]; + [accessory_ release]; [super dealloc]; } -- (void) positionViews { - CGRect frame = [cancel_ frame]; - frame.origin.x = [self frame].size.width - frame.size.width - 5; - frame.origin.y = ([self frame].size.height - frame.size.height) / 2; - [cancel_ setFrame:frame]; +- (void) setEditing:(BOOL)editing { + if ((editing_ = editing)) + [list_ reloadData]; + else + [delegate_ updateData]; - CGSize prgsize = {75, 100}; - CGRect prgrect = {{ - [self frame].size.width - prgsize.width - 10, - ([self frame].size.height - prgsize.height) / 2 - } , prgsize}; - [progress_ setFrame:prgrect]; + [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")]; + [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")]; + [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain]; +} - CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]); - unsigned indoffset = ([self frame].size.height - indsize.height) / 2; - CGRect indrect = {{indoffset, indoffset}, indsize}; - [indicator_ setFrame:indrect]; +- (void) viewDidAppear:(BOOL)animated { + [super viewDidAppear:animated]; + [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; +} - CGSize prmsize = {215, indsize.height + 4}; - CGRect prmrect = {{ - indoffset * 2 + indsize.width, - unsigned([self frame].size.height - prmsize.height) / 2 - 1 - }, prmsize}; - [prompt_ setFrame:prmrect]; +- (void) viewWillDisappear:(BOOL)animated { + [super viewWillDisappear:animated]; + if (editing_) [self setEditing:NO]; } -- (void)setFrame:(CGRect)frame { - [super setFrame:frame]; +- (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath { + Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)])); + return section; +} - [self positionViews]; +- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { + return editing_ ? [sections_ count] : [filtered_ count] + 1; } -- (id) initWithFrame:(CGRect)frame delegate:(id)delegate { - if ((self = [super initWithFrame:frame])) { - [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth]; +/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { + return 45.0f; +}*/ - [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]]; - [self setBarStyle:UIBarStyleBlack]; +- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { + static NSString *reuseIdentifier = @"SectionCell"; - UIBarStyle barstyle([self _barStyle:NO]); - bool ugly(barstyle == UIBarStyleDefault); + SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; + if (cell == nil) + cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease]; - UIProgressIndicatorStyle style = ugly ? - UIProgressIndicatorStyleMediumBrown : - UIProgressIndicatorStyleMediumWhite; + [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_]; - indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero]; - [indicator_ setStyle:style]; - [indicator_ startAnimation]; - [self addSubview:indicator_]; + return cell; +} - prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero]; - [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]]; - [prompt_ setBackgroundColor:[UIColor clearColor]]; - [prompt_ setFont:[UIFont systemFontOfSize:15]]; - [self addSubview:prompt_]; +- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { + if (editing_) + return; - progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero]; - [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin]; - [progress_ setStyle:0]; - [self addSubview:progress_]; + Section *section = [self sectionAtIndexPath:indexPath]; + NSString *name = [section name]; + NSString *title; - cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted]; - [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; - [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside]; - [cancel_ setBarStyle:barstyle]; + if ([indexPath row] == 0) { + section = nil; + name = nil; + title = UCLocalize("ALL_PACKAGES"); + } else { + if (name != nil) { + name = [NSString stringWithString:name]; + title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"]; + } else { + name = @""; + title = UCLocalize("NO_SECTION"); + } + } - [self positionViews]; - } return self; -} + FilteredPackageController *table = [[[FilteredPackageController alloc] + initWithDatabase:database_ + title:title + filter:@selector(isVisibleInSection:) + with:name + ] autorelease]; -- (void) cancel { - [cancel_ removeFromSuperview]; -} + [table setDelegate:delegate_]; -- (void) start { - [prompt_ setText:UCLocalize("UPDATING_DATABASE")]; - [progress_ setProgress:0]; - [self addSubview:cancel_]; + [[self navigationController] pushViewController:table animated:YES]; } -- (void) stop { - [cancel_ removeFromSuperview]; -} +- (NSString *) title { return UCLocalize("SECTIONS"); } -- (void) setPrompt:(NSString *)prompt { - [prompt_ setText:prompt]; -} +- (id) initWithDatabase:(Database *)database { + if ((self = [super init]) != nil) { + database_ = database; -- (void) setProgress:(float)progress { - [progress_ setProgress:progress]; -} + [[self navigationItem] setTitle:UCLocalize("SECTIONS")]; -@end -/* }}} */ + sections_ = [[NSMutableArray arrayWithCapacity:16] retain]; + filtered_ = [[NSMutableArray arrayWithCapacity:16] retain]; -@class CYNavigationController; + list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]]; + [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; + [list_ setRowHeight:45.0f]; + [[self view] addSubview:list_]; -/* Cydia Tab Bar Controller {{{ */ -@interface CYTabBarController : UITabBarController { - _transient Database *database_; + [list_ setDataSource:self]; + [list_ setDelegate:self]; + + [self reloadData]; + } return self; } -@end +- (void) reloadData { + NSArray *packages = [database_ packages]; -@implementation CYTabBarController + [sections_ removeAllObjects]; + [filtered_ removeAllObjects]; -/* XXX: some logic should probably go here related to -freeing the view controllers on tab change */ + NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]); -- (void) reloadData { - size_t count([[self viewControllers] count]); - for (size_t i(0); i != count; ++i) { - CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]); - [page reloadData]; - } -} + _trace(); + for (Package *package in packages) { + NSString *name([package section]); + NSString *key(name == nil ? @"" : name); -- (id) initWithDatabase:(Database *)database { - if ((self = [super init]) != nil) { - database_ = database; - } return self; -} + Section *section; -@end -/* }}} */ + _profile(SectionsView$reloadData$Section) + section = [sections objectForKey:key]; + if (section == nil) { + _profile(SectionsView$reloadData$Section$Allocate) + section = [[[Section alloc] initWithName:name localize:YES] autorelease]; + [sections setObject:section forKey:key]; + _end + } + _end -/* Cydia Navigation Controller {{{ */ -@interface CYNavigationController : UINavigationController { - _transient Database *database_; - _transient id delegate_; -} + [section addToCount]; -- (id) initWithDatabase:(Database *)database; -- (void) reloadData; + _profile(SectionsView$reloadData$Filter) + if (![package valid] || ![package visible]) + continue; + _end -@end + [section addToRow]; + } + _trace(); + [sections_ addObjectsFromArray:[sections allValues]]; -@implementation CYNavigationController + [sections_ sortUsingSelector:@selector(compareByLocalized:)]; -- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation { - // Inherit autorotation settings for modal parents. - if ([self parentViewController] && [[self parentViewController] modalViewController] == self) { - return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation]; - } else { - return [super shouldAutorotateToInterfaceOrientation:orientation]; + for (Section *section in sections_) { + size_t count([section row]); + if (count == 0) + continue; + + section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease]; + [section setCount:count]; + [filtered_ addObject:section]; } -} -- (void) dealloc { - [super dealloc]; -} + [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] + initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT")) + style:UIBarButtonItemStylePlain + target:self + action:@selector(editButtonClicked) + ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)]; -- (void) reloadData { - size_t count([[self viewControllers] count]); - for (size_t i(0); i != count; ++i) { - CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]); - [page reloadData]; - } + [list_ reloadData]; + _trace(); } -- (void) setDelegate:(id)delegate { - delegate_ = delegate; +- (void) resetView { + if (editing_) + [self editButtonClicked]; } -- (id) initWithDatabase:(Database *)database { - if ((self = [super init]) != nil) { - database_ = database; - } return self; +- (void)editButtonClicked { + [self setEditing:!editing_]; } -@end -/* }}} */ -/* Cydia:// Protocol {{{ */ -@interface CydiaURLProtocol : NSURLProtocol { -} - -@end - -@implementation CydiaURLProtocol - -+ (BOOL) canInitWithRequest:(NSURLRequest *)request { - NSURL *url([request URL]); - if (url == nil) - return NO; - NSString *scheme([[url scheme] lowercaseString]); - if (scheme == nil || ![scheme isEqualToString:@"cydia"]) - return NO; - return YES; -} - -+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request { - return request; -} - -- (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request { - id client([self client]); - if (icon == nil) - [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]]; - else { - NSData *data(UIImagePNGRepresentation(icon)); - - NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]); - [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; - [client URLProtocol:self didLoadData:data]; - [client URLProtocolDidFinishLoading:self]; - } -} - -- (void) startLoading { - id client([self client]); - NSURLRequest *request([self request]); - - NSURL *url([request URL]); - NSString *href([url absoluteString]); - - NSString *path([href substringFromIndex:8]); - NSRange slash([path rangeOfString:@"/"]); - - NSString *command; - if (slash.location == NSNotFound) { - command = path; - path = nil; - } else { - command = [path substringToIndex:slash.location]; - path = [path substringFromIndex:(slash.location + 1)]; - } - - Database *database([Database sharedInstance]); - - if ([command isEqualToString:@"package-icon"]) { - if (path == nil) - goto fail; - path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - Package *package([database packageWithName:path]); - if (package == nil) - goto fail; - UIImage *icon([package icon]); - [self _returnPNGWithImage:icon forRequest:request]; - } else if ([command isEqualToString:@"source-icon"]) { - if (path == nil) - goto fail; - path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - NSString *source(Simplify(path)); - UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]); - if (icon == nil) - icon = [UIImage applicationImageNamed:@"unknown.png"]; - [self _returnPNGWithImage:icon forRequest:request]; - } else if ([command isEqualToString:@"uikit-image"]) { - if (path == nil) - goto fail; - path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - UIImage *icon(_UIImageWithName(path)); - [self _returnPNGWithImage:icon forRequest:request]; - } else if ([command isEqualToString:@"section-icon"]) { - if (path == nil) - goto fail; - path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - NSString *section(Simplify(path)); - UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]); - if (icon == nil) - icon = [UIImage applicationImageNamed:@"unknown.png"]; - [self _returnPNGWithImage:icon forRequest:request]; - } else fail: { - [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]]; - } -} - -- (void) stopLoading { +- (UIView *) accessoryView { + return accessory_; } @end /* }}} */ - -/* Sections Controller {{{ */ -@interface SectionsController : CYViewController < +/* Changes Controller {{{ */ +@interface ChangesController : CYViewController < UITableViewDataSource, UITableViewDelegate > { _transient Database *database_; + unsigned era_; + CFMutableArrayRef packages_; NSMutableArray *sections_; - NSMutableArray *filtered_; UITableView *list_; - UIView *accessory_; - BOOL editing_; + unsigned upgrades_; + BOOL hasSentFirstLoad_; } -- (id) initWithDatabase:(Database *)database; +- (id) initWithDatabase:(Database *)database delegate:(id)delegate; - (void) reloadData; -- (void) resetView; - -- (void) editButtonClicked; @end -@implementation SectionsController +@implementation ChangesController - (void) dealloc { - [list_ setDataSource:nil]; [list_ setDelegate:nil]; + [list_ setDataSource:nil]; + + CFRelease(packages_); [sections_ release]; - [filtered_ release]; [list_ release]; - [accessory_ release]; [super dealloc]; } - (void) viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; - [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; + if (!hasSentFirstLoad_) { + hasSentFirstLoad_ = YES; + [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0]; + } else { + [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; + } } -- (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath { - Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)])); - return section; +- (NSInteger) numberOfSectionsInTableView:(UITableView *)list { + NSInteger count([sections_ count]); + return count == 0 ? 1 : count; } -- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { - return editing_ ? [sections_ count] : [filtered_ count] + 1; +- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section { + if ([sections_ count] == 0) + return nil; + return [[sections_ objectAtIndex:section] name]; } -/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { - return 45.0f; -}*/ +- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section { + if ([sections_ count] == 0) + return 0; + return [[sections_ objectAtIndex:section] count]; +} -- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { - static NSString *reuseIdentifier = @"SectionCell"; +- (Package *) packageAtIndex:(NSUInteger)index { + return (Package *) CFArrayGetValueAtIndex(packages_, index); +} - SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; - if (cell == nil) - cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease]; +- (Package *) packageAtIndexPath:(NSIndexPath *)path { +@synchronized (database_) { + if ([database_ era] != era_) + return nil; - [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_]; + NSUInteger sectionIndex([path section]); + if (sectionIndex >= [sections_ count]) + return nil; + Section *section([sections_ objectAtIndex:sectionIndex]); + NSInteger row([path row]); + return [[[self packageAtIndex:([section row] + row)] retain] autorelease]; +} } +- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path { + PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]); + if (cell == nil) + cell = [[[PackageCell alloc] init] autorelease]; + [cell setPackage:[self packageAtIndexPath:path]]; return cell; } -- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { - if (editing_) - return; - - Section *section = [self sectionAtIndexPath:indexPath]; - NSString *name = [section name]; - NSString *title; - - if ([indexPath row] == 0) { - section = nil; - name = nil; - title = UCLocalize("ALL_PACKAGES"); - } else { - if (name != nil) { - name = [NSString stringWithString:name]; - title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"]; - } else { - name = @""; - title = UCLocalize("NO_SECTION"); - } - } - - FilteredPackageController *table = [[[FilteredPackageController alloc] - initWithDatabase:database_ - title:title - filter:@selector(isVisibleInSection:) - with:name - ] autorelease]; +- (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path { + Package *package([self packageAtIndexPath:path]); + PackageController *view([delegate_ packageController]); + [view setDelegate:delegate_]; + [view setPackage:package]; + [[self navigationController] pushViewController:view animated:YES]; + return path; +} - [table setDelegate:delegate_]; +- (void) refreshButtonClicked { + [delegate_ beginUpdate]; + [[self navigationItem] setLeftBarButtonItem:nil animated:YES]; +} - [[self navigationController] pushViewController:table animated:YES]; +- (void) upgradeButtonClicked { + [delegate_ distUpgrade]; } -- (NSString *) title { return UCLocalize("SECTIONS"); } +- (NSString *) title { return UCLocalize("CHANGES"); } -- (id) initWithDatabase:(Database *)database { +- (id) initWithDatabase:(Database *)database delegate:(id)delegate { if ((self = [super init]) != nil) { database_ = database; + [[self navigationItem] setTitle:UCLocalize("CHANGES")]; - [[self navigationItem] setTitle:UCLocalize("SECTIONS")]; + packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL); sections_ = [[NSMutableArray arrayWithCapacity:16] retain]; - filtered_ = [[NSMutableArray arrayWithCapacity:16] retain]; - list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]]; + list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain]; [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; - [list_ setRowHeight:45.0f]; + [list_ setRowHeight:73]; [[self view] addSubview:list_]; [list_ setDataSource:self]; [list_ setDelegate:self]; - [self reloadData]; + delegate_ = delegate; } return self; } +- (void) _reloadPackages:(NSArray *)packages { + CFRelease(packages_); + packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL); + + _trace(); + _profile(ChangesController$_reloadPackages$Filter) + for (Package *package in packages) + if ([package upgradableAndEssential:YES] || [package visible]) + CFArrayAppendValue(packages_, package); + _end + _trace(); + _profile(ChangesController$_reloadPackages$radixSort) + [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast(&PackageChangesRadix) withContext:NULL]; + _end + _trace(); +} + - (void) reloadData { +@synchronized (database_) { + era_ = [database_ era]; NSArray *packages = [database_ packages]; [sections_ removeAllObjects]; - [filtered_ removeAllObjects]; - NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]); +#if 1 + UIProgressHUD *hud([delegate_ addProgressHUD]); + [hud setText:UCLocalize("LOADING")]; + //NSLog(@"HUD:%@::%@", delegate_, hud); + [self yieldToSelector:@selector(_reloadPackages:) withObject:packages]; + [delegate_ removeProgressHUD:hud]; +#else + [self _reloadPackages:packages]; +#endif - _trace(); - for (Package *package in packages) { - NSString *name([package section]); - NSString *key(name == nil ? @"" : name); + Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease]; + Section *ignored = nil; + Section *section = nil; + time_t last = 0; - Section *section; - - _profile(SectionsView$reloadData$Section) - section = [sections objectForKey:key]; - if (section == nil) { - _profile(SectionsView$reloadData$Section$Allocate) - section = [[[Section alloc] initWithName:name localize:YES] autorelease]; - [sections setObject:section forKey:key]; - _end - } - _end - - [section addToCount]; - - _profile(SectionsView$reloadData$Filter) - if (![package valid] || ![package visible]) - continue; - _end - - [section addToRow]; - } - _trace(); - - [sections_ addObjectsFromArray:[sections allValues]]; - - [sections_ sortUsingSelector:@selector(compareByLocalized:)]; - - for (Section *section in sections_) { - size_t count([section row]); - if (count == 0) - continue; - - section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease]; - [section setCount:count]; - [filtered_ addObject:section]; - } - - [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] - initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT")) - style:UIBarButtonItemStylePlain - target:self - action:@selector(editButtonClicked) - ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)]; - - [list_ reloadData]; - _trace(); -} - -- (void) resetView { - if (editing_) - [self editButtonClicked]; -} - -- (void) editButtonClicked { - if ((editing_ = !editing_)) - [list_ reloadData]; - else - [delegate_ updateData]; - - [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")]; - [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")]; - [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain]; -} - -- (UIView *) accessoryView { - return accessory_; -} - -@end -/* }}} */ -/* Changes Controller {{{ */ -@interface ChangesController : CYViewController < - UITableViewDataSource, - UITableViewDelegate -> { - _transient Database *database_; - CFMutableArrayRef packages_; - NSMutableArray *sections_; - UITableView *list_; - unsigned upgrades_; - BOOL hasSentFirstLoad_; -} - -- (id) initWithDatabase:(Database *)database delegate:(id)delegate; -- (void) reloadData; - -@end - -@implementation ChangesController - -- (void) dealloc { - [list_ setDelegate:nil]; - [list_ setDataSource:nil]; - - CFRelease(packages_); - - [sections_ release]; - [list_ release]; - [super dealloc]; -} - -- (void) viewDidAppear:(BOOL)animated { - [super viewDidAppear:animated]; - if (!hasSentFirstLoad_) { - hasSentFirstLoad_ = YES; - [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0]; - } else { - [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; - } -} - -- (NSInteger) numberOfSectionsInTableView:(UITableView *)list { - NSInteger count([sections_ count]); - return count == 0 ? 1 : count; -} - -- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section { - if ([sections_ count] == 0) - return nil; - return [[sections_ objectAtIndex:section] name]; -} - -- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section { - if ([sections_ count] == 0) - return 0; - return [[sections_ objectAtIndex:section] count]; -} - -- (Package *) packageAtIndex:(NSUInteger)index { - return (Package *) CFArrayGetValueAtIndex(packages_, index); -} - -- (Package *) packageAtIndexPath:(NSIndexPath *)path { - Section *section([sections_ objectAtIndex:[path section]]); - NSInteger row([path row]); - return [self packageAtIndex:([section row] + row)]; -} - -- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path { - PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]); - if (cell == nil) - cell = [[[PackageCell alloc] init] autorelease]; - [cell setPackage:[self packageAtIndexPath:path]]; - return cell; -} - -/*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path { - return [PackageCell heightForPackage:[self packageAtIndexPath:path]]; -}*/ - -- (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path { - Package *package([self packageAtIndexPath:path]); - PackageController *view([delegate_ packageController]); - [view setDelegate:delegate_]; - [view setPackage:package]; - [[self navigationController] pushViewController:view animated:YES]; - return path; -} - -- (void) refreshButtonClicked { - [delegate_ beginUpdate]; - [[self navigationItem] setLeftBarButtonItem:nil animated:YES]; -} - -- (void) upgradeButtonClicked { - [delegate_ distUpgrade]; -} - -- (NSString *) title { return UCLocalize("CHANGES"); } - -- (id) initWithDatabase:(Database *)database delegate:(id)delegate { - if ((self = [super init]) != nil) { - database_ = database; - [[self navigationItem] setTitle:UCLocalize("CHANGES")]; - - packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL); - - sections_ = [[NSMutableArray arrayWithCapacity:16] retain]; - - list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain]; - [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; - [list_ setRowHeight:73.0f]; - [[self view] addSubview:list_]; - - [list_ setDataSource:self]; - [list_ setDelegate:self]; - - delegate_ = delegate; - } return self; -} - -- (void) _reloadPackages:(NSArray *)packages { - _trace(); - for (Package *package in packages) - if ([package upgradableAndEssential:YES] || [package visible]) - CFArrayAppendValue(packages_, package); - - _trace(); - [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast(&PackageChangesRadix) withContext:NULL]; - _trace(); -} - -- (void) reloadData { - NSArray *packages = [database_ packages]; - - CFArrayRemoveAllValues(packages_); - - [sections_ removeAllObjects]; - -#if 1 - UIProgressHUD *hud([delegate_ addProgressHUD]); - [hud setText:UCLocalize("LOADING")]; - //NSLog(@"HUD:%@::%@", delegate_, hud); - [self yieldToSelector:@selector(_reloadPackages:) withObject:packages]; - [delegate_ removeProgressHUD:hud]; -#else - [self _reloadPackages:packages]; -#endif - - Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease]; - Section *ignored = nil; - Section *section = nil; - time_t last = 0; - - upgrades_ = 0; - bool unseens = false; + upgrades_ = 0; + bool unseens = false; CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle)); @@ -7197,7 +7107,9 @@ freeing the view controllers on tab change */ target:self action:@selector(refreshButtonClicked) ] autorelease]]; -} + + PrintTimes(); +} } @end /* }}} */ @@ -7243,7 +7155,13 @@ freeing the view controllers on tab change */ search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)]; [search_ layoutSubviews]; [search_ setPlaceholder:UCLocalize("SEARCH_EX")]; - UITextField *textField = [search_ searchField]; + + UITextField *textField; + if ([search_ respondsToSelector:@selector(searchField)]) + textField = [search_ searchField]; + else + textField = MSHookIvar(search_, "_searchField"); + [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin]; [search_ setDelegate:self]; [textField setEnablesReturnKeyAutomatically:NO]; @@ -7270,7 +7188,7 @@ freeing the view controllers on tab change */ @end /* }}} */ /* Settings Controller {{{ */ -@interface SettingsController : CYViewController < +@interface CYPackageSettingsController : CYViewController < UITableViewDataSource, UITableViewDelegate > { @@ -7288,7 +7206,7 @@ freeing the view controllers on tab change */ @end -@implementation SettingsController +@implementation CYPackageSettingsController - (void) dealloc { [name_ release]; @@ -7377,6 +7295,8 @@ freeing the view controllers on tab change */ [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")]; [ignoredCell_ setAccessoryView:ignoredSwitch_]; [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone]; + // FIXME: Ignored state is not saved. + [ignoredCell_ setUserInteractionEnabled:NO]; [table_ setDataSource:self]; [table_ setDelegate:self]; @@ -7436,509 +7356,776 @@ freeing the view controllers on tab change */ @end /* }}} */ -/* Role Controller {{{ */ -@interface RoleController : CYViewController < - UITableViewDataSource, - UITableViewDelegate +/* Source Cell {{{ */ +@interface SourceCell : CYTableViewCell < + ContentDelegate > { - _transient Database *database_; - // XXX: ok, "roledelegate_"?... - _transient id roledelegate_; - UITableView *table_; - UISegmentedControl *segment_; - UIView *container_; + UIImage *icon_; + NSString *origin_; + NSString *label_; } -- (void) showDoneButton; -- (void) resizeSegmentedControl; +- (void) setSource:(Source *)source; @end -@implementation RoleController -- (void) dealloc { - [table_ release]; - [segment_ release]; - [container_ release]; +@implementation SourceCell - [super dealloc]; -} +- (void) clearSource { + [icon_ release]; + [origin_ release]; + [label_ release]; -- (id) initWithDatabase:(Database *)database delegate:(id)delegate { - if ((self = [super init])) { - database_ = database; - roledelegate_ = delegate; + icon_ = nil; + origin_ = nil; + label_ = nil; +} - [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")]; +- (void) setSource:(Source *)source { + [self clearSource]; - NSArray *items = [NSArray arrayWithObjects: - UCLocalize("USER"), - UCLocalize("HACKER"), - UCLocalize("DEVELOPER"), - nil]; - segment_ = [[UISegmentedControl alloc] initWithItems:items]; - container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)]; - [container_ addSubview:segment_]; + if (icon_ == nil) + icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]]; + if (icon_ == nil) + icon_ = [UIImage applicationImageNamed:@"unknown.png"]; + icon_ = [icon_ retain]; - int index = -1; - if ([Role_ isEqualToString:@"User"]) index = 0; - if ([Role_ isEqualToString:@"Hacker"]) index = 1; - if ([Role_ isEqualToString:@"Developer"]) index = 2; - if (index != -1) { - [segment_ setSelectedSegmentIndex:index]; - [self showDoneButton]; - } + origin_ = [[source name] retain]; + label_ = [[source uri] retain]; - [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged]; - [self resizeSegmentedControl]; + [content_ setNeedsDisplay]; +} - table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped]; - [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; - [table_ setDelegate:self]; - [table_ setDataSource:self]; - [[self view] addSubview:table_]; - [table_ reloadData]; +- (void) dealloc { + [self clearSource]; + [super dealloc]; +} + +- (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier { + if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) { + UIView *content([self contentView]); + CGRect bounds([content bounds]); + + content_ = [[ContentView alloc] initWithFrame:bounds]; + [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; + [content_ setBackgroundColor:[UIColor whiteColor]]; + [content addSubview:content_]; + + [content_ setDelegate:self]; + [content_ setOpaque:YES]; } return self; } -- (void) resizeSegmentedControl { - CGFloat width = [[self view] frame].size.width; - [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)]; +- (void) drawContentRect:(CGRect)rect { + bool highlighted(highlighted_); + float width(rect.size.width); + + if (icon_ != nil) + [icon_ drawInRect:CGRectMake(10, 10, 30, 30)]; + + if (highlighted) + UISetColor(White_); + + if (!highlighted) + UISetColor(Black_); + [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation]; + + if (!highlighted) + UISetColor(Blue_); + [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation]; } -- (void) viewWillAppear:(BOOL)animated { - [super viewWillAppear:animated]; +@end +/* }}} */ +/* Source Table {{{ */ +@interface SourceController : CYViewController < + UITableViewDataSource, + UITableViewDelegate +> { + _transient Database *database_; + UITableView *list_; + NSMutableArray *sources_; + int offset_; - [self resizeSegmentedControl]; + NSString *href_; + UIProgressHUD *hud_; + NSError *error_; + + //NSURLConnection *installer_; + NSURLConnection *trivial_; + NSURLConnection *trivial_bz2_; + NSURLConnection *trivial_gz_; + //NSURLConnection *automatic_; + + BOOL cydia_; } -- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration { - [self resizeSegmentedControl]; +- (id) initWithDatabase:(Database *)database; + +- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated; + +@end + +@implementation SourceController + +- (void) _releaseConnection:(NSURLConnection *)connection { + if (connection != nil) { + [connection cancel]; + //[connection setDelegate:nil]; + [connection release]; + } } -- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { - [self resizeSegmentedControl]; +- (void) dealloc { + if (href_ != nil) + [href_ release]; + if (hud_ != nil) + [hud_ release]; + if (error_ != nil) + [error_ release]; + + //[self _releaseConnection:installer_]; + [self _releaseConnection:trivial_]; + [self _releaseConnection:trivial_gz_]; + [self _releaseConnection:trivial_bz2_]; + //[self _releaseConnection:automatic_]; + + [sources_ release]; + [list_ release]; + [super dealloc]; } -- (void) save { - NSString *role(nil); +- (void) viewDidAppear:(BOOL)animated { + [super viewDidAppear:animated]; + [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; +} - switch ([segment_ selectedSegmentIndex]) { - case 0: role = @"User"; break; - case 1: role = @"Hacker"; break; - case 2: role = @"Developer"; break; +- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { + return offset_ == 0 ? 1 : 2; +} + +- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { + switch (section + (offset_ == 0 ? 1 : 0)) { + case 0: return UCLocalize("ENTERED_BY_USER"); + case 1: return UCLocalize("INSTALLED_BY_PACKAGE"); _nodefault } +} - if (![role isEqualToString:Role_]) { - bool rolling(Role_ == nil); - Role_ = role; - - Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys: - Role_, @"Role", - nil]; +- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { + int count = [sources_ count]; + switch (section) { + case 0: return (offset_ == 0 ? count : offset_); + case 1: return count - offset_; - [Metadata_ setObject:Settings_ forKey:@"Settings"]; + _nodefault + } +} - Changed_ = true; +- (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath { + unsigned idx = 0; + switch (indexPath.section) { + case 0: idx = indexPath.row; break; + case 1: idx = indexPath.row + offset_; break; - if (rolling) - [roledelegate_ loadData]; - else - [roledelegate_ updateData]; + _nodefault } + return [sources_ objectAtIndex:idx]; } -- (void) segmentChanged:(UISegmentedControl *)control { - [self showDoneButton]; -} +- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { + static NSString *cellIdentifier = @"SourceCell"; -- (void) saveAndClose { - [self save]; + SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; + if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease]; + [cell setSource:[self sourceAtIndexPath:indexPath]]; - [[self navigationItem] setRightBarButtonItem:nil]; - [[self navigationController] dismissModalViewControllerAnimated:YES]; + return cell; } -- (void) doneButtonClicked { - UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease]; - [spinner startAnimating]; - UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease]; - [[self navigationItem] setRightBarButtonItem:spinItem]; +- (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath { + return UITableViewCellAccessoryDisclosureIndicator; +} - [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0]; +- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { + Source *source = [self sourceAtIndexPath:indexPath]; + + FilteredPackageController *packages = [[[FilteredPackageController alloc] + initWithDatabase:database_ + title:[source label] + filter:@selector(isVisibleInSource:) + with:source + ] autorelease]; + + [packages setDelegate:delegate_]; + + [[self navigationController] pushViewController:packages animated:YES]; } -- (void) showDoneButton { - [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] - initWithTitle:UCLocalize("DONE") - style:UIBarButtonItemStyleDone - target:self - action:@selector(doneButtonClicked) - ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)]; +- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { + Source *source = [self sourceAtIndexPath:indexPath]; + return [source record] != nil; } -- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { - // XXX: For not having a single cell in the table, this sure is a lot of sections. - return 6; +- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { + Source *source = [self sourceAtIndexPath:indexPath]; + [Sources_ removeObjectForKey:[source key]]; + [delegate_ syncData]; } -- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { - return 0; // :( +- (void) complete { + [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys: + @"deb", @"Type", + href_, @"URI", + @"./", @"Distribution", + nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]]; + + [delegate_ syncData]; } -- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { - return nil; // This method is required by the protocol. +- (NSString *) getWarning { + NSString *href(href_); + NSRange colon([href rangeOfString:@"://"]); + if (colon.location != NSNotFound) + href = [href substringFromIndex:(colon.location + 3)]; + href = [href stringByAddingPercentEscapes]; + href = [CydiaURL(@"api/repotag/") stringByAppendingString:href]; + href = [href stringByCachingURLWithCurrentCDN]; + + NSURL *url([NSURL URLWithString:href]); + + NSStringEncoding encoding; + NSError *error(nil); + + if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error]) + return [warning length] == 0 ? nil : warning; + return nil; } -- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section { - if (section == 1) - return UCLocalize("ROLE_EX"); - if (section == 4) - return [NSString stringWithFormat: - @"%@: %@\n%@: %@\n%@: %@", - UCLocalize("USER"), UCLocalize("USER_EX"), - UCLocalize("HACKER"), UCLocalize("HACKER_EX"), - UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX") - ]; - else return nil; +- (void) _endConnection:(NSURLConnection *)connection { + // XXX: the memory management in this method is horribly awkward + + NSURLConnection **field = NULL; + if (connection == trivial_) + field = &trivial_; + else if (connection == trivial_bz2_) + field = &trivial_bz2_; + else if (connection == trivial_gz_) + field = &trivial_gz_; + _assert(field != NULL); + [connection release]; + *field = nil; + + if ( + trivial_ == nil && + trivial_bz2_ == nil && + trivial_gz_ == nil + ) { + bool defer(false); + + if (cydia_) { + if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) { + defer = true; + + UIAlertView *alert = [[[UIAlertView alloc] + initWithTitle:UCLocalize("SOURCE_WARNING") + message:warning + delegate:self + cancelButtonTitle:UCLocalize("CANCEL") + otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil + ] autorelease]; + + [alert setContext:@"warning"]; + [alert setNumberOfRows:1]; + [alert show]; + } else + [self complete]; + } else if (error_ != nil) { + UIAlertView *alert = [[[UIAlertView alloc] + initWithTitle:UCLocalize("VERIFICATION_ERROR") + message:[error_ localizedDescription] + delegate:self + cancelButtonTitle:UCLocalize("OK") + otherButtonTitles:nil + ] autorelease]; + + [alert setContext:@"urlerror"]; + [alert show]; + } else { + UIAlertView *alert = [[[UIAlertView alloc] + initWithTitle:UCLocalize("NOT_REPOSITORY") + message:UCLocalize("NOT_REPOSITORY_EX") + delegate:self + cancelButtonTitle:UCLocalize("OK") + otherButtonTitles:nil + ] autorelease]; + + [alert setContext:@"trivial"]; + [alert show]; + } + + [delegate_ setStatusBarShowsProgress:NO]; + [delegate_ removeProgressHUD:hud_]; + + [hud_ autorelease]; + hud_ = nil; + + if (!defer) { + [href_ release]; + href_ = nil; + } + + if (error_ != nil) { + [error_ release]; + error_ = nil; + } + } } -- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { - return section == 3 ? 44.0f : 0; +- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response { + switch ([response statusCode]) { + case 200: + cydia_ = YES; + } } -- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { - return section == 3 ? container_ : nil; +- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { + lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]); + if (error_ != nil) + error_ = [error retain]; + [self _endConnection:connection]; } -@end -/* }}} */ -/* Stash Controller {{{ */ -@interface CYStashController : CYViewController { - // XXX: just delete these things - _transient UIActivityIndicatorView *spinner_; - _transient UILabel *status_; - _transient UILabel *caption_; +- (void) connectionDidFinishLoading:(NSURLConnection *)connection { + [self _endConnection:connection]; } -@end -@implementation CYStashController -- (id) init { - if ((self = [super init])) { - [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]]; +- (NSString *) title { return UCLocalize("SOURCES"); } - spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease]; - CGRect spinrect = [spinner_ frame]; - spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2); - spinrect.origin.y = [[self view] frame].size.height - 80.0f; - [spinner_ setFrame:spinrect]; - [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin]; - [[self view] addSubview:spinner_]; - [spinner_ startAnimating]; +- (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method { + NSMutableURLRequest *request = [NSMutableURLRequest + requestWithURL:[NSURL URLWithString:href] + cachePolicy:NSURLRequestUseProtocolCachePolicy + timeoutInterval:120.0 + ]; - CGRect captrect; - captrect.size.width = [[self view] frame].size.width; - captrect.size.height = 40.0f; - captrect.origin.x = 0; - captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2); - caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease]; - [caption_ setText:@"Initializing Filesystem"]; - [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin]; - [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]]; - [caption_ setTextColor:[UIColor whiteColor]]; - [caption_ setBackgroundColor:[UIColor clearColor]]; - [caption_ setShadowColor:[UIColor blackColor]]; - [caption_ setTextAlignment:UITextAlignmentCenter]; - [[self view] addSubview:caption_]; + [request setHTTPMethod:method]; - CGRect statusrect; - statusrect.size.width = [[self view] frame].size.width; - statusrect.size.height = 30.0f; - statusrect.origin.x = 0; - statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height; - status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease]; - [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin]; - [status_ setText:@"(Cydia will exit when complete.)"]; - [status_ setFont:[UIFont systemFontOfSize:16.0f]]; - [status_ setTextColor:[UIColor whiteColor]]; - [status_ setBackgroundColor:[UIColor clearColor]]; - [status_ setShadowColor:[UIColor blackColor]]; - [status_ setTextAlignment:UITextAlignmentCenter]; - [[self view] addSubview:status_]; - } return self; + if (Machine_ != NULL) + [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"]; + if (UniqueID_ != nil) + [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"]; + if (Role_ != nil) + [request setValue:Role_ forHTTPHeaderField:@"X-Role"]; + + return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease]; } -- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation { - return IsWildcat_ || orientation == UIInterfaceOrientationPortrait; -} -@end -/* }}} */ +- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button { + NSString *context([alert context]); + + if ([context isEqualToString:@"source"]) { + switch (button) { + case 1: { + NSString *href = [[alert textField] text]; + + //installer_ = [[self _requestHRef:href method:@"GET"] retain]; + + if (![href hasSuffix:@"/"]) + href_ = [href stringByAppendingString:@"/"]; + else + href_ = href; + href_ = [href_ retain]; + + trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain]; + trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain]; + trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain]; + //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain]; + + cydia_ = false; -/* Cydia Container {{{ */ -@interface CYContainer : UIViewController { - _transient Database *database_; - RefreshBar *refreshbar_; + // XXX: this is stupid + hud_ = [[delegate_ addProgressHUD] retain]; + [hud_ setText:UCLocalize("VERIFYING_URL")]; + } break; - bool dropped_; - bool updating_; - // XXX: ok, "updatedelegate_"?... - _transient NSObject *updatedelegate_; - // XXX: can't we query for this variable when we need it? - _transient UITabBarController *root_; -} + case 0: + break; -- (void) setTabBarController:(UITabBarController *)controller; + _nodefault + } -- (void) dropBar:(BOOL)animated; -- (void) beginUpdate; -- (void) raiseBar:(BOOL)animated; -- (BOOL) updating; + [alert dismissWithClickedButtonIndex:-1 animated:YES]; + } else if ([context isEqualToString:@"trivial"]) + [alert dismissWithClickedButtonIndex:-1 animated:YES]; + else if ([context isEqualToString:@"urlerror"]) + [alert dismissWithClickedButtonIndex:-1 animated:YES]; + else if ([context isEqualToString:@"warning"]) { + switch (button) { + case 1: + [self complete]; + break; -@end + case 0: + break; -@implementation CYContainer + _nodefault + } -- (BOOL) _reallyWantsFullScreenLayout { - return YES; + [href_ release]; + href_ = nil; + + [alert dismissWithClickedButtonIndex:-1 animated:YES]; + } } -// NOTE: UIWindow only sends the top controller these messages, -// So we have to forward them on. +- (id) initWithDatabase:(Database *)database { + if ((self = [super init]) != nil) { + [[self navigationItem] setTitle:UCLocalize("SOURCES")]; + [self updateButtonsForEditingStatus:NO animated:NO]; -- (void) viewDidAppear:(BOOL)animated { - [super viewDidAppear:animated]; - [root_ viewDidAppear:animated]; -} + database_ = database; + sources_ = [[NSMutableArray arrayWithCapacity:16] retain]; -- (void) viewWillAppear:(BOOL)animated { - [super viewWillAppear:animated]; - [root_ viewWillAppear:animated]; -} + list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain]; + [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; + [list_ setRowHeight:56]; + [[self view] addSubview:list_]; -- (void) viewDidDisappear:(BOOL)animated { - [super viewDidDisappear:animated]; - [root_ viewDidDisappear:animated]; -} + [list_ setDataSource:self]; + [list_ setDelegate:self]; -- (void) viewWillDisappear:(BOOL)animated { - [super viewWillDisappear:animated]; - [root_ viewWillDisappear:animated]; + [self reloadData]; + } return self; } -- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation { - return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait); -} +- (void) reloadData { + pkgSourceList list; + if (!list.ReadMainList()) + return; -- (void) setTabBarController:(UITabBarController *)controller { - root_ = controller; - [[self view] addSubview:[root_ view]]; -} + [sources_ removeAllObjects]; + [sources_ addObjectsFromArray:[database_ sources]]; + _trace(); + [sources_ sortUsingSelector:@selector(compareByNameAndType:)]; + _trace(); -- (void) setUpdate:(NSDate *)date { - [self beginUpdate]; + int count([sources_ count]); + offset_ = 0; + for (int i = 0; i != count; i++) { + if ([[sources_ objectAtIndex:i] record] == nil) + break; + offset_++; + } + + [list_ setEditing:NO]; + [self updateButtonsForEditingStatus:NO animated:NO]; + [list_ reloadData]; } -- (void) beginUpdate { - [self dropBar:YES]; - [refreshbar_ start]; +- (void) addButtonClicked { + /*[book_ pushPage:[[[AddSourceController alloc] + initWithBook:book_ + database:database_ + ] autorelease]];*/ - updating_ = true; + UIAlertView *alert = [[[UIAlertView alloc] + initWithTitle:UCLocalize("ENTER_APT_URL") + message:nil + delegate:self + cancelButtonTitle:UCLocalize("CANCEL") + otherButtonTitles:UCLocalize("ADD_SOURCE"), nil + ] autorelease]; - [NSThread - detachNewThreadSelector:@selector(performUpdate) - toTarget:self - withObject:nil - ]; -} + [alert setContext:@"source"]; + [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)]; -- (void) performUpdate { _pooled - Status status; - status.setDelegate(self); - [database_ updateWithStatus:status]; + [alert setNumberOfRows:1]; + [alert addTextFieldWithValue:@"http://" label:@""]; - [self - performSelectorOnMainThread:@selector(completeUpdate) - withObject:nil - waitUntilDone:NO - ]; + UITextInputTraits *traits = [[alert textField] textInputTraits]; + [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone]; + [traits setAutocorrectionType:UITextAutocorrectionTypeNo]; + [traits setKeyboardType:UIKeyboardTypeURL]; + // XXX: UIReturnKeyDone + [traits setReturnKeyType:UIReturnKeyNext]; + + [alert show]; } -- (void) completeUpdate { - if (!updating_) - return; - updating_ = false; +- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated { + [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc] + initWithTitle:UCLocalize("ADD") + style:UIBarButtonItemStylePlain + target:self + action:@selector(addButtonClicked) + ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated]; - [self raiseBar:YES]; - [refreshbar_ stop]; - [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0]; -} + [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] + initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT")) + style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain) + target:self + action:@selector(editButtonClicked) + ] autorelease] animated:animated]; -- (void) cancelUpdate { - updating_ = false; - [self raiseBar:YES]; - [refreshbar_ stop]; - [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0]; + if (IsWildcat_ && !editing) + [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] + initWithTitle:UCLocalize("SETTINGS") + style:UIBarButtonItemStylePlain + target:self + action:@selector(settingsButtonClicked) + ] autorelease]]; } -- (void) cancelPressed { - [self cancelUpdate]; +- (void) settingsButtonClicked { + [delegate_ showSettings]; } -- (BOOL) updating { - return updating_; -} +- (void) editButtonClicked { + [list_ setEditing:![list_ isEditing] animated:YES]; -- (void) setProgressError:(NSString *)error withTitle:(NSString *)title { - [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]]; + [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES]; } -- (void) startProgress { -} +@end +/* }}} */ -- (void) setProgressTitle:(NSString *)title { - [self - performSelectorOnMainThread:@selector(_setProgressTitle:) - withObject:title - waitUntilDone:YES - ]; +/* Role Controller {{{ */ +@interface CYSettingsController : CYViewController < + UITableViewDataSource, + UITableViewDelegate +> { + _transient Database *database_; + // XXX: ok, "roledelegate_"?... + _transient id roledelegate_; + UITableView *table_; + UISegmentedControl *segment_; + UIView *container_; } -- (bool) isCancelling:(size_t)received { - return !updating_; -} +- (void) showDoneButton; +- (void) resizeSegmentedControl; -- (void) setProgressPercent:(float)percent { - [self - performSelectorOnMainThread:@selector(_setProgressPercent:) - withObject:[NSNumber numberWithFloat:percent] - waitUntilDone:YES - ]; +@end + +@implementation CYSettingsController +- (void) dealloc { + [table_ release]; + [segment_ release]; + [container_ release]; + + [super dealloc]; } -- (void) addProgressOutput:(NSString *)output { - [self - performSelectorOnMainThread:@selector(_addProgressOutput:) - withObject:output - waitUntilDone:YES - ]; +- (id) initWithDatabase:(Database *)database delegate:(id)delegate { + if ((self = [super init])) { + database_ = database; + roledelegate_ = delegate; + + [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")]; + + NSArray *items = [NSArray arrayWithObjects: + UCLocalize("USER"), + UCLocalize("HACKER"), + UCLocalize("DEVELOPER"), + nil]; + segment_ = [[UISegmentedControl alloc] initWithItems:items]; + container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)]; + [container_ addSubview:segment_]; + + int index = -1; + if ([Role_ isEqualToString:@"User"]) index = 0; + if ([Role_ isEqualToString:@"Hacker"]) index = 1; + if ([Role_ isEqualToString:@"Developer"]) index = 2; + if (index != -1) { + [segment_ setSelectedSegmentIndex:index]; + [self showDoneButton]; + } + + [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged]; + [self resizeSegmentedControl]; + + table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped]; + [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; + [table_ setDelegate:self]; + [table_ setDataSource:self]; + [[self view] addSubview:table_]; + [table_ reloadData]; + } return self; } -- (void) _setProgressTitle:(NSString *)title { - [refreshbar_ setPrompt:title]; +- (void) resizeSegmentedControl { + CGFloat width = [[self view] frame].size.width; + [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)]; } -- (void) _setProgressPercent:(NSNumber *)percent { - [refreshbar_ setProgress:[percent floatValue]]; +- (void) viewWillAppear:(BOOL)animated { + [super viewWillAppear:animated]; + + [self resizeSegmentedControl]; } -- (void) _addProgressOutput:(NSString *)output { +- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration { + [self resizeSegmentedControl]; } -- (void) setUpdateDelegate:(id)delegate { - updatedelegate_ = delegate; +- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { + [self resizeSegmentedControl]; } -- (CGFloat) statusBarHeight { - if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) { - return [[UIApplication sharedApplication] statusBarFrame].size.height; - } else { - return [[UIApplication sharedApplication] statusBarFrame].size.width; +- (void) save { + NSString *role(nil); + + switch ([segment_ selectedSegmentIndex]) { + case 0: role = @"User"; break; + case 1: role = @"Hacker"; break; + case 2: role = @"Developer"; break; + + _nodefault } -} -- (void) dropBar:(BOOL)animated { - if (dropped_) - return; - dropped_ = true; + if (![role isEqualToString:Role_]) { + bool rolling(Role_ == nil); + Role_ = role; - [[self view] addSubview:refreshbar_]; + Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys: + Role_, @"Role", + nil]; - CGFloat sboffset = [self statusBarHeight]; + [Metadata_ setObject:Settings_ forKey:@"Settings"]; + Changed_ = true; - CGRect barframe = [refreshbar_ frame]; - barframe.origin.y = sboffset; - [refreshbar_ setFrame:barframe]; + if (rolling) + [roledelegate_ loadData]; + else + [roledelegate_ updateData]; + } +} - if (animated) - [UIView beginAnimations:nil context:NULL]; - CGRect viewframe = [[root_ view] frame]; - viewframe.origin.y += barframe.size.height + sboffset; - viewframe.size.height -= barframe.size.height + sboffset; - [[root_ view] setFrame:viewframe]; - if (animated) - [UIView commitAnimations]; +- (void) segmentChanged:(UISegmentedControl *)control { + [self showDoneButton]; +} - // Ensure bar has the proper width for our view, it might have changed - barframe.size.width = viewframe.size.width; - [refreshbar_ setFrame:barframe]; +- (void) saveAndClose { + [self save]; - // XXX: fix Apple's layout bug - [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; + [[self navigationItem] setRightBarButtonItem:nil]; + [[self navigationController] dismissModalViewControllerAnimated:YES]; } -- (void) raiseBar:(BOOL)animated { - if (!dropped_) - return; - dropped_ = false; +- (void) doneButtonClicked { + UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease]; + [spinner startAnimating]; + UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease]; + [[self navigationItem] setRightBarButtonItem:spinItem]; - [refreshbar_ removeFromSuperview]; + [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0]; +} - CGFloat sboffset = [self statusBarHeight]; +- (void) showDoneButton { + [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] + initWithTitle:UCLocalize("DONE") + style:UIBarButtonItemStyleDone + target:self + action:@selector(doneButtonClicked) + ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)]; +} - if (animated) - [UIView beginAnimations:nil context:NULL]; - CGRect barframe = [refreshbar_ frame]; - CGRect viewframe = [[root_ view] frame]; - viewframe.origin.y -= barframe.size.height + sboffset; - viewframe.size.height += barframe.size.height + sboffset; - [[root_ view] setFrame:viewframe]; - if (animated) - [UIView commitAnimations]; +- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { + // XXX: For not having a single cell in the table, this sure is a lot of sections. + return 6; +} - // XXX: fix Apple's layout bug - [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; +- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { + return 0; // :( } -- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration { - // XXX: fix Apple's layout bug - [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { + return nil; // This method is required by the protocol. } -- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { - if (dropped_) { - [self raiseBar:NO]; - [self dropBar:NO]; - } +- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section { + if (section == 1) + return UCLocalize("ROLE_EX"); + if (section == 4) + return [NSString stringWithFormat: + @"%@: %@\n%@: %@\n%@: %@", + UCLocalize("USER"), UCLocalize("USER_EX"), + UCLocalize("HACKER"), UCLocalize("HACKER_EX"), + UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX") + ]; + else return nil; +} - // XXX: fix Apple's layout bug - [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; +- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { + return section == 3 ? 44.0f : 0; } -- (void) statusBarFrameChanged:(NSNotification *)notification { - if (dropped_) { - [self raiseBar:NO]; - [self dropBar:NO]; - } +- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { + return section == 3 ? container_ : nil; } -- (void) dealloc { - [refreshbar_ release]; - [[NSNotificationCenter defaultCenter] removeObserver:self]; - [super dealloc]; +@end +/* }}} */ +/* Stash Controller {{{ */ +@interface CYStashController : CYViewController { + // XXX: just delete these things + _transient UIActivityIndicatorView *spinner_; + _transient UILabel *status_; + _transient UILabel *caption_; } +@end -- (id) initWithDatabase:(Database *)database { - if ((self = [super init]) != nil) { - database_ = database; +@implementation CYStashController +- (id) init { + if ((self = [super init])) { + [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]]; - [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil]; + spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease]; + CGRect spinrect = [spinner_ frame]; + spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2); + spinrect.origin.y = [[self view] frame].size.height - 80.0f; + [spinner_ setFrame:spinrect]; + [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin]; + [[self view] addSubview:spinner_]; + [spinner_ startAnimating]; - refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self]; + CGRect captrect; + captrect.size.width = [[self view] frame].size.width; + captrect.size.height = 40.0f; + captrect.origin.x = 0; + captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2); + caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease]; + [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")]; + [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin]; + [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]]; + [caption_ setTextColor:[UIColor whiteColor]]; + [caption_ setBackgroundColor:[UIColor clearColor]]; + [caption_ setShadowColor:[UIColor blackColor]]; + [caption_ setTextAlignment:UITextAlignmentCenter]; + [[self view] addSubview:caption_]; + + CGRect statusrect; + statusrect.size.width = [[self view] frame].size.width; + statusrect.size.height = 30.0f; + statusrect.origin.x = 0; + statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height; + status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease]; + [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin]; + [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")]; + [status_ setFont:[UIFont systemFontOfSize:16.0f]]; + [status_ setTextColor:[UIColor whiteColor]]; + [status_ setBackgroundColor:[UIColor clearColor]]; + [status_ setShadowColor:[UIColor blackColor]]; + [status_ setTextAlignment:UITextAlignmentCenter]; + [[self view] addSubview:status_]; } return self; } +- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation { + return IsWildcat_ || orientation == UIInterfaceOrientationPortrait; +} @end /* }}} */ @@ -7962,7 +8149,6 @@ typedef enum { // XXX: evaluate all fields for _transient UIWindow *window_; - CYContainer *container_; CYTabBarController *tabbar_; NSMutableArray *essential_; @@ -7970,15 +8156,17 @@ typedef enum { Database *database_; - int tag_; - int hudcount_; NSURL *starturl_; + int tag_; - SectionsController *sections_; + unsigned locked_; + unsigned activity_; + + CYSectionsController *sections_; ChangesController *changes_; ManageController *manage_; SearchController *search_; - SourceTable *sources_; + SourceController *sources_; InstalledController *installed_; id queueDelegate_; @@ -7991,6 +8179,9 @@ typedef enum { - (void) setPage:(CYViewController *)page; - (void) loadData; +// XXX: I hate prototypes +- (id) queueBadgeController; + @end static _finline void _setHomePage(Cydia *self) { @@ -8000,15 +8191,11 @@ static _finline void _setHomePage(Cydia *self) { @implementation Cydia - (void) beginUpdate { - [container_ beginUpdate]; + [tabbar_ beginUpdate]; } - (BOOL) updating { - return [container_ updating]; -} - -- (UIView *) rotatingContentViewForWindow:(UIWindow *)window { - return window_; + return [tabbar_ updating]; } - (void) _loaded { @@ -8042,36 +8229,52 @@ static _finline void _setHomePage(Cydia *self) { } - (void) _saveConfig { + _trace(); + MetaFile_.Sync(); + _trace(); + if (Changed_) { - _trace(); NSString *error(nil); + if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) { _trace(); NSError *error(nil); if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error]) NSLog(@"failure to save metadata data: %@", error); _trace(); + + Changed_ = false; } else { NSLog(@"failure to serialize metadata: %@", error); - return; } - - Changed_ = false; } } - (void) _updateData { [self _saveConfig]; - /* XXX: this is just stupid */ - if (tag_ != 1 && sections_ != nil) - [sections_ reloadData]; - if (tag_ != 2 && changes_ != nil) - [changes_ reloadData]; - if (tag_ != 4 && search_ != nil) - [search_ reloadData]; + NSMutableSet *tabs([[[NSMutableSet alloc] initWithCapacity:10] autorelease]); + + [tabs addObject:[tabbar_ selectedViewController]]; + + if (sections_ != nil) + [tabs addObject:sections_]; + if (changes_ != nil) + [tabs addObject:changes_]; + if (manage_ != nil) + [tabs addObject:manage_]; + if (search_ != nil) + [tabs addObject:search_]; + if (sources_ != nil) + [tabs addObject:sources_]; + if (installed_ != nil) + [tabs addObject:installed_]; - [(CYNavigationController *)[tabbar_ selectedViewController] reloadData]; + for (CYNavigationController *tab in tabs) + [tab reloadData]; + + [queueDelegate_ queueStatusDidChange]; + [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)]; } - (int)indexOfTabWithTag:(int)tag { @@ -8132,7 +8335,7 @@ static _finline void _setHomePage(Cydia *self) { // If we can reach the server, auto-refresh! if (reachable) - [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO]; + [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO]; [pool release]; } @@ -8166,24 +8369,20 @@ static _finline void _setHomePage(Cydia *self) { } } + NSLog(@"changes:#%u", changes); + UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem]; if (changes != 0) { + _trace(); NSString *badge([[NSNumber numberWithInt:changes] stringValue]); [changesItem setBadgeValue:badge]; [changesItem setAnimatedBadge:([essential_ count] > 0)]; - - if ([self respondsToSelector:@selector(setApplicationBadge:)]) - [self setApplicationBadge:badge]; - else - [self setApplicationBadgeString:badge]; + [self setApplicationIconBadgeNumber:changes]; } else { + _trace(); [changesItem setBadgeValue:nil]; [changesItem setAnimatedBadge:NO]; - - if ([self respondsToSelector:@selector(removeApplicationBadge)]) - [self removeApplicationBadge]; - else // XXX: maybe use setApplicationBadgeString also? - [self setApplicationIconBadgeNumber:0]; + [self setApplicationIconBadgeNumber:0]; } [self _updateData]; @@ -8221,7 +8420,7 @@ static _finline void _setHomePage(Cydia *self) { CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease]; if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet]; - [container_ presentModalViewController:navigation animated:YES]; + [tabbar_ presentModalViewController:navigation animated:YES]; [progress detachNewThreadSelector:@selector(update_) @@ -8245,10 +8444,6 @@ static _finline void _setHomePage(Cydia *self) { _error->Discard(); } -- (CGRect) popUpBounds { - return [[tabbar_ view] bounds]; -} - - (bool) perform { if (![database_ prepare]) return false; @@ -8260,7 +8455,7 @@ static _finline void _setHomePage(Cydia *self) { if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet]; - [container_ presentModalViewController:confirm_ animated:YES]; + [tabbar_ presentModalViewController:confirm_ animated:YES]; return true; } @@ -8319,6 +8514,8 @@ static _finline void _setHomePage(Cydia *self) { } - (void) confirmWithNavigationController:(UINavigationController *)navigation { + Queuing_ = false; + ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]; if (navigation != nil) { @@ -8327,7 +8524,7 @@ static _finline void _setHomePage(Cydia *self) { navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease]; if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet]; - [container_ presentModalViewController:navigation animated:YES]; + [tabbar_ presentModalViewController:navigation animated:YES]; } [progress @@ -8336,9 +8533,12 @@ static _finline void _setHomePage(Cydia *self) { withObject:nil title:UCLocalize("RUNNING") ]; + + ++locked_; } - (void) progressControllerIsComplete:(ProgressController *)progress { + --locked_; [self complete]; } @@ -8358,9 +8558,9 @@ static _finline void _setHomePage(Cydia *self) { return browser; } -- (SectionsController *) sectionsController { +- (CYSectionsController *) sectionsController { if (sections_ == nil) - sections_ = [[SectionsController alloc] initWithDatabase:database_]; + sections_ = [[CYSectionsController alloc] initWithDatabase:database_]; return sections_; } @@ -8388,9 +8588,9 @@ static _finline void _setHomePage(Cydia *self) { return search_; } -- (SourceTable *) sourcesController { +- (SourceController *) sourcesController { if (sources_ == nil) - sources_ = [[SourceTable alloc] initWithDatabase:database_]; + sources_ = [[SourceController alloc] initWithDatabase:database_]; return sources_; } @@ -8429,11 +8629,21 @@ static _finline void _setHomePage(Cydia *self) { } - (void) showSettings { - RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease]; + CYSettingsController *role = [[[CYSettingsController alloc] initWithDatabase:database_ delegate:self] autorelease]; CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease]; if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet]; - [container_ presentModalViewController:nav animated:YES]; + [tabbar_ presentModalViewController:nav animated:YES]; +} + +- (void) retainNetworkActivityIndicator { + if (activity_++ == 0) + [self setNetworkActivityIndicatorVisible:YES]; +} + +- (void) releaseNetworkActivityIndicator { + if (--activity_ == 0) + [self setNetworkActivityIndicatorVisible:NO]; } - (void) setPackageController:(PackageController *)view { @@ -8463,18 +8673,12 @@ static _finline void _setHomePage(Cydia *self) { @synchronized (self) { if (clear) { [database_ clear]; - - // Stop queuing. Queuing_ = false; - [[[self queueBadgeController] tabBarItem] setBadgeValue:nil]; } else { - // Start queuing. Queuing_ = true; - [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")]; } [self _updateData]; - [queueDelegate_ queueStatusDidChange]; } } @@ -8523,7 +8727,9 @@ static _finline void _setHomePage(Cydia *self) { } - (void) system:(NSString *)command { _pooled + _trace(); system([command UTF8String]); + _trace(); } - (void) applicationWillSuspend { @@ -8531,13 +8737,10 @@ static _finline void _setHomePage(Cydia *self) { [super applicationWillSuspend]; } -- (BOOL) hudIsShowing { - return (hudcount_ > 0); -} - -- (void) applicationSuspend:(__GSEvent *)event { +- (BOOL) isSafeToSuspend { // Use external process status API internally. // This is probably a really bad idea. + // XXX: what is the point of this? does this solve anything at all? uint64_t status = 0; int notify_token; if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) { @@ -8545,17 +8748,21 @@ static _finline void _setHomePage(Cydia *self) { notify_cancel(notify_token); } - if (![self hudIsShowing] && status == 0) + return locked_ == 0 && status == 0; +} + +- (void) applicationSuspend:(__GSEvent *)event { + if ([self isSafeToSuspend]) [super applicationSuspend:event]; } - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 { - if (![self hudIsShowing]) + if ([self isSafeToSuspend]) [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3]; } - (void) _setSuspended:(BOOL)value { - if (![self hudIsShowing]) + if ([self isSafeToSuspend]) [super _setSuspended:value]; } @@ -8566,11 +8773,11 @@ static _finline void _setHomePage(Cydia *self) { [window_ setUserInteractionEnabled:NO]; [hud show:YES]; - UIViewController *target = container_; + UIViewController *target = tabbar_; while ([target modalViewController] != nil) target = [target modalViewController]; [[target view] addSubview:hud]; - hudcount_++; + ++locked_; return hud; } @@ -8578,7 +8785,7 @@ static _finline void _setHomePage(Cydia *self) { [hud show:NO]; [hud removeFromSuperview]; [window_ setUserInteractionEnabled:YES]; - hudcount_--; + --locked_; } - (CYViewController *) pageForPackage:(NSString *)name { @@ -8611,12 +8818,12 @@ static _finline void _setHomePage(Cydia *self) { if (![path hasPrefix:@"/"]) path = [@"/" stringByAppendingString:path]; - if ([path isEqualToString:@"/add-source"]) - return [[[AddSourceController alloc] initWithDatabase:database_] autorelease]; - else if ([path isEqualToString:@"/storage"]) + if ([path isEqualToString:@"/storage"]) return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]]; + /*else if ([path isEqualToString:@"/add-source"]) + return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];*/ else if ([path isEqualToString:@"/sources"]) - return [[[SourceTable alloc] initWithDatabase:database_] autorelease]; + return [[[SourceController alloc] initWithDatabase:database_] autorelease]; else if ([path isEqualToString:@"/packages"]) return [[[InstalledController alloc] initWithDatabase:database_] autorelease]; else if ([path hasPrefix:@"/url/"]) @@ -8624,7 +8831,7 @@ static _finline void _setHomePage(Cydia *self) { else if ([path hasPrefix:@"/launch/"]) [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO]; else if ([path hasPrefix:@"/package-settings/"]) - return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease]; + return [[[CYPackageSettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease]; else if ([path hasPrefix:@"/package-signature/"]) return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease]; else if ([path hasPrefix:@"/package/"]) @@ -8646,8 +8853,6 @@ static _finline void _setHomePage(Cydia *self) { CYViewController *page = nil; int tag = 0; - NSLog(@"open url: %@", url); - if ((page = [self pageForURL:url hasTag:&tag])) { [self setPage:page]; tag_ = tag; @@ -8659,21 +8864,22 @@ static _finline void _setHomePage(Cydia *self) { - (void) applicationOpenURL:(NSURL *)url { [super applicationOpenURL:url]; - NSLog(@"first: %@", url); + if (!loaded_) starturl_ = [url retain]; else [self openCydiaURL:url]; } - (void) applicationWillResignActive:(UIApplication *)application { // Stop refreshing if you get a phone call or lock the device. - if ([container_ updating]) - [container_ cancelUpdate]; + if ([tabbar_ updating]) + [tabbar_ cancelUpdate]; if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)]) [super applicationWillResignActive:application]; } - (void) addStashController { + ++locked_; stash_ = [[CYStashController alloc] init]; [window_ addSubview:[stash_ view]]; } @@ -8681,6 +8887,7 @@ static _finline void _setHomePage(Cydia *self) { - (void) removeStashController { [[stash_ view] removeFromSuperview]; [stash_ release]; + --locked_; } - (void) stash { @@ -8732,7 +8939,33 @@ static _finline void _setHomePage(Cydia *self) { [tabbar_ setViewControllers:controllers]; } +- (void)showFakeTabBarInView:(UIView *)view { + static UITabBar *fake = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)]; + if (view != nil) { + CGRect frame = [fake frame]; + frame.origin.y = [view frame].size.height - frame.size.height; + frame.size.width = [view frame].size.width; + [fake setFrame:frame]; + [fake setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin]; + [view addSubview:fake]; + } else { + [fake removeFromSuperview]; + } +} + - (void) applicationDidFinishLaunching:(id)unused { +_trace(); + CydiaApp = self; + + if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)]) + [self setApplicationSupportsShakeToEdit:NO]; + + [NSURLCache setSharedURLCache:[[[SDURLCache alloc] + initWithMemoryCapacity:524288 + diskCapacity:10485760 + diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"] + ] autorelease]]; + [CYBrowserController _initialize]; [NSURLProtocol registerClass:[CydiaURLProtocol class]]; @@ -8748,9 +8981,7 @@ static _finline void _setHomePage(Cydia *self) { essential_ = [[NSMutableArray alloc] initWithCapacity:4]; broken_ = [[NSMutableArray alloc] initWithCapacity:4]; - UIScreen *screen([UIScreen mainScreen]); - - window_ = [[UIWindow alloc] initWithFrame:[screen bounds]]; + window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; [window_ orderFront:self]; [window_ makeKey:self]; [window_ setHidden:NO]; @@ -8778,14 +9009,12 @@ static _finline void _setHomePage(Cydia *self) { database_ = [Database sharedInstance]; [self setupTabBarController]; - - container_ = [[CYContainer alloc] initWithDatabase:database_]; - [container_ setUpdateDelegate:self]; - [container_ setTabBarController:tabbar_]; - [window_ addSubview:[container_ view]]; + [tabbar_ setUpdateDelegate:self]; + [window_ addSubview:[tabbar_ view]]; // Show pinstripes while loading data. - [[container_ view] setBackgroundColor:[UIColor pinStripeColor]]; + [[tabbar_ view] setBackgroundColor:[UIColor pinStripeColor]]; + [self showFakeTabBarInView:[tabbar_ tabBar]]; [self performSelector:@selector(loadData) withObject:nil afterDelay:0]; _trace(); @@ -8798,47 +9027,14 @@ _trace(); return; } + CGRect fixframe = [[tabbar_ view] frame]; + if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) + fixframe.size = CGSizeMake(fixframe.size.height, fixframe.size.width); + CYLoadingIndicator *loading = [[[CYLoadingIndicator alloc] initWithFrame:fixframe] autorelease]; + [loading setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; + [[tabbar_ view] addSubview:loading]; [window_ setUserInteractionEnabled:NO]; - UIView *container = [[[UIView alloc] init] autorelease]; - [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin]; - - UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease]; - [spinner startAnimating]; - [container addSubview:spinner]; - - UILabel *label = [[[UILabel alloc] init] autorelease]; - [label setFont:[UIFont boldSystemFontOfSize:15.0f]]; - [label setBackgroundColor:[UIColor clearColor]]; - [label setTextColor:[UIColor blackColor]]; - [label setShadowColor:[UIColor whiteColor]]; - [label setShadowOffset:CGSizeMake(0, 1)]; - [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]]; - [container addSubview:label]; - - CGSize viewsize = [[tabbar_ view] frame].size; - CGSize spinnersize = [spinner bounds].size; - CGSize textsize = [[label text] sizeWithFont:[label font]]; - float bothwidth = spinnersize.width + textsize.width + 5.0f; - - CGRect containrect = { - CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))), - CGSizeMake(bothwidth, spinnersize.height) - }; - CGRect textrect = { - CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))), - textsize - }; - CGRect spinrect = { - CGPointZero, - spinnersize - }; - - [container setFrame:containrect]; - [spinner setFrame:spinrect]; - [label setFrame:textrect]; - [[container_ view] addSubview:container]; - [self reloadData]; PrintTimes(); @@ -8848,14 +9044,16 @@ _trace(); _setHomePage(self); } + [self showFakeTabBarInView:nil]; + [starturl_ release]; starturl_ = nil; [window_ setUserInteractionEnabled:YES]; // XXX: does this actually slow anything down? - [[container_ view] setBackgroundColor:[UIColor clearColor]]; - [container removeFromSuperview]; + [[tabbar_ view] setBackgroundColor:[UIColor clearColor]]; + [loading removeFromSuperview]; } - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {