]> git.saurik.com Git - cydia.git/blobdiff - CyteKit/WebViewController.mm
Swap awkward va_list hack for awkward switch hack.
[cydia.git] / CyteKit / WebViewController.mm
index 374cbef10b14bc84dca12e063837d81840205a5c..9d1866a66337cd7df1034698055763762a2823ec 100644 (file)
@@ -1,15 +1,14 @@
 #include "CyteKit/UCPlatform.h"
-#include "CyteKit/WebViewController.h"
-
-#include "CyteKit/MFMailComposeViewController-MailToURL.h"
-
-#include "iPhonePrivate.h"
 
 #include "CyteKit/IndirectDelegate.h"
 #include "CyteKit/Localize.h"
-#include "CyteKit/WebViewController.h"
-#include "CyteKit/PerlCompatibleRegEx.hpp"
+#include "CyteKit/MFMailComposeViewController-MailToURL.h"
+#include "CyteKit/RegEx.hpp"
 #include "CyteKit/WebThreadLocked.hpp"
+#include "CyteKit/WebViewController.h"
+
+#include "iPhonePrivate.h"
+#include <Menes/ObjectHandle.h>
 
 //#include <QuartzCore/CALayer.h>
 // XXX: fix the minimum requirement
@@ -17,18 +16,11 @@ extern NSString * const kCAFilterNearest;
 
 #include <WebCore/WebCoreThread.h>
 
-#import <WebKit/WebKitErrors.h>
-#import <WebKit/WebPreferences.h>
-
-#include <WebKit/DOMCSSPrimitiveValue.h>
-#include <WebKit/DOMCSSStyleDeclaration.h>
-#include <WebKit/DOMDocument.h>
-#include <WebKit/DOMHTMLBodyElement.h>
-#include <WebKit/DOMRGBColor.h>
-
 #include <dlfcn.h>
 #include <objc/runtime.h>
 
+#include "Substrate.hpp"
+
 #define ForSaurik 0
 #define DefaultTimeout_ 120.0
 
@@ -45,11 +37,6 @@ static Class $MFMailComposeViewController;
 
 float CYScrollViewDecelerationRateNormal;
 
-@interface WebView (Apple)
-- (void) _setLayoutInterval:(float)interval;
-- (void) _setAllowsMessaging:(BOOL)allows;
-@end
-
 @interface WebFrame (Cydia)
 - (void) cydia$updateHeight;
 @end
@@ -70,6 +57,57 @@ float CYScrollViewDecelerationRateNormal;
 
 @end
 
+// Diversion {{{
+static _H<NSMutableSet> Diversions_;
+
+@implementation Diversion {
+    RegEx pattern_;
+    _H<NSString> key_;
+    _H<NSString> format_;
+}
+
+- (id) initWithFrom:(NSString *)from to:(NSString *)to {
+    if ((self = [super init]) != nil) {
+        pattern_ = [from UTF8String];
+        key_ = from;
+        format_ = to;
+    } return self;
+}
+
+- (NSString *) divert:(NSString *)url {
+    return !pattern_(url) ? nil : pattern_->*format_;
+}
+
++ (NSURL *) divertURL:(NSURL *)url {
+  divert:
+    NSString *href([url absoluteString]);
+
+    for (Diversion *diversion in (id) Diversions_)
+        if (NSString *diverted = [diversion divert:href]) {
+#if !ForRelease
+            NSLog(@"div: %@", diverted);
+#endif
+            url = [NSURL URLWithString:diverted];
+            goto divert;
+        }
+
+    return url;
+}
+
+- (NSString *) key {
+    return key_;
+}
+
+- (NSUInteger) hash {
+    return [key_ hash];
+}
+
+- (BOOL) isEqual:(Diversion *)object {
+    return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
+}
+
+@end
+// }}}
 /* Indirect Delegate {{{ */
 @implementation IndirectDelegate
 
@@ -100,7 +138,7 @@ float CYScrollViewDecelerationRateNormal;
     // XXX: WebThreadCreateNSInvocation returns nil
 
 #if ShowInternals
-    fprintf(stderr, "[%s]R?%s\n", class_getName(self->isa), sel_getName(sel));
+    fprintf(stderr, "[%s]R?%s\n", class_getName(object_getClass(self)), sel_getName(sel));
 #endif
 
     return delegate_ == nil ? NO : [delegate_ respondsToSelector:sel];
