]> git.saurik.com Git - cydia.git/blobdiff - MobileCydia.mm
Add /usr/share/bigboss/icons from the bigboss package.
[cydia.git] / MobileCydia.mm
index ebe39718fc5fcc1980d500d6fc38d347316718b4..a54c7b7332d8ca6b3cd27b36c394c8b937ba8840 100644 (file)
@@ -206,6 +206,7 @@ void PrintTimes() {
 #define _end }
 /* }}} */
 
+#include "Version.h"
 #define Cydia_ CYDIA_VERSION
 
 #define lprintf(args...) fprintf(stderr, args)
@@ -244,6 +245,11 @@ union SplitHash {
 };
 // }}}
 
+static NSString *Colon_;
+NSString *Elision_;
+static NSString *Error_;
+static NSString *Warning_;
+
 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
 
 static _finline NSString *CydiaURL(NSString *path) {
@@ -266,6 +272,11 @@ 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;
@@ -691,8 +702,11 @@ static NSMutableDictionary *Metadata_;
 static _transient NSMutableDictionary *Settings_;
 static _transient NSString *Role_;
 static _transient NSMutableDictionary *Packages_;
+static _transient NSMutableDictionary *Values_;
 static _transient NSMutableDictionary *Sections_;
 static _transient NSMutableDictionary *Sources_;
+static _transient NSNumber *Version_;
+static _transient _H<NSString> CydiaSource_;
 static bool Changed_;
 static time_t now_;
 
@@ -703,6 +717,8 @@ 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_;
 
@@ -712,6 +728,45 @@ static NSString *kCydiaProgressEventTypeStatus = @"Status";
 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
 /* }}} */
 
+static void AddSource(NSDictionary *source) {
+    [Sources_ setObject:source forKey:[NSString stringWithFormat:@"%@:%@:%@", [source objectForKey:@"Type"], [source objectForKey:@"URI"], [source objectForKey:@"Distribution"]]];
+    Changed_ = true;
+}
+
+static void AddSource(NSString *href, NSString *distribution, NSArray *sections = nil) {
+    AddSource([NSMutableDictionary dictionaryWithObjectsAndKeys:
+        @"deb", @"Type",
+        href, @"URI",
+        distribution, @"Distribution",
+        sections ?: [NSMutableArray array], @"Sections",
+    nil]);
+}
+
+static void WriteSources() {
+    FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
+    _assert(file != NULL);
+
+    fprintf(file, "deb http://%s/ tangelo-3.7 main\n",
+        [CydiaSource_ UTF8String]
+    );
+
+    for (NSString *key in [Sources_ allKeys]) {
+        NSDictionary *source([Sources_ objectForKey:key]);
+
+        NSArray *sections([source objectForKey:@"Sections"] ?: [NSArray array]);
+
+        fprintf(file, "%s %s %s%s%s\n",
+            [[source objectForKey:@"Type"] UTF8String],
+            [[source objectForKey:@"URI"] UTF8String],
+            [[source objectForKey:@"Distribution"] UTF8String],
+            [sections count] == 0 ? "" : " ",
+            [[sections componentsJoinedByString:@" "] UTF8String]
+        );
+    }
+
+    fclose(file);
+}
+
 /* Display Helpers {{{ */
 inline float Interpolate(float begin, float end, float fraction) {
     return (end - begin) * fraction + begin;
@@ -821,6 +876,8 @@ static NSString *CYHex(NSData *data, bool reverse = false) {
 @class CYPackageController;
 
 @protocol CydiaDelegate
+- (void) returnToCydia;
+- (void) saveState;
 - (void) retainNetworkActivityIndicator;
 - (void) releaseNetworkActivityIndicator;
 - (void) clearPackage:(Package *)package;
@@ -833,6 +890,7 @@ static NSString *CYHex(NSData *data, bool reverse = false) {
 - (void) loadData;
 - (void) updateData;
 - (void) syncData;
+- (void) addSource:(NSDictionary *)source;
 - (void) addTrivialSource:(NSString *)href;
 - (void) showSettings;
 - (UIProgressHUD *) addProgressHUD;
@@ -871,6 +929,7 @@ class Status :
     }
 
     virtual void IMSHit(pkgAcquire::ItemDesc &item) {
+        Done(item);
     }
 
     virtual void Fetch(pkgAcquire::ItemDesc &item) {
@@ -880,6 +939,9 @@ class Status :
     }
 
     virtual void Done(pkgAcquire::ItemDesc &item) {
+        NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
+        CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
+        [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
     }
 
     virtual void Fail(pkgAcquire::ItemDesc &item) {
@@ -1326,6 +1388,22 @@ static void PackageImport(const void *key, const void *value, void *context) {
     authority_ = nil;
 }
 
++ (NSString *) webScriptNameForSelector:(SEL)selector {
+    if (false);
+    else if (selector == @selector(addSection:))
+        return @"addSection";
+    else if (selector == @selector(removeSection:))
+        return @"removeSection";
+    else if (selector == @selector(remove))
+        return @"remove";
+    else
+        return nil;
+}
+
++ (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
+    return [self webScriptNameForSelector:selector] == nil;
+}
+
 + (NSArray *) _attributeKeys {
     return [NSArray arrayWithObjects:
         @"distribution",
@@ -1334,6 +1412,7 @@ static void PackageImport(const void *key, const void *value, void *context) {
         @"label",
         @"name",
         @"origin",
+        @"sections",
         @"shortDescription",
         @"trusted",
         @"type",
@@ -1420,7 +1499,7 @@ static void PackageImport(const void *key, const void *value, void *context) {
     NSDictionary *lhr = [self record];
     NSDictionary *rhr = [source record];
 
-    if (lhr != rhr)
+    if ((lhr == nil) != (rhr == nil))
         return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
 
     NSString *lhs = [self name];
@@ -1447,6 +1526,62 @@ static void PackageImport(const void *key, const void *value, void *context) {
     return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
 }
 
+- (NSArray *) sections {
+    return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
+}
+
+- (void) _addSection:(NSString *)section {
+    if (record_ == nil)
+        return;
+    else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
+        if (![sections containsObject:section]) {
+            [sections addObject:section];
+            Changed_ = true;
+        }
+    } else {
+        [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
+        Changed_ = true;
+    }
+}
+
+- (bool) addSection:(NSString *)section {
+    if (record_ == nil)
+        return false;
+
+    [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
+    return true;
+}
+
+- (void) _removeSection:(NSString *)section {
+    if (record_ == nil)
+        return;
+
+    if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
+        if ([sections containsObject:section]) {
+            [sections removeObject:section];
+            Changed_ = true;
+        }
+}
+
+- (bool) removeSection:(NSString *)section {
+    if (record_ == nil)
+        return false;
+
+    [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
+    return true;
+}
+
+- (void) _remove {
+    [Sources_ removeObjectForKey:[self key]];
+    Changed_ = true;
+}
+
+- (bool) remove {
+    bool value(record_ != nil);
+    [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
+    return value;
+}
+
 - (NSDictionary *) record {
     return record_;
 }
@@ -1665,6 +1800,7 @@ static void PackageImport(const void *key, const void *value, void *context) {
 struct ParsedPackage {
     CYString tagline_;
 
+    CYString architecture_;
     CYString icon_;
 
     CYString depiction_;
@@ -1957,6 +2093,7 @@ struct PackageNameOrdering :
 + (NSArray *) _attributeKeys {
     return [NSArray arrayWithObjects:
         @"applications",
+        @"architecture",
         @"author",
         @"depiction",
         @"essential",
@@ -2003,6 +2140,12 @@ struct PackageNameOrdering :
     return relations;
 } }
 
+- (NSString *) architecture {
+    [self parse];
+@synchronized (database_) {
+    return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
+} }
+
 - (NSString *) getField:(NSString *)name {
 @synchronized (database_) {
     if ([database_ era] != era_ || file_.end())
@@ -2041,6 +2184,7 @@ struct PackageNameOrdering :
                 const char *name_;
                 CYString *value_;
             } names[] = {
+                {"architecture", &parsed->architecture_},
                 {"icon", &parsed->icon_},
                 {"depiction", &parsed->depiction_},
                 {"homepage", &parsed->homepage_},
@@ -2309,8 +2453,29 @@ struct PackageNameOrdering :
 } }
 
 - (NSString *) shortDescription {
-    return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
-}
+    if (parsed_ != NULL)
+        return static_cast<NSString *>(parsed_->tagline_);
+
+@synchronized (database_) {
+    pkgRecords::Parser &parser([database_ records]->Lookup(file_));
+
+    const char *start, *end;
+    if (!parser.ShortDesc(start, end))
+        return nil;
+
+    if (end - start > 200)
+        end = start + 200;
+
+    /*
+    if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
+        end = stop;
+
+    while (end != start && end[-1] == '\r')
+        --end;
+    */
+
+    return [(id) CYStringCreate(start, end - start) autorelease];
+} }
 
 - (unichar) index {
     _profile(Package$index)
@@ -2482,14 +2647,12 @@ struct PackageNameOrdering :
     if (parsed_ != NULL)
         if (NSString *href = parsed_->icon_)
             if ([href hasPrefix:@"file:///"])
-                // XXX: correct escaping
-                icon = [UIImage imageAtPath:[href substringFromIndex:7]];
+                icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
     if (icon == nil) if (section != nil)
-        icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
+        icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
     if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
         if ([dicon hasPrefix:@"file:///"])
-            // XXX: correct escaping
-            icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
+            icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
     if (icon == nil)
         icon = [UIImage applicationImageNamed:@"unknown.png"];
     return icon;
@@ -2690,33 +2853,34 @@ struct PackageNameOrdering :
     NSRange range;
     NSUInteger length;
 
-    [self parse];
-
-    string = [self id];
+    string = [self name];
     length = [string length];
 
     for (NSString *term in query) {
         range = [string rangeOfString:term options:MatchCompareOptions_];
         if (range.location != NSNotFound)
-            rank_ -= 10 * 100000 / length;
+            rank_ -= 6 * 1000000 / length;
     }
 
-    string = [self name];
+    if (rank_ == 0) {
+        string = [self id];
+        length = [string length];
 
-    for (NSString *term in query) {
-        range = [string rangeOfString:term options:MatchCompareOptions_];
-        if (range.location != NSNotFound)
-            rank_ -= 6 * 100000 / length;
+        for (NSString *term in query) {
+            range = [string rangeOfString:term options:MatchCompareOptions_];
+            if (range.location != NSNotFound)
+                rank_ -= 6 * 1000000 / length;
+        }
     }
 
     string = [self shortDescription];
     length = [string length];
-    NSUInteger stop(std::min<NSUInteger>(length, 100));
+    NSUInteger stop(std::min<NSUInteger>(length, 200));
 
     for (NSString *term in query) {
         range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
         if (range.location != NSNotFound)
-            rank_ -= 2 * 100000 / length;
+            rank_ -= 2 * 100000;
     }
 
     return rank_ != 0;
@@ -2990,11 +3154,6 @@ struct PackageNameOrdering :
 @end
 /* }}} */
 
-static NSString *Colon_;
-NSString *Elision_;
-static NSString *Error_;
-static NSString *Warning_;
-
 class CydiaLogCleaner :
     public pkgArchiveCleaner
 {
@@ -3140,6 +3299,8 @@ class CydiaLogCleaner :
 }
 
 - (Package *) packageWithName:(NSString *)name {
+    if (name == nil)
+        return nil;
 @synchronized (self) {
     if (static_cast<pkgDepCache *>(cache_) == NULL)
         return nil;
@@ -3757,6 +3918,7 @@ static _H<NSMutableSet> Diversions_;
 + (NSArray *) _attributeKeys {
     return [NSArray arrayWithObjects:
         @"bbsnum",
+        @"cydiaSource",
         @"device",
         @"ecid",
         @"firmware",
@@ -3831,10 +3993,16 @@ 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(addSource:::))
+        return @"addSource";
+    else if (selector == @selector(addTokenHost:))
+        return @"addTokenHost";
     else if (selector == @selector(addTrivialSource:))
         return @"addTrivialSource";
     else if (selector == @selector(close))
@@ -3859,6 +4027,10 @@ static _H<NSMutableSet> Diversions_;
         return @"getPreferredLanguages";
     else if (selector == @selector(getPackageById:))
         return @"getPackageById";
+    else if (selector == @selector(getMetadataKeys))
+        return @"getMetadataKeys";
+    else if (selector == @selector(getMetadataValue:))
+        return @"getMetadataValue";
     else if (selector == @selector(getSessionValue:))
         return @"getSessionValue";
     else if (selector == @selector(installPackages:))
@@ -3871,6 +4043,12 @@ static _H<NSMutableSet> Diversions_;
         return @"refreshSources";
     else if (selector == @selector(removeButton))
         return @"removeButton";
+    else if (selector == @selector(saveConfig))
+        return @"saveConfig";
+    else if (selector == @selector(setCydiaSource:))
+        return @"setCydiaSource";
+    else if (selector == @selector(setMetadataValue::))
+        return @"setMetadataValue";
     else if (selector == @selector(setSessionValue::))
         return @"setSessionValue";
     else if (selector == @selector(substitutePackageNames:))
@@ -3971,6 +4149,45 @@ static _H<NSMutableSet> Diversions_;
     return value;
 }
 
+- (void) _setCydiaSource:(NSString *)source {
+    @synchronized (HostConfig_) {
+        CydiaSource_ = source;
+        [Metadata_ setObject:source forKey:@"CydiaSource"];
+    }
+
+    Changed_ = true;
+}
+
+- (void) setCydiaSource:(NSString *)source {
+    [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
+}
+
+- (NSString *) cydiaSource {
+    @synchronized (HostConfig_) {
+        return (id) CydiaSource_ ?: [NSNull null];
+    }
+}
+
+- (NSArray *) getMetadataKeys {
+@synchronized (Values_) {
+    return [Values_ allKeys];
+} }
+
+- (id) getMetadataValue:(NSString *)key {
+@synchronized (Values_) {
+    return [Values_ objectForKey:key];
+} }
+
+- (void) setMetadataValue:(NSString *)key :(NSString *)value {
+@synchronized (Values_) {
+    if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
+        [Values_ removeObjectForKey:key];
+    else
+        [Values_ setObject:value forKey:key];
+
+    [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
+} }
+
 - (id) getSessionValue:(NSString *)key {
 @synchronized (SessionData_) {
     return [SessionData_ objectForKey:key];
@@ -3989,6 +4206,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])
@@ -4003,6 +4230,20 @@ static _H<NSMutableSet> Diversions_;
     [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
 }
 
+- (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
+    NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
+
+    for (NSString *section in sections)
+        [array addObject:section];
+
+    [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
+        @"deb", @"Type",
+        href, @"URI",
+        distribution, @"Distribution",
+        array, @"Sections",
+    nil] waitUntilDone:NO];
+}
+
 - (void) addTrivialSource:(NSString *)href {
     [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
 }
@@ -4011,6 +4252,10 @@ static _H<NSMutableSet> Diversions_;
     [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
 }
 
+- (void) saveConfig {
+    [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
+}
+
 - (NSArray *) getAllSources {
     return [[Database sharedInstance] sources];
 }
@@ -4207,6 +4452,24 @@ static _H<NSMutableSet> Diversions_;
 @end
 /* }}} */
 
+@interface NSURL (CydiaSecure)
+@end
+
+@implementation NSURL (CydiaSecure)
+
+- (bool) isCydiaSecure {
+    if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
+        return true;
+
+    @synchronized (HostConfig_) {
+        if ([InsecureHosts_ containsObject:[self host]])
+            return true;
+    }
+
+    return false;
+}
+
+@end
 
 /* Cydia Browser Controller {{{ */
 @implementation CydiaWebViewController
@@ -4257,14 +4520,25 @@ static _H<NSMutableSet> Diversions_;
 }
 
 - (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;
 }
@@ -4274,23 +4548,35 @@ static _H<NSMutableSet> Diversions_;
     [cydia_ setDelegate:delegate];
 }
 
+- (NSString *) applicationNameForUserAgent {
+    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];
+
+    return application;
+}
+
 - (id) init {
     if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
         cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
+    } return self;
+}
 
-        WebView *webview([[webview_ _documentView] webView]);
+@end
 
-        NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
+@interface AppCacheController : CydiaWebViewController {
+}
 
-        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];
+@end
 
-        [webview setApplicationNameForUserAgent:application];
-    } return self;
+@implementation AppCacheController
+
+- (void) didReceiveMemoryWarning {
 }
 
 @end
@@ -4398,8 +4684,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) _doContinue {
-    [self dismissModalViewControllerAnimated:YES];
     [delegate_ cancelAndClear:NO];
+    [self dismissModalViewControllerAnimated:YES];
 }
 
 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
@@ -4834,8 +5120,12 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 - (void) close {
     UpdateExternalStatus(0);
 
+    if (Finish_ > 1)
+        [delegate_ saveState];
+
     switch (Finish_) {
         case 0:
+            [delegate_ returnToCydia];
         break;
 
         case 1:
@@ -5038,7 +5328,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     bool commercial_;
     _H<NSString> source_;
     _H<UIImage> badge_;
-    _H<Package> package_;
     _H<UIImage> placard_;
     bool summarized_;
 }
@@ -5080,75 +5369,83 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     source_ = nil;
     badge_ = nil;
     placard_ = nil;
-    package_ = nil;
 
-    [package parse];
+    if (package == nil)
+        [content_ setBackgroundColor:[UIColor whiteColor]];
+    else {
+        [package parse];
 
-    Source *source = [package source];
+        Source *source = [package source];
 
-    icon_ = [package icon];
-    name_ = [package name];
+        icon_ = [package icon];
 
-    if (IsWildcat_)
-        description_ = [package longDescription];
-    if (description_ == nil)
-        description_ = [package shortDescription];
+        if (NSString *name = [package name])
+            name_ = [NSString stringWithString:name];
 
-    commercial_ = [package isCommercial];
+        NSString *description(nil);
 
-    package_ = package;
+        if (description == nil && IsWildcat_)
+            description = [package longDescription];
+        if (description == nil)
+            description = [package shortDescription];
 
-    NSString *label = nil;
-    bool trusted = false;
+        if (description != nil)
+            description_ = [NSString stringWithString:description];
 
-    if (source != nil) {
-        label = [source label];
-        trusted = [source trusted];
-    } else if ([[package id] isEqualToString:@"firmware"])
-        label = UCLocalize("APPLE");
-    else
-        label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
+        commercial_ = [package isCommercial];
 
-    NSString *from(label);
+        NSString *label = nil;
+        bool trusted = false;
 
-    NSString *section = [package simpleSection];
-    if (section != nil && ![section isEqualToString:label]) {
-        section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
-        from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
-    }
+        if (source != nil) {
+            label = [source label];
+            trusted = [source trusted];
+        } else if ([[package id] isEqualToString:@"firmware"])
+            label = UCLocalize("APPLE");
+        else
+            label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
 
-    source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
+        NSString *from(label);
 
-    if (NSString *purpose = [package primaryPurpose])
-        badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
+        NSString *section = [package simpleSection];
+        if (section != nil && ![section isEqualToString:label]) {
+            section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
+            from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
+        }
 
-    UIColor *color;
-    NSString *placard;
+        source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
 
-    if (NSString *mode = [package_ mode]) {
-        if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
-            color = RemovingColor_;
-            //placard = @"removing";
-        } else {
-            color = InstallingColor_;
-            //placard = @"installing";
-        }
+        if (NSString *purpose = [package primaryPurpose])
+            badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
 
-        // XXX: the removing/installing placards are not @2x
-        placard = nil;
-    } else {
-        color = [UIColor whiteColor];
+        UIColor *color;
+        NSString *placard;
 
-        if ([package installed] != nil)
-            placard = @"installed";
-        else
+        if (NSString *mode = [package mode]) {
+            if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
+                color = RemovingColor_;
+                //placard = @"removing";
+            } else {
+                color = InstallingColor_;
+                //placard = @"installing";
+            }
+
+            // XXX: the removing/installing placards are not @2x
             placard = nil;
-    }
+        } else {
+            color = [UIColor whiteColor];
 
-    [content_ setBackgroundColor:color];
+            if ([package installed] != nil)
+                placard = @"installed";
+            else
+                placard = nil;
+        }
 
-    if (placard != nil)
-        placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
+        [content_ setBackgroundColor:color];
+
+        if (placard != nil)
+            placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
+    }
 
     [self setNeedsDisplay];
     [content_ setNeedsDisplay];
@@ -5433,13 +5730,16 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) releaseSubviews {
     list_ = nil;
+
+    package_ = nil;
+    files_ = nil;
+
+    [super releaseSubviews];
 }
 
 - (id) initWithDatabase:(Database *)database {
     if ((self = [super init]) != nil) {
         database_ = database;
-
-        files_ = [NSMutableArray arrayWithCapacity:32];
     } return self;
 }
 
@@ -5447,7 +5747,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     package_ = nil;
     name_ = nil;
 
-    [files_ removeAllObjects];
+    files_ = [NSMutableArray arrayWithCapacity:32];
 
     if (package != nil) {
         package_ = package;
@@ -5603,7 +5903,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     if ((self = [super init]) != nil) {
         database_ = database;
         buttons_ = [NSMutableArray arrayWithCapacity:4];
-        name_ = [NSString stringWithString:name];
+        name_ = name == nil ? @"" : [NSString stringWithString:name];
         [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
     } return self;
 }
@@ -5742,6 +6042,9 @@ 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];
 }
 
@@ -5818,7 +6121,9 @@ 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] asSummary:[self isSummarized]];
+
+    Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
+    [cell setPackage:package asSummary:[self isSummarized]];
     return cell;
 }
 
@@ -5829,7 +6134,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
-    if ([self showsSections])
+    if (![self showsSections])
         return nil;
 
     return index_;
@@ -5854,31 +6159,34 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         database_ = database;
         title_ = [title copy];
         [[self navigationItem] setTitle:title_];
+    } return self;
+}
 
-#if TryIndexedCollation
-        if ([[self class] hasIndexedCollation])
-            index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
-        else
-#endif
-            index_ = [NSMutableArray arrayWithCapacity:32];
+- (void) loadView {
+    [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
 
-        indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
+    list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
+    [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
+    [[self view] addSubview:list_];
 
-        packages_ = [NSArray array];
-        sections_ = [NSMutableArray arrayWithCapacity:16];
+    // XXX: is 20 the most optimal number here?
+    [list_ setSectionIndexMinimumDisplayRowCount:20];
 
-        list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
-        [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
-        [[self view] addSubview:list_];
+    [(UITableView *) list_ setDataSource:self];
+    [list_ setDelegate:self];
 
-        // XXX: is 20 the most optimal number here?
-        [list_ setSectionIndexMinimumDisplayRowCount:20];
+    [self updateHeight];
+}
 
-        [(UITableView *) list_ setDataSource:self];
-        [list_ setDelegate:self];
+- (void) releaseSubviews {
+    list_ = nil;
 
-        [self updateHeight];
-    } return self;
+    packages_ = nil;
+    sections_ = nil;
+    index_ = nil;
+    indices_ = nil;
+
+    [super releaseSubviews];
 }
 
 - (void) setDelegate:(id)delegate {
@@ -5934,13 +6242,15 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     packages_ = packages;
 
-    [indices_ removeAllObjects];
-    [sections_ removeAllObjects];
+    indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
+    sections_ = [NSMutableArray arrayWithCapacity:16];
 
     Section *section = nil;
 
 #if TryIndexedCollation
     if ([[self class] hasIndexedCollation]) {
+        index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
+
         id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
         NSArray *titles = [collation sectionIndexTitles];
         int secidx = -1;
@@ -5973,7 +6283,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     } else
 #endif
     {
-        [index_ removeAllObjects];
+        index_ = [NSMutableArray arrayWithCapacity:32];
 
         bool sectioned([self showsSections]);
         if (!sectioned) {
@@ -6019,7 +6329,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) reloadData {
     [super reloadData];
-    [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
+
+    if ([self shouldYield])
+        [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
+    else
+        [self _reloadData];
 }
 
 - (void) resetCursor {
@@ -6137,6 +6451,9 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     return [NSURL URLWithString:@"cydia://home"];
 }
 
+- (void) didReceiveMemoryWarning {
+}
+
 - (void) aboutButtonClicked {
     UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
 
@@ -6533,14 +6850,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];
@@ -6559,7 +6868,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;
 
@@ -6643,8 +6952,15 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 - (void) reloadData {
     [super reloadData];
 
-    if (UIViewController *visible = [self visibleViewController])
+    UIViewController *visible([self visibleViewController]);
+    if (visible != nil)
         [visible reloadData];
+
+    // on the iPad, this view controller is ALSO visible. :(
+    if (IsWildcat_)
+        if (UIViewController *top = [self topViewController])
+            if (top != visible)
+                [top reloadData];
 }
 
 - (void) unloadData {
@@ -6755,8 +7071,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         if (path == nil)
             goto fail;
         path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
-        NSString *section(Simplify(path));
-        UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
+        UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
         if (icon == nil)
             icon = [UIImage applicationImageNamed:@"unknown.png"];
         [self _returnPNGWithImage:icon forRequest:request];
@@ -6932,14 +7247,16 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) releaseSubviews {
     list_ = nil;
+
+    sections_ = nil;
+    filtered_ = nil;
+
+    [super releaseSubviews];
 }
 
 - (id) initWithDatabase:(Database *)database {
     if ((self = [super init]) != nil) {
         database_ = database;
-
-        sections_ = [NSMutableArray arrayWithCapacity:16];
-        filtered_ = [NSMutableArray arrayWithCapacity:16];
     } return self;
 }
 
@@ -6948,8 +7265,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     NSArray *packages = [database_ packages];
 
-    [sections_ removeAllObjects];
-    [filtered_ removeAllObjects];
+    sections_ = [NSMutableArray arrayWithCapacity:16];
+    filtered_ = [NSMutableArray arrayWithCapacity:16];
 
     NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
 
@@ -7069,7 +7386,9 @@ 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] asSummary:false];
+
+    Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
+    [cell setPackage:package asSummary:false];
     return cell;
 }
 
@@ -7088,6 +7407,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) upgradeButtonClicked {
     [delegate_ distUpgrade];
+    [[self navigationItem] setRightBarButtonItem:nil animated:YES];
 }
 
 - (void) loadView {
@@ -7109,14 +7429,16 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) releaseSubviews {
     list_ = nil;
+
+    packages_ = nil;
+    sections_ = nil;
+
+    [super releaseSubviews];
 }
 
 - (id) initWithDatabase:(Database *)database {
     if ((self = [super init]) != nil) {
         database_ = database;
-
-        packages_ = [NSArray array];
-        sections_ = [NSMutableArray arrayWithCapacity:16];
     } return self;
 }
 
@@ -7161,7 +7483,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         goto reload;
 
     packages_ = packages;
-    [sections_ removeAllObjects];
+    sections_ = [NSMutableArray arrayWithCapacity:16];
 
     Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
     Section *ignored = nil;
@@ -7225,21 +7547,19 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     [list_ reloadData];
 
-    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]];
+    [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
+        initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
+        style:UIBarButtonItemStylePlain
+        target:self
+        action:@selector(upgradeButtonClicked)
+    ] autorelease]) animated:YES];
 
-    if (![delegate_ updating])
-        [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
-            initWithTitle:UCLocalize("REFRESH")
-            style:UIBarButtonItemStylePlain
-            target:self
-            action:@selector(refreshButtonClicked)
-        ] autorelease]];
+    [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
+        initWithTitle:UCLocalize("REFRESH")
+        style:UIBarButtonItemStylePlain
+        target:self
+        action:@selector(refreshButtonClicked)
+    ] autorelease]) animated:YES];
 
     PrintTimes();
 } }
