]> git.saurik.com Git - cydia.git/blobdiff - MobileCydia.mm
Port build environment to Xcode 5.0.2 (iOS 7 SDK).
[cydia.git] / MobileCydia.mm
index 0bd84783994872483065e771e275e01c15f27c8f..79163ba9506a496e611d2dbfe5a681fc6007dd1f 100644 (file)
@@ -1,40 +1,22 @@
 /* Cydia - iPhone UIKit Front-End for Debian APT
- * Copyright (C) 2008-2011  Jay Freeman (saurik)
+ * Copyright (C) 2008-2013  Jay Freeman (saurik)
 */
 
-/* Modified BSD License {{{ */
+/* GNU General Public License, Version 3 {{{ */
 /*
- *        Redistribution and use in source and binary
- * forms, with or without modification, are permitted
- * provided that the following conditions are met:
+ * Cydia is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published
+ * by the Free Software Foundation, either version 3 of the License,
+ * or (at your option) any later version.
  *
- * 1. Redistributions of source code must retain the
- *    above copyright notice, this list of conditions
- *    and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the
- *    above copyright notice, this list of conditions
- *    and the following disclaimer in the documentation
- *    and/or other materials provided with the
- *    distribution.
- * 3. The name of the author may not be used to endorse
- *    or promote products derived from this software
- *    without specific prior written permission.
+ * Cydia is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
  *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
- * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
- * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
+ * You should have received a copy of the GNU General Public License
+ * along with Cydia.  If not, see <http://www.gnu.org/licenses/>.
+**/
 /* }}} */
 
 // XXX: wtf/FastMalloc.h... wtf?
@@ -56,7 +38,6 @@
 #include <CoreFoundation/CFInternal.h>
 #endif
 
-#include <CoreFoundation/CFPriv.h>
 #include <CoreFoundation/CFUniChar.h>
 
 #include <SystemConfiguration/SystemConfiguration.h>
 #include <QuartzCore/CALayer.h>
 
 #include <WebCore/WebCoreThread.h>
+#include <WebKit/DOMHTMLIFrameElement.h>
 
 #include <algorithm>
 #include <iomanip>
+#include <set>
 #include <sstream>
 #include <string>
 
