]> git.saurik.com Git - cydia.git/blobdiff - MobileCydia.mm
Background appcache initialization using custom URL.
[cydia.git] / MobileCydia.mm
index f24459b3d3714eec55a0fa62ad03bacf215ece90..64c388c97f3f26657e7f3d35aa4f874dc83a7188 100644 (file)
@@ -125,8 +125,6 @@ extern "C" {
 #include "SDURLCache/SDURLCache.h"
 
 #include "substrate.h"
-
-#include "Version.h"
 /* }}} */
 
 /* Profiler {{{ */
@@ -208,6 +206,35 @@ void PrintTimes() {
     while (false); \
     [_pool release];
 
+#define Cydia_ CYDIA_VERSION
+
+#define lprintf(args...) fprintf(stderr, args)
+
+#define ForRelease 1
+#define TraceLogging (1 && !ForRelease)
+#define HistogramInsertionSort (!ForRelease ? 0 : 0)
+#define ProfileTimes (0 && !ForRelease)
+#define ForSaurik (0 && !ForRelease)
+#define LogBrowser (0 && !ForRelease)
+#define TrackResize (0 && !ForRelease)
+#define ManualRefresh (1 && !ForRelease)
+#define ShowInternals (0 && !ForRelease)
+#define AlwaysReload (0 && !ForRelease)
+#define TryIndexedCollation (0 && !ForRelease)
+
+#if !TraceLogging
+#undef _trace
+#define _trace(args...)
+#endif
+
+#if !ProfileTimes
+#undef _profile
+#define _profile(name) {
+#undef _end
+#define _end }
+#define PrintTimes() do {} while (false)
+#endif
+
 // Hash Functions/Structures {{{
 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
 
@@ -293,7 +320,9 @@ static _finline void UpdateExternalStatus(uint64_t newStatus) {
     NSDate *future([NSDate distantFuture]);
     NSString *mode([loop currentMode] ?: NSDefaultRunLoopMode);
 
+_trace();
     while (!stopped && [loop runMode:mode beforeDate:future]);
+_trace();
 
     return [context count] == 0 ? nil : [context objectAtIndex:0];
 }
@@ -360,33 +389,6 @@ static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSC
 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
 
-#define lprintf(args...) fprintf(stderr, args)
-
-#define ForRelease 1
-#define TraceLogging (1 && !ForRelease)
-#define HistogramInsertionSort (!ForRelease ? 0 : 0)
-#define ProfileTimes (0 && !ForRelease)
-#define ForSaurik (0 && !ForRelease)
-#define LogBrowser (0 && !ForRelease)
-#define TrackResize (0 && !ForRelease)
-#define ManualRefresh (1 && !ForRelease)
-#define ShowInternals (0 && !ForRelease)
-#define AlwaysReload (0 && !ForRelease)
-#define TryIndexedCollation (0 && !ForRelease)
-
-#if !TraceLogging
-#undef _trace
-#define _trace(args...)
-#endif
-
-#if !ProfileTimes
-#undef _profile
-#define _profile(name) {
-#undef _end
-#define _end }
-#define PrintTimes() do {} while (false)
-#endif
-
 /* Radix Sort {{{ */
 typedef uint32_t (*SKRadixFunction)(id, void *);
 
@@ -842,9 +844,22 @@ class Pcre {
     const char *data_;
 
   public:
+    Pcre() :
+        code_(NULL),
+        study_(NULL)
+    {
+    }
+
     Pcre(const char *regex) :
+        code_(NULL),
         study_(NULL)
     {
+        this->operator =(regex);
+    }
+
+    void operator =(const char *regex) {
+        _assert(code_ == NULL);
+
         const char *error;
         int offset;
         code_ = pcre_compile(regex, 0, &error, &offset, NULL);
@@ -863,19 +878,31 @@ class Pcre {
         delete matches_;
     }
 
-    NSString *operator [](size_t match) {
+    NSString *operator [](size_t match) const {
         return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
     }
 
-    bool operator ()(NSString *data) {
+    _finline bool operator ()(NSString *data) {
         // XXX: length is for characters, not for bytes
         return operator ()([data UTF8String], [data length]);
     }
 
+    _finline bool operator ()(const char *data) {
+        return operator ()(data, strlen(data));
+    }
+
     bool operator ()(const char *data, size_t size) {
         data_ = data;
         return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
     }
+
+    NSString *operator ->*(NSString *format) const {
+        id values[capture_];
+        for (int i(0); i != capture_; ++i)
+            values[i] = this->operator [](i + 1);
+
+        return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
+    }
 };
 /* }}} */
 /* Mime Addresses {{{ */
@@ -1067,7 +1094,15 @@ bool IsWildcat_;
 static CGFloat ScreenScale_;
 static NSString *Idiom_;
 
-static NSMutableSet *CydiaHosts_;
+static NSMutableDictionary *SessionData_;
+static NSObject *HostConfig_;
+static NSMutableSet *BridgedHosts_;
+static NSMutableSet *PipelinedHosts_;
+
+static NSString *kCydiaProgressEventTypeError = @"Error";
+static NSString *kCydiaProgressEventTypeInformation = @"Information";
+static NSString *kCydiaProgressEventTypeStatus = @"Status";
+static NSString *kCydiaProgressEventTypeWarning = @"Warning";
 /* }}} */
 
 /* Display Helpers {{{ */
@@ -1170,7 +1205,6 @@ bool isSectionVisible(NSString *section) {
 - (CYViewController *) pageForPackage:(NSString *)name;
 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
-- (void) addCydiaHost:(NSString *)host;
 @end
 /* }}} */
 
@@ -1251,7 +1285,7 @@ class Status :
 
     virtual void Fetch(pkgAcquire::ItemDesc &item) {
         NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
-        CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:@"STATUS" forItem:item]);
+        CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
         [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
     }
 
@@ -1269,7 +1303,7 @@ class Status :
         if (error.empty())
             return;
 
-        CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:@"ERROR" forItem:item]);
+        CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
         [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
     }
 
@@ -1489,9 +1523,9 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
     if (value != nil) {
         NSString *mode(nil); {
             NSString *type([self type]);
-            if ([type isEqualToString:@"ERROR"])
+            if ([type isEqualToString:kCydiaProgressEventTypeError])
                 mode = UCLocalize("ERROR");
-            else if ([type isEqualToString:@"WARNING"])
+            else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
                 mode = UCLocalize("WARNING");
         }
 
@@ -1667,7 +1701,7 @@ static void PackageImport(const void *key, const void *value, void *context) {
 - (NSString *) host;
 
 - (NSString *) name;
-- (NSString *) description;
+- (NSString *) shortDescription;
 - (NSString *) label;
 - (NSString *) origin;
 - (NSString *) version;
@@ -1704,13 +1738,13 @@ static void PackageImport(const void *key, const void *value, void *context) {
 
 + (NSArray *) _attributeKeys {
     return [NSArray arrayWithObjects:
-        @"description",
         @"distribution",
         @"host",
         @"key",
         @"label",
         @"name",
         @"origin",
+        @"shortDescription",
         @"trusted",
         @"type",
         @"uri",
@@ -1854,7 +1888,7 @@ static void PackageImport(const void *key, const void *value, void *context) {
     return origin_.empty() ? (id) authority_ : origin_;
 }
 
-- (NSString *) description {
+- (NSString *) shortDescription {
     return description_;
 }
 
@@ -3439,11 +3473,11 @@ static NSString *Warning_;
             [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
         } else if (strncmp(data, "status: ", 8) == 0) {
             // status: <package>: {unpacked,half-configured,installed}
-            CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:@"STATUS"]);
+            CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
             [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
         } else if (strncmp(data, "processing: ", 12) == 0) {
             // processing: configure: config-test
-            CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:@"STATUS"]);
+            CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
             [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
         } else if (pmstatus_r(data, size)) {
             std::string type([pmstatus_r[1] UTF8String]);
@@ -3458,10 +3492,10 @@ static NSString *Warning_;
             NSString *string = pmstatus_r[4];
 
             if (type == "pmerror") {
-                CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"ERROR" forPackage:package]);
+                CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
                 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
             } else if (type == "pmstatus") {
-                CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"STATUS" forPackage:package]);
+                CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
                 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
             } else if (type == "pmconffile")
                 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
@@ -3482,7 +3516,7 @@ static NSString *Warning_;
     while (std::getline(is, line)) {
         lprintf("O:%s\n", line.c_str());
 
-        CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:@"INFORMATION"]);
+        CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
         [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
     }
 
@@ -3619,7 +3653,7 @@ static NSString *Warning_;
 
         lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
 
-        [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
+        [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
     }
 
     return fatal;
@@ -3686,7 +3720,7 @@ static NSString *Warning_;
         // else if (error == "Malformed Status line")
         // else if (error == "The list of sources could not be read.")
         else {
-            [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
+            [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
             return;
         }
 
@@ -3711,7 +3745,7 @@ static NSString *Warning_;
         return;
 
     if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
-        [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:@"ERROR"] forTask:title];
+        [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
         return;
     }
 
@@ -3723,7 +3757,7 @@ static NSString *Warning_;
             return;
 
         if (cache_->BrokenCount() != 0) {
-            [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:@"ERROR"] forTask:title];
+            [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
             return;
         }
 
@@ -4033,7 +4067,42 @@ static NSString *Warning_;
 @end
 /* }}} */
 
-/* Web Scripting {{{ */
+@interface Diversion : NSObject {
+    Pcre pattern_;
+    _H<NSString> key_;
+    _H<NSString> format_;
+}
+
+@end
+
+@implementation Diversion
+
+- (id) initWithFrom:(NSString *)from to:(NSString *)to {
+    if ((self = [super init]) != nil) {
+        pattern_ = [from UTF8String];
+        key_ = from;
+        format_ = to;
+    } return self;
+}
+
+- (NSString *) divert:(NSString *)url {
+    return !pattern_(url) ? nil : pattern_->*format_;
+}
+
+- (NSString *) key {
+    return key_;
+}
+
+- (NSUInteger) hash {
+    return [key_ hash];
+}
+
+- (BOOL) isEqual:(Diversion *)object {
+    return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
+}
+
+@end
+
 @interface CydiaObject : NSObject {
     id indirect_;
     _transient id delegate_;
@@ -4043,6 +4112,17 @@ static NSString *Warning_;
 
 @end
 
+@interface CYBrowserController : BrowserController {
+    CydiaObject *cydia_;
+}
+
++ (void) addDiversion:(Diversion *)diversion;
+
+@end
+
+static NSMutableSet *Diversions_;
+
+/* Web Scripting {{{ */
 @implementation CydiaObject
 
 - (void) dealloc {
@@ -4130,12 +4210,16 @@ static NSString *Warning_;
 
 + (NSString *) webScriptNameForSelector:(SEL)selector {
     if (false);
-    else if (selector == @selector(addCydiaHost:))
-        return @"addCydiaHost";
+    else if (selector == @selector(addBridgedHost:))
+        return @"addBridgedHost";
+    else if (selector == @selector(addPipelinedHost:scheme:))
+        return @"addPipelinedHost";
     else if (selector == @selector(addTrivialSource:))
         return @"addTrivialSource";
     else if (selector == @selector(close))
         return @"close";
+    else if (selector == @selector(divert::))
+        return @"divert";
     else if (selector == @selector(du:))
         return @"du";
     else if (selector == @selector(stringWithFormat:arguments:))
@@ -4150,14 +4234,20 @@ static NSString *Warning_;
         return @"getInstalledPackages";
     else if (selector == @selector(getPackageById:))
         return @"getPackageById";
+    else if (selector == @selector(getSessionValue:))
+        return @"getSessionValue";
     else if (selector == @selector(installPackages:))
         return @"installPackages";
     else if (selector == @selector(localizedStringForKey:value:table:))
         return @"localize";
+    else if (selector == @selector(popViewController:))
+        return @"popViewController";
     else if (selector == @selector(refreshSources))
         return @"refreshSources";
     else if (selector == @selector(removeButton))
         return @"removeButton";
+    else if (selector == @selector(setSessionValue::))
+        return @"setSessionValue";
     else if (selector == @selector(substitutePackageNames:))
         return @"substitutePackageNames";
     else if (selector == @selector(scrollToBottom:))
@@ -4198,6 +4288,10 @@ static NSString *Warning_;
     return [feature isEqualToString:@"window.open"];
 }
 
+- (void) divert:(NSString *)from :(NSString *)to {
+    [CYBrowserController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
+}
+
 - (NSNumber *) getKernelNumber:(NSString *)name {
     const char *string([name UTF8String]);
 
@@ -4232,8 +4326,36 @@ static NSString *Warning_;
     return [NSString stringWithCString:value];
 }
 
-- (void) addCydiaHost:(NSString *)host {
-    [delegate_ performSelectorOnMainThread:@selector(addCydiaHost:) withObject:host waitUntilDone:NO];
+- (id) getSessionValue:(NSString *)key {
+@synchronized (SessionData_) {
+    return [SessionData_ objectForKey:key];
+} }
+
+- (void) setSessionValue:(NSString *)key :(NSString *)value {
+@synchronized (SessionData_) {
+    if (value == (id) [WebUndefined undefined])
+        [SessionData_ removeObjectForKey:key];
+    else
+        [SessionData_ setObject:value forKey:key];
+} }
+
+- (void) addBridgedHost:(NSString *)host {
+@synchronized (HostConfig_) {
+    [BridgedHosts_ addObject:host];
+} }
+
+- (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
+@synchronized (HostConfig_) {
+    if (scheme != (id) [WebUndefined undefined])
+        host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
+
+    [PipelinedHosts_ addObject:host];
+} }
+
+- (void) popViewController:(NSNumber *)value {
+    if (value == (id) [WebUndefined undefined])
+        value = [NSNumber numberWithBool:YES];
+    [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
 }
 
 - (void) addTrivialSource:(NSString *)href {
@@ -4509,16 +4631,12 @@ static NSString *Warning_;
     } return self;
 }
 
-// XXX: factor this out somewhere
-- (UIColor *) groupTableViewBackgroundColor {
-    UIDevice *device([UIDevice currentDevice]);
-    bool iPad([device respondsToSelector:@selector(userInterfaceIdiom)] && [device userInterfaceIdiom] == UIUserInterfaceIdiomPad);
-    return iPad ? [UIColor colorWithRed:0.821 green:0.834 blue:0.860 alpha:1] : [UIColor groupTableViewBackgroundColor];
-}
-
 - (void) loadView {
     [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
-    [[self view] setBackgroundColor:[self groupTableViewBackgroundColor]];
+
+    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];
@@ -4545,12 +4663,6 @@ static NSString *Warning_;
 /* }}} */
 
 /* Cydia Browser Controller {{{ */
-@interface CYBrowserController : BrowserController {
-    CydiaObject *cydia_;
-}
-
-@end
-
 @implementation CYBrowserController
 
 - (void) dealloc {
@@ -4562,7 +4674,12 @@ static NSString *Warning_;
     return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
 }
 
-- (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
++ (void) initialize {
+    Diversions_ = [[NSMutableSet alloc] initWithCapacity:0];
+}
+
++ (void) addDiversion:(Diversion *)diversion {
+    [Diversions_ addObject:diversion];
 }
 
 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
@@ -4570,32 +4687,34 @@ static NSString *Warning_;
 
     WebDataSource *source([frame dataSource]);
     NSURLResponse *response([source response]);
-
     NSURL *url([response URL]);
-    //NSString *scheme([url scheme]);
-    NSString *host([url host]);
 
-    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
-        NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
-        NSDictionary *headers([http allHeaderFields]);
-        [self setHeaders:headers forHost:host];
+    @synchronized (HostConfig_) {
+        if ([[[url scheme] lowercaseString] isEqualToString:@"https"])
+            if ([BridgedHosts_ containsObject:[url host]])
+                [window setValue:cydia_ forKey:@"cydia"];
     }
-
-    if ([CydiaHosts_ containsObject:host])
-        [window setValue:cydia_ forKey:@"cydia"];
 }
 
 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
     NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
 
+  divert:
+    NSURL *url([copy URL]);
+    NSString *href([url absoluteString]);
+
+    for (Diversion *diversion in Diversions_)
+        if (NSString *diverted = [diversion divert:href]) {
+            [copy setURL:[NSURL URLWithString:diverted]];
+            goto divert;
+        }
+
     if (System_ != NULL)
         [copy setValue:System_ forHTTPHeaderField:@"X-System"];
     if (Machine_ != NULL)
         [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
     if (Token_ != nil)
         [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
-    if (Role_ != nil)
-        [copy setValue:Role_ forHTTPHeaderField:@"X-Role"];
 
     return copy;
 }
@@ -5161,9 +5280,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) viewWillAppear:(BOOL)animated {
-    if (![self hasLoaded])
-        [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
-
+    [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
     [super viewWillAppear:animated];
 }
 
@@ -6052,6 +6169,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) reloadData {
+    [super reloadData];
+
     package_ = [database_ packageWithName:name_];
 
     [buttons_ removeAllObjects];
@@ -6087,8 +6206,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         target:self
         action:@selector(customButtonClicked)
     ] autorelease];
-
-    [super reloadData];
 }
 
 - (bool) isLoading {
@@ -6703,7 +6820,18 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 @end
 /* }}} */
 
-@class CYNavigationController;
+/* Cydia Navigation Controller Interface {{{ */
+@interface CYNavigationController : UINavigationController {
+    _transient Database *database_;
+    _transient id<UINavigationControllerDelegate> delegate_;
+}
+
+- (NSArray *) navigationURLCollection;
+- (id) initWithDatabase:(Database *)database;
+- (void) unloadData:(BOOL)selected;
+
+@end
+/* }}} */
 
 /* Cydia Tab Bar Controller {{{ */
 @interface CYTabBarController : UITabBarController <
@@ -6728,6 +6856,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 - (void) beginUpdate;
 - (void) raiseBar:(BOOL)animated;
 - (BOOL) updating;
+- (void) unloadData;
 
 @end
 
@@ -6777,11 +6906,13 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     return items;
 }
 
-- (void) reloadData {
-    for (CYViewController *controller in [self viewControllers])
-        [controller reloadData];
+- (void) unloadData {
+    CYNavigationController *selected((CYNavigationController *) [self selectedViewController]);
+    for (CYNavigationController *controller in [self viewControllers])
+        [controller unloadData:(controller == selected)];
 
-    [(CYNavigationController *)[self unselectedViewController] reloadData];
+    if (CYNavigationController *unselected = (CYNavigationController *) [self unselectedViewController])
+        [unselected unloadData:YES];
 }
 
 - (void) dealloc {
@@ -6993,19 +7124,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 @end
 /* }}} */
-/* Cydia Navigation Controller {{{ */
-@interface CYNavigationController : UINavigationController {
-    _transient Database *database_;
-    _transient id<UINavigationControllerDelegate> delegate_;
-}
-
-- (NSArray *) navigationURLCollection;
-- (id) initWithDatabase:(Database *)database;
-- (void) reloadData;
-
-@end
-
 
+/* Cydia Navigation Controller Implementation {{{ */
 @implementation CYNavigationController
 
 - (NSArray *) navigationURLCollection {
@@ -7020,14 +7140,18 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     return stack;
 }
 
-- (void) reloadData {
+- (void) unloadData:(BOOL)selected {
+    CYViewController *top((CYViewController *) [self topViewController]);
+    bool loaded([top hasLoaded]);
+
     for (CYViewController *page in [self viewControllers]) {
-        // Only reload controllers that have already loaded.
-        // This prevents a page from accidentally loading too
-        // early if it hasn't been shown on the screen yet.
-        if ([page hasLoaded])
-            [page reloadData];
+        NSLog(@"%@ %@", page, top);
+        if (!selected || page != top)
+            [page unloadData];
     }
+
+    if (selected && loaded)
+        [top reloadData];
 }
 
 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
@@ -7200,7 +7324,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     NSMutableArray *sections_;
     NSMutableArray *filtered_;
     UITableView *list_;
-    BOOL editing_;
 }
 
 - (id) initWithDatabase:(Database *)database;
@@ -7223,24 +7346,22 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) updateNavigationItem {
-    [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
+    [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
     if ([sections_ count] == 0) {
         [[self navigationItem] setRightBarButtonItem:nil];
     } else {
         [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
-            initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
+            initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
             target:self
             action:@selector(editButtonClicked)
         ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
     }
 }
 
-- (BOOL) isEditing {
-    return editing_;
-}
+- (void) setEditing:(BOOL)editing animated:(BOOL)animated {
+    [super setEditing:editing animated:animated];
 
-- (void) setEditing:(BOOL)editing {
-    if ((editing_ = editing))
+    if (editing)
         [list_ reloadData];
     else
         [delegate_ updateData];
@@ -7255,16 +7376,27 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) viewWillDisappear:(BOOL)animated {
     [super viewWillDisappear:animated];
-    if (editing_) [self setEditing:NO];
+    if ([self isEditing]) [self setEditing:NO];
 }
 
 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
-    Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
+    Section *section = nil;
+    int index = [indexPath row];
+    if (![self isEditing]) {
+        index -= 1; 
+        if (index >= 0)
+            section = [filtered_ objectAtIndex:index];
+    } else {
+        section = [sections_ objectAtIndex:index];
+    }
     return section;
 }
 
 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
-    return editing_ ? [sections_ count] : [filtered_ count] + 1;
+    if ([self isEditing])
+        return [sections_ count];
+    else
+        return [filtered_ count] + 1;
 }
 
 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
@@ -7278,13 +7410,13 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     if (cell == nil)
         cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
 
-    [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
+    [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
 
     return cell;
 }
 
 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
-    if (editing_)
+    if ([self isEditing])
         return;
 
     Section *section = [self sectionAtIndexPath:indexPath];
@@ -7385,7 +7517,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) editButtonClicked {
-    [self setEditing:(!editing_)];
+    [self setEditing:![self isEditing] animated:YES];
 }
 
 @end
@@ -7402,7 +7534,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     NSMutableArray *sections_;
     UITableView *list_;
     unsigned upgrades_;
-    BOOL hasSentFirstLoad_;
 }
 
 - (id) initWithDatabase:(Database *)database;
@@ -7423,21 +7554,9 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     return [NSURL URLWithString:@"cydia://changes"];
 }
 
-- (void) viewWillAppear:(BOOL)animated {
-    // Loads after it appears, so don't load beforehand.
-    loaded_ = YES;
-    [super viewWillAppear:animated];
-}
-
 - (void) viewDidAppear:(BOOL)animated {
     [super viewDidAppear:animated];
-
-    if (!hasSentFirstLoad_) {
-        hasSentFirstLoad_ = YES;
-        [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
-    } else {
-        [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
-    }
+    [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
 }
 
 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
@@ -7547,7 +7666,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     _trace();
 }
 
-- (void) reloadData {
+- (void) _reloadData {
 @synchronized (database_) {
     era_ = [database_ era];
     NSArray *packages = [database_ packages];
@@ -7645,6 +7764,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     PrintTimes();
 } }
 
+- (void) reloadData {
+    [super reloadData];
+    [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
+}
+
 @end
 /* }}} */
 /* Search Controller {{{ */
@@ -7721,8 +7845,9 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) reloadData {
     [self setObject:[search_ text]];
-    [super reloadData];
     [self resetCursor];
+
+    [super reloadData];
 }
 
 - (void) didSelectPackage:(Package *)package {
@@ -8116,6 +8241,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [key_ release];
     key_ = [[source_ key] retain];
     [self setObject:source_];
+
     [[self navigationItem] setTitle:[source_ label]];
 
     [super reloadData];
@@ -8393,8 +8519,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
     if (UniqueID_ != nil)
         [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
-    if (Role_ != nil)
-        [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
 
     return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
 }
@@ -8772,6 +8896,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) reloadData {
     [super reloadData];
+
     [table_ reloadData];
 }
 
@@ -8961,7 +9086,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 - (void) _updateData {
     [self _saveConfig];
 
-    [tabbar_ reloadData];
+    [tabbar_ unloadData];
 
     CYNavigationController *navigation = [self queueNavigationController];
 
@@ -9668,16 +9793,14 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [tabbar_ setUpdateDelegate:self];
 }
 
-- (void) addCydiaHost:(NSString *)host {
-    [CydiaHosts_ addObject:host];
-}
-
 - (void) applicationDidFinishLaunching:(id)unused {
 _trace();
     if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
         [self setApplicationSupportsShakeToEdit:NO];
 
-    [self addCydiaHost:[[NSURL URLWithString:CydiaURL(@"")] host]];
+    @synchronized (HostConfig_) {
+        [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
+    }
 
     [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
         initWithMemoryCapacity:524288
@@ -9698,6 +9821,9 @@ _trace();
     essential_ = [[NSMutableArray alloc] initWithCapacity:4];
     broken_ = [[NSMutableArray alloc] initWithCapacity:4];
 
+    // XXX: I really need this thing... like, seriously... I'm sorry
+    [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
+
     window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
     [window_ orderFront:self];
     [window_ makeKey:self];
@@ -9736,6 +9862,21 @@ _trace();
 _trace();
 }
 
+- (NSArray *) defaultStartPages {
+    NSMutableArray *standard = [NSMutableArray array];
+    [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
+    [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
+    [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
+    if (!IsWildcat_) {
+        [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
+    } else {
+        [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
+        [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
+    }
+    [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
+    return standard;
+}
+
 - (void) loadData {
 _trace();
     if (Role_ == nil) {
@@ -9753,42 +9894,48 @@ _trace();
 
     [self disemulate];
 
-    int selectedIndex = 0;
-    NSMutableArray *items = nil;
+    int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
+    NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
+    int standardIndex = 0;
+    NSArray *standard = [self defaultStartPages];
 
-    bool recently = false;
-    NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
-    if (closed != nil) {
+    BOOL valid = YES;
+
+    if (saved == nil)
+        valid = NO;
+
+    NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
+    if (valid && closed != nil) {
         NSTimeInterval interval([closed timeIntervalSinceNow]);
         // XXX: Is 15 minutes the optimal time here?
-        if (interval <= 0 && interval > -(15*60))
-            recently = true;
+        if (interval > 0 && interval <= -(15*60))
+            valid = NO;
     }
 
-    items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
-    selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
-
-    BOOL enough = YES;
-    for (NSArray *entry in items)
-        if ([entry count] <= 0)
-            enough = NO;
+    if (valid && [saved count] != [standard count])
+        valid = NO;
 
-    if (!recently || !items || !enough) {
-        selectedIndex = 0;
-        items = [NSMutableArray array];
-        [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
-        [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
-        [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
-        if (!IsWildcat_) {
-            [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
-        } else {
-            [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
-            [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
+    if (valid) {
+        for (unsigned int i = 0; i < [standard count]; i++) {
+            NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
+            // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
+            //      but it's good enough for now.
+            if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
+                valid = NO;
+                break;
+            }
         }
-        [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
     }
 
-    [tabbar_ setSelectedIndex:selectedIndex];
+    NSArray *items = nil;
+    if (valid) {
+        [tabbar_ setSelectedIndex:savedIndex];
+        items = saved;
+    } else {
+        [tabbar_ setSelectedIndex:standardIndex];
+        items = standard;
+    }
+
     for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
         NSArray *stack = [items objectAtIndex:tab];
         CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
@@ -9861,52 +10008,63 @@ MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL
     return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
 }
 
-static NSNumber *shouldPlayKeyboardSounds;
+static NSSet *MobilizedFiles_;
 
-Class $UIHardware;
+static NSURL *MobilizeURL(NSURL *url) {
+    NSString *path([url path]);
+    if ([path hasPrefix:@"/var/root/"]) {
+        NSString *file([path substringFromIndex:10]);
+        if ([MobilizedFiles_ containsObject:file])
+            url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
+    }
 
-MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
-    switch (sound) {
-        case 1104: // Keyboard Button Clicked
-        case 1105: // Keyboard Delete Repeated
-            if (shouldPlayKeyboardSounds == nil) {
-                NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
-                shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
-            }
+    return url;
+}
 
-            if (![shouldPlayKeyboardSounds boolValue])
-                break;
+Class $CFXPreferencesPropertyListSource;
+@class CFXPreferencesPropertyListSource;
 
-        default:
-            _UIHardware$_playSystemSound$(self, _cmd, sound);
-    }
+MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
+    NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
+    NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
+    url = MobilizeURL(url);
+    BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
+    //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
+    url = old;
+    [pool release];
+    return value;
 }
 
-Class $UIApplication;
+MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
+    NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
+    NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
+    url = MobilizeURL(url);
+    void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
+    //NSLog(@"%@ %@", [url absoluteString], value);
+    url = old;
+    [pool release];
+    return value;
+}
 
-MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
-    static BOOL initialized = NO;
-    static BOOL started = NO;
+Class $NSURLConnection;
 
-    NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
-    BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
+MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
+    NSMutableURLRequest *copy([request mutableCopy]);
 
-    if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
-        id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
-        if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
-        if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
+    NSURL *url([copy URL]);
+    NSString *host([url host]);
+    NSString *scheme([[url scheme] lowercaseString]);
 
-        if (initialized && !enabled) {
-            initialized = NO;
-            [bundle performSelector:@selector(_accessibilityStopServer)];
-        } else if (enabled) {
-            initialized = YES;
-            if (!started) {
-                started = YES;
-                [bundle performSelector:@selector(_accessibilityStartServer)];
-            }
-        }
+    NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
+
+    @synchronized (HostConfig_) {
+        if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
+            if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
+                [copy setHTTPShouldUsePipelining:YES];
     }
+
+    if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
+    } return self;
 }
 
 int main(int argc, char *argv[]) { _pooled
@@ -9939,15 +10097,40 @@ int main(int argc, char *argv[]) { _pooled
             NSLog(@"unknown UIUserInterfaceIdiom!");
     }
 
-    CydiaHosts_ = [NSMutableSet setWithCapacity:2];
+    SessionData_ = [[NSMutableDictionary alloc] initWithCapacity:4];
+
+    HostConfig_ = [[NSObject alloc] init];
+    @synchronized (HostConfig_) {
+        BridgedHosts_ = [NSMutableSet setWithCapacity:4];
+        PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
+    }
 
     UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
 
     PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
 
+    MobilizedFiles_ = [NSMutableSet setWithObjects:
+        @"Library/Preferences/com.apple.Accessibility.plist",
+        @"Library/Preferences/com.apple.preferences.sounds.plist",
+    nil];
+
     /* Library Hacks {{{ */
     class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
 
+    $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
+
+    Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
+    if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
+        _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
+        method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
+    }
+
+    Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
+    if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
+        _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
+        method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
+    }
+
     $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
     Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
     if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
@@ -9955,37 +10138,40 @@ int main(int argc, char *argv[]) { _pooled
         method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
     }
 
-    $UIHardware = objc_getClass("UIHardware");
-    Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
-    if (UIHardware$_playSystemSound$ != NULL) {
-        _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
-        method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
-    }
-
-    $UIApplication = objc_getClass("UIApplication");
-    Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
-    if (UIApplication$_updateApplicationAccessibility != NULL) {
-        _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
-        method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
+    $NSURLConnection = objc_getClass("NSURLConnection");
+    Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
+    if (NSURLConnection$init$ != NULL) {
+        _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
+        method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
     }
     /* }}} */
     /* Set Locale {{{ */
     Locale_ = CFLocaleCopyCurrent();
     Languages_ = [NSLocale preferredLanguages];
+
     //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
     //NSLog(@"%@", [Languages_ description]);
 
     const char *lang;
-    if (Languages_ == nil || [Languages_ count] == 0)
+    if (Locale_ != NULL)
+        lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
+    else if (Languages_ != nil && [Languages_ count] != 0)
+        lang = [[Languages_ objectAtIndex:0] UTF8String];
+    else
         // XXX: consider just setting to C and then falling through?
         lang = NULL;
-    else {
-        lang = [[Languages_ objectAtIndex:0] UTF8String];
-        setenv("LANG", lang, true);
-        std::setlocale(LC_ALL, lang);
+
+    if (lang != NULL) {
+        Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
+        lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
     }
 
     NSLog(@"Setting Language: %s", lang);
+
+    if (lang != NULL) {
+        setenv("LANG", lang, true);
+        std::setlocale(LC_ALL, lang);
+    }
     /* }}} */
 
     apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);