@@ -7405,7 +7725,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 @implementation PackageSettingsController
 
 - (NSURL *) navigationURL {
-    return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
+    return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
 }
 
 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
@@ -7538,6 +7858,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     table_ = nil;
     ignoredSwitch_ = nil;
     subscribedSwitch_ = nil;
+
+    [super releaseSubviews];
 }
 
 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
@@ -7740,7 +8062,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 @implementation SourceController
 
 - (NSURL *) navigationURL {
-    return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
+    return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
 }
 
 - (id) initWithDatabase:(Database *)database source:(Source *)source {
@@ -8006,8 +8328,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
     ];
@@ -8016,8 +8340,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];
 }
@@ -8099,12 +8426,15 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) releaseSubviews {
     list_ = nil;
+
+    sources_ = nil;
+
+    [super releaseSubviews];
 }
 
 - (id) initWithDatabase:(Database *)database {
     if ((self = [super init]) != nil) {
         database_ = database;
-        sources_ = [NSMutableArray arrayWithCapacity:16];
     } return self;
 }
 
@@ -8115,7 +8445,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
         return;
 
-    [sources_ removeAllObjects];
+    sources_ = [NSMutableArray arrayWithCapacity:16];
     [sources_ addObjectsFromArray:[database_ sources]];
     _trace();
     [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
@@ -8262,6 +8592,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     table_ = nil;
     segment_ = nil;
     container_ = nil;
+
+    [super releaseSubviews];
 }
 
 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
