]> git.saurik.com Git - cydia.git/blobdiff - MobileCydia.mm
If you have cydia. access, get Token_.
[cydia.git] / MobileCydia.mm
index 4737baf2e8e5f2f4f6078a4f87955d5a592981fc..776c31cefada61e26963eec3f50dd854beb5fd1d 100644 (file)
@@ -120,18 +120,20 @@ extern "C" {
 
 #include <Cytore.hpp>
 
+#include <CydiaSubstrate/CydiaSubstrate.h>
 #include "Menes/Menes.h"
 
 #include "CyteKit/PerlCompatibleRegEx.hpp"
+#include "CyteKit/TableViewCell.h"
 #include "CyteKit/WebScriptObject-Cyte.h"
 #include "CyteKit/WebViewController.h"
 #include "CyteKit/stringWithUTF8Bytes.h"
 
+#include "Cydia/MIMEAddress.h"
+#include "Cydia/LoadingViewController.h"
 #include "Cydia/ProgressEvent.h"
 
 #include "SDURLCache/SDURLCache.h"
-
-#include <CydiaSubstrate/CydiaSubstrate.h>
 /* }}} */
 
 /* Profiler {{{ */
@@ -204,15 +206,7 @@ void PrintTimes() {
 #define _end }
 /* }}} */
 
-#define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
-
-#define CYPoolStart() \
-    NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
-    do
-#define CYPoolEnd() \
-    while (false); \
-    [_pool release];
-
+#include "Version.h"
 #define Cydia_ CYDIA_VERSION
 
 #define lprintf(args...) fprintf(stderr, args)
@@ -273,88 +267,16 @@ static _finline void UpdateExternalStatus(uint64_t newStatus) {
     notify_post("com.saurik.Cydia.status");
 }
 
+static CGFloat CYStatusBarHeight(UIInterfaceOrientation orientation) {
+    CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
+    return UIInterfaceOrientationIsPortrait(orientation) ? size.height : size.width;
+}
+
 /* NSForcedOrderingSearch doesn't work on the iPhone */
 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
 
-/* Radix Sort {{{ */
-typedef uint32_t (*SKRadixFunction)(id, void *);
-
-@interface NSMutableArray (Radix)
-- (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
-@end
-
-struct RadixItem_ {
-    size_t index;
-    uint32_t key;
-};
-
-@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;
-    static const size_t bits = 11;
-    static const size_t slots = 1 << bits;
-    static const size_t passes = (width + (bits - 1)) / bits;
-
-    size_t *hist(new size_t[slots]);
-
-    for (size_t pass(0); pass != passes; ++pass) {
-        memset(hist, 0, sizeof(size_t) * slots);
-
-        for (size_t i(0); i != count; ++i) {
-            uint32_t key(lhs[i].key);
-            key >>= pass * bits;
-            key &= _not(uint32_t) >> width - bits;
-            ++hist[key];
-        }
-
-        size_t offset(0);
-        for (size_t i(0); i != slots; ++i) {
-            size_t local(offset);
-            offset += hist[i];
-            hist[i] = local;
-        }
-
-        for (size_t i(0); i != count; ++i) {
-            uint32_t key(lhs[i].key);
-            key >>= pass * bits;
-            key &= _not(uint32_t) >> width - bits;
-            rhs[hist[key]++] = lhs[i];
-        }
-
-        RadixItem_ *tmp(lhs);
-        lhs = rhs;
-        rhs = tmp;
-    }
-
-    delete [] hist;
-
-    const void **values(new const void *[count]);
-    for (size_t i(0); i != count; ++i)
-        values[i] = [self objectAtIndex:lhs[i].index];
-    CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
-    delete [] values;
-
-    delete [] swap;
-}
-
-@end
-/* }}} */
 /* Insertion Sort {{{ */
 
 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
@@ -674,74 +596,6 @@ struct NSStringMapEqual :
 };
 /* }}} */
 
-/* Mime Addresses {{{ */
-@interface Address : NSObject {
-    _H<NSString> name_;
-    _H<NSString> address_;
-}
-
-- (NSString *) name;
-- (NSString *) address;
-
-- (void) setAddress:(NSString *)address;
-
-+ (Address *) addressWithString:(NSString *)string;
-- (Address *) initWithString:(NSString *)string;
-
-@end
-
-@implementation Address
-
-- (NSString *) name {
-    return name_;
-}
-
-- (NSString *) address {
-    return address_;
-}
-
-- (void) setAddress:(NSString *)address {
-    address_ = address;
-}
-
-+ (Address *) addressWithString:(NSString *)string {
-    return [[[Address alloc] initWithString:string] autorelease];
-}
-
-+ (NSArray *) _attributeKeys {
-    return [NSArray arrayWithObjects:
-        @"address",
-        @"name",
-    nil];
-}
-
-- (NSArray *) attributeKeys {
-    return [[self class] _attributeKeys];
-}
-
-+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
-    return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
-}
-
-- (Address *) initWithString:(NSString *)string {
-    if ((self = [super init]) != nil) {
-        const char *data = [string UTF8String];
-        size_t size = [string length];
-
-        static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
-
-        if (address_r(data, size)) {
-            name_ = address_r[1];
-            address_ = address_r[2];
-        } else {
-            name_ = string;
-            address_ = nil;
-        }
-    } return self;
-}
-
-@end
-/* }}} */
 /* CoreGraphics Primitives {{{ */
 class CYColor {
   private:
@@ -855,7 +709,10 @@ static NSString *Idiom_;
 static _H<NSMutableDictionary> SessionData_;
 static _H<NSObject> HostConfig_;
 static _H<NSMutableSet> BridgedHosts_;
+static _H<NSMutableSet> TokenHosts_;
+static _H<NSMutableSet> InsecureHosts_;
 static _H<NSMutableSet> PipelinedHosts_;
+static _H<NSMutableSet> CachedURLs_;
 
 static NSString *kCydiaProgressEventTypeError = @"Error";
 static NSString *kCydiaProgressEventTypeInformation = @"Information";
@@ -928,7 +785,7 @@ bool isSectionVisible(NSString *section) {
     return hidden == nil || ![hidden boolValue];
 }
 
-static id CYIOGetValue(const char *path, NSString *property) {
+static NSObject *CYIOGetValue(const char *path, NSString *property) {
     io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
     if (entry == MACH_PORT_NULL)
         return nil;
@@ -941,7 +798,7 @@ static id CYIOGetValue(const char *path, NSString *property) {
     return [(id) value autorelease];
 }
 
-static NSString *CYHex(NSData *data, bool reverse, bool capital) {
+static NSString *CYHex(NSData *data, bool reverse = false) {
     if (data == nil)
         return nil;
 
@@ -951,7 +808,7 @@ static NSString *CYHex(NSData *data, bool reverse, bool capital) {
 
     char string[length * 2 + 1];
     for (size_t i(0); i != length; ++i)
-        sprintf(string + i * 2, capital ? "%.2X" : "%.2x", bytes[reverse ? length - i - 1 : i]);
+        sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
 
     return [NSString stringWithUTF8String:string];
 }
@@ -1414,6 +1271,7 @@ static void PackageImport(const void *key, const void *value, void *context) {
     CYString uri_;
     CYString distribution_;
     CYString type_;
+    CYString base_;
     CYString version_;
 
     _H<NSString> host_;
@@ -1438,6 +1296,9 @@ static void PackageImport(const void *key, const void *value, void *context) {
 - (NSString *) uri;
 - (NSString *) distribution;
 - (NSString *) type;
+
+- (NSString *) base;
+
 - (NSString *) key;
 - (NSString *) host;
 
@@ -1458,6 +1319,8 @@ static void PackageImport(const void *key, const void *value, void *context) {
     distribution_.clear();
     type_.clear();
 
+    base_.clear();
+
     description_.clear();
     label_.clear();
     origin_.clear();
@@ -1506,6 +1369,8 @@ static void PackageImport(const void *key, const void *value, void *context) {
 
     debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
     if (dindex != NULL) {
+        base_.set(pool, dindex->MetaIndexURI(""));
+
         FileFd fd;
         if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
             _error->Discard();
@@ -1548,8 +1413,7 @@ static void PackageImport(const void *key, const void *value, void *context) {
         host_ = [host_ lowercaseString];
 
     if (host_ != nil)
-        // XXX: this is due to a bug in _H<>
-        authority_ = (id) host_;
+        authority_ = host_;
     else
         authority_ = [url path];
 }
@@ -1611,6 +1475,10 @@ static void PackageImport(const void *key, const void *value, void *context) {
     return type_;
 }
 
+- (NSString *) base {
+    return base_;
+}
+
 - (NSString *) key {
     return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
 }
@@ -1826,6 +1694,8 @@ struct ParsedPackage {
 
     apr_pool_t *pool_;
 
+    uint32_t rank_;
+
     _transient Database *database_;
 
     pkgCache::VerIterator version_;
@@ -1863,7 +1733,7 @@ struct ParsedPackage {
 
 - (NSString *) uri;
 
-- (Address *) maintainer;
+- (MIMEAddress *) maintainer;
 - (size_t) size;
 - (NSString *) longDescription;
 - (NSString *) shortDescription;
@@ -1899,7 +1769,7 @@ struct ParsedPackage {
 - (UIImage *) icon;
 - (NSString *) homepage;
 - (NSString *) depiction;
-- (Address *) author;
+- (MIMEAddress *) author;
 
 - (NSString *) support;
 
@@ -1909,7 +1779,8 @@ struct ParsedPackage {
 
 - (Source *) source;
 
-- (BOOL) matches:(NSString *)text;
+- (uint32_t) rank;
+- (BOOL) matches:(NSArray *)query;
 
 - (bool) hasSupportingRole;
 - (BOOL) hasTag:(NSString *)tag;
@@ -1926,7 +1797,7 @@ struct ParsedPackage {
 - (void) install;
 - (void) remove;
 
-- (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
+- (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
 - (bool) isVisibleInSection:(NSString *)section;
@@ -2405,14 +2276,14 @@ struct PackageNameOrdering :
 #endif
 }
 
-- (Address *) maintainer {
+- (MIMEAddress *) maintainer {
 @synchronized (database_) {
     if ([database_ era] != era_ || file_.end())
         return nil;
 
     pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
     const std::string &maintainer(parser->Maintainer());
-    return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
+    return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
 } }
 
 - (size_t) size {
@@ -2640,12 +2511,12 @@ struct PackageNameOrdering :
     return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
 }
 
-- (Address *) sponsor {
-    return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
+- (MIMEAddress *) sponsor {
+    return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
 }
 
-- (Address *) author {
-    return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
+- (MIMEAddress *) author {
+    return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
 }
 
 - (NSString *) support {
@@ -2813,30 +2684,50 @@ struct PackageNameOrdering :
     return source_ == (Source *) [NSNull null] ? nil : source_;
 }
 
-- (BOOL) matches:(NSString *)text {
-    if (text == nil)
+- (uint32_t) rank {
+    return rank_;
+}
+
+- (BOOL) matches:(NSArray *)query {
+    if (query == nil || [query count] == 0)
         return NO;
 
+    rank_ = 0;
+
+    NSString *string;
     NSRange range;
+    NSUInteger length;
 
-    range = [[self id] rangeOfString:text options:MatchCompareOptions_];
-    if (range.location != NSNotFound)
-        return YES;
+    [self parse];
 
-    range = [[self name] rangeOfString:text options:MatchCompareOptions_];
-    if (range.location != NSNotFound)
-        return YES;
+    string = [self id];
+    length = [string length];
 
-    [self parse];
+    for (NSString *term in query) {
+        range = [string rangeOfString:term options:MatchCompareOptions_];
+        if (range.location != NSNotFound)
+            rank_ -= 10 * 100000 / length;
+    }
 
-    NSString *description([self shortDescription]);
-    NSUInteger length([description length]);
+    string = [self name];
 
-    range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_ range:NSMakeRange(0, std::min<NSUInteger>(length, 100))];
-    if (range.location != NSNotFound)
-        return YES;
+    for (NSString *term in query) {
+        range = [string rangeOfString:term options:MatchCompareOptions_];
+        if (range.location != NSNotFound)
+            rank_ -= 6 * 100000 / length;
+    }
 
-    return NO;
+    string = [self shortDescription];
+    length = [string length];
+    NSUInteger stop(std::min<NSUInteger>(length, 100));
+
+    for (NSString *term in query) {
+        range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
+        if (range.location != NSNotFound)
+            rank_ -= 2 * 100000 / length;
+    }
+
+    return rank_ != 0;
 }
 
 - (bool) hasSupportingRole {
@@ -2940,7 +2831,7 @@ struct PackageNameOrdering :
     cache->MarkDelete(iterator_, true);
 } }
 
-- (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
+- (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
     _profile(Package$isUnfilteredAndSearchedForBy)
         bool value(true);
 
@@ -2949,7 +2840,7 @@ struct PackageNameOrdering :
         _end
 
         _profile(Package$isUnfilteredAndSearchedForBy$Match)
-            value &= [self matches:search];
+            value &= [self matches:query];
         _end
 
         return value;
@@ -3108,10 +2999,19 @@ struct PackageNameOrdering :
 /* }}} */
 
 static NSString *Colon_;
-static NSString *Elision_;
+NSString *Elision_;
 static NSString *Error_;
 static NSString *Warning_;
 
+class CydiaLogCleaner :
+    public pkgArchiveCleaner
+{
+  protected:
+    virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
+        unlink(File);
+    }
+};
+
 /* Database Implementation {{{ */
 @implementation Database
 
@@ -3140,7 +3040,7 @@ static NSString *Warning_;
     [super dealloc];
 }
 
-- (void) _readCydia:(NSNumber *)fd { _pooled
+- (void) _readCydia:(NSNumber *)fd {
     __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
     std::istream is(&ib);
     std::string line;
@@ -3148,6 +3048,8 @@ static NSString *Warning_;
     static Pcre finish_r("^finish:([^:]*)$");
 
     while (std::getline(is, line)) {
+        NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
+
         const char *data(line.c_str());
         size_t size = line.size();
         lprintf("C:%s\n", data);
@@ -3158,12 +3060,14 @@ static NSString *Warning_;
             if (index != INT_MAX && index > Finish_)
                 Finish_ = index;
         }
+
+        [pool release];
     }
 
     _assume(false);
 }
 
-- (void) _readStatus:(NSNumber *)fd { _pooled
+- (void) _readStatus:(NSNumber *)fd {
     __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
     std::istream is(&ib);
     std::string line;
@@ -3172,6 +3076,8 @@ static NSString *Warning_;
     static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
 
     while (std::getline(is, line)) {
+        NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
+
         const char *data(line.c_str());
         size_t size(line.size());
         lprintf("S:%s\n", data);
@@ -3211,21 +3117,27 @@ static NSString *Warning_;
                 lprintf("E:unknown pmstatus\n");
         } else
             lprintf("E:unknown status\n");
+
+        [pool release];
     }
 
     _assume(false);
 }
 
-- (void) _readOutput:(NSNumber *)fd { _pooled
+- (void) _readOutput:(NSNumber *)fd {
     __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
     std::istream is(&ib);
     std::string line;
 
     while (std::getline(is, line)) {
+        NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
+
         lprintf("O:%s\n", line.c_str());
 
         CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
         [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
+
+        [pool release];
     }
 
     _assume(false);
@@ -3371,7 +3283,7 @@ static NSString *Warning_;
     return [self popErrorWithTitle:title] || !success;
 }
 
-- (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
+- (void) reloadDataWithInvocation:(NSInvocation *)invocation {
 @synchronized (self) {
     ++era_;
 
@@ -3507,9 +3419,9 @@ static NSString *Warning_;
             packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
         _trace();*/
 
-        [(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)];
+        [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
+        [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
+        [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
 
         /*_trace();
         PrintTimes();
@@ -3537,7 +3449,7 @@ static NSString *Warning_;
 
         _trace();
     }
-} } CYPoolEnd() _trace(); }
+} }
 
 - (void) clear {
 @synchronized (self) {
@@ -3574,15 +3486,7 @@ static NSString *Warning_;
     pkgAcquire fetcher;
     fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
 
-    class LogCleaner :
-        public pkgArchiveCleaner
-    {
-      protected:
-        virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
-            unlink(File);
-        }
-    } cleaner;
-
+    CydiaLogCleaner cleaner;
     if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
         return false;
 
@@ -3713,13 +3617,13 @@ static NSString *Warning_;
     bool success(ListUpdate(status, list, PulseInterval_));
     if (status.WasCancelled())
         _error->Discard();
-    else
+    else {
         [self popErrorWithTitle:title forOperation:success];
+        [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
+        Changed_ = true;
+    }
 
     [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
-
-    [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
-    Changed_ = true;
 }
 
 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
@@ -3935,10 +3839,14 @@ static _H<NSMutableSet> Diversions_;
     if (false);
     else if (selector == @selector(addBridgedHost:))
         return @"addBridgedHost";
+    else if (selector == @selector(addInsecureHost:))
+        return @"addInsecureHost";
     else if (selector == @selector(addInternalRedirect::))
         return @"addInternalRedirect";
     else if (selector == @selector(addPipelinedHost:scheme:))
         return @"addPipelinedHost";
+    else if (selector == @selector(addTokenHost:))
+        return @"addTokenHost";
     else if (selector == @selector(addTrivialSource:))
         return @"addTrivialSource";
     else if (selector == @selector(close))
@@ -3955,6 +3863,8 @@ static _H<NSMutableSet> Diversions_;
         return @"getKernelString";
     else if (selector == @selector(getInstalledPackages))
         return @"getInstalledPackages";
+    else if (selector == @selector(getIORegistryEntry::))
+        return @"getIORegistryEntry";
     else if (selector == @selector(getLocaleIdentifier))
         return @"getLocaleIdentifier";
     else if (selector == @selector(getPreferredLanguages))
@@ -4007,6 +3917,8 @@ static _H<NSMutableSet> Diversions_;
         return @"statfs";
     else if (selector == @selector(supports:))
         return @"supports";
+    else if (selector == @selector(unload))
+        return @"unload";
     else
         return nil;
 }
@@ -4019,6 +3931,10 @@ static _H<NSMutableSet> Diversions_;
     return [feature isEqualToString:@"window.open"];
 }
 
+- (void) unload {
+    [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
+}
+
 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
     [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
 }
@@ -4057,6 +3973,16 @@ static _H<NSMutableSet> Diversions_;
     return [NSString stringWithCString:value];
 }
 
+- (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
+    NSObject *value(CYIOGetValue([path UTF8String], entry));
+
+    if (value != nil)
+        if ([value isKindOfClass:[NSData class]])
+            value = CYHex((NSData *) value);
+
+    return value;
+}
+
 - (id) getSessionValue:(NSString *)key {
 @synchronized (SessionData_) {
     return [SessionData_ objectForKey:key];
@@ -4075,6 +4001,16 @@ static _H<NSMutableSet> Diversions_;
     [BridgedHosts_ addObject:host];
 } }
 
+- (void) addInsecureHost:(NSString *)host {
+@synchronized (HostConfig_) {
+    [InsecureHosts_ addObject:host];
+} }
+
+- (void) addTokenHost:(NSString *)host {
+@synchronized (HostConfig_) {
+    [TokenHosts_ addObject:host];
+} }
+
 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
 @synchronized (HostConfig_) {
     if (scheme != (id) [WebUndefined undefined])
@@ -4293,121 +4229,24 @@ static _H<NSMutableSet> Diversions_;
 @end
 /* }}} */
 
-/* @ Loading... Indicator {{{ */
-@interface CYLoadingIndicator : UIView {
-    _H<UIActivityIndicatorView> spinner_;
-    _H<UILabel> label_;
-    _H<UIView> container_;
-}
-
-@property (readonly, nonatomic) UILabel *label;
-@property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
-
-@end
-
-@implementation CYLoadingIndicator
-
-- (id) initWithFrame:(CGRect)frame {
-    if ((self = [super initWithFrame:frame]) != nil) {
-        container_ = [[[UIView alloc] init] autorelease];
-        [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
-
-        spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
-        [spinner_ startAnimating];
-        [container_ addSubview:spinner_];
-
-        label_ = [[[UILabel alloc] init] autorelease];
-        [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
-        [label_ setBackgroundColor:[UIColor clearColor]];
-        [label_ setTextColor:[UIColor blackColor]];
-        [label_ setShadowColor:[UIColor whiteColor]];
-        [label_ setShadowOffset:CGSizeMake(0, 1)];
-        [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
-        [container_ addSubview:label_];
-
-        CGSize viewsize = frame.size;
-        CGSize spinnersize = [spinner_ bounds].size;
-        CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
-        float bothwidth = spinnersize.width + textsize.width + 5.0f;
-
-        CGRect containrect = {
-            CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
-            CGSizeMake(bothwidth, spinnersize.height)
-        };
-        CGRect textrect = {
-            CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
-            textsize
-        };
-        CGRect spinrect = {
-            CGPointZero,
-            spinnersize
-        };
-
-        [container_ setFrame:containrect];
-        [spinner_ setFrame:spinrect];
-        [label_ setFrame:textrect];
-        [self addSubview:container_];
-    } return self;
-}
-
-- (UILabel *) label {
-    return label_;
-}
-
-- (UIActivityIndicatorView *) activityIndicatorView {
-    return spinner_;
-}
-
-@end
-/* }}} */
-/* Emulated Loading Controller {{{ */
-@interface CYEmulatedLoadingController : CyteViewController {
-    _transient Database *database_;
-    _H<CYLoadingIndicator> indicator_;
-    _H<UITabBar> tabbar_;
-    _H<UINavigationBar> navbar_;
-}
-
+@interface NSURL (CydiaSecure)
 @end
 
-@implementation CYEmulatedLoadingController
-
-- (id) initWithDatabase:(Database *)database {
-    if ((self = [super init]) != nil) {
-        database_ = database;
-    } return self;
-}
-
-- (void) loadView {
-    [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
-
-    UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
-    [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
-    [[self view] addSubview:table];
-
-    indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
-    [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
-    [[self view] addSubview:indicator_];
+@implementation NSURL (CydiaSecure)
 
-    tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
-    [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
-    [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
-    [[self view] addSubview:tabbar_];
+- (bool) isCydiaSecure {
+    if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
+        return true;
 
-    navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
-    [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
-    [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
-    [[self view] addSubview:navbar_];
-}
+    @synchronized (HostConfig_) {
+        if ([InsecureHosts_ containsObject:[self host]])
+            return true;
+    }
 
-- (void) releaseSubviews {
-    indicator_ = nil;
-    tabbar_ = nil;
-    navbar_ = nil;
+    return false;
 }
 
 @end
-/* }}} */
 
 /* Cydia Browser Controller {{{ */
 @implementation CydiaWebViewController
@@ -4446,19 +4285,37 @@ static _H<NSMutableSet> Diversions_;
         [window setValue:cydia_ forKey:@"cydia"];
 }
 
+- (void) _setupMail:(MFMailComposeViewController *)controller {
+    [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
+
+    system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
+    [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
+}
+
 - (NSURL *) URLWithURL:(NSURL *)url {
     return [Diversion divertURL:url];
 }
 
 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
+    NSURL *url([request URL]);
+    NSString *host([url host]);
+
     NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
 
-    if (System_ != NULL)
+    if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
         [copy setValue:System_ forHTTPHeaderField:@"X-System"];
-    if (Machine_ != NULL)
+    if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
         [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
-    if (Token_ != nil)
-        [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
+
+    bool token;
+    @synchronized (HostConfig_) {
+        token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
+    }
+
+    if ([url isCydiaSecure] && token) {
+        if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
+            [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
+    }
 
     return copy;
 }
@@ -4468,22 +4325,22 @@ static _H<NSMutableSet> Diversions_;
     [cydia_ setDelegate:delegate];
 }
 
-- (id) init {
-    if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
-        cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
-
-        WebView *webview([[webview_ _documentView] webView]);
+- (NSString *) applicationNameForUserAgent {
+    NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
 
-        NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
+    if (Safari_ != nil)
+        application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
+    if (Build_ != nil)
+        application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
+    if (Product_ != nil)
+        application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
 
-        if (Safari_ != nil)
-            application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
-        if (Build_ != nil)
-            application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
-        if (Product_ != nil)
-            application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
+    return application;
+}
 
-        [webview setApplicationNameForUserAgent:application];
+- (id) init {
+    if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
+        cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
     } return self;
 }
 
@@ -4958,7 +4815,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     ProgressDelegate
 > {
     _transient Database *database_;
-    _H<CydiaProgressData> progress_;
+    _H<CydiaProgressData, 1> progress_;
     unsigned cancel_;
 }
 
@@ -4975,7 +4832,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) dealloc {
     [database_ setProgressDelegate:nil];
-    [progress_ setDelegate:nil];
     [super dealloc];
 }
 
@@ -5223,71 +5079,9 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 @end
 /* }}} */
 
-/* Cell Content View {{{ */
-@protocol ContentDelegate
-- (void) drawContentRect:(CGRect)rect;
-@end
-
-@interface ContentView : UIView {
-    _transient id<ContentDelegate> delegate_;
-}
-
-@end
-
-@implementation ContentView
-
-- (id) initWithFrame:(CGRect)frame {
-    if ((self = [super initWithFrame:frame]) != nil) {
-        [self setNeedsDisplayOnBoundsChange:YES];
-    } return self;
-}
-
-- (void) setDelegate:(id<ContentDelegate>)delegate {
-    delegate_ = delegate;
-}
-
-- (void) drawRect:(CGRect)rect {
-    [super drawRect:rect];
-    [delegate_ drawContentRect:rect];
-}
-
-@end
-/* }}} */
-/* Cydia TableView Cell {{{ */
-@interface CYTableViewCell : UITableViewCell {
-    _H<ContentView> content_;
-    bool highlighted_;
-}
-
-@end
-
-@implementation CYTableViewCell
-
-- (void) _updateHighlightColorsForView:(UIView *)view highlighted:(BOOL)highlighted {
-    //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
-
-    if (view == (UIView *) 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 : CYTableViewCell <
-    ContentDelegate
+@interface PackageCell : CyteTableViewCell <
+    CyteTableViewCellDelegate
 > {
     _H<UIImage> icon_;
     _H<NSString> name_;
@@ -5297,10 +5091,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     _H<UIImage> badge_;
     _H<Package> package_;
     _H<UIImage> placard_;
+    bool summarized_;
 }
 
 - (PackageCell *) init;
-- (void) setPackage:(Package *)package;
+- (void) setPackage:(Package *)package asSummary:(bool)summary;
 
 - (void) drawContentRect:(CGRect)rect;
 
@@ -5314,7 +5109,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         UIView *content([self contentView]);
         CGRect bounds([content bounds]);
 
-        content_ = [[[ContentView alloc] initWithFrame:bounds] autorelease];
+        content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
         [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
         [content addSubview:content_];
 
@@ -5327,7 +5122,9 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
 }
 
-- (void) setPackage:(Package *)package {
+- (void) setPackage:(Package *)package asSummary:(bool)summary {
+    summarized_ = summary;
+
     icon_ = nil;
     name_ = nil;
     description_ = nil;
@@ -5341,12 +5138,19 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     Source *source = [package source];
 
     icon_ = [package icon];
-    name_ = [package name];
 
-    if (IsWildcat_)
-        description_ = [package longDescription];
-    if (description_ == nil)
-        description_ = [package shortDescription];
+    if (NSString *name = [package name])
+        name_ = [NSString stringWithString:name];
+
+    NSString *description(nil);
+
+    if (description == nil && IsWildcat_)
+        description = [package longDescription];
+    if (description == nil)
+        description = [package shortDescription];
+
+    if (description != nil)
+        description_ = [NSString stringWithString:description];
 
     commercial_ = [package isCommercial];
 
@@ -5408,25 +5212,19 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [content_ setNeedsDisplay];
 }
 
-- (void) drawContentRect:(CGRect)rect {
+- (void) drawSummaryContentRect:(CGRect)rect {
     bool highlighted(highlighted_);
     float width([self bounds].size.width);
 
-#if 0
-    CGContextRef context(UIGraphicsGetCurrentContext());
-    [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
-    CGContextFillRect(context, rect);
-#endif
-
     if (icon_ != nil) {
         CGRect rect;
         rect.size = [(UIImage *) icon_ size];
 
-        rect.size.width /= 2;
-        rect.size.height /= 2;
+        rect.size.width /= 4;
+        rect.size.height /= 4;
 
-        rect.origin.x = 25 - rect.size.width / 2;
-        rect.origin.y = 25 - rect.size.height / 2;
+        rect.origin.x = 14 - rect.size.width / 4;
+        rect.origin.y = 14 - rect.size.height / 4;
 
         [icon_ drawInRect:rect];
     }
@@ -5435,11 +5233,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         CGRect rect;
         rect.size = [(UIImage *) badge_ size];
 
-        rect.size.width /= 2;
-        rect.size.height /= 2;
+        rect.size.width /= 4;
+        rect.size.height /= 4;
 
-        rect.origin.x = 36 - rect.size.width / 2;
-        rect.origin.y = 36 - rect.size.height / 2;
+        rect.origin.x = 20 - rect.size.width / 4;
+        rect.origin.y = 20 - rect.size.height / 4;
 
         [badge_ drawInRect:rect];
     }
@@ -5449,22 +5247,70 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     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];
+    [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
 
-    if (!highlighted)
-        UISetColor(commercial_ ? Purplish_ : Gray_);
+    if (placard_ != nil)
+        [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
+}
+
+- (void) drawNormalContentRect:(CGRect)rect {
+    bool highlighted(highlighted_);
+    float width([self bounds].size.width);
+
+    if (icon_ != nil) {
+        CGRect rect;
+        rect.size = [(UIImage *) icon_ size];
+
+        rect.size.width /= 2;
+        rect.size.height /= 2;
+
+        rect.origin.x = 25 - rect.size.width / 2;
+        rect.origin.y = 25 - rect.size.height / 2;
+
+        [icon_ drawInRect:rect];
+    }
+
+    if (badge_ != nil) {
+        CGRect rect;
+        rect.size = [(UIImage *) badge_ size];
+
+        rect.size.width /= 2;
+        rect.size.height /= 2;
+
+        rect.origin.x = 36 - rect.size.width / 2;
+        rect.origin.y = 36 - rect.size.height / 2;
+
+        [badge_ drawInRect:rect];
+    }
+
+    if (highlighted)
+        UISetColor(White_);
+
+    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 (!highlighted)
+        UISetColor(commercial_ ? Purplish_ : Gray_);
     [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
 
     if (placard_ != nil)
         [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
 }
 
+- (void) drawContentRect:(CGRect)rect {
+    if (summarized_)
+        [self drawSummaryContentRect:rect];
+    else
+        [self drawNormalContentRect:rect];
+}
+
 @end
 /* }}} */
 /* Section Cell {{{ */
-@interface SectionCell : CYTableViewCell <
-    ContentDelegate
+@interface SectionCell : CyteTableViewCell <
+    CyteTableViewCellDelegate
 > {
     _H<NSString> basic_;
     _H<NSString> section_;
@@ -5490,7 +5336,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         UIView *content([self contentView]);
         CGRect bounds([content bounds]);
 
-        content_ = [[[ContentView alloc] initWithFrame:bounds] autorelease];
+        content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
         [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
         [content addSubview:content_];
         [content_ setBackgroundColor:[UIColor whiteColor]];
@@ -5590,7 +5436,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     _H<Package> package_;
     _H<NSString> name_;
     _H<NSMutableArray> files_;
-    _H<UITableView> list_;
+    _H<UITableView, 2> list_;
 }
 
 - (id) initWithDatabase:(Database *)database;
@@ -5600,12 +5446,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 @implementation FileTable
 
-- (void) dealloc {
-    [(UITableView *) list_ setDataSource:nil];
-    [list_ setDelegate:nil];
-    [super dealloc];
-}
-
 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
     return files_ == nil ? 0 : [files_ count];
 }
@@ -5651,6 +5491,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) releaseSubviews {
     list_ = nil;
+
+    [super releaseSubviews];
 }
 
 - (id) initWithDatabase:(Database *)database {
@@ -5880,26 +5722,30 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 > {
     _transient Database *database_;
     unsigned era_;
-    _H<NSMutableArray> packages_;
+    _H<NSArray> packages_;
     _H<NSMutableArray> sections_;
-    _H<UITableView> list_;
+    _H<UITableView, 2> list_;
     _H<NSMutableArray> index_;
     _H<NSMutableDictionary> indices_;
     _H<NSString> title_;
+    unsigned reloading_;
 }
 
 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
 - (void) setDelegate:(id)delegate;
 - (void) resetCursor;
+- (void) clearData;
 
 @end
 
 @implementation PackageListController
 
-- (void) dealloc {
-    [list_ setDataSource:nil];
-    [list_ setDelegate:nil];
-    [super dealloc];
+- (bool) isSummarized {
+    return false;
+}
+
+- (bool) showsSections {
+    return true;
 }
 
 - (void) deselectWithAnimation:(BOOL)animated {
@@ -5927,15 +5773,27 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [self resizeForKeyboardBounds:bounds duration:0];
 }
 
+- (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
+    if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
+        *curve = UIViewAnimationCurveEaseInOut;
+    else
+        [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
+
+    if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
+        *duration = 0.3;
+    else
+        [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
+}
+
 - (void) keyboardWillShow:(NSNotification *)notification {
     CGRect bounds;
     CGPoint center;
-    NSTimeInterval duration;
-    UIViewAnimationCurve curve;
     [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
     [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
-    [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
-    [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
+
+    NSTimeInterval duration;
+    UIViewAnimationCurve curve;
+    [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
 
     CGRect kbframe = CGRectMake(round(center.x - bounds.size.width / 2.0), round(center.y - bounds.size.height / 2.0), bounds.size.width, bounds.size.height);
     UIViewController *base = self;
@@ -5944,14 +5802,16 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
     CGRect intersection = CGRectIntersection(viewframe, kbframe);
 
+    if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
+        intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
+
     [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
 }
 
 - (void) keyboardWillHide:(NSNotification *)notification {
     NSTimeInterval duration;
     UIViewAnimationCurve curve;
-    [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
-    [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
+    [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
 
     [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
 }
@@ -6021,7 +5881,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
     if (cell == nil)
         cell = [[[PackageCell alloc] init] autorelease];
-    [cell setPackage:[self packageAtIndexPath:path]];
+    [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
     return cell;
 }
 
@@ -6032,8 +5892,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
-    // XXX: is 20 the most optimal number here?
-    return [packages_ count] > 20 ? index_ : nil;
+    if ([self showsSections])
+        return nil;
+
+    return index_;
 }
 
 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
@@ -6046,6 +5908,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     return index;
 }
 
+- (void) updateHeight {
+    [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
+}
+
 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
     if ((self = [super init]) != nil) {
         database_ = database;
@@ -6061,56 +5927,88 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
         indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
 
-        packages_ = [NSMutableArray arrayWithCapacity:16];
+        packages_ = [NSArray array];
         sections_ = [NSMutableArray arrayWithCapacity:16];
+    } return self;
+}
 
-        list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
-        [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
-        [list_ setRowHeight:73];
-        [[self view] addSubview:list_];
+- (void) loadView {
+    [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
 
-        [(UITableView *) list_ setDataSource:self];
-        [list_ setDelegate:self];
-    } return self;
+    list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
+    [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
+    [[self view] addSubview:list_];
+
+    // XXX: is 20 the most optimal number here?
+    [list_ setSectionIndexMinimumDisplayRowCount:20];
+
+    [(UITableView *) list_ setDataSource:self];
+    [list_ setDelegate:self];
+
+    [self updateHeight];
+}
+
+- (void) releaseSubviews {
+    list_ = nil;
+
+    [super releaseSubviews];
 }
 
 - (void) setDelegate:(id)delegate {
     delegate_ = delegate;
 }
 
-- (bool) hasPackage:(Package *)package {
-    return true;
+- (bool) shouldYield {
+    return false;
 }
 
-- (bool) shouldYield {
+- (bool) shouldBlock {
     return false;
 }
 
-- (void) _reloadPackages:(NSArray *)packages {
-    [packages_ removeAllObjects];
-    [sections_ removeAllObjects];
+- (NSMutableArray *) _reloadPackages {
+@synchronized (database_) {
+    era_ = [database_ era];
+    NSArray *packages([database_ packages]);
 
-    _profile(PackageTable$reloadData$Filter)
-        for (Package *package in packages)
-            if ([self hasPackage:package])
-                [packages_ addObject:package];
-    _end
-}
+    return [NSMutableArray arrayWithArray:packages];
+} }
 
 - (void) _reloadData {
-    era_ = [database_ era];
-    NSArray *packages = [database_ packages];
+    if (reloading_ != 0) {
+        reloading_ = 2;
+        return;
+    }
+
+    NSArray *packages;
 
     if ([self shouldYield]) {
-        UIProgressHUD *hud([delegate_ addProgressHUD]);
-        [hud setText:UCLocalize("LOADING")];
-        [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
-        [delegate_ removeProgressHUD:hud];
+        do {
+            UIProgressHUD *hud;
+
+            if (![self shouldBlock])
+                hud = nil;
+            else {
+                hud = [delegate_ addProgressHUD];
+                [hud setText:UCLocalize("LOADING")];
+            }
+
+            reloading_ = 1;
+            packages = [self yieldToSelector:@selector(_reloadPackages)];
+
+            if (hud != nil)
+                [delegate_ removeProgressHUD:hud];
+        } while (reloading_ == 2);
+
+        reloading_ = 0;
     } else {
-        [self _reloadPackages:packages];
+        packages = [self _reloadPackages];
     }
 
+    packages_ = packages;
+
     [indices_ removeAllObjects];
+    [sections_ removeAllObjects];
 
     Section *section = nil;
 
@@ -6150,6 +6048,12 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     {
         [index_ removeAllObjects];
 
+        bool sectioned([self showsSections]);
+        if (!sectioned) {
+            section = [[[Section alloc] initWithName:nil localize:false] autorelease];
+            [sections_ addObject:section];
+        }
+
         _profile(PackageTable$reloadData$Section)
             for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
                 Package *package;
@@ -6160,7 +6064,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
                     index = [package index];
                 _end
 
-                if (section == nil || [section index] != index) {
+                if (sectioned && (section == nil || [section index] != index)) {
                     _profile(PackageTable$reloadData$Section$Allocate)
                         section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
                     _end
@@ -6178,7 +6082,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         _end
     }
 
+    [self updateHeight];
+
     _profile(PackageTable$reloadData$List)
+        [(UITableView *) list_ setDataSource:self];
         [list_ reloadData];
     _end
 }
@@ -6189,7 +6096,16 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) resetCursor {
-    [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
+    [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
+}
+
+- (void) clearData {
+    [self updateHeight];
+
+    [list_ setDataSource:nil];
+    [list_ reloadData];
+
+    [self resetCursor];
 }
 
 @end
@@ -6218,6 +6134,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) setFilter:(SEL)filter {
+@synchronized (self) {
     filter_ = filter;
 
     /* XXX: this is an unsafe optimization of doomy hell */
@@ -6225,22 +6142,44 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     _assert(method != NULL);
     imp_ = method_getImplementation(method);
     _assert(imp_ != NULL);
-}
+} }
 
 - (void) setObject:(id)object {
+@synchronized (self) {
     object_ = object;
-}
+} }
 
 - (void) setObject:(id)object forFilter:(SEL)filter {
+@synchronized (self) {
     [self setFilter:filter];
     [self setObject:object];
-}
+} }
+
+- (NSMutableArray *) _reloadPackages {
+@synchronized (database_) {
+    era_ = [database_ era];
+    NSArray *packages([database_ packages]);
+
+    NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
+
+    IMP imp;
+    SEL filter;
+    _H<NSObject> object;
+
+    @synchronized (self) {
+        imp = imp_;
+        filter = filter_;
+        object = object_;
+    }
 
-- (bool) hasPackage:(Package *)package {
-    _profile(FilteredPackageTable$hasPackage)
-        return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
+    _profile(PackageTable$reloadData$Filter)
+        for (Package *package in packages)
+            if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
+                [filtered addObject:package];
     _end
-}
+
+    return filtered;
+} }
 
 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
     if ((self = [super initWithDatabase:database title:title]) != nil) {
@@ -6299,11 +6238,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     ] autorelease];
 }
 
-- (void) unloadData {
-    [super unloadData];
-    [self reloadData];
-}
-
 @end
 /* }}} */
 /* Manage Controller {{{ */
@@ -6487,14 +6421,13 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     ProgressDelegate
 > {
     _transient Database *database_;
-    _H<RefreshBar> refreshbar_;
+    _H<RefreshBar, 1> refreshbar_;
 
     bool dropped_;
     bool updating_;
     // XXX: ok, "updatedelegate_"?...
     _transient NSObject<CydiaDelegate> *updatedelegate_;
 
-    id root_;
     _H<UIViewController> remembered_;
     _transient UIViewController *transient_;
 }
@@ -6554,20 +6487,21 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) unloadData {
-    UIViewController *selected([self selectedViewController]);
+    [super unloadData];
+
     for (UINavigationController *controller in [self viewControllers])
         [controller unloadData];
 
-    [selected reloadData];
+    if (UIViewController *selected = [self selectedViewController])
+        [selected reloadData];
 
-    if (UIViewController *unselected = [self unselectedViewController])
+    if (UIViewController *unselected = [self unselectedViewController]) {
+        [unselected unloadData];
         [unselected reloadData];
-
-    [super unloadData];
+    }
 }
 
 - (void) dealloc {
-    [refreshbar_ setDelegate:nil];
     [[NSNotificationCenter defaultCenter] removeObserver:self];
 
     [super dealloc];
@@ -6603,7 +6537,9 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     ];
 }
 
-- (void) performUpdate { _pooled
+- (void) performUpdate {
+    NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
+
     Status status;
     status.setDelegate(self);
     [database_ updateWithStatus:status];
@@ -6613,6 +6549,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         withObject:nil
         waitUntilDone:NO
     ];
+
+    [pool release];
 }
 
 - (void) stopUpdateWithSelector:(SEL)selector {
@@ -6668,14 +6606,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     updatedelegate_ = delegate;
 }
 
-- (CGFloat) statusBarHeight {
-    if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
-        return [[UIApplication sharedApplication] statusBarFrame].size.height;
-    } else {
-        return [[UIApplication sharedApplication] statusBarFrame].size.width;
-    }
-}
-
 - (UIView *) transitionView {
     if ([self respondsToSelector:@selector(_transitionView)])
         return [self _transitionView];
@@ -6694,7 +6624,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     CGRect barframe([refreshbar_ frame]);
 
     if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
-        barframe.origin.y = [self statusBarHeight];
+        barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
     else
         barframe.origin.y = 0;
 
@@ -6714,9 +6644,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     // Ensure bar has the proper width for our view, it might have changed
     barframe.size.width = viewframe.size.width;
     [refreshbar_ setFrame:barframe];
-
-    // XXX: fix Apple's layout bug
-    [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
 }
 
 - (void) raiseBar:(BOOL)animated {
@@ -6739,18 +6666,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     if (animated)
         [UIView commitAnimations];
-
-    // XXX: fix Apple's layout bug
-    // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
 }
 
-#if 0
-- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
-    // XXX: fix Apple's layout bug
-    // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
-}
-#endif
-
 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
     bool dropped(dropped_);
 
@@ -6761,9 +6678,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     if (dropped)
         [self dropBar:NO];
-
-    // XXX: fix Apple's layout bug
-    // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
 }
 
 - (void) statusBarFrameChanged:(NSNotification *)notification {
@@ -6884,6 +6798,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         Package *package([database packageWithName:path]);
         if (package == nil)
             goto fail;
+        [package parse];
         UIImage *icon([package icon]);
         [self _returnPNGWithImage:icon forRequest:request];
     } else if ([command isEqualToString:@"source-icon"]) {
@@ -6906,7 +6821,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
             goto fail;
         path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
         NSString *section(Simplify(path));
-        UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
+        UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
         if (icon == nil)
             icon = [UIImage applicationImageNamed:@"unknown.png"];
         [self _returnPNGWithImage:icon forRequest:request];
@@ -6964,7 +6879,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     _transient Database *database_;
     _H<NSMutableArray> sections_;
     _H<NSMutableArray> filtered_;
-    _H<UITableView> list_;
+    _H<UITableView, 2> list_;
 }
 
 - (id) initWithDatabase:(Database *)database;
@@ -7082,6 +6997,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) releaseSubviews {
     list_ = nil;
+
+    [super releaseSubviews];
 }
 
 - (id) initWithDatabase:(Database *)database {
@@ -7164,9 +7081,9 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 > {
     _transient Database *database_;
     unsigned era_;
-    CFMutableArrayRef packages_;
+    _H<NSArray> packages_;
     _H<NSMutableArray> sections_;
-    _H<UITableView> list_;
+    _H<UITableView, 2> list_;
     unsigned upgrades_;
 }
 
@@ -7176,11 +7093,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 @implementation ChangesController
 
-- (void) dealloc {
-    CFRelease(packages_);
-    [super dealloc];
-}
-
 - (NSURL *) navigationURL {
     return [NSURL URLWithString:@"cydia://changes"];
 }
@@ -7207,10 +7119,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     return [[sections_ objectAtIndex:section] count];
 }
 
-- (Package *) packageAtIndex:(NSUInteger)index {
-    return (Package *) CFArrayGetValueAtIndex(packages_, index);
-}
-
 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
 @synchronized (database_) {
     if ([database_ era] != era_)
@@ -7221,14 +7129,14 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         return nil;
     Section *section([sections_ objectAtIndex:sectionIndex]);
     NSInteger row([path row]);
-    return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
+    return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
 } }
 
 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
     PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
     if (cell == nil)
         cell = [[[PackageCell alloc] init] autorelease];
-    [cell setPackage:[self packageAtIndexPath:path]];
+    [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
     return cell;
 }
 
@@ -7268,51 +7176,60 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) releaseSubviews {
     list_ = nil;
+
+    [super releaseSubviews];
 }
 
 - (id) initWithDatabase:(Database *)database {
     if ((self = [super init]) != nil) {
         database_ = database;
 
-        packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
+        packages_ = [NSArray array];
         sections_ = [NSMutableArray arrayWithCapacity:16];
     } return self;
 }
 
-// this mostly works because reloadData (below) is @synchronized (database_)
-// XXX: that said, I've been running into problems with NSRangeExceptions :(
-- (void) _reloadPackages:(NSArray *)packages {
-    CFRelease(packages_);
-    packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
+- (NSMutableArray *) _reloadPackages {
+@synchronized (database_) {
+    era_ = [database_ era];
+    NSArray *packages([database_ packages]);
+
+    NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
 
     _trace();
     _profile(ChangesController$_reloadPackages$Filter)
         for (Package *package in packages)
             if ([package upgradableAndEssential:YES] || [package visible])
-                CFArrayAppendValue(packages_, package);
+                CFArrayAppendValue((CFMutableArrayRef) filtered, package);
     _end
     _trace();
     _profile(ChangesController$_reloadPackages$radixSort)
-        [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
+        [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
     _end
     _trace();
-}
+
+    return filtered;
+} }
 
 - (void) _reloadData {
-@synchronized (database_) {
-    era_ = [database_ era];
-    NSArray *packages = [database_ packages];
+    NSArray *packages;
 
-#if 1
-    UIProgressHUD *hud([delegate_ addProgressHUD]);
-    [hud setText:UCLocalize("LOADING")];
-    //NSLog(@"HUD:%@::%@", delegate_, hud);
-    [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
-    [delegate_ removeProgressHUD:hud];
-#else
-    [self _reloadPackages:packages];
-#endif
+  reload:
+    if (true) {
+        UIProgressHUD *hud([delegate_ addProgressHUD]);
+        [hud setText:UCLocalize("LOADING")];
+        //NSLog(@"HUD:%@::%@", delegate_, hud);
+        packages = [self yieldToSelector:@selector(_reloadPackages)];
+        [delegate_ removeProgressHUD:hud];
+    } else {
+        packages = [self _reloadPackages];
+    }
+
+@synchronized (database_) {
+    if (era_ != [database_ era])
+        goto reload;
 
+    packages_ = packages;
     [sections_ removeAllObjects];
 
     Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
@@ -7325,8 +7242,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
 
-    for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
-        Package *package = [self packageAtIndex:offset];
+    for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
+        Package *package = [packages_ objectAtIndex:offset];
 
         BOOL uae = [package upgradableAndEssential:YES];
 
@@ -7366,7 +7283,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     if (unseens) {
         Section *last = [sections_ lastObject];
         size_t count = [last count];
-        CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
+        [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
         [sections_ removeLastObject];
     }
 
@@ -7407,7 +7324,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 @interface SearchController : FilteredPackageListController <
     UISearchBarDelegate
 > {
-    _H<UISearchBar> search_;
+    _H<UISearchBar, 1> search_;
     BOOL searchloaded_;
 }
 
@@ -7418,11 +7335,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 @implementation SearchController
 
-- (void) dealloc {
-    [search_ setDelegate:nil];
-    [super dealloc];
-}
-
 - (NSURL *) navigationURL {
     if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
         return [NSURL URLWithString:@"cydia://search"];
@@ -7430,14 +7342,28 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
 }
 
+- (void) useSearch {
+    [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
+    [self clearData];
+    [self reloadData];
+}
+
+- (void) viewWillAppear:(BOOL)animated {
+    [super viewWillAppear:animated];
+
+    if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
+        [self useSearch];
+}
+
 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
     [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
+    [self clearData];
+    [self reloadData];
 }
 
 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
-    [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
     [search_ resignFirstResponder];
-    [self reloadData];
+    [self useSearch];
 }
 
 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
@@ -7455,11 +7381,30 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (bool) shouldYield {
+    return YES;
+}
+
+- (bool) shouldBlock {
     return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
 }
 
+- (bool) isSummarized {
+    return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
+}
+
+- (bool) showsSections {
+    return false;
+}
+
+- (NSMutableArray *) _reloadPackages {
+    NSMutableArray *packages([super _reloadPackages]);
+    if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
+        [packages radixSortUsingSelector:@selector(rank)];
+    return packages;
+}
+
 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
-    if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:query])) {
+    if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
         search_ = [[[UISearchBar alloc] init] autorelease];
         [search_ setDelegate:self];
 
@@ -7490,7 +7435,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) reloadData {
-    [self setObject:[search_ text]];
+    id object([search_ text]);
+    if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
+        object = [object componentsSeparatedByString:@" "];
+
+    [self setObject:object];
     [self resetCursor];
 
     [super reloadData];
@@ -7511,7 +7460,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     _transient Database *database_;
     _H<NSString> name_;
     _H<Package> package_;
-    _H<UITableView> table_;
+    _H<UITableView, 2> table_;
     _H<UISwitch> subscribedSwitch_;
     _H<UISwitch> ignoredSwitch_;
     _H<UITableViewCell> subscribedCell_;
@@ -7658,6 +7607,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     table_ = nil;
     ignoredSwitch_ = nil;
     subscribedSwitch_ = nil;
+
+    [super releaseSubviews];
 }
 
 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
@@ -7697,10 +7648,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 @implementation InstalledController
 
-- (void) dealloc {
-    [super dealloc];
-}
-
 - (NSURL *) navigationURL {
     return [NSURL URLWithString:@"cydia://installed"];
 }
@@ -7757,8 +7704,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 /* }}} */
 
 /* Source Cell {{{ */
-@interface SourceCell : CYTableViewCell <
-    ContentDelegate
+@interface SourceCell : CyteTableViewCell <
+    CyteTableViewCellDelegate
 > {
     _H<UIImage> icon_;
     _H<NSString> origin_;
@@ -7771,17 +7718,44 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 @implementation SourceCell
 
+- (void) _setImage:(UIImage *)image {
+    icon_ = image;
+    [content_ setNeedsDisplay];
+}
+
+- (void) _setSource:(Source *)source {
+    NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
+
+    if (NSString *base = [source base])
+        if ([base length] != 0) {
+            NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
+
+            if (NSData *data = [NSURLConnection
+                sendSynchronousRequest:[NSURLRequest
+                    requestWithURL:url
+                    //cachePolicy:NSURLRequestUseProtocolCachePolicy
+                    //timeoutInterval:5
+                ]
+
+                returningResponse:NULL
+                error:NULL
+            ])
+                if (UIImage *image = [UIImage imageWithData:data])
+                    [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
+        }
+
+    [pool release];
+}
+
 - (void) setSource:(Source *)source {
-    icon_ = nil;
-    if (icon_ == nil)
-        icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
-    if (icon_ == nil)
-        icon_ = [UIImage applicationImageNamed:@"unknown.png"];
+    icon_ = [UIImage applicationImageNamed:@"unknown.png"];
 
     origin_ = [source name];
     label_ = [source uri];
 
     [content_ setNeedsDisplay];
+
+    [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
 }
 
 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
@@ -7789,7 +7763,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         UIView *content([self contentView]);
         CGRect bounds([content bounds]);
 
-        content_ = [[[ContentView alloc] initWithFrame:bounds] autorelease];
+        content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
         [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
         [content_ setBackgroundColor:[UIColor whiteColor]];
         [content addSubview:content_];
@@ -7865,7 +7839,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     UITableViewDelegate
 > {
     _transient Database *database_;
-    _H<UITableView> list_;
+    _H<UITableView, 2> list_;
     _H<NSMutableArray> sources_;
     int offset_;
 
@@ -8103,8 +8077,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
+    NSURL *url([NSURL URLWithString:href]);
+
     NSMutableURLRequest *request = [NSMutableURLRequest
-        requestWithURL:[NSURL URLWithString:href]
+        requestWithURL:url
         cachePolicy:NSURLRequestUseProtocolCachePolicy
         timeoutInterval:120.0
     ];
@@ -8113,8 +8089,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     if (Machine_ != NULL)
         [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
-    if (UniqueID_ != nil)
-        [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
+
+    if ([url isCydiaSecure]) {
+        if (UniqueID_ != nil)
+            [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
+    }
 
     return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
 }
@@ -8196,6 +8175,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) releaseSubviews {
     list_ = nil;
+
+    [super releaseSubviews];
 }
 
 - (id) initWithDatabase:(Database *)database {
@@ -8243,7 +8224,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     ] autorelease];
 
     [alert setContext:@"source"];
-    [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
 
     [alert setNumberOfRows:1];
     [alert addTextFieldWithValue:@"http://" label:@""];
@@ -8307,7 +8287,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     _transient Database *database_;
     // XXX: ok, "roledelegate_"?...
     _transient id roledelegate_;
-    _H<UITableView> table_;
+    _H<UITableView, 2> table_;
     _H<UISegmentedControl> segment_;
     _H<UIView> container_;
 }
@@ -8360,6 +8340,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     table_ = nil;
     segment_ = nil;
     container_ = nil;
+
+    [super releaseSubviews];
 }
 
 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
@@ -8543,6 +8525,14 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [[self view] addSubview:status_];
 }
 
+- (void) releaseSubviews {
+    spinner_ = nil;
+    status_ = nil;
+    caption_ = nil;
+
+    [super releaseSubviews];
+}
+
 @end
 /* }}} */
 
@@ -8573,6 +8563,24 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 #endif
 }
 
+- (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
+    if (NSURLResponse *response = [cached response])
+        if (NSString *mime = [response MIMEType])
+            if ([mime isEqualToString:@"text/cache-manifest"]) {
+                NSURL *url([response URL]);
+
+#if !ForRelease
+                NSLog(@"###: %@", [url absoluteString]);
+#endif
+
+                @synchronized (HostConfig_) {
+                    [CachedURLs_ addObject:url];
+                }
+            }
+
+    [super storeCachedResponse:cached forRequest:request];
+}
+
 @end
 
 @interface Cydia : UIApplication <
@@ -8584,7 +8592,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 > {
     _H<UIWindow> window_;
     _H<CYTabBarController> tabbar_;
-    _H<CYEmulatedLoadingController> emulated_;
+    _H<CydiaLoadingViewController> emulated_;
 
     _H<NSMutableArray> essential_;
     _H<NSMutableArray> broken_;
@@ -8713,37 +8721,36 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     //  - We already auto-refreshed this launch.
     //  - Auto-refresh is disabled.
     if (recently || loaded_ || ManualRefresh) {
-        [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
-
         // If we are cancelling, we need to make sure it knows it's already loaded.
         loaded_ = true;
-        return;
+
+        [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
     } else {
         // We are going to load, so remember that.
         loaded_ = true;
-    }
 
-    SCNetworkReachabilityFlags flags; {
-        SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
-        SCNetworkReachabilityGetFlags(reachability, &flags);
-        CFRelease(reachability);
-    }
+        SCNetworkReachabilityFlags flags; {
+            SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
+            SCNetworkReachabilityGetFlags(reachability, &flags);
+            CFRelease(reachability);
+        }
 
-    // XXX: this elaborate mess is what Apple is using to determine this? :(
-    // XXX: do we care if the user has to intervene? maybe that's ok?
-    bool reachable(
-        (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
-            (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
-                (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
-                (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
-            ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
-            (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
-        )
-    );
+        // XXX: this elaborate mess is what Apple is using to determine this? :(
+        // XXX: do we care if the user has to intervene? maybe that's ok?
+        bool reachable(
+            (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
+                (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
+                    (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
+                    (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
+                ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
+                (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
+            )
+        );
 
-    // If we can reach the server, auto-refresh!
-    if (reachable)
-        [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
+        // If we can reach the server, auto-refresh!
+        if (reachable)
+            [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
+    }
 
     [pool release];
 }
@@ -8752,7 +8759,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
 }
 
-- (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
+- (void) reloadDataWithInvocation:(NSInvocation *)invocation {
+@synchronized (self) {
     UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
     [hud setText:UCLocalize("RELOADING_DATA")];
 
@@ -8777,8 +8785,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         }
     }
 
-    NSLog(@"changes:#%u", changes);
-
     UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
     if (changes != 0) {
         _trace();
@@ -8796,7 +8802,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [self _updateData];
 
     [self refreshIfPossible];
-}
+} }
 
 - (void) updateData {
     [self _updateData];
@@ -8804,12 +8810,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) update_ {
     [database_ update];
-}
-
-- (void) complete {
-    @synchronized (self) {
-        [self _reloadDataWithInvocation:nil];
-    }
+    [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
 }
 
 - (void) disemulate {
@@ -8866,6 +8867,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
 }
 
+- (void) reloadData {
+    [self reloadDataWithInvocation:nil];
+}
+
 - (void) syncData {
     [self _saveConfig];
 
@@ -8885,8 +8890,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     fclose(file);
 
     [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
-
-    [self complete];
 }
 
 - (void) addTrivialSource:(NSString *)href {
@@ -8899,16 +8902,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     Changed_ = true;
 }
 
-- (void) reloadDataWithInvocation:(NSInvocation *)invocation {
-    @synchronized (self) {
-        [self _reloadDataWithInvocation:invocation];
-    }
-}
-
-- (void) reloadData {
-    [self reloadDataWithInvocation:nil];
-}
-
 - (void) resolve {
     pkgProblemResolver *resolver = [database_ resolver];
 
@@ -8986,12 +8979,16 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     }
 }
 
+- (void) perform_ {
+    [database_ perform];
+    [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
+}
+
 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
     Queuing_ = false;
     ++locked_;
-    [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
+    [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
     --locked_;
-    [self complete];
 }
 
 - (void) showSettings {
@@ -9083,10 +9080,14 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     }
 }
 
-- (void) system:(NSString *)command { _pooled
+- (void) system:(NSString *)command {
+    NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
+
     _trace();
     system([command UTF8String]);
     _trace();
+
+    [pool release];
 }
 
 - (void) applicationWillSuspend {
@@ -9457,7 +9458,7 @@ _trace();
     [window_ setUserInteractionEnabled:NO];
     [self setupViewControllers];
 
-    emulated_ = [[[CYEmulatedLoadingController alloc] initWithDatabase:database_] autorelease];
+    emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
     [window_ addSubview:[emulated_ view]];
 
     [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
@@ -9653,6 +9654,8 @@ MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest
     NSMutableURLRequest *copy([request mutableCopy]);
 
     NSURL *url([copy URL]);
+
+    NSString *href([url absoluteString]);
     NSString *host([url host]);
     NSString *scheme([[url scheme] lowercaseString]);
 
@@ -9662,13 +9665,29 @@ MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest
         if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
             if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
                 [copy setHTTPShouldUsePipelining:YES];
+
+        if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
+            if ([control isEqualToString:@"max-age=0"])
+                if ([CachedURLs_ containsObject:href]) {
+#if !ForRelease
+                    NSLog(@"~~~: %@", href);
+#endif
+
+                    [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
+
+                    [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
+                    [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
+                    [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
+                }
     }
 
     if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
     } return self;
 }
 
-int main(int argc, char *argv[]) { _pooled
+int main(int argc, char *argv[]) {
+    NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
+
     _trace();
 
     UpdateExternalStatus(0);
@@ -9703,7 +9722,10 @@ int main(int argc, char *argv[]) { _pooled
     HostConfig_ = [[[NSObject alloc] init] autorelease];
     @synchronized (HostConfig_) {
         BridgedHosts_ = [NSMutableSet setWithCapacity:4];
+        TokenHosts_ = [NSMutableSet setWithCapacity:4];
+        InsecureHosts_ = [NSMutableSet setWithCapacity:4];
         PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
+        CachedURLs_ = [NSMutableSet setWithCapacity:32];
     }
 
     UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
@@ -9842,9 +9864,9 @@ int main(int argc, char *argv[]) { _pooled
     else
         Machine_ = machine;
 
-    SerialNumber_ = CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
-    ChipID_ = CYHex(CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true, true);
-    BBSNum_ = CYHex(CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false, false);
+    SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
+    ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
+    BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
 
     UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
 
@@ -10010,5 +10032,6 @@ int main(int argc, char *argv[]) { _pooled
     CGColorSpaceRelease(space_);
     CFRelease(Locale_);
 
+    [pool release];
     return value;
 }