]> git.saurik.com Git - cydia.git/blobdiff - MobileCydia.mm
Remove firmware (>= 3.2) dependency from control file.
[cydia.git] / MobileCydia.mm
index b849f5ecc187ada7926aa60ebe41d789e2ab9d5a..f113a80c84cc488c3cac89412492615cb71fb67f 100644 (file)
@@ -118,7 +118,10 @@ extern "C" {
 #include <errno.h>
 #include <pcre.h>
 
+#include <Cytore.hpp>
+
 #include "UICaboodle/BrowserView.h"
+#include "SDURLCache/SDURLCache.h"
 
 #include "substrate.h"
 /* }}} */
@@ -202,6 +205,15 @@ void PrintTimes() {
     while (false); \
     [_pool release];
 
+// Hash Functions/Structures {{{
+extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
+
+union SplitHash {
+    uint32_t u32;
+    uint16_t u16[2];
+};
+// }}}
+
 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
 
 void NSLogPoint(const char *fix, const CGPoint &point) {
@@ -265,8 +277,6 @@ static _finline void UpdateExternalStatus(uint64_t newStatus) {
 }
 
 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
-    /*return [self performSelector:selector withObject:object];*/
-
     volatile bool stopped(false);
 
     NSMutableArray *context([NSMutableArray arrayWithObjects:
@@ -755,17 +765,24 @@ class CYString {
             cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
     }
 
+    void copy(apr_pool_t *pool) {
+        char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
+        memcpy(temp, data_, size_);
+        temp[size_] = '\0';
+        data_ = temp;
+    }
+
     void set(apr_pool_t *pool, const char *data, size_t size) {
         if (size == 0)
             clear();
         else {
             clear_();
 
-            char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
-            memcpy(temp, data, size);
-            temp[size] = '\0';
-            data_ = temp;
+            data_ = const_cast<char *>(data);
             size_ = size;
+
+            if (pool != NULL)
+                copy(pool);
         }
     }
 
@@ -790,6 +807,10 @@ class CYString {
     _finline operator id() {
         return (NSString *) static_cast<CFStringRef>(*this);
     }
+
+    _finline operator const char *() {
+        return reinterpret_cast<const char *>(data_);
+    }
 };
 /* }}} */
 /* C++ NSString Algorithm Adapters {{{ */
@@ -1050,7 +1071,7 @@ static _transient NSMutableDictionary *Packages_;
 static _transient NSMutableDictionary *Sections_;
 static _transient NSMutableDictionary *Sources_;
 static bool Changed_;
-static NSDate *now_;
+static time_t now_;
 
 static bool IsWildcat_;
 /* }}} */
@@ -1079,9 +1100,7 @@ NSString *SizeString(double size) {
 
 static _finline const char *StripVersion_(const char *version) {
     const char *colon(strchr(version, ':'));
-    if (colon != NULL)
-        version = colon + 1;
-    return version;
+    return colon == NULL ? version : colon + 1;
 }
 
 NSString *LocalizeSection(NSString *section) {
@@ -1178,7 +1197,6 @@ bool isSectionVisible(NSString *section) {
 - (void) syncData;
 - (void) showSettings;
 - (UIProgressHUD *) addProgressHUD;
-- (BOOL) hudIsShowing;
 - (void) removeProgressHUD:(UIProgressHUD *)hud;
 - (CYViewController *) pageForPackage:(NSString *)name;
 - (PackageController *) packageController;
@@ -1406,6 +1424,109 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 @end
 /* }}} */
 
+// Cytore Definitions {{{
+struct PackageValue :
+    Cytore::Block
+{
+    Cytore::Offset<PackageValue> next_;
+
+    uint32_t index_ : 23;
+    uint32_t subscribed_ : 1;
+    uint32_t : 8;
+
+    int32_t first_;
+    int32_t last_;
+
+    uint16_t vhash_;
+    uint16_t nhash_;
+
+    char version_[8];
+    char name_[];
+};
+
+struct MetaValue :
+    Cytore::Block
+{
+    uint32_t active_;
+    Cytore::Offset<PackageValue> packages_[1 << 16];
+};
+
+static Cytore::File<MetaValue> MetaFile_;
+// }}}
+// Cytore Helper Functions {{{
+static PackageValue *PackageFind(const char *name, size_t length) {
+    SplitHash nhash = { hashlittle(name, length) };
+
+    PackageValue *metadata;
+
+    Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
+    offset: if (offset->IsNull()) {
+        *offset = MetaFile_.New<PackageValue>(length + 1);
+        metadata = &MetaFile_.Get(*offset);
+
+        memcpy(metadata->name_, name, length + 1);
+        metadata->nhash_ = nhash.u16[1];
+    } else {
+        metadata = &MetaFile_.Get(*offset);
+
+        if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
+            offset = &metadata->next_;
+            goto offset;
+        }
+    }
+
+    return metadata;
+}
+
+static void PackageImport(const void *key, const void *value, void *context) {
+    char buffer[1024];
+    if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
+        NSLog(@"failed to import package %@", key);
+        return;
+    }
+
+    PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
+    NSDictionary *package((NSDictionary *) value);
+
+    if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
+        if ([subscribed boolValue])
+            metadata->subscribed_ = true;
+
+    if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
+        time_t time([date timeIntervalSince1970]);
+        if (metadata->first_ > time || metadata->first_ == 0)
+            metadata->first_ = time;
+    }
+
+    bool versioned(false);
+
+    if (NSDate *date = [package objectForKey:@"LastSeen"]) {
+        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 (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
+                size_t length(strlen(buffer));
+                uint16_t vhash(hashlittle(buffer, length));
+
+                size_t capped(std::min<size_t>(8, length));
+                char *latest(buffer + length - capped);
+
+                strncpy(metadata->version_, latest, sizeof(metadata->version_));
+                metadata->vhash_ = vhash;
+            }
+}
+// }}}
+
 /* Source Class {{{ */
 @interface Source : NSObject {
     CYString depiction_;
@@ -1693,48 +1814,51 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 @end
 /* }}} */
 /* Package Class {{{ */
+struct ParsedPackage {
+    CYString tagline_;
+
+    CYString icon_;
+
+    CYString depiction_;
+    CYString homepage_;
+
+    CYString sponsor_;
+    CYString author_;
+
+    CYString bugs_;
+    CYString support_;
+};
+
 @interface Package : NSObject {
-    unsigned era_;
+    uint32_t era_ : 29;
+    uint32_t essential_ : 1;
+    uint32_t obsolete_ : 1;
+    uint32_t ignored_ : 1;
+
     apr_pool_t *pool_;
 
+    _transient Database *database_;
+
     pkgCache::VerIterator version_;
     pkgCache::PkgIterator iterator_;
-    _transient Database *database_;
     pkgCache::VerFileIterator file_;
 
-    Source *source_;
-    bool parsed_;
-
-    CYString section_;
-    _transient NSString *section$_;
-    bool essential_;
-    bool obsolete_;
+    CYString id_;
+    CYString name_;
 
-    NSString *latest_;
+    CYString latest_;
     CYString installed_;
 
-    CYString id_;
-    CYString name_;
-    CYString tagline_;
-    CYString icon_;
-    CYString depiction_;
-    CYString homepage_;
+    CYString section_;
+    _transient NSString *section$_;
 
-    CYString sponsor_;
-    Address *sponsor$_;
+    Source *source_;
 
-    CYString author_;
-    Address *author$_;
+    PackageValue *metadata_;
+    ParsedPackage *parsed_;
 
-    CYString bugs_;
-    CYString support_;
     NSMutableArray *tags_;
     NSString *role_;
-
-    NSMutableDictionary *metadata_;
-    _transient NSDate *firstSeen_;
-    _transient NSDate *lastSeen_;
-    bool subscribed_;
 }
 
 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
@@ -1757,9 +1881,12 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 - (NSString *) shortDescription;
 - (unichar) index;
 
-- (NSMutableDictionary *) metadata;
-- (NSDate *) seen;
-- (BOOL) subscribed;
+- (PackageValue *) metadata;
+- (time_t) seen;
+
+- (bool) subscribed;
+- (bool) setSubscribed:(bool)subscribed;
+
 - (BOOL) ignored;
 
 - (NSString *) latest;
@@ -1803,6 +1930,8 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 - (NSArray *) purposes;
 - (bool) isCommercial;
 
+- (void) setIndex:(size_t)index;
+
 - (CYString &) cyname;
 
 - (uint32_t) compareBySection:(NSArray *)sections;
@@ -1837,7 +1966,7 @@ uint32_t PackageChangesRadix(Package *self, void *) {
         value.bits.ignored = [self ignored] ? 0 : 1;
         value.bits.upgradable = 1;
     } else {
-        value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
+        value.bits.timestamp = [self seen] >> 2;
         value.bits.ignored = 0;
         value.bits.upgradable = 0;
     }
@@ -1845,9 +1974,6 @@ uint32_t PackageChangesRadix(Package *self, void *) {
     return _not(uint32_t) - value.key;
 }
 
-_finline static void Stifle(uint8_t &value) {
-}
-
 uint32_t PackagePrefixRadix(Package *self, void *context) {
     size_t offset(reinterpret_cast<size_t>(context));
     CYString &name([self cyname]);
@@ -1870,8 +1996,6 @@ uint32_t PackagePrefixRadix(Package *self, void *context) {
 
     uint8_t data[4];
 
-    // 0.607997
-
     if (offset == 0 && zeros != 0) {
         memset(data, '0', zeros);
         memcpy(data + zeros, text, 4 - zeros);
@@ -1955,24 +2079,17 @@ struct PackageNameOrdering :
 }
 
 - (void) dealloc {
+    if (parsed_ != NULL)
+        delete parsed_;
+
     if (source_ != nil)
         [source_ release];
 
-    if (latest_ != nil)
-        [latest_ release];
-
-    if (sponsor$_ != nil)
-        [sponsor$_ release];
-    if (author$_ != nil)
-        [author$_ release];
     if (tags_ != nil)
         [tags_ release];
     if (role_ != nil)
         [role_ release];
 
-    if (metadata_ != nil)
-        [metadata_ release];
-
     [super dealloc];
 }
 
@@ -2000,12 +2117,15 @@ struct PackageNameOrdering :
 }
 
 - (void) parse {
-    if (parsed_)
+    if (parsed_ != NULL)
         return;
-    parsed_ = true;
-    if (file_.end())
+@synchronized (database_) {
+    if ([database_ era] != era_ || file_.end())
         return;
 
+    ParsedPackage *parsed(new ParsedPackage);
+    parsed_ = parsed;
+
     _profile(Package$parse)
         pkgRecords::Parser *parser;
 
@@ -2020,14 +2140,14 @@ struct PackageNameOrdering :
                 const char *name_;
                 CYString *value_;
             } names[] = {
-                {"icon", &icon_},
-                {"depiction", &depiction_},
-                {"homepage", &homepage_},
+                {"icon", &parsed->icon_},
+                {"depiction", &parsed->depiction_},
+                {"homepage", &parsed->homepage_},
                 {"website", &website},
-                {"bugs", &bugs_},
-                {"support", &support_},
-                {"sponsor", &sponsor_},
-                {"author", &author_},
+                {"bugs", &parsed->bugs_},
+                {"support", &parsed->support_},
+                {"sponsor", &parsed->sponsor_},
+                {"author", &parsed->author_},
             };
 
             for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
@@ -2050,44 +2170,33 @@ struct PackageNameOrdering :
                     stop = end;
                 while (stop != start && stop[-1] == '\r')
                     --stop;
-                tagline_.set(pool_, start, stop - start);
+                parsed->tagline_.set(pool_, start, stop - start);
             }
         _end
 
         _profile(Package$parse$Retain)
-            if (homepage_.empty())
-                homepage_ = website;
-            if (homepage_ == depiction_)
-                homepage_.clear();
+            if (parsed->homepage_.empty())
+                parsed->homepage_ = website;
+            if (parsed->homepage_ == parsed->depiction_)
+                parsed->homepage_.clear();
         _end
     _end
-}
+} }
 
 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
     if ((self = [super init]) != nil) {
     _profile(Package$initWithVersion)
-        era_ = [database era];
         pool_ = pool;
 
-        version_ = version;
-
-        _profile(Package$initWithVersion$ParentPkg)
-            iterator_ = version.ParentPkg();
-        _end
-
         database_ = database;
+        era_ = [database era];
 
-        _profile(Package$initWithVersion$Latest)
-            const char *latest(StripVersion_(version_.VerStr()));
-            latest_ = (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(latest), strlen(latest), kCFStringEncodingASCII, NO);
-        _end
+        version_ = version;
 
-        pkgCache::VerIterator current;
-        _profile(Package$initWithVersion$Versions)
-            current = iterator_.CurrentVer();
-            if (!current.end())
-                installed_.set(pool_, StripVersion_(current.VerStr()));
+        pkgCache::PkgIterator iterator(version.ParentPkg());
+        iterator_ = iterator;
 
+        _profile(Package$initWithVersion$Version)
             if (!version_.end())
                 file_ = version_.FileList();
             else {
@@ -2096,87 +2205,82 @@ struct PackageNameOrdering :
             }
         _end
 
-        _profile(Package$initWithVersion$Name)
-            id_.set(pool_, iterator_.Name());
-            name_.set(pool, iterator_.Display());
-        _end
+        _profile(Package$initWithVersion$Cache)
+            name_.set(NULL, iterator.Display());
 
-        _profile(Package$initWithVersion$lowercaseString)
-            char *data(id_.data());
-            for (size_t i(0), e(id_.size()); i != e; ++i)
-                // XXX: do not use tolower() as this is not locale-specific? :(
-                data[i] |= 0x20;
+            latest_.set(NULL, StripVersion_(version_.VerStr()));
+
+            pkgCache::VerIterator current(iterator.CurrentVer());
+            if (!current.end())
+                installed_.set(NULL, StripVersion_(current.VerStr()));
         _end
 
         _profile(Package$initWithVersion$Tags)
-            pkgCache::TagIterator tag(iterator_.TagList());
+            pkgCache::TagIterator tag(iterator.TagList());
             if (!tag.end()) {
                 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
                 do {
                     const char *name(tag.Name());
                     [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
+
                     if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
                         role_ = (NSString *) CYStringCreate(name + 6);
+
+                    if (strncmp(name, "cydia::", 7) == 0) {
+                        if (strcmp(name + 7, "essential") == 0)
+                            essential_ = true;
+                        else if (strcmp(name + 7, "obsolete") == 0)
+                            obsolete_ = true;
+                    }
+
                     ++tag;
                 } while (!tag.end());
             }
         _end
 
-        bool changed(false);
-
         _profile(Package$initWithVersion$Metadata)
-            metadata_ = [Packages_ objectForKey:id_];
+            const char *mixed(iterator.Name());
+            size_t size(strlen(mixed));
+            char lower[size + 1];
 
-            if (metadata_ == nil) {
-                firstSeen_ = now_;
+            for (size_t i(0); i != size; ++i)
+                lower[i] = mixed[i] | 0x20;
+            lower[size] = '\0';
 
-                metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
-                    firstSeen_, @"FirstSeen",
-                    latest_, @"LastVersion",
-                nil] mutableCopy];
+            PackageValue *metadata(PackageFind(lower, size));
+            metadata_ = metadata;
 
-                changed = true;
-            } else {
-                firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
-                lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
+            id_.set(NULL, metadata->name_, size);
 
-                if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
-                    subscribed_ = [subscribed boolValue];
+            const char *latest(version_.VerStr());
+            size_t length(strlen(latest));
 
-                NSString *version([metadata_ objectForKey:@"LastVersion"]);
+            uint16_t vhash(hashlittle(latest, length));
 
-                if (firstSeen_ == nil) {
-                    firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
-                    [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
-                    changed = true;
-                }
+            size_t capped(std::min<size_t>(8, length));
+            latest = latest + length - capped;
 
-                if (version == nil) {
-                    [metadata_ setObject:latest_ forKey:@"LastVersion"];
-                    changed = true;
-                } else if (![version isEqualToString:latest_]) {
-                    [metadata_ setObject:latest_ forKey:@"LastVersion"];
-                    lastSeen_ = now_;
-                    [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
-                    changed = true;
-                }
-            }
+            if (metadata->first_ == 0)
+                metadata->first_ = now_;
 
-            metadata_ = [metadata_ retain];
+            if (metadata->last_ == 0)
+                metadata->last_ = metadata->first_;
 
-            if (changed) {
-                [Packages_ setObject:metadata_ forKey:id_];
-                Changed_ = true;
+            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;
             }
         _end
 
         _profile(Package$initWithVersion$Section)
-            section_.set(pool_, iterator_.Section());
+            section_.set(NULL, iterator.Section());
         _end
 
-        _profile(Package$initWithVersion$hasTag)
-            obsolete_ = [self hasTag:@"cydia::obsolete"];
-            essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
+        _profile(Package$initWithVersion$Flags)
+            essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
+            ignored_ = iterator->SelectedState == pkgCache::State::Hold;
         _end
     _end } return self;
 }
@@ -2191,12 +2295,26 @@ struct PackageNameOrdering :
     if (version.end())
         return nil;
 
-    return [[[Package alloc]
-        initWithVersion:version
-        withZone:zone
-        inPool:pool
-        database:database
-    ] autorelease];
+    Package *package;
+
+    _profile(Package$packageWithIterator$Allocate)
+        package = [Package allocWithZone:zone];
+    _end
+
+    _profile(Package$packageWithIterator$Initialize)
+        package = [package
+            initWithVersion:version
+            withZone:zone
+            inPool:pool
+            database:database
+        ];
+    _end
+
+    _profile(Package$packageWithIterator$Autorelease)
+        package = [package autorelease];
+    _end
+
+    return package;
 }
 
 - (pkgCache::PkgIterator) iterator {
@@ -2285,7 +2403,7 @@ struct PackageNameOrdering :
 } }
 
 - (NSString *) shortDescription {
-    return tagline_;
+    return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
 }
 
 - (unichar) index {
@@ -2300,26 +2418,29 @@ struct PackageNameOrdering :
     _end
 }
 
-- (NSMutableDictionary *) metadata {
+- (PackageValue *) metadata {
     return metadata_;
 }
 
-- (NSDate *) seen {
-    if (subscribed_ && lastSeen_ != nil)
-        return lastSeen_;
-    return firstSeen_;
+- (time_t) seen {
+    PackageValue *metadata([self metadata]);
+    return metadata->subscribed_ ? metadata->last_ : metadata->first_;
 }
 
-- (BOOL) subscribed {
-    return subscribed_;
+- (bool) subscribed {
+    return [self metadata]->subscribed_;
 }
 
-- (BOOL) ignored {
-    NSDictionary *metadata([self metadata]);
-    if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
-        return [ignored boolValue];
-    else
+- (bool) setSubscribed:(bool)subscribed {
+    PackageValue *metadata([self metadata]);
+    if (metadata->subscribed_ == subscribed)
         return false;
+    metadata->subscribed_ = subscribed;
+    return true;
+}
+
+- (BOOL) ignored {
+    return ignored_;
 }
 
 - (NSString *) latest {
@@ -2448,10 +2569,11 @@ struct PackageNameOrdering :
     NSString *section = [self simpleSection];
 
     UIImage *icon(nil);
-    if (!icon_.empty())
-        if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
-            // XXX: correct escaping
-            icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
+    if (parsed_ != NULL)
+        if (NSString *href = parsed_->icon_)
+            if ([href hasPrefix:@"file:///"])
+                // XXX: correct escaping
+                icon = [UIImage imageAtPath:[href substringFromIndex:7]];
     if (icon == nil) if (section != nil)
         icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
     if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
@@ -2464,31 +2586,23 @@ struct PackageNameOrdering :
 }
 
 - (NSString *) homepage {
-    return homepage_;
+    return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
 }
 
 - (NSString *) depiction {
-    return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
+    return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
 }
 
 - (Address *) sponsor {
-    if (sponsor$_ == nil) {
-        if (sponsor_.empty())
-            return nil;
-        sponsor$_ = [[Address addressWithString:sponsor_] retain];
-    } return sponsor$_;
+    return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
 }
 
 - (Address *) author {
-    if (author$_ == nil) {
-        if (author_.empty())
-            return nil;
-        author$_ = [[Address addressWithString:author_] retain];
-    } return author$_;
+    return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
 }
 
 - (NSString *) support {
-    return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
+    return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
 }
 
 - (NSArray *) files {
@@ -2670,6 +2784,11 @@ struct PackageNameOrdering :
     return [self hasTag:@"cydia::commercial"];
 }
 
+- (void) setIndex:(size_t)index {
+    if (metadata_->index_ != index)
+        metadata_->index_ = index;
+}
+
 - (CYString &) cyname {
     return name_.empty() ? id_ : name_;
 }
@@ -3032,7 +3151,13 @@ 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);
 
         int fds[2];
 
@@ -3231,15 +3356,12 @@ static NSString *Warning_;
     delete policy_;
     policy_ = NULL;
 
-    if (now_ != nil) {
-        [now_ release];
-        now_ = nil;
-    }
-
     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)
@@ -3272,7 +3394,7 @@ static NSString *Warning_;
 
     unlink("/tmp/cydia.chk");
 
-    now_ = [[NSDate date] retain];
+    now_ = [[NSDate date] timeIntervalSince1970];
 
     policy_ = new pkgDepCache::Policy();
     records_ = new pkgRecords(cache_);
@@ -3358,6 +3480,14 @@ static NSString *Warning_;
         //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
 
         _trace();
+
+        size_t count(CFArrayGetCount(packages_));
+        MetaFile_->active_ = count;
+
+        for (size_t index(0); index != count; ++index)
+            [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
+
+        _trace();
     }
 } } CYPoolEnd() _trace(); }
 
@@ -3678,7 +3808,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (NSArray *) getInstalledPackages {
     NSArray *packages([[Database sharedInstance] packages]);
-    NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
+    NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
     for (Package *package in packages)
         if ([package installed] != nil)
             [installed addObject:package];
@@ -4879,14 +5009,14 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) onSwitch:(id)sender {
-    NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
+    NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
     if (metadata == nil) {
         metadata = [NSMutableDictionary dictionaryWithCapacity:2];
         [Sections_ setObject:metadata forKey:basic_];
     }
 
-    Changed_ = true;
     [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
+    Changed_ = true;
 }
 
 - (void) setSection:(Section *)section editing:(BOOL)editing {
@@ -5284,6 +5414,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     UITableViewDelegate
 > {
     _transient Database *database_;
+    unsigned era_;
     NSMutableArray *packages_;
     NSMutableArray *sections_;
     UITableView *list_;
@@ -5341,11 +5472,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"]);
@@ -5410,6 +5545,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) reloadData {
+    era_ = [database_ era];
     NSArray *packages = [database_ packages];
 
     [packages_ removeAllObjects];
@@ -6490,10 +6626,25 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 @class CYNavigationController;
 
 /* Cydia Tab Bar Controller {{{ */
-@interface CYTabBarController : UITabBarController {
+@interface CYTabBarController : UITabBarController <
+    ProgressDelegate
+> {
     _transient Database *database_;
+    RefreshBar *refreshbar_;
+
+    bool dropped_;
+    bool updating_;
+    // XXX: ok, "updatedelegate_"?...
+    _transient NSObject<CydiaDelegate> *updatedelegate_;
+
+    id root_;
 }
 
+- (void) dropBar:(BOOL)animated;
+- (void) beginUpdate;
+- (void) raiseBar:(BOOL)animated;
+- (BOOL) updating;
+
 @end
 
 @implementation CYTabBarController
@@ -6512,60 +6663,284 @@ freeing the view controllers on tab change */
 - (id) initWithDatabase:(Database *)database {
     if ((self = [super init]) != nil) {
         database_ = database;
+
+        [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
+        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
+
+        refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
     } return self;
 }
 
-@end
-/* }}} */
+- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
+    return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
+}
 
-/* Cydia Navigation Controller {{{ */
-@interface CYNavigationController : UINavigationController {
-    _transient Database *database_;
-    _transient id<UINavigationControllerDelegate> delegate_;
+- (void) setUpdate:(NSDate *)date {
+    [self beginUpdate];
 }
 
-- (id) initWithDatabase:(Database *)database;
-- (void) reloadData;
+- (void) beginUpdate {
+    [self dropBar:YES];
+    [refreshbar_ start];
 
-@end
+    updating_ = true;
 
+    [NSThread
+        detachNewThreadSelector:@selector(performUpdate)
+        toTarget:self
+        withObject:nil
+    ];
+}
 
-@implementation CYNavigationController
+- (void) performUpdate { _pooled
+    Status status;
+    status.setDelegate(self);
+    [database_ updateWithStatus:status];
 
-- (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];
-    }
+    [self
+        performSelectorOnMainThread:@selector(completeUpdate)
+        withObject:nil
+        waitUntilDone:NO
+    ];
 }
 
-- (void) dealloc {
-    [super dealloc];
+- (void) completeUpdate {
+    if (!updating_)
+        return;
+    updating_ = false;
+
+    [self raiseBar:YES];
+    [refreshbar_ stop];
+    [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
 }
 
-- (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) cancelUpdate {
+    updating_ = false;
+    [self raiseBar:YES];
+    [refreshbar_ stop];
+    [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
 }
 
-- (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
-    delegate_ = delegate;
+- (void) cancelPressed {
+    [self cancelUpdate];
 }
 
-- (id) initWithDatabase:(Database *)database {
-    if ((self = [super init]) != nil) {
-        database_ = database;
-    } return self;
+- (BOOL) updating {
+    return updating_;
 }
 
-@end
-/* }}} */
-/* Cydia:// Protocol {{{ */
+- (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
+    [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
+}
+
+- (void) startProgress {
+}
+
+- (void) setProgressTitle:(NSString *)title {
+    [self
+        performSelectorOnMainThread:@selector(_setProgressTitle:)
+        withObject:title
+        waitUntilDone:YES
+    ];
+}
+
+- (bool) isCancelling:(size_t)received {
+    return !updating_;
+}
+
+- (void) setProgressPercent:(float)percent {
+    [self
+        performSelectorOnMainThread:@selector(_setProgressPercent:)
+        withObject:[NSNumber numberWithFloat:percent]
+        waitUntilDone:YES
+    ];
+}
+
+- (void) addProgressOutput:(NSString *)output {
+    [self
+        performSelectorOnMainThread:@selector(_addProgressOutput:)
+        withObject:output
+        waitUntilDone:YES
+    ];
+}
+
+- (void) _setProgressTitle:(NSString *)title {
+    [refreshbar_ setPrompt:title];
+}
+
+- (void) _setProgressPercent:(NSNumber *)percent {
+    [refreshbar_ setProgress:[percent floatValue]];
+}
+
+- (void) _addProgressOutput:(NSString *)output {
+}
+
+- (void) setUpdateDelegate:(id)delegate {
+    updatedelegate_ = delegate;
+}
+
+- (CGFloat) statusBarHeight {
+    if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
+        return [[UIApplication sharedApplication] statusBarFrame].size.height;
+    } else {
+        return [[UIApplication sharedApplication] statusBarFrame].size.width;
+    }
+}
+
+- (UIView *) transitionView {
+    if ([self respondsToSelector:@selector(_transitionView)])
+        return [self _transitionView];
+    else
+        return MSHookIvar<id>(self, "_viewControllerTransitionView");
+}
+
+- (void) dropBar:(BOOL)animated {
+    if (dropped_)
+        return;
+    dropped_ = true;
+
+    UIView *transition([self transitionView]);
+    [[self view] addSubview:refreshbar_];
+
+    CGRect barframe([refreshbar_ frame]);
+
+    if (false) // XXX: _UIApplicationLinkedOnOrAfter(4)
+        barframe.origin.y = [self statusBarHeight];
+    else
+        barframe.origin.y = 0;
+
+    [refreshbar_ setFrame:barframe];
+
+    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];
+
+    // 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];
+}
+
+- (void) raiseBar:(BOOL)animated {
+    if (!dropped_)
+        return;
+    dropped_ = false;
+
+    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 0
+- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
+    // XXX: fix Apple's layout bug
+    // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
+}
+#endif
+
+- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
+    bool dropped(dropped_);
+
+    if (dropped)
+        [self raiseBar:NO];
+
+    [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
+
+    if (dropped)
+        [self dropBar:NO];
+
+    // XXX: fix Apple's layout bug
+    // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
+}
+
+- (void) statusBarFrameChanged:(NSNotification *)notification {
+    if (dropped_) {
+        [self raiseBar:NO];
+        [self dropBar:NO];
+    }
+}
+
+- (void) dealloc {
+    [refreshbar_ release];
+    [[NSNotificationCenter defaultCenter] removeObserver:self];
+    [super dealloc];
+}
+
+@end
+/* }}} */
+
+/* Cydia Navigation Controller {{{ */
+@interface CYNavigationController : UINavigationController {
+    _transient Database *database_;
+    _transient id<UINavigationControllerDelegate> delegate_;
+}
+
+- (id) initWithDatabase:(Database *)database;
+- (void) reloadData;
+
+@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];
+    }
+}
+
+- (void) dealloc {
+    [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<UINavigationControllerDelegate>)delegate {
+    delegate_ = delegate;
+}
+
+- (id) initWithDatabase:(Database *)database {
+    if ((self = [super init]) != nil) {
+        database_ = database;
+    } return self;
+}
+
+@end
+/* }}} */
+/* Cydia:// Protocol {{{ */
 @interface CydiaURLProtocol : NSURLProtocol {
 }
 
@@ -6876,6 +7251,7 @@ freeing the view controllers on tab change */
     UITableViewDelegate
 > {
     _transient Database *database_;
+    unsigned era_;
     CFMutableArrayRef packages_;
     NSMutableArray *sections_;
     UITableView *list_;
@@ -6933,10 +7309,14 @@ freeing the view controllers on tab change */
 }
 
 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
+@synchronized (database_) {
+    if ([database_ era] != era_)
+        return nil;
+
     Section *section([sections_ objectAtIndex:[path section]]);
     NSInteger row([path row]);
-    return [self packageAtIndex:([section row] + row)];
-}
+    return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
+} }
 
 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
     PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
@@ -7003,6 +7383,7 @@ freeing the view controllers on tab change */
 }
 
 - (void) reloadData {
+    era_ = [database_ era];
     NSArray *packages = [database_ packages];
 
     CFArrayRemoveAllValues(packages_);
@@ -7020,9 +7401,9 @@ freeing the view controllers on tab change */
 #endif
 
     Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
-    Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
+    Section *ignored = nil;
     Section *section = nil;
-    NSDate *last = nil;
+    time_t last = 0;
 
     upgrades_ = 0;
     bool unseens = false;
@@ -7036,22 +7417,14 @@ freeing the view controllers on tab change */
 
         if (!uae) {
             unseens = true;
-            NSDate *seen;
-
-            _profile(ChangesController$reloadData$Remember)
-                seen = [package seen];
-            _end
+            time_t seen([package seen]);
 
-            if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
+            if (section == nil || last != seen) {
                 last = seen;
 
                 NSString *name;
-                if (seen == nil)
-                    name = UCLocalize("UNKNOWN");
-                else {
-                    name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
-                    [name autorelease];
-                }
+                name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
+                [name autorelease];
 
                 _profile(ChangesController$reloadData$Allocate)
                     name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
@@ -7061,9 +7434,12 @@ freeing the view controllers on tab change */
             }
 
             [section addToCount];
-        } else if ([package ignored])
+        } else if ([package ignored]) {
+            if (ignored == nil) {
+                ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
+            }
             [ignored addToCount];
-        else {
+        else {
             ++upgrades_;
             [upgradable addToCount];
         }
@@ -7147,7 +7523,13 @@ freeing the view controllers on tab change */
         search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
         [search_ layoutSubviews];
         [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
-        UITextField *textField = [search_ searchField];
+
+        UITextField *textField;
+        if ([search_ respondsToSelector:@selector(searchField)])
+            textField = [search_ searchField];
+        else
+            textField = MSHookIvar<UITextField *>(search_, "_searchField");
+
         [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
         [search_ setDelegate:self];
         [textField setEnablesReturnKeyAutomatically:NO];
@@ -7218,38 +7600,23 @@ freeing the view controllers on tab change */
     if (package_ == nil)
         return 0;
 
-    return 1;
+    return 2;
 }
 
 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
     return UCLocalize("SHOW_ALL_CHANGES_EX");
 }
 
-- (void) onSomething:(BOOL)value withKey:(NSString *)key {
+- (void) onSubscribed:(id)control {
+    bool value([control isOn]);
     if (package_ == nil)
         return;
-
-    NSMutableDictionary *metadata([package_ metadata]);
-
-    BOOL before;
-    if (NSNumber *number = [metadata objectForKey:key])
-        before = [number boolValue];
-    else
-        before = NO;
-
-    if (value != before) {
-        [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
-        Changed_ = true;
+    if ([package_ setSubscribed:value])
         [delegate_ updateData];
-    }
-}
-
-- (void) onSubscribed:(id)control {
-    [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
 }
 
 - (void) onIgnored:(id)control {
-    [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
+    // TODO: set Held state - possibly call out to dpkg, etc.
 }
 
 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
@@ -7458,7 +7825,6 @@ freeing the view controllers on tab change */
         nil];
 
         [Metadata_ setObject:Settings_ forKey:@"Settings"];
-
         Changed_ = true;
 
         if (rolling)
@@ -7594,273 +7960,6 @@ freeing the view controllers on tab change */
 @end
 /* }}} */
 
-/* Cydia Container {{{ */
-@interface CYContainer : UIViewController <ProgressDelegate> {
-    _transient Database *database_;
-    RefreshBar *refreshbar_;
-
-    bool dropped_;
-    bool updating_;
-    // XXX: ok, "updatedelegate_"?...
-    _transient NSObject<CydiaDelegate> *updatedelegate_;
-    // XXX: can't we query for this variable when we need it?
-    _transient UITabBarController *root_;
-}
-
-- (void) setTabBarController:(UITabBarController *)controller;
-
-- (void) dropBar:(BOOL)animated;
-- (void) beginUpdate;
-- (void) raiseBar:(BOOL)animated;
-- (BOOL) updating;
-
-@end
-
-@implementation CYContainer
-
-- (BOOL) _reallyWantsFullScreenLayout {
-    return YES;
-}
-
-// NOTE: UIWindow only sends the top controller these messages,
-//       So we have to forward them on.
-
-- (void) viewDidAppear:(BOOL)animated {
-    [super viewDidAppear:animated];
-    [root_ viewDidAppear:animated];
-}
-
-- (void) viewWillAppear:(BOOL)animated {
-    [super viewWillAppear:animated];
-    [root_ viewWillAppear:animated];
-}
-
-- (void) viewDidDisappear:(BOOL)animated {
-    [super viewDidDisappear:animated];
-    [root_ viewDidDisappear:animated];
-}
-
-- (void) viewWillDisappear:(BOOL)animated {
-    [super viewWillDisappear:animated];
-    [root_ viewWillDisappear:animated];
-}
-
-- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
-    return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
-}
-
-- (void) setTabBarController:(UITabBarController *)controller {
-    root_ = controller;
-    [[self view] addSubview:[root_ view]];
-}
-
-- (void) setUpdate:(NSDate *)date {
-    [self beginUpdate];
-}
-
-- (void) beginUpdate {
-    [self dropBar:YES];
-    [refreshbar_ start];
-
-    updating_ = true;
-
-    [NSThread
-        detachNewThreadSelector:@selector(performUpdate)
-        toTarget:self
-        withObject:nil
-    ];
-}
-
-- (void) performUpdate { _pooled
-    Status status;
-    status.setDelegate(self);
-    [database_ updateWithStatus:status];
-
-    [self
-        performSelectorOnMainThread:@selector(completeUpdate)
-        withObject:nil
-        waitUntilDone:NO
-    ];
-}
-
-- (void) completeUpdate {
-    if (!updating_)
-        return;
-    updating_ = false;
-
-    [self raiseBar:YES];
-    [refreshbar_ stop];
-    [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
-}
-
-- (void) cancelUpdate {
-    updating_ = false;
-    [self raiseBar:YES];
-    [refreshbar_ stop];
-    [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
-}
-
-- (void) cancelPressed {
-    [self cancelUpdate];
-}
-
-- (BOOL) updating {
-    return updating_;
-}
-
-- (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
-    [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
-}
-
-- (void) startProgress {
-}
-
-- (void) setProgressTitle:(NSString *)title {
-    [self
-        performSelectorOnMainThread:@selector(_setProgressTitle:)
-        withObject:title
-        waitUntilDone:YES
-    ];
-}
-
-- (bool) isCancelling:(size_t)received {
-    return !updating_;
-}
-
-- (void) setProgressPercent:(float)percent {
-    [self
-        performSelectorOnMainThread:@selector(_setProgressPercent:)
-        withObject:[NSNumber numberWithFloat:percent]
-        waitUntilDone:YES
-    ];
-}
-
-- (void) addProgressOutput:(NSString *)output {
-    [self
-        performSelectorOnMainThread:@selector(_addProgressOutput:)
-        withObject:output
-        waitUntilDone:YES
-    ];
-}
-
-- (void) _setProgressTitle:(NSString *)title {
-    [refreshbar_ setPrompt:title];
-}
-
-- (void) _setProgressPercent:(NSNumber *)percent {
-    [refreshbar_ setProgress:[percent floatValue]];
-}
-
-- (void) _addProgressOutput:(NSString *)output {
-}
-
-- (void) setUpdateDelegate:(id)delegate {
-    updatedelegate_ = delegate;
-}
-
-- (CGFloat) statusBarHeight {
-    if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
-        return [[UIApplication sharedApplication] statusBarFrame].size.height;
-    } else {
-        return [[UIApplication sharedApplication] statusBarFrame].size.width;
-    }
-}
-
-- (void) dropBar:(BOOL)animated {
-    if (dropped_)
-        return;
-    dropped_ = true;
-
-    [[self view] addSubview:refreshbar_];
-
-    CGFloat sboffset = [self statusBarHeight];
-
-    CGRect barframe = [refreshbar_ frame];
-    barframe.origin.y = sboffset;
-    [refreshbar_ setFrame:barframe];
-
-    if (animated)
-        [UIView beginAnimations:nil context:NULL];
-    CGRect viewframe = [[root_ view] frame];
-    viewframe.origin.y += barframe.size.height + sboffset;
-    viewframe.size.height -= barframe.size.height + sboffset;
-    [[root_ view] setFrame:viewframe];
-    if (animated)
-        [UIView commitAnimations];
-
-    // 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];
-}
-
-- (void) raiseBar:(BOOL)animated {
-    if (!dropped_)
-        return;
-    dropped_ = false;
-
-    [refreshbar_ removeFromSuperview];
-
-    CGFloat sboffset = [self statusBarHeight];
-
-    if (animated)
-        [UIView beginAnimations:nil context:NULL];
-    CGRect barframe = [refreshbar_ frame];
-    CGRect viewframe = [[root_ view] frame];
-    viewframe.origin.y -= barframe.size.height + sboffset;
-    viewframe.size.height += barframe.size.height + sboffset;
-    [[root_ view] setFrame:viewframe];
-    if (animated)
-        [UIView commitAnimations];
-
-    // XXX: fix Apple's layout bug
-    [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
-}
-
-- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
-    // XXX: fix Apple's layout bug
-    [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
-}
-
-- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
-    if (dropped_) {
-        [self raiseBar:NO];
-        [self dropBar:NO];
-    }
-
-    // XXX: fix Apple's layout bug
-    [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
-}
-
-- (void) statusBarFrameChanged:(NSNotification *)notification {
-    if (dropped_) {
-        [self raiseBar:NO];
-        [self dropBar:NO];
-    }
-}
-
-- (void) dealloc {
-    [refreshbar_ release];
-    [[NSNotificationCenter defaultCenter] removeObserver:self];
-    [super dealloc];
-}
-
-- (id) initWithDatabase:(Database *)database {
-    if ((self = [super init]) != nil) {
-        database_ = database;
-
-        [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
-        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
-
-        refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
-    } return self;
-}
-
-@end
-/* }}} */
-
 typedef enum {
     kCydiaTag = 0,
     kSectionsTag = 1,
@@ -7881,7 +7980,6 @@ typedef enum {
     // XXX: evaluate all fields for _transient
 
     UIWindow *window_;
-    CYContainer *container_;
     CYTabBarController *tabbar_;
 
     NSMutableArray *essential_;
@@ -7890,9 +7988,8 @@ typedef enum {
     Database *database_;
 
     int tag_;
-
-    UIKeyboard *keyboard_;
-    int huds_;
+    unsigned locked_;
+    NSURL *starturl_;
 
     SectionsController *sections_;
     ChangesController *changes_;
@@ -7911,6 +8008,9 @@ typedef enum {
 - (void) setPage:(CYViewController *)page;
 - (void) loadData;
 
+// XXX: I hate prototypes
+- (id) queueBadgeController;
+
 @end
 
 static _finline void _setHomePage(Cydia *self) {
@@ -7920,11 +8020,11 @@ static _finline void _setHomePage(Cydia *self) {
 @implementation Cydia
 
 - (void) beginUpdate {
-    [container_ beginUpdate];
+    [tabbar_ beginUpdate];
 }
 
 - (BOOL) updating {
-    return [container_ updating];
+    return [tabbar_ updating];
 }
 
 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
@@ -7962,21 +8062,24 @@ static _finline void _setHomePage(Cydia *self) {
 }
 
 - (void) _saveConfig {
+    _trace();
+    MetaFile_.Sync();
+    _trace();
+
     if (Changed_) {
-        _trace();
         NSString *error(nil);
+
         if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
             _trace();
             NSError *error(nil);
             if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
                 NSLog(@"failure to save metadata data: %@", error);
             _trace();
+
+            Changed_ = false;
         } else {
             NSLog(@"failure to serialize metadata: %@", error);
-            return;
         }
-
-        Changed_ = false;
     }
 }
 
@@ -7992,6 +8095,9 @@ static _finline void _setHomePage(Cydia *self) {
         [search_ reloadData];
 
     [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
+
+    [queueDelegate_ queueStatusDidChange];
+    [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
 }
 
 - (int)indexOfTabWithTag:(int)tag {
@@ -8052,7 +8158,7 @@ static _finline void _setHomePage(Cydia *self) {
 
     // If we can reach the server, auto-refresh!
     if (reachable)
-        [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
+        [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
 
     [pool release];
 }
@@ -8141,7 +8247,7 @@ static _finline void _setHomePage(Cydia *self) {
     CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
     if (IsWildcat_)
         [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
-    [container_ presentModalViewController:navigation animated:YES];
+    [tabbar_ presentModalViewController:navigation animated:YES];
 
     [progress
         detachNewThreadSelector:@selector(update_)
@@ -8180,7 +8286,7 @@ static _finline void _setHomePage(Cydia *self) {
 
     if (IsWildcat_)
         [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
-    [container_ presentModalViewController:confirm_ animated:YES];
+    [tabbar_ presentModalViewController:confirm_ animated:YES];
 
     return true;
 }
@@ -8239,6 +8345,8 @@ static _finline void _setHomePage(Cydia *self) {
 }
 
 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
+    Queuing_ = false;
+
     ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
 
     if (navigation != nil) {
@@ -8247,7 +8355,7 @@ static _finline void _setHomePage(Cydia *self) {
         navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
         if (IsWildcat_)
             [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
-        [container_ presentModalViewController:navigation animated:YES];
+        [tabbar_ presentModalViewController:navigation animated:YES];
     }
 
     [progress
@@ -8256,9 +8364,12 @@ static _finline void _setHomePage(Cydia *self) {
         withObject:nil
         title:UCLocalize("RUNNING")
     ];
+
+    ++locked_;
 }
 
 - (void) progressControllerIsComplete:(ProgressController *)progress {
+    --locked_;
     [self complete];
 }
 
@@ -8353,7 +8464,7 @@ static _finline void _setHomePage(Cydia *self) {
     CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
     if (IsWildcat_)
         [nav setModalPresentationStyle:UIModalPresentationFormSheet];
-    [container_ presentModalViewController:nav animated:YES];
+    [tabbar_ presentModalViewController:nav animated:YES];
 }
 
 - (void) setPackageController:(PackageController *)view {
@@ -8383,18 +8494,12 @@ static _finline void _setHomePage(Cydia *self) {
     @synchronized (self) {
         if (clear) {
             [database_ clear];
-
-            // Stop queuing.
             Queuing_ = false;
-            [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
         } else {
-            // Start queuing.
             Queuing_ = true;
-            [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
         }
 
         [self _updateData];
-        [queueDelegate_ queueStatusDidChange];
     }
 }
 
@@ -8451,13 +8556,10 @@ static _finline void _setHomePage(Cydia *self) {
     [super applicationWillSuspend];
 }
 
-- (BOOL) hudIsShowing {
-    return (huds_ > 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", &notify_token) == NOTIFY_STATUS_OK) {
@@ -8465,17 +8567,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];
 }
 
@@ -8486,11 +8592,11 @@ static _finline void _setHomePage(Cydia *self) {
     [window_ setUserInteractionEnabled:NO];
     [hud show:YES];
 
-    UIViewController *target = container_;
+    UIViewController *target = tabbar_;
     while ([target modalViewController] != nil) target = [target modalViewController];
     [[target view] addSubview:hud];
 
-    huds_++;
+    ++locked_;
     return hud;
 }
 
@@ -8498,7 +8604,7 @@ static _finline void _setHomePage(Cydia *self) {
     [hud show:NO];
     [hud removeFromSuperview];
     [window_ setUserInteractionEnabled:YES];
-    huds_--;
+    --locked_;
 }
 
 - (CYViewController *) pageForPackage:(NSString *)name {
@@ -8562,26 +8668,39 @@ static _finline void _setHomePage(Cydia *self) {
     return nil;
 }
 
-- (void) applicationOpenURL:(NSURL *)url {
-    [super applicationOpenURL:url];
-    int tag;
-    if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
+- (BOOL) openCydiaURL:(NSURL *)url {
+    CYViewController *page = nil;
+    int tag = 0;
+
+    NSLog(@"open url: %@", url);
+
+    if ((page = [self pageForURL:url hasTag:&tag])) {
         [self setPage:page];
         tag_ = tag;
         [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
     }
+
+    return !!page;
+}
+
+- (void) applicationOpenURL:(NSURL *)url {
+    [super applicationOpenURL:url];
+    NSLog(@"first: %@", url);
+    if (!loaded_) starturl_ = [url retain];
+    else [self openCydiaURL:url];
 }
 
 - (void) applicationWillResignActive:(UIApplication *)application {
     // Stop refreshing if you get a phone call or lock the device.
-    if ([container_ updating])
-        [container_ cancelUpdate];
+    if ([tabbar_ updating])
+        [tabbar_ cancelUpdate];
 
     if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
         [super applicationWillResignActive:application];
 }
 
 - (void) addStashController {
+    ++locked_;
     stash_ = [[CYStashController alloc] init];
     [window_ addSubview:[stash_ view]];
 }
@@ -8589,6 +8708,7 @@ static _finline void _setHomePage(Cydia *self) {
 - (void) removeStashController {
     [[stash_ view] removeFromSuperview];
     [stash_ release];
+    --locked_;
 }
 
 - (void) stash {
@@ -8641,6 +8761,13 @@ static _finline void _setHomePage(Cydia *self) {
 }
 
 - (void) applicationDidFinishLaunching:(id)unused {
+_trace();
+    [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]];
@@ -8686,14 +8813,11 @@ static _finline void _setHomePage(Cydia *self) {
     database_ = [Database sharedInstance];
 
     [self setupTabBarController];
-
-    container_ = [[CYContainer alloc] initWithDatabase:database_];
-    [container_ setUpdateDelegate:self];
-    [container_ setTabBarController:tabbar_];
-    [window_ addSubview:[container_ view]];
+    [tabbar_ setUpdateDelegate:self];
+    [window_ addSubview:[tabbar_ view]];
 
     // Show pinstripes while loading data.
-    [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
+    [[tabbar_ view] setBackgroundColor:[UIColor pinStripeColor]];
 
     [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
 _trace();
@@ -8745,18 +8869,24 @@ _trace();
     [container setFrame:containrect];
     [spinner setFrame:spinrect];
     [label setFrame:textrect];
-    [[container_ view] addSubview:container];
+    [[tabbar_ view] addSubview:container];
 
     [self reloadData];
     PrintTimes();
 
-    // Show the home page
-    [tabbar_ setSelectedIndex:0];
-    _setHomePage(self);
+    // Show the initial page
+    if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
+        [tabbar_ setSelectedIndex:0];
+        _setHomePage(self);
+    }
+
+    [starturl_ release];
+    starturl_ = nil;
+
     [window_ setUserInteractionEnabled:YES];
 
     // XXX: does this actually slow anything down?
-    [[container_ view] setBackgroundColor:[UIColor clearColor]];
+    [[tabbar_ view] setBackgroundColor:[UIColor clearColor]];
     [container removeFromSuperview];
 }
 
@@ -8997,11 +9127,6 @@ int main(int argc, char *argv[]) { _pooled
     if (Settings_ != nil)
         Role_ = [Settings_ objectForKey:@"Role"];
 
-    if (Packages_ == nil) {
-        Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
-        [Metadata_ setObject:Packages_ forKey:@"Packages"];
-    }
-
     if (Sections_ == nil) {
         Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
         [Metadata_ setObject:Sections_ forKey:@"Sections"];
@@ -9013,6 +9138,18 @@ int main(int argc, char *argv[]) { _pooled
     }
     /* }}} */
 
+    _trace();
+    MetaFile_.Open("/var/lib/cydia/metadata.cb0");
+    _trace();
+
+    if (Packages_ != nil) {
+        CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
+        _trace();
+        [Metadata_ removeObjectForKey:@"Packages"];
+        Packages_ = nil;
+        Changed_ = true;
+    }
+
     Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
 
     if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)