@@ -8445,6 +8777,14 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [[self view] addSubview:status_];
 }
 
+- (void) releaseSubviews {
+    spinner_ = nil;
+    status_ = nil;
+    caption_ = nil;
+
+    [super releaseSubviews];
+}
+
 @end
 /* }}} */
 
@@ -8571,6 +8911,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     }
 }
 
+- (void) returnToCydia {
+    [self _loaded];
+}
+
 - (void) _saveConfig {
     _trace();
     MetaFile_.Sync();
@@ -8591,6 +8935,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
             NSLog(@"failure to serialize metadata: %@", error);
         }
     }
+
+    WriteSources();
 }
 
 // Navigation controller for the queuing badge.
@@ -8605,7 +8951,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) _updateData {
     [self _saveConfig];
-
     [self unloadData];
 
     UINavigationController *navigation = [self queueNavigationController];
@@ -8712,8 +9057,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     }
 
     [self _updateData];
-
-    [self refreshIfPossible];
 } }
 
 - (void) updateData {
@@ -8781,36 +9124,28 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) reloadData {
     [self reloadDataWithInvocation:nil];
+    if ([database_ progressDelegate] == nil)
+        [self _loaded];
 }
 
 - (void) syncData {
     [self _saveConfig];
+    [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
+}
 
-    FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
-    _assert(file != NULL);
-
-    for (NSString *key in [Sources_ allKeys]) {
-        NSDictionary *source([Sources_ objectForKey:key]);
-
-        fprintf(file, "%s %s %s\n",
-            [[source objectForKey:@"Type"] UTF8String],
-            [[source objectForKey:@"URI"] UTF8String],
-            [[source objectForKey:@"Distribution"] UTF8String]
-        );
-    }
-
-    fclose(file);
+- (void) addSource:(NSDictionary *) source {
+    AddSource(source);
+}
 
-    [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
+- (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
+    AddSource(href, distribution, sections);
 }
 
 - (void) addTrivialSource:(NSString *)href {
-    [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
-        @"deb", @"Type",
-        href, @"URI",
-        @"./", @"Distribution",
-    nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
+    AddSource(href, @"./");
+}
 
+- (void) updateValues {
     Changed_ = true;
 }
 
@@ -8901,6 +9236,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     ++locked_;
     [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
     --locked_;
+    [self refreshIfPossible];
 }
 
 - (void) showSettings {
@@ -9054,7 +9390,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (UIProgressHUD *) addProgressHUD {
-    UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
+    UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
     [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
 
     [window_ setUserInteractionEnabled:NO];
@@ -9066,7 +9402,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     UIView *view([target view]);
     [view addSubview:hud];
 
-    [hud show:YES];
+    [hud showInView:[tabbar_ view]];
 
     ++locked_;
     return hud;
@@ -9074,7 +9410,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) removeProgressHUD:(UIProgressHUD *)hud {
     --locked_;
-    [hud show:NO];
+    [hud hide];
     [hud removeFromSuperview];
     [window_ setUserInteractionEnabled:YES];
 }
@@ -9154,7 +9490,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
                 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
                 [(SourcesController *)controller showAddSourcePrompt];
             } else {
-                Source *source = [database_ sourceWithKey:argument];
+                Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
                 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
             }
         }
@@ -9213,15 +9549,19 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         [super applicationWillResignActive:application];
 }
 
-- (void) applicationWillTerminate:(UIApplication *)application {
-    Changed_ = true;
+- (void) saveState {
     [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
     [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
     [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
+    Changed_ = true;
 
     [self _saveConfig];
 }
 
+- (void) applicationWillTerminate:(UIApplication *)application {
+    [self saveState];
+}
+
 - (void) setConfigurationData:(NSString *)data {
     static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
 
@@ -9305,7 +9645,20 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [tabbar_ setUpdateDelegate:self];
 }
 
+- (void) _sendMemoryWarningNotification {
+    [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
+}
+
+- (void) _sendMemoryWarningNotifications {
+    while (true) {
+        [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
+        usleep(250000);
+    }
+}
+
 - (void) applicationDidFinishLaunching:(id)unused {
+    //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
+
 _trace();
     if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
         [self setApplicationSupportsShakeToEdit:NO];
@@ -9337,7 +9690,7 @@ _trace();
     broken_ = [NSMutableArray arrayWithCapacity:4];
 
     // XXX: I really need this thing... like, seriously... I'm sorry
-    [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
+    [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
 
     window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
     [window_ orderFront:self];
@@ -9404,7 +9757,8 @@ _trace();
         [window_ setUserInteractionEnabled:NO];
     }
 
-    [self reloadData];
+    [self reloadDataWithInvocation:nil];
+    [self refreshIfPossible];
     PrintTimes();
 
     [self disemulate];
@@ -9634,6 +9988,8 @@ int main(int argc, char *argv[]) {
     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];
     }
@@ -9778,7 +10134,7 @@ int main(int argc, char *argv[]) {
     ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
     BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
 
-    UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
+    UniqueID_ = [device uniqueIdentifier];
 
     CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
     $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
@@ -9815,15 +10171,28 @@ int main(int argc, char *argv[]) {
         Settings_ = [Metadata_ objectForKey:@"Settings"];
 
         Packages_ = [Metadata_ objectForKey:@"Packages"];
+
+        Values_ = [Metadata_ objectForKey:@"Values"];
         Sections_ = [Metadata_ objectForKey:@"Sections"];
         Sources_ = [Metadata_ objectForKey:@"Sources"];
 
         Token_ = [Metadata_ objectForKey:@"Token"];
+
+        Version_ = [Metadata_ objectForKey:@"Version"];
+
+        @synchronized (HostConfig_) {
+            CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
+        }
     }
 
     if (Settings_ != nil)
         Role_ = [Settings_ objectForKey:@"Role"];
 
+    if (Values_ == nil) {
+        Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
+        [Metadata_ setObject:Values_ forKey:@"Values"];
+    }
+
     if (Sections_ == nil) {
         Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
         [Metadata_ setObject:Sections_ forKey:@"Sections"];
@@ -9833,8 +10202,36 @@ int main(int argc, char *argv[]) {
         Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
         [Metadata_ setObject:Sources_ forKey:@"Sources"];
     }
+
+    if (Version_ == nil) {
+        Version_ = [NSNumber numberWithUnsignedInt:0];
+        [Metadata_ setObject:Version_ forKey:@"Version"];
+    }
+
+    @synchronized (HostConfig_) {
+        if (CydiaSource_ == nil) {
+            CydiaSource_ = @"apt.saurik.com";
+            [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
+        }
+    }
+
+    if ([Version_ unsignedIntValue] == 0) {
+        AddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
+        AddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
+        AddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
+        AddSource(@"http://repo666.ultrasn0w.com/", @"./");
+
+        Version_ = [NSNumber numberWithUnsignedInt:1];
+        [Metadata_ setObject:Version_ forKey:@"Version"];
+
+        [Metadata_ removeObjectForKey:@"LastUpdate"];
+
+        Changed_ = true;
+    }
     /* }}} */
 
+    WriteSources();
+
     _trace();
     MetaFile_.Open("/var/lib/cydia/metadata.cb0");
     _trace();