]> git.saurik.com Git - cydia.git/blobdiff - UICaboodle/BrowserView.mm
Merge commit 'f64f9f6255e43c48ba2b8e5cea6a5b23e5d14e26' into tab-backup
[cydia.git] / UICaboodle / BrowserView.mm
index caa2ba28e4e58da653ee3cdcdf60a69074bf9743..2abc02ecc607b3c968bbf2c656260fb490b10b70 100644 (file)
@@ -1,30 +1,57 @@
+#include <UIKit/UIKit.h>
+#include "iPhonePrivate.h"
+
+#include "UCPlatform.h"
+
 #include <UICaboodle/BrowserView.h>
 #include <UICaboodle/UCLocalize.h>
 
-#import <QuartzCore/CALayer.h>
+//#include <QuartzCore/CALayer.h>
 // XXX: fix the minimum requirement
 extern NSString * const kCAFilterNearest;
 
 #include <WebCore/WebCoreThread.h>
-#include <WebKit/WebPreferences-WebPrivate.h>
+
+#include <WebKit/WebPolicyDelegate.h>
+#include <WebKit/WebPreferences.h>
+
+#include <WebKit/DOMCSSPrimitiveValue.h>
+#include <WebKit/DOMCSSStyleDeclaration.h>
+#include <WebKit/DOMDocument.h>
+#include <WebKit/DOMHTMLBodyElement.h>
+#include <WebKit/DOMRGBColor.h>
+
+//#include <WebCore/Page.h>
+//#include <WebCore/Settings.h>
 
 #include "substrate.h"
 
 #define ForSaurik 0
 
-static bool Wildcat_;
+template <typename Type_>
+static inline void CYRelease(Type_ &value) {
+    if (value != nil) {
+        [value release];
+        value = nil;
+    }
+}
 
-static CFArrayRef (*$GSSystemCopyCapability)(CFStringRef);
-static CFArrayRef (*$GSSystemGetCapability)(CFStringRef);
-static Class $UIFormAssistant;
-static Class $UIWebBrowserView;
+float CYScrollViewDecelerationRateNormal;
 
-@interface NSString (UIKit)
-- (NSString *) stringByAddingPercentEscapes;
+@interface WebView (Apple)
+- (void) _setLayoutInterval:(float)interval;
+@end
+
+@interface WebPreferences (Apple)
++ (void) _setInitialDefaultTextEncodingToSystemEncoding;
+- (void) _setLayoutInterval:(NSInteger)interval;
+- (void) setOfflineWebApplicationCacheEnabled:(BOOL)enabled;
 @end
 
 /* Indirect Delegate {{{ */
-@interface IndirectDelegate : NSObject {
+@interface IndirectDelegate : NSObject <
+    HookProtocol
+> {
     _transient volatile id delegate_;
 }
 
@@ -43,50 +70,9 @@ static Class $UIWebBrowserView;
     return self;
 }
 
-- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
-    if (delegate_ != nil)
-        return [delegate_ webView:sender didClearWindowObject:window forFrame:frame];
-}
-
-- (void) webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame {
-    if (delegate_ != nil)
-        return [delegate_ webView:sender didCommitLoadForFrame:frame];
-}
-
-- (void) webView:(WebView *)sender didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
-    if (delegate_ != nil)
-        return [delegate_ webView:sender didFailLoadWithError:error forFrame:frame];
-}
-
-- (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
-    if (delegate_ != nil)
-        return [delegate_ webView:sender didFailProvisionalLoadWithError:error forFrame:frame];
-}
-
-- (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
-    if (delegate_ != nil)
-        return [delegate_ webView:sender didFinishLoadForFrame:frame];
-}
-
-- (void) webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
+- (void) didDismissModalViewController {
     if (delegate_ != nil)
-        return [delegate_ webView:sender didReceiveTitle:title forFrame:frame];
-}
-
-- (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
-    if (delegate_ != nil)
-        return [delegate_ webView:sender didStartProvisionalLoadForFrame:frame];
-}
-
-- (void) webView:(WebView *)sender resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
-    if (delegate_ != nil)
-        return [delegate_ webView:sender resource:identifier didReceiveAuthenticationChallenge:challenge fromDataSource:source];
-}
-
-- (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
-    if (delegate_ != nil)
-        return [delegate_ webView:sender resource:identifier willSendRequest:request redirectResponse:redirectResponse fromDataSource:source];
-    return nil;
+        return [delegate_ didDismissModalViewController];
 }
 
 - (IMP) methodForSelector:(SEL)sel {
@@ -124,17 +110,9 @@ static Class $UIWebBrowserView;
 @end
 /* }}} */
 
-@interface WebView (UICaboodle)
-- (void) setScriptDebugDelegate:(id)delegate;
-- (void) _setFormDelegate:(id)delegate;
-- (void) _setUIKitDelegate:(id)delegate;
-- (void) setWebMailDelegate:(id)delegate;
-- (void) _setLayoutInterval:(float)interval;
-@end
-
 @implementation WebScriptObject (UICaboodle)
 
-- (unsigned) count {
+- (NSUInteger) count {
     id length([self valueForKey:@"length"]);
     if ([length respondsToSelector:@selector(intValue)])
         return [length intValue];
@@ -148,905 +126,577 @@ static Class $UIWebBrowserView;
 
 @end
 
-#define ShowInternals 0
-#define LogBrowser 0
-
-#define lprintf(args...) fprintf(stderr, args)
-
-@implementation BrowserView
-
-#if ShowInternals
-#include "UICaboodle/UCInternal.h"
-#endif
-
-+ (void) _initialize {
-    [WebView enableWebThread];
-
-    WebPreferences *preferences([WebPreferences standardPreferences]);
-    [preferences setCacheModel:WebCacheModelDocumentBrowser];
-    [preferences setOfflineWebApplicationCacheEnabled:YES];
-
-    [WebPreferences _setInitialDefaultTextEncodingToSystemEncoding];
-
-    $GSSystemCopyCapability = reinterpret_cast<CFArrayRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemCopyCapability"));
-    $GSSystemGetCapability = reinterpret_cast<CFArrayRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemGetCapability"));
-    $UIFormAssistant = objc_getClass("UIFormAssistant");
+// CYWebPolicyDecision* {{{
+enum CYWebPolicyDecision {
+    CYWebPolicyDecisionUnknown,
+    CYWebPolicyDecisionDownload,
+    CYWebPolicyDecisionIgnore,
+    CYWebPolicyDecisionUse,
+};
 
-    $UIWebBrowserView = objc_getClass("UIWebBrowserView");
-    if ($UIWebBrowserView == nil) {
-        Wildcat_ = false;
-        $UIWebBrowserView = objc_getClass("UIWebDocumentView");
-    } else {
-        Wildcat_ = true;
-    }
+@interface CYWebPolicyDecisionMediator : NSObject <
+    WebPolicyDecisionListener
+> {
+    id<WebPolicyDecisionListener> listener_;
+    CYWebPolicyDecision decision_;
 }
 
-- (void) dealloc {
-#if LogBrowser
-    NSLog(@"[BrowserView dealloc]");
-#endif
-
-    if (challenge_ != nil)
-        [challenge_ release];
-
-    WebThreadLock();
-
-    WebView *webview = [document_ webView];
-    [webview setFrameLoadDelegate:nil];
-    [webview setResourceLoadDelegate:nil];
-    [webview setUIDelegate:nil];
-    [webview setScriptDebugDelegate:nil];
-    [webview setPolicyDelegate:nil];
-
-    /* XXX: these are set by UIWebDocumentView
-    [webview setDownloadDelegate:nil];
-    [webview _setFormDelegate:nil];
-    [webview _setUIKitDelegate:nil];
-    [webview setEditingDelegate:nil];*/
-
-    /* XXX: no one sets this, ever
-    [webview setWebMailDelegate:nil];*/
-
-    [document_ setDelegate:nil];
-    [document_ setGestureDelegate:nil];
-
-    if ([document_ respondsToSelector:@selector(setFormEditingDelegate:)])
-        [document_ setFormEditingDelegate:nil];
-
-    [document_ setInteractionDelegate:nil];
+- (id) initWithListener:(id<WebPolicyDecisionListener>)listener;
 
-    [indirect_ setDelegate:nil];
-
-    //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
-
-    [webview close];
-
-#if RecycleWebViews
-    [document_ removeFromSuperview];
-    [Documents_ addObject:[document_ autorelease]];
-#else
-    [document_ release];
-#endif
+- (CYWebPolicyDecision) decision;
+- (bool) decided;
+- (bool) decide;
 
-    [indirect_ release];
-
-    WebThreadUnlock();
-
-    [scroller_ setDelegate:nil];
-
-    if (button_ != nil)
-        [button_ release];
-    if (style_ != nil)
-        [style_ release];
-    if (function_ != nil)
-        [function_ release];
-    if (finish_ != nil)
-        [finish_ release];
-    if (closer_ != nil)
-        [closer_ release];
-    if (special_ != nil)
-        [special_ release];
+@end
 
-    [scroller_ release];
-    [indicator_ release];
-    if (confirm_ != nil)
-        [confirm_ release];
-    if (sensitive_ != nil)
-        [sensitive_ release];
-    if (title_ != nil)
-        [title_ release];
-    [super dealloc];
-}
+@implementation CYWebPolicyDecisionMediator
 
-- (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
-    [self loadRequest:[NSURLRequest
-        requestWithURL:url
-        cachePolicy:policy
-        timeoutInterval:120.0
-    ]];
+- (id) initWithListener:(id<WebPolicyDecisionListener>)listener {
+    if ((self = [super init]) != nil) {
+        listener_ = listener;
+    } return self;
 }
 
-- (void) loadURL:(NSURL *)url {
-    [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
+- (CYWebPolicyDecision) decision {
+    return decision_;
 }
 
-- (void) loadRequest:(NSURLRequest *)request {
-    pushed_ = true;
-    error_ = false;
-
-    WebThreadLock();
-    [document_ loadRequest:request];
-    WebThreadUnlock();
+- (bool) decided {
+    return decision_ != CYWebPolicyDecisionUnknown;
 }
 
-- (void) reloadURL {
-    if (request_ == nil)
-        return;
-
-    if ([request_ HTTPBody] == nil && [request_ HTTPBodyStream] == nil)
-        [self loadRequest:request_];
-    else {
-        UIActionSheet *sheet = [[[UIActionSheet alloc]
-            initWithTitle:UCLocalize("RESUBMIT_FORM")
-            buttons:[NSArray arrayWithObjects:UCLocalize("CANCEL"), UCLocalize("SUBMIT"), nil]
-            defaultButtonIndex:0
-            delegate:self
-            context:@"submit"
-        ] autorelease];
-
-        [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
+- (bool) decide {
+    switch (decision_) {
+        case CYWebPolicyDecisionUnknown:
+        default:
+            NSLog(@"CYWebPolicyDecisionUnknown");
+            return false;
 
-        [sheet setNumberOfRows:1];
-        [sheet popupAlertAnimated:YES];
+        case CYWebPolicyDecisionDownload: [listener_ download]; break;
+        case CYWebPolicyDecisionIgnore: [listener_ ignore]; break;
+        case CYWebPolicyDecisionUse: [listener_ use]; break;
     }
-}
 
-- (WebView *) webView {
-    return [document_ webView];
+    return true;
 }
 
-- (UIWebDocumentView *) documentView {
-    return document_;
+- (void) download {
+    decision_ = CYWebPolicyDecisionDownload;
 }
 
-/* XXX: WebThreadLock? */
-- (void) _fixScroller:(CGRect)bounds {
-    float extra;
-
-    if (!editing_ || $UIFormAssistant == nil)
-        extra = 0;
-    else {
-        UIFormAssistant *assistant([$UIFormAssistant sharedFormAssistant]);
-        CGRect peripheral([assistant peripheralFrame]);
-#if LogBrowser
-        NSLog(@"per:%f", peripheral.size.height);
-#endif
-        extra = peripheral.size.height;
-    }
-
-    CGRect subrect([scroller_ frame]);
-    subrect.size.height -= extra;
-
-    if ([scroller_ respondsToSelector:@selector(setScrollerIndicatorSubrect:)])
-        [scroller_ setScrollerIndicatorSubrect:subrect];
-
-    [document_ setValue:[NSValue valueWithSize:NSMakeSize(subrect.size.width, subrect.size.height)] forGestureAttribute:UIGestureAttributeVisibleSize];
-
-    CGSize size(size_);
-    size.height += extra;
-    [scroller_ setContentSize:size];
-
-    if ([scroller_ respondsToSelector:@selector(releaseRubberBandIfNecessary)])
-        [scroller_ releaseRubberBandIfNecessary];
-}
-
-- (void) fixScroller {
-    CGRect bounds([document_ documentBounds]);
-#if TrackResize
-    NSLog(@"_fs:(%f,%f+%f,%f)", bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height);
-#endif
-    [self _fixScroller:bounds];
+- (void) ignore {
+    decision_ = CYWebPolicyDecisionIgnore;
 }
 
-- (void) view:(UIView *)sender didSetFrame:(CGRect)frame {
-    size_ = frame.size;
-#if TrackResize
-    NSLog(@"dsf:(%f,%f+%f,%f)", frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
-#endif
-    [self _fixScroller:frame];
+- (void) use {
+    decision_ = CYWebPolicyDecisionUse;
 }
 
-- (void) view:(UIView *)sender didSetFrame:(CGRect)frame oldFrame:(CGRect)old {
-    [self view:sender didSetFrame:frame];
-}
+@end
+// }}}
 
-- (void) pushPage:(RVPage *)page {
-    [page setDelegate:delegate_];
-    [self setBackButtonTitle:title_];
-    [book_ pushPage:page];
-}
+@implementation CYWebView : UIWebView
 
-- (void) _pushPage {
-    if (pushed_)
-        return;
-    // WTR: [self autorelease];
-    pushed_ = true;
-    [book_ pushPage:self];
+- (id) initWithFrame:(CGRect)frame {
+    if ((self = [super initWithFrame:frame]) != nil) {
+    } return self;
 }
 
-- (void) swapPage:(RVPage *)page {
-    [page setDelegate:delegate_];
-    if (pushed_)
-        [book_ swapPage:page];
-    else
-        [book_ pushPage:page];
+- (void) dealloc {
+    [super dealloc];
 }
 
-- (BOOL) getSpecial:(NSURL *)url swap:(BOOL)swap {
-#if LogBrowser
-    NSLog(@"getSpecial:%@", url);
-#endif
-
-    if (RVPage *page = [delegate_ pageForURL:url hasTag:NULL]) {
-        if (swap)
-            [self swapPage:page];
-        else
-            [self pushPage:page];
-
-        return true;
-    } else
-        return false;
+- (id<CYWebViewDelegate>) delegate {
+    return (id<CYWebViewDelegate>) [super delegate];
 }
 
-- (void) formAssistant:(id)sender didBeginEditingFormNode:(id)node {
-}
+/*- (WebView *) webView:(WebView *)view createWebViewWithRequest:(NSURLRequest *)request {
+    id<CYWebViewDelegate> delegate([self delegate]);
+    WebView *created(nil);
+    if (created == nil && [delegate respondsToSelector:@selector(webView:createWebViewWithRequest:)])
+        created = [delegate webView:view createWebViewWithRequest:request];
+    if (created == nil && [UIWebView instancesRespondToSelector:@selector(webView:createWebViewWithRequest:)])
+        created = [super webView:view createWebViewWithRequest:request];
+    return created;
+}*/
 
-- (void) formAssistant:(id)sender didEndEditingFormNode:(id)node {
-    [self fixScroller];
+// webView:decidePolicyForNavigationAction:request:frame:decisionListener: (2.0+) {{{
+- (void) webView:(WebView *)view decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
+    id<CYWebViewDelegate> delegate([self delegate]);
+    CYWebPolicyDecisionMediator *mediator([[[CYWebPolicyDecisionMediator alloc] initWithListener:listener] autorelease]);
+    if (![mediator decided] && [delegate respondsToSelector:@selector(webView:decidePolicyForNavigationAction:request:frame:decisionListener:)])
+        [delegate webView:view decidePolicyForNavigationAction:action request:request frame:frame decisionListener:mediator];
+    if (![mediator decided] && [UIWebView instancesRespondToSelector:@selector(webView:decidePolicyForNavigationAction:request:frame:decisionListener:)])
+        [super webView:view decidePolicyForNavigationAction:action request:request frame:frame decisionListener:mediator];
+    [mediator decide];
+}
+// }}}
+// webView:decidePolicyForNewWindowAction:request:newFrameName:decisionListener: (3.0+) {{{
+static void $UIWebViewWebViewDelegate$webView$decidePolicyForNewWindowAction$request$newFrameName$decisionListener$(UIWebViewWebViewDelegate *self, SEL sel, WebView *view, NSDictionary *action, NSURLRequest *request, NSString *frame, id<WebPolicyDecisionListener> listener) {
+    UIWebView *uiWebView(MSHookIvar<UIWebView *>(self, "uiWebView"));
+    if ([uiWebView respondsToSelector:@selector(webView:decidePolicyForNewWindowAction:request:newFrameName:decisionListener:)])
+        [uiWebView webView:view decidePolicyForNewWindowAction:action request:request newFrameName:frame decisionListener:listener];
+}
+
+- (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
+    id<CYWebViewDelegate> delegate([self delegate]);
+    CYWebPolicyDecisionMediator *mediator([[[CYWebPolicyDecisionMediator alloc] initWithListener:listener] autorelease]);
+    if (![mediator decided] && [delegate respondsToSelector:@selector(webView:decidePolicyForNewWindowAction:request:newFrameName:decisionListener:)])
+        [delegate webView:view decidePolicyForNewWindowAction:action request:request newFrameName:frame decisionListener:mediator];
+    if (![mediator decided] && [UIWebView instancesRespondToSelector:@selector(webView:decidePolicyForNewWindowAction:request:newFrameName:decisionListener:)])
+        [super webView:view decidePolicyForNewWindowAction:action request:request newFrameName:frame decisionListener:mediator];
+    [mediator decide];
+}
+// }}}
+// webView:didClearWindowObject:forFrame: (3.2+) {{{
+static void $UIWebViewWebViewDelegate$webView$didClearWindowObject$forFrame$(UIWebViewWebViewDelegate *self, SEL sel, WebView *view, WebScriptObject *window, WebFrame *frame) {
+    UIWebView *uiWebView(MSHookIvar<UIWebView *>(self, "uiWebView"));
+    if ([uiWebView respondsToSelector:@selector(webView:didClearWindowObject:forFrame:)])
+        [uiWebView webView:view didClearWindowObject:window forFrame:frame];
+}
+
+- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
+    id<CYWebViewDelegate> delegate([self delegate]);
+    if ([delegate respondsToSelector:@selector(webView:didClearWindowObject:forFrame:)])
+        [delegate webView:view didClearWindowObject:window forFrame:frame];
+    if ([UIWebView instancesRespondToSelector:@selector(webView:didClearWindowObject:forFrame:)])
+        [super webView:view didClearWindowObject:window forFrame:frame];
+}
+// }}}
+// webView:didFailLoadWithError:forFrame: (2.0+) {{{
+- (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
+    id<CYWebViewDelegate> delegate([self delegate]);
+    if ([delegate respondsToSelector:@selector(webView:didFailLoadWithError:forFrame:)])
+        [delegate webView:view didFailLoadWithError:error forFrame:frame];
+    if ([UIWebView instancesRespondToSelector:@selector(webView:didFailLoadWithError:forFrame:)])
+        [super webView:view didFailLoadWithError:error forFrame:frame];
+}
+// }}}
+// webView:didFailProvisionalLoadWithError:forFrame: (2.0+) {{{
+- (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
+    id<CYWebViewDelegate> delegate([self delegate]);
+    if ([delegate respondsToSelector:@selector(webView:didFailProvisionalLoadWithError:forFrame:)])
+        [delegate webView:view didFailProvisionalLoadWithError:error forFrame:frame];
+    if ([UIWebView instancesRespondToSelector:@selector(webView:didFailProvisionalLoadWithError:forFrame:)])
+        [super webView:view didFailProvisionalLoadWithError:error forFrame:frame];
+}
+// }}}
+// webView:didFinishLoadForFrame: (2.0+) {{{
+- (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
+    id<CYWebViewDelegate> delegate([self delegate]);
+    if ([delegate respondsToSelector:@selector(webView:didFinishLoadForFrame:)])
+        [delegate webView:view didFinishLoadForFrame:frame];
+    if ([UIWebView instancesRespondToSelector:@selector(webView:didFinishLoadForFrame:)])
+        [super webView:view didFinishLoadForFrame:frame];
+}
+// }}}
+// webView:didReceiveTitle:forFrame: (3.2+) {{{
+static void $UIWebViewWebViewDelegate$webView$didReceiveTitle$forFrame$(UIWebViewWebViewDelegate *self, SEL sel, WebView *view, NSString *title, WebFrame *frame) {
+    UIWebView *uiWebView(MSHookIvar<UIWebView *>(self, "uiWebView"));
+    if ([uiWebView respondsToSelector:@selector(webView:didReceiveTitle:forFrame:)])
+        [uiWebView webView:view didReceiveTitle:title forFrame:frame];
+}
+
+- (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
+    id<CYWebViewDelegate> delegate([self delegate]);
+    if ([delegate respondsToSelector:@selector(webView:didReceiveTitle:forFrame:)])
+        [delegate webView:view didReceiveTitle:title forFrame:frame];
+    if ([UIWebView instancesRespondToSelector:@selector(webView:didReceiveTitle:forFrame:)])
+        [super webView:view didReceiveTitle:title forFrame:frame];
+}
+// }}}
+// webView:didStartProvisionalLoadForFrame: (2.0+) {{{
+- (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
+    id<CYWebViewDelegate> delegate([self delegate]);
+    if ([delegate respondsToSelector:@selector(webView:didStartProvisionalLoadForFrame:)])
+        [delegate webView:view didStartProvisionalLoadForFrame:frame];
+    if ([UIWebView instancesRespondToSelector:@selector(webView:didStartProvisionalLoadForFrame:)])
+        [super webView:view didStartProvisionalLoadForFrame:frame];
+}
+// }}}
+// webView:resource:willSendRequest:redirectResponse:fromDataSource: (3.2+) {{{
+static NSURLRequest *$UIWebViewWebViewDelegate$webView$resource$willSendRequest$redirectResponse$fromDataSource$(UIWebViewWebViewDelegate *self, SEL sel, WebView *view, id identifier, NSURLRequest *request, NSURLResponse *response, WebDataSource *source) {
+    UIWebView *uiWebView(MSHookIvar<UIWebView *>(self, "uiWebView"));
+    if ([uiWebView respondsToSelector:@selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:)])
+        request = [uiWebView webView:view resource:identifier willSendRequest:request redirectResponse:response fromDataSource:source];
+    return request;
 }
 
-- (void) webViewShow:(WebView *)sender {
-    /* XXX: this is where I cry myself to sleep */
+- (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
+    id<CYWebViewDelegate> delegate([self delegate]);
+    if ([UIWebView instancesRespondToSelector:@selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:)])
+        request = [super webView:view resource:identifier willSendRequest:request redirectResponse:response fromDataSource:source];
+    if ([delegate respondsToSelector:@selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:)])
+        request = [delegate webView:view resource:identifier willSendRequest:request redirectResponse:response fromDataSource:source];
+    return request;
 }
-
-- (bool) _allowJavaScriptPanel {
-    return true;
+// }}}
+// webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame: (2.1+) {{{
+- (void) webView:(WebView *)view runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
+    id<CYWebViewDelegate> delegate([self delegate]);
+    if ([UIWebView instancesRespondToSelector:@selector(webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:)])
+        if (
+            ![delegate respondsToSelector:@selector(webView:shouldRunJavaScriptAlertPanelWithMessage:initiatedByFrame:)] ||
+            [delegate webView:view shouldRunJavaScriptAlertPanelWithMessage:message initiatedByFrame:frame]
+        )
+            [super webView:view runJavaScriptAlertPanelWithMessage:message initiatedByFrame:frame];
+}
+// }}}
+// webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame: (2.1+) {{{
+- (BOOL) webView:(WebView *)view runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
+    id<CYWebViewDelegate> delegate([self delegate]);
+    if ([UIWebView instancesRespondToSelector:@selector(webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:)])
+        if (
+            ![delegate respondsToSelector:@selector(webView:shouldRunJavaScriptConfirmPanelWithMessage:initiatedByFrame:)] ||
+            [delegate webView:view shouldRunJavaScriptConfirmPanelWithMessage:message initiatedByFrame:frame]
+        )
+            return [super webView:view runJavaScriptConfirmPanelWithMessage:message initiatedByFrame:frame];
+    return NO;
+}
+// }}}
+// webView:runJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame: (2.1+) {{{
+- (NSString *) webView:(WebView *)view runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
+    id<CYWebViewDelegate> delegate([self delegate]);
+    if ([UIWebView instancesRespondToSelector:@selector(webView:runJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame:)])
+        if (
+            ![delegate respondsToSelector:@selector(webView:shouldRunJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame:)] ||
+            [delegate webView:view shouldRunJavaScriptTextInputPanelWithPrompt:prompt defaultText:text initiatedByFrame:frame]
+        )
+            return [super webView:view runJavaScriptTextInputPanelWithPrompt:prompt defaultText:text initiatedByFrame:frame];
+    return nil;
 }
-
-- (bool) allowSensitiveRequests {
-    return [self _allowJavaScriptPanel];
+// }}}
+// webViewClose: (3.2+) {{{
+static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *self, SEL sel, WebView *view) {
+    UIWebView *uiWebView(MSHookIvar<UIWebView *>(self, "uiWebView"));
+    if ([uiWebView respondsToSelector:@selector(webViewClose:)])
+        [uiWebView webViewClose:view];
 }
 
-- (void) _promptForSensitive:(NSMutableArray *)array {
-    NSString *name([array objectAtIndex:0]);
-
-    UIActionSheet *sheet = [[[UIActionSheet alloc]
-        initWithTitle:nil
-        buttons:[NSArray arrayWithObjects:UCLocalize("YES"), UCLocalize("NO"), nil]
-        defaultButtonIndex:0
-        delegate:indirect_
-        context:@"sensitive"
-    ] autorelease];
-
-    [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
-
-    NSString *host(@"XXX");
-
-    [sheet setNumberOfRows:1];
-    [sheet setBodyText:[NSString stringWithFormat:@"The website at %@ is requesting your phone's %@. This is almost certainly for product licensing purposes. Will you allow this?", host, name]];
-    [sheet popupAlertAnimated:YES];
-
-    NSRunLoop *loop([NSRunLoop currentRunLoop]);
-    NSDate *future([NSDate distantFuture]);
-
-    while (sensitive_ == nil && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
-
-    NSNumber *sensitive([sensitive_ autorelease]);
-    sensitive_ = nil;
-
-    [self autorelease];
-    [array replaceObjectAtIndex:0 withObject:sensitive];
+- (void) webViewClose:(WebView *)view {
+    id<CYWebViewDelegate> delegate([self delegate]);
+    if ([delegate respondsToSelector:@selector(webViewClose:)])
+        [delegate webViewClose:view];
+    if ([UIWebView instancesRespondToSelector:@selector(webViewClose:)])
+        [super webViewClose:view];
 }
+// }}}
 
-- (bool) promptForSensitive:(NSString *)name {
-    if (![self allowSensitiveRequests])
-        return false;
-
-    NSMutableArray *array([NSMutableArray arrayWithCapacity:1]);
-    [array addObject:name];
+- (void) _updateViewSettings {
+    [super _updateViewSettings];
 
-    [self performSelectorOnMainThread:@selector(_promptForSensitive:) withObject:array waitUntilDone:YES];
-    return [[array lastObject] boolValue];
+    id<CYWebViewDelegate> delegate([self delegate]);
+    if ([delegate respondsToSelector:@selector(webViewUpdateViewSettings:)])
+        [delegate webViewUpdateViewSettings:self];
 }
 
-- (void) webView:(WebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
-    if (![self _allowJavaScriptPanel])
-        return;
-    [self retain];
-
-    UIActionSheet *sheet = [[[UIActionSheet alloc]
-        initWithTitle:nil
-        buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
-        defaultButtonIndex:0
-        delegate:self
-        context:@"alert"
-    ] autorelease];
-
-    [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
-
-    [sheet setBodyText:message];
-    [sheet popupAlertAnimated:YES];
++ (void) initialize {
+    if (Class $UIWebViewWebViewDelegate = objc_getClass("UIWebViewWebViewDelegate")) {
+        class_addMethod($UIWebViewWebViewDelegate, @selector(webView:decidePolicyForNewWindowAction:request:newFrameName:decisionListener:), (IMP) &$UIWebViewWebViewDelegate$webView$decidePolicyForNewWindowAction$request$newFrameName$decisionListener$, "v28@0:4@8@12@16@20@24");
+        class_addMethod($UIWebViewWebViewDelegate, @selector(webView:didClearWindowObject:forFrame:), (IMP) &$UIWebViewWebViewDelegate$webView$didClearWindowObject$forFrame$, "v20@0:4@8@12@16");
+        class_addMethod($UIWebViewWebViewDelegate, @selector(webView:didReceiveTitle:forFrame:), (IMP) &$UIWebViewWebViewDelegate$webView$didReceiveTitle$forFrame$, "v20@0:4@8@12@16");
+        class_addMethod($UIWebViewWebViewDelegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:), (IMP) &$UIWebViewWebViewDelegate$webView$resource$willSendRequest$redirectResponse$fromDataSource$, "@28@0:4@8@12@16@20@24");
+        class_addMethod($UIWebViewWebViewDelegate, @selector(webViewClose:), (IMP) &$UIWebViewWebViewDelegate$webViewClose$, "v12@0:4@8");
+    }
 }
 
-- (BOOL) webView:(WebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
-    if (![self _allowJavaScriptPanel])
-        return NO;
-    [self retain];
-
-    UIActionSheet *sheet = [[[UIActionSheet alloc]
-        initWithTitle:nil
-        buttons:[NSArray arrayWithObjects:UCLocalize("OK"), UCLocalize("CANCEL"), nil]
-        defaultButtonIndex:0
-        delegate:indirect_
-        context:@"confirm"
-    ] autorelease];
-
-    [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
-
-    [sheet setNumberOfRows:1];
-    [sheet setBodyText:message];
-    [sheet popupAlertAnimated:YES];
+@end
 
-    NSRunLoop *loop([NSRunLoop currentRunLoop]);
-    NSDate *future([NSDate distantFuture]);
+#define ShowInternals 0
+#define LogBrowser 0
 
-    while (confirm_ == nil && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
+#define lprintf(args...) fprintf(stderr, args)
 
-    NSNumber *confirm([confirm_ autorelease]);
-    confirm_ = nil;
+@implementation BrowserController
 
-    [self autorelease];
-    return [confirm boolValue];
-}
+#if ShowInternals
+#include "UICaboodle/UCInternal.h"
+#endif
 
-- (void) setAutoPopup:(BOOL)popup {
-    popup_ = popup;
-}
++ (void) _initialize {
+    [WebPreferences _setInitialDefaultTextEncodingToSystemEncoding];
 
-- (void) setSpecial:(id)function {
-    if (special_ != nil)
-        [special_ autorelease];
-    special_ = function == nil ? nil : [function retain];
+    if (float *_UIScrollViewDecelerationRateNormal = reinterpret_cast<float *>(dlsym(RTLD_DEFAULT, "UIScrollViewDecelerationRateNormal")))
+        CYScrollViewDecelerationRateNormal = *_UIScrollViewDecelerationRateNormal;
+    else // XXX: this actually might be fast on some older systems: we should look into this
+        CYScrollViewDecelerationRateNormal = 0.998;
 }
 
-- (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
-    if (button_ != nil)
-        [button_ autorelease];
-    button_ = button == nil ? nil : [[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:button]]] retain];
+- (void) dealloc {
+#if LogBrowser
+    NSLog(@"[BrowserController dealloc]");
+#endif
 
-    if (style_ != nil)
-        [style_ autorelease];
-    style_ = style == nil ? nil : [style retain];
+    [webview_ setDelegate:nil];
 
-    if (function_ != nil)
-        [function_ autorelease];
-    function_ = function == nil ? nil : [function retain];
+    [indirect_ setDelegate:nil];
+    [indirect_ release];
 
-    [self reloadButtons];
-}
+    if (challenge_ != nil)
+        [challenge_ release];
 
-- (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
-    if (button_ != nil)
-        [button_ autorelease];
-    button_ = button == nil ? nil : [button retain];
+    if (request_ != nil)
+        [request_ release];
 
+    if (custom_ != nil)
+        [custom_ release];
     if (style_ != nil)
-        [style_ autorelease];
-    style_ = style == nil ? nil : [style retain];
+        [style_ release];
 
     if (function_ != nil)
-        [function_ autorelease];
-    function_ = function == nil ? nil : [function retain];
-
-    [self reloadButtons];
-}
-
-- (void) setFinishHook:(id)function {
-    if (finish_ != nil)
-        [finish_ autorelease];
-    finish_ = function == nil ? nil : [function retain];
-}
-
-- (void) setPopupHook:(id)function {
+        [function_ release];
     if (closer_ != nil)
-        [closer_ autorelease];
-    closer_ = function == nil ? nil : [function retain];
-}
-
-- (void) _openMailToURL:(NSURL *)url {
-    [UIApp openURL:url];// asPanel:YES];
-}
-
-- (void) webView:(WebView *)sender willBeginEditingFormElement:(id)element {
-    editing_ = true;
-}
-
-- (void) webView:(WebView *)sender didBeginEditingFormElement:(id)element {
-    [self fixScroller];
-}
+        [closer_ release];
 
-- (void) webViewDidEndEditingFormElements:(WebView *)sender {
-    editing_ = false;
-    [self fixScroller];
-}
+    if (title_ != nil)
+        [title_ release];
 
-- (void) webViewClose:(WebView *)sender {
-    [book_ close];
-}
+    if ([loading_ count] != 0)
+        [delegate_ releaseNetworkActivityIndicator];
+    [loading_ release];
 
-- (void) close {
-    [book_ close];
-}
+    [reloaditem_ release];
+    [loadingitem_ release];
 
-- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
-}
+    [indicator_ release];
 
-- (void) webView:(WebView *)sender unableToImplementPolicyWithError:(NSError *)error frame:(WebFrame *)frame {
-    NSLog(@"err:%@", error);
+    [super dealloc];
 }
 
-- (void) webView:(WebView *)sender decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
-#if LogBrowser
-    NSLog(@"nwa:%@", name);
-#endif
-
-    if (NSURL *url = [request URL]) {
-        if (name == nil) unknown: {
-            if (![self getSpecial:url swap:NO]) {
-                NSString *scheme([[url scheme] lowercaseString]);
-                if ([scheme isEqualToString:@"mailto"])
-                    [self _openMailToURL:url];
-                else goto use;
-            }
-        } else if ([name isEqualToString:@"_open"])
-            [delegate_ openURL:url];
-        else if ([name isEqualToString:@"_popup"]) {
-            NSString *scheme([[url scheme] lowercaseString]);
-            if ([scheme isEqualToString:@"mailto"])
-                [self _openMailToURL:url];
-            else {
-                RVBook *book([[[RVPopUpBook alloc] initWithFrame:[delegate_ popUpBounds]] autorelease]);
-                [book setHook:indirect_];
-
-                RVPage *page([delegate_ pageForURL:url hasTag:NULL]);
-                if (page == nil) {
-                    /* XXX: call createWebViewWithRequest instead? */
-
-                    [self setBackButtonTitle:title_];
-
-                    BrowserView *browser([[[class_ alloc] initWithBook:book] autorelease]);
-                    [browser loadURL:url];
-                    page = browser;
-                }
-
-                [book setDelegate:delegate_];
-                [page setDelegate:delegate_];
-
-                [book setPage:page];
-                [book_ pushBook:book];
-            }
-        } else goto unknown;
-
-        [listener ignore];
-    } else use:
-        [listener use];
+- (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
+    [self loadRequest:[NSURLRequest
+        requestWithURL:url
+        cachePolicy:policy
+        timeoutInterval:120.0
+    ]];
 }
 
-- (void) webView:(WebView *)sender decidePolicyForMIMEType:(NSString *)type request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
-    if ([WebView canShowMIMEType:type])
-        [listener use];
-    else {
-        // XXX: handle more mime types!
-        [listener ignore];
-
-        WebView *webview([document_ webView]);
-        if (frame == [webview mainFrame])
-            [UIApp openURL:[request URL]];
-    }
+- (void) loadURL:(NSURL *)url {
+    [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
 }
 
-- (void) webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
-    if (request == nil) ignore: {
-        [listener ignore];
-        return;
-    }
-
-    NSURL *url([request URL]);
-    NSString *host([url host]);
-
-    if (url == nil) use: {
-        if (!error_ && [frame parentFrame] == nil) {
-            if (request_ != nil)
-                [request_ autorelease];
-            request_ = [request retain];
-#if LogBrowser
-            NSLog(@"dpn:%@", request_);
-#endif
-        }
-
-        [listener use];
-
-        WebView *webview([document_ webView]);
-        if (frame == [webview mainFrame])
-            [self _pushPage];
-        return;
-    }
-#if LogBrowser
-    else NSLog(@"nav:%@:%@", url, [action description]);
-#endif
-
-    const NSArray *capability;
-
-    if ($GSSystemCopyCapability != NULL) {
-        capability = reinterpret_cast<const NSArray *>((*$GSSystemCopyCapability)(kGSDisplayIdentifiersCapability));
-        capability = [capability autorelease];
-    } else if ($GSSystemGetCapability != NULL) {
-        capability = reinterpret_cast<const NSArray *>((*$GSSystemGetCapability)(kGSDisplayIdentifiersCapability));
-    } else
-        capability = nil;
-
-    NSURL *open(nil);
-
-    if (capability != nil && (
-        [url isGoogleMapsURL] && [capability containsObject:@"com.apple.Maps"] && (open = [url mapsURL]) != nil||
-        [host hasSuffix:@"youtube.com"] && [capability containsObject:@"com.apple.youtube"] && (open = [url youTubeURL]) != nil ||
-        [url respondsToSelector:@selector(phobosURL)] && (open = [url phobosURL]) != nil
-    )) {
-        url = open;
-      open:
-        [UIApp openURL:url];
-        goto ignore;
-    }
-
-    int store(_not(int));
-    if (NSURL *itms = [url itmsURL:&store]) {
+- (void) loadRequest:(NSURLRequest *)request {
 #if LogBrowser
-        NSLog(@"itms#%@#%u#%@", url, store, itms);
+    NSLog(@"loadRequest:%@", request);
 #endif
 
-        if (capability != nil && (
-            store == 1 && [capability containsObject:@"com.apple.MobileStore"] ||
-            store == 2 && [capability containsObject:@"com.apple.AppStore"]
-        )) {
-            url = itms;
-            goto open;
-        }
-    }
-
-    NSString *scheme([[url scheme] lowercaseString]);
-
-    if ([scheme isEqualToString:@"tel"]) {
-        // XXX: intelligence
-        goto open;
-    }
-
-    if ([scheme isEqualToString:@"mailto"]) {
-        [self _openMailToURL:url];
-        goto ignore;
-    }
-
-    if ([self getSpecial:url swap:YES])
-        goto ignore;
-    else if ([WebView _canHandleRequest:request])
-        goto use;
-    else if ([url isSpringboardHandledURL])
-        goto open;
-    else
-        goto use;
-}
+    error_ = false;
 
-- (void) webView:(WebView *)sender setStatusText:(NSString *)text {
-    //lprintf("Status:%s\n", [text UTF8String]);
+    WebThreadLock();
+    [webview_ loadRequest:request];
+    WebThreadUnlock();
 }
 
-- (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
-    NSString *context([sheet context]);
-
-    if ([context isEqualToString:@"alert"]) {
-        [self autorelease];
-        [sheet dismiss];
-    } else if ([context isEqualToString:@"confirm"]) {
-        switch (button) {
-            case 1:
-                confirm_ = [NSNumber numberWithBool:YES];
-            break;
-
-            case 2:
-                confirm_ = [NSNumber numberWithBool:NO];
-            break;
-        }
-
-        [sheet dismiss];
-    } else if ([context isEqualToString:@"sensitive"]) {
-        switch (button) {
-            case 1:
-                sensitive_ = [NSNumber numberWithBool:YES];
-            break;
-
-            case 2:
-                sensitive_ = [NSNumber numberWithBool:NO];
-            break;
-        }
-
-        [sheet dismiss];
-    } else if ([context isEqualToString:@"challenge"]) {
-        id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
-
-        switch (button) {
-            case 1: {
-                NSString *username([[sheet textFieldAtIndex:0] text]);
-                NSString *password([[sheet textFieldAtIndex:1] text]);
-
-                NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
-
-                [sender useCredential:credential forAuthenticationChallenge:challenge_];
-            } break;
-
-            case 2:
-                [sender cancelAuthenticationChallenge:challenge_];
-            break;
-
-            _nodefault
-        }
-
-        [challenge_ release];
-        challenge_ = nil;
-
-        [sheet dismiss];
-    } else if ([context isEqualToString:@"submit"]) {
-        switch (button) {
-            case 1:
-            break;
-
-            case 2:
-                if (request_ != nil) {
-                    WebThreadLock();
-                    [document_ loadRequest:request_];
-                    WebThreadUnlock();
-                }
-            break;
+- (void) reloadURL {
+    if (request_ == nil)
+        return;
 
-            _nodefault
-        }
+    if ([request_ HTTPBody] == nil && [request_ HTTPBodyStream] == nil)
+        [self loadRequest:request_];
+    else {
+        UIAlertView *alert = [[[UIAlertView alloc]
+            initWithTitle:UCLocalize("RESUBMIT_FORM")
+            message:nil
+            delegate:self
+            cancelButtonTitle:UCLocalize("CANCEL")
+            otherButtonTitles:UCLocalize("SUBMIT"), nil
+        ] autorelease];
 
-        [sheet dismiss];
+        [alert setContext:@"submit"];
+        [alert show];
     }
 }
 
-- (void) webView:(WebView *)sender resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
-    challenge_ = [challenge retain];
-
-    NSURLProtectionSpace *space([challenge protectionSpace]);
-    NSString *realm([space realm]);
-    if (realm == nil)
-        realm = @"";
+- (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
+    if (custom_ != nil)
+        [custom_ autorelease];
+    if (button == nil)
+        custom_ = nil;
+    else
+        custom_ = [[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:button]]] retain];
 
-    UIActionSheet *sheet = [[[UIActionSheet alloc]
-        initWithTitle:realm
-        buttons:[NSArray arrayWithObjects:UCLocalize("LOGIN"), UCLocalize("CANCEL"), nil]
-        defaultButtonIndex:0
-        delegate:self
-        context:@"challenge"
-    ] autorelease];
+    if (style_ != nil)
+        [style_ autorelease];
+    if (style == nil)
+        style_ = nil;
+    else
+        style_ = [style retain];
 
-    [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
+    if (function_ != nil)
+        [function_ autorelease];
+    if (function == nil)
+        function_ = nil;
+    else
+        function_ = [function retain];
 
-    [sheet setNumberOfRows:1];
+    [self applyRightButton];
+}
 
-    [sheet addTextFieldWithValue:@"" label:UCLocalize("USERNAME")];
-    [sheet addTextFieldWithValue:@"" label:UCLocalize("PASSWORD")];
+- (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
+    if (custom_ != nil)
+        [custom_ autorelease];
+    if (button == nil)
+        custom_ = nil;
+    else
+        custom_ = [button retain];
 
-    UITextField *username([sheet textFieldAtIndex:0]); {
-        UITextInputTraits *traits([username textInputTraits]);
-        [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
-        [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
-        [traits setKeyboardType:UIKeyboardTypeASCIICapable];
-        [traits setReturnKeyType:UIReturnKeyNext];
-    }
+    if (style_ != nil)
+        [style_ autorelease];
+    if (style == nil)
+        style_ = nil;
+    else
+        style_ = [style retain];
 
-    UITextField *password([sheet textFieldAtIndex:1]); {
-        UITextInputTraits *traits([password textInputTraits]);
-        [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
-        [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
-        [traits setKeyboardType:UIKeyboardTypeASCIICapable];
-        // XXX: UIReturnKeyDone
-        [traits setReturnKeyType:UIReturnKeyNext];
-        [traits setSecureTextEntry:YES];
-    }
+    if (function_ != nil)
+        [function_ autorelease];
+    if (function == nil)
+        function_ = nil;
+    else
+        function_ = [function retain];
 
-    [sheet popupAlertAnimated:YES];
+    [self applyRightButton];
 }
 
-- (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
-    return request;
+- (void) setPopupHook:(id)function {
+    if (closer_ != nil)
+        [closer_ autorelease];
+    if (function == nil)
+        closer_ = nil;
+    else
+        closer_ = [function retain];
 }
 
-- (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request windowFeatures:(NSDictionary *)features {
-//- (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request userGesture:(BOOL)gesture {
-#if LogBrowser
-    NSLog(@"cwv:%@ (%@): %@", request, title_, features == nil ? @"{}" : [features description]);
-    //NSLog(@"cwv:%@ (%@): %@", request, title_, gesture ? @"Yes" : @"No");
-#endif
-
-    NSNumber *value([features objectForKey:@"width"]);
-    float width(value == nil ? 0 : [value floatValue]);
-
-    RVBook *book(!popup_ ? book_ : [[[RVPopUpBook alloc] initWithFrame:[delegate_ popUpBounds]] autorelease]);
-
-    /* XXX: deal with cydia:// pages */
-    BrowserView *browser([[[class_ alloc] initWithBook:book forWidth:width] autorelease]);
-
-    if (features != nil && popup_) {
-        [book setDelegate:delegate_];
-        [book setHook:indirect_];
-        [browser setDelegate:delegate_];
+- (void) _setViewportWidth {
+    [[webview_ _documentView] setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
+}
 
-        [browser loadRequest:request];
+- (void) setViewportWidth:(float)width {
+    width_ = width != 0 ? width : [[self class] defaultWidth];
+    [self _setViewportWidth];
+}
 
-        [book setPage:browser];
-        [book_ pushBook:book];
-    } else if (request == nil) {
-        [self setBackButtonTitle:title_];
-        [browser setDelegate:delegate_];
-        [browser retain];
-    } else {
-        [self pushPage:browser];
-        [browser loadRequest:request];
-    }
+- (void) webViewUpdateViewSettings:(UIWebView *)view {
+    [self _setViewportWidth];
+}
 
-    return [browser webView];
+- (void) _openMailToURL:(NSURL *)url {
+    [[UIApplication sharedApplication] openURL:url];// asPanel:YES];
 }
 
-- (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request {
-    return [self webView:sender createWebViewWithRequest:request windowFeatures:nil];
-    //return [self webView:sender createWebViewWithRequest:request userGesture:YES];
+- (bool) _allowJavaScriptPanel {
+    return true;
 }
 
-- (void) webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
-    if ([frame parentFrame] != nil)
+- (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
+    [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
+    [self _didFinishLoading];
+
+    if ([error code] == NSURLErrorCancelled)
         return;
 
-    title_ = [title retain];
-    [book_ reloadTitleForPage:self];
+    if ([frame parentFrame] == nil) {
+        [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
+            [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
+            [[error localizedDescription] stringByAddingPercentEscapes]
+        ]]];
+
+        error_ = true;
+    }
 }
 
-- (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
-    /*if ([loading_ count] == 0)
-        [self retain];*/
-    [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
+// CYWebViewDelegate {{{
+- (void) webView:(WebView *)view decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
+#if LogBrowser
+    NSLog(@"decidePolicyForNavigationAction:%@ request:%@ frame:%@", action, request, frame);
+#endif
 
     if ([frame parentFrame] == nil) {
-        [document_ resignFirstResponder];
-
-        reloading_ = false;
-
-        if (title_ != nil) {
-            [title_ release];
-            title_ = nil;
+        if (!error_) {
+            if (request_ != nil)
+                [request_ autorelease];
+            if (request == nil)
+                request_ = nil;
+            else
+                request_ = [request retain];
         }
+    }
+}
 
-        if (button_ != nil) {
-            [button_ release];
-            button_ = nil;
-        }
+- (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
+#if LogBrowser
+    NSLog(@"decidePolicyForNewWindowAction:%@ request:%@ newFrameName:%@", action, request, frame);
+#endif
 
-        if (style_ != nil) {
-            [style_ release];
-            style_ = nil;
-        }
+    NSURL *url([request URL]);
+    if (url == nil)
+        return;
 
-        if (function_ != nil) {
-            [function_ release];
-            function_ = nil;
-        }
+    if ([frame isEqualToString:@"_open"])
+        [delegate_ openURL:url];
 
-        if (finish_ != nil) {
-            [finish_ release];
-            finish_ = nil;
-        }
+    NSString *scheme([[url scheme] lowercaseString]);
+    if ([scheme isEqualToString:@"mailto"])
+        [self _openMailToURL:url];
 
-        if (closer_ != nil) {
-            [closer_ release];
-            closer_ = nil;
-        }
+    CYViewController *page([delegate_ pageForURL:url]);
 
-        if (special_ != nil) {
-            [special_ release];
-            special_ = nil;
-        }
+    if (page == nil) {
+        BrowserController *browser([[[class_ alloc] init] autorelease]);
+        [browser loadRequest:request];
+        page = browser;
+    }
 
-        [book_ reloadTitleForPage:self];
+    [page setDelegate:delegate_];
 
-        if (Wildcat_) {
-            CGRect webrect = [scroller_ bounds];
-            webrect.size.height = 1;
-            [document_ setFrame:webrect];
-        }
+    if (![frame isEqualToString:@"_popup"]) {
+        [[self navigationItem] setTitle:title_];
 
-        if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
-            [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
-        else
-            [scroller_ scrollRectToVisible:CGRectZero animated:NO];
-
-        if ([scroller_ respondsToSelector:@selector(setZoomScale:duration:)])
-            [scroller_ setZoomScale:1 duration:0];
-        else if ([scroller_ respondsToSelector:@selector(_setZoomScale:duration:)])
-            [scroller_ _setZoomScale:1 duration:0];
-        /*else if ([scroller_ respondsToSelector:@selector(setZoomScale:animated:)])
-            [scroller_ setZoomScale:1 animated:NO];*/
-
-        if (!Wildcat_) {
-            CGRect webrect = [scroller_ bounds];
-            webrect.size.height = 0;
-            [document_ setFrame:webrect];
-        }
-    }
+        [[self navigationController] pushViewController:page animated:YES];
+    } else {
+        UCNavigationController *navigation([[[UCNavigationController alloc] initWithRootViewController:page] autorelease]);
 
-    [self reloadButtons];
-}
+        [navigation setHook:indirect_];
+        [navigation setDelegate:delegate_];
 
-- (void) _finishLoading {
-    size_t count([loading_ count]);
-    /*if (count == 0)
-        [self autorelease];*/
-    if (reloading_ || count != 0)
-        return;
-    if (finish_ != nil)
-        [self callFunction:finish_];
-    [self reloadButtons];
-}
+        [[page navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
+            initWithTitle:UCLocalize("CLOSE")
+            style:UIBarButtonItemStylePlain
+            target:page
+            action:@selector(close)
+        ] autorelease]];
 
-- (bool) isLoading {
-    return [loading_ count] != 0;
-}
+        [[self navigationController] presentModalViewController:navigation animated:YES];
+    }
 
-- (void) reloadButtons {
-    if ([self isLoading])
-        [indicator_ startAnimation];
-    else
-        [indicator_ stopAnimation];
-    [super reloadButtons];
+    [listener ignore];
 }
 
-- (BOOL) webView:(WebView *)sender shouldScrollToPoint:(struct CGPoint)point forFrame:(WebFrame *)frame {
-    return [document_ webView:sender shouldScrollToPoint:point forFrame:frame];
+- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
 }
 
-- (void) webView:(WebView *)sender didReceiveViewportArguments:(id)arguments forFrame:(WebFrame *)frame {
-    return [document_ webView:sender didReceiveViewportArguments:arguments forFrame:frame];
-}
+- (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
+#if LogBrowser
+    NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
+#endif
 
-- (void) webView:(WebView *)sender needsScrollNotifications:(id)notifications forFrame:(WebFrame *)frame {
-    return [document_ webView:sender needsScrollNotifications:notifications forFrame:frame];
+    [self _didFailWithError:error forFrame:frame];
 }
 
-- (void) webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame {
-    [self _pushPage];
-    return [document_ webView:sender didCommitLoadForFrame:frame];
-}
+- (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
+#if LogBrowser
+    NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
+#endif
 
-- (void) webView:(WebView *)sender didReceiveDocTypeForFrame:(WebFrame *)frame {
-    return [document_ webView:sender didReceiveDocTypeForFrame:frame];
+    [self _didFailWithError:error forFrame:frame];
 }
 
-- (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
+- (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
     [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
-    [self _finishLoading];
 
     if ([frame parentFrame] == nil) {
         if (DOMDocument *document = [frame DOMDocument])
             if (DOMNodeList<NSFastEnumeration> *bodies = [document getElementsByTagName:@"body"])
-                for (DOMHTMLBodyElement *body in bodies) {
+                for (DOMHTMLBodyElement *body in (id) bodies) {
                     DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
 
                     bool colored(false);
@@ -1063,7 +713,7 @@ static Class $UIWebBrowserView;
                             UIColor *uic(nil);
 
                             if (red == 0xc7 && green == 0xce && blue == 0xd5)
-                                uic = [UIColor pinStripeColor];
+                                uic = [UIColor groupTableViewBackgroundColor];
                             else if (alpha != 0)
                                 uic = [UIColor
                                     colorWithRed:(red / 255)
@@ -1080,358 +730,327 @@ static Class $UIWebBrowserView;
                     }
 
                     if (!colored)
-                        [scroller_ setBackgroundColor:[UIColor pinStripeColor]];
+                        [scroller_ setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
                     break;
                 }
     }
 
-    return [document_ webView:sender didFinishLoadForFrame:frame];
+    [self _didFinishLoading];
 }
 
-- (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
-    _trace();
-    /*if ([frame parentFrame] == nil)
-        [self autorelease];*/
-
-    [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
-    [self _finishLoading];
-
-    if (reloading_)
+- (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
+    if ([frame parentFrame] != nil)
         return;
 
-    if ([frame parentFrame] == nil) {
-        [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
-            [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
-            [[error localizedDescription] stringByAddingPercentEscapes]
-        ]]];
+    if (title_ != nil)
+        [title_ autorelease];
+    title_ = [title retain];
 
-        error_ = true;
-    }
+    [[self navigationItem] setTitle:title_];
 }
 
-- (void) webView:(WebView *)sender didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
-    [self _didFailWithError:error forFrame:frame];
-    if ([document_ respondsToSelector:@selector(webView:didFailLoadWithError:forFrame:)])
-        [document_ webView:sender didFailLoadWithError:error forFrame:frame];
-}
+- (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
+    [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
 
-- (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
-    [self _didFailWithError:error forFrame:frame];
-}
+    if ([frame parentFrame] == nil) {
+        CYRelease(title_);
+        CYRelease(custom_);
+        CYRelease(style_);
+        CYRelease(function_);
+        CYRelease(closer_);
+
+        // XXX: do we still need to do this?
+        [[self navigationItem] setTitle:nil];
+    }
 
-- (void) webView:(WebView *)sender addMessageToConsole:(NSDictionary *)dictionary {
-#if LogBrowser || ForSaurik
-    lprintf("Console:%s\n", [[dictionary description] UTF8String]);
-#endif
+    [self _didStartLoading];
 }
 
-- (void) webView:(WebView *)sender didReceiveMessage:(NSDictionary *)dictionary {
-#if LogBrowser || ForSaurik
-    lprintf("Console:%s\n", [[dictionary description] UTF8String]);
+- (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
+#if LogBrowser
+    NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
 #endif
-    if ([document_ respondsToSelector:@selector(webView:didReceiveMessage:)])
-        [document_ webView:sender didReceiveMessage:dictionary];
-}
 
-- (void) webView:(id)sender willCloseFrame:(id)frame {
-    if ([document_ respondsToSelector:@selector(webView:willCloseFrame:)])
-        [document_ webView:sender willCloseFrame:frame];
+    return request;
 }
 
-- (void) webView:(id)sender didFinishDocumentLoadForFrame:(id)frame {
-    if ([document_ respondsToSelector:@selector(webView:didFinishDocumentLoadForFrame:)])
-        [document_ webView:sender didFinishDocumentLoadForFrame:frame];
+- (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
+    return [self _allowJavaScriptPanel];
 }
 
-- (void) webView:(id)sender didFirstLayoutInFrame:(id)frame {
-    if ([document_ respondsToSelector:@selector(webView:didFirstLayoutInFrame:)])
-        [document_ webView:sender didFirstLayoutInFrame:frame];
+- (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
+    return [self _allowJavaScriptPanel];
 }
 
-- (void) webViewFormEditedStatusHasChanged:(id)changed {
-    if ([document_ respondsToSelector:@selector(webViewFormEditedStatusHasChanged:)])
-        [document_ webViewFormEditedStatusHasChanged:changed];
+- (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
+    return [self _allowJavaScriptPanel];
 }
 
-- (void) webView:(id)sender formStateDidFocusNode:(id)formState {
-    if ([document_ respondsToSelector:@selector(webView:formStateDidFocusNode:)])
-        [document_ webView:sender formStateDidFocusNode:formState];
+- (void) webViewClose:(WebView *)view {
+    [self close];
 }
+// }}}
 
-- (void) webView:(id)sender formStateDidBlurNode:(id)formState {
-    if ([document_ respondsToSelector:@selector(webView:formStateDidBlurNode:)])
-        [document_ webView:sender formStateDidBlurNode:formState];
+- (void) close {
+    [[self navigationController] dismissModalViewControllerAnimated:YES];
 }
 
-/* XXX: fix this stupid include file
-- (void) webView:(WebView *)sender frame:(WebFrame *)frame exceededDatabaseQuotaForSecurityOrigin:(WebSecurityOrigin *)origin database:(NSString *)database {
-    [origin setQuota:0x500000];
-}*/
-
-- (void) webViewDidLayout:(id)sender {
-    [document_ webViewDidLayout:sender];
-}
+- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
+    NSString *context([alert context]);
 
-- (void) webView:(id)sender didFirstVisuallyNonEmptyLayoutInFrame:(id)frame {
-    [document_ webView:sender didFirstVisuallyNonEmptyLayoutInFrame:frame];
-}
+    if ([context isEqualToString:@"sensitive"]) {
+        switch (button) {
+            case 1:
+                sensitive_ = [NSNumber numberWithBool:YES];
+            break;
 
-- (void) webView:(id)sender saveStateToHistoryItem:(id)item forFrame:(id)frame {
-    [document_ webView:sender saveStateToHistoryItem:item forFrame:frame];
-}
+            case 2:
+                sensitive_ = [NSNumber numberWithBool:NO];
+            break;
+        }
 
-- (void) webView:(id)sender restoreStateFromHistoryItem:(id)item forFrame:(id)frame force:(BOOL)force {
-    [document_ webView:sender restoreStateFromHistoryItem:item forFrame:frame force:force];
-}
+        [alert dismissWithClickedButtonIndex:-1 animated:YES];
+    } else if ([context isEqualToString:@"challenge"]) {
+        id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
 
-- (void) webView:(id)sender attachRootLayer:(id)layer {
-    [document_ webView:sender attachRootLayer:layer];
-}
+        switch (button) {
+            case 1: {
+                NSString *username([[alert textFieldAtIndex:0] text]);
+                NSString *password([[alert textFieldAtIndex:1] text]);
 
-- (id) webView:(id)sender plugInViewWithArguments:(id)arguments fromPlugInPackage:(id)package {
-    return [document_ webView:sender plugInViewWithArguments:arguments fromPlugInPackage:package];
-}
+                NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
 
-- (void) webView:(id)sender willShowFullScreenForPlugInView:(id)view {
-    [document_ webView:sender willShowFullScreenForPlugInView:view];
-}
+                [sender useCredential:credential forAuthenticationChallenge:challenge_];
+            } break;
 
-- (void) webView:(id)sender didHideFullScreenForPlugInView:(id)view {
-    [document_ webView:sender didHideFullScreenForPlugInView:view];
-}
+            case 2:
+                [sender cancelAuthenticationChallenge:challenge_];
+            break;
 
-- (void) webView:(id)sender willAddPlugInView:(id)view {
-    [document_ webView:sender willAddPlugInView:view];
-}
+            _nodefault
+        }
 
-- (void) webView:(id)sender didObserveDeferredContentChange:(int)change forFrame:(id)frame {
-    [document_ webView:sender didObserveDeferredContentChange:change forFrame:frame];
-}
+        [challenge_ release];
+        challenge_ = nil;
 
-- (void) webViewDidPreventDefaultForEvent:(id)sender {
-    [document_ webViewDidPreventDefaultForEvent:sender];
-}
+        [alert dismissWithClickedButtonIndex:-1 animated:YES];
+    } else if ([context isEqualToString:@"submit"]) {
+        if (button == [alert cancelButtonIndex]) {
+        } else if (button == [alert firstOtherButtonIndex]) {
+            if (request_ != nil) {
+                WebThreadLock();
+                [webview_ loadRequest:request_];
+                WebThreadUnlock();
+            }
+        }
 
-- (void) _setTileDrawingEnabled:(BOOL)enabled {
-    //[document_ setTileDrawingEnabled:enabled];
+        [alert dismissWithClickedButtonIndex:-1 animated:YES];
+    }
 }
 
-- (void) setViewportWidth:(float)width {
-    width_ = width != 0 ? width : [[self class] defaultWidth];
-    [document_ setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
+- (UIBarButtonItemStyle) rightButtonStyle {
+    if (style_ == nil) normal:
+        return UIBarButtonItemStylePlain;
+    else if ([style_ isEqualToString:@"Normal"])
+        return UIBarButtonItemStylePlain;
+    else if ([style_ isEqualToString:@"Highlighted"])
+        return UIBarButtonItemStyleDone;
+    else goto normal;
 }
 
-- (void) willStartGesturesInView:(UIView *)view forEvent:(GSEventRef)event {
-    [self _setTileDrawingEnabled:NO];
+- (UIBarButtonItem *) customButton {
+    return [[[UIBarButtonItem alloc]
+        initWithTitle:custom_
+        style:[self rightButtonStyle]
+        target:self
+        action:@selector(customButtonClicked)
+    ] autorelease];
 }
 
-- (void) didFinishGesturesInView:(UIView *)view forEvent:(GSEventRef)event {
-    [self _setTileDrawingEnabled:YES];
-    [document_ redrawScaledDocument];
+- (UIBarButtonItem *) rightButton {
+    return reloaditem_;
 }
 
-- (void) scrollerWillStartDragging:(UIScroller *)scroller {
-    [self _setTileDrawingEnabled:NO];
+- (void) applyLoadingTitle {
+    [[self navigationItem] setTitle:UCLocalize("LOADING")];
 }
 
-- (void) scrollerDidEndDragging:(UIScroller *)scroller willSmoothScroll:(BOOL)smooth {
-    [self _setTileDrawingEnabled:YES];
+- (void) layoutRightButton {
+    [[loadingitem_ view] addSubview:indicator_];
+    [[loadingitem_ view] bringSubviewToFront:indicator_];
 }
 
-- (void) scrollerDidEndDragging:(UIScroller *)scroller {
-    [self _setTileDrawingEnabled:YES];
-}
+- (void) applyRightButton {
+    if ([self isLoading]) {
+        [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
+        [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
 
-- (id) initWithBook:(RVBook *)book forWidth:(float)width ofClass:(Class)_class {
-    if ((self = [super initWithBook:book]) != nil) {
-        class_ = _class;
-        loading_ = [[NSMutableSet alloc] initWithCapacity:3];
-        popup_ = false;
+        [indicator_ startAnimating];
+        [self applyLoadingTitle];
+    } else {
+        [indicator_ stopAnimating];
 
-        struct CGRect bounds = [self bounds];
+        [[self navigationItem] setRightBarButtonItem:(
+            custom_ != nil ? [self customButton] : [self rightButton]
+        ) animated:YES];
+    }
+}
 
-        scroller_ = [[objc_getClass(Wildcat_ ? "UIScrollView" : "UIScroller") alloc] initWithFrame:bounds];
-        [self addSubview:scroller_];
+- (void) didStartLoading {
+    // Overridden in subclasses.
+}
 
-        [scroller_ setFixedBackgroundPattern:YES];
-        [scroller_ setBackgroundColor:[UIColor pinStripeColor]];
+- (void) _didStartLoading {
+    [self applyRightButton];
 
-        [scroller_ setScrollingEnabled:YES];
-        [scroller_ setClipsSubviews:YES];
+    if ([loading_ count] != 1)
+        return;
 
-        if (!Wildcat_)
-            [scroller_ setAllowsRubberBanding:YES];
+    [delegate_ retainNetworkActivityIndicator];
+    [self didStartLoading];
+}
 
-        [scroller_ setDelegate:self];
-        [scroller_ setBounces:YES];
+- (void) didFinishLoading {
+    // Overridden in subclasses.
+}
 
-        if (!Wildcat_) {
-            [scroller_ setScrollHysteresis:8];
-            [scroller_ setThumbDetectionEnabled:NO];
-            [scroller_ setDirectionalScrolling:YES];
-            //[scroller_ setScrollDecelerationFactor:0.99]; /* 0.989324 */
-            [scroller_ setEventMode:YES];
-        }
+- (void) _didFinishLoading {
+    if ([loading_ count] != 0)
+        return;
 
-        if (Wildcat_) {
-            UIScrollView *scroller((UIScrollView *)scroller_);
-            //[scroller setDirectionalLockEnabled:NO];
-            [scroller setDelaysContentTouches:NO];
-            //[scroller setScrollsToTop:NO];
-            //[scroller setCanCancelContentTouches:NO];
-        }
+    [self applyRightButton];
+    [[self navigationItem] setTitle:title_];
 
-        [scroller_ setShowBackgroundShadow:NO]; /* YES */
-        //[scroller_ setAllowsRubberBanding:YES]; /* Vertical */
+    [delegate_ releaseNetworkActivityIndicator];
+    [self didFinishLoading];
+}
 
-        if (!Wildcat_)
-            [scroller_ setAdjustForContentSizeChange:YES]; /* NO */
+- (bool) isLoading {
+    return [loading_ count] != 0;
+}
 
-        CGRect webrect = [scroller_ bounds];
-        webrect.size.height = 0;
+- (id) initWithWidth:(float)width ofClass:(Class)_class {
+    if ((self = [super init]) != nil) {
+        class_ = _class;
+        loading_ = [[NSMutableSet alloc] initWithCapacity:5];
 
-        WebView *webview;
+        indirect_ = [[IndirectDelegate alloc] initWithDelegate:self];
 
-        WebThreadLock();
+        webview_ = [[[CYWebView alloc] initWithFrame:[[self view] bounds]] autorelease];
+        [webview_ setDelegate:self];
+        [self setView:webview_];
 
-#if RecycleWebViews
-        document_ = [Documents_ lastObject];
-        if (document_ != nil) {
-            document_ = [document_ retain];
-            webview = [document_ webView];
-            [Documents_ removeLastObject];
-            [document_ setFrame:webrect];
-        } else {
-#else
-        if (true) {
-#endif
-            document_ = [[$UIWebBrowserView alloc] initWithFrame:webrect];
-            webview = [document_ webView];
-
-            // XXX: this is terribly (too?) expensive
-            //[document_ setDrawsBackground:NO];
-            [webview setPreferencesIdentifier:@"Cydia"];
-
-            [document_ setTileSize:CGSizeMake(webrect.size.width, 500)];
-
-            if ([document_ respondsToSelector:@selector(enableReachability)])
-                [document_ enableReachability];
-            if ([document_ respondsToSelector:@selector(setAllowsMessaging:)])
-                [document_ setAllowsMessaging:YES];
-            if ([document_ respondsToSelector:@selector(useSelectionAssistantWithMode:)])
-                [document_ useSelectionAssistantWithMode:0];
-
-            [document_ setTilingEnabled:YES];
-            [document_ setDrawsGrid:NO];
-            [document_ setLogsTilingChanges:NO];
-            [document_ setTileMinificationFilter:kCAFilterNearest];
-
-            if ([document_ respondsToSelector:@selector(setDataDetectorTypes:)])
-                /* XXX: abstractify */
-                [document_ setDataDetectorTypes:0x80000000];
-            else
-                [document_ setDetectsPhoneNumbers:NO];
+        if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
+            [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
+        else
+            [webview_ setDetectsPhoneNumbers:NO];
 
-            [document_ setAutoresizes:YES];
+        [webview_ setScalesPageToFit:YES];
 
-            [document_ setMinimumScale:0.25f forDocumentTypes:0x10];
-            [document_ setMaximumScale:5.00f forDocumentTypes:0x10];
-            [document_ setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:0x10];
-            //[document_ setViewportSize:CGSizeMake(980, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
+        UIWebDocumentView *document([webview_ _documentView]);
 
-            [document_ setViewportSize:CGSizeMake(320, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x2];
+        // XXX: I think this improves scrolling; the hardcoded-ness sucks
+        [document setTileSize:CGSizeMake(320, 500)];
 
-            [document_ setMinimumScale:1.00f forDocumentTypes:0x8];
-            [document_ setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:0x8];
-            [document_ setViewportSize:CGSizeMake(320, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x8];
+        [document setBackgroundColor:[UIColor clearColor]];
 
-            [document_ _setDocumentType:0x4];
+        // XXX: this is terribly (too?) expensive
+        [document setDrawsBackground:NO];
 
-            if ([document_ respondsToSelector:@selector(setZoomsFocusedFormControl:)])
-                [document_ setZoomsFocusedFormControl:YES];
-            [document_ setContentsPosition:7];
-            [document_ setEnabledGestures:0xa];
-            [document_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeIsZoomRubberBandEnabled];
-            [document_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeUpdatesScroller];
+        WebView *webview([document webView]);
+        WebPreferences *preferences([webview preferences]);
 
-            [document_ setSmoothsFonts:YES];
-            [document_ setAllowsImageSheet:YES];
-            [webview _setUsesLoaderCache:YES];
+        // XXX: I have no clue if I actually /want/ this modification
+        if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
+            [webview _setLayoutInterval:0];
+        else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
+            [preferences _setLayoutInterval:0];
 
-            [webview setGroupName:@"CydiaGroup"];
+        [preferences setCacheModel:WebCacheModelDocumentBrowser];
+        [preferences setOfflineWebApplicationCacheEnabled:YES];
 
-            WebPreferences *preferences([webview preferences]);
+        if ([webview_ respondsToSelector:@selector(_scrollView)]) {
+            scroller_ = [webview_ _scrollView];
 
-            if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
-                [webview _setLayoutInterval:0];
-            else
-                [preferences _setLayoutInterval:0];
-        }
+            [scroller_ setDirectionalLockEnabled:YES];
+            [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
+            [scroller_ setDelaysContentTouches:NO];
 
-        [self setViewportWidth:width];
+            [scroller_ setCanCancelContentTouches:YES];
+        } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
+            UIScroller *scroller([webview_ _scroller]);
+            scroller_ = (UIScrollView *) scroller;
 
-        [document_ setDelegate:self];
-        [document_ setGestureDelegate:self];
+            [scroller setDirectionalScrolling:YES];
+            // XXX: we might be better off /not/ setting this on older systems
+            [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
+            [scroller setScrollHysteresis:0]; /* 8 */
 
-        if ([document_ respondsToSelector:@selector(setFormEditingDelegate:)])
-            [document_ setFormEditingDelegate:self];
+            [scroller setThumbDetectionEnabled:NO];
 
-        [document_ setInteractionDelegate:self];
+            // use NO with UIApplicationUseLegacyEvents(YES)
+            [scroller setEventMode:YES];
 
-        [scroller_ addSubview:document_];
+            // XXX: this is handled by setBounces, right?
+            //[scroller setAllowsRubberBanding:YES];
+        }
 
-        //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
+        [scroller_ setFixedBackgroundPattern:YES];
+        [scroller_ setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
+        [scroller_ setClipsSubviews:YES];
 
-        indirect_ = [[IndirectDelegate alloc] initWithDelegate:self];
+        [scroller_ setBounces:YES];
+        [scroller_ setScrollingEnabled:YES];
+        [scroller_ setShowBackgroundShadow:NO];
 
-        [webview setFrameLoadDelegate:indirect_];
-        [webview setPolicyDelegate:indirect_];
-        [webview setResourceLoadDelegate:indirect_];
-        [webview setUIDelegate:indirect_];
+        [self setViewportWidth:width];
 
-        /* XXX: do not turn this on under penalty of extreme pain */
-        [webview setScriptDebugDelegate:nil];
+        reloaditem_ = [[UIBarButtonItem alloc]
+            initWithTitle:UCLocalize("RELOAD")
+            style:[self rightButtonStyle]
+            target:self
+            action:@selector(reloadButtonClicked)
+        ];
 
-        WebThreadUnlock();
+        loadingitem_ = [[UIBarButtonItem alloc]
+            initWithTitle:@" "
+            style:UIBarButtonItemStylePlain
+            target:self
+            action:@selector(reloadButtonClicked)
+        ];
 
-        CGSize indsize = [UIProgressIndicator defaultSizeForStyle:UIProgressIndicatorStyleMediumWhite];
-        indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(bounds.size.width - 39, 12, indsize.width, indsize.height)];
-        [indicator_ setStyle:UIProgressIndicatorStyleMediumWhite];
+        indicator_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]; 
+        [indicator_ setFrame:CGRectMake(15, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
 
-        [self setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
-        [scroller_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
+        [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
         [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
-        [document_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
-
-        /*UIWebView *test([[[UIWebView alloc] initWithFrame:[self bounds]] autorelease]);
-        [test loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.saurik.com/"]]];
-        [self addSubview:test];*/
     } return self;
 }
 
-- (id) initWithBook:(RVBook *)book forWidth:(float)width {
-    return [self initWithBook:book forWidth:width ofClass:[self class]];
+- (id) initWithWidth:(float)width {
+    return [self initWithWidth:width ofClass:[self class]];
 }
 
-- (id) initWithBook:(RVBook *)book {
-    return [self initWithBook:book forWidth:0];
+- (id) init {
+    return [self initWithWidth:0];
 }
 
-- (NSString *) stringByEvaluatingJavaScriptFromString:(NSString *)script {
-    WebThreadLock();
-    WebView *webview([document_ webView]);
-    NSString *string([webview stringByEvaluatingJavaScriptFromString:script]);
-    WebThreadUnlock();
-    return string;
+- (void) didDismissModalViewController {
+    if (closer_ != nil)
+        [self callFunction:closer_];
 }
 
 - (void) callFunction:(WebScriptObject *)function {
     WebThreadLock();
 
-    WebView *webview([document_ webView]);
+    WebView *webview([[webview_ _documentView] webView]);
     WebFrame *frame([webview mainFrame]);
+    WebPreferences *preferences([webview preferences]);
 
-    id _private(MSHookIvar<id>(webview, "_private"));
+    bool maybe([preferences javaScriptCanOpenWindowsAutomatically]);
+    [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
+
+    /*id _private(MSHookIvar<id>(webview, "_private"));
     WebCore::Page *page(_private == nil ? NULL : MSHookIvar<WebCore::Page *>(_private, "page"));
     WebCore::Settings *settings(page == NULL ? NULL : page->settings());
 
@@ -1441,9 +1060,9 @@ static Class $UIWebBrowserView;
     else {
         no = settings->JavaScriptCanOpenWindowsAutomatically();
         settings->setJavaScriptCanOpenWindowsAutomatically(true);
-    }
+    }*/
 
-    if (UIWindow *window = [self window])
+    if (UIWindow *window = [[self view] window])
         if (UIResponder *responder = [window firstResponder])
             [responder resignFirstResponder];
 
@@ -1451,73 +1070,29 @@ static Class $UIWebBrowserView;
     JSGlobalContextRef context([frame globalContext]);
     JSObjectCallAsFunction(context, object, NULL, 0, NULL, NULL);
 
-    if (settings != NULL)
-        settings->setJavaScriptCanOpenWindowsAutomatically(no);
+    /*if (settings != NULL)
+        settings->setJavaScriptCanOpenWindowsAutomatically(no);*/
+
+    [preferences setJavaScriptCanOpenWindowsAutomatically:maybe];
 
     WebThreadUnlock();
 }
 
-- (void) didCloseBook:(RVBook *)book {
-    if (closer_ != nil)
-        [self callFunction:closer_];
+- (void) reloadButtonClicked {
+    [self reloadURL];
 }
 
-- (void) __rightButtonClicked {
-    reloading_ = true;
-    [self reloadURL];
+- (void) _customButtonClicked {
+    [self reloadButtonClicked];
 }
 
-- (void) _rightButtonClicked {
+- (void) customButtonClicked {
 #if !AlwaysReload
     if (function_ != nil)
         [self callFunction:function_];
     else
 #endif
-        [self __rightButtonClicked];
-}
-
-- (id) _rightButtonTitle {
-    return UCLocalize("RELOAD");
-}
-
-- (id) rightButtonTitle {
-    return [self isLoading] ? @"" : button_ != nil ? button_ : [self _rightButtonTitle];
-}
-
-- (UINavigationButtonStyle) rightButtonStyle {
-    if (style_ == nil) normal:
-        return UINavigationButtonStyleNormal;
-    else if ([style_ isEqualToString:@"Normal"])
-        return UINavigationButtonStyleNormal;
-    else if ([style_ isEqualToString:@"Back"])
-        return UINavigationButtonStyleBack;
-    else if ([style_ isEqualToString:@"Highlighted"])
-        return UINavigationButtonStyleHighlighted;
-    else if ([style_ isEqualToString:@"Destructive"])
-        return UINavigationButtonStyleDestructive;
-    else goto normal;
-}
-
-- (NSString *) title {
-    return title_ == nil ? UCLocalize("LOADING") : title_;
-}
-
-- (NSString *) backButtonTitle {
-    return UCLocalize("BROWSER");
-}
-
-- (void) setPageActive:(BOOL)active {
-    if (!active)
-        [indicator_ removeFromSuperview];
-    else
-        [[book_ navigationBar] addSubview:indicator_];
-}
-
-- (void) resetViewAnimated:(BOOL)animated {
-}
-
-- (void) setPushed:(bool)pushed {
-    pushed_ = pushed;
+    [self _customButtonClicked];
 }
 
 + (float) defaultWidth {