]> git.saurik.com Git - cydia.git/blobdiff - MobileCydia.mm
Instead of using sbdidlaunch, let's just spin on gssc.
[cydia.git] / MobileCydia.mm
index dd645d9fdc41ef8d088c548fcdc11c56cd6ba9d8..7f05319193ea06cb4d7c989b294fdd73d55807d4 100644 (file)
@@ -118,8 +118,6 @@ extern "C" {
 #include <errno.h>
 #include <pcre.h>
 
-#include <ext/hash_map>
-
 #include "UICaboodle/BrowserView.h"
 
 #include "substrate.h"
@@ -197,6 +195,13 @@ void PrintTimes() {
 
 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
 
+#define CYPoolStart() \
+    NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
+    do
+#define CYPoolEnd() \
+    while (false); \
+    [_pool release];
+
 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
 
 void NSLogPoint(const char *fix, const CGPoint &point) {
@@ -377,7 +382,7 @@ static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive |
 
 #define ForRelease 1
 #define TraceLogging (1 && !ForRelease)
-#define HistogramInsertionSort (0 && !ForRelease)
+#define HistogramInsertionSort (!ForRelease ? 0 : 0)
 #define ProfileTimes (0 && !ForRelease)
 #define ForSaurik (0 && !ForRelease)
 #define LogBrowser (0 && !ForRelease)
@@ -404,7 +409,6 @@ static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive |
 typedef uint32_t (*SKRadixFunction)(id, void *);
 
 @interface NSMutableArray (Radix)
-- (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
 @end
 
@@ -413,7 +417,20 @@ struct RadixItem_ {
     uint32_t key;
 };
 
-static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
+@implementation NSMutableArray (Radix)
+
+- (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
+    size_t count([self count]);
+    struct RadixItem_ *swap(new RadixItem_[count * 2]);
+
+    for (size_t i(0); i != count; ++i) {
+        RadixItem_ &item(swap[i]);
+        item.index = i;
+
+        id object([self objectAtIndex:i]);
+        item.key = function(object, argument);
+    }
+
     struct RadixItem_ *lhs(swap), *rhs(swap + count);
 
     static const size_t width = 32;
@@ -454,68 +471,15 @@ static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *sw
 
     delete [] hist;
 
-    NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
+    const void **values(new const void *[count]);
     for (size_t i(0); i != count; ++i)
-        [values addObject:[self objectAtIndex:lhs[i].index]];
-    [self setArray:values];
+        values[i] = [self objectAtIndex:lhs[i].index];
+    CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
+    delete [] values;
 
     delete [] swap;
 }
 
-@implementation NSMutableArray (Radix)
-
-- (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
-    size_t count([self count]);
-    if (count == 0)
-        return;
-
-#if 0
-    NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
-    [invocation setSelector:selector];
-    [invocation setArgument:&object atIndex:2];
-#else
-    /* XXX: this is an unsafe optimization of doomy hell */
-    Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
-    _assert(method != NULL);
-    uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
-    _assert(imp != NULL);
-#endif
-
-    struct RadixItem_ *swap(new RadixItem_[count * 2]);
-
-    for (size_t i(0); i != count; ++i) {
-        RadixItem_ &item(swap[i]);
-        item.index = i;
-
-        id object([self objectAtIndex:i]);
-
-#if 0
-        [invocation setTarget:object];
-        [invocation invoke];
-        [invocation getReturnValue:&item.key];
-#else
-        item.key = imp(object, selector, object);
-#endif
-    }
-
-    RadixSort_(self, count, swap);
-}
-
-- (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
-    size_t count([self count]);
-    struct RadixItem_ *swap(new RadixItem_[count * 2]);
-
-    for (size_t i(0); i != count; ++i) {
-        RadixItem_ &item(swap[i]);
-        item.index = i;
-
-        id object([self objectAtIndex:i]);
-        item.key = function(object, argument);
-    }
-
-    RadixSort_(self, count, swap);
-}
-
 @end
 /* }}} */
 /* Insertion Sort {{{ */
@@ -552,7 +516,7 @@ void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFCompar
     const void **values(new const void *[range.length]);
     CFArrayGetValues(array, range, values);
 
-#if HistogramInsertionSort
+#if HistogramInsertionSort > 0
     uint32_t total(0), *offsets(new uint32_t[range.length]);
 #endif
 
@@ -560,9 +524,13 @@ void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFCompar
         const void *value(values[index]);
         //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
         CFIndex correct(index);
-        while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
+        while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
+#if HistogramInsertionSort > 1
+            NSLog(@"%@ < %@", value, values[correct - 1]);
+#endif
             if (--correct == 0)
                 break;
+        }
         if (correct != index) {
             size_t offset(index - correct);
 #if HistogramInsertionSort
@@ -579,7 +547,7 @@ void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFCompar
     CFArrayReplaceValues(array, range, values, range.length);
     delete [] values;
 
-#if HistogramInsertionSort
+#if HistogramInsertionSort > 0
     for (CFIndex index(0); index != range.length; ++index)
         if (offsets[index] != 0)
             NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
@@ -725,6 +693,16 @@ NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *s
 /* }}} */
 
 /* C++ NSString Wrapper Cache {{{ */
+static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
+    return size == 0 ? NULL :
+        CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
+        CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
+}
+
+static _finline CFStringRef CYStringCreate(const char *data) {
+    return CYStringCreate(data, strlen(data));
+}
+
 class CYString {
   private:
     char *data_;
@@ -803,14 +781,10 @@ class CYString {
         return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
     }
 
-    operator CFStringRef() {
-        if (cache_ == NULL) {
-            if (size_ == 0)
-                return nil;
-            cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
-            if (cache_ == NULL)
-                cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
-        } return cache_;
+    _finline operator CFStringRef() {
+        if (cache_ == NULL)
+            cache_ = CYStringCreate(data_, size_);
+        return cache_;
     }
 
     _finline operator id() {
@@ -977,6 +951,11 @@ class CYColor {
   private:
     CGColorRef color_;
 
+    static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
+        CGFloat color[] = {red, green, blue, alpha};
+        return CGColorCreate(space, color);
+    }
+
   public:
     CYColor() :
         color_(NULL)
@@ -984,7 +963,7 @@ class CYColor {
     }
 
     CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
-        color_(NULL)
+        color_(Create_(space, red, green, blue, alpha))
     {
         Set(space, red, green, blue, alpha);
     }
@@ -1000,8 +979,7 @@ class CYColor {
 
     void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
         Clear();
-        float color[] = {red, green, blue, alpha};
-        color_ = CGColorCreate(space, (CGFloat *) color);
+        color_ = Create_(space, red, green, blue, alpha);
     }
 
     operator CGColorRef() {
@@ -1055,6 +1033,7 @@ static NSString *SerialNumber_ = nil;
 static NSString *ChipID_ = nil;
 static NSString *Token_ = nil;
 static NSString *UniqueID_ = nil;
+static NSString *PLMN_ = nil;
 static NSString *Build_ = nil;
 static NSString *Product_ = nil;
 static NSString *Safari_ = nil;
@@ -1098,26 +1077,13 @@ NSString *SizeString(double size) {
     return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
 }
 
-static _finline CFStringRef CFCString(const char *value) {
-    return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
-}
-
-const char *StripVersion_(const char *version) {
+static _finline const char *StripVersion_(const char *version) {
     const char *colon(strchr(version, ':'));
     if (colon != NULL)
         version = colon + 1;
     return version;
 }
 
-CFStringRef StripVersion(const char *version) {
-    const char *colon(strchr(version, ':'));
-    if (colon != NULL)
-        version = colon + 1;
-    return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
-    // XXX: performance
-    return CFCString(version);
-}
-
 NSString *LocalizeSection(NSString *section) {
     static Pcre title_r("^(.*?) \\((.*)\\)$");
     if (title_r(section)) {
@@ -1212,6 +1178,7 @@ bool isSectionVisible(NSString *section) {
 - (void) syncData;
 - (void) showSettings;
 - (UIProgressHUD *) addProgressHUD;
+- (BOOL) hudIsShowing;
 - (void) removeProgressHUD:(UIProgressHUD *)hud;
 - (CYViewController *) pageForPackage:(NSString *)name;
 - (PackageController *) packageController;
@@ -1359,7 +1326,7 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
     pkgSourceList *list_;
 
     SourceMap sources_;
-    NSMutableArray *packages_;
+    CFMutableArrayRef packages_;
 
     _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
     Status status_;
@@ -1397,8 +1364,6 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 - (bool) upgrade;
 - (void) update;
 
-- (void) setVisible;
-
 - (void) updateWithStatus:(Status &)status;
 
 - (void) setDelegate:(id)delegate;
@@ -1521,6 +1486,7 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 }
 
 - (void) dealloc {
+    // XXX: this is a very inefficient way to call these deconstructors
     [self _clear];
     [super dealloc];
 }
@@ -1737,14 +1703,11 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
     pkgCache::VerFileIterator file_;
 
     Source *source_;
-    bool cached_;
     bool parsed_;
 
     CYString section_;
-    NSString *section$_;
+    _transient NSString *section$_;
     bool essential_;
-    bool required_;
-    bool visible_;
     bool obsolete_;
 
     NSString *latest_;
@@ -1768,8 +1731,6 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
     NSMutableArray *tags_;
     NSString *role_;
 
-    NSArray *relationships_;
-
     NSMutableDictionary *metadata_;
     _transient NSDate *firstSeen_;
     _transient NSDate *lastSeen_;
@@ -1818,8 +1779,6 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 - (BOOL) hasMode;
 - (NSString *) mode;
 
-- (void) setVisible;
-
 - (NSString *) id;
 - (NSString *) name;
 - (UIImage *) icon;
@@ -1830,7 +1789,6 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 - (NSString *) support;
 
 - (NSArray *) files;
-- (NSArray *) relationships;
 - (NSArray *) warnings;
 - (NSArray *) applications;
 
@@ -1849,14 +1807,12 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 
 - (uint32_t) compareBySection:(NSArray *)sections;
 
-- (uint32_t) compareForChanges;
-
 - (void) install;
 - (void) remove;
 
 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
-- (bool) isInstalledAndVisible:(NSNumber *)number;
+- (bool) isInstalledAndUnfiltered:(NSNumber *)number;
 - (bool) isVisibleInSection:(NSString *)section;
 - (bool) isVisibleInSource:(Source *)source;
 
@@ -1936,11 +1892,14 @@ uint32_t PackagePrefixRadix(Package *self, void *context) {
 
         for (size_t i(0); i != 4; ++i)
             if (isalpha(data[i]))
-                data[i] &= 0xdf;
+                data[i] |= 0x20;
     }
 
     if (offset == 0)
-        data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
+        if (data[0] == '@')
+            data[0] = 0x7f;
+        else
+            data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
 
     /* XXX: ntohl may be more honest */
     return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
@@ -1998,8 +1957,6 @@ struct PackageNameOrdering :
 - (void) dealloc {
     if (source_ != nil)
         [source_ release];
-    if (section$_ != nil)
-        [section$_ release];
 
     if (latest_ != nil)
         [latest_ release];
@@ -2013,8 +1970,6 @@ struct PackageNameOrdering :
     if (role_ != nil)
         [role_ release];
 
-    if (relationships_ != nil)
-        [relationships_ release];
     if (metadata_ != nil)
         [metadata_ release];
 
@@ -2108,23 +2063,23 @@ struct PackageNameOrdering :
     _end
 }
 
-- (void) setVisible {
-    visible_ = required_ && [self unfiltered];
-}
-
 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
     if ((self = [super init]) != nil) {
     _profile(Package$initWithVersion)
-    @synchronized (database) {
         era_ = [database era];
         pool_ = pool;
 
         version_ = version;
-        iterator_ = version.ParentPkg();
+
+        _profile(Package$initWithVersion$ParentPkg)
+            iterator_ = version.ParentPkg();
+        _end
+
         database_ = database;
 
         _profile(Package$initWithVersion$Latest)
-            latest_ = (NSString *) StripVersion(version_.VerStr());
+            const char *latest(StripVersion_(version_.VerStr()));
+            latest_ = (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(latest), strlen(latest), kCFStringEncodingASCII, NO);
         _end
 
         pkgCache::VerIterator current;
@@ -2146,16 +2101,12 @@ struct PackageNameOrdering :
             name_.set(pool, iterator_.Display());
         _end
 
-        if (!file_.end()) {
-            _profile(Package$initWithVersion$Source)
-                source_ = [database_ getSource:file_.File()];
-                if (source_ != nil)
-                    [source_ retain];
-                cached_ = true;
-            _end
-        }
-
-        required_ = true;
+        _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;
+        _end
 
         _profile(Package$initWithVersion$Tags)
             pkgCache::TagIterator tag(iterator_.TagList());
@@ -2163,23 +2114,18 @@ struct PackageNameOrdering :
                 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
                 do {
                     const char *name(tag.Name());
-                    [tags_ addObject:(NSString *)CFCString(name)];
+                    [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
                     if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
-                        role_ = (NSString *) CFCString(name + 6);
-                    if (required_ && strncmp(name, "require::", 9) == 0 && (
-                        true
-                    ))
-                        required_ = false;
+                        role_ = (NSString *) CYStringCreate(name + 6);
                     ++tag;
                 } while (!tag.end());
             }
         _end
 
         bool changed(false);
-        NSString *key([static_cast<id>(id_) lowercaseString]);
 
         _profile(Package$initWithVersion$Metadata)
-            metadata_ = [Packages_ objectForKey:key];
+            metadata_ = [Packages_ objectForKey:id_];
 
             if (metadata_ == nil) {
                 firstSeen_ = now_;
@@ -2219,7 +2165,7 @@ struct PackageNameOrdering :
             metadata_ = [metadata_ retain];
 
             if (changed) {
-                [Packages_ setObject:metadata_ forKey:key];
+                [Packages_ setObject:metadata_ forKey:id_];
                 Changed_ = true;
             }
         _end
@@ -2228,14 +2174,14 @@ struct PackageNameOrdering :
             section_.set(pool_, iterator_.Section());
         _end
 
-        obsolete_ = [self hasTag:@"cydia::obsolete"];
-        essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
-        [self setVisible];
-    } _end } return self;
+        _profile(Package$initWithVersion$hasTag)
+            obsolete_ = [self hasTag:@"cydia::obsolete"];
+            essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
+        _end
+    _end } return self;
 }
 
 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
-@synchronized ([Database class]) {
     pkgCache::VerIterator version;
 
     _profile(Package$packageWithIterator$GetCandidateVer)
@@ -2251,7 +2197,7 @@ struct PackageNameOrdering :
         inPool:pool
         database:database
     ] autorelease];
-} }
+}
 
 - (pkgCache::PkgIterator) iterator {
     return iterator_;
@@ -2262,17 +2208,11 @@ struct PackageNameOrdering :
         if (section_.empty())
             return nil;
 
-        std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
-        NSString *name(section_);
-
-      lookup:
-        if (NSDictionary *value = [SectionMap_ objectForKey:name])
-            if (NSString *rename = [value objectForKey:@"Rename"]) {
-                name = rename;
-                goto lookup;
-            }
-
-        section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
+        _profile(Package$section)
+            std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
+            NSString *name(section_);
+            section$_ = [SectionMap_ objectForKey:name] ?: name;
+        _end
     } return section$_;
 }
 
@@ -2317,8 +2257,10 @@ struct PackageNameOrdering :
 }
 
 - (NSString *) longDescription {
-    if (file_.end())
+@synchronized (database_) {
+    if ([database_ era] != era_ || file_.end())
         return nil;
+
     pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
     NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
 
@@ -2334,7 +2276,7 @@ struct PackageNameOrdering :
     }
 
     return [trimmed componentsJoinedByString:@"\n"];
-}
+} }
 
 - (NSString *) shortDescription {
     return tagline_;
@@ -2394,9 +2336,9 @@ struct PackageNameOrdering :
     _profile(Package$upgradableAndEssential)
         pkgCache::VerIterator current(iterator_.CurrentVer());
         if (current.end())
-            return essential && essential_ && visible_;
+            return essential && essential_;
         else
-            return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
+            return !version_.end() && version_ != current;
     _end
 }
 
@@ -2409,12 +2351,31 @@ struct PackageNameOrdering :
 }
 
 - (BOOL) unfiltered {
-    NSString *section([self section]);
-    return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
+    _profile(Package$unfiltered$obsolete)
+        if (obsolete_)
+            return false;
+    _end
+
+    _profile(Package$unfiltered$hasSupportingRole)
+        if (![self hasSupportingRole])
+            return false;
+    _end
+
+    return true;
 }
 
 - (BOOL) visible {
-    return visible_;
+    if (![self unfiltered])
+        return false;
+
+    NSString *section([self section]);
+
+    _profile(Package$visible$isSectionVisible)
+        if (section != nil && !isSectionVisible(section))
+            return false;
+    _end
+
+    return true;
 }
 
 - (BOOL) half {
@@ -2540,10 +2501,6 @@ struct PackageNameOrdering :
     return files;
 }
 
