X-Git-Url: https://git.saurik.com/cydia.git/blobdiff_plain/7585ce6664b4c87d7b8711506ba64d354c293e9a..1b1d445bc087b7d185fb0ec63c8c96d17704c954:/MobileCydia.mm diff --git a/MobileCydia.mm b/MobileCydia.mm index 0b022ee3..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" /* }}} */ @@ -1010,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_; @@ -1183,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; @@ -1196,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 {{{ */ @@ -1344,6 +1346,7 @@ typedef std::map< unsigned long, _H > SourceMap; pkgSourceList *list_; SourceMap sources_; + CFMutableArrayRef deadSources_; CFMutableArrayRef packages_; _transient NSObject *delegate_; @@ -1353,6 +1356,8 @@ typedef std::map< unsigned long, _H > SourceMap; int cydiafd_; int statusfd_; FILE *input_; + + std::map > sections_; } + (Database *) sharedInstance; @@ -1386,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 {{{ */ @@ -1447,6 +1455,7 @@ struct PackageValue : struct MetaValue : Cytore::Block { + uint32_t active_; Cytore::Offset packages_[1 << 16]; }; @@ -1488,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"]) { @@ -1497,22 +1506,12 @@ static void PackageImport(const void *key, const void *value, void *context) { metadata->first_ = time; } - bool versioned(false); + NSDate *date([package objectForKey:@"LastSeen"]); + NSString *version([package objectForKey:@"LastVersion"]); - if (NSDate *date = [package objectForKey:@"LastSeen"]) { + if (date != nil && version != nil) { time_t time([date timeIntervalSince1970]); - if (metadata->last_ < time || metadata->last_ == 0) { - metadata->last_ = time; - versioned = true; - } - } else if (metadata->last_ == 0) { - metadata->last_ = metadata->first_; - if (metadata->version_[0] == '\0') - versioned = true; - } - - if (versioned) - if (NSString *version = [package objectForKey:@"LastVersion"]) + 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)); @@ -1522,7 +1521,10 @@ static void PackageImport(const void *key, const void *value, void *context) { strncpy(metadata->version_, latest, sizeof(metadata->version_)); metadata->vhash_ = vhash; + + metadata->last_ = time; } + } } // }}} @@ -1829,7 +1831,8 @@ struct ParsedPackage { }; @interface Package : NSObject { - uint32_t era_ : 29; + uint32_t era_ : 26; + uint32_t role_ : 3; uint32_t essential_ : 1; uint32_t obsolete_ : 1; uint32_t ignored_ : 1; @@ -1848,7 +1851,7 @@ struct ParsedPackage { CYString latest_; CYString installed_; - CYString section_; + const char *section_; _transient NSString *section$_; Source *source_; @@ -1857,7 +1860,6 @@ struct ParsedPackage { ParsedPackage *parsed_; NSMutableArray *tags_; - NSString *role_; } - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database; @@ -1919,7 +1921,6 @@ struct ParsedPackage { - (NSArray *) applications; - (Source *) source; -- (NSString *) role; - (BOOL) matches:(NSString *)text; @@ -2080,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]; } @@ -2205,7 +2201,6 @@ struct PackageNameOrdering : _end _profile(Package$initWithVersion$Cache) - id_.set(NULL, iterator.Name()); name_.set(NULL, iterator.Display()); latest_.set(NULL, StripVersion_(version_.VerStr())); @@ -2215,19 +2210,6 @@ struct PackageNameOrdering : installed_.set(NULL, StripVersion_(current.VerStr())); _end - _profile(Package$initWithVersion$Lower) - // 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; - } - _end - _profile(Package$initWithVersion$Tags) pkgCache::TagIterator tag(iterator.TagList()); if (!tag.end()) { @@ -2236,8 +2218,18 @@ struct PackageNameOrdering : 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) @@ -2252,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)); @@ -2266,19 +2268,16 @@ struct PackageNameOrdering : if (metadata->first_ == 0) metadata->first_ = now_; - if (metadata->last_ == 0) - metadata->last_ = metadata->first_; - if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) { - if (metadata->version_[0] != '\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$Flags) @@ -2326,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$_; } @@ -2482,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 @@ -2498,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)) @@ -2721,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; @@ -2747,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; @@ -2879,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 { @@ -3044,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_); @@ -3154,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]; @@ -3229,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; } @@ -3335,7 +3342,9 @@ static NSString *Warning_; ++era_; [self releasePackages]; + sources_.clear(); + CFArrayRemoveAllValues(deadSources_); _error->Discard(); @@ -3356,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) @@ -3423,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]); } { @@ -3477,6 +3493,8 @@ static NSString *Warning_; _trace(); size_t count(CFArrayGetCount(packages_)); + MetaFile_->active_ = count; + for (size_t index(0); index != count; ++index) [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index]; @@ -3499,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 { @@ -3573,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) @@ -3594,6 +3616,8 @@ static NSString *Warning_; ]; } + [CydiaApp releaseNetworkActivityIndicator]; + if (failed) { _trace(); return; @@ -3672,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 /* }}} */ @@ -3928,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_; @@ -4429,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; } } @@ -4486,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); @@ -4659,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 { @@ -4753,7 +4887,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { - (PackageCell *) init; - (void) setPackage:(Package *)package; -+ (int) heightForPackage:(Package *)package; - (void) drawContentRect:(CGRect)rect; @end @@ -4905,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; - [badge_ drawAtPoint:CGPointMake( - 36 - size.width / 2, - 36 - size.height / 2 - )]; + rect.origin.x = 36 - rect.size.width / 2; + rect.origin.y = 36 - rect.size.height / 2; + + [badge_ drawInRect:rect]; } if (highlighted) @@ -4929,10 +5066,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { [placard_ drawAtPoint:CGPointMake(width - 52, 9)]; } -+ (int) heightForPackage:(Package *)package { - return 73; -} - @end /* }}} */ /* Section Cell {{{ */ @@ -5056,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)]; @@ -5318,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 { @@ -5407,6 +5543,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { UITableViewDelegate > { _transient Database *database_; + unsigned era_; NSMutableArray *packages_; NSMutableArray *sections_; UITableView *list_; @@ -5446,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]; } @@ -5464,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"]); @@ -5482,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]]; @@ -5494,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; } @@ -5508,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]; @@ -5516,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]; @@ -5533,6 +5681,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) { } - (void) reloadData { + era_ = [database_ era]; NSArray *packages = [database_ packages]; [packages_ removeAllObjects]; @@ -5544,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]; @@ -5725,1165 +5907,1217 @@ 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); +@end - if (icon_ != nil) - [icon_ drawInRect:CGRectMake(10, 10, 30, 30)]; +@implementation HomeController - if (highlighted) - UISetColor(White_); ++ (BOOL)shouldHideNavigationBar { + return NO; +} - if (!highlighted) - UISetColor(Black_); - [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation]; +- (void) _setMoreHeaders:(NSMutableURLRequest *)request { + [super _setMoreHeaders:request]; - if (!highlighted) - UISetColor(Blue_); - [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation]; - - 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) viewWillAppear:(BOOL)animated { + [super viewWillAppear:animated]; -- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated; + if ([[self class] shouldHideNavigationBar]) + [[self navigationController] setNavigationBarHidden:YES animated:animated]; +} -@end +- (void) viewWillDisappear:(BOOL)animated { + [super viewWillDisappear:animated]; -@implementation SourceTable + if ([[self class] shouldHideNavigationBar]) + [[self navigationController] setNavigationBarHidden:NO animated:animated]; +} -- (void) _releaseConnection:(NSURLConnection *)connection { - if (connection != nil) { - [connection cancel]; - //[connection setDelegate:nil]; - [connection release]; - } +- (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; } -- (void) dealloc { - if (href_ != nil) - [href_ release]; - if (hud_ != nil) - [hud_ release]; - if (error_ != nil) - [error_ release]; +@end +/* }}} */ +/* Manage Controller {{{ */ +@interface ManageController : CYBrowserController { +} - //[self _releaseConnection:installer_]; - [self _releaseConnection:trivial_]; - [self _releaseConnection:trivial_gz_]; - [self _releaseConnection:trivial_bz2_]; - //[self _releaseConnection:automatic_]; +- (void) queueStatusDidChange; +@end - [sources_ release]; - [list_ release]; - [super dealloc]; -} +@implementation ManageController -- (void) viewDidAppear:(BOOL)animated { - [super viewDidAppear:animated]; - [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; -} +- (id) init { + if ((self = [super init]) != nil) { + [[self navigationItem] setTitle:UCLocalize("MANAGE")]; -- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { - return offset_ == 0 ? 1 : 2; -} + [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] + initWithTitle:UCLocalize("SETTINGS") + style:UIBarButtonItemStylePlain + target:self + action:@selector(settingsButtonClicked) + ] autorelease]]; -- (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"); + [self queueStatusDidChange]; + } return self; +} - _nodefault - } +- (void) settingsButtonClicked { + [delegate_ showSettings]; } -- (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_; +#if !AlwaysReload +- (void) queueButtonClicked { + [delegate_ queue]; +} - _nodefault - } +- (void) applyLoadingTitle { + // No "Loading" title. } -- (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath { - unsigned idx = 0; - switch (indexPath.section) { - case 0: idx = indexPath.row; break; - case 1: idx = indexPath.row + offset_; break; +- (void) applyRightButton { + // No right button. +} +#endif - _nodefault +- (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]; } - return [sources_ objectAtIndex:idx]; +#endif } -- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { - Source *source = [self sourceAtIndexPath:indexPath]; - return [source description] == nil ? 56 : 73; +- (bool) isLoading { + return false; } -- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { - static NSString *cellIdentifier = @"SourceCell"; - - SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; - if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease]; - [cell setSource:[self sourceAtIndexPath:indexPath]]; +@end +/* }}} */ - return cell; +/* Refresh Bar {{{ */ +@interface RefreshBar : UINavigationBar { + UIProgressIndicator *indicator_; + UITextLabel *prompt_; + UIProgressBar *progress_; + UINavigationButton *cancel_; } -- (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath { - return UITableViewCellAccessoryDisclosureIndicator; -} +@end -- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { - Source *source = [self sourceAtIndexPath:indexPath]; +@implementation RefreshBar - FilteredPackageController *packages = [[[FilteredPackageController alloc] - initWithDatabase:database_ - title:[source label] - filter:@selector(isVisibleInSource:) - with:source - ] autorelease]; +- (void) dealloc { + [indicator_ release]; + [prompt_ release]; + [progress_ release]; + [cancel_ release]; + [super dealloc]; +} - [packages setDelegate:delegate_]; +- (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]; - [[self navigationController] pushViewController:packages animated:YES]; -} + CGSize prgsize = {75, 100}; + CGRect prgrect = {{ + [self frame].size.width - prgsize.width - 10, + ([self frame].size.height - prgsize.height) / 2 + } , prgsize}; + [progress_ setFrame:prgrect]; -- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { - Source *source = [self sourceAtIndexPath:indexPath]; - return [source record] != nil; -} + CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]); + unsigned indoffset = ([self frame].size.height - indsize.height) / 2; + CGRect indrect = {{indoffset, indoffset}, indsize}; + [indicator_ setFrame:indrect]; -- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { - Source *source = [self sourceAtIndexPath:indexPath]; - [Sources_ removeObjectForKey:[source key]]; - [delegate_ syncData]; + 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) complete { - [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys: - @"deb", @"Type", - href_, @"URI", - @"./", @"Distribution", - nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]]; +- (void)setFrame:(CGRect)frame { + [super setFrame:frame]; - [delegate_ syncData]; + [self positionViews]; } -- (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]); +- (id) initWithFrame:(CGRect)frame delegate:(id)delegate { + if ((self = [super initWithFrame:frame])) { + [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth]; - NSStringEncoding encoding; - NSError *error(nil); + [self setBarStyle:UIBarStyleBlack]; - if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error]) - return [warning length] == 0 ? nil : warning; - return nil; -} + UIBarStyle barstyle([self _barStyle:NO]); + bool ugly(barstyle == UIBarStyleDefault); -- (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]; + 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]); - - if ([context isEqualToString:@"source"]) { - switch (button) { - case 1: { - NSString *href = [[alert textField] text]; +- (void) dropBar:(BOOL)animated; +- (void) beginUpdate; +- (void) raiseBar:(BOOL)animated; +- (BOOL) updating; - //installer_ = [[self _requestHRef:href method:@"GET"] retain]; +@end - if (![href hasSuffix:@"/"]) - href_ = [href stringByAppendingString:@"/"]; - else - href_ = href; - href_ = [href_ retain]; +@implementation CYTabBarController - 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]; +/* XXX: some logic should probably go here related to +freeing the view controllers on tab change */ - cydia_ = false; +- (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]; + } +} - // XXX: this is stupid - hud_ = [[delegate_ addProgressHUD] retain]; - [hud_ setText:UCLocalize("VERIFYING_URL")]; - } break; +- (id) initWithDatabase:(Database *)database { + if ((self = [super init]) != nil) { + database_ = database; - case 0: - break; + [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil]; - _nodefault - } + refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self]; + } return self; +} - [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; +- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation { + return IsWildcat_ || orientation == UIInterfaceOrientationPortrait; +} - 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]; + + if (animated) + [UIView commitAnimations]; + + // Ensure bar has the proper width for our view, it might have changed + barframe.size.width = viewframe.size.width; + [refreshbar_ setFrame:barframe]; + + // XXX: fix Apple's layout bug + [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; } -- (NSString *) title { return UCLocalize("INSTALLED"); } +- (void) raiseBar:(BOOL)animated { + if (!dropped_) + return; + dropped_ = false; -- (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; + UIView *transition([self transitionView]); + [refreshbar_ removeFromSuperview]; + + CGRect barframe([refreshbar_ frame]); + + if (animated) + [UIView beginAnimations:nil context:NULL]; + + CGRect viewframe = [transition frame]; + viewframe.origin.y -= barframe.size.height; + viewframe.size.height += barframe.size.height; + [transition setFrame:viewframe]; + + if (animated) + [UIView commitAnimations]; + + // XXX: fix Apple's layout bug + // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; } -#if !AlwaysReload -- (void) queueButtonClicked { - [delegate_ queue]; +#if 0 +- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration { + // XXX: fix Apple's layout bug + // SRK [[self 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) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { + bool dropped(dropped_); -- (void) reloadData { - [packages_ reloadData]; -} + if (dropped) + [self raiseBar:NO]; -- (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]]; -} + [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; -- (void) roleButtonClicked { - [packages_ setObject:[NSNumber numberWithBool:expert_]]; - [packages_ reloadData]; - expert_ = !expert_; + if (dropped) + [self dropBar:NO]; - [self updateRoleButton]; + // XXX: fix Apple's layout bug + // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; } -- (void) setDelegate:(id)delegate { - [super setDelegate:delegate]; - [packages_ setDelegate:delegate]; +- (void) statusBarFrameChanged:(NSNotification *)notification { + if (dropped_) { + [self raiseBar:NO]; + [self dropBar:NO]; + } +} + +- (void) dealloc { + [refreshbar_ release]; + [[NSNotificationCenter defaultCenter] removeObserver:self]; + [super dealloc]; } @end /* }}} */ -/* Home Controller {{{ */ -@interface HomeController : CYBrowserController { +/* Cydia Navigation Controller {{{ */ +@interface CYNavigationController : UINavigationController { + _transient Database *database_; + _transient id delegate_; } +- (id) initWithDatabase:(Database *)database; +- (void) reloadData; + @end -@implementation HomeController -- (void) _setMoreHeaders:(NSMutableURLRequest *)request { - [super _setMoreHeaders:request]; +@implementation CYNavigationController - 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"]; +- (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) aboutButtonClicked { - UIAlertView *alert([[[UIAlertView alloc] init] autorelease]); - - [alert setTitle:UCLocalize("ABOUT_CYDIA")]; - [alert addButtonWithTitle:UCLocalize("CLOSE")]; - [alert setCancelButtonIndex:0]; - - [alert setMessage: - @"Copyright (C) 2008-2010\n" - "Jay Freeman (saurik)\n" - "saurik@saurik.com\n" - "http://www.saurik.com/" - ]; - - [alert show]; +- (void) dealloc { + [super dealloc]; } -- (void) viewWillAppear:(BOOL)animated { - [super viewWillAppear:animated]; - //[[self navigationController] setNavigationBarHidden:YES 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]; + } } -- (void) viewWillDisappear:(BOOL)animated { - [super viewWillDisappear:animated]; - //[[self navigationController] setNavigationBarHidden:NO animated:animated]; +- (void) setDelegate:(id)delegate { + delegate_ = delegate; } -- (id) init { +- (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]; - - CGSize prgsize = {75, 100}; - CGRect prgrect = {{ - [self frame].size.width - prgsize.width - 10, - ([self frame].size.height - prgsize.height) / 2 - } , prgsize}; - [progress_ setFrame:prgrect]; - - CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]); - unsigned indoffset = ([self frame].size.height - indsize.height) / 2; - CGRect indrect = {{indoffset, indoffset}, indsize}; - [indicator_ setFrame:indrect]; +- (void) setEditing:(BOOL)editing { + if ((editing_ = editing)) + [list_ reloadData]; + else + [delegate_ updateData]; - 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]; + [[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]; } -- (void)setFrame:(CGRect)frame { - [super setFrame:frame]; - - [self positionViews]; +- (void) viewDidAppear:(BOOL)animated { + [super viewDidAppear:animated]; + [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; } -- (id) initWithFrame:(CGRect)frame delegate:(id)delegate { - if ((self = [super initWithFrame:frame])) { - [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth]; - - [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]]; - [self setBarStyle:UIBarStyleBlack]; +- (void) viewWillDisappear:(BOOL)animated { + [super viewWillDisappear:animated]; + if (editing_) [self setEditing:NO]; +} - UIBarStyle barstyle([self _barStyle:NO]); - bool ugly(barstyle == UIBarStyleDefault); +- (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath { + Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)])); + return section; +} - UIProgressIndicatorStyle style = ugly ? - UIProgressIndicatorStyleMediumBrown : - UIProgressIndicatorStyleMediumWhite; +- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { + return editing_ ? [sections_ count] : [filtered_ count] + 1; +} - indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero]; - [indicator_ setStyle:style]; - [indicator_ startAnimation]; - [self addSubview:indicator_]; +/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { + return 45.0f; +}*/ - prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero]; - [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]]; - [prompt_ setBackgroundColor:[UIColor clearColor]]; - [prompt_ setFont:[UIFont systemFontOfSize:15]]; - [self addSubview:prompt_]; +- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { + static NSString *reuseIdentifier = @"SectionCell"; - progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero]; - [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin]; - [progress_ setStyle:0]; - [self addSubview:progress_]; + SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; + if (cell == nil) + cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease]; - cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted]; - [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; - [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside]; - [cancel_ setBarStyle:barstyle]; + [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_]; - [self positionViews]; - } return self; + return cell; } -- (void) cancel { - [cancel_ removeFromSuperview]; -} +- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { + if (editing_) + return; -- (void) start { - [prompt_ setText:UCLocalize("UPDATING_DATABASE")]; - [progress_ setProgress:0]; - [self addSubview:cancel_]; -} + Section *section = [self sectionAtIndexPath:indexPath]; + NSString *name = [section name]; + NSString *title; -- (void) stop { - [cancel_ removeFromSuperview]; -} + 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"); + } + } -- (void) setPrompt:(NSString *)prompt { - [prompt_ setText:prompt]; -} + FilteredPackageController *table = [[[FilteredPackageController alloc] + initWithDatabase:database_ + title:title + filter:@selector(isVisibleInSection:) + with:name + ] autorelease]; -- (void) setProgress:(float)progress { - [progress_ setProgress:progress]; + [table setDelegate:delegate_]; + + [[self navigationController] pushViewController:table animated:YES]; } -@end -/* }}} */ +- (NSString *) title { return UCLocalize("SECTIONS"); } -@class CYNavigationController; +- (id) initWithDatabase:(Database *)database { + if ((self = [super init]) != nil) { + database_ = database; -/* Cydia Tab Bar Controller {{{ */ -@interface CYTabBarController : UITabBarController < - ProgressDelegate -> { - _transient Database *database_; - RefreshBar *refreshbar_; + [[self navigationItem] setTitle:UCLocalize("SECTIONS")]; - bool dropped_; - bool updating_; - // XXX: ok, "updatedelegate_"?... - _transient NSObject *updatedelegate_; + sections_ = [[NSMutableArray arrayWithCapacity:16] retain]; + filtered_ = [[NSMutableArray arrayWithCapacity:16] retain]; - id root_; -} + list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]]; + [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; + [list_ setRowHeight:45.0f]; + [[self view] addSubview:list_]; -- (void) dropBar:(BOOL)animated; -- (void) beginUpdate; -- (void) raiseBar:(BOOL)animated; -- (BOOL) updating; + [list_ setDataSource:self]; + [list_ setDelegate:self]; -@end + [self reloadData]; + } return self; +} -@implementation CYTabBarController +- (void) reloadData { + NSArray *packages = [database_ packages]; -/* XXX: some logic should probably go here related to -freeing the view controllers on tab change */ + [sections_ removeAllObjects]; + [filtered_ removeAllObjects]; -- (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]; - } -} + NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]); -- (id) initWithDatabase:(Database *)database { - if ((self = [super init]) != nil) { - database_ = database; + _trace(); + for (Package *package in packages) { + NSString *name([package section]); + NSString *key(name == nil ? @"" : name); - [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil]; + Section *section; - refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self]; - } return self; -} + _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 -- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation { - return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait); -} + [section addToCount]; -- (void) setUpdate:(NSDate *)date { - [self beginUpdate]; -} + _profile(SectionsView$reloadData$Filter) + if (![package valid] || ![package visible]) + continue; + _end -- (void) beginUpdate { - [self dropBar:YES]; - [refreshbar_ start]; + [section addToRow]; + } + _trace(); - updating_ = true; + [sections_ addObjectsFromArray:[sections allValues]]; - [NSThread - detachNewThreadSelector:@selector(performUpdate) - toTarget:self - withObject:nil - ]; -} + [sections_ sortUsingSelector:@selector(compareByLocalized:)]; -- (void) performUpdate { _pooled - Status status; - status.setDelegate(self); - [database_ updateWithStatus:status]; + for (Section *section in sections_) { + size_t count([section row]); + if (count == 0) + continue; - [self - performSelectorOnMainThread:@selector(completeUpdate) - withObject:nil - waitUntilDone:NO - ]; -} + section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease]; + [section setCount:count]; + [filtered_ addObject:section]; + } -- (void) completeUpdate { - if (!updating_) - return; - updating_ = false; + [[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)]; - [self raiseBar:YES]; - [refreshbar_ stop]; - [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0]; + [list_ reloadData]; + _trace(); } -- (void) cancelUpdate { - updating_ = false; - [self raiseBar:YES]; - [refreshbar_ stop]; - [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0]; +- (void) resetView { + if (editing_) + [self editButtonClicked]; } -- (void) cancelPressed { - [self cancelUpdate]; +- (void)editButtonClicked { + [self setEditing:!editing_]; } -- (BOOL) updating { - return updating_; +- (UIView *) accessoryView { + return accessory_; } -- (void) setProgressError:(NSString *)error withTitle:(NSString *)title { - [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]]; +@end +/* }}} */ +/* Changes Controller {{{ */ +@interface ChangesController : CYViewController < + UITableViewDataSource, + UITableViewDelegate +> { + _transient Database *database_; + unsigned era_; + CFMutableArrayRef packages_; + NSMutableArray *sections_; + UITableView *list_; + unsigned upgrades_; + BOOL hasSentFirstLoad_; } -- (void) startProgress { -} +- (id) initWithDatabase:(Database *)database delegate:(id)delegate; +- (void) reloadData; -- (void) setProgressTitle:(NSString *)title { - [self - performSelectorOnMainThread:@selector(_setProgressTitle:) - withObject:title - waitUntilDone:YES - ]; -} +@end -- (bool) isCancelling:(size_t)received { - return !updating_; +@implementation ChangesController + +- (void) dealloc { + [list_ setDelegate:nil]; + [list_ setDataSource:nil]; + + CFRelease(packages_); + + [sections_ release]; + [list_ release]; + [super dealloc]; } -- (void) setProgressPercent:(float)percent { - [self - performSelectorOnMainThread:@selector(_setProgressPercent:) - withObject:[NSNumber numberWithFloat:percent] - waitUntilDone:YES - ]; +- (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]; + } } -- (void) addProgressOutput:(NSString *)output { - [self - performSelectorOnMainThread:@selector(_addProgressOutput:) - withObject:output - waitUntilDone:YES - ]; +- (NSInteger) numberOfSectionsInTableView:(UITableView *)list { + NSInteger count([sections_ count]); + return count == 0 ? 1 : count; } -- (void) _setProgressTitle:(NSString *)title { - [refreshbar_ setPrompt:title]; +- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section { + if ([sections_ count] == 0) + return nil; + return [[sections_ objectAtIndex:section] name]; } -- (void) _setProgressPercent:(NSNumber *)percent { - [refreshbar_ setProgress:[percent floatValue]]; +- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section { + if ([sections_ count] == 0) + return 0; + return [[sections_ objectAtIndex:section] count]; } -- (void) _addProgressOutput:(NSString *)output { +- (Package *) packageAtIndex:(NSUInteger)index { + return (Package *) CFArrayGetValueAtIndex(packages_, index); } -- (void) setUpdateDelegate:(id)delegate { - updatedelegate_ = delegate; +- (Package *) packageAtIndexPath:(NSIndexPath *)path { +@synchronized (database_) { + if ([database_ era] != era_) + return nil; + + 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; } -- (CGFloat) statusBarHeight { - if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) { - return [[UIApplication sharedApplication] statusBarFrame].size.height; - } else { - return [[UIApplication sharedApplication] statusBarFrame].size.width; - } +- (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; } -- (UIView *) transitionView { - if ([self respondsToSelector:@selector(_transitionView)]) - return [self _transitionView]; - else - return MSHookIvar(self, "_viewControllerTransitionView"); +- (void) refreshButtonClicked { + [delegate_ beginUpdate]; + [[self navigationItem] setLeftBarButtonItem:nil animated:YES]; } -- (void) dropBar:(BOOL)animated { - if (dropped_) - return; - dropped_ = true; +- (void) upgradeButtonClicked { + [delegate_ distUpgrade]; +} - UIView *transition([self transitionView]); - [[self view] addSubview:refreshbar_]; +- (NSString *) title { return UCLocalize("CHANGES"); } - CGRect barframe([refreshbar_ frame]); +- (id) initWithDatabase:(Database *)database delegate:(id)delegate { + if ((self = [super init]) != nil) { + database_ = database; + [[self navigationItem] setTitle:UCLocalize("CHANGES")]; - if (false) // XXX: _UIApplicationLinkedOnOrAfter(4) - barframe.origin.y = [self statusBarHeight]; - else - barframe.origin.y = 0; + packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL); - [refreshbar_ setFrame:barframe]; + sections_ = [[NSMutableArray arrayWithCapacity:16] retain]; - if (animated) - [UIView beginAnimations:nil context:NULL]; + list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain]; + [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; + [list_ setRowHeight:73]; + [[self view] addSubview:list_]; - CGRect viewframe = [transition frame]; - viewframe.origin.y += barframe.size.height; - viewframe.size.height -= barframe.size.height; - [transition setFrame:viewframe]; + [list_ setDataSource:self]; + [list_ setDelegate:self]; - if (animated) - [UIView commitAnimations]; + delegate_ = delegate; + } return self; +} - // Ensure bar has the proper width for our view, it might have changed - barframe.size.width = viewframe.size.width; - [refreshbar_ setFrame:barframe]; +- (void) _reloadPackages:(NSArray *)packages { + CFRelease(packages_); + packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL); - // XXX: fix Apple's layout bug - [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; + _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) raiseBar:(BOOL)animated { - if (!dropped_) - return; - dropped_ = false; +- (void) reloadData { +@synchronized (database_) { + era_ = [database_ era]; + NSArray *packages = [database_ packages]; - UIView *transition([self transitionView]); - [refreshbar_ removeFromSuperview]; + [sections_ removeAllObjects]; - CGRect barframe([refreshbar_ frame]); +#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 - if (animated) - [UIView beginAnimations:nil context:NULL]; + Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease]; + Section *ignored = nil; + Section *section = nil; + time_t last = 0; - CGRect viewframe = [transition frame]; - viewframe.origin.y -= barframe.size.height; - viewframe.size.height += barframe.size.height; - [transition setFrame:viewframe]; + upgrades_ = 0; + bool unseens = false; - if (animated) - [UIView commitAnimations]; + CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle)); - // XXX: fix Apple's layout bug - // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; -} + for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) { + Package *package = [self packageAtIndex:offset]; -#if 0 -- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration { - // XXX: fix Apple's layout bug - // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; -} -#endif + BOOL uae = [package upgradableAndEssential:YES]; -- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { - bool dropped(dropped_); + if (!uae) { + unseens = true; + time_t seen([package seen]); - if (dropped) - [self raiseBar:NO]; + if (section == nil || last != seen) { + last = seen; - [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; + NSString *name; + name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]); + [name autorelease]; - if (dropped) - [self dropBar:NO]; + _profile(ChangesController$reloadData$Allocate) + name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name]; + section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease]; + [sections_ addObject:section]; + _end + } - // XXX: fix Apple's layout bug - // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; -} + [section addToCount]; + } else if ([package ignored]) { + if (ignored == nil) { + ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease]; + } + [ignored addToCount]; + } else { + ++upgrades_; + [upgradable addToCount]; + } + } + _trace(); -- (void) statusBarFrameChanged:(NSNotification *)notification { - if (dropped_) { - [self raiseBar:NO]; - [self dropBar:NO]; + CFRelease(formatter); + + if (unseens) { + Section *last = [sections_ lastObject]; + size_t count = [last count]; + CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0); + [sections_ removeLastObject]; } -} -- (void) dealloc { - [refreshbar_ release]; - [[NSNotificationCenter defaultCenter] removeObserver:self]; - [super dealloc]; -} + if ([ignored count] != 0) + [sections_ insertObject:ignored atIndex:0]; + if (upgrades_ != 0) + [sections_ insertObject:upgradable atIndex:0]; -@end -/* }}} */ + [list_ reloadData]; -/* Cydia Navigation Controller {{{ */ -@interface CYNavigationController : UINavigationController { - _transient Database *database_; - _transient id delegate_; + if (upgrades_ > 0) + [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] + initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]] + style:UIBarButtonItemStylePlain + target:self + action:@selector(upgradeButtonClicked) + ] autorelease]]; + + if (![delegate_ updating]) + [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] + initWithTitle:UCLocalize("REFRESH") + style:UIBarButtonItemStylePlain + target:self + action:@selector(refreshButtonClicked) + ] autorelease]]; + + PrintTimes(); +} } + +@end +/* }}} */ +/* Search Controller {{{ */ +@interface SearchController : FilteredPackageController < + UISearchBarDelegate +> { + UISearchBar *search_; } - (id) initWithDatabase:(Database *)database; @@ -6891,814 +7125,774 @@ freeing the view controllers on tab change */ @end - -@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 { - return [super shouldAutorotateToInterfaceOrientation:orientation]; - } -} +@implementation SearchController - (void) dealloc { + [search_ release]; [super dealloc]; } -- (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]; - } -} - -- (void) setDelegate:(id)delegate { - delegate_ = delegate; -} - -- (id) initWithDatabase:(Database *)database { - if ((self = [super init]) != nil) { - database_ = database; - } return self; +- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar { + [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)]; + [search_ resignFirstResponder]; + [self reloadData]; } -@end -/* }}} */ -/* Cydia:// Protocol {{{ */ -@interface CydiaURLProtocol : NSURLProtocol { +- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text { + [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)]; + [self reloadData]; } -@end - -@implementation CydiaURLProtocol +- (NSString *) title { return nil; } -+ (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; +- (id) initWithDatabase:(Database *)database { + return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil]; } -+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request { - return request; -} +- (void)viewDidAppear:(BOOL)animated { + [super viewDidAppear:animated]; + if (!search_) { + search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)]; + [search_ layoutSubviews]; + [search_ setPlaceholder:UCLocalize("SEARCH_EX")]; -- (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)); + UITextField *textField; + if ([search_ respondsToSelector:@selector(searchField)]) + textField = [search_ searchField]; + else + textField = MSHookIvar(search_, "_searchField"); - 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]; + [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin]; + [search_ setDelegate:self]; + [textField setEnablesReturnKeyAutomatically:NO]; + [[self navigationItem] setTitleView:textField]; } } -- (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]); +- (void) _reloadData { +} - 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) reloadData { + _profile(SearchController$reloadData) + [packages_ reloadData]; + _end + PrintTimes(); + [packages_ resetCursor]; } -- (void) stopLoading { +- (void) didSelectPackage:(Package *)package { + [search_ resignFirstResponder]; + [super didSelectPackage:package]; } @end /* }}} */ - -/* Sections Controller {{{ */ -@interface SectionsController : CYViewController < +/* Settings Controller {{{ */ +@interface CYPackageSettingsController : CYViewController < UITableViewDataSource, UITableViewDelegate > { _transient Database *database_; - NSMutableArray *sections_; - NSMutableArray *filtered_; - UITableView *list_; - UIView *accessory_; - BOOL editing_; + NSString *name_; + Package *package_; + UITableView *table_; + UISwitch *subscribedSwitch_; + UISwitch *ignoredSwitch_; + UITableViewCell *subscribedCell_; + UITableViewCell *ignoredCell_; } -- (id) initWithDatabase:(Database *)database; -- (void) reloadData; -- (void) resetView; - -- (void) editButtonClicked; +- (id) initWithDatabase:(Database *)database package:(NSString *)package; @end -@implementation SectionsController +@implementation CYPackageSettingsController - (void) dealloc { - [list_ setDataSource:nil]; - [list_ setDelegate:nil]; + [name_ release]; + if (package_ != nil) + [package_ release]; + [table_ release]; + [subscribedSwitch_ release]; + [ignoredSwitch_ release]; + [subscribedCell_ release]; + [ignoredCell_ release]; - [sections_ release]; - [filtered_ release]; - [list_ release]; - [accessory_ release]; [super dealloc]; } -- (void) viewDidAppear:(BOOL)animated { - [super viewDidAppear:animated]; - [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; -} +- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { + if (package_ == nil) + return 0; -- (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath { - Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)])); - return section; + return 1; } - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { - return editing_ ? [sections_ count] : [filtered_ count] + 1; -} - -/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { - return 45.0f; -}*/ - -- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { - static NSString *reuseIdentifier = @"SectionCell"; - - SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; - if (cell == nil) - cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease]; + if (package_ == nil) + return 0; - [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_]; + return 2; +} - return cell; +- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section { + return UCLocalize("SHOW_ALL_CHANGES_EX"); } -- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { - if (editing_) +- (void) onSubscribed:(id)control { + bool value([control isOn]); + if (package_ == nil) return; + if ([package_ setSubscribed:value]) + [delegate_ updateData]; +} - Section *section = [self sectionAtIndexPath:indexPath]; - NSString *name = [section name]; - NSString *title; +- (void) onIgnored:(id)control { + // TODO: set Held state - possibly call out to dpkg, etc. +} - 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"); - } - } +- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { + if (package_ == nil) + return nil; - FilteredPackageController *table = [[[FilteredPackageController alloc] - initWithDatabase:database_ - title:title - filter:@selector(isVisibleInSection:) - with:name - ] autorelease]; + switch ([indexPath row]) { + case 0: return subscribedCell_; + case 1: return ignoredCell_; - [table setDelegate:delegate_]; + _nodefault + } - [[self navigationController] pushViewController:table animated:YES]; + return nil; } -- (NSString *) title { return UCLocalize("SECTIONS"); } +- (NSString *) title { return UCLocalize("SETTINGS"); } -- (id) initWithDatabase:(Database *)database { - if ((self = [super init]) != nil) { +- (id) initWithDatabase:(Database *)database package:(NSString *)package { + if ((self = [super init])) { database_ = database; + name_ = [package retain]; - [[self navigationItem] setTitle:UCLocalize("SECTIONS")]; + [[self navigationItem] setTitle:UCLocalize("SETTINGS")]; - sections_ = [[NSMutableArray arrayWithCapacity:16] retain]; - filtered_ = [[NSMutableArray arrayWithCapacity:16] retain]; + table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped]; + [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; + [[self view] addSubview:table_]; - list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]]; - [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; - [list_ setRowHeight:45.0f]; - [[self view] addSubview:list_]; + subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)]; + [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; + [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged]; - [list_ setDataSource:self]; - [list_ setDelegate:self]; + ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)]; + [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; + [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged]; + + subscribedCell_ = [[UITableViewCell alloc] init]; + [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")]; + [subscribedCell_ setAccessoryView:subscribedSwitch_]; + [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone]; + + ignoredCell_ = [[UITableViewCell alloc] init]; + [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]; [self reloadData]; } return self; } - (void) reloadData { - NSArray *packages = [database_ packages]; - - [sections_ removeAllObjects]; - [filtered_ removeAllObjects]; - - NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]); - - _trace(); - for (Package *package in packages) { - NSString *name([package section]); - NSString *key(name == nil ? @"" : name); - - 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]; + if (package_ != nil) + [package_ autorelease]; + package_ = [database_ packageWithName:name_]; + if (package_ != nil) { + [package_ retain]; + [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO]; + [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO]; } - _trace(); - [sections_ addObjectsFromArray:[sections allValues]]; + [table_ reloadData]; +} - [sections_ sortUsingSelector:@selector(compareByLocalized:)]; +@end +/* }}} */ +/* Signature Controller {{{ */ +@interface SignatureController : CYBrowserController { + _transient Database *database_; + NSString *package_; +} - for (Section *section in sections_) { - size_t count([section row]); - if (count == 0) - continue; +- (id) initWithDatabase:(Database *)database package:(NSString *)package; - section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease]; - [section setCount:count]; - [filtered_ addObject:section]; - } +@end - [[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)]; +@implementation SignatureController - [list_ reloadData]; - _trace(); +- (void) dealloc { + [package_ release]; + [super dealloc]; } -- (void) resetView { - if (editing_) - [self editButtonClicked]; +- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame { + // XXX: dude! + [super webView:view didClearWindowObject:window forFrame:frame]; } -- (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]; +- (id) initWithDatabase:(Database *)database package:(NSString *)package { + if ((self = [super init]) != nil) { + database_ = database; + package_ = [package retain]; + [self reloadData]; + } return self; } -- (UIView *) accessoryView { - return accessory_; +- (void) reloadData { + [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]]; } @end /* }}} */ -/* Changes Controller {{{ */ -@interface ChangesController : CYViewController < - UITableViewDataSource, - UITableViewDelegate + +/* Source Cell {{{ */ +@interface SourceCell : CYTableViewCell < + ContentDelegate > { - _transient Database *database_; - CFMutableArrayRef packages_; - NSMutableArray *sections_; - UITableView *list_; - unsigned upgrades_; - BOOL hasSentFirstLoad_; + UIImage *icon_; + NSString *origin_; + NSString *label_; } -- (id) initWithDatabase:(Database *)database delegate:(id)delegate; -- (void) reloadData; +- (void) setSource:(Source *)source; @end -@implementation ChangesController - -- (void) dealloc { - [list_ setDelegate:nil]; - [list_ setDataSource:nil]; +@implementation SourceCell - CFRelease(packages_); +- (void) clearSource { + [icon_ release]; + [origin_ release]; + [label_ release]; - [sections_ release]; - [list_ release]; - [super dealloc]; + icon_ = nil; + origin_ = nil; + label_ = nil; } -- (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]; - } -} +- (void) setSource:(Source *)source { + [self clearSource]; -- (NSInteger) numberOfSectionsInTableView:(UITableView *)list { - NSInteger count([sections_ count]); - return count == 0 ? 1 : count; -} + if (icon_ == nil) + icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]]; + if (icon_ == nil) + icon_ = [UIImage applicationImageNamed:@"unknown.png"]; + icon_ = [icon_ retain]; -- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section { - if ([sections_ count] == 0) - return nil; - return [[sections_ objectAtIndex:section] name]; -} + origin_ = [[source name] retain]; + label_ = [[source uri] retain]; -- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section { - if ([sections_ count] == 0) - return 0; - return [[sections_ objectAtIndex:section] count]; + [content_ setNeedsDisplay]; } -- (Package *) packageAtIndex:(NSUInteger)index { - return (Package *) CFArrayGetValueAtIndex(packages_, index); +- (void) dealloc { + [self clearSource]; + [super dealloc]; } -- (Package *) packageAtIndexPath:(NSIndexPath *)path { - Section *section([sections_ objectAtIndex:[path section]]); - NSInteger row([path row]); - return [self packageAtIndex:([section row] + row)]; +- (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; } -- (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) drawContentRect:(CGRect)rect { + bool highlighted(highlighted_); + float width(rect.size.width); -/*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path { - return [PackageCell heightForPackage:[self packageAtIndexPath:path]]; -}*/ + if (icon_ != nil) + [icon_ drawInRect:CGRectMake(10, 10, 30, 30)]; -- (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; -} + if (highlighted) + UISetColor(White_); -- (void) refreshButtonClicked { - [delegate_ beginUpdate]; - [[self navigationItem] setLeftBarButtonItem:nil animated:YES]; -} + if (!highlighted) + UISetColor(Black_); + [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation]; -- (void) upgradeButtonClicked { - [delegate_ distUpgrade]; + if (!highlighted) + UISetColor(Blue_); + [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation]; } -- (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]; +@end +/* }}} */ +/* Source Table {{{ */ +@interface SourceController : CYViewController < + UITableViewDataSource, + UITableViewDelegate +> { + _transient Database *database_; + UITableView *list_; + NSMutableArray *sources_; + int offset_; - delegate_ = delegate; - } return self; -} + NSString *href_; + UIProgressHUD *hud_; + NSError *error_; -- (void) _reloadPackages:(NSArray *)packages { - _trace(); - for (Package *package in packages) - if ([package upgradableAndEssential:YES] || [package visible]) - CFArrayAppendValue(packages_, package); + //NSURLConnection *installer_; + NSURLConnection *trivial_; + NSURLConnection *trivial_bz2_; + NSURLConnection *trivial_gz_; + //NSURLConnection *automatic_; - _trace(); - [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast(&PackageChangesRadix) withContext:NULL]; - _trace(); + BOOL cydia_; } -- (void) reloadData { - NSArray *packages = [database_ packages]; +- (id) initWithDatabase:(Database *)database; - CFArrayRemoveAllValues(packages_); +- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated; - [sections_ removeAllObjects]; +@end -#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 +@implementation SourceController - Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease]; - Section *ignored = nil; - Section *section = nil; - time_t last = 0; +- (void) _releaseConnection:(NSURLConnection *)connection { + if (connection != nil) { + [connection cancel]; + //[connection setDelegate:nil]; + [connection release]; + } +} - upgrades_ = 0; - bool unseens = false; +- (void) dealloc { + if (href_ != nil) + [href_ release]; + if (hud_ != nil) + [hud_ release]; + if (error_ != nil) + [error_ release]; - CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle)); + //[self _releaseConnection:installer_]; + [self _releaseConnection:trivial_]; + [self _releaseConnection:trivial_gz_]; + [self _releaseConnection:trivial_bz2_]; + //[self _releaseConnection:automatic_]; - for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) { - Package *package = [self packageAtIndex:offset]; + [sources_ release]; + [list_ release]; + [super dealloc]; +} - BOOL uae = [package upgradableAndEssential:YES]; +- (void) viewDidAppear:(BOOL)animated { + [super viewDidAppear:animated]; + [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; +} - if (!uae) { - unseens = true; - time_t seen([package seen]); +- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { + return offset_ == 0 ? 1 : 2; +} - if (section == nil || last != seen) { - last = seen; +- (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"); - NSString *name; - name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]); - [name autorelease]; + _nodefault + } +} - _profile(ChangesController$reloadData$Allocate) - name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name]; - section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease]; - [sections_ addObject:section]; - _end - } +- (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_; - [section addToCount]; - } else if ([package ignored]) { - if (ignored == nil) { - ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease]; - } - [ignored addToCount]; - } else { - ++upgrades_; - [upgradable addToCount]; - } + _nodefault } - _trace(); +} - CFRelease(formatter); +- (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath { + unsigned idx = 0; + switch (indexPath.section) { + case 0: idx = indexPath.row; break; + case 1: idx = indexPath.row + offset_; break; - if (unseens) { - Section *last = [sections_ lastObject]; - size_t count = [last count]; - CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0); - [sections_ removeLastObject]; + _nodefault } + return [sources_ objectAtIndex:idx]; +} - if ([ignored count] != 0) - [sections_ insertObject:ignored atIndex:0]; - if (upgrades_ != 0) - [sections_ insertObject:upgradable atIndex:0]; - - [list_ reloadData]; +- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { + static NSString *cellIdentifier = @"SourceCell"; - if (upgrades_ > 0) - [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] - initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]] - style:UIBarButtonItemStylePlain - target:self - action:@selector(upgradeButtonClicked) - ] autorelease]]; + SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; + if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease]; + [cell setSource:[self sourceAtIndexPath:indexPath]]; - if (![delegate_ updating]) - [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] - initWithTitle:UCLocalize("REFRESH") - style:UIBarButtonItemStylePlain - target:self - action:@selector(refreshButtonClicked) - ] autorelease]]; + return cell; } -@end -/* }}} */ -/* Search Controller {{{ */ -@interface SearchController : FilteredPackageController < - UISearchBarDelegate -> { - UISearchBar *search_; +- (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath { + return UITableViewCellAccessoryDisclosureIndicator; } -- (id) initWithDatabase:(Database *)database; -- (void) reloadData; +- (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]; -@implementation SearchController + [packages setDelegate:delegate_]; -- (void) dealloc { - [search_ release]; - [super dealloc]; + [[self navigationController] pushViewController:packages animated:YES]; } -- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar { - [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)]; - [search_ resignFirstResponder]; - [self reloadData]; +- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { + Source *source = [self sourceAtIndexPath:indexPath]; + return [source record] != nil; } -- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text { - [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)]; - [self reloadData]; +- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { + Source *source = [self sourceAtIndexPath:indexPath]; + [Sources_ removeObjectForKey:[source key]]; + [delegate_ syncData]; } -- (NSString *) title { return nil; } +- (void) complete { + [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys: + @"deb", @"Type", + href_, @"URI", + @"./", @"Distribution", + nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]]; -- (id) initWithDatabase:(Database *)database { - return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil]; + [delegate_ syncData]; } -- (void)viewDidAppear:(BOOL)animated { - [super viewDidAppear:animated]; - if (!search_) { - 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]; - [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin]; - [search_ setDelegate:self]; - [textField setEnablesReturnKeyAutomatically:NO]; - [[self navigationItem] setTitleView:textField]; - } -} +- (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]; -- (void) _reloadData { -} + NSURL *url([NSURL URLWithString:href]); -- (void) reloadData { - _profile(SearchController$reloadData) - [packages_ reloadData]; - _end - PrintTimes(); - [packages_ resetCursor]; + NSStringEncoding encoding; + NSError *error(nil); + + if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error]) + return [warning length] == 0 ? nil : warning; + return nil; } -- (void) didSelectPackage:(Package *)package { - [search_ resignFirstResponder]; - [super didSelectPackage:package]; +- (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; + } + } } -@end -/* }}} */ -/* Settings Controller {{{ */ -@interface SettingsController : CYViewController < - UITableViewDataSource, - UITableViewDelegate -> { - _transient Database *database_; - NSString *name_; - Package *package_; - UITableView *table_; - UISwitch *subscribedSwitch_; - UISwitch *ignoredSwitch_; - UITableViewCell *subscribedCell_; - UITableViewCell *ignoredCell_; +- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response { + switch ([response statusCode]) { + case 200: + cydia_ = YES; + } } -- (id) initWithDatabase:(Database *)database package:(NSString *)package; +- (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 +- (void) connectionDidFinishLoading:(NSURLConnection *)connection { + [self _endConnection:connection]; +} -@implementation SettingsController +- (NSString *) title { return UCLocalize("SOURCES"); } -- (void) dealloc { - [name_ release]; - if (package_ != nil) - [package_ release]; - [table_ release]; - [subscribedSwitch_ release]; - [ignoredSwitch_ release]; - [subscribedCell_ release]; - [ignoredCell_ release]; +- (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method { + NSMutableURLRequest *request = [NSMutableURLRequest + requestWithURL:[NSURL URLWithString:href] + cachePolicy:NSURLRequestUseProtocolCachePolicy + timeoutInterval:120.0 + ]; - [super dealloc]; -} + [request setHTTPMethod:method]; -- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { - if (package_ == nil) - return 0; + 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 1; + return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease]; } -- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { - if (package_ == nil) - return 0; +- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button { + NSString *context([alert context]); - return 2; -} + if ([context isEqualToString:@"source"]) { + switch (button) { + case 1: { + NSString *href = [[alert textField] text]; -- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section { - return UCLocalize("SHOW_ALL_CHANGES_EX"); -} + //installer_ = [[self _requestHRef:href method:@"GET"] retain]; -- (void) onSubscribed:(id)control { - bool value([control isOn]); - if (package_ == nil) - return; - if ([package_ setSubscribed:value]) - [delegate_ updateData]; -} + if (![href hasSuffix:@"/"]) + href_ = [href stringByAppendingString:@"/"]; + else + href_ = href; + href_ = [href_ retain]; -- (void) onIgnored:(id)control { - // TODO: set Held state - possibly call out to dpkg, etc. -} + 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]; -- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { - if (package_ == nil) - return nil; + cydia_ = false; - switch ([indexPath row]) { - case 0: return subscribedCell_; - case 1: return ignoredCell_; + // XXX: this is stupid + hud_ = [[delegate_ addProgressHUD] retain]; + [hud_ setText:UCLocalize("VERIFYING_URL")]; + } break; - _nodefault - } + case 0: + break; - return nil; -} + _nodefault + } -- (NSString *) title { return UCLocalize("SETTINGS"); } + [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; -- (id) initWithDatabase:(Database *)database package:(NSString *)package { - if ((self = [super init])) { - database_ = database; - name_ = [package retain]; + case 0: + break; - [[self navigationItem] setTitle:UCLocalize("SETTINGS")]; + _nodefault + } - table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped]; - [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; - [[self view] addSubview:table_]; + [href_ release]; + href_ = nil; - subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)]; - [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; - [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged]; + [alert dismissWithClickedButtonIndex:-1 animated:YES]; + } +} - ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)]; - [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; - [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged]; +- (id) initWithDatabase:(Database *)database { + if ((self = [super init]) != nil) { + [[self navigationItem] setTitle:UCLocalize("SOURCES")]; + [self updateButtonsForEditingStatus:NO animated:NO]; - subscribedCell_ = [[UITableViewCell alloc] init]; - [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")]; - [subscribedCell_ setAccessoryView:subscribedSwitch_]; - [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone]; + database_ = database; + sources_ = [[NSMutableArray arrayWithCapacity:16] retain]; - ignoredCell_ = [[UITableViewCell alloc] init]; - [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")]; - [ignoredCell_ setAccessoryView:ignoredSwitch_]; - [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone]; + list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain]; + [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; + [list_ setRowHeight:56]; + [[self view] addSubview:list_]; + + [list_ setDataSource:self]; + [list_ setDelegate:self]; - [table_ setDataSource:self]; - [table_ setDelegate:self]; [self reloadData]; } return self; } - (void) reloadData { - if (package_ != nil) - [package_ autorelease]; - package_ = [database_ packageWithName:name_]; - if (package_ != nil) { - [package_ retain]; - [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO]; - [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO]; + pkgSourceList list; + if (!list.ReadMainList()) + return; + + [sources_ removeAllObjects]; + [sources_ addObjectsFromArray:[database_ sources]]; + _trace(); + [sources_ sortUsingSelector:@selector(compareByNameAndType:)]; + _trace(); + + int count([sources_ count]); + offset_ = 0; + for (int i = 0; i != count; i++) { + if ([[sources_ objectAtIndex:i] record] == nil) + break; + offset_++; } - [table_ reloadData]; + [list_ setEditing:NO]; + [self updateButtonsForEditingStatus:NO animated:NO]; + [list_ reloadData]; } -@end -/* }}} */ -/* Signature Controller {{{ */ -@interface SignatureController : CYBrowserController { - _transient Database *database_; - NSString *package_; -} +- (void) addButtonClicked { + /*[book_ pushPage:[[[AddSourceController alloc] + initWithBook:book_ + database:database_ + ] autorelease]];*/ -- (id) initWithDatabase:(Database *)database package:(NSString *)package; + UIAlertView *alert = [[[UIAlertView alloc] + initWithTitle:UCLocalize("ENTER_APT_URL") + message:nil + delegate:self + cancelButtonTitle:UCLocalize("CANCEL") + otherButtonTitles:UCLocalize("ADD_SOURCE"), nil + ] autorelease]; -@end + [alert setContext:@"source"]; + [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)]; -@implementation SignatureController + [alert setNumberOfRows:1]; + [alert addTextFieldWithValue:@"http://" label:@""]; -- (void) dealloc { - [package_ release]; - [super dealloc]; + UITextInputTraits *traits = [[alert textField] textInputTraits]; + [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone]; + [traits setAutocorrectionType:UITextAutocorrectionTypeNo]; + [traits setKeyboardType:UIKeyboardTypeURL]; + // XXX: UIReturnKeyDone + [traits setReturnKeyType:UIReturnKeyNext]; + + [alert show]; } -- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame { - // XXX: dude! - [super webView:view didClearWindowObject:window forFrame:frame]; +- (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 navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] + initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT")) + style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain) + target:self + action:@selector(editButtonClicked) + ] autorelease] animated:animated]; + + if (IsWildcat_ && !editing) + [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] + initWithTitle:UCLocalize("SETTINGS") + style:UIBarButtonItemStylePlain + target:self + action:@selector(settingsButtonClicked) + ] autorelease]]; } -- (id) initWithDatabase:(Database *)database package:(NSString *)package { - if ((self = [super init]) != nil) { - database_ = database; - package_ = [package retain]; - [self reloadData]; - } return self; +- (void) settingsButtonClicked { + [delegate_ showSettings]; } -- (void) reloadData { - [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]]; +- (void) editButtonClicked { + [list_ setEditing:![list_ isEditing] animated:YES]; + + [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES]; } @end /* }}} */ /* Role Controller {{{ */ -@interface RoleController : CYViewController < +@interface CYSettingsController : CYViewController < UITableViewDataSource, UITableViewDelegate > { @@ -7715,7 +7909,7 @@ freeing the view controllers on tab change */ @end -@implementation RoleController +@implementation CYSettingsController - (void) dealloc { [table_ release]; [segment_ release]; @@ -7903,7 +8097,7 @@ freeing the view controllers on tab change */ 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_ setText:UCLocalize("PREPARING_FILESYSTEM")]; [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin]; [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]]; [caption_ setTextColor:[UIColor whiteColor]]; @@ -7919,7 +8113,7 @@ freeing the view controllers on tab change */ 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_ setText:UCLocalize("EXIT_WHEN_COMPLETE")]; [status_ setFont:[UIFont systemFontOfSize:16.0f]]; [status_ setTextColor:[UIColor whiteColor]]; [status_ setBackgroundColor:[UIColor clearColor]]; @@ -7962,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_; @@ -8002,10 +8198,6 @@ static _finline void _setHomePage(Cydia *self) { return [tabbar_ updating]; } -- (UIView *) rotatingContentViewForWindow:(UIWindow *)window { - return window_; -} - - (void) _loaded { if ([broken_ count] != 0) { int count = [broken_ count]; @@ -8061,15 +8253,25 @@ static _finline void _setHomePage(Cydia *self) { - (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]]; - [(CYNavigationController *)[tabbar_ selectedViewController] reloadData]; + 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_]; + + for (CYNavigationController *tab in tabs) + [tab reloadData]; [queueDelegate_ queueStatusDidChange]; [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)]; @@ -8167,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]; @@ -8246,10 +8444,6 @@ static _finline void _setHomePage(Cydia *self) { _error->Discard(); } -- (CGRect) popUpBounds { - return [[tabbar_ view] bounds]; -} - - (bool) perform { if (![database_ prepare]) return false; @@ -8339,9 +8533,12 @@ static _finline void _setHomePage(Cydia *self) { withObject:nil title:UCLocalize("RUNNING") ]; + + ++locked_; } - (void) progressControllerIsComplete:(ProgressController *)progress { + --locked_; [self complete]; } @@ -8361,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_; } @@ -8391,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_; } @@ -8432,13 +8629,23 @@ 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]; [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 { WebThreadLock(); [view setPackage:nil]; @@ -8520,7 +8727,9 @@ static _finline void _setHomePage(Cydia *self) { } - (void) system:(NSString *)command { _pooled + _trace(); system([command UTF8String]); + _trace(); } - (void) applicationWillSuspend { @@ -8528,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) { @@ -8542,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]; } @@ -8567,7 +8777,7 @@ static _finline void _setHomePage(Cydia *self) { while ([target modalViewController] != nil) target = [target modalViewController]; [[target view] addSubview:hud]; - hudcount_++; + ++locked_; return hud; } @@ -8575,7 +8785,7 @@ static _finline void _setHomePage(Cydia *self) { [hud show:NO]; [hud removeFromSuperview]; [window_ setUserInteractionEnabled:YES]; - hudcount_--; + --locked_; } - (CYViewController *) pageForPackage:(NSString *)name { @@ -8608,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/"]) @@ -8621,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/"]) @@ -8643,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; @@ -8656,7 +8864,7 @@ 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]; } @@ -8671,6 +8879,7 @@ static _finline void _setHomePage(Cydia *self) { } - (void) addStashController { + ++locked_; stash_ = [[CYStashController alloc] init]; [window_ addSubview:[stash_ view]]; } @@ -8678,6 +8887,7 @@ static _finline void _setHomePage(Cydia *self) { - (void) removeStashController { [[stash_ view] removeFromSuperview]; [stash_ release]; + --locked_; } - (void) stash { @@ -8729,8 +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]]; @@ -8746,9 +8981,7 @@ _trace(); 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]; @@ -8781,6 +9014,7 @@ _trace(); // Show pinstripes while loading data. [[tabbar_ view] setBackgroundColor:[UIColor pinStripeColor]]; + [self showFakeTabBarInView:[tabbar_ tabBar]]; [self performSelector:@selector(loadData) withObject:nil afterDelay:0]; _trace(); @@ -8793,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]; - [[tabbar_ view] addSubview:container]; - [self reloadData]; PrintTimes(); @@ -8843,6 +9044,8 @@ _trace(); _setHomePage(self); } + [self showFakeTabBarInView:nil]; + [starturl_ release]; starturl_ = nil; @@ -8850,7 +9053,7 @@ _trace(); // XXX: does this actually slow anything down? [[tabbar_ view] setBackgroundColor:[UIColor clearColor]]; - [container removeFromSuperview]; + [loading removeFromSuperview]; } - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {