| /* | |
| * Copyright (C) 2016 Apple Inc. All rights reserved. | |
| * | |
| * Redistribution and use in source and binary forms, with or without | |
| * modification, are permitted provided that the following conditions | |
| * are met: | |
| * 1. Redistributions of source code must retain the above copyright | |
| * notice, this list of conditions and the following disclaimer. | |
| * 2. Redistributions in binary form must reproduce the above copyright | |
| * notice, this list of conditions and the following disclaimer in the | |
| * documentation and/or other materials provided with the distribution. | |
| * | |
| * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' | |
| * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, | |
| * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR | |
| * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS | |
| * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR | |
| * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF | |
| * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS | |
| * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN | |
| * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) | |
| * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF | |
| * THE POSSIBILITY OF SUCH DAMAGE. | |
| */ | |
| #import "WebViewController.h" | |
| #import "SettingsViewController.h" | |
| #import "TabViewController.h" | |
| #import <WebKit/WKNavigation.h> | |
| #import <WebKit/WKNavigationDelegate.h> | |
| #import <WebKit/WKPreferencesPrivate.h> | |
| #import <WebKit/WKProcessPoolPrivate.h> | |
| #import <WebKit/WKWebView.h> | |
| #import <WebKit/WKWebViewConfiguration.h> | |
| #import <WebKit/WKWebsiteDataStorePrivate.h> | |
| #import <WebKit/_WKFeature.h> | |
| #import <WebKit/_WKProcessPoolConfiguration.h> | |
| #import <WebKit/_WKWebsiteDataStoreConfiguration.h> | |
| static const NSString * const kURLArgumentString = @"--url"; | |
| @implementation NSURL (BundleURLMethods) | |
| + (NSURL *)__bundleURLForFileURL:(NSURL *)url bundle:(NSBundle *)bundle | |
| { | |
| if (![url.scheme isEqualToString:@"file"]) | |
| return nil; | |
| NSString *resourcePath = [bundle.resourcePath stringByAppendingString:@"/"]; | |
| if (![url.path hasPrefix:resourcePath]) | |
| return nil; | |
| NSURLComponents *bundleComponents = [[NSURLComponents alloc] init]; | |
| bundleComponents.scheme = @"bundle"; | |
| bundleComponents.path = [url.path substringFromIndex:resourcePath.length]; | |
| return [bundleComponents.URL copy]; | |
| } | |
| + (NSURL *)__fileURLForBundleURL:(NSURL *)url bundle:(NSBundle *)bundle | |
| { | |
| if (![url.scheme isEqualToString:@"bundle"]) | |
| return nil; | |
| return [bundle.resourceURL URLByAppendingPathComponent:url.path]; | |
| } | |
| @end | |
| @interface URLTextField : UITextField | |
| @end | |
| @implementation URLTextField | |
| - (CGRect)clearButtonRectForBounds:(CGRect)bounds | |
| { | |
| CGRect rect = [super clearButtonRectForBounds:bounds]; | |
| rect.origin.x = bounds.origin.x + bounds.size.width - rect.size.width - 16; | |
| return rect; | |
| } | |
| - (CGRect)editingRectForBounds:(CGRect)bounds | |
| { | |
| CGRect rect = [super editingRectForBounds:bounds]; | |
| CGRect clearButtonRect = [self clearButtonRectForBounds:bounds]; | |
| rect.size.width = MIN(rect.size.width, clearButtonRect.origin.x - 3 - rect.origin.x); | |
| return rect; | |
| } | |
| @end | |
| @interface WebViewController () <WKNavigationDelegate> { | |
| WKWebsiteDataStore *_dataStore; | |
| WKWebView *_currentWebView; | |
| NSURL *_initialURL; | |
| NSLayoutConstraint *_urlFieldContainerAboveKeyboardConstraint; | |
| } | |
| - (WKWebView *)createWebView; | |
| - (void)removeWebView:(WKWebView *)webView; | |
| - (void)setCurrentWebView:(WKWebView *)webView; | |
| @end | |
| void* EstimatedProgressContext = &EstimatedProgressContext; | |
| void* TitleContext = &TitleContext; | |
| void* URLContext = &URLContext; | |
| @implementation WebViewController | |
| - (void)viewDidLoad | |
| { | |
| [super viewDidLoad]; | |
| self.webViews = [[NSMutableArray alloc] initWithCapacity:1]; | |
| #pragma clang diagnostic push | |
| #pragma clang diagnostic ignored "-Wdeprecated-declarations" | |
| self.tabViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"idTabViewController"]; | |
| #pragma clang diagnostic pop | |
| self.tabViewController.parent = self; | |
| self.tabViewController.modalPresentationStyle = UIModalPresentationPopover; | |
| #pragma clang diagnostic push | |
| #pragma clang diagnostic ignored "-Wdeprecated-declarations" | |
| self.settingsViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"idSettingsViewController"]; | |
| #pragma clang diagnostic pop | |
| self.settingsViewController.parent = self; | |
| self.settingsViewController.modalPresentationStyle = UIModalPresentationPopover; | |
| // Only active while editing the URL, so that focusing an input in web content doesn't resize the web view. | |
| _urlFieldContainerAboveKeyboardConstraint = [self.urlFieldContainer.bottomAnchor constraintLessThanOrEqualToAnchor:self.view.keyboardLayoutGuide.topAnchor]; | |
| if ([self.urlField respondsToSelector:@selector(setCornerConfiguration:)]) | |
| [self.urlField setValue:[NSClassFromString(@"UICornerConfiguration") performSelector:@selector(capsuleConfiguration)] forKey:@"cornerConfiguration"]; | |
| self.urlField.backgroundColor = [UIColor colorWithDynamicProvider:^(UITraitCollection *traitCollection) { | |
| if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) | |
| return [UIColor colorWithWhite:1 alpha:0.08]; | |
| return [UIColor colorWithWhite:0 alpha:0.05]; | |
| }]; | |
| self.urlField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 0)]; | |
| self.urlField.leftViewMode = UITextFieldViewModeAlways; | |
| for (UIBarButtonItem *item in self.toolbar.items) { | |
| if ([item respondsToSelector:@selector(setHidesSharedBackground:)]) | |
| [item setValue:@YES forKey:@"hidesSharedBackground"]; | |
| } | |
| WKWebView *webView = [self createWebView]; | |
| [webView loadRequest:[NSURLRequest requestWithURL:[self targetURLorDefaultURL]]]; | |
| [self setCurrentWebView:webView]; | |
| } | |
| - (void)didReceiveMemoryWarning | |
| { | |
| [super didReceiveMemoryWarning]; | |
| } | |
| #pragma mark Actions | |
| - (IBAction)reload:(id)sender | |
| { | |
| [self.currentWebView reload]; | |
| } | |
| - (IBAction)goBack:(id)sender | |
| { | |
| [self.currentWebView goBack]; | |
| } | |
| - (IBAction)goForward:(id)sender | |
| { | |
| [self.currentWebView goForward]; | |
| } | |
| - (IBAction)urlFieldEditingBegan:(id)sender | |
| { | |
| self.urlField.selectedTextRange = [self.urlField textRangeFromPosition:self.urlField.beginningOfDocument toPosition:self.urlField.endOfDocument]; | |
| _urlFieldContainerAboveKeyboardConstraint.active = YES; | |
| } | |
| - (IBAction)urlFieldEditingEnded:(id)sender | |
| { | |
| _urlFieldContainerAboveKeyboardConstraint.active = NO; | |
| } | |
| - (IBAction)navigateTo:(id)sender | |
| { | |
| [self.urlField resignFirstResponder]; | |
| NSString* requestedDestination = self.urlField.text; | |
| if ([requestedDestination rangeOfString:@"^[\\p{Alphabetic}]+:" options:(NSRegularExpressionSearch | NSCaseInsensitiveSearch | NSAnchoredSearch)].location == NSNotFound) | |
| requestedDestination = [@"http://" stringByAppendingString:requestedDestination]; | |
| NSURL* requestedURL = [NSURL URLWithString:requestedDestination]; | |
| if ([requestedURL.scheme isEqualToString:@"bundle"]) { | |
| NSBundle *frameworkBundle = [NSBundle bundleForClass:[WebViewController class]]; | |
| requestedURL = [NSURL __fileURLForBundleURL:requestedURL bundle:frameworkBundle]; | |
| [self.currentWebView loadFileURL:requestedURL allowingReadAccessToURL:frameworkBundle.resourceURL]; | |
| } | |
| [self.currentWebView loadRequest:[NSURLRequest requestWithURL:requestedURL]]; | |
| } | |
| - (IBAction)showTabs:(id)sender | |
| { | |
| [self presentViewController:self.tabViewController animated:YES completion:nil]; | |
| self.tabViewController.popoverPresentationController.barButtonItem = self.tabButton; | |
| } | |
| - (IBAction)showSettings:(id)sender | |
| { | |
| UIPopoverPresentationController *presentationController = [self.settingsViewController popoverPresentationController]; | |
| presentationController.barButtonItem = self.settingsButton; | |
| [self presentViewController:self.settingsViewController animated:YES completion:nil]; | |
| } | |
| #pragma mark Public methods | |
| @dynamic currentWebView; | |
| - (WKWebView *)currentWebView | |
| { | |
| return _currentWebView; | |
| } | |
| - (WKWebsiteDataStore *)dataStore | |
| { | |
| if (!_dataStore) { | |
| _WKWebsiteDataStoreConfiguration *dataStoreConfiguration = [[_WKWebsiteDataStoreConfiguration alloc] init]; | |
| dataStoreConfiguration.webPushMachServiceName = @"com.apple.webkit.webpushd.service"; | |
| _dataStore = [[WKWebsiteDataStore alloc] _initWithConfiguration:dataStoreConfiguration]; | |
| } | |
| return _dataStore; | |
| } | |
| - (void)setCurrentWebView:(WKWebView *)webView | |
| { | |
| [_currentWebView removeObserver:self forKeyPath:@"estimatedProgress" context:EstimatedProgressContext]; | |
| [_currentWebView removeObserver:self forKeyPath:@"URL" context:URLContext]; | |
| [_currentWebView removeFromSuperview]; | |
| _currentWebView = webView; | |
| [_currentWebView addObserver:self forKeyPath:@"estimatedProgress" options:(NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew) context:EstimatedProgressContext]; | |
| [_currentWebView addObserver:self forKeyPath:@"URL" options:(NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew) context:URLContext]; | |
| [self.webViewContainer addSubview:_currentWebView]; | |
| } | |
| - (void)selectWebViewAtIndex:(NSUInteger)index | |
| { | |
| if (index >= self.webViews.count) | |
| return; | |
| self.currentWebView = self.webViews[index]; | |
| } | |
| - (void)removeWebViewAtIndex:(NSUInteger)index | |
| { | |
| if (index >= self.webViews.count) | |
| return; | |
| [self removeWebView:self.webViews[index]]; | |
| } | |
| - (void)addWebView | |
| { | |
| self.currentWebView = [self createWebView]; | |
| } | |
| - (NSURL *)currentURL | |
| { | |
| return self.currentWebView.URL; | |
| } | |
| #pragma mark Internal methods | |
| - (void)updateCapturePreviewPreference | |
| { | |
| BOOL enabled = [self.settingsViewController showsCapturePreviewInPrompt]; | |
| for (WKWebView *webView in self.webViews) | |
| [self setCapturePreviewEnabled:enabled forPreferences:webView.configuration.preferences]; | |
| } | |
| - (void)setCapturePreviewEnabled:(BOOL)enabled forPreferences:(WKPreferences *)preferences | |
| { | |
| for (_WKFeature *feature in [WKPreferences _features]) { | |
| if ([feature.key isEqualToString:@"CaptureDevicePreviewInPromptEnabled"]) { | |
| [preferences _setEnabled:enabled forFeature:feature]; | |
| return; | |
| } | |
| } | |
| } | |
| - (WKWebView *)createWebView | |
| { | |
| WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; | |
| #if TARGET_OS_SIMULATOR | |
| configuration.preferences._mockCaptureDevicesEnabled = YES; | |
| #endif | |
| [self setCapturePreviewEnabled:[self.settingsViewController showsCapturePreviewInPrompt] forPreferences:configuration.preferences]; | |
| configuration.preferences._notificationsEnabled = YES; | |
| configuration.preferences._pushAPIEnabled = YES; | |
| configuration.preferences._notificationEventEnabled = YES; | |
| configuration.preferences._appBadgeEnabled = YES; | |
| configuration.preferences.elementFullscreenEnabled = YES; | |
| configuration.websiteDataStore = [self dataStore]; | |
| #pragma clang diagnostic push | |
| #pragma clang diagnostic ignored "-Wdeprecated-declarations" | |
| _WKProcessPoolConfiguration *processConfiguration = [[_WKProcessPoolConfiguration alloc] init]; | |
| processConfiguration.usesWebProcessCache = YES; | |
| configuration.processPool = [[WKProcessPool alloc] _initWithConfiguration:processConfiguration]; | |
| #pragma clang diagnostic pop | |
| WKWebView *webView = [[WKWebView alloc] initWithFrame:self.webViewContainer.bounds configuration:configuration]; | |
| webView.inspectable = YES; | |
| webView.navigationDelegate = self; | |
| webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; | |
| [webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:TitleContext]; | |
| [self.webViews addObject:webView]; | |
| [self.tabViewController.tableView reloadData]; | |
| return webView; | |
| } | |
| - (void)removeWebView:(WKWebView *)webView | |
| { | |
| NSUInteger index = [self.webViews indexOfObject:webView]; | |
| if (index != NSNotFound) { | |
| [self.webViews[index] removeObserver:self forKeyPath:@"title" context:TitleContext]; | |
| [self.webViews removeObjectAtIndex:index]; | |
| } if (!self.webViews.count) | |
| [self createWebView]; | |
| if (index >= self.webViews.count) | |
| index = self.webViews.count - 1; | |
| [self setCurrentWebView:self.webViews[index]]; | |
| [self.tabViewController.tableView reloadData]; | |
| } | |
| - (NSString *)addProtocolIfNecessary:(NSString *)address | |
| { | |
| if ([address rangeOfString:@"://"].length > 0) | |
| return address; | |
| if ([address hasPrefix:@"data:"]) | |
| return address; | |
| if ([address hasPrefix:@"about:"]) | |
| return address; | |
| return [@"http://" stringByAppendingString:address]; | |
| } | |
| - (NSURL *)targetURLorDefaultURL | |
| { | |
| if (_initialURL) | |
| return _initialURL; | |
| NSArray *args = [[NSProcessInfo processInfo] arguments]; | |
| const NSUInteger targetURLIndex = [args indexOfObject:kURLArgumentString]; | |
| // FIXME: Add support for passing file URLs on the command line. | |
| if (targetURLIndex != NSNotFound && targetURLIndex + 1 < [args count]) { | |
| NSString *targetURL = [self addProtocolIfNecessary:[args objectAtIndex:targetURLIndex + 1]]; | |
| NSURL *url = [NSURL URLWithString:targetURL]; | |
| if (url) | |
| return url; | |
| } | |
| return [NSURL URLWithString:[self.settingsViewController defaultURL]]; | |
| } | |
| #pragma mark Navigation Delegate | |
| - (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error | |
| { | |
| [webView loadHTMLString:[error description] baseURL:nil]; | |
| } | |
| #pragma mark KVO | |
| - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context | |
| { | |
| if (context == EstimatedProgressContext) { | |
| float value = [[change valueForKey:NSKeyValueChangeNewKey] floatValue]; | |
| [self.progressView setProgress:value animated:YES]; | |
| } else if (context == URLContext) { | |
| NSURL *newURLValue = [change valueForKey:NSKeyValueChangeNewKey]; | |
| if ([newURLValue isKindOfClass:[NSURL class]]) { | |
| if ([newURLValue.scheme isEqualToString:@"file"]) | |
| newURLValue = [NSURL __bundleURLForFileURL:newURLValue bundle:[NSBundle bundleForClass:[WebViewController class]]]; | |
| self.urlField.text = [newURLValue absoluteString]; | |
| } else if ([newURLValue isKindOfClass:[NSNull class]]) | |
| self.urlField.text = @""; | |
| } else if (context == TitleContext) | |
| [self.tabViewController.tableView reloadData]; | |
| else | |
| [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; | |
| } | |
| @end |