-- (NSArray *) relationships {
-    return relationships_;
-}
-
 - (NSArray *) warnings {
     NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
     const char *name(iterator_.Name());
@@ -2629,21 +2586,16 @@ struct PackageNameOrdering :
 }
 
 - (Source *) source {
-    if (!cached_) {
+    if (source_ == nil) {
         @synchronized (database_) {
             if ([database_ era] != era_ || file_.end())
-                source_ = nil;
-            else {
-                source_ = [database_ getSource:file_.File()];
-                if (source_ != nil)
-                    [source_ retain];
-            }
-
-            cached_ = true;
+                source_ = (Source *) [NSNull null];
+            else
+                source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
         }
     }
 
-    return source_;
+    return source_ == (Source *) [NSNull null] ? nil : source_;
 }
 
 - (NSString *) role {
@@ -2726,57 +2678,42 @@ struct PackageNameOrdering :
     return _not(uint32_t);
 }
 
-- (uint32_t) compareForChanges {
-    union {
-        uint32_t key;
-
-        struct {
-            uint32_t timestamp : 30;
-            uint32_t ignored : 1;
-            uint32_t upgradable : 1;
-        } bits;
-    } value;
-
-    bool upgradable([self upgradableAndEssential:YES]);
-    value.bits.upgradable = upgradable ? 1 : 0;
-
-    if (upgradable) {
-        value.bits.timestamp = 0;
-        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.ignored = 0;
-        value.bits.upgradable = 0;
-    }
-
-    return _not(uint32_t) - value.key;
-}
-
 - (void) clear {
+@synchronized (database_) {
     pkgProblemResolver *resolver = [database_ resolver];
     resolver->Clear(iterator_);
-    resolver->Protect(iterator_);
-}
+
+    pkgCacheFile &cache([database_ cache]);
+    cache->SetReInstall(iterator_, false);
+    cache->MarkKeep(iterator_, false);
+} }
 
 - (void) install {
+@synchronized (database_) {
     pkgProblemResolver *resolver = [database_ resolver];
     resolver->Clear(iterator_);
     resolver->Protect(iterator_);
+
     pkgCacheFile &cache([database_ cache]);
+    cache->SetReInstall(iterator_, false);
     cache->MarkInstall(iterator_, false);
+
     pkgDepCache::StateCache &state((*cache)[iterator_]);
     if (!state.Install())
         cache->SetReInstall(iterator_, true);
-}
+} }
 
 - (void) remove {
+@synchronized (database_) {
     pkgProblemResolver *resolver = [database_ resolver];
     resolver->Clear(iterator_);
-    resolver->Protect(iterator_);
     resolver->Remove(iterator_);
-    [database_ cache]->MarkDelete(iterator_, true);
-}
+    resolver->Protect(iterator_);
+
+    pkgCacheFile &cache([database_ cache]);
+    cache->SetReInstall(iterator_, false);
+    cache->MarkDelete(iterator_, true);
+} }
 
 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
     _profile(Package$isUnfilteredAndSearchedForBy)
@@ -2813,19 +2750,18 @@ struct PackageNameOrdering :
     _end
 }
 
-- (bool) isInstalledAndVisible:(NSNumber *)number {
-    return (![number boolValue] || [self visible]) && ![self uninstalled];
+- (bool) isInstalledAndUnfiltered:(NSNumber *)number {
+    return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
 }
 
 - (bool) isVisibleInSection:(NSString *)name {
-    NSString *section = [self section];
+    NSString *section([self section]);
 
-    return
-        [self visible] && (
-            name == nil ||
-            section == nil && [name length] == 0 ||
-            [name isEqualToString:section]
-        );
+    return (
+        name == nil ||
+        section == nil && [name length] == 0 ||
+        [name isEqualToString:section]
+    ) && [self visible];
 }
 
 - (bool) isVisibleInSource:(Source *)source {
@@ -2954,6 +2890,7 @@ struct PackageNameOrdering :
 /* }}} */
 
 static NSString *Colon_;
+static NSString *Elision_;
 static NSString *Error_;
 static NSString *Warning_;
 
@@ -2972,6 +2909,7 @@ static NSString *Warning_;
 }
 
 - (void) dealloc {
+    // XXX: actually implement this thing
     _assert(false);
     NSRecycleZone(zone_);
     // XXX: malloc_destroy_zone(zone_);
@@ -3065,7 +3003,7 @@ static NSString *Warning_;
 }
 
 - (Package *) packageWithName:(NSString *)name {
-@synchronized ([Database class]) {
+@synchronized (self) {
     if (static_cast<pkgDepCache *>(cache_) == NULL)
         return nil;
     pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
@@ -3083,7 +3021,7 @@ static NSString *Warning_;
         zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
         apr_pool_create(&pool_, NULL);
 
-        packages_ = [[NSMutableArray alloc] init];
+        packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
 
         int fds[2];
 
@@ -3096,7 +3034,7 @@ static NSString *Warning_;
         [NSThread
             detachNewThreadSelector:@selector(_readCydia:)
             toTarget:self
-            withObject:[[NSNumber numberWithInt:fds[0]] retain]
+            withObject:[NSNumber numberWithInt:fds[0]]
         ];
 
         _assert(pipe(fds) != -1);
@@ -3105,7 +3043,7 @@ static NSString *Warning_;
         [NSThread
             detachNewThreadSelector:@selector(_readStatus:)
             toTarget:self
-            withObject:[[NSNumber numberWithInt:fds[0]] retain]
+            withObject:[NSNumber numberWithInt:fds[0]]
         ];
 
         _assert(pipe(fds) != -1);
@@ -3121,7 +3059,7 @@ static NSString *Warning_;
         [NSThread
             detachNewThreadSelector:@selector(_readOutput:)
             toTarget:self
-            withObject:[[NSNumber numberWithInt:fds[0]] retain]
+            withObject:[NSNumber numberWithInt:fds[0]]
         ];
     } return self;
 }
@@ -3151,7 +3089,7 @@ static NSString *Warning_;
 }
 
 - (NSArray *) packages {
-    return packages_;
+    return (NSArray *) packages_;
 }
 
 - (NSArray *) sources {
@@ -3167,7 +3105,7 @@ static NSString *Warning_;
 
     NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
 
-    for (Package *package in packages_) {
+    for (Package *package in [self packages]) {
         if (![package broken])
             continue;
         pkgCache::PkgIterator pkg([package iterator]);
@@ -3259,13 +3197,13 @@ static NSString *Warning_;
     return [self popErrorWithTitle:title] || !success;
 }
 
-- (void) reloadData { _pooled
-@synchronized ([Database class]) {
-    @synchronized (self) {
-        ++era_;
-    }
+- (void) reloadData { CYPoolStart() {
+@synchronized (self) {
+    ++era_;
+
+    CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
+    CFArrayRemoveAllValues(packages_);
 
-    [packages_ removeAllObjects];
     sources_.clear();
 
     _error->Discard();
@@ -3358,8 +3296,6 @@ static NSString *Warning_;
             return;
     }
 
-    _trace();
-
     for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
         std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
         for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
@@ -3371,8 +3307,6 @@ static NSString *Warning_;
             }
     }
 
-    _trace();
-
     {
         /*std::vector<Package *> packages;
         packages.reserve(std::max(10000U, [packages_ count] + 1000));
@@ -3384,7 +3318,7 @@ static NSString *Warning_;
         for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
             if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
                 //packages.push_back(package);
-                [packages_ addObject:package];
+                CFArrayAppendValue(packages_, [package retain]);
 
         _trace();
 
@@ -3394,9 +3328,9 @@ static NSString *Warning_;
             packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
         _trace();*/
 
-        [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
-        [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
-        [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
+        [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
+        [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
+        [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
 
         /*_trace();
         PrintTimes();
@@ -3410,12 +3344,25 @@ static NSString *Warning_;
 
         //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
 
-        CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
+        CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
 
         //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
 
         _trace();
     }
+} } CYPoolEnd() _trace(); }
+
+- (void) clear {
+@synchronized (self) {
+    delete resolver_;
+    resolver_ = new pkgProblemResolver(cache_);
+
+    for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
+        if (!cache_[iterator].Keep()) {
+            cache_->MarkKeep(iterator, false);
+            cache_->SetReInstall(iterator, false);
+        }
+    }
 } }
 
 - (void) configure {
@@ -3561,11 +3508,6 @@ static NSString *Warning_;
     [self updateWithStatus:status_];
 }
 
-- (void) setVisible {
-    for (Package *package in packages_)
-        [package setVisible];
-}
-
 - (void) updateWithStatus:(Status &)status {
     _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
     NSString *title(UCLocalize("REFRESHING_DATA"));
@@ -3621,7 +3563,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 /* Web Scripting {{{ */
 @interface CydiaObject : NSObject {
     id indirect_;
-    id delegate_;
+    _transient id delegate_;
 }
 
 - (id) initWithDelegate:(IndirectDelegate *)indirect;
@@ -4104,32 +4046,30 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
         [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
 
-        UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
+        [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
             initWithTitle:UCLocalize("CANCEL")
             // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
             style:UIBarButtonItemStylePlain
             target:self
             action:@selector(cancelButtonClicked)
-        ];
-        [[self navigationItem] setLeftBarButtonItem:leftItem];
-        [leftItem release];
+        ] autorelease]];
     } return self;
 }
 
 - (void) applyRightButton {
-    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
-        initWithTitle:UCLocalize("CONFIRM")
-        style:UIBarButtonItemStylePlain
-        target:self
-        action:@selector(confirmButtonClicked)
-    ];
 #if !AlwaysReload && !IgnoreInstall
-    if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
-    else [super applyRightButton];
+    if (issues_ == nil && ![self isLoading])
+        [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
+            initWithTitle:UCLocalize("CONFIRM")
+            style:UIBarButtonItemStylePlain
+            target:self
+            action:@selector(confirmButtonClicked)
+        ] autorelease]];
+    else
+        [super applyRightButton];
 #else
     [[self navigationItem] setRightBarButtonItem:nil];
 #endif
-    [rightItem release];
 }
 
 - (void) cancelButtonClicked {
@@ -4158,8 +4098,9 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 /* Progress Data {{{ */
 @interface ProgressData : NSObject {
     SEL selector_;
-    id target_;
-    id object_;
+    // XXX: should these really both be _transient?
+    _transient id target_;
+    _transient id object_;
 }
 
 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
@@ -4286,16 +4227,15 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     CGRect prgrect = {{
         (bounds.size.width - prgsize.width) / 2,
-        bounds.size.height - prgsize.height - 64
+        bounds.size.height - prgsize.height - 20
     }, prgsize};
 
-    float closewidth = bounds.size.width - 20;
-    if (closewidth > 300) closewidth = 300;
+    float closewidth = std::min(bounds.size.width - 20, 300.0f);
 
     [progress_ setFrame:prgrect];
     [status_ setFrame:CGRectMake(
         10,
-        bounds.size.height - prgsize.height - 94,
+        bounds.size.height - prgsize.height - 50,
         bounds.size.width - 20,
         24
     )];
@@ -4303,11 +4243,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         10,
         20,
         bounds.size.width - 20,
-        bounds.size.height - 106
+        bounds.size.height - 62
     )];
     [close_ setFrame:CGRectMake(
         (bounds.size.width - closewidth) / 2,
-        bounds.size.height - prgsize.height - 94,
+        bounds.size.height - prgsize.height - 50,
         closewidth,
         32 + prgsize.height
     )];
@@ -4330,8 +4270,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     if ([context isEqualToString:@"conffile"]) {
         FILE *input = [database_ input];
-        if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
-        else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
+        if (button == [alert cancelButtonIndex])
+            fprintf(input, "N\n");
+        else if (button == [alert firstOtherButtonIndex])
+            fprintf(input, "Y\n");
         fflush(input);
     }
 }
@@ -4421,8 +4363,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
     [[data target] performSelector:[data selector] withObject:[data object]];
-    [data release];
-
     [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
 }
 
@@ -4476,11 +4416,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [NSThread
         detachNewThreadSelector:@selector(_detachNewThreadData:)
         toTarget:self
-        withObject:[[ProgressData alloc]
+        withObject:[[[ProgressData alloc]
             initWithSelector:selector
             target:target
             object:object
-        ]
+        ] autorelease]
     ];
 }
 
@@ -4610,9 +4550,9 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 @end
 
 @implementation ContentView
+
 - (id) initWithFrame:(CGRect)frame {
     if ((self = [super initWithFrame:frame]) != nil) {
-        /* Fix landscape stretching. */
         [self setNeedsDisplayOnBoundsChange:YES];
     } return self;
 }
@@ -4625,10 +4565,47 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [super drawRect:rect];
     [delegate_ drawContentRect:rect];
 }
+
+@end
+/* }}} */
+/* Cydia TableView Cell {{{ */
+@interface CYTableViewCell : UITableViewCell {
+    ContentView *content_;
+    bool highlighted_;
+}
+
+@end
+
+@implementation CYTableViewCell
+
+- (void) dealloc {
+    [content_ release];
+    [super dealloc];
+}
+
+- (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
+    //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
+
+    if (view == content_) {
+        //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
+        highlighted_ = highlighted;
+    }
+
+    [super _updateHighlightColorsForView:view highlighted:highlighted];
+}
+
+- (void) setSelected:(BOOL)selected animated:(BOOL)animated {
+    //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
+    highlighted_ = selected;
+
+    [super setSelected:selected animated:animated];
+    [content_ setNeedsDisplay];
+}
+
 @end
 /* }}} */
 /* Package Cell {{{ */
-@interface PackageCell : UITableViewCell <
+@interface PackageCell : CYTableViewCell <
     ContentDelegate
 > {
     UIImage *icon_;
@@ -4638,10 +4615,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     NSString *source_;
     UIImage *badge_;
     Package *package_;
-    UIColor *color_;
-    ContentView *content_;
-    BOOL faded_;
-    float fade_;
     UIImage *placard_;
 }
 
@@ -4692,15 +4665,9 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) dealloc {
     [self clearPackage];
-    [content_ release];
-    [color_ release];
     [super dealloc];
 }
 
-- (float) fade {
-    return faded_ ? [self selectionPercent] : fade_;
-}
-
 - (PackageCell *) init {
     CGRect frame(CGRectMake(0, 0, 320, 74));
     if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
@@ -4713,8 +4680,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
         [content_ setDelegate:self];
         [content_ setOpaque:YES];
-        if ([self respondsToSelector:@selector(selectionPercent)])
-            faded_ = YES;
     } return self;
 }
 
@@ -4785,7 +4750,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) drawContentRect:(CGRect)rect {
-    bool selected([self isSelected]);
+    bool highlighted(highlighted_);
     float width([self bounds].size.width);
 
 #if 0
@@ -4816,15 +4781,15 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         )];
     }
 
-    if (selected)
+    if (highlighted)
         UISetColor(White_);
 
-    if (!selected)
+    if (!highlighted)
         UISetColor(commercial_ ? Purple_ : Black_);
     [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
     [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
 
-    if (!selected)
+    if (!highlighted)
         UISetColor(commercial_ ? Purplish_ : Gray_);
     [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
 
@@ -4832,12 +4797,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
 }
 
-- (void) setSelected:(BOOL)selected animated:(BOOL)fade {
-    //[self _setBackgroundColor];
-    [super setSelected:selected animated:fade];
-    [content_ setNeedsDisplay];
-}
-
 + (int) heightForPackage:(Package *)package {
     return 73;
 }
@@ -4845,7 +4804,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 @end
 /* }}} */
 /* Section Cell {{{ */
-@interface SectionCell : UITableViewCell <
+@interface SectionCell : CYTableViewCell <
     ContentDelegate
 > {
     NSString *basic_;
@@ -4853,8 +4812,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     NSString *name_;
     NSString *count_;
     UIImage *icon_;
-    ContentView *content_;
-    id switch_;
+    UISwitch *switch_;
     BOOL editing_;
 }
 
@@ -4890,15 +4848,13 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [self clearSection];
     [icon_ release];
     [switch_ release];
-    [content_ release];
-
     [super dealloc];
 }
 
 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
     if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
         icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
-        switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
+        switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
         [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
 
         UIView *content([self contentView]);
@@ -4968,20 +4924,19 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) drawContentRect:(CGRect)rect {
-    BOOL selected = [self isSelected];
+    bool highlighted(highlighted_);
 
     [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
 
-    if (selected)
+    if (highlighted)
         UISetColor(White_);
 
-    if (!selected)
-        UISetColor(Black_);
-
     float width(rect.size.width);
     if (editing_)
         width -= 87;
 
+    if (!highlighted)
+        UISetColor(Black_);
     [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
 
     CGSize size = [count_ sizeWithFont:Font14_];
@@ -5300,6 +5255,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         target:self
         action:@selector(customButtonClicked)
     ];
+
+    [self reloadURL];
 }
 
 - (bool) isLoading {
@@ -5323,9 +5280,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     UITableView *list_;
     NSMutableArray *index_;
     NSMutableDictionary *indices_;
-    id target_;
+    // XXX: this target_ seems to be delegate_. :(
+    _transient id target_;
     SEL action_;
-    id delegate_;
+    // XXX: why do we even have this delegate_?
+    _transient id delegate_;
 }
 
 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
@@ -5654,14 +5613,13 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 @end
 /* }}} */
 /* Source Cell {{{ */
-@interface SourceCell : UITableViewCell <
+@interface SourceCell : CYTableViewCell <
     ContentDelegate
 > {
     UIImage *icon_;
     NSString *origin_;
     NSString *description_;
     NSString *label_;
-    ContentView *content_;
 }
 
 - (void) setSource:(Source *)source;
@@ -5700,7 +5658,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) dealloc {
     [self clearSource];
-    [content_ release];
     [super dealloc];
 }
 
@@ -5719,30 +5676,25 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     } return self;
 }
 
-- (void) setSelected:(BOOL)selected animated:(BOOL)animated {
-    [super setSelected:selected animated:animated];
-    [content_ setNeedsDisplay];
-}
-
 - (void) drawContentRect:(CGRect)rect {
-    bool selected([self isSelected]);
+    bool highlighted(highlighted_);
     float width(rect.size.width);
 
     if (icon_ != nil)
         [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
 
-    if (selected)
+    if (highlighted)
         UISetColor(White_);
 
-    if (!selected)
+    if (!highlighted)
         UISetColor(Black_);
     [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
 
-    if (!selected)
+    if (!highlighted)
         UISetColor(Blue_);
     [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
 
-    if (!selected)
+    if (!highlighted)
         UISetColor(Gray_);
     [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
 }
@@ -5780,7 +5732,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 @implementation SourceTable
 
-- (void) _deallocConnection:(NSURLConnection *)connection {
+- (void) _releaseConnection:(NSURLConnection *)connection {
     if (connection != nil) {
         [connection cancel];
         //[connection setDelegate:nil];
@@ -5796,11 +5748,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     if (error_ != nil)
         [error_ release];
 
-    //[self _deallocConnection:installer_];
-    [self _deallocConnection:trivial_];
-    [self _deallocConnection:trivial_gz_];
-    [self _deallocConnection:trivial_bz2_];
-    //[self _deallocConnection:automatic_];
+    //[self _releaseConnection:installer_];
+    [self _releaseConnection:trivial_];
+    [self _releaseConnection:trivial_gz_];
+    [self _releaseConnection:trivial_bz2_];
+    //[self _releaseConnection:automatic_];
 
     [sources_ release];
     [list_ release];
@@ -5921,6 +5873,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) _endConnection:(NSURLConnection *)connection {
+    // XXX: the memory management in this method is horribly awkward
+
     NSURLConnection **field = NULL;
     if (connection == trivial_)
         field = &trivial_;
@@ -6060,6 +6014,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
                 cydia_ = false;
 
+                // XXX: this is stupid
                 hud_ = [[delegate_ addProgressHUD] retain];
                 [hud_ setText:UCLocalize("VERIFYING_URL")];
             } break;
@@ -6124,11 +6079,12 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
     _trace();
 
-     int count([sources_ count]);
+    int count([sources_ count]);
     offset_ = 0;
     for (int i = 0; i != count; i++) {
-        if ([[sources_ objectAtIndex:i] record] == nil) break;
-        else offset_++;
+        if ([[sources_ objectAtIndex:i] record] == nil)
+            break;
+        offset_++;
     }
 
     [list_ setEditing:NO];
@@ -6167,34 +6123,27 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
-    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
+    [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
         initWithTitle:UCLocalize("ADD")
         style:UIBarButtonItemStylePlain
         target:self
         action:@selector(addButtonClicked)
-    ];
-    [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
-    [leftItem release];
+    ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
 
-    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
-        initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
-        style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
+    [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
+        initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
+        style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
         target:self
         action:@selector(editButtonClicked)
-    ];
-    [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
-    [rightItem release];
+    ] autorelease] animated:animated];
 
-    if (IsWildcat_ && !editing) {
-        UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
+    if (IsWildcat_ && !editing)
+        [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
             initWithTitle:UCLocalize("SETTINGS")
             style:UIBarButtonItemStylePlain
             target:self
             action:@selector(settingsButtonClicked)
-            ];
-        [[self navigationItem] setLeftBarButtonItem:settingsItem];
-        [settingsItem release];
-    }
+        ] autorelease]];
 }
 
 - (void) settingsButtonClicked {
@@ -6231,7 +6180,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 - (NSString *) title { return UCLocalize("INSTALLED"); }
 
 - (id) initWithDatabase:(Database *)database {
-    if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
+    if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
         [self updateRoleButton];
         [self queueStatusDidChange];
     } return self;
@@ -6246,15 +6195,16 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 - (void) queueStatusDidChange {
 #if !AlwaysReload
     if (IsWildcat_) {
-        UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
-            initWithTitle:UCLocalize("QUEUE")
-            style:UIBarButtonItemStyleDone
-            target:self
-            action:@selector(queueButtonClicked)
-        ];
-        if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
-        else [[self navigationItem] setLeftBarButtonItem:nil];
-        [queueItem release];
+        if (Queuing_) {
+            [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
+                initWithTitle:UCLocalize("QUEUE")
+                style:UIBarButtonItemStyleDone
+                target:self
+                action:@selector(queueButtonClicked)
+            ] autorelease]];
+        } else {
+            [[self navigationItem] setLeftBarButtonItem:nil];
+        }
     }
 #endif
 }
@@ -6264,14 +6214,13 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) updateRoleButton {
-    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
-        initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
-        style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
-        target:self
-        action:@selector(roleButtonClicked)
-    ];
-    if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
-    [rightItem release];
+    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]];
 }
 
 - (void) roleButtonClicked {
@@ -6305,6 +6254,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         [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"];
 }
 
 - (void) aboutButtonClicked {
@@ -6360,14 +6311,12 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     if ((self = [super init]) != nil) {
         [[self navigationItem] setTitle:UCLocalize("MANAGE")];
 
-        UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
+        [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
             initWithTitle:UCLocalize("SETTINGS")
             style:UIBarButtonItemStylePlain
             target:self
             action:@selector(settingsButtonClicked)
-        ];
-        [[self navigationItem] setLeftBarButtonItem:settingsItem];
-        [settingsItem release];
+        ] autorelease]];
 
         [self queueStatusDidChange];
     } return self;
@@ -6394,15 +6343,12 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 - (void) queueStatusDidChange {
 #if !AlwaysReload
     if (!IsWildcat_ && Queuing_) {
-        UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
+        [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
             initWithTitle:UCLocalize("QUEUE")
             style:UIBarButtonItemStyleDone
             target:self
             action:@selector(queueButtonClicked)
-        ];
-        [[self navigationItem] setRightBarButtonItem:queueItem];
-
-        [queueItem release];
+        ] autorelease]];
     } else {
         [[self navigationItem] setRightBarButtonItem:nil];
     }
@@ -6428,6 +6374,14 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 @implementation RefreshBar
 