@@ -111,7 +149,7 @@ float CYScrollViewDecelerationRateNormal;
         return method;
 
 #if ShowInternals
-    fprintf(stderr, "[%s]S?%s\n", class_getName(self->isa), sel_getName(sel));
+    fprintf(stderr, "[%s]S?%s\n", class_getName(object_getClass(self)), sel_getName(sel));
 #endif
 
     if (delegate_ != nil)
@@ -131,7 +169,43 @@ float CYScrollViewDecelerationRateNormal;
 @end
 /* }}} */
 
-@implementation CyteWebViewController
+@implementation CyteWebViewController {
+    _H<CyteWebView, 1> webview_;
+    _transient UIScrollView *scroller_;
+
+    _H<UIActivityIndicatorView> indicator_;
+    _H<IndirectDelegate, 1> indirect_;
+    _H<NSURLAuthenticationChallenge> challenge_;
+
+    bool error_;
+    _H<NSURLRequest> request_;
+    bool ready_;
+
+    _transient NSNumber *sensitive_;
+    _H<NSURL> appstore_;
+
+    _H<NSString> title_;
+    _H<NSMutableSet> loading_;
+
+    _H<NSMutableSet> registered_;
+    _H<NSTimer> timer_;
+
+    // XXX: NSString * or UIImage *
+    _H<NSObject> custom_;
+    _H<NSString> style_;
+
+    _H<WebScriptObject> function_;
+
+    float width_;
+    Class class_;
+
+    _H<UIBarButtonItem> reloaditem_;
+    _H<UIBarButtonItem> loadingitem_;
+
+    bool visible_;
+    bool hidesNavigationBar_;
+    bool allowsNavigationAction_;
+}
 
 #if ShowInternals
 #include "CyteKit/UCInternal.h"
@@ -151,10 +225,12 @@ float CYScrollViewDecelerationRateNormal;
     dlopen("/System/Library/Frameworks/MessageUI.framework/MessageUI", RTLD_GLOBAL | RTLD_LAZY);
     $MFMailComposeViewController = objc_getClass("MFMailComposeViewController");
 
-    if (float *_UIScrollViewDecelerationRateNormal = reinterpret_cast<float *>(dlsym(RTLD_DEFAULT, "UIScrollViewDecelerationRateNormal")))
+    if (CGFloat *_UIScrollViewDecelerationRateNormal = reinterpret_cast<CGFloat *>(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;
+
+    Diversions_ = [NSMutableSet setWithCapacity:0];
 }
 
 - (bool) retainsNetworkActivityIndicator {
@@ -166,7 +242,7 @@ float CYScrollViewDecelerationRateNormal;
         [loading_ removeAllObjects];
 
         if ([self retainsNetworkActivityIndicator])
-            [delegate_ releaseNetworkActivityIndicator];
+            [self.delegate releaseNetworkActivityIndicator];
     }
 }
 
@@ -188,8 +264,16 @@ float CYScrollViewDecelerationRateNormal;
     return (CyteWebView *) [self view];
 }
 
+- (CyteWebViewController *) indirect {
+    return (CyteWebViewController *) (IndirectDelegate *) indirect_;
+}
+
++ (void) addDiversion:(Diversion *)diversion {
+    [Diversions_ addObject:diversion];
+}
+
 - (NSURL *) URLWithURL:(NSURL *)url {
-    return url;
+    return [Diversion divertURL:url];
 }
 
 - (NSURLRequest *) requestWithURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy referrer:(NSString *)referrer {
@@ -209,6 +293,10 @@ float CYScrollViewDecelerationRateNormal;
     request_ = request;
 }
 
+- (NSURLRequest *) request {
+    return request_;
+}
+
 - (void) setURL:(NSURL *)url {
     [self setURL:url withReferrer:nil];
 }
@@ -414,7 +502,7 @@ float CYScrollViewDecelerationRateNormal;
     NSURL *url([request URL]);
 
     // XXX: filter to internal usage?
-    CyteViewController *page([delegate_ pageForURL:url forExternal:NO withReferrer:referrer]);
+    CyteViewController *page([self.delegate pageForURL:url forExternal:NO withReferrer:referrer]);
 
     if (page == nil) {
         CyteWebViewController *browser([[[class_ alloc] init] autorelease]);
@@ -422,8 +510,8 @@ float CYScrollViewDecelerationRateNormal;
         page = browser;
     }
 