@@ -126,10 +109,13 @@ extern "C" {
 #include <CydiaSubstrate/CydiaSubstrate.h>
 #include "Menes/Menes.h"
 
+#include "CyteKit/IndirectDelegate.h"
 #include "CyteKit/PerlCompatibleRegEx.hpp"
 #include "CyteKit/TableViewCell.h"
+#include "CyteKit/TabBarController.h"
 #include "CyteKit/WebScriptObject-Cyte.h"
 #include "CyteKit/WebViewController.h"
+#include "CyteKit/WebViewTableViewCell.h"
 #include "CyteKit/stringWithUTF8Bytes.h"
 
 #include "Cydia/MIMEAddress.h"
@@ -209,6 +195,10 @@ void PrintTimes() {
 #define _end }
 /* }}} */
 
+// XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
+#define synchronized(lock) \
+    synchronized(static_cast<NSObject *>(lock))
+
 extern NSString *Cydia_;
 
 #define lprintf(args...) fprintf(stderr, args)
@@ -252,6 +242,39 @@ NSString *Elision_;
 static NSString *Error_;
 static NSString *Warning_;
 
+static NSString *Cache_;
+
+static void (*$SBSSetInterceptsMenuButtonForever)(bool);
+
+static CFStringRef (*$MGCopyAnswer)(CFStringRef);
+
+static NSString *UniqueIdentifier(UIDevice *device = nil) {
+    if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
+        return [device ?: [UIDevice currentDevice] uniqueIdentifier];
+    else
+        return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
+}
+
+static bool IsReachable(const char *name) {
+    SCNetworkReachabilityFlags flags; {
+        SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
+        SCNetworkReachabilityGetFlags(reachability, &flags);
+        CFRelease(reachability);
+    }
+
+    // XXX: this elaborate mess is what Apple is using to determine this? :(
+    // XXX: do we care if the user has to intervene? maybe that's ok?
+    return
+        (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
+            (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
+                (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
+                (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
+            ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
+            (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
+        )
+    ;
+}
+
 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
 
 static _finline NSString *CydiaURL(NSString *path) {
@@ -265,6 +288,15 @@ static _finline NSString *CydiaURL(NSString *path) {
     return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
 }
 
+static void ReapZombie(pid_t pid) {
+    int status;
+  wait:
+    if (waitpid(pid, &status, 0) == -1)
+        if (errno == EINTR)
+            goto wait;
+        else _assert(false);
+}
+
 static _finline void UpdateExternalStatus(uint64_t newStatus) {
     int notify_token;
     if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
@@ -404,7 +436,6 @@ NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *s
 /* Cydia NSString Additions {{{ */
 @interface NSString (Cydia)
 - (NSComparisonResult) compareByPath:(NSString *)other;
-- (NSString *) stringByCachingURLWithCurrentCDN;
 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
 @end
 
@@ -440,13 +471,6 @@ NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *s
     return result == NSOrderedSame ? value : result;
 }
 
-- (NSString *) stringByCachingURLWithCurrentCDN {
-    return [self
-        stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
-        withString:@"://cache.cydia.saurik.com/"
-    ];
-}
-
 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
     return [(id)CFURLCreateStringByAddingPercentEscapes(
         kCFAllocatorDefault,
@@ -646,7 +670,7 @@ class CYColor {
 /* }}} */
 
 /* Random Global Variables {{{ */
-static const int PulseInterval_ = 50000;
+static int PulseInterval_ = 500000;
 
 static const NSString *UI_;
 
@@ -662,6 +686,7 @@ static bool Queuing_;
 static CYColor Blue_;
 static CYColor Blueish_;
 static CYColor Black_;
+static CYColor Folder_;
 static CYColor Off_;
 static CYColor White_;
 static CYColor Gray_;
@@ -680,20 +705,20 @@ static BOOL Ignored_;
 static _H<UIFont> Font12_;
 static _H<UIFont> Font12Bold_;
 static _H<UIFont> Font14_;
+static _H<UIFont> Font18_;
 static _H<UIFont> Font18Bold_;
 static _H<UIFont> Font22Bold_;
 
 static const char *Machine_ = NULL;
-static NSString *System_ = nil;
+static _H<NSString> System_;
 static NSString *SerialNumber_ = nil;
 static NSString *ChipID_ = nil;
 static NSString *BBSNum_ = nil;
 static _H<NSString> Token_;
-static NSString *UniqueID_ = nil;
-static NSString *PLMN_ = nil;
-static NSString *Build_ = nil;
-static NSString *Product_ = nil;
-static NSString *Safari_ = nil;
+static _H<NSString> UniqueID_;
+static _H<NSString> UserAgent_;
+static _H<NSString> Product_;
+static _H<NSString> Safari_;
 
 static CFLocaleRef Locale_;
 static NSArray *Languages_;
@@ -702,20 +727,18 @@ static CGColorSpaceRef space_;
 static NSDictionary *SectionMap_;
 static NSMutableDictionary *Metadata_;
 static _transient NSMutableDictionary *Settings_;
-static _transient NSString *Role_;
 static _transient NSMutableDictionary *Packages_;
 static _transient NSMutableDictionary *Values_;
 static _transient NSMutableDictionary *Sections_;
 _H<NSMutableDictionary> Sources_;
 static _transient NSNumber *Version_;
-_H<NSString> CydiaSource_;
 bool Changed_;
 static time_t now_;
 
 bool IsWildcat_;
 static CGFloat ScreenScale_;
 static NSString *Idiom_;
-_H<NSString> Firmware_;
+static _H<NSString> Firmware_;
 static NSString *Major_;
 
 static _H<NSMutableDictionary> SessionData_;
@@ -840,6 +863,16 @@ static NSString *CYHex(NSData *data, bool reverse = false) {
 
 @class CYPackageController;
 
+@protocol SourceDelegate
+- (void) setFetch:(NSNumber *)fetch;
+@end
+
+@protocol FetchDelegate
+- (bool) isSourceCancelled;
+- (void) startSourceFetch:(NSString *)uri;
+- (void) stopSourceFetch:(NSString *)uri;
+@end
+
 @protocol CydiaDelegate
 - (void) returnToCydia;
 - (void) saveState;
@@ -851,44 +884,34 @@ static NSString *CYHex(NSData *data, bool reverse = false) {
 - (void) removePackage:(Package *)package;
 - (void) beginUpdate;
 - (BOOL) updating;
+- (bool) requestUpdate;
 - (void) distUpgrade;
 - (void) loadData;
 - (void) updateData;
+- (void) _saveConfig;
 - (void) syncData;
 - (void) addSource:(NSDictionary *)source;
 - (void) addTrivialSource:(NSString *)href;
-- (void) showSettings;
 - (UIProgressHUD *) addProgressHUD;
 - (void) removeProgressHUD:(UIProgressHUD *)hud;
-- (CyteViewController *) pageForPackage:(NSString *)name;
 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
 @end
 /* }}} */
 
-/* Status Delegation {{{ */
-class Status :
+/* CancelStatus {{{ */
+class CancelStatus :
     public pkgAcquireStatus
 {
   private:
-    _transient NSObject<ProgressDelegate> *delegate_;
     bool cancelled_;
 
   public:
-    Status() :
-        delegate_(nil),
+    CancelStatus() :
         cancelled_(false)
     {
     }
 
-    void setDelegate(NSObject<ProgressDelegate> *delegate) {
-        delegate_ = delegate;
-    }
-
-    NSObject<ProgressDelegate> *getDelegate() const {
-        return delegate_;
-    }
-
     virtual bool MediaChange(std::string media, std::string drive) {
         return false;
     }
@@ -897,6 +920,39 @@ class Status :
         Done(item);
     }
 
+    virtual bool Pulse_(pkgAcquire *Owner) = 0;
+
+    virtual bool Pulse(pkgAcquire *Owner) {
+        if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
+            return true;
+        else {
+            cancelled_ = true;
+            return false;
+        }
+    }
+
+    _finline bool WasCancelled() const {
+        return cancelled_;
+    }
+};
+/* }}} */
+/* DelegateStatus {{{ */
+class CydiaStatus :
+    public CancelStatus
+{
+  private:
+    _transient NSObject<ProgressDelegate> *delegate_;
+
+  public:
+    CydiaStatus() :
+        delegate_(nil)
+    {
+    }
+
+    void setDelegate(NSObject<ProgressDelegate> *delegate) {
+        delegate_ = delegate;
+    }
+
     virtual void Fetch(pkgAcquire::ItemDesc &item) {
         NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
         CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
@@ -924,9 +980,7 @@ class Status :
         [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
     }
 
-    virtual bool Pulse(pkgAcquire *Owner) {
-        bool value = pkgAcquireStatus::Pulse(Owner);
-
+    virtual bool Pulse_(pkgAcquire *Owner) {
         double percent(
             double(CurrentBytes + CurrentItems) /
             double(TotalBytes + TotalItems)
@@ -940,16 +994,7 @@ class Status :
             [NSNumber numberWithDouble:CurrentCPS], @"Speed",
         nil] waitUntilDone:YES];
 
-        if (value && ![delegate_ isProgressCancelled])
-            return true;
-        else {
-            cancelled_ = true;
-            return false;
-        }
-    }
-
-    _finline bool WasCancelled() const {
-        return cancelled_;
+        return ![delegate_ isProgressCancelled];
     }
 
     virtual void Start() {
@@ -990,7 +1035,7 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
     _transient NSObject<DatabaseDelegate> *delegate_;
     _transient NSObject<ProgressDelegate> *progress_;
 
-    Status status_;
+    CydiaStatus status_;
 
     int cydiafd_;
     int statusfd_;
@@ -1027,7 +1072,7 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 - (bool) upgrade;
 - (void) update;
 
-- (void) updateWithStatus:(Status &)status;
+- (void) updateWithStatus:(CancelStatus &)status;
 
 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
 
@@ -1035,11 +1080,61 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 - (NSObject<ProgressDelegate> *) progressDelegate;
 
 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
+- (void) setFetch:(bool)fetch forURI:(const char *)uri;
+- (void) resetFetch;
 
 - (NSString *) mappedSectionForPointer:(const char *)pointer;
 
 @end
 /* }}} */
+/* SourceStatus {{{ */
+class SourceStatus :
+    public CancelStatus
+{
+  private:
+    _transient NSObject<FetchDelegate> *delegate_;
+    _transient Database *database_;
+
+  public:
+    SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
+        delegate_(delegate),
+        database_(database)
+    {
+    }
+
+    void Set(bool fetch, pkgAcquire::ItemDesc &desc) {
+        desc.Owner->ID = 0;
+        [database_ setFetch:fetch forURI:desc.Owner->DescURI().c_str()];
+    }
+
+    virtual void Fetch(pkgAcquire::ItemDesc &desc) {
+        Set(true, desc);
+    }
+
+    virtual void Done(pkgAcquire::ItemDesc &desc) {
+        Set(false, desc);
+    }
+
+    virtual void Fail(pkgAcquire::ItemDesc &desc) {
+        Set(false, desc);
+    }
+
+    virtual bool Pulse_(pkgAcquire *Owner) {
+        for (pkgAcquire::ItemCIterator item = Owner->ItemsBegin(); item != Owner->ItemsEnd(); ++item)
+            if ((*item)->ID != 0);
+            else if ((*item)->Status == pkgAcquire::Item::StatIdle) {
+                (*item)->ID = 1;
+                [database_ setFetch:true forURI:(*item)->DescURI().c_str()];
+            } else (*item)->ID = 0;
+        return ![delegate_ isSourceCancelled];
+    }
+
+    virtual void Stop() {
+        pkgAcquireStatus::Stop();
+        [database_ resetFetch];
+    }
+};
+/* }}} */
 /* ProgressEvent Implementation {{{ */
 @implementation CydiaProgressEvent
 
@@ -1302,8 +1397,12 @@ static void PackageImport(const void *key, const void *value, void *context) {
 
     CYString defaultIcon_;
 
-    _H<NSDictionary> record_;
+    _H<NSMutableDictionary> record_;
     BOOL trusted_;
+
+    std::set<std::string> fetches_;
+    std::set<std::string> files_;
+    _transient NSObject<SourceDelegate> *delegate_;
 }
 
 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
@@ -1313,6 +1412,7 @@ static void PackageImport(const void *key, const void *value, void *context) {
 - (NSString *) depictionForPackage:(NSString *)package;
 - (NSString *) supportForPackage:(NSString *)package;
 
+- (metaIndex *) metaIndex;
 - (NSDictionary *) record;
 - (BOOL) trusted;
 
@@ -1332,30 +1432,13 @@ static void PackageImport(const void *key, const void *value, void *context) {
 - (NSString *) defaultIcon;
 - (NSURL *) iconURL;
 
+- (void) setFetch:(bool)fetch forURI:(const char *)uri;
+- (void) resetFetch;
+
 @end
 
 @implementation Source
 
-- (void) _clear {
-    uri_.clear();
-    distribution_.clear();
-    type_.clear();
-
-    base_.clear();
-
-    description_.clear();
-    label_.clear();
-    origin_.clear();
-    depiction_.clear();
-    support_.clear();
-    version_.clear();
-    defaultIcon_.clear();
-
-    record_ = nil;
-    host_ = nil;
-    authority_ = nil;
-}
-
 + (NSString *) webScriptNameForSelector:(SEL)selector {
     if (false);
     else if (selector == @selector(addSection:))
@@ -1401,9 +1484,11 @@ static void PackageImport(const void *key, const void *value, void *context) {
     return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
 }
 
-- (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
-    [self _clear];
+- (metaIndex *) metaIndex {
+    return index_;
+}
 
+- (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
     trusted_ = index->IsTrusted();
 
     uri_.set(pool, index->GetURI());
@@ -1412,7 +1497,19 @@ static void PackageImport(const void *key, const void *value, void *context) {
 
     debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
     if (dindex != NULL) {
-        base_.set(pool, dindex->MetaIndexURI(""));
+        std::string file(dindex->MetaIndexURI(""));
+        files_.insert(file + "Release.gpg");
+        files_.insert(file + "Release");
+        base_.set(pool, file);
+
+        std::vector<IndexTarget *> *targets(dindex->ComputeIndexTargets());
+        for (std::vector<IndexTarget *>::const_iterator target(targets->begin()); target != targets->end(); ++target) {
+            std::string file((*target)->URI);
+            files_.insert(file);
+            files_.insert(file + ".gz");
+            files_.insert(file + ".bz2");
+            files_.insert(file + "Index");
+        } delete targets;
 
         FileFd fd;
         if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
@@ -1648,6 +1745,31 @@ static void PackageImport(const void *key, const void *value, void *context) {
     return defaultIcon_;
 }
 
+- (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
+    delegate_ = delegate;
+}
+
+- (bool) fetch {
+    return !fetches_.empty();
+}
+
+- (void) setFetch:(bool)fetch forURI:(const char *)uri {
+    if (!fetch) {
+        if (fetches_.erase(uri) == 0)
+            return;
+    } else if (files_.find(uri) == files_.end())
+        return;
+    else if (!fetches_.insert(uri).second)
+        return;
+
+    [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
+}
+
+- (void) resetFetch {
+    fetches_.clear();
+    [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
+}
+
 @end
 /* }}} */
 /* CydiaOperation Class {{{ */
@@ -1816,11 +1938,8 @@ struct ParsedPackage {
 
     CYString depiction_;
     CYString homepage_;
-
-    CYString sponsor_;
     CYString author_;
 
-    CYString bugs_;
     CYString support_;
 };
 
@@ -1922,7 +2041,6 @@ struct ParsedPackage {
 - (uint32_t) rank;
 - (BOOL) matches:(NSArray *)query;
 
-- (bool) hasSupportingRole;
 - (BOOL) hasTag:(NSString *)tag;
 - (NSString *) primaryPurpose;
 - (NSArray *) purposes;
@@ -1940,7 +2058,7 @@ struct ParsedPackage {
 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
-- (bool) isVisibleInSection:(NSString *)section;
+- (bool) isVisibleInSection:(NSString *)section source:(Source *)source;
 - (bool) isVisibleInSource:(Source *)source;
 
 @end
@@ -2090,6 +2208,8 @@ struct PackageNameOrdering :
         return @"clear";
     else if (selector == @selector(getField:))
         return @"getField";
+    else if (selector == @selector(getRecord))
+        return @"getRecord";
     else if (selector == @selector(hasTag:))
         return @"hasTag";
     else if (selector == @selector(install))
@@ -2131,7 +2251,6 @@ struct PackageNameOrdering :
         @"simpleSection",
         @"size",
         @"source",
-        @"sponsor",
         @"state",
         @"support",
         @"tags",
@@ -2175,6 +2294,19 @@ struct PackageNameOrdering :
     return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
 } }
 
+- (NSString *) getRecord {
+@synchronized (database_) {
+    if ([database_ era] != era_ || file_.end())
+        return nil;
+
+    pkgRecords::Parser &parser([database_ records]->Lookup(file_));
+
+    const char *start, *end;
+    parser.GetRec(start, end);
+
+    return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
+} }
+
 - (void) parse {
     if (parsed_ != NULL)
         return;
@@ -2192,6 +2324,7 @@ struct PackageNameOrdering :
             parser = &[database_ records]->Lookup(file_);
         _end
 
+        CYString bugs;
         CYString website;
 
         _profile(Package$parse$Find)
@@ -2204,9 +2337,8 @@ struct PackageNameOrdering :
                 {"depiction", &parsed->depiction_},
                 {"homepage", &parsed->homepage_},
                 {"website", &website},
-                {"bugs", &parsed->bugs_},
+                {"bugs", &bugs},
                 {"support", &parsed->support_},
-                {"sponsor", &parsed->sponsor_},
                 {"author", &parsed->author_},
                 {"md5sum", &parsed->md5sum_},
             };
@@ -2240,6 +2372,8 @@ struct PackageNameOrdering :
                 parsed->homepage_ = website;
             if (parsed->homepage_ == parsed->depiction_)
                 parsed->homepage_.clear();
+            if (parsed->support_.empty())
+                parsed->support_ = bugs;
         _end
     _end
 } }
@@ -2285,9 +2419,14 @@ struct PackageNameOrdering :
             pkgCache::TagIterator tag(iterator.TagList());
             if (!tag.end()) {
                 tags_ = [NSMutableArray arrayWithCapacity:8];
-                do {
+
+                goto tag; for (; !tag.end(); ++tag) tag: {
                     const char *name(tag.Name());
-                    [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
+                    NSString *string((NSString *) CYStringCreate(name));
+                    if (string == nil)
+                        continue;
+
+                    [tags_ addObject:[string autorelease]];
 
                     if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
                         if (strcmp(name + 6, "enduser") == 0)
@@ -2308,9 +2447,7 @@ struct PackageNameOrdering :
                         else if (strcmp(name + 7, "obsolete") == 0)
                             obsolete_ = true;
                     }
-
-                    ++tag;
-                } while (!tag.end());
+                }
             }
         _end
 
@@ -2348,7 +2485,7 @@ struct PackageNameOrdering :
         _end
 
         _profile(Package$initWithVersion$Section)
-            section_ = iterator.Section();
+            section_ = version_.Section();
         _end
 
         _profile(Package$initWithVersion$Flags)
@@ -2579,8 +2716,8 @@ struct PackageNameOrdering :
             return false;
     _end
 
-    _profile(Package$unfiltered$hasSupportingRole)
-        if (_unlikely(![self hasSupportingRole]))
+    _profile(Package$unfiltered$role)
+        if (_unlikely(role_ > 3))
             return false;
     _end
 
@@ -2619,11 +2756,19 @@ struct PackageNameOrdering :
 }
 
 - (BOOL) hasMode {
+@synchronized (database_) {
+    if ([database_ era] != era_ || iterator_.end())
+        return nil;
+
     pkgDepCache::StateCache &state([database_ cache][iterator_]);
     return state.Mode != pkgDepCache::ModeKeep;
-}
+} }
 
 - (NSString *) mode {
+@synchronized (database_) {
+    if ([database_ era] != era_ || iterator_.end())
+        return nil;
+
     pkgDepCache::StateCache &state([database_ cache][iterator_]);
 
     switch (state.Mode) {
@@ -2655,7 +2800,7 @@ struct PackageNameOrdering :
             }
         _nodefault
     }
-}
+} }
 
 - (NSString *) id {
     return id_;
@@ -2691,16 +2836,12 @@ struct PackageNameOrdering :
     return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
 }
 
-- (MIMEAddress *) sponsor {
-    return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
-}
-
 - (MIMEAddress *) author {
     return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
 }
 
 - (NSString *) support {
-    return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
+    return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
 }
 
 - (NSArray *) files {
@@ -2836,7 +2977,8 @@ struct PackageNameOrdering :
 
                 NSString *bundle([file stringByDeletingLastPathComponent]);
                 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
-                if (icon == nil || [icon length] == 0)
+                // XXX: maybe this should check if this is really a string, not just for length
+                if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
                     icon = @"icon.png";
                 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
 
@@ -2911,24 +3053,6 @@ struct PackageNameOrdering :
     return rank_ != 0;
 }
 
-- (bool) hasSupportingRole {
-    if (role_ == 0)
-        return true;
-    if (role_ == 1)
-        return true;
-    if ([Role_ isEqualToString:@"User"])
-        return false;
-    if (role_ == 2)
-        return true;
-    if ([Role_ isEqualToString:@"Hacker"])
-        return false;
-    if (role_ == 3)
-        return true;
-    if ([Role_ isEqualToString:@"Developer"])
-        return false;
-    _assert(false);
-}
-
 - (NSArray *) tags {
     return tags_;
 }
@@ -3048,16 +3172,19 @@ struct PackageNameOrdering :
 }
 
 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
-    return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
+    return ![self uninstalled] && role_ <= ([number boolValue] ? 1 : 3);
 }
 
-- (bool) isVisibleInSection:(NSString *)name {
+- (bool) isVisibleInSection:(NSString *)name source:(Source *)source {
     NSString *section([self section]);
 
     return (
         name == nil ||
         section == nil && [name length] == 0 ||
         [name isEqualToString:section]
+    ) && (
+        source == nil ||
+        [self source] == source
     ) && [self visible];
 }
 
@@ -3451,6 +3578,10 @@ class CydiaLogCleaner :
 
         lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
 
+        static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
+        if (warning && no_pubkey(error.c_str()))
+            continue;
+
         [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
     }
 
@@ -3502,29 +3633,47 @@ class CydiaLogCleaner :
 
     NSString *title(UCLocalize("DATABASE"));
 
+    list_ = new pkgSourceList();
+    if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
+        return;
+
+    for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
+        Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
+        [sourceList_ addObject:object];
+    }
+
     _trace();
     OpProgress progress;
-    while (!cache_.Open(progress, true)) { pop:
-        std::string error;
-        bool warning(!_error->PopMessage(error));
-        lprintf("cache_.Open():[%s]\n", error.c_str());
-
-        if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
-            [delegate_ repairWithSelector:@selector(configure)];
-        else if (error == "The package lists or status file could not be parsed or opened.")
-            [delegate_ repairWithSelector:@selector(update)];
-        // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
-        // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
-        // else if (error == "Malformed Status line")
-        // else if (error == "The list of sources could not be read.")
-        else {
+  open:
+    if (!cache_.Open(progress, true)) {
+        // XXX: what if there are errors, but Open() == true? this should be merged with popError:
+        while (!_error->empty()) {
+            std::string error;
+            bool warning(!_error->PopMessage(error));
+
+            lprintf("cache_.Open():[%s]\n", error.c_str());
+
             [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
-            return;
+
+            SEL repair(NULL);
+            if (false);
+            else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
+                repair = @selector(configure);
+            //else if (error == "The package lists or status file could not be parsed or opened.")
+            //    repair = @selector(update);
+            // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
+            // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
+            // else if (error == "Malformed Status line")
+            // else if (error == "The list of sources could not be read.")
+
+            if (repair != NULL) {
+                _error->Discard();
+                [delegate_ repairWithSelector:repair];
+                goto open;
+            }
         }
 
-        if (warning)
-            goto pop;
-        _error->Discard();
+        return;
     }
     _trace();
 
@@ -3538,10 +3687,6 @@ class CydiaLogCleaner :
     fetcher_ = new pkgAcquire(&status_);
     lock_ = NULL;
 
-    list_ = new pkgSourceList();
-    if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
-        return;
-
     if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
         [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
         return;
@@ -3563,11 +3708,9 @@ class CydiaLogCleaner :
             return;
     }
 
-    for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
-        Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
-        [sourceList_ addObject:object];
-
-        std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
+    for (Source *object in (id) sourceList_) {
+        metaIndex *source([object metaIndex]);
+        std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
         for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
             // XXX: this could be more intelligent
             if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
@@ -3649,6 +3792,7 @@ class CydiaLogCleaner :
 }
 
 - (bool) clean {
+@synchronized (self) {
     // XXX: I don't remember this condition
     if (lock_ != NULL)
         return false;
@@ -3669,7 +3813,7 @@ class CydiaLogCleaner :
         return false;
 
     return true;
-}
+} }
 
 - (bool) prepare {
     fetcher_->Shutdown();
@@ -3724,7 +3868,14 @@ class CydiaLogCleaner :
         if ((*item)->Status == pkgAcquire::Item::StatIdle)
             continue;
 
+        std::string uri = (*item)->DescURI();
+        std::string error = (*item)->ErrorText;
+
+        lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
         failed = true;
+
+        CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
+        [delegate_ addProgressEventOnMainThread:event forTask:title];
     }
 
     [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
@@ -3739,11 +3890,8 @@ class CydiaLogCleaner :
 
     _system->UnLock();
     pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
-
-    if (_error->PendingError()) {
-        _trace();
+    if ([self popErrorWithTitle:title])
         return;
-    }
 
     if (result == pkgPackageManager::Failed) {
         _trace();
@@ -3778,7 +3926,7 @@ class CydiaLogCleaner :
     [self updateWithStatus:status_];
 }
 
-- (void) updateWithStatus:(Status &)status {
+- (void) updateWithStatus:(CancelStatus &)status {
     NSString *title(UCLocalize("REFRESHING_DATA"));
 
     pkgSourceList list;
@@ -3822,6 +3970,16 @@ class CydiaLogCleaner :
     return i == sourceMap_.end() ? nil : i->second;
 }
 
+- (void) setFetch:(bool)fetch forURI:(const char *)uri {
+    for (Source *source in (id) sourceList_)
+        [source setFetch:fetch forURI:uri];
+}
+
+- (void) resetFetch {
+    for (Source *source in (id) sourceList_)
+        [source resetFetch];
+}
+
 - (NSString *) mappedSectionForPointer:(const char *)section {
     _H<NSString> *mapped;
 
@@ -3911,7 +4069,7 @@ static _H<NSMutableSet> Diversions_;
 @end
 
 @interface CydiaObject : NSObject {
-    _H<IndirectDelegate> indirect_;
+    _H<CyteWebViewController> indirect_;
     _transient id delegate_;
 }
 
@@ -3919,11 +4077,16 @@ static _H<NSMutableSet> Diversions_;
 
 @end
 
+@class CydiaObject;
+
 @interface CydiaWebViewController : CyteWebViewController {
     _H<CydiaObject> cydia_;
 }
 
 + (void) addDiversion:(Diversion *)diversion;
++ (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
++ (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
+- (void) setDelegate:(id)delegate;
 
 @end
 
@@ -3932,7 +4095,7 @@ static _H<NSMutableSet> Diversions_;
 
 - (id) initWithDelegate:(IndirectDelegate *)indirect {
     if ((self = [super init]) != nil) {
-        indirect_ = indirect;
+        indirect_ = (CyteWebViewController *) indirect;
     } return self;
 }
 
@@ -3943,14 +4106,17 @@ static _H<NSMutableSet> Diversions_;
 + (NSArray *) _attributeKeys {
     return [NSArray arrayWithObjects:
         @"bbsnum",
-        @"cydiaSource",
+        @"build",
+        @"coreFoundationVersionNumber",
         @"device",
         @"ecid",
         @"firmware",
         @"hostname",
         @"idiom",
+        @"mcc",
+        @"mnc",
         @"model",
-        @"plmn",
+        @"operator",
         @"role",
         @"serial",
         @"token",
@@ -3970,8 +4136,16 @@ static _H<NSMutableSet> Diversions_;
     return Cydia_;
 }
 
+- (NSString *) build {
+    return System_;
+}
+
+- (NSString *) coreFoundationVersionNumber {
+    return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
+}
+
 - (NSString *) device {
-    return [[UIDevice currentDevice] uniqueIdentifier];
+    return UniqueIdentifier();
 }
 
 - (NSString *) firmware {
@@ -3986,8 +4160,22 @@ static _H<NSMutableSet> Diversions_;
     return (id) Idiom_ ?: [NSNull null];
 }
 
-- (NSString *) plmn {
-    return (id) PLMN_ ?: [NSNull null];
+- (NSString *) mcc {
+    if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
+        return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
+    return nil;
+}
+
+- (NSString *) mnc {
+    if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
+        return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
+    return nil;
+}
+
+- (NSString *) operator {
+    if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
+        return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
+    return nil;
 }
 
 - (NSString *) bbsnum {
@@ -4003,7 +4191,7 @@ static _H<NSMutableSet> Diversions_;
 }
 
 - (NSString *) role {
-    return (id) Role_ ?: [NSNull null];
+    return (id) [NSNull null];
 }
 
 - (NSString *) model {
@@ -4037,7 +4225,9 @@ static _H<NSMutableSet> Diversions_;
     else if (selector == @selector(stringWithFormat:arguments:))
         return @"format";
     else if (selector == @selector(getAllSources))
-        return @"getAllSourcs";
+        return @"getAllSources";
+    else if (selector == @selector(getApplicationInfo:value:))
+        return @"getApplicationInfoValue";
     else if (selector == @selector(getKernelNumber:))
         return @"getKernelNumber";
     else if (selector == @selector(getKernelString:))
@@ -4060,18 +4250,20 @@ static _H<NSMutableSet> Diversions_;
         return @"getSessionValue";
     else if (selector == @selector(installPackages:))
         return @"installPackages";
+    else if (selector == @selector(isReachable:))
+        return @"isReachable";
     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(registerFrame:))
+        return @"registerFrame";
     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::))
@@ -4100,6 +4292,10 @@ static _H<NSMutableSet> Diversions_;
         return @"setPasteboardString";
     else if (selector == @selector(setPasteboardURL:))
         return @"setPasteboardURL";
+    else if (selector == @selector(setScrollAlwaysBounceVertical:))
+        return @"setScrollAlwaysBounceVertical";
+    else if (selector == @selector(setScrollIndicatorStyle:))
+        return @"setScrollIndicatorStyle";
     else if (selector == @selector(setToken:))
         return @"setToken";
     else if (selector == @selector(setViewportWidth:))
@@ -4126,10 +4322,28 @@ static _H<NSMutableSet> Diversions_;
     [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
 }
 
+- (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
+    [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
+}
+
+- (void) setScrollIndicatorStyle:(NSString *)style {
+    [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
+}
+
 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
     [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
 }
 
+- (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
+    char path[1024];
+    if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
+        return (id) [NSNull null];
+    NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
+    if (info == nil)
+        return (id) [NSNull null];
+    return [info objectForKey:key];
+}
+
 - (NSNumber *) getKernelNumber:(NSString *)name {
     const char *string([name UTF8String]);
 
@@ -4174,30 +4388,16 @@ 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];
 } }
 
+- (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
+    WebFrame *frame([iframe contentFrame]);
+    [indirect_ registerFrame:frame];
+}
+
 - (id) getMetadataValue:(NSString *)key {
 @synchronized (Values_) {
     return [Values_ objectForKey:key];
@@ -4339,32 +4539,25 @@ static _H<NSMutableSet> Diversions_;
         /* XXX: this should probably not use du */
         execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
         exit(1);
-        _assert(false);
-    }
-
-    _assert(close(fds[1]) != -1);
+    } else {
+        _assert(close(fds[1]) != -1);
 
-    if (FILE *du = fdopen(fds[0], "r")) {
-        char line[1024];
-        while (fgets(line, sizeof(line), du) != NULL) {
-            size_t length(strlen(line));
-            while (length != 0 && line[length - 1] == '\n')
-                line[--length] = '\0';
-            if (char *tab = strchr(line, '\t')) {
-                *tab = '\0';
-                value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
+        if (FILE *du = fdopen(fds[0], "r")) {
+            char line[1024];
+            while (fgets(line, sizeof(line), du) != NULL) {
+                size_t length(strlen(line));
+                while (length != 0 && line[length - 1] == '\n')
+                    line[--length] = '\0';
+                if (char *tab = strchr(line, '\t')) {
+                    *tab = '\0';
+                    value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
+                }
             }
-        }
-
-        fclose(du);
-    } else _assert(close(fds[0]));
 
-    int status;
-  wait:
-    if (waitpid(pid, &status, 0) == -1)
-        if (errno == EINTR)
-            goto wait;
-        else _assert(false);
+            fclose(du);
+        } else
+            _assert(close(fds[0]) != -1);
+    } ReapZombie(pid);
 
     return value;
 }
@@ -4373,12 +4566,16 @@ static _H<NSMutableSet> Diversions_;
     [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
 }
 
+- (NSNumber *) isReachable:(NSString *)name {
+    return [NSNumber numberWithBool:IsReachable([name UTF8String])];
+}
+
 - (void) installPackages:(NSArray *)packages {
     [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
 }
 
 - (NSString *) substitutePackageNames:(NSString *)message {
-    NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
+    NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
     for (size_t i(0), e([words count]); i != e; ++i) {
         NSString *word([words objectAtIndex:i]);
         if (Package *package = [[Database sharedInstance] packageWithName:word])
@@ -4515,7 +4712,10 @@ static _H<NSMutableSet> Diversions_;
 
 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
     [super webView:view didClearWindowObject:window forFrame:frame];
+    [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
+}
 
++ (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
     WebDataSource *source([frame dataSource]);
     NSURLResponse *response([source response]);
     NSURL *url([response URL]);
@@ -4532,7 +4732,7 @@ static _H<NSMutableSet> Diversions_;
     }
 
     if (bridged)
-        [window setValue:cydia_ forKey:@"cydia"];
+        [window setValue:cydia forKey:@"cydia"];
 }
 
 - (void) _setupMail:(MFMailComposeViewController *)controller {
@@ -4547,26 +4747,50 @@ 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]);
+    return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
+}
+
++ (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
+    NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
+
+    NSURL *url([copy URL]);
+    NSString *href([url absoluteString]);
+    NSString *host([url host]);
+
+    if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
+        if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
+            [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
+            [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
+        }
 
-    NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
+        [copy setValue:nil forHTTPHeaderField:@"Referer"];
+        [copy setValue:nil forHTTPHeaderField:@"Origin"];
 
-    if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
-        [copy setValue:System_ forHTTPHeaderField:@"X-System"];
+        [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
+        return copy;
+    }
+
+    if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
+        [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
     if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
         [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
 
+    bool bridged;
     bool token;
+
     @synchronized (HostConfig_) {
-        token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
+        bridged = [BridgedHosts_ containsObject:host];
+        token = [TokenHosts_ containsObject:host];
     }
 
-    if ([url isCydiaSecure] && token) {
-        if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
-            [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
-        if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
-            [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
+    if ([url isCydiaSecure]) {
+        if (bridged) {
+            if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
+                [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
+        } else if (token) {
+            if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
+                [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
+        }
     }
 
     return copy;
@@ -4578,16 +4802,7 @@ static _H<NSMutableSet> Diversions_;
 }
 
 - (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;
+    return UserAgent_;
 }
 
 - (id) init {
@@ -4606,6 +4821,11 @@ static _H<NSMutableSet> Diversions_;
 @implementation AppCacheController
 
 - (void) didReceiveMemoryWarning {
+    // XXX: this doesn't work
+}
+
+- (bool) retainsNetworkActivityIndicator {
+    return false;
 }
 
 @end
@@ -4700,7 +4920,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         if (button == [alert cancelButtonIndex])
             [self dismissModalViewControllerAnimated:YES];
         else if (button == [alert firstOtherButtonIndex]) {
-            [self complete];
+            [self performSelector:@selector(complete) withObject:nil afterDelay:0];
         }
 
         [alert dismissWithClickedButtonIndex:-1 animated:YES];
@@ -4803,7 +5023,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
                                 reason = @"virtual";
                         }
 
-                        NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
+                        NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSString stringWithUTF8String:start.CompType()], @"operator",
                             [NSString stringWithUTF8String:start.TargetVer()], @"value",
                         nil]);
@@ -4882,6 +5102,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
             ] autorelease];
 
             [essential_ setContext:@"remove"];
+            [essential_ setNumberOfRows:2];
         } else {
             essential_ = [[[UIAlertView alloc]
                 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
@@ -4935,8 +5156,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 #endif
 
 - (void) cancelButtonClicked {
-    [self dismissModalViewControllerAnimated:YES];
     [delegate_ cancelAndClear:YES];
+    [self dismissModalViewControllerAnimated:YES];
 }
 
 #if !AlwaysReload
@@ -5000,6 +5221,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     } return self;
 }
 
+- (id) delegate {
+    return delegate_;
+}
+
 - (void) setDelegate:(id)delegate {
     delegate_ = delegate;
 }
@@ -5146,6 +5371,34 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [super viewWillAppear:animated];
 }
 
+- (void) reloadSpringBoard {
+    if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
+        system("/bin/launchctl stop com.apple.backboardd");
+        sleep(15);
+        system("/usr/bin/killall backboardd SpringBoard sbreload");
+        return;
+    }
+
+    pid_t pid(ExecFork());
+    if (pid == 0) {
+        if (setsid() == -1)
+            perror("setsid");
+
+        pid_t pid(ExecFork());
+        if (pid == 0) {
+            execl("/usr/bin/sbreload", "sbreload", NULL);
+            perror("sbreload");
+
+            exit(0);
+        } ReapZombie(pid);
+
+        exit(0);
+    } ReapZombie(pid);
+
+    sleep(15);
+    system("/usr/bin/killall backboardd SpringBoard sbreload");
+}
+
 - (void) close {
     UpdateExternalStatus(0);
 
@@ -5173,10 +5426,12 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
             _trace();
             goto reload;
 
-        reload:
-            system("/usr/bin/sbreload");
-            _trace();
-        break;
+        reload: {
+            UIProgressHUD *hud([delegate_ addProgressHUD]);
+            [hud setText:UCLocalize("LOADING")];
+            [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
+            return;
+        }
 
         case 4:
             _trace();
@@ -5281,10 +5536,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
     }
 
-    _trace();
-    system("su -c /usr/bin/uicache mobile");
-    _trace();
-
     UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
 
     [progress_ setRunning:false];
@@ -5386,7 +5637,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (NSString *) accessibilityLabel {
-    return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
+    return name_;
 }
 
 - (void) setPackage:(Package *)package asSummary:(bool)summary {
@@ -5411,14 +5662,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         if (NSString *name = [package name])
             name_ = [NSString stringWithString:name];
 
-        NSString *description(nil);
-
-        if (description == nil && IsWildcat_)
-            description = [package longDescription];
-        if (description == nil)
-            description = [package shortDescription];
-
-        if (description != nil)
+        if (NSString *description = [package shortDescription])
             description_ = [NSString stringWithString:description];
 
         commercial_ = [package isCommercial];
@@ -5453,14 +5697,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         if (NSString *mode = [package mode]) {
             if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
                 color = RemovingColor_;
-                //placard = @"removing";
+                placard = @"removing";
             } else {
                 color = InstallingColor_;
-                //placard = @"installing";
+                placard = @"installing";
             }
-
-            // XXX: the removing/installing placards are not @2x
-            placard = nil;
         } else {
             color = [UIColor whiteColor];
 
@@ -5493,8 +5734,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
             rect.size.height /= 2;
         }
 
-        rect.origin.x = 18 - rect.size.width / 2;
-        rect.origin.y = 18 - rect.size.height / 2;
+        rect.origin.x = 19 - rect.size.width / 2;
+        rect.origin.y = 19 - rect.size.height / 2;
 
         [icon_ drawInRect:rect];
     }
@@ -5506,13 +5747,13 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         rect.size.width /= 4;
         rect.size.height /= 4;
 
-        rect.origin.x = 23 - rect.size.width / 2;
-        rect.origin.y = 23 - rect.size.height / 2;
+        rect.origin.x = 25 - rect.size.width / 2;
+        rect.origin.y = 25 - rect.size.height / 2;
 
         [badge_ drawInRect:rect];
     }
 
-    if (highlighted)
+    if (highlighted && kCFCoreFoundationVersionNumber < 800)
         UISetColor(White_);
 
     if (!highlighted)
@@ -5520,7 +5761,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
 
     if (placard_ != nil)
-        [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
+        [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
 }
 
 - (void) drawNormalContentRect:(CGRect)rect {
@@ -5555,7 +5796,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         [badge_ drawInRect:rect];
     }
 
-    if (highlighted)
+    if (highlighted && kCFCoreFoundationVersionNumber < 800)
         UISetColor(White_);
 
     if (!highlighted)
@@ -5602,6 +5843,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
     if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
         icon_ = [UIImage applicationImageNamed:@"folder.png"];
+        // XXX: this initial frame is wrong, but is fixed later
         switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
         [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
 
@@ -5650,7 +5892,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         section_ = [section localized];
 
         name_  = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
-        count_ = [NSString stringWithFormat:@"%d", [section count]];
+        count_ = [NSString stringWithFormat:@"%zd", [section count]];
 
         if (editing_)
             [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
@@ -5666,7 +5908,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [super setFrame:frame];
 
     CGRect rect([switch_ frame]);
-    [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
+    [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
 }
 
 - (NSString *) accessibilityLabel {
@@ -5676,24 +5918,24 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 - (void) drawContentRect:(CGRect)rect {
     bool highlighted(highlighted_ && !editing_);
 
-    [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
+    [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
 
-    if (highlighted)
+    if (highlighted && kCFCoreFoundationVersionNumber < 800)
         UISetColor(White_);
 
     float width(rect.size.width);
     if (editing_)
-        width -= 87;
+        width -= 9 + [switch_ frame].size.width;
 
     if (!highlighted)
         UISetColor(Black_);
-    [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
+    [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:UILineBreakModeTailTruncation];
 
     CGSize size = [count_ sizeWithFont:Font14_];
 
-    UISetColor(White_);
+    UISetColor(Folder_);
     if (count_ != nil)
-        [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
+        [count_ drawAtPoint:CGPointMake(10 + (30 - size.width) / 2, 18) withFont:Font12Bold_];
 }
 
 @end
@@ -5745,14 +5987,12 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) loadView {
-    [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
-
-    list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
+    list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
     [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
     [list_ setRowHeight:24.0f];
     [(UITableView *) list_ setDataSource:self];
     [list_ setDelegate:self];
-    [[self view] addSubview:list_];
+    [self setView:list_];
 }
 
 - (void) viewDidLoad {
@@ -5834,7 +6074,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     _H<UIBarButtonItem> button_;
 }
 
-- (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
+- (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
 
 @end
 
@@ -5907,20 +6147,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     }
 }
 
-// We don't want to allow non-commercial packages to do custom things to the install button,
-// so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
-- (void) customButtonClicked {
-    if (commercial_)
-        [super customButtonClicked];
-    else
-        [self _customButtonClicked];
-}
-
 - (void) reloadButtonClicked {
-    // Don't reload a commerical package by tapping the loading button,
-    // but if it's not an Install button, we should forward it on.
-    if (![package_ uninstalled])
-        [self _customButtonClicked];
+    if (commercial_ && function_ == nil && [package_ uninstalled])
+        return;
+    [self customButtonClicked];
 }
 
 - (void) applyLoadingTitle {
@@ -5932,12 +6162,12 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 #endif
 
-- (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
+- (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
     if ((self = [super init]) != nil) {
         database_ = database;
         buttons_ = [NSMutableArray arrayWithCapacity:4];
         name_ = name == nil ? @"" : [NSString stringWithString:name];
-        [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
+        [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
     } return self;
 }
 
@@ -6013,6 +6243,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 @implementation PackageListController
 
+- (NSURL *) referrerURL {
+    return [self navigationURL];
+}
+
 - (bool) isSummarized {
     return false;
 }
@@ -6070,8 +6304,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     CGRect kbframe = CGRectMake(round(center.x - bounds.size.width / 2.0), round(center.y - bounds.size.height / 2.0), bounds.size.width, bounds.size.height);
     UIViewController *base = self;
-    while ([base parentViewController] != nil)
-        base = [base parentViewController];
+    while ([base parentOrPresentingViewController] != nil)
+        base = [base parentOrPresentingViewController];
     CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
     CGRect intersection = CGRectIntersection(viewframe, kbframe);
 
@@ -6111,7 +6345,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) didSelectPackage:(Package *)package {
-    CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
+    CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
     [view setDelegate:delegate_];
     [[self navigationController] pushViewController:view animated:YES];
 }
@@ -6196,11 +6430,13 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) loadView {
-    [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
+    UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
+    [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
+    [self setView:view];
 
     list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
     [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
-    [[self view] addSubview:list_];
+    [view addSubview:list_];
 
     // XXX: is 20 the most optimal number here?
     [list_ setSectionIndexMinimumDisplayRowCount:20];
@@ -6250,6 +6486,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     NSArray *packages;
 
+  reload:
     if ([self shouldYield]) {
         do {
             UIProgressHUD *hud;
@@ -6267,12 +6504,15 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
             if (hud != nil)
                 [delegate_ removeProgressHUD:hud];
         } while (reloading_ == 2);
-
-        reloading_ = 0;
     } else {
         packages = [self _reloadPackages];
     }
 
+@synchronized (database_) {
+    if (era_ != [database_ era])
+        goto reload;
+    reloading_ = 0;
+
     packages_ = packages;
 
     indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
@@ -6358,7 +6598,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         [(UITableView *) list_ setDataSource:self];
         [list_ reloadData];
     _end
-}
+} }
 
 - (void) reloadData {
     [super reloadData];
@@ -6389,10 +6629,15 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     SEL filter_;
     IMP imp_;
     _H<NSObject> object_;
+    _H<NSObject> stuff_;
 }
 
 - (void) setObject:(id)object;
+- (void) setStuff:(id)object;
+- (void) setObject:(id)object andStuff:(id)stuff;
+
 - (void) setObject:(id)object forFilter:(SEL)filter;
+- (void) setObject:(id)object andStuff:(id)stuff forFilter:(SEL)filter;
 
 - (SEL) filter;
 - (void) setFilter:(SEL)filter;
@@ -6423,10 +6668,28 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     object_ = object;
 } }
 
+- (void) setStuff:(id)stuff {
+@synchronized (self) {
+    stuff_ = stuff;
+} }
+
+- (void) setObject:(id)object andStuff:(id)stuff {
+@synchronized (self) {
+    object_ = object;
+    stuff_ = stuff;
+} }
+
 - (void) setObject:(id)object forFilter:(SEL)filter {
 @synchronized (self) {
     [self setFilter:filter];
-    [self setObject:object];
+    object_ = object;
+} }
+
+- (void) setObject:(id)object andStuff:(id)stuff forFilter:(SEL)filter {
+@synchronized (self) {
+    [self setFilter:filter];
+    object_ = object;
+    stuff_ = stuff;
 } }
 
 - (NSMutableArray *) _reloadPackages {
@@ -6439,16 +6702,18 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     IMP imp;
     SEL filter;
     _H<NSObject> object;
+    _H<NSObject> stuff;
 
     @synchronized (self) {
         imp = imp_;
         filter = filter_;
         object = object_;
+        stuff = stuff_;
     }
 
     _profile(PackageTable$reloadData$Filter)
         for (Package *package in packages)
-            if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
+            if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id, id)>(imp))(package, filter, object, stuff))
                 [filtered addObject:package];
     _end
 
@@ -6458,7 +6723,15 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
     if ((self = [super initWithDatabase:database title:title]) != nil) {
         [self setFilter:filter];
-        [self setObject:object];
+        object_ = object;
+    } return self;
+}
+
+- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object with:(id)stuff {
+    if ((self = [super initWithDatabase:database title:title]) != nil) {
+        [self setFilter:filter];
+        object_ = object;
+        stuff_ = stuff;
     } return self;
 }
 
@@ -6467,24 +6740,43 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 /* Home Controller {{{ */
 @interface HomeController : CydiaWebViewController {
+    CFRunLoopRef runloop_;
+    SCNetworkReachabilityRef reachability_;
 }
 
 @end
 
 @implementation HomeController
 
+static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
+    [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
+}
+
 - (id) init {
     if ((self = [super init]) != nil) {
         [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
         [self reloadData];
+
+        reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
+        if (reachability_ != NULL) {
+            SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
+            SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
+
+            CFRunLoopRef runloop(CFRunLoopGetCurrent());
+            if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
+                runloop_ = runloop;
+        }
     } return self;
 }
 
-- (NSURL *) navigationURL {
-    return [NSURL URLWithString:@"cydia://home"];
+- (void) dealloc {
+    if (reachability_ != NULL && runloop_ != NULL)
+        SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
+    [super dealloc];
 }
 
-- (void) didReceiveMemoryWarning {
+- (NSURL *) navigationURL {
+    return [NSURL URLWithString:@"cydia://home"];
 }
 
 - (void) aboutButtonClicked {
@@ -6495,7 +6787,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [alert setCancelButtonIndex:0];
 
     [alert setMessage:
-        @"Copyright \u00a9 2008-2011\n"
+        @"Copyright \u00a9 2008-2013\n"
         "SaurikIT, LLC\n"
         "\n"
         "Jay Freeman (saurik)\n"
@@ -6515,171 +6807,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     ] autorelease];
 }
 
-@end
-/* }}} */
-/* Manage Controller {{{ */
-@interface ManageController : CydiaWebViewController {
-}
-
-- (void) queueStatusDidChange;
-
-@end
-
-@implementation ManageController
-
-- (id) init {
-    if ((self = [super init]) != nil) {
-        [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
-    } return self;
-}
-
-- (NSURL *) navigationURL {
-    return [NSURL URLWithString:@"cydia://manage"];
-}
-
-- (UIBarButtonItem *) leftButton {
-    return [[[UIBarButtonItem alloc]
-        initWithTitle:UCLocalize("SETTINGS")
-        style:UIBarButtonItemStylePlain
-        target:self
-        action:@selector(settingsButtonClicked)
-    ] autorelease];
-}
-
-- (void) settingsButtonClicked {
-    [delegate_ showSettings];
-}
-
-- (void) queueButtonClicked {
-    [delegate_ queue];
-}
-
-- (UIBarButtonItem *) customButton {
-    return Queuing_ ? [[[UIBarButtonItem alloc]
-        initWithTitle:UCLocalize("QUEUE")
-        style:UIBarButtonItemStyleDone
-        target:self
-        action:@selector(queueButtonClicked)
-    ] autorelease] : [super customButton];
-}
-
-- (void) queueStatusDidChange {
-    [self applyRightButton];
-}
-
-- (bool) isLoading {
-    return !Queuing_ && [super isLoading];
-}
-
-@end
-/* }}} */
-
-/* Refresh Bar {{{ */
-@interface RefreshBar : UINavigationBar {
-    _H<UIProgressIndicator> indicator_;
-    _H<UITextLabel> prompt_;
-    _H<UIProgressBar> progress_;
-    _H<UINavigationButton> cancel_;
-}
-
-@end
-
-@implementation RefreshBar
-
-- (void) positionViews {
-    CGRect frame = [cancel_ frame];
-    frame.size = [cancel_ sizeThatFits:frame.size];
-    frame.origin.x = [self frame].size.width - frame.size.width - 5;
-    frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
-    [cancel_ setFrame:frame];
-
-    CGSize prgsize = {75, 100};
-    CGRect prgrect = {{
-        [self frame].size.width - prgsize.width - 10,
-        ([self frame].size.height - prgsize.height) / 2
-    } , prgsize};
-    [progress_ setFrame:prgrect];
-
-    CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
-    unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
-    CGRect indrect = {{indoffset, indoffset}, indsize};
-    [indicator_ setFrame:indrect];
-
-    CGSize prmsize = {215, indsize.height + 4};
-    CGRect prmrect = {{
-        indoffset * 2 + indsize.width,
-        unsigned([self frame].size.height - prmsize.height) / 2 - 1
-    }, prmsize};
-    [prompt_ setFrame:prmrect];
-}
-
-- (void) setFrame:(CGRect)frame {
-    [super setFrame:frame];
-    [self positionViews];
-}
-
-- (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
-    if ((self = [super initWithFrame:frame]) != nil) {
-        [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
-
-        [self setBarStyle:UIBarStyleBlack];
-
-        UIBarStyle barstyle([self _barStyle:NO]);
-        bool ugly(barstyle == UIBarStyleDefault);
-
-        UIProgressIndicatorStyle style = ugly ?
-            UIProgressIndicatorStyleMediumBrown :
-            UIProgressIndicatorStyleMediumWhite;
-
-        indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
-        [(UIProgressIndicator *) indicator_ setStyle:style];
-        [indicator_ startAnimation];
-        [self addSubview:indicator_];
-
-        prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
-        [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
-        [prompt_ setBackgroundColor:[UIColor clearColor]];
-        [prompt_ setFont:[UIFont systemFontOfSize:15]];
-        [self addSubview:prompt_];
-
-        progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
-        [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
-        [(UIProgressBar *) progress_ setStyle:0];
-        [self addSubview:progress_];
-
-        cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
-        [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
-        [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
-        [cancel_ setBarStyle:barstyle];
-
-        [self positionViews];
-    } return self;
-}
-
-- (void) setCancellable:(bool)cancellable {
-    if (cancellable)
-        [self addSubview:cancel_];
-    else
-        [cancel_ removeFromSuperview];
-}
-
-- (void) start {
-    [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
-    [progress_ setProgress:0];
-}
-
-- (void) stop {
-    [self setCancellable:NO];
-}
-
-- (void) setPrompt:(NSString *)prompt {
-    [prompt_ setText:prompt];
-}
-
-- (void) setProgress:(float)progress {
-    [progress_ setProgress:progress];
-}
-
 @end
 /* }}} */
 
@@ -6693,62 +6820,26 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 /* }}} */
 
 /* Cydia Tab Bar Controller {{{ */
-@interface CYTabBarController : UITabBarController <
+@interface CydiaTabBarController : CyteTabBarController <
     UITabBarControllerDelegate,
-    ProgressDelegate
+    FetchDelegate
 > {
     _transient Database *database_;
-    _H<RefreshBar, 1> refreshbar_;
 
-    bool dropped_;
+    _H<UIActivityIndicatorView> indicator_;
+
     bool updating_;
     // XXX: ok, "updatedelegate_"?...
     _transient NSObject<CydiaDelegate> *updatedelegate_;
-
-    _H<UIViewController> remembered_;
-    _transient UIViewController *transient_;
 }
 
 - (NSArray *) navigationURLCollection;
-- (void) dropBar:(BOOL)animated;
 - (void) beginUpdate;
-- (void) raiseBar:(BOOL)animated;
 - (BOOL) updating;
-- (void) unloadData;
 
 @end
 
-@implementation CYTabBarController
-
-- (void) setUnselectedViewController:(UIViewController *)transient {
-    NSMutableArray *controllers = [[self viewControllers] mutableCopy];
-    if (transient != nil) {
-        if (transient_ == nil)
-            remembered_ = [controllers objectAtIndex:0];
-        transient_ = transient;
-        [transient_ setTabBarItem:[remembered_ tabBarItem]];
-        [controllers replaceObjectAtIndex:0 withObject:transient_];
-        [self setSelectedIndex:0];
-        [self setViewControllers:controllers];
-        [self concealTabBarSelection];
-    } else if (remembered_ != nil) {
-        [remembered_ setTabBarItem:[transient_ tabBarItem]];
-        transient_ = transient;
-        [controllers replaceObjectAtIndex:0 withObject:remembered_];
-        remembered_ = nil;
-        [self setViewControllers:controllers];
-        [self revealTabBarSelection];
-    }
-}
-
-- (UIViewController *) unselectedViewController {
-    return transient_;
-}
-
-- (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
-    if ([self unselectedViewController])
-        [self setUnselectedViewController:nil];
-}
+@implementation CydiaTabBarController
 
 - (NSArray *) navigationURLCollection {
     NSMutableArray *items([NSMutableArray array]);
@@ -6763,43 +6854,15 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     return items;
 }
 
-- (void) dismissModalViewControllerAnimated:(BOOL)animated {
-    if ([self modalViewController] == nil && [self unselectedViewController] != nil)
-        [self setUnselectedViewController:nil];
-    else
-        [super dismissModalViewControllerAnimated:YES];
-}
-
-- (void) unloadData {
-    [super unloadData];
-
-    for (UINavigationController *controller in [self viewControllers])
-        [controller unloadData];
-
-    if (UIViewController *selected = [self selectedViewController])
-        [selected reloadData];
-
-    if (UIViewController *unselected = [self unselectedViewController]) {
-        [unselected unloadData];
-        [unselected reloadData];
-    }
-}
-
-- (void) dealloc {
-    [[NSNotificationCenter defaultCenter] removeObserver:self];
-
-    [super dealloc];
-}
-
 - (id) initWithDatabase:(Database *)database {
     if ((self = [super init]) != nil) {
         database_ = database;
         [self setDelegate:self];
 
-        [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
-        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
+        indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
+        [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
 
-        refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
+        [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
     } return self;
 }
 
@@ -6808,8 +6871,17 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) beginUpdate {
-    [(RefreshBar *) refreshbar_ start];
-    [self dropBar:YES];
+    if (updating_)
+        return;
+
+    UIViewController *controller([[self viewControllers] objectAtIndex:1]);
+    UITabBarItem *item([controller tabBarItem]);
+
+    [item setBadgeValue:@""];
+    UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
+
+    [indicator_ startAnimating];
+    [badge addSubview:indicator_];
 
     [updatedelegate_ retainNetworkActivityIndicator];
     updating_ = true;
@@ -6824,8 +6896,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 - (void) performUpdate {
     NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
 
-    Status status;
-    status.setDelegate(self);
+    SourceStatus status(self, database_);
     [database_ updateWithStatus:status];
 
     [self
@@ -6841,8 +6912,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     updating_ = false;
     [updatedelegate_ releaseNetworkActivityIndicator];
 
-    [self raiseBar:YES];
-    [refreshbar_ stop];
+    UIViewController *controller([[self viewControllers] objectAtIndex:1]);
+    [[controller tabBarItem] setBadgeValue:nil];
+
+    [indicator_ removeFromSuperview];
+    [indicator_ stopAnimating];
 
     [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
 }
@@ -6854,7 +6928,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) cancelUpdate {
-    [self stopUpdateWithSelector:@selector(updateData)];
+    [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
 }
 
 - (void) cancelPressed {
@@ -6865,25 +6939,14 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     return updating_;
 }
 
-- (void) addProgressEvent:(CydiaProgressEvent *)event {
-    [refreshbar_ setPrompt:[event compoundMessage]];
-}
-
-- (bool) isProgressCancelled {
+- (bool) isSourceCancelled {
     return !updating_;
 }
 
-- (void) setProgressCancellable:(NSNumber *)cancellable {
-    [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
-}
-
-- (void) setProgressPercent:(NSNumber *)percent {
-    [refreshbar_ setProgress:[percent floatValue]];
+- (void) startSourceFetch:(NSString *)uri {
 }
 
-- (void) setProgressStatus:(NSDictionary *)status {
-    if (status != nil)
-        [self setProgressPercent:[status objectForKey:@"Percent"]];
+- (void) stopSourceFetch:(NSString *)uri {
 }
 
 - (void) setUpdateDelegate:(id)delegate {
@@ -6891,84 +6954,12 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (UIView *) transitionView {
-    if ([self respondsToSelector:@selector(_transitionView)])
-        return [self _transitionView];
-    else
+    if (![self respondsToSelector:@selector(_transitionView)])
         return MSHookIvar<id>(self, "_viewControllerTransitionView");
-}
-
-- (void) dropBar:(BOOL)animated {
-    if (dropped_)
-        return;
-    dropped_ = true;
-
-    UIView *transition([self transitionView]);
-    [[self view] addSubview:refreshbar_];
-
-    CGRect barframe([refreshbar_ frame]);
-
-    if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
-        barframe.origin.y = CYStatusBarHeight();
+    else if (kCFCoreFoundationVersionNumber < 800)
+        return [self _transitionView];
     else
-        barframe.origin.y = 0;
-
-    [refreshbar_ setFrame:barframe];
-
-    if (animated)
-        [UIView beginAnimations:nil context:NULL];
-
-    CGRect viewframe = [transition frame];
-    viewframe.origin.y += barframe.size.height;
-    viewframe.size.height -= barframe.size.height;
-    [transition setFrame:viewframe];
-
-    if (animated)
-        [UIView commitAnimations];
-
-    // Ensure bar has the proper width for our view, it might have changed
-    barframe.size.width = viewframe.size.width;
-    [refreshbar_ setFrame:barframe];
-}
-
-- (void) raiseBar:(BOOL)animated {
-    if (!dropped_)
-        return;
-    dropped_ = false;
-
-    UIView *transition([self transitionView]);
-    [refreshbar_ removeFromSuperview];
-
-    CGRect barframe([refreshbar_ frame]);
-
-    if (animated)
-        [UIView beginAnimations:nil context:NULL];
-
-    CGRect viewframe = [transition frame];
-    viewframe.origin.y -= barframe.size.height;
-    viewframe.size.height += barframe.size.height;
-    [transition setFrame:viewframe];
-
-    if (animated)
-        [UIView commitAnimations];
-}
-
-- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
-    bool dropped(dropped_);
-
-    if (dropped)
-        [self raiseBar:NO];
-
-    [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
-
-    if (dropped)
-        [self dropBar:NO];
-}
-
-- (void) statusBarFrameChanged:(NSNotification *)notification {
-    if (dropped_) {
-        [self raiseBar:NO];
-        [self dropBar:NO];
-    }
+        return [[[self _transitionView] superview] superview];
 }
 
 @end
@@ -7119,37 +7110,52 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 /* Section Controller {{{ */
 @interface SectionController : FilteredPackageListController {
+    _H<NSString> key_;
     _H<NSString> section_;
 }
 
-- (id) initWithDatabase:(Database *)database section:(NSString *)section;
+- (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
 
 @end
 
 @implementation SectionController
 
-- (NSURL *) navigationURL {
-    NSString *name = section_;
-    if (name == nil)
-        name = @"all";
+- (NSURL *) referrerURL {
+    NSString *name(section_);
+    name = name ?: @"*";
+    NSString *key(key_);
+    key = key ?: @"*";
+    return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
+}
 
-    return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
+- (NSURL *) navigationURL {
+    NSString *name(section_);
+    name = name ?: @"*";
+    NSString *key(key_);
+    key = key ?: @"*";
+    return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
 }
 
-- (id) initWithDatabase:(Database *)database section:(NSString *)name {
+- (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
     NSString *title;
-    if (name == nil)
+    if (section == nil)
         title = UCLocalize("ALL_PACKAGES");
-    else if (![name isEqual:@""])
-        title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
+    else if (![section isEqual:@""])
+        title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
     else
         title = UCLocalize("NO_SECTION");
 
-    if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
-        section_ = name;
+    if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:source:) with:section with:source]) != nil) {
+        key_ = [source key];
+        section_ = section;
     } return self;
 }
 
+- (void) reloadData {
+    [super setStuff:[database_ sourceWithKey:key_]];
+    [super reloadData];
+}
+
 @end
 /* }}} */
 /* Sections Controller {{{ */
@@ -7158,12 +7164,13 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     UITableViewDelegate
 > {
     _transient Database *database_;
+    _H<NSString> key_;
     _H<NSMutableArray> sections_;
     _H<NSMutableArray> filtered_;
     _H<UITableView, 2> list_;
 }
 
-- (id) initWithDatabase:(Database *)database;
+- (id) initWithDatabase:(Database *)database source:(Source *)source;
 - (void) editButtonClicked;
 
 @end
@@ -7171,7 +7178,13 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 @implementation SectionsController
 
 - (NSURL *) navigationURL {
-    return [NSURL URLWithString:@"cydia://sections"];
+    return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
+}
+
+- (Source *) source {
+    if (key_ == nil)
+        return nil;
+    return [database_ sourceWithKey:key_];
 }
 
 - (void) updateNavigationItem {
@@ -7205,14 +7218,14 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) viewWillDisappear:(BOOL)animated {
     [super viewWillDisappear:animated];
-    if ([self isEditing]) [self setEditing:NO];
+    [self setEditing:NO];
 }
 
 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
     Section *section = nil;
     int index = [indexPath row];
     if (![self isEditing]) {
-        index -= 1; 
+        index -= 1;
         if (index >= 0)
             section = [filtered_ objectAtIndex:index];
     } else {
@@ -7252,6 +7265,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     SectionController *controller = [[[SectionController alloc]
         initWithDatabase:database_
+        source:[self source]
         section:[section name]
     ] autorelease];
     [controller setDelegate:delegate_];
@@ -7260,14 +7274,12 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) loadView {
-    [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
-
-    list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
+    list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
     [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
-    [list_ setRowHeight:45.0f];
+    [list_ setRowHeight:46];
     [(UITableView *) list_ setDataSource:self];
     [list_ setDelegate:self];
-    [[self view] addSubview:list_];
+    [self setView:list_];
 }
 
 - (void) viewDidLoad {
@@ -7285,9 +7297,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [super releaseSubviews];
 }
 
-- (id) initWithDatabase:(Database *)database {
+- (id) initWithDatabase:(Database *)database source:(Source *)source {
     if ((self = [super init]) != nil) {
         database_ = database;
+        key_ = [source key];
     } return self;
 }
 
@@ -7301,8 +7314,13 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
 
+    Source *source([self source]);
+
     _trace();
     for (Package *package in packages) {
+        if (source != nil && [package source] != source)
+            continue;
+
         NSString *name([package section]);
         NSString *key(name == nil ? @"" : name);
 
@@ -7362,7 +7380,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 > {
     _transient Database *database_;
     unsigned era_;
-    _H<NSArray> packages_;
+    _H<NSMutableArray> packages_;
     _H<NSMutableArray> sections_;
     _H<UITableView, 2> list_;
     unsigned upgrades_;
@@ -7425,15 +7443,43 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
     Package *package([self packageAtIndexPath:path]);
-    CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
+    CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
     [view setDelegate:delegate_];
     [[self navigationController] pushViewController:view animated:YES];
     return path;
 }
 
+- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
+    NSString *context([alert context]);
+
+    if ([context isEqualToString:@"norefresh"])
+        [alert dismissWithClickedButtonIndex:-1 animated:YES];
+}
+
+- (void) setLeftBarButtonItem {
+    if ([delegate_ updating])
+        [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
+            initWithTitle:UCLocalize("CANCEL")
+            style:UIBarButtonItemStyleDone
+            target:self
+            action:@selector(cancelButtonClicked)
+        ] autorelease] animated:YES];
+    else
+        [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
+            initWithTitle:UCLocalize("REFRESH")
+            style:UIBarButtonItemStylePlain
+            target:self
+            action:@selector(refreshButtonClicked)
+        ] autorelease] animated:YES];
+}
+
 - (void) refreshButtonClicked {
-    [delegate_ beginUpdate];
-    [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
+    if ([delegate_ requestUpdate])
+        [self setLeftBarButtonItem];
+}
+
+- (void) cancelButtonClicked {
+    [delegate_ cancelUpdate];
 }
 
 - (void) upgradeButtonClicked {
@@ -7442,14 +7488,16 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) loadView {
-    [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
+    UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
+    [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
+    [self setView:view];
 
-    list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
+    list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
     [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
     [list_ setRowHeight:73];
     [(UITableView *) list_ setDataSource:self];
     [list_ setDelegate:self];
-    [[self view] addSubview:list_];
+    [view addSubview:list_];
 }
 
 - (void) viewDidLoad {
@@ -7496,7 +7544,9 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 } }
 
 - (void) _reloadData {
-    NSArray *packages;
+    [self setLeftBarButtonItem];
+
+    NSMutableArray *packages;
 
   reload:
     if (true) {
@@ -7585,13 +7635,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         action:@selector(upgradeButtonClicked)
     ] autorelease]) animated:YES];
 
-    [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
-        initWithTitle:UCLocalize("REFRESH")
-        style:UIBarButtonItemStylePlain
-        target:self
-        action:@selector(refreshButtonClicked)
-    ] autorelease]) animated:YES];
-
     PrintTimes();
 } }
 
@@ -7617,26 +7660,32 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 @implementation SearchController
 
+- (NSURL *) referrerURL {
+    return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
+}
+
 - (NSURL *) navigationURL {
     if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
         return [NSURL URLWithString:@"cydia://search"];
     else
-        return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
+        return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
+}
+
+- (NSArray *) termsForQuery:(NSString *)query {
+    NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
+    for (NSString *component in [query componentsSeparatedByString:@" "])
+        if ([component length] != 0)
+            [terms addObject:component];
+
+    return terms;
 }
 
 - (void) useSearch {
-    [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
+    [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
     [self clearData];
     [self reloadData];
 }
 
-- (void) viewWillAppear:(BOOL)animated {
-    [super viewWillAppear:animated];
-
-    if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
-        [self useSearch];
-}
-
 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
     [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
     [self clearData];
@@ -7686,7 +7735,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
-    if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
+    if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
         search_ = [[[UISearchBar alloc] init] autorelease];
         [search_ setDelegate:self];
 
@@ -7714,12 +7763,15 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         [textField setEnablesReturnKeyAutomatically:NO];
         [[self navigationItem] setTitleView:textField];
     }
+
+    if ([self isSummarized])
+        [search_ becomeFirstResponder];
 }
 
 - (void) reloadData {
     id object([search_ text]);
     if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
-        object = [object componentsSeparatedByString:@" "];
+        object = [self termsForQuery:object];
 
     [self setObject:object];
     [self resetCursor];
@@ -7813,18 +7865,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         pclose(dpkg);
 
         exit(0);
-        _assert(false);
-    }
-
-    _forever {
-        int status;
-        int result(waitpid(pid, &status, 0));
-
-        if (result != -1) {
-            _assert(result == pid);
-            break;
-        }
-    }
+    } ReapZombie(pid);
 }
 
 - (void) onIgnored:(id)control {
@@ -7850,13 +7891,15 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) loadView {
-    [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
+    UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
+    [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
+    [self setView:view];
 
     table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
     [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
     [(UITableView *) table_ setDataSource:self];
     [table_ setDelegate:self];
-    [[self view] addSubview:table_];
+    [view addSubview:table_];
 
     subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
     [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
@@ -7918,25 +7961,32 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 /* Installed Controller {{{ */
 @interface InstalledController : FilteredPackageListController {
-    BOOL expert_;
 }
 
 - (id) initWithDatabase:(Database *)database;
-
-- (void) updateRoleButton;
 - (void) queueStatusDidChange;
 
 @end
 
 @implementation InstalledController
 
+- (NSURL *) referrerURL {
+    return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
+}
+
 - (NSURL *) navigationURL {
     return [NSURL URLWithString:@"cydia://installed"];
 }
 
 - (id) initWithDatabase:(Database *)database {
     if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
-        [self updateRoleButton];
+        UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("SIMPLE"), UCLocalize("EXPERT"), nil]] autorelease]);
+        [segmented setSelectedSegmentIndex:0];
+        [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
+        [[self navigationItem] setTitleView:segmented];
+
+        [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
+
         [self queueStatusDidChange];
     } return self;
 }
@@ -7949,37 +7999,23 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) queueStatusDidChange {
 #if !AlwaysReload
-    if (IsWildcat_) {
-        if (Queuing_) {
-            [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
-                initWithTitle:UCLocalize("QUEUE")
-                style:UIBarButtonItemStyleDone
-                target:self
-                action:@selector(queueButtonClicked)
-            ] autorelease]];
-        } else {
-            [[self navigationItem] setLeftBarButtonItem:nil];
-        }
-    }
-#endif
-}
-
-- (void) updateRoleButton {
-    if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
-        [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
-            initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
-            style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
+    if (Queuing_) {
+        [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
+            initWithTitle:UCLocalize("QUEUE")
+            style:UIBarButtonItemStyleDone
             target:self
-            action:@selector(roleButtonClicked)
+            action:@selector(queueButtonClicked)
         ] autorelease]];
+    } else {
+        [[self navigationItem] setLeftBarButtonItem:nil];
+    }
+#endif
 }
 
-- (void) roleButtonClicked {
-    [self setObject:[NSNumber numberWithBool:expert_]];
+- (void) modeChanged:(UISegmentedControl *)segmented {
+    bool simple([segmented selectedSegmentIndex] == 0);
+    [self setObject:[NSNumber numberWithBool:simple]];
     [self reloadData];
-    expert_ = !expert_;
-
-    [self updateRoleButton];
 }
 
 @end
@@ -7987,22 +8023,29 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 /* Source Cell {{{ */
 @interface SourceCell : CyteTableViewCell <
-    CyteTableViewCellDelegate
+    CyteTableViewCellDelegate,
+    SourceDelegate
 > {
+    _H<Source, 1> source_;
+    _H<NSURL> url_;
     _H<UIImage> icon_;
     _H<NSString> origin_;
     _H<NSString> label_;
+    _H<UIActivityIndicatorView> indicator_;
 }
 
 - (void) setSource:(Source *)source;
+- (void) setFetch:(NSNumber *)fetch;
 
 @end
 
 @implementation SourceCell
 
-- (void) _setImage:(UIImage *)image {
-    icon_ = image;
-    [content_ setNeedsDisplay];
+- (void) _setImage:(NSArray *)data {
+    if ([url_ isEqual:[data objectAtIndex:0]]) {
+        icon_ = [data objectAtIndex:1];
+        [content_ setNeedsDisplay];
+    }
 }
 
 - (void) _setSource:(NSURL *) url {
@@ -8011,20 +8054,25 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     if (NSData *data = [NSURLConnection
         sendSynchronousRequest:[NSURLRequest
             requestWithURL:url
-            //cachePolicy:NSURLRequestUseProtocolCachePolicy
-            //timeoutInterval:5
+            cachePolicy:NSURLRequestUseProtocolCachePolicy
+            timeoutInterval:10
         ]
 
         returningResponse:NULL
         error:NULL
     ])
         if (UIImage *image = [UIImage imageWithData:data])
-            [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
+            [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
 
     [pool release];
 }
 
 - (void) setSource:(Source *)source {
+    source_ = source;
+    [source_ setDelegate:self];
+
+    [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
+
     icon_ = [UIImage applicationImageNamed:@"unknown.png"];
 
     origin_ = [source name];
@@ -8032,8 +8080,18 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     [content_ setNeedsDisplay];
 
-    if (NSURL *url = [source iconURL])
-        [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url];
+    url_ = [source iconURL];
+    [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
+}
+
+- (void) setAllSource {
+    source_ = nil;
+    [indicator_ stopAnimating];
+
+    icon_ = [UIImage applicationImageNamed:@"folder.png"];
+    origin_ = UCLocalize("ALL_SOURCES");
+    label_ = UCLocalize("ALL_SOURCES_EX");
+    [content_ setNeedsDisplay];
 }
 
 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
@@ -8049,12 +8107,31 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         [content_ setDelegate:self];
         [content_ setOpaque:YES];
 
+        indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
+        [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
+        [content addSubview:indicator_];
+
         [[content_ layer] setContentsGravity:kCAGravityTopLeft];
     } return self;
 }
 
+- (void) layoutSubviews {
+    [super layoutSubviews];
+
+    UIView *content([self contentView]);
+    CGRect bounds([content bounds]);
+
+    CGRect frame([indicator_ frame]);
+    frame.origin.x = bounds.size.width - frame.size.width;
+    frame.origin.y = (bounds.size.height - frame.size.height) / 2;
+
+    if (kCFCoreFoundationVersionNumber < 800)
+        frame.origin.x -= 8;
+    [indicator_ setFrame:frame];
+}
+
 - (NSString *) accessibilityLabel {
-    return label_;
+    return origin_;
 }
 
 - (void) drawContentRect:(CGRect)rect {
@@ -8070,57 +8147,29 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
             rect.size.height /= 2;
         }
 
-        rect.origin.x = 25 - rect.size.width / 2;
-        rect.origin.y = 25 - rect.size.height / 2;
+        rect.origin.x = 26 - rect.size.width / 2;
+        rect.origin.y = 26 - rect.size.height / 2;
 
         [icon_ drawInRect:rect];
     }
 
-    if (highlighted)
+    if (highlighted && kCFCoreFoundationVersionNumber < 800)
         UISetColor(White_);
 
     if (!highlighted)
         UISetColor(Black_);
-    [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 60) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
+    [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 61) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
 
     if (!highlighted)
-        UISetColor(Blue_);
-    [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 75) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
-}
-
-@end
-/* }}} */
-/* Source Controller {{{ */
-@interface SourceController : FilteredPackageListController {
-    _transient Source *source_;
-    _H<NSString> key_;
+        UISetColor(Gray_);
+    [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 61) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
 }
 
-- (id) initWithDatabase:(Database *)database source:(Source *)source;
-
-@end
-
-@implementation SourceController
-
-- (NSURL *) navigationURL {
-    return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
-}
-
-- (id) initWithDatabase:(Database *)database source:(Source *)source {
-    if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
-        source_ = source;
-        key_ = [source key];
-    } return self;
-}
-
-- (void) reloadData {
-    source_ = [database_ sourceWithKey:key_];
-    key_ = [source_ key];
-    [self setObject:source_];
-
-    [[self navigationItem] setTitle:[source_ label]];
-
-    [super reloadData];
+- (void) setFetch:(NSNumber *)fetch {
+    if ([fetch boolValue])
+        [indicator_ startAnimating];
+    else
+        [indicator_ stopAnimating];
 }
 
 @end
@@ -8131,6 +8180,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     UITableViewDelegate
 > {
     _transient Database *database_;
+    unsigned era_;
+
     _H<UITableView, 2> list_;
     _H<NSMutableArray> sources_;
     int offset_;
@@ -8139,17 +8190,14 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     _H<UIProgressHUD> hud_;
     _H<NSError> error_;
 
-    //NSURLConnection *installer_;
-    NSURLConnection *trivial_;
     NSURLConnection *trivial_bz2_;
     NSURLConnection *trivial_gz_;
-    //NSURLConnection *automatic_;
 
     BOOL cydia_;
 }
 
 - (id) initWithDatabase:(Database *)database;
-- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
+- (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
 
 @end
 
@@ -8164,11 +8212,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) dealloc {
-    //[self _releaseConnection:installer_];
-    [self _releaseConnection:trivial_];
     [self _releaseConnection:trivial_gz_];
     [self _releaseConnection:trivial_bz2_];
-    //[self _releaseConnection:automatic_];
 
     [super dealloc];
 }
@@ -8183,60 +8228,90 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
-    return 1;
+    return 2;
 }
 
 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
+    if (section == 1)
+        return UCLocalize("INDIVIDUAL_SOURCES");
     return nil;
 }
 
 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
-    return [sources_ count];
+    switch (section) {
+        case 0: return 1;
+        case 1: return [sources_ count];
+        default: return 0;
+    }
 }
 
 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
-    return [sources_ objectAtIndex:[indexPath row]];
-}
+@synchronized (database_) {
+    if ([database_ era] != era_)
+        return nil;
+    if ([indexPath section] != 1)
+        return nil;
+    NSUInteger index([indexPath row]);
+    if (index >= [sources_ count])
+        return nil;
+    return [sources_ objectAtIndex:index];
+} }
 
 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     static NSString *cellIdentifier = @"SourceCell";
 
     SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
-    if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
-    [cell setSource:[self sourceAtIndexPath:indexPath]];
+    if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
     [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
 
+    Source *source([self sourceAtIndexPath:indexPath]);
+    if (source == nil)
+        [cell setAllSource];
+    else
+        [cell setSource:source];
+
     return cell;
 }
 
 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
-    Source *source = [self sourceAtIndexPath:indexPath];
-
-    SourceController *controller = [[[SourceController alloc]
+    SectionsController *controller([[[SectionsController alloc]
         initWithDatabase:database_
-        source:source
-    ] autorelease];
+        source:[self sourceAtIndexPath:indexPath]
+    ] autorelease]);
 
     [controller setDelegate:delegate_];
-
     [[self navigationController] pushViewController:controller animated:YES];
 }
 
 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
+    if ([indexPath section] != 1)
+        return false;
     Source *source = [self sourceAtIndexPath:indexPath];
     return [source record] != nil;
 }
 
 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
+    _assert([indexPath section] == 1);
     if (editingStyle ==  UITableViewCellEditingStyleDelete) {
         Source *source = [self sourceAtIndexPath:indexPath];
+        if (source == nil) return;
+
         [Sources_ removeObjectForKey:[source key]];
-        [delegate_ syncData];
+        Changed_ = true;
+
+        [delegate_ _saveConfig];
+        [delegate_ reloadDataWithInvocation:nil];
     }
 }
 
+- (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
+    [self updateButtonsForEditingStatusAnimated:YES];
+}
+
 - (void) complete {
     [delegate_ addTrivialSource:href_];
+    href_ = nil;
+
     [delegate_ syncData];
 }
 
@@ -8247,7 +8322,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         href = [href substringFromIndex:(colon.location + 3)];
     href = [href stringByAddingPercentEscapes];
     href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
-    href = [href stringByCachingURLWithCurrentCDN];
 
     NSURL *url([NSURL URLWithString:href]);
 
@@ -8263,9 +8337,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     // XXX: the memory management in this method is horribly awkward
 
     NSURLConnection **field = NULL;
-    if (connection == trivial_)
-        field = &trivial_;
-    else if (connection == trivial_bz2_)
+    if (connection == trivial_bz2_)
         field = &trivial_bz2_;
     else if (connection == trivial_gz_)
         field = &trivial_gz_;
@@ -8274,17 +8346,18 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     *field = nil;
 
     if (
-        trivial_ == nil &&
         trivial_bz2_ == nil &&
         trivial_gz_ == nil
     ) {
+        NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
+
         [delegate_ releaseNetworkActivityIndicator];
 
         [delegate_ removeProgressHUD:hud_];
         hud_ = nil;
 
         if (cydia_) {
-            if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
+            if (warning != nil) {
                 UIAlertView *alert = [[[UIAlertView alloc]
                     initWithTitle:UCLocalize("SOURCE_WARNING")
                     message:warning
@@ -8316,6 +8389,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
             [alert setContext:@"urlerror"];
             [alert show];
+
+            href_ = nil;
         } else {
             UIAlertView *alert = [[[UIAlertView alloc]
                 initWithTitle:UCLocalize("NOT_REPOSITORY")
@@ -8327,9 +8402,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
             [alert setContext:@"trivial"];
             [alert show];
+
+            href_ = nil;
         }
 
-        href_ = nil;
         error_ = nil;
     }
 }
@@ -8342,7 +8418,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
-    lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
+    lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
     error_ = error;
     [self _endConnection:connection];
 }
@@ -8357,7 +8433,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     NSMutableURLRequest *request = [NSMutableURLRequest
         requestWithURL:url
         cachePolicy:NSURLRequestUseProtocolCachePolicy
-        timeoutInterval:120.0
+        timeoutInterval:10
     ];
 
     [request setHTTPMethod:method];
@@ -8365,11 +8441,12 @@ 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"];
+        if (UniqueID_ != nil)
             [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
-        }
     }
 
     return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
@@ -8383,17 +8460,29 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
             case 1: {
                 NSString *href = [[alert textField] text];
 
-                //installer_ = [[self _requestHRef:href method:@"GET"] retain];
+                static Pcre href_r("^http(s?)://[^# ]*$");
+                if (!href_r(href)) {
+                    UIAlertView *alert = [[[UIAlertView alloc]
+                        initWithTitle:Error_
+                        message:UCLocalize("INVALID_URL")
+                        delegate:self
+                        cancelButtonTitle:UCLocalize("OK")
+                        otherButtonTitles:nil
+                    ] autorelease];
+
+                    [alert setContext:@"badurl"];
+                    [alert show];
+
+                    break;
+                }
 
                 if (![href hasSuffix:@"/"])
                     href_ = [href stringByAppendingString:@"/"];
                 else
                     href_ = href;
 
-                trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
                 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
                 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
-                //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
 
                 cydia_ = false;
 
@@ -8417,7 +8506,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     else if ([context isEqualToString:@"warning"]) {
         switch (button) {
             case 1:
-                [self complete];
+                [self performSelector:@selector(complete) withObject:nil afterDelay:0];
             break;
 
             case 0:
@@ -8426,28 +8515,64 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
             _nodefault
         }
 
-        href_ = nil;
-
         [alert dismissWithClickedButtonIndex:-1 animated:YES];
     }
 }
 
-- (void) loadView {
-    [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
+- (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
+    BOOL editing([list_ isEditing]);
 
-    list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
+    if (editing)
+        [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
+            initWithTitle:UCLocalize("ADD")
+            style:UIBarButtonItemStylePlain
+            target:self
+            action:@selector(addButtonClicked)
+        ] autorelease] animated:animated];
+    else if ([delegate_ updating])
+        [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
+            initWithTitle:UCLocalize("CANCEL")
+            style:UIBarButtonItemStyleDone
+            target:self
+            action:@selector(cancelButtonClicked)
+        ] autorelease] animated:animated];
+    else
+        [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
+            initWithTitle:UCLocalize("REFRESH")
+            style:UIBarButtonItemStylePlain
+            target:self
+            action:@selector(refreshButtonClicked)
+        ] autorelease] animated:animated];
+
+    [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
+        initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
+        style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
+        target:self
+        action:@selector(editButtonClicked)
+    ] autorelease] animated:animated];
+}
+
+- (void) loadView {
+    list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
     [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
     [list_ setRowHeight:53];
     [(UITableView *) list_ setDataSource:self];
     [list_ setDelegate:self];
-    [[self view] addSubview:list_];
+    [self setView:list_];
 }
 
 - (void) viewDidLoad {
     [super viewDidLoad];
 
     [[self navigationItem] setTitle:UCLocalize("SOURCES")];
-    [self updateButtonsForEditingStatus:NO animated:NO];
+    [self updateButtonsForEditingStatusAnimated:NO];
+}
+
+- (void) viewWillAppear:(BOOL)animated {
+    [super viewWillAppear:animated];
+
+    [list_ setEditing:NO];
+    [self updateButtonsForEditingStatusAnimated:NO];
 }
 
 - (void) releaseSubviews {
@@ -8466,10 +8591,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) reloadData {
     [super reloadData];
+    [self updateButtonsForEditingStatusAnimated:YES];
 
-    pkgSourceList list;
-    if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
-        return;
+@synchronized (database_) {
+    era_ = [database_ era];
 
     sources_ = [NSMutableArray arrayWithCapacity:16];
     [sources_ addObjectsFromArray:[database_ sources]];
@@ -8485,10 +8610,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         offset_++;
     }
 
-    [list_ setEditing:NO];
-    [self updateButtonsForEditingStatus:NO animated:NO];
     [list_ reloadData];
-}
+} }
 
 - (void) showAddSourcePrompt {
     UIAlertView *alert = [[[UIAlertView alloc]
@@ -8520,235 +8643,23 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [self showAddSourcePrompt];
 }
 
-- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
-    [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
-        initWithTitle:UCLocalize("ADD")
-        style:UIBarButtonItemStylePlain
-        target:self
-        action:@selector(addButtonClicked)
-    ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
-
-    [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
-        initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
-        style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
-        target:self
-        action:@selector(editButtonClicked)
-    ] autorelease] animated:animated];
-
-    if (IsWildcat_ && !editing)
-        [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
-            initWithTitle:UCLocalize("SETTINGS")
-            style:UIBarButtonItemStylePlain
-            target:self
-            action:@selector(settingsButtonClicked)
-        ] autorelease]];
+- (void) refreshButtonClicked {
+    if ([delegate_ requestUpdate])
+        [self updateButtonsForEditingStatusAnimated:YES];
 }
 
-- (void) settingsButtonClicked {
-    [delegate_ showSettings];
+- (void) cancelButtonClicked {
+    [delegate_ cancelUpdate];
 }
 
 - (void) editButtonClicked {
     [list_ setEditing:![list_ isEditing] animated:YES];
-
-    [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
+    [self updateButtonsForEditingStatusAnimated:YES];
 }
 
 @end
 /* }}} */
 
-/* Settings Controller {{{ */
-@interface SettingsController : CyteViewController <
-    UITableViewDataSource,
-    UITableViewDelegate
-> {
-    _transient Database *database_;
-    // XXX: ok, "roledelegate_"?...
-    _transient id roledelegate_;
-    _H<UITableView, 2> table_;
-    _H<UISegmentedControl> segment_;
-    _H<UIView> container_;
-}
-
-- (void) showDoneButton;
-- (void) resizeSegmentedControl;
-
-@end
-
-@implementation SettingsController
-
-- (void) loadView {
-    [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
-
-    table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
-    [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
-    [table_ setDelegate:self];
-    [(UITableView *) table_ setDataSource:self];
-    [[self view] addSubview:table_];
-
-    NSArray *items = [NSArray arrayWithObjects:
-        UCLocalize("USER"),
-        UCLocalize("HACKER"),
-        UCLocalize("DEVELOPER"),
-    nil];
-    segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
-    [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
-    container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
-    [container_ addSubview:segment_];
-}
-
-- (void) viewDidLoad {
-    [super viewDidLoad];
-
-    [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
-
-    int index = -1;
-    if ([Role_ isEqualToString:@"User"]) index = 0;
-    if ([Role_ isEqualToString:@"Hacker"]) index = 1;
-    if ([Role_ isEqualToString:@"Developer"]) index = 2;
-    if (index != -1) {
-        [segment_ setSelectedSegmentIndex:index];
-        [self showDoneButton];
-    }
-
-    [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
-    [self resizeSegmentedControl];
-}
-
-- (void) releaseSubviews {
-    table_ = nil;
-    segment_ = nil;
-    container_ = nil;
-
-    [super releaseSubviews];
-}
-
-- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
-    if ((self = [super init]) != nil) {
-        database_ = database;
-        roledelegate_ = delegate;
-    } return self;
-}
-
-- (void) resizeSegmentedControl {
-    CGFloat width = [[self view] frame].size.width;
-    [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
-}
-
-- (void) viewWillAppear:(BOOL)animated {
-    [super viewWillAppear:animated];
-
-    [self resizeSegmentedControl];
-}
-
-- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
-    [self resizeSegmentedControl];
-}
-
-- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
-    [self resizeSegmentedControl];
-}
-
-- (void) save {
-    NSString *role(nil);
-
-    switch ([segment_ selectedSegmentIndex]) {
-        case 0: role = @"User"; break;
-        case 1: role = @"Hacker"; break;
-        case 2: role = @"Developer"; break;
-
-        _nodefault
-    }
-
-    if (![role isEqualToString:Role_]) {
-        bool rolling(Role_ == nil);
-        Role_ = role;
-
-        Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
-            Role_, @"Role",
-        nil];
-
-        [Metadata_ setObject:Settings_ forKey:@"Settings"];
-        Changed_ = true;
-
-        if (rolling)
-            [roledelegate_ loadData];
-        else
-            [roledelegate_ updateData];
-    }
-}
-
-- (void) segmentChanged:(UISegmentedControl *)control {
-    [self showDoneButton];
-}
-
-- (void) saveAndClose {
-    [self save];
-
-    [[self navigationItem] setRightBarButtonItem:nil];
-    [[self navigationController] dismissModalViewControllerAnimated:YES];
-}
-
-- (void) doneButtonClicked {
-    UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
-    [spinner startAnimating];
-    UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
-    [[self navigationItem] setRightBarButtonItem:spinItem];
-
-    [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
-}
-
-- (void) showDoneButton {
-    [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
-        initWithTitle:UCLocalize("DONE")
-        style:UIBarButtonItemStyleDone
-        target:self
-        action:@selector(doneButtonClicked)
-    ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
-}
-
-- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
-    // XXX: For not having a single cell in the table, this sure is a lot of sections.
-    return 6;
-}
-
-- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
-    return 0; // :(
-}
-
-- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
-    return nil; // This method is required by the protocol.
-}
-
-- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
-    if (section == 1)
-        return UCLocalize("ROLE_EX");
-    if (section == 4)
-        return [NSString stringWithFormat:
-            @"%@: %@\n%@: %@\n%@: %@",
-            UCLocalize("USER"), UCLocalize("USER_EX"),
-            UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
-            UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
-        ];
-    else return nil;
-}
-
-- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
-    return section == 3 ? 44.0f : 0;
-}
-
-- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
-    return section == 3 ? container_ : nil;
-}
-
-- (void) reloadData {
-    [super reloadData];
-
-    [table_ reloadData];
-}
-
-@end
-/* }}} */
 /* Stash Controller {{{ */
 @interface StashController : CyteViewController {
     _H<UIActivityIndicatorView> spinner_;
@@ -8761,8 +8672,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 @implementation StashController
 
 - (void) loadView {
-    [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
-    [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
+    UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
+    [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
+    [self setView:view];
+
+    [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
 
     spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
     CGRect spinrect = [spinner_ frame];
@@ -8770,7 +8684,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     spinrect.origin.y = [[self view] frame].size.height - 80.0f;
     [spinner_ setFrame:spinrect];
     [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
-    [[self view] addSubview:spinner_];
+    [view addSubview:spinner_];
     [spinner_ startAnimating];
 
     CGRect captrect;
@@ -8786,7 +8700,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [caption_ setBackgroundColor:[UIColor clearColor]];
     [caption_ setShadowColor:[UIColor blackColor]];
     [caption_ setTextAlignment:UITextAlignmentCenter];
-    [[self view] addSubview:caption_];
+    [view addSubview:caption_];
 
     CGRect statusrect;
     statusrect.size.width = [[self view] frame].size.width;
@@ -8801,7 +8715,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [status_ setBackgroundColor:[UIColor clearColor]];
     [status_ setShadowColor:[UIColor blackColor]];
     [status_ setTextAlignment:UITextAlignmentCenter];
-    [[self view] addSubview:status_];
+    [view addSubview:status_];
 }
 
 - (void) releaseSubviews {
@@ -8870,7 +8784,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     UITabBarControllerDelegate
 > {
     _H<UIWindow> window_;
-    _H<CYTabBarController> tabbar_;
+    _H<CydiaTabBarController> tabbar_;
     _H<CydiaLoadingViewController> emulated_;
 
     _H<NSMutableArray> essential_;
@@ -8894,10 +8808,52 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 @implementation Cydia
 
+- (void) lockSuspend {
+    if (locked_++ == 0) {
+        if ($SBSSetInterceptsMenuButtonForever != NULL)
+            (*$SBSSetInterceptsMenuButtonForever)(true);
+
+        [self setIdleTimerDisabled:YES];
+    }
+}
+
+- (void) unlockSuspend {
+    if (--locked_ == 0) {
+        [self setIdleTimerDisabled:NO];
+
+        if ($SBSSetInterceptsMenuButtonForever != NULL)
+            (*$SBSSetInterceptsMenuButtonForever)(false);
+    }
+}
+
 - (void) beginUpdate {
     [tabbar_ beginUpdate];
 }
 
+- (void) cancelUpdate {
+    [tabbar_ cancelUpdate];
+}
+
+- (bool) requestUpdate {
+    if (IsReachable("cydia.saurik.com")) {
+        [self beginUpdate];
+        return true;
+    } else {
+        UIAlertView *alert = [[[UIAlertView alloc]
+            initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
+            message:@"Host Unreachable" // XXX: Localize
+            delegate:self
+            cancelButtonTitle:UCLocalize("OK")
+            otherButtonTitles:nil
+        ] autorelease];
+
+        [alert setContext:@"norefresh"];
+        [alert show];
+
+        return false;
+    }
+}
+
 - (BOOL) updating {
     return [tabbar_ updating];
 }
@@ -8910,7 +8866,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
             initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
             message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
             delegate:self
-            cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
+            cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
             otherButtonTitles:
                 UCLocalize("TEMPORARY_IGNORE"),
             nil
@@ -8943,9 +8899,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) _saveConfig {
-    _trace();
-    MetaFile_.Sync();
-    _trace();
+    @synchronized (database_) {
+        _trace();
+        MetaFile_.Sync();
+        _trace();
+    }
 
     if (Changed_) {
         NSString *error(nil);
@@ -9004,7 +8962,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     //  - We already refreshed recently.
     //  - We already auto-refreshed this launch.
     //  - Auto-refresh is disabled.
-    if (recently || loaded_ || ManualRefresh) {
+    //  - Cydia's server is not reachable
+    if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
         // If we are cancelling, we need to make sure it knows it's already loaded.
         loaded_ = true;
 
@@ -9013,27 +8972,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         // We are going to load, so remember that.
         loaded_ = true;
 
-        SCNetworkReachabilityFlags flags; {
-            SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
-            SCNetworkReachabilityGetFlags(reachability, &flags);
-            CFRelease(reachability);
-        }
-
-        // XXX: this elaborate mess is what Apple is using to determine this? :(
-        // XXX: do we care if the user has to intervene? maybe that's ok?
-        bool reachable(
-            (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
-                (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
-                    (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
-                    (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
-                ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
-                (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
-            )
-        );
-
-        // If we can reach the server, auto-refresh!
-        if (reachable)
-            [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
+        [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
     }
 
     [pool release];
@@ -9046,13 +8985,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
 @synchronized (self) {
     UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
-    [hud setText:UCLocalize("RELOADING_DATA")];
+    if (hud != nil)
+        [hud setText:UCLocalize("RELOADING_DATA")];
 
     [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
 
-    if (hud != nil)
-        [self removeProgressHUD:hud];
-
     size_t changes(0);
 
     [essential_ removeAllObjects];
@@ -9062,8 +8999,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     for (Package *package in packages) {
         if ([package half])
             [broken_ addObject:package];
-        if ([package upgradableAndEssential:NO]) {
-            if ([package essential])
+        if ([package upgradableAndEssential:YES] && ![package ignored]) {
+            if ([package essential] && [package installed] != nil)
                 [essential_ addObject:package];
             ++changes;
         }
@@ -9084,12 +9021,21 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     }
 
     [self _updateData];
+
+    if (hud != nil)
+        [self removeProgressHUD:hud];
 } }
 
 - (void) updateData {
     [self _updateData];
 }
 
+- (void) updateDataAndLoad {
+    [self _updateData];
+    if ([database_ progressDelegate] == nil)
+        [self _loaded];
+}
+
 - (void) update_ {
     [database_ update];
     [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
@@ -9100,6 +9046,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         return;
 
     [window_ addSubview:[tabbar_ view]];
+    if ([window_ respondsToSelector:@selector(setRootViewController:)])
+        [window_ setRootViewController:tabbar_];
     [[emulated_ view] removeFromSuperview];
     emulated_ = nil;
     [window_ setUserInteractionEnabled:YES];
@@ -9253,21 +9201,30 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     }
 }
 
+- (void) _uicache {
+    _trace();
+    system("su -c /usr/bin/uicache mobile");
+    _trace();
+}
+
+- (void) uicache {
+    UIProgressHUD *hud([self addProgressHUD]);
+    [hud setText:UCLocalize("LOADING")];
+    [self yieldToSelector:@selector(_uicache)];
+    [self removeProgressHUD:hud];
+}
+
 - (void) perform_ {
     [database_ perform];
     [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
+    [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
 }
 
 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
     Queuing_ = false;
-    ++locked_;
+    [self lockSuspend];
     [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
-    --locked_;
-    [self refreshIfPossible];
-}
-
-- (void) showSettings {
-    [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
+    [self unlockSuspend];
 }
 
 - (void) retainNetworkActivityIndicator {
@@ -9428,30 +9385,34 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     [hud showInView:[target view]];
 
-    ++locked_;
+    [self lockSuspend];
     return hud;
 }
 
 - (void) removeProgressHUD:(UIProgressHUD *)hud {
-    --locked_;
+    [self unlockSuspend];
     [hud hide];
     [hud removeFromSuperview];
     [window_ setUserInteractionEnabled:YES];
 }
 
-- (CyteViewController *) pageForPackage:(NSString *)name {
-    return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
+- (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
+    return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
 }
 
-- (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
+- (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
     NSString *scheme([[url scheme] lowercaseString]);
     if ([[url absoluteString] length] <= [scheme length] + 3)
         return nil;
     NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
-    NSArray *components([path pathComponents]);
+    NSArray *components([path componentsSeparatedByString:@"/"]);
 
-    if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
-        return [self pageForPackage:[components objectAtIndex:1]];
+    if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
+        CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
+        if (controller != nil)
+            [controller setDelegate:self];
+        return controller;
+    }
 
     if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
         return nil;
@@ -9465,10 +9426,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
         controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
     } else if (!external && [components count] == 1) {
-        if ([base isEqualToString:@"manage"]) {
-            controller = [[[ManageController alloc] init] autorelease];
-        }
-
         if ([base isEqualToString:@"sources"]) {
             controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
         }
@@ -9478,7 +9435,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         }
 
         if ([base isEqualToString:@"sections"]) {
-            controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
+            controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
         }
 
         if ([base isEqualToString:@"search"]) {
@@ -9493,10 +9450,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
             controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
         }
     } else if ([components count] == 2) {
-        NSString *argument = [components objectAtIndex:1];
+        NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
 
         if ([base isEqualToString:@"package"]) {
-            controller = [self pageForPackage:argument];
+            controller = [self pageForPackage:argument withReferrer:referrer];
         }
 
         if (!external && [base isEqualToString:@"search"]) {
@@ -9504,9 +9461,9 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         }
 
         if (!external && [base isEqualToString:@"sections"]) {
-            if ([argument isEqualToString:@"all"])
+            if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
                 argument = nil;
-            controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
+            controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
         }
 
         if (!external && [base isEqualToString:@"sources"]) {
@@ -9514,8 +9471,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
                 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
                 [(SourcesController *)controller showAddSourcePrompt];
             } else {
-                Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
-                controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
+                Source *source([database_ sourceWithKey:argument]);
+                controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
             }
         }
 
@@ -9524,8 +9481,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
             return nil;
         }
     } else if (!external && [components count] == 3) {
-        NSString *arg1 = [components objectAtIndex:1];
-        NSString *arg2 = [components objectAtIndex:2];
+        NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
+        NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
 
         if ([base isEqualToString:@"package"]) {
             if ([arg2 isEqualToString:@"settings"]) {
@@ -9537,6 +9494,12 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
                 }
             }
         }
+
+        if ([base isEqualToString:@"sections"]) {
+            Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
+            NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
+            controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
+        }
     }
 
     [controller setDelegate:self];
@@ -9544,13 +9507,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
-    CyteViewController *page([self pageForURL:url forExternal:external]);
+    CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
 
-    if (page != nil) {
-        UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
-        [nav setViewControllers:[NSArray arrayWithObject:page]];
-        [tabbar_ setUnselectedViewController:nav];
-    }
+    if (page != nil)
+        [tabbar_ setUnselectedViewController:page];
 
     return page != nil;
 }
@@ -9614,7 +9574,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) addStashController {
-    ++locked_;
+    [self lockSuspend];
     stash_ = [[[StashController alloc] init] autorelease];
     [window_ addSubview:[stash_ view]];
 }
@@ -9622,12 +9582,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 - (void) removeStashController {
     [[stash_ view] removeFromSuperview];
     stash_ = nil;
-    --locked_;
+    [self unlockSuspend];
 }
 
 - (void) stash {
-    [self setIdleTimerDisabled:YES];
-
     [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
     UpdateExternalStatus(1);
     [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
@@ -9635,27 +9593,35 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     [self removeStashController];
 
-    if (ExecFork() == 0) {
+    pid_t pid(ExecFork());
+    if (pid == 0) {
         execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
         perror("launchctl stop");
-    }
+
+        exit(0);
+    } ReapZombie(pid);
 }
 
 - (void) setupViewControllers {
-    tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
-
-    NSMutableArray *items([NSMutableArray arrayWithObjects:
-        [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
-        [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
-        [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
-        [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
-    nil]);
-
-    if (IsWildcat_) {
-        [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
-        [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
+    tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
+
+    NSMutableArray *items;
+    if (kCFCoreFoundationVersionNumber < 800) {
+        items = [NSMutableArray arrayWithObjects:
+            [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
+            [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
+            [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
+            [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease],
+            [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
+        nil];
     } else {
-        [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
+        items = [NSMutableArray arrayWithObjects:
+            [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home7.png"] selectedImage:[UIImage applicationImageNamed:@"home7s.png"]] autorelease],
+            [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install7.png"] selectedImage:[UIImage applicationImageNamed:@"install7s.png"]] autorelease],
+            [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes7.png"] selectedImage:[UIImage applicationImageNamed:@"changes7s.png"]] autorelease],
+            [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease],
+            [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search7.png"] selectedImage:[UIImage applicationImageNamed:@"search7s.png"]] autorelease],
+        nil];
     }
 
     NSMutableArray *controllers([NSMutableArray array]);
@@ -9670,16 +9636,25 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) _sendMemoryWarningNotification {
-    [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
+    if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
+        [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
+    else
+        [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
 }
 
 - (void) _sendMemoryWarningNotifications {
     while (true) {
         [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
-        usleep(250000);
+        sleep(2);
+        //usleep(2000000);
     }
 }
 
+- (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
+    NSLog(@"--");
+    [[NSURLCache sharedURLCache] removeAllCachedResponses];
+}
+
 - (void) applicationDidFinishLaunching:(id)unused {
     //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
 
@@ -9694,7 +9669,7 @@ _trace();
     [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
         initWithMemoryCapacity:524288
         diskCapacity:10485760
-        diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
+        diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
     ] autorelease]];
 
     [CydiaWebViewController _initialize];
@@ -9707,6 +9682,7 @@ _trace();
     Font12_ = [UIFont systemFontOfSize:12];
     Font12Bold_ = [UIFont boldSystemFontOfSize:12];
     Font14_ = [UIFont systemFontOfSize:14];
+    Font18_ = [UIFont systemFontOfSize:18];
     Font18Bold_ = [UIFont boldSystemFontOfSize:18];
     Font22Bold_ = [UIFont boldSystemFontOfSize:22];
 
@@ -9721,18 +9697,7 @@ _trace();
     [window_ makeKey:self];
     [window_ setHidden:NO];
 
-    if (
-        readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
-        readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
-        readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
-        //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
-        readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
-        readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
-        readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
-        readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
-        //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
-        false
-    ) {
+    if (false) stash: {
         [self addStashController];
         // XXX: this would be much cleaner as a yieldToSelector:
         // that way the removeStashController could happen right here inline
@@ -9741,6 +9706,31 @@ _trace();
         return;
     }
 
+    struct stat root;
+    int error(stat("/", &root));
+    _assert(error != -1);
+
+    #define Stash_(path) do { \
+        struct stat folder; \
+        int error(lstat((path), &folder)); \
+        if (error != -1 && ( \
+            folder.st_dev == root.st_dev && \
+            S_ISDIR(folder.st_mode) \
+        ) || error == -1 && ( \
+            errno == ENOENT || \
+            errno == ENOTDIR \
+        )) goto stash; \
+    } while (false)
+
+    Stash_("/Applications");
+    Stash_("/Library/Ringtones");
+    Stash_("/Library/Wallpaper");
+    //Stash_("/usr/bin");
+    Stash_("/usr/include");
+    Stash_("/usr/lib/pam");
+    Stash_("/usr/share");
+    //Stash_("/var/lib");
+
     database_ = [Database sharedInstance];
     [database_ setDelegate:self];
 
@@ -9749,6 +9739,8 @@ _trace();
 
     emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
     [window_ addSubview:[emulated_ view]];
+    if ([window_ respondsToSelector:@selector(setRootViewController:)])
+        [window_ setRootViewController:emulated_];
 
     [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
 _trace();
@@ -9757,29 +9749,18 @@ _trace();
 - (NSArray *) defaultStartPages {
     NSMutableArray *standard = [NSMutableArray array];
     [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
-    [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
+    [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
     [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://installed"]];
     [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
     return standard;
 }
 
 - (void) loadData {
 _trace();
-    if (Role_ == nil) {
-        [window_ setUserInteractionEnabled:YES];
-        [self showSettings];
-        return;
-    } else {
-        if ([emulated_ modalViewController] != nil)
-            [emulated_ dismissModalViewControllerAnimated:YES];
-        [window_ setUserInteractionEnabled:NO];
-    }
+    if ([emulated_ modalViewController] != nil)
+        [emulated_ dismissModalViewControllerAnimated:YES];
+    [window_ setUserInteractionEnabled:NO];
 
     [self reloadDataWithInvocation:nil];
     [self refreshIfPossible];
@@ -9788,7 +9769,7 @@ _trace();
     [self disemulate];
 
     int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
-    NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
+    NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
     int standardIndex = 0;
     NSArray *standard = [self defaultStartPages];
 
@@ -9800,8 +9781,8 @@ _trace();
     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))
+        // XXX: Is 30 minutes the optimal time here?
+        if (interval <= -(30*60))
             valid = NO;
     }
 
@@ -9837,7 +9818,7 @@ _trace();
         for (unsigned int nav = 0; nav < [stack count]; nav++) {
             NSString *addr = [stack objectAtIndex:nav];
             NSURL *url = [NSURL URLWithString:addr];
-            CyteViewController *page = [self pageForURL:url forExternal:NO];
+            CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
             if (page != nil)
                 [current addObject:page];
         }
@@ -9892,14 +9873,6 @@ id Dealloc_(id self, SEL selector) {
     return object;
 }*/
 
-Class $WebDefaultUIKitDelegate;
-
-MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
-    if (delegate == nil && $WebDefaultUIKitDelegate != nil)
-        delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
-    return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
-}
-
 static NSSet *MobilizedFiles_;
 
 static NSURL *MobilizeURL(NSURL *url) {
@@ -9941,11 +9914,10 @@ MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferen
 Class $NSURLConnection;
 
 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]);
+    NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
 
     NSURL *url([copy URL]);
 
-    NSString *href([url absoluteString]);
     NSString *host([url host]);
     NSString *scheme([[url scheme] lowercaseString]);
 
@@ -9958,9 +9930,9 @@ MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest
 
         if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
             if ([control isEqualToString:@"max-age=0"])
-                if ([CachedURLs_ containsObject:href]) {
+                if ([CachedURLs_ containsObject:url]) {
 #if !ForRelease
-                    NSLog(@"~~~: %@", href);
+                    NSLog(@"~~~: %@", url);
 #endif
 
                     [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
@@ -9975,6 +9947,24 @@ MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest
     } return self;
 }
 
+Class $WAKWindow;
+
+static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
+    CGSize size([[UIScreen mainScreen] bounds].size);
+    /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
+        if ([$WAKWindow hasLandscapeOrientation])
+            std::swap(size.width, size.height);*/
+    return size;
+}
+
+Class $NSUserDefaults;
+
+MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
+    if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
+        return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
+    return _NSUserDefaults$objectForKey$(self, _cmd, key);
+}
+
 int main(int argc, char *argv[]) {
     NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
 
@@ -9982,12 +9972,6 @@ int main(int argc, char *argv[]) {
 
     UpdateExternalStatus(0);
 
-    if (Class $UIDevice = objc_getClass("UIDevice")) {
-        UIDevice *device([$UIDevice currentDevice]);
-        IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
-    } else
-        IsWildcat_ = false;
-
     UIScreen *screen([UIScreen mainScreen]);
     if ([screen respondsToSelector:@selector(scale)])
         ScreenScale_ = [screen scale];
@@ -9995,18 +9979,14 @@ int main(int argc, char *argv[]) {
         ScreenScale_ = 1;
 
     UIDevice *device([UIDevice currentDevice]);
-    if (![device respondsToSelector:@selector(userInterfaceIdiom)])
-        Idiom_ = @"iphone";
-    else {
+    if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
         UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
-        if (idiom == UIUserInterfaceIdiomPhone)
-            Idiom_ = @"iphone";
-        else if (idiom == UIUserInterfaceIdiomPad)
-            Idiom_ = @"ipad";
-        else
-            NSLog(@"unknown UIUserInterfaceIdiom!");
+        if (idiom == UIUserInterfaceIdiomPad)
+            IsWildcat_ = true;
     }
 
+    Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
+
     Pcre pattern("^([0-9]+\\.[0-9]+)");
 
     if (pattern([device systemVersion]))
@@ -10041,6 +10021,11 @@ int main(int argc, char *argv[]) {
     /* Library Hacks {{{ */
     class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
 
+    $WAKWindow = objc_getClass("WAKWindow");
+    if ($WAKWindow != NULL)
+        if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
+            method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
+
     $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
 
     Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
@@ -10055,19 +10040,19 @@ int main(int argc, char *argv[]) {
         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) {
-        _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
-        method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
-    }
-
     $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$));
     }
+
+    $NSUserDefaults = objc_getClass("NSUserDefaults");
+    Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
+    if (NSUserDefaults$objectForKey$ != NULL) {
+        _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
+        method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
+    }
     /* }}} */
     /* Set Locale {{{ */
     Locale_ = CFLocaleCopyCurrent();
@@ -10130,6 +10115,11 @@ int main(int argc, char *argv[]) {
     setuid(0);
     setgid(0);
 
+    if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
+        system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
+
+    Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
+
     /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
     alloc_ = alloc->method_imp;
     alloc->method_imp = (IMP) &Alloc_;*/
@@ -10138,6 +10128,9 @@ int main(int argc, char *argv[]) {
     dealloc_ = dealloc->method_imp;
     dealloc->method_imp = (IMP) &Dealloc_;*/
 
+    void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
+    $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
+
     /* System Information {{{ */
     size_t size;
 
@@ -10169,30 +10162,23 @@ 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_ = [device uniqueIdentifier];
+    UniqueID_ = UniqueIdentifier(device);
 
-    CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
-    $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
-    CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
-
-    CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
-    $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
-    CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
-
-    if (mcc != NULL && mnc != NULL)
-        PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
-
-    if (mnc != NULL)
-        CFRelease(mnc);
-    if (mcc != NULL)
-        CFRelease(mcc);
-
-    if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
-        Build_ = [system objectForKey:@"ProductBuildVersion"];
     if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
         Product_ = [info objectForKey:@"SafariProductVersion"];
         Safari_ = [info objectForKey:@"CFBundleVersion"];
     }
+
+    NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
+
+    if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
+        agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
+    if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
+        agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
+    if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
+        agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
+
+    UserAgent_ = agent;
     /* }}} */
     /* Load Database {{{ */
     _trace();
@@ -10214,15 +10200,8 @@ int main(int argc, char *argv[]) {
         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"];
@@ -10243,13 +10222,6 @@ int main(int argc, char *argv[]) {
         [Metadata_ setObject:Version_ forKey:@"Version"];
     }
 
-    @synchronized (HostConfig_) {
-        if (CydiaSource_ == nil) {
-            CydiaSource_ = @"apt.saurik.com";
-            [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
-        }
-    }
-
     if ([Version_ unsignedIntValue] == 0) {
         CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
         CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
@@ -10263,6 +10235,16 @@ int main(int argc, char *argv[]) {
 
         Changed_ = true;
     }
+
+    _H<NSMutableArray> broken([NSMutableArray array]);
+    for (NSString *key in (id) Sources_)
+        if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
+            [broken addObject:key];
+    if ([broken count] != 0) {
+        for (NSString *key in (id) broken)
+            [Sources_ removeObjectForKey:key];
+        Changed_ = true;
+    } broken = nil;
     /* }}} */
 
     CydiaWriteSources();
@@ -10302,11 +10284,7 @@ int main(int argc, char *argv[]) {
 
     int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
 
-    if (access("/tmp/.cydia.fw", F_OK) == 0) {
-        unlink("/tmp/.cydia.fw");
-        goto firmware;
-    } else if (access("/User", F_OK) != 0 || version < 4) {
-      firmware:
+    if (access("/User", F_OK) != 0 || version != 6) {
         _trace();
         system("/usr/libexec/cydia/firmware.sh");
         _trace();
@@ -10344,6 +10322,7 @@ int main(int argc, char *argv[]) {
     Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
     Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
     Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
+    Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
     Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
     White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
     Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
@@ -10355,14 +10334,18 @@ int main(int argc, char *argv[]) {
     RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
     /* }}}*/
     /* UIKit Configuration {{{ */
-    void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
-    if ($GSFontSetUseLegacyFontMetrics != NULL)
-        $GSFontSetUseLegacyFontMetrics(YES);
-
     // XXX: I have a feeling this was important
     //UIKeyboardDisableAutomaticAppearance();
     /* }}} */
 
+    $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
+
+    const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
+    BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
+    bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
+
+    PulseInterval_ = fast ? 50000 : 500000;
+
     Colon_ = UCLocalize("COLON_DELIMITED");
     Elision_ = UCLocalize("ELISION");
     Error_ = UCLocalize("ERROR");