+- (void) dealloc {
+    [indicator_ release];
+    [prompt_ release];
+    [progress_ release];
+    [cancel_ release];
+    [super dealloc];
+}
+
 - (void) positionViews {
     CGRect frame = [cancel_ frame];
     frame.origin.x = [self frame].size.width - frame.size.width - 5;
@@ -6528,7 +6482,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 /* Cydia Tab Bar Controller {{{ */
 @interface CYTabBarController : UITabBarController {
-    Database *database_;
+    _transient Database *database_;
 }
 
 @end
@@ -6558,7 +6512,7 @@ freeing the view controllers on tab change */
 /* Cydia Navigation Controller {{{ */
 @interface CYNavigationController : UINavigationController {
     _transient Database *database_;
-    id<UINavigationControllerDelegate> delegate_;
+    _transient id<UINavigationControllerDelegate> delegate_;
 }
 
 - (id) initWithDatabase:(Database *)database;
@@ -6759,7 +6713,9 @@ freeing the view controllers on tab change */
     static NSString *reuseIdentifier = @"SectionCell";
 
     SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
-    if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
+    if (cell == nil)
+        cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
+
     [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
 
     return cell;
@@ -6828,40 +6784,13 @@ freeing the view controllers on tab change */
     [sections_ removeAllObjects];
     [filtered_ removeAllObjects];
 
-#if 0
-    typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
-    SectionMap sections;
-    sections.resize(64);
-#else
     NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
-#endif
 
     _trace();
     for (Package *package in packages) {
         NSString *name([package section]);
         NSString *key(name == nil ? @"" : name);
 
-#if 0
-        Section **section;
-
-        _profile(SectionsView$reloadData$Section)
-            section = &sections[key];
-            if (*section == nil) {
-                _profile(SectionsView$reloadData$Section$Allocate)
-                    *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
-                _end
-            }
-        _end
-
-        [*section addToCount];
-
-        _profile(SectionsView$reloadData$Filter)
-            if (![package valid] || ![package visible])
-                continue;
-        _end
-
-        [*section addToRow];
-#else
         Section *section;
 
         _profile(SectionsView$reloadData$Section)
@@ -6882,16 +6811,10 @@ freeing the view controllers on tab change */
         _end
 
         [section addToRow];
-#endif
     }
     _trace();
 
-#if 0
-    for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
-        [sections_ addObject:i->second];
-#else
     [sections_ addObjectsFromArray:[sections allValues]];
-#endif
 
     [sections_ sortUsingSelector:@selector(compareByLocalized:)];
 
@@ -6905,14 +6828,12 @@ freeing the view controllers on tab change */
         [filtered_ addObject:section];
     }
 
-    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
-        initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
+    [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
+        initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
         style:UIBarButtonItemStylePlain
         target:self
         action:@selector(editButtonClicked)
-    ];
-    [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
-    [rightItem release];
+    ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
 
     [list_ reloadData];
     _trace();
@@ -6946,7 +6867,7 @@ freeing the view controllers on tab change */
     UITableViewDelegate
 > {
     _transient Database *database_;
-    NSMutableArray *packages_;
+    CFMutableArrayRef packages_;
     NSMutableArray *sections_;
     UITableView *list_;
     unsigned upgrades_;
@@ -6964,7 +6885,8 @@ freeing the view controllers on tab change */
     [list_ setDelegate:nil];
     [list_ setDataSource:nil];
 
-    [packages_ release];
+    CFRelease(packages_);
+
     [sections_ release];
     [list_ release];
     [super dealloc];
@@ -6997,10 +6919,14 @@ freeing the view controllers on tab change */
     return [[sections_ objectAtIndex:section] count];
 }
 
+- (Package *) packageAtIndex:(NSUInteger)index {
+    return (Package *) CFArrayGetValueAtIndex(packages_, index);
+}
+
 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
     Section *section([sections_ objectAtIndex:[path section]]);
     NSInteger row([path row]);
-    return [packages_ objectAtIndex:([section row] + row)];
+    return [self packageAtIndex:([section row] + row)];
 }
 
 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
@@ -7040,7 +6966,8 @@ freeing the view controllers on tab change */
         database_ = database;
         [[self navigationItem] setTitle:UCLocalize("CHANGES")];
 
-        packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
+        packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
+
         sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
 
         list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
@@ -7058,29 +6985,30 @@ freeing the view controllers on tab change */
 - (void) _reloadPackages:(NSArray *)packages {
     _trace();
     for (Package *package in packages)
-        if (
-            [package uninstalled] && [package valid] && [package visible] ||
-            [package upgradableAndEssential:YES]
-        )
-            [packages_ addObject:package];
+        if ([package upgradableAndEssential:YES] || [package visible])
+            CFArrayAppendValue(packages_, package);
 
     _trace();
-    [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
+    [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
     _trace();
 }
 
 - (void) reloadData {
     NSArray *packages = [database_ packages];
 
-    [packages_ removeAllObjects];
+    CFArrayRemoveAllValues(packages_);
+
     [sections_ removeAllObjects];
 
+#if 1
     UIProgressHUD *hud([delegate_ addProgressHUD]);
-    // XXX: localize
-    [hud setText:@"Loading Changes"];
-    NSLog(@"HUD:%@::%@", delegate_, hud);
+    [hud setText:UCLocalize("LOADING")];
+    //NSLog(@"HUD:%@::%@", delegate_, hud);
     [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
     [delegate_ removeProgressHUD:hud];
+#else
+    [self _reloadPackages:packages];
+#endif
 
     Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
     Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
@@ -7092,8 +7020,8 @@ freeing the view controllers on tab change */
 
     CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
 
-    for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
-        Package *package = [packages_ objectAtIndex:offset];
+    for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
+        Package *package = [self packageAtIndex:offset];
 
         BOOL uae = [package upgradableAndEssential:YES];
 
@@ -7138,7 +7066,7 @@ freeing the view controllers on tab change */
     if (unseens) {
         Section *last = [sections_ lastObject];
         size_t count = [last count];
-        [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
+        CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
         [sections_ removeLastObject];
     }
 
@@ -7149,23 +7077,21 @@ freeing the view controllers on tab change */
 
     [list_ reloadData];
 
-    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
-        initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
-        style:UIBarButtonItemStylePlain
-        target:self
-        action:@selector(upgradeButtonClicked)
-    ];
-    if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
-    [rightItem release];
+    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]];
 
-    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
-        initWithTitle:UCLocalize("REFRESH")
-        style:UIBarButtonItemStylePlain
-        target:self
-        action:@selector(refreshButtonClicked)
-    ];
-    if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
-    [leftItem release];
+    if (![delegate_ updating])
+        [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
+            initWithTitle:UCLocalize("REFRESH")
+            style:UIBarButtonItemStylePlain
+            target:self
+            action:@selector(refreshButtonClicked)
+        ] autorelease]];
 }
 
 @end
@@ -7247,8 +7173,8 @@ freeing the view controllers on tab change */
     NSString *name_;
     Package *package_;
     UITableView *table_;
-    id subscribedSwitch_;
-    id ignoredSwitch_;
+    UISwitch *subscribedSwitch_;
+    UISwitch *ignoredSwitch_;
     UITableViewCell *subscribedCell_;
     UITableViewCell *ignoredCell_;
 }