-    [page setDelegate:delegate_];
-    [page setPageColor:color_];
+    [page setDelegate:self.delegate];
+    [page setPageColor:self.pageColor];
 
     if (!pop) {
         [[self navigationItem] setTitle:title_];
@@ -432,7 +520,7 @@ float CYScrollViewDecelerationRateNormal;
     } else {
         UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
 
-        [navigation setDelegate:delegate_];
+        [navigation setDelegate:self.delegate];
 
         [[page navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
             initWithTitle:UCLocalize("CLOSE")
@@ -448,10 +536,10 @@ float CYScrollViewDecelerationRateNormal;
 // CyteWebViewDelegate {{{
 - (void) webView:(WebView *)view addMessageToConsole:(NSDictionary *)message {
 #if LogMessages
-    static Pcre irritating("^(?"
+    static RegEx 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$");
+    ")\\n");
 
     if (NSString *data = [message objectForKey:@"message"])
         if (irritating(data))
@@ -466,10 +554,39 @@ float CYScrollViewDecelerationRateNormal;
     NSLog(@"decidePolicyForNavigationAction:%@ request:%@ %@ frame:%@", action, request, [request allHTTPHeaderFields], frame);
 #endif
 
+    NSURL *url(request == nil ? nil : [request URL]);
+    NSString *scheme([[url scheme] lowercaseString]);
+    NSString *absolute([[url absoluteString] lowercaseString]);
+
+    if (
+        [scheme isEqualToString:@"itms"] ||
+        [scheme isEqualToString:@"itmss"] ||
+        [scheme isEqualToString:@"itms-apps"] ||
+        [scheme isEqualToString:@"itms-appss"] ||
+        [absolute hasPrefix:@"http://itunes.apple.com/"] ||
+        [absolute hasPrefix:@"https://itunes.apple.com/"] ||
+    false) {
+        appstore_ = url;
+
+        UIAlertView *alert = [[[UIAlertView alloc]
+            initWithTitle:UCLocalize("APP_STORE_REDIRECT")
+            message:nil
+            delegate:self
+            cancelButtonTitle:UCLocalize("CANCEL")
+            otherButtonTitles:
+                UCLocalize("ALLOW"),
+            nil
+        ] autorelease];
+
+        [alert setContext:@"itmsappss"];
+        [alert show];
+
+        [listener ignore];
+        return;
+    }
+
     if ([frame parentFrame] == nil) {
         if (!error_) {
-            NSURL *url(request == nil ? nil : [request URL]);
-
             if (request_ != nil && ![[request_ URL] isEqual:url] && ![self allowsNavigationAction]) {
                 if (url != nil)
                     [self pushRequest:request forAction:action asPop:NO];
@@ -481,7 +598,7 @@ float CYScrollViewDecelerationRateNormal;
 
 - (void) webView:(WebView *)view didDecidePolicy:(CYWebPolicyDecision)decision forNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame {
 #if LogBrowser
-    NSLog(@"didDecidePolicy:%u forNavigationAction:%@ request:%@ frame:%@", decision, action, request, [request allHTTPHeaderFields], frame);
+    NSLog(@"didDecidePolicy:%u forNavigationAction:%@ request:%@ %@ frame:%@", decision, action, request, [request allHTTPHeaderFields], frame);
 #endif
 
     if ([frame parentFrame] == nil) {
@@ -512,7 +629,7 @@ float CYScrollViewDecelerationRateNormal;
         return;
 
     if ([name isEqualToString:@"_open"])
-        [delegate_ openURL:url];
+        [self.delegate openURL:url];
     else {
         NSString *scheme([[url scheme] lowercaseString]);
         if ([scheme isEqualToString:@"mailto"])
@@ -536,7 +653,6 @@ float CYScrollViewDecelerationRateNormal;
 #endif
 
     if ([frame parentFrame] == nil) {
-        loaded_ = true;
     }
 }
 
@@ -589,8 +705,8 @@ float CYScrollViewDecelerationRateNormal;
                         }
                     }
 
-                    [self setPageColor:uic];
-                    [scroller_ setBackgroundColor:color_];
+                    [super setPageColor:uic];
+                    [scroller_ setBackgroundColor:self.pageColor];
                     break;
                 }
     }
@@ -659,7 +775,7 @@ float CYScrollViewDecelerationRateNormal;
     [alert addTextFieldWithValue:@"" label:UCLocalize("PASSWORD")];
 
     UITextField *username([alert textFieldAtIndex:0]); {
-        UITextInputTraits *traits([username textInputTraits]);
+        NSObject<UITextInputTraits> *traits([username textInputTraits]);
         [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
         [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
         [traits setKeyboardType:UIKeyboardTypeASCIICapable];
@@ -667,7 +783,7 @@ float CYScrollViewDecelerationRateNormal;
     }
 
     UITextField *password([alert textFieldAtIndex:1]); {
-        UITextInputTraits *traits([password textInputTraits]);
+        NSObject<UITextInputTraits> *traits([password textInputTraits]);
         [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
         [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
         [traits setKeyboardType:UIKeyboardTypeASCIICapable];
@@ -687,6 +803,14 @@ float CYScrollViewDecelerationRateNormal;
     return request;
 }
 
+- (NSURLRequest *) webThreadWebView:(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;
+}
+
 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
     return [self _allowJavaScriptPanel];
 }
@@ -739,6 +863,13 @@ float CYScrollViewDecelerationRateNormal;
 
         challenge_ = nil;
 
+        [alert dismissWithClickedButtonIndex:-1 animated:YES];
+    } else if ([context isEqualToString:@"itmsappss"]) {
+        if (button == [alert cancelButtonIndex]) {
+        } else if (button == [alert firstOtherButtonIndex]) {
+            [self.delegate openURL:appstore_];
+        }
+
         [alert dismissWithClickedButtonIndex:-1 animated:YES];
     } else if ([context isEqualToString:@"submit"]) {
         if (button == [alert cancelButtonIndex]) {
@@ -765,9 +896,9 @@ float CYScrollViewDecelerationRateNormal;
 
 - (UIBarButtonItem *) customButton {
     if (custom_ == nil)
-        return nil;
+        return [self rightButton];
     else if ((/*clang:*/id) custom_ == [NSNull null])
-        return (UIBarButtonItem *) [NSNull null];
+        return nil;
 
     return [[[UIBarButtonItem alloc]
         initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
@@ -820,14 +951,7 @@ float CYScrollViewDecelerationRateNormal;
         [self applyLoadingTitle];
     } else {
         [indicator_ stopAnimating];
-
-        UIBarButtonItem *button([self customButton]);
-        if (button == nil)
-            button = [self rightButton];
-        else if (button == (UIBarButtonItem *) [NSNull null])
-            button = nil;
-
-        [[self navigationItem] setRightBarButtonItem:button animated:YES];
+        [[self navigationItem] setRightBarButtonItem:[self customButton] animated:YES];
     }
 }
 
@@ -842,7 +966,7 @@ float CYScrollViewDecelerationRateNormal;
         return;
 
     if ([self retainsNetworkActivityIndicator])
-        [delegate_ retainNetworkActivityIndicator];
+        [self.delegate retainNetworkActivityIndicator];
 
     [self didStartLoading];
 }
@@ -859,7 +983,7 @@ float CYScrollViewDecelerationRateNormal;
     [[self navigationItem] setTitle:title_];
 
     if ([self retainsNetworkActivityIndicator])
-        [delegate_ releaseNetworkActivityIndicator];
+        [self.delegate releaseNetworkActivityIndicator];
 
     [self didFinishLoading];
 }
@@ -873,7 +997,7 @@ float CYScrollViewDecelerationRateNormal;
         width_ = width;
         class_ = _class;
 
-        [self setPageColor:nil];
+        [super setPageColor:nil];
 
         allowsNavigationAction_ = true;
 
@@ -892,7 +1016,7 @@ float CYScrollViewDecelerationRateNormal;
             initWithTitle:(kCFCoreFoundationVersionNumber >= 800 ? @"       " : @" ")
             style:UIBarButtonItemStylePlain
             target:self
-            action:@selector(reloadButtonClicked)
+            action:@selector(customButtonClicked)
         ] autorelease];
 
         UIActivityIndicatorViewStyle style;
@@ -914,8 +1038,13 @@ float CYScrollViewDecelerationRateNormal;
     } return self;
 }
 
+static _H<NSString> UserAgent_;
++ (void) setApplicationNameForUserAgent:(NSString *)userAgent {
+    UserAgent_ = userAgent;
+}
+
 - (NSString *) applicationNameForUserAgent {
-    return nil;
+    return UserAgent_;
 }
 
 - (void) loadView {
@@ -947,7 +1076,7 @@ float CYScrollViewDecelerationRateNormal;
         [preferences _setLayoutInterval:0];
 
     [preferences setCacheModel:WebCacheModelDocumentBrowser];
-    [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
+    [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
 
     if ([preferences respondsToSelector:@selector(setOfflineWebApplicationCacheEnabled:)])
         [preferences setOfflineWebApplicationCacheEnabled:YES];
@@ -995,7 +1124,7 @@ float CYScrollViewDecelerationRateNormal;
     [webview_ setBackgroundColor:nil];
 
     [scroller_ setFixedBackgroundPattern:YES];
-    [scroller_ setBackgroundColor:color_];
+    [scroller_ setBackgroundColor:self.pageColor];
     [scroller_ setClipsSubviews:YES];
 
     [scroller_ setBounces:YES];
@@ -1004,6 +1133,13 @@ float CYScrollViewDecelerationRateNormal;
 
     [self setViewportWidth:width_];
 
+    if ([[UIColor groupTableViewBackgroundColor] isEqual:[UIColor clearColor]]) {
+        UITableView *table([[[UITableView alloc] initWithFrame:[webview_ bounds] style:UITableViewStyleGrouped] autorelease]);
+        [table setScrollsToTop:NO];
+        [webview_ insertSubview:table atIndex:0];
+        [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
+    }
+
     [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
 
     ready_ = false;
@@ -1038,16 +1174,34 @@ float CYScrollViewDecelerationRateNormal;
     } return self;
 }
 
++ (void) _lockJavaScript:(WebPreferences *)preferences {
+    WebThreadLocked lock;
+    [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
+}
+
 - (void) callFunction:(WebScriptObject *)function {
     WebThreadLocked lock;
 
     WebView *webview([[[self webView] _documentView] webView]);
-    WebFrame *frame([webview mainFrame]);
+    WebPreferences *preferences([webview preferences]);
 
+    [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
+    if ([webview respondsToSelector:@selector(_preferencesChanged:)])
+        [webview _preferencesChanged:preferences];
+    else
+        [webview _preferencesChangedNotification:[NSNotification notificationWithName:@"" object:preferences]];
+
+    WebFrame *frame([webview mainFrame]);
     JSGlobalContextRef context([frame globalContext]);
+
     JSObjectRef object([function JSObject]);
     if ($JSObjectCallAsFunction != NULL)
         ($JSObjectCallAsFunction)(context, object, NULL, 0, NULL, NULL);
+
+    // XXX: the JavaScript code submits a form, which seems to happen asynchronously
+    NSObject *target([CyteWebViewController class]);
+    [NSObject cancelPreviousPerformRequestsWithTarget:target selector:@selector(_lockJavaScript:) object:preferences];
+    [target performSelector:@selector(_lockJavaScript:) withObject:preferences afterDelay:1];
 }
 
 - (void) reloadButtonClicked {
@@ -1207,3 +1361,29 @@ float CYScrollViewDecelerationRateNormal;
 }
 
 @end
+
+MSClassHook(WAKWindow)
+
+static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
+    CGSize size([[UIScreen mainScreen] bounds].size);
+    /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
+        if ([$WAKWindow hasLandscapeOrientation])
+            std::swap(size.width, size.height);*/
+    return size;
+}
+
+static struct WAKWindow$screenSize { WAKWindow$screenSize() {
+    if ($WAKWindow != NULL)
+        if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
+            method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
+} } WAKWindow$screenSize;;
+
+MSClassHook(NSUserDefaults)
+
+MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
+    if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
+        return [NSString stringWithFormat:@"%@/%@/%@", NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject, NSBundle.mainBundle.bundleIdentifier, @"LocalStorage"];
+    return _NSUserDefaults$objectForKey$(self, _cmd, key);
+}
+
+CYHook(NSUserDefaults, objectForKey$, objectForKey:)