]> git.saurik.com Git - cydia.git/blobdiff - UICaboodle/BrowserView.mm
Filter out the more annoying console.log() messages.
[cydia.git] / UICaboodle / BrowserView.mm
index 73f615539260b782ccca8e6ccda846814e9b3378..7a356428275b0a8e434b8e84ee895e085cb72a98 100644 (file)
@@ -4,6 +4,7 @@
 #include "UCPlatform.h"
 
 #include <UICaboodle/BrowserView.h>
+#include "UICaboodle/PerlCompatibleRegEx.hpp"
 #include <UICaboodle/UCLocalize.h>
 
 //#include <QuartzCore/CALayer.h>
@@ -27,6 +28,25 @@ extern NSString * const kCAFilterNearest;
 #include "substrate.h"
 
 #define ForSaurik 0
+#define DefaultTimeout_ 120.0
+
+#define ShowInternals 0
+#define LogBrowser 0
+#define LogMessages 0
+
+#define lprintf(args...) fprintf(stderr, args)
+
+// WebThreadLocked {{{
+struct WebThreadLocked {
+    _finline WebThreadLocked() {
+        WebThreadLock();
+    }
+
+    _finline ~WebThreadLocked() {
+        WebThreadUnlock();
+    }
+};
+// }}}
 
 template <typename Type_>
 static inline void CYRelease(Type_ &value) {
@@ -40,6 +60,7 @@ float CYScrollViewDecelerationRateNormal;
 
 @interface WebView (Apple)
 - (void) _setLayoutInterval:(float)interval;
+- (void) _setAllowsMessaging:(BOOL)allows;
 @end
 
 @interface WebPreferences (Apple)
@@ -49,9 +70,7 @@ float CYScrollViewDecelerationRateNormal;
 @end
 
 /* Indirect Delegate {{{ */
-@interface IndirectDelegate : NSObject <
-    HookProtocol
-> {
+@interface IndirectDelegate : NSObject {
     _transient volatile id delegate_;
 }
 
@@ -70,11 +89,6 @@ float CYScrollViewDecelerationRateNormal;
     return self;
 }
 
-- (void) didDismissModalViewController {
-    if (delegate_ != nil)
-        return [delegate_ didDismissModalViewController];
-}
-
 - (IMP) methodForSelector:(SEL)sel {
     if (IMP method = [super methodForSelector:sel])
         return method;
@@ -85,18 +99,28 @@ float CYScrollViewDecelerationRateNormal;
 - (BOOL) respondsToSelector:(SEL)sel {
     if ([super respondsToSelector:sel])
         return YES;
+
     // XXX: WebThreadCreateNSInvocation returns nil
-    //fprintf(stderr, "[%s]R?%s\n", class_getName(self->isa), sel_getName(sel));
+
+#if ShowInternals
+    fprintf(stderr, "[%s]R?%s\n", class_getName(self->isa), sel_getName(sel));
+#endif
+
     return delegate_ == nil ? NO : [delegate_ respondsToSelector:sel];
 }
 
 - (NSMethodSignature *) methodSignatureForSelector:(SEL)sel {
     if (NSMethodSignature *method = [super methodSignatureForSelector:sel])
         return method;
-    //fprintf(stderr, "[%s]S?%s\n", class_getName(self->isa), sel_getName(sel));
+
+#if ShowInternals
+    fprintf(stderr, "[%s]S?%s\n", class_getName(self->isa), sel_getName(sel));
+#endif
+
     if (delegate_ != nil)
         if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
             return sig;
+
     // XXX: I fucking hate Apple so very very bad
     return [NSMethodSignature signatureWithObjCTypes:"v@:"];
 }
@@ -169,6 +193,7 @@ enum CYWebPolicyDecision {
     switch (decision_) {
         case CYWebPolicyDecisionUnknown:
         default:
+            NSLog(@"CYWebPolicyDecisionUnknown");
             return false;
 
         case CYWebPolicyDecisionDownload: [listener_ download]; break;
@@ -196,6 +221,10 @@ enum CYWebPolicyDecision {
 
 @implementation CYWebView : UIWebView
 
+#if ShowInternals
+#include "UICaboodle/UCInternal.h"
+#endif
+
 - (id) initWithFrame:(CGRect)frame {
     if ((self = [super initWithFrame:frame]) != nil) {
     } return self;
@@ -210,14 +239,30 @@ enum CYWebPolicyDecision {
 }
 
 /*- (WebView *) webView:(WebView *)view createWebViewWithRequest:(NSURLRequest *)request {
-    NSLog(@"createWebViewWithRequest:%@", request);
-    WebView *created(nil); // XXX
+    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:)])
-        return [super webView:view createWebViewWithRequest:request];
-    else
-        return created;
+        created = [super webView:view createWebViewWithRequest:request];
+    return created;
 }*/
 
+// webView:addMessageToConsole: (X.Xx) {{{
+static void $UIWebViewWebViewDelegate$webView$addMessageToConsole$(UIWebViewWebViewDelegate *self, SEL sel, WebView *view, NSDictionary *message) {
+    UIWebView *uiWebView(MSHookIvar<UIWebView *>(self, "uiWebView"));
+    if ([uiWebView respondsToSelector:@selector(webView:addMessageToConsole:)])
+        [uiWebView webView:view addMessageToConsole:message];
+}
+
+- (void) webView:(WebView *)view addMessageToConsole:(NSDictionary *)message {
+    id<CYWebViewDelegate> delegate([self delegate]);
+    if ([delegate respondsToSelector:@selector(webView:addMessageToConsole:)])
+        [delegate webView:view addMessageToConsole:message];
+    if ([UIWebView instancesRespondToSelector:@selector(webView:addMessageToConsole:)])
+        [super webView:view addMessageToConsole:message];
+}
+// }}}
 // 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]);
@@ -246,7 +291,7 @@ static void $UIWebViewWebViewDelegate$webView$decidePolicyForNewWindowAction$req
     [mediator decide];
 }
 // }}}
-// webView:didClearWindowObject:forFrame: (3.2, 4.1+) {{{
+// 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:)])
@@ -288,7 +333,7 @@ static void $UIWebViewWebViewDelegate$webView$didClearWindowObject$forFrame$(UIW
         [super webView:view didFinishLoadForFrame:frame];
 }
 // }}}
-// webView:didReceiveTitle:forFrame: (3.2, 4.1+) {{{
+// 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:)])
@@ -312,13 +357,12 @@ static void $UIWebViewWebViewDelegate$webView$didReceiveTitle$forFrame$(UIWebVie
         [super webView:view didStartProvisionalLoadForFrame:frame];
 }
 // }}}
-// webView:resource:willSendRequest:redirectResponse:fromDataSource: (3.2, 4.1+) {{{
+// 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:)])
-        return [uiWebView webView:view resource:identifier willSendRequest:request redirectResponse:response fromDataSource:source];
-    else
-        return request;
+        request = [uiWebView webView:view resource:identifier willSendRequest:request redirectResponse:response fromDataSource:source];
+    return request;
 }
 
 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
@@ -330,36 +374,42 @@ static NSURLRequest *$UIWebViewWebViewDelegate$webView$resource$willSendRequest$
     return request;
 }
 // }}}
-// webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame: (2.2+) {{{
+// 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:)])
-        // XXX: check delegate
-        if ([delegate webView:view shouldRunJavaScriptAlertPanelWithMessage:message initiatedByFrame:frame])
+        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.2+) {{{
+// 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:)])
-        // XXX: check delegate
-        if ([delegate webView:view shouldRunJavaScriptConfirmPanelWithMessage:message initiatedByFrame:frame])
+        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.2+) {{{
+// 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:)])
-        // XXX: check delegate
-        if ([delegate webView:view shouldRunJavaScriptTextInputPanelWithPrompt:prompt defaultText:text initiatedByFrame:frame])
+        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;
 }
 // }}}
-// webViewClose: (3.2, 4.1+) {{{
+// webViewClose: (3.2+) {{{
 static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *self, SEL sel, WebView *view) {
     UIWebView *uiWebView(MSHookIvar<UIWebView *>(self, "uiWebView"));
     if ([uiWebView respondsToSelector:@selector(webViewClose:)])
@@ -375,8 +425,17 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
 }
 // }}}
 
+- (void) _updateViewSettings {
+    [super _updateViewSettings];
+
+    id<CYWebViewDelegate> delegate([self delegate]);
+    if ([delegate respondsToSelector:@selector(webViewUpdateViewSettings:)])
+        [delegate webViewUpdateViewSettings:self];
+}
+
 + (void) initialize {
     if (Class $UIWebViewWebViewDelegate = objc_getClass("UIWebViewWebViewDelegate")) {
+        class_addMethod($UIWebViewWebViewDelegate, @selector(webView:addMessageToConsole:), (IMP) &$UIWebViewWebViewDelegate$webView$addMessageToConsole$, "v16@0:4@8@12");
         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");
@@ -387,11 +446,6 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
 
 @end
 
-#define ShowInternals 0
-#define LogBrowser 1
-
-#define lprintf(args...) fprintf(stderr, args)
-
 @implementation BrowserController
 
 #if ShowInternals
@@ -420,23 +474,13 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
     if (challenge_ != nil)
         [challenge_ release];
 
-    //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
-
-    if (custom_ != nil)
-        [custom_ release];
-    if (style_ != nil)
-        [style_ release];
-
-    if (function_ != nil)
-        [function_ release];
-    if (closer_ != nil)
-        [closer_ release];
-
-    if (sensitive_ != nil)
-        [sensitive_ release];
     if (title_ != nil)
         [title_ release];
 
+    if ([loading_ count] != 0)
+        [delegate_ releaseNetworkActivityIndicator];
+    [loading_ release];
+
     [reloaditem_ release];
     [loadingitem_ release];
 
@@ -445,12 +489,25 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
     [super dealloc];
 }
 
-- (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
-    [self loadRequest:[NSURLRequest
-        requestWithURL:url
+- (NSURL *) URLWithURL:(NSURL *)url {
+    return url;
+}
+
+- (NSURLRequest *) requestWithURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
+    return [NSURLRequest
+        requestWithURL:[self URLWithURL:url]
         cachePolicy:policy
-        timeoutInterval:120.0
-    ]];
+        timeoutInterval:DefaultTimeout_
+    ];
+}
+
+- (void) setURL:(NSURL *)url {
+    _assert(request_ == nil);
+    request_ = [self requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
+}
+
+- (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
+    [self loadRequest:[self requestWithURL:url cachePolicy:policy]];
 }
 
 - (void) loadURL:(NSURL *)url {
@@ -458,17 +515,25 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
 }
 
 - (void) loadRequest:(NSURLRequest *)request {
+#if LogBrowser
+    NSLog(@"loadRequest:%@", request);
+#endif
+
     error_ = false;
 
-    WebThreadLock();
+    WebThreadLocked lock;
     [webview_ loadRequest:request];
-    WebThreadUnlock();
 }
 
-- (void) reloadURL {
+- (void) reloadURLWithCache:(BOOL)cache {
     if (request_ == nil)
         return;
 
+    NSMutableURLRequest *request([request_ mutableCopy]);
+    [request setCachePolicy:(cache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData)];
+
+    request_ = request;
+
     if ([request_ HTTPBody] == nil && [request_ HTTPBodyStream] == nil)
         [self loadRequest:request_];
     else {
@@ -477,7 +542,9 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
             message:nil
             delegate:self
             cancelButtonTitle:UCLocalize("CANCEL")
-            otherButtonTitles:UCLocalize("SUBMIT"), nil
+            otherButtonTitles:
+                UCLocalize("SUBMIT"),
+            nil
         ] autorelease];
 
         [alert setContext:@"submit"];
@@ -485,47 +552,66 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
     }
 }
 
-- (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
-    if (custom_ != nil)
-        [custom_ autorelease];
-    custom_ = button == nil ? nil : [[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:button]]] retain];
+- (void) reloadURL {
+    [self reloadURLWithCache:YES];
+}
 
-    if (style_ != nil)
-        [style_ autorelease];
-    style_ = style == nil ? nil : [style retain];
+- (void) reloadData {
+    [super reloadData];
+    [self reloadURLWithCache:YES];
+}
 
-    if (function_ != nil)
-        [function_ autorelease];
-    function_ = function == nil ? nil : [function retain];
+- (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
+    custom_ = button;
+    style_ = style;
+    function_ = function;
 
-    [self applyRightButton];
+    [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
 }
 
 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
-    if (custom_ != nil)
-        [custom_ autorelease];
-    custom_ = button == nil ? nil : [button retain];
+    custom_ = button;
+    style_ = style;
+    function_ = function;
 
-    if (style_ != nil)
-        [style_ autorelease];
-    style_ = style == nil ? nil : [style retain];
+    [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
+}
 
-    if (function_ != nil)
-        [function_ autorelease];
-    function_ = function == nil ? nil : [function retain];
+- (void) removeButton {
+    custom_ = [NSNull null];
+    [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
+}
 
-    [self applyRightButton];
+- (void) scrollToBottomAnimated:(NSNumber *)animated {
+    CGSize size([scroller_ contentSize]);
+    CGPoint offset([scroller_ contentOffset]);
+    CGRect frame([scroller_ frame]);
+
+    if (size.height - offset.y < frame.size.height + 20.f) {
+        CGRect rect = {{0, size.height-1}, {size.width, 1}};
+        [scroller_ scrollRectToVisible:rect animated:[animated boolValue]];
+    }
 }
 
-- (void) setPopupHook:(id)function {
-    if (closer_ != nil)
-        [closer_ autorelease];
-    closer_ = function == nil ? nil : [function retain];
+- (void) _setViewportWidth {
+    [[webview_ _documentView] setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
 }
 
 - (void) setViewportWidth:(float)width {
     width_ = width != 0 ? width : [[self class] defaultWidth];
-    [[webview_ _documentView] setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
+    [self _setViewportWidth];
+}
+
+- (void) _setViewportWidthOnMainThread:(NSNumber *)width {
+    [self setViewportWidth:[width floatValue]];
+}
+
+- (void) setViewportWidthOnMainThread:(float)width {
+    [self performSelectorOnMainThread:@selector(_setViewportWidthOnMainThread:) withObject:[NSNumber numberWithFloat:width] waitUntilDone:NO];
+}
+
+- (void) webViewUpdateViewSettings:(UIWebView *)view {
+    [self _setViewportWidth];
 }
 
 - (void) _openMailToURL:(NSURL *)url {
@@ -536,6 +622,24 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
     return true;
 }
 
+- (bool) allowsNavigationAction {
+    return allowsNavigationAction_;
+}
+
+- (void) setAllowsNavigationAction:(bool)value {
+    allowsNavigationAction_ = value;
+}
+
+- (void) setAllowsNavigationActionByNumber:(NSNumber *)value {
+    [self setAllowsNavigationAction:[value boolValue]];
+}
+
+- (void) popViewControllerWithNumber:(NSNumber *)value {
+    UINavigationController *navigation([self navigationController]);
+    if ([navigation topViewController] == self)
+        [navigation popViewControllerAnimated:[value boolValue]];
+}
+
 - (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
     [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
     [self _didFinishLoading];
@@ -553,39 +657,11 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
     }
 }
 
-// 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 (!error_ && [frame parentFrame] == nil) {
-        if (request_ != nil)
-            [request_ autorelease];
-        if (request == nil)
-            request_ = nil;
-        else
-            request_ = [request retain];
-    }
-}
-
-- (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
-
+- (void) pushRequest:(NSURLRequest *)request asPop:(bool)pop {
     NSURL *url([request URL]);
-    if (url == nil)
-        return;
 
-    if ([frame isEqualToString:@"_open"])
-        [delegate_ openURL:url];
-
-    NSString *scheme([[url scheme] lowercaseString]);
-    if ([scheme isEqualToString:@"mailto"])
-        [self _openMailToURL:url];
-
-    CYViewController *page([delegate_ pageForURL:url hasTag:NULL]);
+    // XXX: filter to internal usage?
+    CYViewController *page([delegate_ pageForURL:url forExternal:NO]);
 
     if (page == nil) {
         BrowserController *browser([[[class_ alloc] init] autorelease]);
@@ -595,18 +671,15 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
 
     [page setDelegate:delegate_];
 
-    if (![frame isEqualToString:@"_popup"]) {
+    if (!pop) {
         [[self navigationItem] setTitle:title_];
 
         [[self navigationController] pushViewController:page animated:YES];
     } else {
-        UCNavigationController *navigation([[[UCNavigationController alloc] init] autorelease]);
+        UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
 
-        [navigation setHook:indirect_];
         [navigation setDelegate:delegate_];
 
-        [navigation setViewControllers:[NSArray arrayWithObject:page]];
-
         [[page navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
             initWithTitle:UCLocalize("CLOSE")
             style:UIBarButtonItemStylePlain
@@ -615,6 +688,60 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
         ] autorelease]];
 
         [[self navigationController] presentModalViewController:navigation animated:YES];
+
+        [delegate_ unloadData];
+    }
+}
+
+// CYWebViewDelegate {{{
+- (void) webView:(WebView *)view addMessageToConsole:(NSDictionary *)message {
+#if LogMessages
+    static Pcre irritating("^(?:The page at .* displayed insecure content from .*\\.|Unsafe JavaScript attempt to access frame with URL .* from frame with URL .*\\. Domains, protocols and ports must match\\.)\\n$");
+    if (NSString *data = [message objectForKey:@"message"])
+        if (irritating(data))
+            return;
+
+    NSLog(@"addMessageToConsole:%@", message);
+#endif
+}
+
+- (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) {
+        if (!error_) {
+            NSURL *url(request == nil ? nil : [request URL]);
+
+            if (request_ == nil || [self allowsNavigationAction] || [[request_ URL] isEqual:url])
+                request_ = request;
+            else {
+                if (url != nil)
+                    [self pushRequest:request asPop:NO];
+                [listener ignore];
+            }
+        }
+    }
+}
+
+- (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
+
+    NSURL *url([request URL]);
+    if (url == nil)
+        return;
+
+    if ([frame isEqualToString:@"_open"])
+        [delegate_ openURL:url];
+    else {
+        NSString *scheme([[url scheme] lowercaseString]);
+        if ([scheme isEqualToString:@"mailto"])
+            [self _openMailToURL:url];
+        else
+            [self pushRequest:request asPop:[frame isEqualToString:@"_popup"]];
     }
 
     [listener ignore];
@@ -648,7 +775,7 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
                 for (DOMHTMLBodyElement *body in (id) bodies) {
                     DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
 
-                    bool colored(false);
+                    UIColor *uic(nil);
 
                     if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
                         if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
@@ -659,10 +786,8 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
                             float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
                             float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
 
-                            UIColor *uic(nil);
-
                             if (red == 0xc7 && green == 0xce && blue == 0xd5)
-                                uic = [UIColor groupTableViewBackgroundColor];
+                                uic = [UIColor pinStripeColor];
                             else if (alpha != 0)
                                 uic = [UIColor
                                     colorWithRed:(red / 255)
@@ -670,16 +795,10 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
                                     blue:(blue / 255)
                                     alpha:alpha
                                 ];
-
-                            if (uic != nil) {
-                                colored = true;
-                                [scroller_ setBackgroundColor:uic];
-                            }
                         }
                     }
 
-                    if (!colored)
-                        [scroller_ setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
+                    [scroller_ setBackgroundColor:(uic ?: [UIColor clearColor])];
                     break;
                 }
     }
@@ -691,7 +810,10 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
     if ([frame parentFrame] != nil)
         return;
 
+    if (title_ != nil)
+        [title_ autorelease];
     title_ = [title retain];
+
     [[self navigationItem] setTitle:title_];
 }
 
@@ -700,10 +822,11 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
 
     if ([frame parentFrame] == nil) {
         CYRelease(title_);
-        CYRelease(custom_);
-        CYRelease(style_);
-        CYRelease(function_);
-        CYRelease(closer_);
+        custom_ = nil;
+        style_ = nil;
+        function_ = nil;
+
+        [self setHidesNavigationBar:NO];
 
         // XXX: do we still need to do this?
         [[self navigationItem] setTitle:nil];
@@ -713,6 +836,10 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
 }
 
 - (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
+
     return request;
 }
 
@@ -777,19 +904,12 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
 
         [alert dismissWithClickedButtonIndex:-1 animated:YES];
     } else if ([context isEqualToString:@"submit"]) {
-        switch (button) {
-            case 1:
-            break;
-
-            case 2:
-                if (request_ != nil) {
-                    WebThreadLock();
-                    [webview_ loadRequest:request_];
-                    WebThreadUnlock();
-                }
-            break;
-
-            _nodefault
+        if (button == [alert cancelButtonIndex]) {
+        } else if (button == [alert firstOtherButtonIndex]) {
+            if (request_ != nil) {
+                WebThreadLocked lock;
+                [webview_ loadRequest:request_];
+            }
         }
 
         [alert dismissWithClickedButtonIndex:-1 animated:YES];
@@ -807,8 +927,8 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
 }
 
 - (UIBarButtonItem *) customButton {
-    return [[[UIBarButtonItem alloc]
-        initWithTitle:custom_
+    return custom_ == [NSNull null] ? nil : [[[UIBarButtonItem alloc]
+        initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
         style:[self rightButtonStyle]
         target:self
         action:@selector(customButtonClicked)
@@ -823,21 +943,43 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
     [[self navigationItem] setTitle:UCLocalize("LOADING")];
 }
 
+- (void) layoutRightButton {
+    [[loadingitem_ view] addSubview:indicator_];
+    [[loadingitem_ view] bringSubviewToFront:indicator_];
+}
+
 - (void) applyRightButton {
     if ([self isLoading]) {
         [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
-        // XXX: why do we do this again here?
-        [[loadingitem_ view] addSubview:indicator_];
+        [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
+
+        [indicator_ startAnimating];
         [self applyLoadingTitle];
-    } else if (custom_ != nil) {
-        [[self navigationItem] setRightBarButtonItem:[self customButton] animated:YES];
     } else {
-        [[self navigationItem] setRightBarButtonItem:[self rightButton] animated:YES];
+        [indicator_ stopAnimating];
+
+        [[self navigationItem] setRightBarButtonItem:(
+            custom_ != nil ? [self customButton] : [self rightButton]
+        ) animated:YES];
     }
 }
 
+- (void) didStartLoading {
+    // Overridden in subclasses.
+}
+
 - (void) _didStartLoading {
     [self applyRightButton];
+
+    if ([loading_ count] != 1)
+        return;
+
+    [delegate_ retainNetworkActivityIndicator];
+    [self didStartLoading];
+}
+
+- (void) didFinishLoading {
+    // Overridden in subclasses.
 }
 
 - (void) _didFinishLoading {
@@ -845,10 +987,10 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
         return;
 
     [self applyRightButton];
+    [[self navigationItem] setTitle:title_];
 
-    // XXX: wtf?
-    if (![self isLoading])
-        [[self navigationItem] setTitle:title_];
+    [delegate_ releaseNetworkActivityIndicator];
+    [self didFinishLoading];
 }
 
 - (bool) isLoading {
@@ -857,12 +999,16 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
 
 - (id) initWithWidth:(float)width ofClass:(Class)_class {
     if ((self = [super init]) != nil) {
+        allowsNavigationAction_ = true;
+
         class_ = _class;
         loading_ = [[NSMutableSet alloc] initWithCapacity:5];
 
         indirect_ = [[IndirectDelegate alloc] initWithDelegate:self];
 
-        webview_ = [[[CYWebView alloc] initWithFrame:[[self view] bounds]] autorelease];
+        CGRect bounds([[self view] bounds]);
+
+        webview_ = [[[CYWebView alloc] initWithFrame:bounds] autorelease];
         [webview_ setDelegate:self];
         [self setView:webview_];
 
@@ -879,6 +1025,8 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
         [document setTileSize:CGSizeMake(320, 500)];
 
         [document setBackgroundColor:[UIColor clearColor]];
+
+        // XXX: this is terribly (too?) expensive
         [document setDrawsBackground:NO];
 
         WebView *webview([document webView]);
@@ -893,6 +1041,13 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
         [preferences setCacheModel:WebCacheModelDocumentBrowser];
         [preferences setOfflineWebApplicationCacheEnabled:YES];
 
+#if LogMessages
+        if ([document respondsToSelector:@selector(setAllowsMessaging:)])
+            [document setAllowsMessaging:YES];
+        if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
+            [webview _setAllowsMessaging:YES];
+#endif
+
         if ([webview_ respondsToSelector:@selector(_scrollView)]) {
             scroller_ = [webview_ _scrollView];
 
@@ -920,7 +1075,7 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
         }
 
         [scroller_ setFixedBackgroundPattern:YES];
-        [scroller_ setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
+        [scroller_ setBackgroundColor:[UIColor clearColor]];
         [scroller_ setClipsSubviews:YES];
 
         [scroller_ setBounces:YES];
@@ -943,12 +1098,13 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
             action:@selector(reloadButtonClicked)
         ];
 
-        CGSize indsize = [UIProgressIndicator defaultSizeForStyle:UIProgressIndicatorStyleMediumWhite];
-        indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(15, 5, indsize.width, indsize.height)];
-        [indicator_ setStyle:UIProgressIndicatorStyleMediumWhite];
-        [indicator_ startAnimation];
-        [[loadingitem_ view] addSubview:indicator_];
+        indicator_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]; 
+        [indicator_ setFrame:CGRectMake(15, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
+
+        UITableView *table([[[UITableView alloc] initWithFrame:bounds style:UITableViewStyleGrouped] autorelease]);
+        [webview_ insertSubview:table atIndex:0];
 
+        [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
         [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
         [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
     } return self;
@@ -962,13 +1118,14 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
     return [self initWithWidth:0];
 }
 
-- (void) didDismissModalViewController {
-    if (closer_ != nil)
-        [self callFunction:closer_];
+- (id) initWithURL:(NSURL *)url {
+    if ((self = [self init]) != nil) {
+        [self setURL:url];
+    } return self;
 }
 
 - (void) callFunction:(WebScriptObject *)function {
-    WebThreadLock();
+    WebThreadLocked lock;
 
     WebView *webview([[webview_ _documentView] webView]);
     WebFrame *frame([webview mainFrame]);
@@ -1001,12 +1158,10 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
         settings->setJavaScriptCanOpenWindowsAutomatically(no);*/
 
     [preferences setJavaScriptCanOpenWindowsAutomatically:maybe];
-
-    WebThreadUnlock();
 }
 
 - (void) reloadButtonClicked {
-    [self reloadURL];
+    [self reloadURLWithCache:YES];
 }
 
 - (void) _customButtonClicked {
@@ -1026,4 +1181,99 @@ static void $UIWebViewWebViewDelegate$webViewClose$(UIWebViewWebViewDelegate *se
     return 980;
 }
 
+- (void) setNavigationBarStyle:(NSString *)name {
+    UIBarStyle style;
+    if ([name isEqualToString:@"Black"])
+        style = UIBarStyleBlack;
+    else
+        style = UIBarStyleDefault;
+
+    [[[self navigationController] navigationBar] setBarStyle:style];
+}
+
+- (void) setNavigationBarTintColor:(UIColor *)color {
+    [[[self navigationController] navigationBar] setTintColor:color];
+}
+
+- (void) setHidesBackButton:(bool)value {
+    [[self navigationItem] setHidesBackButton:value];
+}
+
+- (void) setHidesBackButtonByNumber:(NSNumber *)value {
+    [self setHidesBackButton:[value boolValue]];
+}
+
+- (void) dispatchEvent:(NSString *)event {
+    WebThreadLocked lock;
+
+    NSString *script([NSString stringWithFormat:@
+        "(function() {"
+            "var event = this.document.createEvent('Events');"
+            "event.initEvent('%@', false, false);"
+            "this.document.dispatchEvent(event);"
+        "})();"
+    , event]);
+
+    NSMutableArray *frames([NSMutableArray arrayWithObjects:
+        [[[webview_ _documentView] webView] mainFrame]
+    , nil]);
+
+    while (WebFrame *frame = [frames lastObject]) {
+        WebScriptObject *object([frame windowObject]);
+        [object evaluateWebScript:script];
+        [frames removeLastObject];
+        [frames addObjectsFromArray:[frame childFrames]];
+    }
+}
+
+- (bool) hidesNavigationBar {
+    return hidesNavigationBar_;
+}
+
+- (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
+    if (visible_)
+        [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
+}
+
+- (void) setHidesNavigationBar:(bool)value {
+    if (hidesNavigationBar_ != value) {
+        hidesNavigationBar_ = value;
+        [self _setHidesNavigationBar:YES animated:YES];
+    }
+}
+
+- (void) setHidesNavigationBarByNumber:(NSNumber *)value {
+    [self setHidesNavigationBar:[value boolValue]];
+}
+
+- (void) viewWillAppear:(BOOL)animated {
+    visible_ = true;
+
+    if ([self hidesNavigationBar])
+        [self _setHidesNavigationBar:YES animated:animated];
+
+    [self dispatchEvent:@"CydiaViewWillAppear"];
+    [super viewWillAppear:animated];
+}
+
+- (void) viewDidAppear:(BOOL)animated {
+    [super viewDidAppear:animated];
+    [self dispatchEvent:@"CydiaViewDidAppear"];
+}
+
+- (void) viewWillDisappear:(BOOL)animated {
+    [self dispatchEvent:@"CydiaViewWillDisappear"];
+    [super viewWillDisappear:animated];
+
+    if ([self hidesNavigationBar])
+        [self _setHidesNavigationBar:NO animated:animated];
+
+    visible_ = false;
+}
+
+- (void) viewDidDisappear:(BOOL)animated {
+    [super viewDidDisappear:animated];
+    [self dispatchEvent:@"CydiaViewDidDisappear"];
+}
+
 @end