@@ -7344,11 +7270,11 @@ freeing the view controllers on tab change */
         [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
         [[self view] addSubview:table_];
 
-        subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
+        subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
         [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
         [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
 
-        ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
+        ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
         [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
         [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
 
@@ -7383,7 +7309,6 @@ freeing the view controllers on tab change */
 
 @end
 /* }}} */
-
 /* Signature Controller {{{ */
 @interface SignatureController : CYBrowserController {
     _transient Database *database_;
@@ -7420,13 +7345,15 @@ freeing the view controllers on tab change */
 
 @end
 /* }}} */
+
 /* Role Controller {{{ */
 @interface RoleController : CYViewController <
     UITableViewDataSource,
     UITableViewDelegate
 > {
     _transient Database *database_;
-    id roledelegate_;
+    // XXX: ok, "roledelegate_"?...
+    _transient id roledelegate_;
     UITableView *table_;
     UISegmentedControl *segment_;
     UIView *container_;
@@ -7536,20 +7463,29 @@ freeing the view controllers on tab change */
     [self showDoneButton];
 }
 
-- (void) doneButtonClicked {
+- (void) saveAndClose {
     [self save];
+
+    [[self navigationItem] setRightBarButtonItem:nil];
     [[self navigationController] dismissModalViewControllerAnimated:YES];
 }
 
+- (void) doneButtonClicked {
+    UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
+    [spinner startAnimating];
+    UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
+    [[self navigationItem] setRightBarButtonItem:spinItem];
+
+    [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
+}
+
 - (void) showDoneButton {
-    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
+    [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
         initWithTitle:UCLocalize("DONE")
         style:UIBarButtonItemStyleDone
         target:self
         action:@selector(doneButtonClicked)
-    ];
-    [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
-    [rightItem release];
+    ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
 }
 
 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
@@ -7579,15 +7515,73 @@ freeing the view controllers on tab change */
 }
 
 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
-    if (section == 3) return 44.0f;
-    else return 0;
+    return section == 3 ? 44.0f : 0;
 }
 
 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
-    if (section == 3) return container_;
-    else return nil;
+    return section == 3 ? container_ : nil;
 }
 
+@end
+/* }}} */
+/* Stash Controller {{{ */
+@interface CYStashController : CYViewController {
+    // XXX: just delete these things
+    _transient UIActivityIndicatorView *spinner_;
+    _transient UILabel *status_;
+    _transient UILabel *caption_;
+}
+@end
+
+@implementation CYStashController
+- (id) init {
+    if ((self = [super init])) {
+        [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
+
+        spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
+        CGRect spinrect = [spinner_ frame];
+        spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
+        spinrect.origin.y = [[self view] frame].size.height - 80.0f;
+        [spinner_ setFrame:spinrect];
+        [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
+        [[self view] addSubview:spinner_];
+        [spinner_ startAnimating];
+
+        CGRect captrect;
+        captrect.size.width = [[self view] frame].size.width;
+        captrect.size.height = 40.0f;
+        captrect.origin.x = 0;
+        captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
+        caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
+        [caption_ setText:@"Initializing Filesystem"];
+        [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
+        [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
+        [caption_ setTextColor:[UIColor whiteColor]];
+        [caption_ setBackgroundColor:[UIColor clearColor]];
+        [caption_ setShadowColor:[UIColor blackColor]];
+        [caption_ setTextAlignment:UITextAlignmentCenter];
+        [[self view] addSubview:caption_];
+
+        CGRect statusrect;
+        statusrect.size.width = [[self view] frame].size.width;
+        statusrect.size.height = 30.0f;
+        statusrect.origin.x = 0;
+        statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
+        status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
+        [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
+        [status_ setText:@"(Cydia will exit when complete.)"];
+        [status_ setFont:[UIFont systemFontOfSize:16.0f]];
+        [status_ setTextColor:[UIColor whiteColor]];
+        [status_ setBackgroundColor:[UIColor clearColor]];
+        [status_ setShadowColor:[UIColor blackColor]];
+        [status_ setTextAlignment:UITextAlignmentCenter];
+        [[self view] addSubview:status_];
+    } return self;
+}
+
+- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
+    return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
+}
 @end
 /* }}} */
 
@@ -7598,8 +7592,10 @@ freeing the view controllers on tab change */
 
     bool dropped_;
     bool updating_;
-    id updatedelegate_;
-    UITabBarController *root_;
+    // 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;
@@ -7641,7 +7637,7 @@ freeing the view controllers on tab change */
 }
 
 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
-    return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
+    return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
 }
 
 - (void) setTabBarController:(UITabBarController *)controller {
@@ -7679,7 +7675,8 @@ freeing the view controllers on tab change */
 }
 
 - (void) completeUpdate {
-    if (!updating_) return;
+    if (!updating_)
+        return;
     updating_ = false;
 
     [self raiseBar:YES];
@@ -7761,7 +7758,8 @@ freeing the view controllers on tab change */
 }
 
 - (void) dropBar:(BOOL)animated {
-    if (dropped_) return;
+    if (dropped_)
+        return;
     dropped_ = true;
 
     [[self view] addSubview:refreshbar_];
@@ -7772,12 +7770,14 @@ freeing the view controllers on tab change */
     barframe.origin.y = sboffset;
     [refreshbar_ setFrame:barframe];
 
-    if (animated) [UIView beginAnimations:nil context:NULL];
+    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];
+    if (animated)
+        [UIView commitAnimations];
 
     // Ensure bar has the proper width for our view, it might have changed
     barframe.size.width = viewframe.size.width;
@@ -7788,20 +7788,23 @@ freeing the view controllers on tab change */
 }
 
 - (void) raiseBar:(BOOL)animated {
-    if (!dropped_) return;
+    if (!dropped_)
+        return;
     dropped_ = false;
 
     [refreshbar_ removeFromSuperview];
 
     CGFloat sboffset = [self statusBarHeight];
 
-    if (animated) [UIView beginAnimations:nil context:NULL];
+    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];
+    if (animated)
+        [UIView commitAnimations];
 
     // XXX: fix Apple's layout bug
     [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
@@ -7863,12 +7866,14 @@ typedef enum {
     ConfirmationControllerDelegate,
     ProgressControllerDelegate,
     CydiaDelegate,
-    UINavigationControllerDelegate
+    UINavigationControllerDelegate,
+    UITabBarControllerDelegate
 > {
+    // XXX: evaluate all fields for _transient
+
     UIWindow *window_;
     CYContainer *container_;
-
-    id tabbar_;
+    CYTabBarController *tabbar_;
 
     NSMutableArray *essential_;
     NSMutableArray *broken_;
@@ -7878,7 +7883,7 @@ typedef enum {
     int tag_;
 
     UIKeyboard *keyboard_;
-    UIProgressHUD *hud_;
+    int huds_;
 
     SectionsController *sections_;
     ChangesController *changes_;
@@ -7888,6 +7893,8 @@ typedef enum {
     InstalledController *installed_;
     id queueDelegate_;
 
+    CYStashController *stash_;
+
     bool loaded_;
 }
 
@@ -7981,7 +7988,8 @@ static _finline void _setHomePage(Cydia *self) {
 - (int)indexOfTabWithTag:(int)tag {
     int i = 0;
     for (UINavigationController *controller in [tabbar_ viewControllers]) {
-        if ([[controller tabBarItem] tag] == tag) return i;
+        if ([[controller tabBarItem] tag] == tag)
+            return i;
         i += 1;
     }
 
@@ -8045,13 +8053,13 @@ static _finline void _setHomePage(Cydia *self) {
 }
 
 - (void) _reloadData {
-    UIProgressHUD *hud([self addProgressHUD]);
-    [hud setText:(loaded_ ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
+    UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
+    [hud setText:UCLocalize("RELOADING_DATA")];
 
     [database_ yieldToSelector:@selector(reloadData) withObject:nil];
-    _trace();
 
-    [self removeProgressHUD:hud];
+    if (hud != nil)
+        [self removeProgressHUD:hud];
 
     size_t changes(0);
 
@@ -8073,7 +8081,7 @@ static _finline void _setHomePage(Cydia *self) {
     if (changes != 0) {
         NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
         [changesItem setBadgeValue:badge];
-        [changesItem setAnimatedBadge:YES];
+        [changesItem setAnimatedBadge:([essential_ count] > 0)];
 
         if ([self respondsToSelector:@selector(setApplicationBadge:)])
             [self setApplicationBadge:badge];
@@ -8095,7 +8103,6 @@ static _finline void _setHomePage(Cydia *self) {
 }
 
 - (void) updateData {
-    [database_ setVisible];
     [self _updateData];
 }
 
@@ -8123,7 +8130,8 @@ static _finline void _setHomePage(Cydia *self) {
 
     ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
     CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
-    if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
+    if (IsWildcat_)
+        [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
     [container_ presentModalViewController:navigation animated:YES];
 
     [progress
@@ -8158,10 +8166,11 @@ static _finline void _setHomePage(Cydia *self) {
 
     ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
     [page setDelegate:self];
-    CYNavigationController *confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
+    CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
     [confirm_ setDelegate:self];
 
-    if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
+    if (IsWildcat_)
+        [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
     [container_ presentModalViewController:confirm_ animated:YES];
 
     return true;
@@ -8227,7 +8236,8 @@ static _finline void _setHomePage(Cydia *self) {
         [navigation pushViewController:progress animated:YES];
     } else {
         navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
-        if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
+        if (IsWildcat_)
+            [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
         [container_ presentModalViewController:navigation animated:YES];
     }
 
@@ -8248,9 +8258,9 @@ static _finline void _setHomePage(Cydia *self) {
 
     CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
     [navController setViewControllers:[NSArray arrayWithObject:page]];
-    for (CYNavigationController *page in [tabbar_ viewControllers]) {
-        if (page != navController) [page setViewControllers:nil];
-    }
+    for (CYNavigationController *page in [tabbar_ viewControllers])
+        if (page != navController)
+            [page setViewControllers:nil];
 }
 
 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
@@ -8277,7 +8287,8 @@ static _finline void _setHomePage(Cydia *self) {
             _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
             withClass:[ManageController class]
         ] retain];
-        if (!IsWildcat_) queueDelegate_ = manage_;
+        if (!IsWildcat_)
+            queueDelegate_ = manage_;
     }
     return manage_;
 }
@@ -8297,12 +8308,13 @@ static _finline void _setHomePage(Cydia *self) {
 - (InstalledController *) installedController {
     if (installed_ == nil) {
         installed_ = [[InstalledController alloc] initWithDatabase:database_];
-        if (IsWildcat_) queueDelegate_ = installed_;
+        if (IsWildcat_)
+            queueDelegate_ = installed_;
     }
     return installed_;
 }
 
-- (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
+- (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
     int tag = [[viewController tabBarItem] tag];
     if (tag == tag_) {
         [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
@@ -8328,9 +8340,10 @@ static _finline void _setHomePage(Cydia *self) {
 }
 
 - (void) showSettings {
-    RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
-    CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
-    if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
+    RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
+    CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
+    if (IsWildcat_)
+        [nav setModalPresentationStyle:UIModalPresentationFormSheet];
     [container_ presentModalViewController:nav animated:YES];
 }
 
@@ -8351,7 +8364,8 @@ static _finline void _setHomePage(Cydia *self) {
 // Returns the navigation controller for the queuing badge.
 - (id) queueBadgeController {
     int index = [self indexOfTabWithTag:kManageTag];
-    if (index == -1) index = [self indexOfTabWithTag:kInstalledTag];
+    if (index == -1)
+        index = [self indexOfTabWithTag:kInstalledTag];
 
     return [[tabbar_ viewControllers] objectAtIndex:index];
 }
@@ -8359,16 +8373,7 @@ static _finline void _setHomePage(Cydia *self) {
 - (void) cancelAndClear:(bool)clear {
     @synchronized (self) {
         if (clear) {
-            // Clear all marks.
-            pkgCacheFile &cache([database_ cache]);
-            for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
-                // Unmark method taken from Synaptic Package Manager.
-                // Thanks for being sane, unlike Aptitude.
-                if (!cache[iterator].Keep()) {
-                    cache->MarkKeep(iterator, false);
-                    cache->SetReInstall(iterator, false);
-                }
-            }
+            [database_ clear];
 
             // Stop queuing.
             Queuing_ = false;
@@ -8379,8 +8384,7 @@ static _finline void _setHomePage(Cydia *self) {
             [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
         }
 
-        // Show the changes in the current view.
-        [(CYNavigationController *) [tabbar_ selectedViewController] reloadData];
+        [self _updateData];
         [queueDelegate_ queueStatusDidChange];
     }
 }
@@ -8438,6 +8442,10 @@ static _finline void _setHomePage(Cydia *self) {
     [super applicationWillSuspend];
 }
 
+- (BOOL) hudIsShowing {
+    return (huds_ > 0);
+}
+
 - (void) applicationSuspend:(__GSEvent *)event {
     // Use external process status API internally.
     // This is probably a really bad idea.
@@ -8448,17 +8456,17 @@ static _finline void _setHomePage(Cydia *self) {
         notify_cancel(notify_token);
     }
 
-    if (hud_ == nil && status == 0)
+    if (![self hudIsShowing] && status == 0)
         [super applicationSuspend:event];
 }
 
 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
-    if (hud_ == nil)
+    if (![self hudIsShowing])
         [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
 }
 
 - (void) _setSuspended:(BOOL)value {
-    if (hud_ == nil)
+    if (![self hudIsShowing])
         [super _setSuspended:value];
 }
 
@@ -8468,7 +8476,12 @@ static _finline void _setHomePage(Cydia *self) {
 
     [window_ setUserInteractionEnabled:NO];
     [hud show:YES];
-    [[container_ view] addSubview:hud];
+
+    UIViewController *target = container_;
+    while ([target modalViewController] != nil) target = [target modalViewController];
+    [[target view] addSubview:hud];
+
+    huds_++;
     return hud;
 }
 
@@ -8476,6 +8489,7 @@ static _finline void _setHomePage(Cydia *self) {
     [hud show:NO];
     [hud removeFromSuperview];
     [window_ setUserInteractionEnabled:YES];
+    huds_--;
 }
 
 - (CYViewController *) pageForPackage:(NSString *)name {
@@ -8551,36 +8565,46 @@ static _finline void _setHomePage(Cydia *self) {
 
 - (void) applicationWillResignActive:(UIApplication *)application {
     // Stop refreshing if you get a phone call or lock the device.
-    if ([container_ updating]) [container_ cancelUpdate];
+    if ([container_ updating])
+        [container_ cancelUpdate];
 
     if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
         [super applicationWillResignActive:application];
 }
 
-- (void) applicationDidFinishLaunching:(id)unused {
-    [CYBrowserController _initialize];
+- (void) addStashController {
+    stash_ = [[CYStashController alloc] init];
+    [window_ addSubview:[stash_ view]];
+}
 
-    [NSURLProtocol registerClass:[CydiaURLProtocol class]];
+- (void) removeStashController {
+    [[stash_ view] removeFromSuperview];
+    [stash_ release];
+}
 
-    Font12_ = [[UIFont systemFontOfSize:12] retain];
-    Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
-    Font14_ = [[UIFont systemFontOfSize:14] retain];
-    Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
-    Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
+- (void) stash {
+    [self setIdleTimerDisabled:YES];
 
-    tag_ = 0;
+    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
+    [self setStatusBarShowsProgress:YES];
+    UpdateExternalStatus(1);
 
-    essential_ = [[NSMutableArray alloc] initWithCapacity:4];
-    broken_ = [[NSMutableArray alloc] initWithCapacity:4];
+    [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
 
-    UIScreen *screen([UIScreen mainScreen]);
+    UpdateExternalStatus(0);
+    [self setStatusBarShowsProgress:NO];
 
-    window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
-    [window_ orderFront:self];
-    [window_ makeKey:self];
-    [window_ setHidden:NO];
+    [self removeStashController];
 
-    database_ = [Database sharedInstance];
+    if (ExecFork() == 0) {
+        execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
+        perror("launchctl stop");
+    }
+}
+
+- (void) setupTabBarController {
+    tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
+    [tabbar_ setDelegate:self];
 
     NSMutableArray *items([NSMutableArray arrayWithObjects:
         [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
@@ -8604,15 +8628,31 @@ static _finline void _setHomePage(Cydia *self) {
         [controllers addObject:controller];
     }
 
-    tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
     [tabbar_ setViewControllers:controllers];
-    [tabbar_ setDelegate:self];
-    [tabbar_ setSelectedIndex:0];
+}
 
-    container_ = [[CYContainer alloc] initWithDatabase:database_];
-    [container_ setUpdateDelegate:self];
-    [container_ setTabBarController:tabbar_];
-    [window_ addSubview:[container_ view]];
+- (void) applicationDidFinishLaunching:(id)unused {
+    [CYBrowserController _initialize];
+
+    [NSURLProtocol registerClass:[CydiaURLProtocol class]];
+
+    Font12_ = [[UIFont systemFontOfSize:12] retain];
+    Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
+    Font14_ = [[UIFont systemFontOfSize:14] retain];
+    Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
+    Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
+
+    tag_ = 0;
+
+    essential_ = [[NSMutableArray alloc] initWithCapacity:4];
+    broken_ = [[NSMutableArray alloc] initWithCapacity:4];
+
+    UIScreen *screen([UIScreen mainScreen]);
+
+    window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
+    [window_ orderFront:self];
+    [window_ makeKey:self];
+    [window_ setHidden:NO];
 
     if (
         readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
@@ -8626,48 +8666,89 @@ static _finline void _setHomePage(Cydia *self) {
         //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
         false
     ) {
-        [self setIdleTimerDisabled:YES];
-
-        hud_ = [self addProgressHUD];
-        [hud_ setText:@"Reorganizing:\n\nWill Automatically\nClose When Done"];
-        [self setStatusBarShowsProgress:YES];
-
-        [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
+        [self addStashController];
+        // XXX: this would be much cleaner as a yieldToSelector:
+        // that way the removeStashController could happen right here inline
+        // we also could no longer require the useless stash_ field anymore
+        [self performSelector:@selector(stash) withObject:nil afterDelay:0];
+        return;
+    }
 
-        [self setStatusBarShowsProgress:NO];
-        [self removeProgressHUD:hud_];
-        hud_ = nil;
+    database_ = [Database sharedInstance];
 
-        if (ExecFork() == 0) {
-            execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
-            perror("launchctl stop");
-        }
+    [self setupTabBarController];
 
-        return;
-    }
+    container_ = [[CYContainer alloc] initWithDatabase:database_];
+    [container_ setUpdateDelegate:self];
+    [container_ setTabBarController:tabbar_];
+    [window_ addSubview:[container_ view]];
 
     // Show pinstripes while loading data.
-    [[container_ view] setBackgroundColor:[UIColor performSelector:@selector(pinStripeColor)]];
+    [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
 
     [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
+_trace();
 }
 
 - (void) loadData {
+_trace();
     if (Role_ == nil) {
         [self showSettings];
         return;
     }
 
-    [UIKeyboard initImplementationNow];
+    [window_ setUserInteractionEnabled:NO];
 
-    [self reloadData];
+    UIView *container = [[[UIView alloc] init] autorelease];
+    [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
+
+    UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
+    [spinner startAnimating];
+    [container addSubview:spinner];
+
+    UILabel *label = [[[UILabel alloc] init] autorelease];
+    [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
+    [label setBackgroundColor:[UIColor clearColor]];
+    [label setTextColor:[UIColor blackColor]];
+    [label setShadowColor:[UIColor whiteColor]];
+    [label setShadowOffset:CGSizeMake(0, 1)];
+    [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
+    [container addSubview:label];
+
+    CGSize viewsize = [[tabbar_ view] frame].size;
+    CGSize spinnersize = [spinner bounds].size;
+    CGSize textsize = [[label text] sizeWithFont:[label font]];
+    float bothwidth = spinnersize.width + textsize.width + 5.0f;
+
+    CGRect containrect = {
+        CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
+        CGSizeMake(bothwidth, spinnersize.height)
+    };
+    CGRect textrect = {
+        CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
+        textsize
+    };
+    CGRect spinrect = {
+        CGPointZero,
+        spinnersize
+    };
+
+    [container setFrame:containrect];
+    [spinner setFrame:spinrect];
+    [label setFrame:textrect];
+    [[container_ view] addSubview:container];
 
+    [self reloadData];
     PrintTimes();
 
+    // Show the home page
+    [tabbar_ setSelectedIndex:0];
     _setHomePage(self);
+    [window_ setUserInteractionEnabled:YES];
 
     // XXX: does this actually slow anything down?
     [[container_ view] setBackgroundColor:[UIColor clearColor]];
+    [container removeFromSuperview];
 }
 
 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
@@ -8863,6 +8944,22 @@ int main(int argc, char *argv[]) { _pooled
 
     UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
 
+    CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
+    $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
+    CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
+
+    CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
+    $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
+    CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
+
+    if (mcc != NULL && mnc != NULL)
+        PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
+
+    if (mnc != NULL)
+        CFRelease(mnc);
+    if (mcc != NULL)
+        CFRelease(mcc);
+
     if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
         Build_ = [system objectForKey:@"ProductBuildVersion"];
     if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
@@ -8875,7 +8972,6 @@ int main(int argc, char *argv[]) { _pooled
     Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
     _trace();
     SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
-    _trace();
 
     if (Metadata_ == NULL)
         Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
@@ -8949,7 +9045,10 @@ int main(int argc, char *argv[]) { _pooled
 
     if (lang != NULL)
         _config->Set("APT::Acquire::Translation", lang);
-    _config->Set("Acquire::http::Timeout", 15);
+
+    // XXX: this timeout might be important :(
+    //_config->Set("Acquire::http::Timeout", 15);
+
     _config->Set("Acquire::http::MaxParallel", 3);
     /* }}} */
     /* Color Choices {{{ */
@@ -8978,6 +9077,7 @@ int main(int argc, char *argv[]) { _pooled
     /* }}} */
 
     Colon_ = UCLocalize("COLON_DELIMITED");
+    Elision_ = UCLocalize("ELISION");
     Error_ = UCLocalize("ERROR");
     Warning_ = UCLocalize("WARNING");