| /* | |
| * Copyright (C) 2010-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 "WK2BrowserWindowController.h" | |
| #import "AppDelegate.h" | |
| #import "SettingsController.h" | |
| #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 270000 | |
| #import <AppKit/NSRefreshController.h> | |
| #endif | |
| #import <Metal/Metal.h> | |
| #import <PDFKit/PDFDocument.h> | |
| #import <QuartzCore/CATextLayer.h> | |
| #import <SecurityInterface/SFCertificateTrustPanel.h> | |
| #import <UniformTypeIdentifiers/UniformTypeIdentifiers.h> | |
| #import <WebKit/WKDownload.h> | |
| #import <WebKit/WKDownloadDelegate.h> | |
| #import <WebKit/WKFrameInfo.h> | |
| #import <WebKit/WKNavigationActionPrivate.h> | |
| #import <WebKit/WKNavigationDelegate.h> | |
| #import <WebKit/WKNavigationDelegatePrivate.h> | |
| #import <WebKit/WKOpenPanelParametersPrivate.h> | |
| #import <WebKit/WKPreferencesPrivate.h> | |
| #import <WebKit/WKUIDelegate.h> | |
| #import <WebKit/WKUIDelegatePrivate.h> | |
| #import <WebKit/WKWebViewConfigurationPrivate.h> | |
| #import <WebKit/WKWebViewPrivate.h> | |
| #import <WebKit/WKWebViewPrivateForTesting.h> | |
| #import <WebKit/WKWebpagePreferences.h> | |
| #import <WebKit/WKWebpagePreferencesPrivate.h> | |
| #import <WebKit/WKWebsiteDataStorePrivate.h> | |
| #import <WebKit/WebNSURLExtras.h> | |
| #import <WebKit/_WKArchiveConfiguration.h> | |
| #import <WebKit/_WKFindDelegate.h> | |
| #import <WebKit/_WKFindOptions.h> | |
| #import <WebKit/_WKIconLoadingDelegate.h> | |
| #import <WebKit/_WKInspector.h> | |
| #import <WebKit/_WKInspectorDelegate.h> | |
| #import <WebKit/_WKLinkIconParameters.h> | |
| #import <WebKit/_WKUserInitiatedAction.h> | |
| #import <objc/runtime.h> | |
| static void* keyValueObservingContext = &keyValueObservingContext; | |
| static void* tabSelectionObservingContext = &tabSelectionObservingContext; | |
| static const int testHeaderBannerHeight = 42; | |
| static const int testFooterBannerHeight = 58; | |
| @interface MiniBrowserNSTextFinder : NSTextFinder | |
| @property (nonatomic, copy) dispatch_block_t hideInterfaceCallback; | |
| @end | |
| @implementation MiniBrowserNSTextFinder | |
| - (void)performAction:(NSTextFinderAction)op | |
| { | |
| [super performAction:op]; | |
| if (op == NSTextFinderActionHideFindInterface && _hideInterfaceCallback) | |
| _hideInterfaceCallback(); | |
| } | |
| @end | |
| @interface FindBarFieldEditor : NSTextView | |
| @end | |
| @implementation FindBarFieldEditor | |
| - (void)performTextFinderAction:(id)sender | |
| { | |
| [self.window.windowController performTextFinderAction:sender]; | |
| } | |
| - (BOOL)validateMenuItem:(NSMenuItem *)menuItem | |
| { | |
| if (menuItem.action == @selector(performTextFinderAction:)) | |
| return YES; | |
| return [super validateMenuItem:menuItem]; | |
| } | |
| @end | |
| // A JavaScript dialog, shown as a sheet. WebDriver answers it through the same sheet. | |
| @interface JavaScriptDialog : NSObject | |
| - (instancetype)initWithType:(_WKAutomationSessionJavaScriptDialogType)type message:(NSString *)message defaultText:(NSString *)defaultText completionHandler:(void (^)(BOOL accepted, NSString *text))completionHandler; | |
| @property (readonly) _WKAutomationSessionJavaScriptDialogType type; | |
| @property (readonly) NSString *message; | |
| @property (readonly) NSString *defaultText; | |
| @property (readonly) NSAlert *alert; | |
| // The text field of a prompt. | |
| @property (strong) NSTextField *input; | |
| // Nil once the dialog is complete. | |
| @property (copy) void (^completionHandler)(BOOL accepted, NSString *text); | |
| @end | |
| @implementation JavaScriptDialog | |
| - (instancetype)initWithType:(_WKAutomationSessionJavaScriptDialogType)type message:(NSString *)message defaultText:(NSString *)defaultText completionHandler:(void (^)(BOOL accepted, NSString *text))completionHandler | |
| { | |
| if (!(self = [super init])) | |
| return nil; | |
| _type = type; | |
| _message = [message copy]; | |
| _defaultText = [defaultText copy]; | |
| _alert = [[NSAlert alloc] init]; | |
| _completionHandler = [completionHandler copy]; | |
| return self; | |
| } | |
| @end | |
| @interface WK2BrowserWindowController () <NSTextFinderBarContainer, _WKFindDelegate, NSSearchFieldDelegate, WKDownloadDelegate, WKNavigationDelegate, WKNavigationDelegatePrivate, WKUIDelegate, WKUIDelegatePrivate, _WKIconLoadingDelegate, _WKInspectorDelegate> | |
| @end | |
| @implementation WK2BrowserWindowController { | |
| WKWebViewConfiguration *_configuration; | |
| WKWindowFeatures *_windowFeatures; | |
| WKWebView *_webView; | |
| BOOL _zoomTextOnly; | |
| BOOL _isPrivateBrowsingWindow; | |
| BOOL _useShrinkToFit; | |
| MiniBrowserNSTextFinder *_textFinder; | |
| NSView *_textFindBarView; | |
| NSView *_findBar; | |
| NSSearchField *_findSearchField; | |
| NSTextField *_findMatchCountLabel; | |
| FindBarFieldEditor *_findBarFieldEditor; | |
| id _findBarClickMonitor; | |
| BOOL _findBarVisible; | |
| BOOL _usingFindDelegate; | |
| CATextLayer *_pointerLockBanner; | |
| // WebKit runs one JavaScript dialog per page at a time. | |
| JavaScriptDialog *_currentJavaScriptDialog; | |
| _WKSessionState *_sessionStateToRestoreWhenInspectorLoads; | |
| // The window whose page opened this one with an opener, i.e. this page has JavaScript access back to it. | |
| __weak WK2BrowserWindowController *_openerController; | |
| NSWindowTabGroup *_observedTabGroup; | |
| BOOL _webViewHadFocusWhenHidden; | |
| #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 270000 | |
| NSRefreshController *_refreshController; | |
| #endif | |
| } | |
| - (void)awakeFromNib | |
| { | |
| _webView = [[WKWebView alloc] initWithFrame:[containerView bounds] configuration:_configuration]; | |
| _webView.inspectable = YES; | |
| [self didChangeSettings]; | |
| _webView.allowsMagnification = YES; | |
| _webView.allowsBackForwardNavigationGestures = YES; | |
| _webView._editable = self.isEditable; | |
| // Under automation, a page counts as hidden when its window is minimized or closed, or its tab isn't selected (see | |
| // -hideWebViewWhenTabIsInBackground), but not when other windows cover it. Several MiniBrowsers can run tests side | |
| // by side, and a test bot's screen has room for few of their windows, so they cover each other. A hidden page would | |
| // stop updating its rendering and throttle its timers. | |
| if (_configuration._controlledByAutomation) | |
| _webView._windowOcclusionDetectionEnabled = NO; | |
| [_webView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)]; | |
| [containerView addSubview:_webView]; | |
| [progressIndicator bind:NSHiddenBinding toObject:_webView withKeyPath:@"loading" options:@{ NSValueTransformerNameBindingOption : NSNegateBooleanTransformerName }]; | |
| [progressIndicator bind:NSValueBinding toObject:_webView withKeyPath:@"estimatedProgress" options:nil]; | |
| [_webView addObserver:self forKeyPath:@"title" options:0 context:keyValueObservingContext]; | |
| [_webView addObserver:self forKeyPath:@"URL" options:0 context:keyValueObservingContext]; | |
| [_webView addObserver:self forKeyPath:@"hasOnlySecureContent" options:0 context:keyValueObservingContext]; | |
| [_webView addObserver:self forKeyPath:@"_gpuProcessIdentifier" options:0 context:keyValueObservingContext]; | |
| _webView.navigationDelegate = self; | |
| _webView.UIDelegate = self; | |
| _webView._inspector.delegate = self; | |
| SettingsController *settingsController = [[NSApplication sharedApplication] browserAppDelegate].settingsController; | |
| // This setting installs the new WK2 Icon Loading Delegate and tests that mechanism by | |
| // telling WebKit to load every icon referenced by the page. | |
| if (settingsController.loadsAllSiteIcons) | |
| _webView._iconLoadingDelegate = self; | |
| _webView._observedRenderingProgressEvents = _WKRenderingProgressEventFirstLayout | |
| | _WKRenderingProgressEventFirstVisuallyNonEmptyLayout | |
| | _WKRenderingProgressEventFirstPaintWithSignificantArea | |
| | _WKRenderingProgressEventFirstLayoutAfterSuppressedIncrementalRendering | |
| | _WKRenderingProgressEventFirstPaintAfterSuppressedIncrementalRendering; | |
| if (settingsController.customUserAgent) | |
| _webView.customUserAgent = settingsController.customUserAgent; | |
| _webView._usePlatformFindUI = NO; | |
| _zoomTextOnly = NO; | |
| // FIXME: <webkit.org/b/317881> Remove this protocol check once the CMake port builds WKWebView+RefreshControl.swift. | |
| #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 270000 | |
| Protocol *refreshControlHosting = NSProtocolFromString(@"AppKit.NSRefreshControlHosting"); | |
| if (refreshControlHosting && [_webView conformsToProtocol:refreshControlHosting]) { | |
| _refreshController = [[NSRefreshController alloc] init]; | |
| _refreshController.target = self; | |
| _refreshController.action = @selector(_refreshControllerActivated:); | |
| _webView.refreshController = _refreshController; | |
| } | |
| #endif | |
| } | |
| - (id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)client | |
| { | |
| if (client == _findSearchField) { | |
| if (!_findBarFieldEditor) { | |
| _findBarFieldEditor = [[FindBarFieldEditor alloc] init]; | |
| _findBarFieldEditor.fieldEditor = YES; | |
| } | |
| return _findBarFieldEditor; | |
| } | |
| return nil; | |
| } | |
| - (instancetype)initWithConfiguration:(WKWebViewConfiguration *)configuration | |
| { | |
| return [self initWithConfiguration:configuration windowFeatures:nil]; | |
| } | |
| - (instancetype)initWithConfiguration:(WKWebViewConfiguration *)configuration windowFeatures:(WKWindowFeatures *)windowFeatures | |
| { | |
| if (!(self = [super initWithWindowNibName:@"BrowserWindow"])) | |
| return nil; | |
| _configuration = [configuration copy]; | |
| _windowFeatures = windowFeatures; | |
| _isPrivateBrowsingWindow = !_configuration.websiteDataStore.isPersistent; | |
| // AppKit cascades a window after -windowDidLoad, which would offset each additional automation window | |
| // from the fixed frame that -applyAutomationWindowFrame sets. | |
| if (_configuration._controlledByAutomation) | |
| self.shouldCascadeWindows = NO; | |
| [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userAgentDidChange:) name:kUserAgentChangedNotificationName object:nil]; | |
| return self; | |
| } | |
| - (void)dealloc | |
| { | |
| [self _completeAllJavaScriptDialogs]; | |
| [[NSNotificationCenter defaultCenter] removeObserver:self]; | |
| if (_findBarClickMonitor) | |
| [NSEvent removeMonitor:_findBarClickMonitor]; | |
| _textFinder.client = nil; | |
| _textFinder.findBarContainer = nil; | |
| [self _stopObservingTabGroup]; | |
| [_webView removeObserver:self forKeyPath:@"title"]; | |
| [_webView removeObserver:self forKeyPath:@"URL"]; | |
| [_webView removeObserver:self forKeyPath:@"hasOnlySecureContent"]; | |
| [_webView removeObserver:self forKeyPath:@"_gpuProcessIdentifier"]; | |
| [progressIndicator unbind:NSHiddenBinding]; | |
| [progressIndicator unbind:NSValueBinding]; | |
| } | |
| static NSRect frameForWindowFeatures(WKWindowFeatures *features, NSWindow *window) | |
| { | |
| NSRect contentRect = [window contentRectForFrameRect:window.frame]; | |
| // The web view insets its viewport underneath the titlebar and toolbar, so that inset has to be | |
| // added back on to give the page the size it asked for. | |
| CGFloat viewportInset = NSHeight(window.contentView.frame) - NSHeight(window.contentLayoutRect); | |
| if (features.width.doubleValue > 0) | |
| contentRect.size.width = features.width.doubleValue; | |
| if (features.height.doubleValue > 0) | |
| contentRect.size.height = features.height.doubleValue + viewportInset; | |
| NSRect frameRect = [window frameRectForContentRect:contentRect]; | |
| if (features.x) | |
| frameRect.origin.x = features.x.doubleValue; | |
| if (features.y) | |
| frameRect.origin.y = NSMaxY(NSScreen.screens.firstObject.frame) - features.y.doubleValue - NSHeight(frameRect); | |
| else | |
| frameRect.origin.y = NSMaxY(window.frame) - NSHeight(frameRect); | |
| return [window constrainFrameRect:frameRect toScreen:nil]; | |
| } | |
| - (void)applyWindowFeatures | |
| { | |
| if (!_windowFeatures.x && !_windowFeatures.y && !_windowFeatures.width && !_windowFeatures.height) | |
| return; | |
| NSWindow *window = self.window; | |
| // For windows that are opened with specific geometry, ignore AppKit's frame autosaving (and don't contribute to it). | |
| self.windowFrameAutosaveName = @""; | |
| window.tabbingMode = NSWindowTabbingModeDisallowed; | |
| [window layoutIfNeeded]; | |
| [window setFrame:frameForWindowFeatures(_windowFeatures, window) display:NO]; | |
| } | |
| // WPT's WebDriver tests set this window rect before each test (webdriver/tests/support/defaults.py). | |
| // Starting with it makes those requests no-ops, so that tests don't wait for a resize and relayout. | |
| // In WebDriver's coordinates: the top left corner, relative to the top left of the main screen. | |
| static const NSRect automationWindowRect = { { 200, 100 }, { 800, 600 } }; | |
| - (void)applyAutomationWindowFrame | |
| { | |
| NSWindow *window = self.window; | |
| // Ignore the frame saved by interactive use, so that test results don't depend on how | |
| // MiniBrowser windows were last sized by hand, and don't save automation frames over it. | |
| self.windowFrameAutosaveName = @""; | |
| [window setFrameAutosaveName:@""]; | |
| window.restorable = NO; | |
| NSRect frame = automationWindowRect; | |
| frame.origin.y = NSMaxY(NSScreen.screens.firstObject.frame) - NSMinY(automationWindowRect) - NSHeight(automationWindowRect); | |
| [window setFrame:[window constrainFrameRect:frame toScreen:window.screen] display:NO]; | |
| } | |
| - (void)windowDidLoad | |
| { | |
| [super windowDidLoad]; | |
| // Private windows get separate identifier so they can't merge with regular windows | |
| if (_isPrivateBrowsingWindow) | |
| self.window.tabbingIdentifier = @"MiniBrowserPrivateWindow"; | |
| if (_configuration._controlledByAutomation) | |
| [self applyAutomationWindowFrame]; | |
| [self applyWindowFeatures]; | |
| } | |
| - (void)userAgentDidChange:(NSNotification *)notification | |
| { | |
| SettingsController *settingsController = [[NSApplication sharedApplication] browserAppDelegate].settingsController; | |
| _webView.customUserAgent = settingsController.customUserAgent; | |
| [_webView reload]; | |
| } | |
| - (IBAction)fetch:(id)sender | |
| { | |
| [urlText setStringValue:[self addProtocolIfNecessary:urlText.stringValue]]; | |
| NSURL *url = [NSURL _webkit_URLWithUserTypedString:urlText.stringValue]; | |
| // WebKit puts a page that the app navigates to another site in a new browsing context group, which cuts its | |
| // opener. Comparing hosts is close enough to comparing sites here. | |
| if (![url.host isEqualToString:_webView.URL.host]) | |
| _openerController = nil; | |
| [_webView loadURL:url]; | |
| } | |
| - (IBAction)setPageScale:(id)sender | |
| { | |
| CGFloat scale = [self pageScaleForMenuItemTag:[sender tag]]; | |
| [_webView _setPageScale:scale withOrigin:CGPointZero]; | |
| } | |
| - (CGFloat)viewScaleForMenuItemTag:(NSInteger)tag | |
| { | |
| if (tag == 1) | |
| return 1; | |
| if (tag == 2) | |
| return 0.75; | |
| if (tag == 3) | |
| return 0.5; | |
| if (tag == 4) | |
| return 0.25; | |
| return 1; | |
| } | |
| - (IBAction)togglePictureInPicture:(id)sender | |
| { | |
| [_webView _togglePictureInPicture]; | |
| } | |
| - (IBAction)toggleInWindowFullscreen:(id)sender | |
| { | |
| [_webView _toggleInWindow]; | |
| } | |
| - (void)_webView:(WKWebView *)webView requestNotificationPermissionForSecurityOrigin:(WKSecurityOrigin *)securityOrigin decisionHandler:(void (^)(BOOL))decisionHandler | |
| { | |
| NSDictionary *permissions = [MiniBrowserUserDefaults() dictionaryForKey:@"NotificationPermissions"]; | |
| NSString *originString = [NSString stringWithFormat:@"%@://%@", securityOrigin.protocol, securityOrigin.host]; | |
| id value = [permissions valueForKey:originString]; | |
| if (value) { | |
| decisionHandler([(NSNumber *)value boolValue]); | |
| return; | |
| } | |
| NSAlert* alert = [[NSAlert alloc] init]; | |
| [alert setMessageText:[NSString stringWithFormat:@"Allow notification permissions for %@?", originString]]; | |
| [alert addButtonWithTitle:@"Deny"]; | |
| [alert addButtonWithTitle:@"Allow"]; | |
| [alert beginSheetModalForWindow:self.window completionHandler:^void (NSModalResponse response) { | |
| BOOL granted = response == NSAlertSecondButtonReturn; | |
| NSMutableDictionary *permissions = [[MiniBrowserUserDefaults() dictionaryForKey:@"NotificationPermissions"] mutableCopy]; | |
| if (!permissions) | |
| permissions = [NSMutableDictionary dictionaryWithCapacity:1]; | |
| [permissions setValue:@(granted) forKey:originString]; | |
| [MiniBrowserUserDefaults() setObject:permissions forKey:@"NotificationPermissions"]; | |
| decisionHandler(granted); | |
| }]; | |
| } | |
| - (void)_webView:(WKWebView *)webView requestLocalNetworkAccessPermissionForSecurityOrigin:(WKSecurityOrigin *)securityOrigin topLevelOrigin:(WKSecurityOrigin *)topLevelOrigin isLoopback:(BOOL)isLoopback decisionHandler:(void (^)(WKPermissionDecision))decisionHandler | |
| { | |
| NSString *originString = [NSString stringWithFormat:@"%@://%@", topLevelOrigin.protocol, topLevelOrigin.host]; | |
| NSString *frameString = [securityOrigin.host isEqualToString:topLevelOrigin.host] ? @"" : [NSString stringWithFormat:@" (requested by %@://%@)", securityOrigin.protocol, securityOrigin.host]; | |
| NSString *target = isLoopback ? @"this device (loopback)" : @"devices on your local network"; | |
| NSAlert *alert = [[NSAlert alloc] init]; | |
| [alert setMessageText:[NSString stringWithFormat:@"Allow %@ to connect to %@?%@", originString, target, frameString]]; | |
| [alert setInformativeText:@"Allowing this grants access to every address in that space, not just one device or port."]; | |
| [alert addButtonWithTitle:@"Deny"]; | |
| [alert addButtonWithTitle:@"Allow"]; | |
| [alert beginSheetModalForWindow:self.window completionHandler:^void (NSModalResponse response) { | |
| decisionHandler(response == NSAlertSecondButtonReturn ? WKPermissionDecisionGrant : WKPermissionDecisionDeny); | |
| }]; | |
| } | |
| - (IBAction)setViewScale:(id)sender | |
| { | |
| CGFloat scale = [self viewScaleForMenuItemTag:[sender tag]]; | |
| CGFloat oldScale = [_webView _viewScale]; | |
| if (scale == oldScale) | |
| return; | |
| [_webView _setLayoutMode:_WKLayoutModeDynamicSizeComputedFromViewScale]; | |
| NSRect oldFrame = self.window.frame; | |
| NSSize newFrameSize = NSMakeSize(oldFrame.size.width * (scale / oldScale), oldFrame.size.height * (scale / oldScale)); | |
| [self.window setFrame:NSMakeRect(oldFrame.origin.x, oldFrame.origin.y - (newFrameSize.height - oldFrame.size.height), newFrameSize.width, newFrameSize.height) display:NO animate:NO]; | |
| [_webView _setViewScale:scale]; | |
| } | |
| static BOOL areEssentiallyEqual(double a, double b) | |
| { | |
| double tolerance = 0.001; | |
| return (fabs(a - b) <= tolerance); | |
| } | |
| #pragma GCC diagnostic push | |
| #pragma GCC diagnostic ignored "-Wdeprecated-implementations" | |
| - (BOOL)validateMenuItem:(NSMenuItem *)menuItem | |
| #pragma GCC diagnostic pop | |
| { | |
| SEL action = menuItem.action; | |
| if (action == @selector(cloneSiteIsolatedWindow:)) | |
| return YES; | |
| if (action == @selector(cloneNonIsolatedWindow:)) | |
| return YES; | |
| if (action == @selector(saveAsPDF:)) | |
| return YES; | |
| if (action == @selector(saveAsImage:)) | |
| return YES; | |
| if (action == @selector(saveAsWebArchive:)) | |
| return YES; | |
| if (action == @selector(saveAsCompleteWebPage:)) | |
| return YES; | |
| if (action == @selector(zoomIn:)) | |
| return [self canZoomIn]; | |
| if (action == @selector(zoomOut:)) | |
| return [self canZoomOut]; | |
| if (action == @selector(resetZoom:)) | |
| return [self canResetZoom]; | |
| // Disabled until missing WK2 functionality is exposed via API/SPI. | |
| if (action == @selector(dumpSourceToConsole:) | |
| || action == @selector(forceRepaint:)) | |
| return NO; | |
| if (action == @selector(showHideWebView:)) | |
| [menuItem setTitle:[_webView isHidden] ? @"Show Web View" : @"Hide Web View"]; | |
| else if (action == @selector(removeReinsertWebView:)) | |
| [menuItem setTitle:[_webView window] ? @"Remove Web View" : @"Insert Web View"]; | |
| else if (action == @selector(toggleFullWindowWebView:)) | |
| [menuItem setTitle:[self webViewFillsWindow] ? @"Inset Web View" : @"Fit Web View to Window"]; | |
| else if (action == @selector(toggleZoomMode:)) | |
| [menuItem setState:_zoomTextOnly ? NSControlStateValueOn : NSControlStateValueOff]; | |
| else if (action == @selector(toggleEditable:)) | |
| [menuItem setState:self.isEditable ? NSControlStateValueOn : NSControlStateValueOff]; | |
| else if (action == @selector(showHideWebInspector:)) | |
| [menuItem setTitle:_webView._inspector.isVisible ? @"Close Web Inspector" : @"Show Web Inspector"]; | |
| else if (action == @selector(toggleAlwaysShowsHorizontalScroller:)) | |
| menuItem.state = _webView._alwaysShowsHorizontalScroller ? NSControlStateValueOn : NSControlStateValueOff; | |
| else if (action == @selector(toggleAlwaysShowsVerticalScroller:)) | |
| menuItem.state = _webView._alwaysShowsVerticalScroller ? NSControlStateValueOn : NSControlStateValueOff; | |
| else if (action == @selector(toggleMainThreadStalls:)) | |
| menuItem.state = self.mainThreadStallsEnabled ? NSControlStateValueOn : NSControlStateValueOff; | |
| [_webView _updateMediaPlaybackControlsManager]; | |
| if (action == @selector(togglePictureInPicture:)) { | |
| menuItem.state = _webView._isPictureInPictureActive ? NSControlStateValueOn : NSControlStateValueOff; | |
| return _webView._canTogglePictureInPicture; | |
| } | |
| if (action == @selector(toggleInWindowFullscreen:)) { | |
| menuItem.state = _webView._isInWindowActive ? NSControlStateValueOn : NSControlStateValueOff; | |
| return _webView._canToggleInWindow; | |
| } | |
| if (action == @selector(setPageScale:)) | |
| [menuItem setState:areEssentiallyEqual([_webView _pageScale], [self pageScaleForMenuItemTag:[menuItem tag]])]; | |
| if (action == @selector(setViewScale:)) | |
| [menuItem setState:areEssentiallyEqual([_webView _viewScale], [self viewScaleForMenuItemTag:[menuItem tag]])]; | |
| return YES; | |
| } | |
| - (IBAction)reload:(id)sender | |
| { | |
| [_webView reload]; | |
| } | |
| #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 270000 | |
| - (void)_refreshControllerActivated:(NSRefreshController *)refreshController | |
| { | |
| [_webView reload]; | |
| [refreshController performSelector:@selector(endRefreshing) withObject:nil afterDelay:2.5]; | |
| } | |
| #endif | |
| - (IBAction)showCertificate:(id)sender | |
| { | |
| if (_webView.serverTrust) | |
| [[SFCertificateTrustPanel sharedCertificateTrustPanel] beginSheetForWindow:self.window modalDelegate:nil didEndSelector:nil contextInfo:NULL trust:_webView.serverTrust message:@"TLS Certificate Details"]; | |
| } | |
| - (IBAction)logAccessibilityTrees:(id)sender | |
| { | |
| NSSavePanel *panel = [NSSavePanel savePanel]; | |
| #pragma clang diagnostic push | |
| #pragma clang diagnostic ignored "-Wdeprecated-declarations" | |
| panel.allowedFileTypes = @[ @"axtree" ]; | |
| #pragma clang diagnostic pop | |
| [panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) { | |
| if (result == NSModalResponseOK) { | |
| [self->_webView _retrieveAccessibilityTreeData:^(NSData *data, NSError *error) { | |
| [data writeToURL:[panel URL] options:0 error:nil]; | |
| }]; | |
| } | |
| }]; | |
| } | |
| - (IBAction)forceRepaint:(id)sender | |
| { | |
| // FIXME: This doesn't actually force a repaint. | |
| [_webView setNeedsDisplay:YES]; | |
| } | |
| - (IBAction)goBack:(id)sender | |
| { | |
| [_webView goBack]; | |
| } | |
| - (IBAction)goForward:(id)sender | |
| { | |
| [_webView goForward]; | |
| } | |
| - (IBAction)toggleZoomMode:(id)sender | |
| { | |
| if (_zoomTextOnly) { | |
| _zoomTextOnly = NO; | |
| double currentTextZoom = _webView._textZoomFactor; | |
| _webView._textZoomFactor = 1; | |
| _webView.pageZoom = currentTextZoom; | |
| } else { | |
| _zoomTextOnly = YES; | |
| double currentPageZoom = _webView._pageZoomFactor; | |
| _webView._textZoomFactor = currentPageZoom; | |
| _webView.pageZoom = 1; | |
| } | |
| } | |
| - (IBAction)resetZoom:(id)sender | |
| { | |
| if (![self canResetZoom]) | |
| return; | |
| if (_zoomTextOnly) | |
| _webView._textZoomFactor = 1; | |
| else { | |
| _webView.pageZoom = 1; | |
| _webView.magnification = 1; | |
| } | |
| } | |
| - (BOOL)canResetZoom | |
| { | |
| return _zoomTextOnly ? (_webView._textZoomFactor != 1) : (_webView.pageZoom != 1); | |
| } | |
| - (IBAction)toggleShrinkToFit:(id)sender | |
| { | |
| _useShrinkToFit = !_useShrinkToFit; | |
| toggleUseShrinkToFitButton.image = _useShrinkToFit ? [NSImage imageNamed:@"NSExitFullScreenTemplate"] : [NSImage imageNamed:@"NSEnterFullScreenTemplate"]; | |
| [_webView _setLayoutMode:_useShrinkToFit ? _WKLayoutModeDynamicSizeComputedFromMinimumDocumentSize : _WKLayoutModeViewSize]; | |
| } | |
| - (IBAction)dumpSourceToConsole:(id)sender | |
| { | |
| } | |
| - (IBAction)showHideWebInspector:(id)sender | |
| { | |
| _WKInspector *inspector = _webView._inspector; | |
| if (inspector.isVisible) | |
| [inspector hide]; | |
| else | |
| [inspector show]; | |
| } | |
| - (IBAction)toggleAlwaysShowsHorizontalScroller:(id)sender | |
| { | |
| _webView._alwaysShowsHorizontalScroller = !_webView._alwaysShowsHorizontalScroller; | |
| } | |
| - (IBAction)toggleAlwaysShowsVerticalScroller:(id)sender | |
| { | |
| _webView._alwaysShowsVerticalScroller = !_webView._alwaysShowsVerticalScroller; | |
| } | |
| - (NSURL *)currentURL | |
| { | |
| return _webView.URL; | |
| } | |
| - (NSView *)mainContentView | |
| { | |
| return _webView; | |
| } | |
| - (void)setEditable:(BOOL)editable | |
| { | |
| [super setEditable:editable]; | |
| _webView._editable = editable; | |
| } | |
| - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item | |
| { | |
| SEL action = item.action; | |
| if (action == @selector(goBack:) || action == @selector(goForward:)) | |
| return [_webView validateUserInterfaceItem:item]; | |
| if (action == @selector(showCertificate:)) | |
| return _webView.serverTrust != nil; | |
| return YES; | |
| } | |
| - (void)validateToolbar | |
| { | |
| [toolbar validateVisibleItems]; | |
| } | |
| - (BOOL)windowShouldClose:(id)sender | |
| { | |
| return YES; | |
| } | |
| - (void)windowWillClose:(NSNotification *)notification | |
| { | |
| [self _stopObservingTabGroup]; | |
| [self _completeAllJavaScriptDialogs]; | |
| [[[NSApplication sharedApplication] browserAppDelegate] browserWindowWillClose:self.window]; | |
| } | |
| #define DefaultMinimumZoomFactor (.5) | |
| #define DefaultMaximumZoomFactor (3.0) | |
| #define DefaultZoomFactorRatio (1.2) | |
| - (CGFloat)currentZoomFactor | |
| { | |
| return _zoomTextOnly ? _webView._textZoomFactor : _webView.pageZoom; | |
| } | |
| - (void)setCurrentZoomFactor:(CGFloat)factor | |
| { | |
| if (_zoomTextOnly) | |
| _webView._textZoomFactor = factor; | |
| else | |
| _webView.pageZoom = factor; | |
| } | |
| - (BOOL)canZoomIn | |
| { | |
| return self.currentZoomFactor * DefaultZoomFactorRatio < DefaultMaximumZoomFactor; | |
| } | |
| - (void)zoomIn:(id)sender | |
| { | |
| if (!self.canZoomIn) | |
| return; | |
| self.currentZoomFactor *= DefaultZoomFactorRatio; | |
| } | |
| - (BOOL)canZoomOut | |
| { | |
| return self.currentZoomFactor / DefaultZoomFactorRatio > DefaultMinimumZoomFactor; | |
| } | |
| - (void)zoomOut:(id)sender | |
| { | |
| if (!self.canZoomOut) | |
| return; | |
| self.currentZoomFactor /= DefaultZoomFactorRatio; | |
| } | |
| - (void)didChangeSettings | |
| { | |
| SettingsController *settings = [[NSApplication sharedApplication] browserAppDelegate].settingsController; | |
| WKPreferences *preferences = _webView.configuration.preferences; | |
| _webView._useSystemAppearance = settings.useSystemAppearance; | |
| preferences._tiledScrollingIndicatorVisible = settings.tiledScrollingIndicatorVisible; | |
| preferences._compositingBordersVisible = settings.layerBordersVisible; | |
| preferences._compositingRepaintCountersVisible = settings.layerBordersVisible; | |
| preferences._legacyLineLayoutVisualCoverageEnabled = settings.legacyLineLayoutVisualCoverageEnabled; | |
| preferences._acceleratedDrawingEnabled = settings.acceleratedDrawingEnabled; | |
| preferences._resourceUsageOverlayVisible = settings.resourceUsageOverlayVisible; | |
| preferences._largeImageAsyncDecodingEnabled = settings.largeImageAsyncDecodingEnabled; | |
| preferences._animatedImageAsyncDecodingEnabled = settings.animatedImageAsyncDecodingEnabled; | |
| preferences._colorFilterEnabled = settings.appleColorFilterEnabled; | |
| preferences.siteSpecificQuirksModeEnabled = settings.siteSpecificQuirksModeEnabled; | |
| preferences._punchOutWhiteBackgroundsInDarkMode = settings.punchOutWhiteBackgroundsInDarkMode; | |
| if ([preferences respondsToSelector:@selector(_setAXCustomColorModeEnabled:)]) | |
| preferences._axCustomColorModeEnabled = settings.axCustomColorModeEnabled; | |
| if ([preferences respondsToSelector:@selector(_setShowAXCustomColorModeControls:)]) | |
| preferences._showAXCustomColorModeControls = settings.showAXCustomColorModeControls; | |
| preferences._mockCaptureDevicesEnabled = settings.useMockCaptureDevices; | |
| preferences.tabFocusesLinks = settings.tabFocusesLinksEnabled; | |
| preferences._serviceControlsEnabled = settings.dataDetectorsEnabled; | |
| preferences._telephoneNumberDetectionIsEnabled = settings.dataDetectorsEnabled; | |
| _webView.configuration.defaultWebpagePreferences.securityRestrictionMode = settings.enhancedSecurityEnabled ? WKSecurityRestrictionModeMaximizeCompatibility : WKSecurityRestrictionModeNone; | |
| _webView.configuration.websiteDataStore._resourceLoadStatisticsEnabled = settings.resourceLoadStatisticsEnabled; | |
| [self setWebViewFillsWindow:settings.webViewFillsWindow]; | |
| BOOL useTransparentWindows = settings.useTransparentWindows; | |
| if (useTransparentWindows != !_webView._drawsBackground) { | |
| [self.window setOpaque:!useTransparentWindows]; | |
| [self.window setBackgroundColor:[NSColor clearColor]]; | |
| [self.window setHasShadow:!useTransparentWindows]; | |
| _webView._drawsBackground = !useTransparentWindows; | |
| [self.window display]; | |
| } | |
| BOOL usePaginatedMode = settings.usePaginatedMode; | |
| if (usePaginatedMode != (_webView._paginationMode != _WKPaginationModeUnpaginated)) { | |
| if (usePaginatedMode) { | |
| _webView._paginationMode = _WKPaginationModeLeftToRight; | |
| _webView._pageLength = _webView.bounds.size.width / 2; | |
| _webView._gapBetweenPages = 10; | |
| } else | |
| _webView._paginationMode = _WKPaginationModeUnpaginated; | |
| } | |
| NSUInteger visibleOverlayRegions = 0; | |
| if (settings.nonFastScrollableRegionOverlayVisible) | |
| visibleOverlayRegions |= _WKNonFastScrollableRegion; | |
| if (settings.wheelEventHandlerRegionOverlayVisible) | |
| visibleOverlayRegions |= _WKWheelEventHandlerRegion; | |
| if (settings.interactionRegionOverlayVisible) | |
| visibleOverlayRegions |= _WKInteractionRegion; | |
| if (settings.enhancedSecurityOverlayVisible) | |
| visibleOverlayRegions |= _WKEnhancedSecurityRegion; | |
| if (settings.touchActionRegionOverlayVisible) | |
| visibleOverlayRegions |= _WKTouchActionRegion; | |
| preferences._visibleDebugOverlayRegions = visibleOverlayRegions; | |
| int headerBannerHeight = [settings isSpaceReservedForBanners] ? testHeaderBannerHeight : 0; | |
| if (!headerBannerHeight) | |
| [_webView _setHeaderBannerLayer:nil]; | |
| else { | |
| CALayer *headerBannerLayer = [[CALayer alloc] init]; | |
| [headerBannerLayer setBounds:CGRectMake(0, 0, 0, headerBannerHeight)]; | |
| [headerBannerLayer setAnchorPoint:CGPointZero]; | |
| [headerBannerLayer setBackgroundColor:[NSColor colorWithSRGBRed:172. / 255. green:221 / 255. blue:222. / 255. alpha:1].CGColor]; | |
| [_webView _setHeaderBannerLayer:headerBannerLayer]; | |
| } | |
| int footerBannerHeight = [settings isSpaceReservedForBanners] ? testFooterBannerHeight : 0; | |
| if (!footerBannerHeight) | |
| [_webView _setFooterBannerLayer:nil]; | |
| else { | |
| CALayer *footerBannerLayer = [[CALayer alloc] init]; | |
| [footerBannerLayer setBounds:CGRectMake(0, 0, 0, footerBannerHeight)]; | |
| [footerBannerLayer setAnchorPoint:CGPointZero]; | |
| [footerBannerLayer setBackgroundColor:[NSColor colorWithSRGBRed:116. / 255. green:187. / 255. blue:251. / 255. alpha:1].CGColor]; | |
| [_webView _setFooterBannerLayer:footerBannerLayer]; | |
| } | |
| [self updateTitle:_webView.title]; | |
| } | |
| - (void)updateTitleForBadgeChange | |
| { | |
| [self updateTitle:_webView.title]; | |
| } | |
| - (void)updateTitle:(NSString *)title | |
| { | |
| if (!title.length) { | |
| NSURL *url = _webView.URL; | |
| title = url.lastPathComponent ?: url._web_userVisibleString; | |
| } | |
| if (!title.length) | |
| title = @"MiniBrowser"; | |
| if (BrowserAppDelegate.currentBadge) | |
| title = [title stringByAppendingFormat:@" (%@)", BrowserAppDelegate.currentBadge]; | |
| SettingsController *settings = [[NSApp browserAppDelegate] settingsController]; | |
| pid_t webPID = _webView._webProcessIdentifier; | |
| if (settings.showWebProcessIdentifierInTitle && webPID) | |
| title = [title stringByAppendingFormat:@" [%d]", webPID]; | |
| self.window.title = title; | |
| NSMutableString *subtitle = [@"[WK2" mutableCopy]; | |
| __auto_type appendProcessIdentifier = ^(NSString *name, pid_t processIdentifier) { | |
| if (!processIdentifier) | |
| return; | |
| [subtitle appendFormat:@" %@:%d", name, processIdentifier]; | |
| }; | |
| appendProcessIdentifier(@"web", _webView._webProcessIdentifier); | |
| appendProcessIdentifier(@"net", _webView.configuration.websiteDataStore._networkProcessIdentifier); | |
| appendProcessIdentifier(@"gpu", _webView._gpuProcessIdentifier); | |
| [subtitle appendString:@"]"]; | |
| if (_isPrivateBrowsingWindow) | |
| [subtitle appendString:@" 🙈"]; | |
| if (_webView._editable) | |
| [subtitle appendString:@" ✏️"]; | |
| if (_webView.configuration.preferences._siteIsolationEnabled) | |
| [subtitle appendString:@" (Site Isolated)"]; | |
| self.window.subtitle = subtitle; | |
| } | |
| - (void)hideWebViewWhenTabIsInBackground | |
| { | |
| // AppKit hides a tab that isn't selected only from the window server, so its window still counts as visible, and so | |
| // would its page without occlusion detection. Safari's tabs in the background aren't in a window at all. | |
| [self _stopObservingTabGroup]; | |
| _observedTabGroup = self.window.tabGroup; | |
| [_observedTabGroup addObserver:self forKeyPath:@"selectedWindow" options:NSKeyValueObservingOptionInitial context:tabSelectionObservingContext]; | |
| } | |
| - (void)_stopObservingTabGroup | |
| { | |
| [_observedTabGroup removeObserver:self forKeyPath:@"selectedWindow" context:tabSelectionObservingContext]; | |
| _observedTabGroup = nil; | |
| } | |
| - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context | |
| { | |
| if (context == tabSelectionObservingContext) { | |
| NSWindow *selectedWindow = _observedTabGroup.selectedWindow; | |
| BOOL hidden = selectedWindow && selectedWindow != self.window; | |
| if (hidden == _webView.hidden) | |
| return; | |
| // AppKit moves focus out of a view that it hides, to the next view that takes it, and doesn't move it back. | |
| if (hidden) { | |
| NSResponder *firstResponder = self.window.firstResponder; | |
| _webViewHadFocusWhenHidden = [firstResponder isKindOfClass:NSView.class] && [(NSView *)firstResponder isDescendantOf:_webView]; | |
| _webView.hidden = YES; | |
| } else { | |
| _webView.hidden = NO; | |
| if (_webViewHadFocusWhenHidden) | |
| [self.window makeFirstResponder:_webView]; | |
| } | |
| return; | |
| } | |
| if (context != keyValueObservingContext || object != _webView) | |
| return; | |
| if ([keyPath isEqualToString:@"title"]) | |
| [self updateTitle:_webView.title]; | |
| else if ([keyPath isEqualToString:@"URL"]) | |
| [self updateTextFieldFromURL:_webView.URL]; | |
| else if ([keyPath isEqualToString:@"hasOnlySecureContent"]) | |
| [self updateLockButtonIcon:_webView.hasOnlySecureContent]; | |
| else if ([keyPath isEqualToString:@"_gpuProcessIdentifier"]) | |
| [self updateTitle:_webView.title]; | |
| } | |
| - (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures | |
| { | |
| WK2BrowserWindowController *controller = [[WK2BrowserWindowController alloc] initWithConfiguration:configuration windowFeatures:windowFeatures]; | |
| if (navigationAction._hasOpener) | |
| controller->_openerController = self; | |
| [controller.window makeKeyAndOrderFront:self]; | |
| if (_configuration._controlledByAutomation) | |
| [controller hideWebViewWhenTabIsInBackground]; | |
| [[[NSApplication sharedApplication] browserAppDelegate] didCreateBrowserWindowController:controller]; | |
| return controller->_webView; | |
| } | |
| - (void)webViewDidClose:(WKWebView *)webView | |
| { | |
| // WebKit asks to close the web view, for example for window.close() or WebDriver's Close Window. | |
| // Unlike Cmd-W, this doesn't ask windowShouldClose:, because closing has already been decided: | |
| // window.close() runs beforeunload handlers first, and WebDriver's Close Window doesn't run them | |
| // at all. | |
| [self.window close]; | |
| // Close the web view now, too, rather than when it's deallocated, which can be much later, for | |
| // example after the animation that closes a tab. WebDriver replies to Close Window after this | |
| // returns, and by then, the web view must be gone from its list of windows. | |
| [webView _close]; | |
| } | |
| - (_WKAutomationSessionJavaScriptDialogType)automationDialogType | |
| { | |
| return _currentJavaScriptDialog ? _currentJavaScriptDialog.type : _WKAutomationSessionJavaScriptDialogTypeNone; | |
| } | |
| - (NSString *)automationDialogMessage | |
| { | |
| return _currentJavaScriptDialog.message; | |
| } | |
| - (NSString *)automationDialogDefaultText | |
| { | |
| return _currentJavaScriptDialog.defaultText; | |
| } | |
| - (NSString *)automationDialogUserInput | |
| { | |
| return _currentJavaScriptDialog.input.stringValue; | |
| } | |
| - (void)setAutomationDialogUserInput:(NSString *)userInput | |
| { | |
| _currentJavaScriptDialog.input.stringValue = userInput ?: @""; | |
| } | |
| - (void)completeAutomationDialogAccepting:(BOOL)accepted | |
| { | |
| JavaScriptDialog *dialog = _currentJavaScriptDialog; | |
| if (!dialog) | |
| return; | |
| // End the sheet as its buttons do, so that WebDriver and the user go through the same code. An alert only has OK. | |
| BOOL pressesFirstButton = accepted || dialog.type == _WKAutomationSessionJavaScriptDialogTypeAlert; | |
| [self.window endSheet:dialog.alert.window returnCode:pressesFirstButton ? NSAlertFirstButtonReturn : NSAlertSecondButtonReturn]; | |
| // In case the sheet wasn't showing. | |
| [self _completeJavaScriptDialog:dialog accepted:accepted]; | |
| } | |
| - (void)_completeJavaScriptDialog:(JavaScriptDialog *)dialog accepted:(BOOL)accepted | |
| { | |
| void (^completionHandler)(BOOL accepted, NSString *text) = dialog.completionHandler; | |
| if (!completionHandler) | |
| return; | |
| dialog.completionHandler = nil; | |
| [dialog.input validateEditing]; | |
| // WebKit can show the next dialog before the completion handler returns. | |
| _currentJavaScriptDialog = nil; | |
| completionHandler(accepted, dialog.input.stringValue); | |
| } | |
| - (void)_completeAllJavaScriptDialogs | |
| { | |
| // WebKit requires every dialog to be completed, including the ones it had queued. | |
| while (_currentJavaScriptDialog) | |
| [self _completeJavaScriptDialog:_currentJavaScriptDialog accepted:NO]; | |
| } | |
| - (void)_showJavaScriptDialog:(JavaScriptDialog *)dialog | |
| { | |
| // WebAutomationSession checks for a dialog on the next run loop iteration, so it has to be recorded now. | |
| _currentJavaScriptDialog = dialog; | |
| __weak WK2BrowserWindowController *weakSelf = self; | |
| [dialog.alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse response) { | |
| [weakSelf _completeJavaScriptDialog:dialog accepted:response == NSAlertFirstButtonReturn]; | |
| }]; | |
| } | |
| - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler | |
| { | |
| JavaScriptDialog *dialog = [[JavaScriptDialog alloc] initWithType:_WKAutomationSessionJavaScriptDialogTypeAlert message:message defaultText:nil completionHandler:^(BOOL accepted, NSString *text) { | |
| completionHandler(); | |
| }]; | |
| [dialog.alert setMessageText:[NSString stringWithFormat:@"JavaScript alert dialog from %@.", [frame.request.URL absoluteString]]]; | |
| [dialog.alert setInformativeText:message]; | |
| [dialog.alert addButtonWithTitle:@"OK"]; | |
| [self _showJavaScriptDialog:dialog]; | |
| } | |
| - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler | |
| { | |
| JavaScriptDialog *dialog = [[JavaScriptDialog alloc] initWithType:_WKAutomationSessionJavaScriptDialogTypeConfirm message:message defaultText:nil completionHandler:^(BOOL accepted, NSString *text) { | |
| completionHandler(accepted); | |
| }]; | |
| [dialog.alert setMessageText:[NSString stringWithFormat:@"JavaScript confirm dialog from %@.", [frame.request.URL absoluteString]]]; | |
| [dialog.alert setInformativeText:message]; | |
| [dialog.alert addButtonWithTitle:@"OK"]; | |
| [dialog.alert addButtonWithTitle:@"Cancel"]; | |
| [self _showJavaScriptDialog:dialog]; | |
| } | |
| - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *result))completionHandler | |
| { | |
| JavaScriptDialog *dialog = [[JavaScriptDialog alloc] initWithType:_WKAutomationSessionJavaScriptDialogTypePrompt message:prompt defaultText:defaultText completionHandler:^(BOOL accepted, NSString *text) { | |
| completionHandler(accepted ? text : nil); | |
| }]; | |
| [dialog.alert setMessageText:[NSString stringWithFormat:@"JavaScript prompt dialog from %@.", [frame.request.URL absoluteString]]]; | |
| [dialog.alert setInformativeText:prompt]; | |
| [dialog.alert addButtonWithTitle:@"OK"]; | |
| [dialog.alert addButtonWithTitle:@"Cancel"]; | |
| dialog.input = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)]; | |
| [dialog.input setStringValue:defaultText]; | |
| [dialog.alert setAccessoryView:dialog.input]; | |
| [self _showJavaScriptDialog:dialog]; | |
| } | |
| - (void)webView:(WKWebView *)webView runOpenPanelWithParameters:(WKOpenPanelParameters *)parameters initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSArray<NSURL *> * URLs))completionHandler | |
| { | |
| NSOpenPanel *openPanel = [NSOpenPanel openPanel]; | |
| openPanel.allowsMultipleSelection = parameters.allowsMultipleSelection; | |
| #pragma clang diagnostic push | |
| #pragma clang diagnostic ignored "-Wdeprecated-declarations" | |
| [openPanel setAllowedFileTypes:parameters._allowedFileExtensions]; | |
| #pragma clang diagnostic pop | |
| [openPanel beginSheetModalForWindow:webView.window completionHandler:^(NSInteger result) { | |
| if (result == NSModalResponseOK) | |
| completionHandler(openPanel.URLs); | |
| else | |
| completionHandler(nil); | |
| }]; | |
| } | |
| - (void)_webView:(WebView *)sender runBeforeUnloadConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler | |
| { | |
| NSAlert *alert = [[NSAlert alloc] init]; | |
| alert.messageText = [NSString stringWithFormat:@"JavaScript before unload dialog from %@.", [frame.request.URL absoluteString]]; | |
| alert.informativeText = message; | |
| [alert addButtonWithTitle:@"Leave Page"]; | |
| [alert addButtonWithTitle:@"Stay On Page"]; | |
| [alert beginSheetModalForWindow:self.window completionHandler:^void (NSModalResponse response) { | |
| completionHandler(response == NSAlertFirstButtonReturn); | |
| }]; | |
| } | |
| - (WKDragDestinationAction)_webView:(WKWebView *)webView dragDestinationActionMaskForDraggingInfo:(id)draggingInfo | |
| { | |
| return WKDragDestinationActionAny; | |
| } | |
| - (void)_webView:(WKWebView *)webView setWindowFrame:(CGRect)frame | |
| { | |
| if (!webView.configuration._isControlledByAutomation) | |
| return; | |
| NSRect screensFrame = NSZeroRect; | |
| for (NSScreen *screen in NSScreen.screens) | |
| screensFrame = NSUnionRect(screensFrame, screen.frame); | |
| // AppKit only enforces minSize for user resizes. WebDriver accepts frames far larger than any screen, so keep the | |
| // frame no larger than the screens' bounding box, and touching or overlapping it. | |
| NSSize minSize = self.window.minSize; | |
| NSRect newFrame = frame; | |
| newFrame.size.width = MAX(MIN(NSWidth(frame), NSWidth(screensFrame)), minSize.width); | |
| newFrame.size.height = MAX(MIN(NSHeight(frame), NSHeight(screensFrame)), minSize.height); | |
| newFrame.origin.y = NSMaxY(frame) - NSHeight(newFrame); | |
| newFrame.origin.x = MIN(MAX(NSMinX(newFrame), NSMinX(screensFrame) - NSWidth(newFrame)), NSMaxX(screensFrame)); | |
| newFrame.origin.y = MIN(MAX(NSMinY(newFrame), NSMinY(screensFrame) - NSHeight(newFrame)), NSMaxY(screensFrame)); | |
| [self.window setFrame:newFrame display:YES]; | |
| } | |
| - (void)_webView:(WKWebView *)webView printFrame:(_WKFrameHandle *)frame pdfFirstPageSize:(CGSize)size completionHandler:(void (^)(void))completionHandler | |
| { | |
| [[_webView printOperationWithPrintInfo:[NSPrintInfo sharedPrintInfo]] runOperationModalForWindow:self.window delegate:nil didRunSelector:nil contextInfo:nil]; | |
| completionHandler(); | |
| } | |
| - (void)updateTextFieldFromURL:(NSURL *)URL | |
| { | |
| if (!URL) | |
| return; | |
| if (!URL.absoluteString.length) | |
| return; | |
| urlText.stringValue = [URL _web_userVisibleString]; | |
| } | |
| - (void)updateLockButtonIcon:(BOOL)hasOnlySecureContent | |
| { | |
| if (hasOnlySecureContent) | |
| [lockButton setImage:[NSImage imageWithSystemSymbolName:@"lock" accessibilityDescription:nil]]; | |
| else | |
| [lockButton setImage:[NSImage imageWithSystemSymbolName:@"lock.open" accessibilityDescription:nil]]; | |
| } | |
| - (void)loadURLString:(NSString *)urlString | |
| { | |
| // FIXME: We shouldn't have to set the url text here. | |
| [urlText setStringValue:urlString]; | |
| [self fetch:nil]; | |
| } | |
| - (void)loadHTMLString:(NSString *)HTMLString | |
| { | |
| [_webView loadHTMLString:HTMLString baseURL:nil]; | |
| } | |
| static NSSet *dataTypes(void) | |
| { | |
| return [WKWebsiteDataStore allWebsiteDataTypes]; | |
| } | |
| - (IBAction)fetchWebsiteData:(id)sender | |
| { | |
| [_configuration.websiteDataStore _fetchDataRecordsOfTypes:dataTypes() withOptions:_WKWebsiteDataStoreFetchOptionComputeSizes completionHandler:^(NSArray *websiteDataRecords) { | |
| NSLog(@"did fetch website data %@.", websiteDataRecords); | |
| }]; | |
| } | |
| - (IBAction)fetchAndClearWebsiteData:(id)sender | |
| { | |
| [_configuration.websiteDataStore fetchDataRecordsOfTypes:dataTypes() completionHandler:^(NSArray *websiteDataRecords) { | |
| [self->_configuration.websiteDataStore removeDataOfTypes:dataTypes() forDataRecords:websiteDataRecords completionHandler:^{ | |
| [self->_configuration.websiteDataStore fetchDataRecordsOfTypes:dataTypes() completionHandler:^(NSArray *websiteDataRecords) { | |
| NSLog(@"did clear website data, after clearing data is %@.", websiteDataRecords); | |
| }]; | |
| }]; | |
| }]; | |
| } | |
| - (IBAction)clearWebsiteData:(id)sender | |
| { | |
| [_configuration.websiteDataStore removeDataOfTypes:dataTypes() modifiedSince:[NSDate distantPast] completionHandler:^{ | |
| NSLog(@"Did clear website data."); | |
| }]; | |
| } | |
| - (IBAction)printWebView:(id)sender | |
| { | |
| [[_webView printOperationWithPrintInfo:[NSPrintInfo sharedPrintInfo]] runOperationModalForWindow:self.window delegate:nil didRunSelector:nil contextInfo:nil]; | |
| } | |
| static BOOL isJavaScriptURL(NSURL *url) | |
| { | |
| return [url.scheme isEqualToString:@"javascript"]; | |
| } | |
| static BOOL responseIsAttachment(NSURLResponse *response) | |
| { | |
| if (![response isKindOfClass:[NSHTTPURLResponse class]]) | |
| return NO; | |
| NSString *disposition = [(NSHTTPURLResponse *)response valueForHTTPHeaderField:@"Content-Disposition"]; | |
| if (!disposition.length) | |
| return NO; | |
| NSString *type = [[disposition componentsSeparatedByString:@";"].firstObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; | |
| return [type caseInsensitiveCompare:@"attachment"] == NSOrderedSame; | |
| } | |
| #pragma mark WKNavigationDelegate | |
| - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction preferences:(WKWebpagePreferences *)preferences decisionHandler:(void (^)(WKNavigationActionPolicy, WKWebpagePreferences *))decisionHandler | |
| { | |
| LOG(@"decidePolicyForNavigationAction"); | |
| preferences._networkConnectionIntegrityPolicy = ^{ | |
| if (!NSApplication.sharedApplication.browserAppDelegate.settingsController.advancedPrivacyProtectionsEnabled) | |
| return _WKWebsiteNetworkConnectionIntegrityPolicyNone; | |
| return _WKWebsiteNetworkConnectionIntegrityPolicyEnabled | |
| | _WKWebsiteNetworkConnectionIntegrityPolicyEnhancedTelemetry | |
| | _WKWebsiteNetworkConnectionIntegrityPolicyRequestValidation | |
| | _WKWebsiteNetworkConnectionIntegrityPolicySanitizeLookalikeCharacters; | |
| }(); | |
| preferences.allowsContentJavaScript = NSApplication.sharedApplication.browserAppDelegate.settingsController.allowsContentJavascript; | |
| // This has to be tested before _canHandleRequest, which is true for the http and https | |
| // URLs that a download attribute usually points at. | |
| if (navigationAction.shouldPerformDownload) { | |
| decisionHandler(WKNavigationActionPolicyDownload, preferences); | |
| return; | |
| } | |
| if (navigationAction._canHandleRequest) { | |
| decisionHandler(WKNavigationActionPolicyAllow, preferences); | |
| return; | |
| } | |
| NSURL *url = navigationAction.request.URL; | |
| if (!isJavaScriptURL(url) && navigationAction._userInitiatedAction && !navigationAction._userInitiatedAction.isConsumed) { | |
| [navigationAction._userInitiatedAction consume]; | |
| [[NSWorkspace sharedWorkspace] openURL:url]; | |
| } | |
| decisionHandler(WKNavigationActionPolicyCancel, preferences); | |
| [self validateToolbar]; | |
| } | |
| - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler | |
| { | |
| LOG(@"decidePolicyForNavigationResponse"); | |
| // WebKit does not turn these into downloads on the client's behalf, so a browser that wants | |
| // them downloaded has to ask for it here. | |
| BOOL shouldDownload = responseIsAttachment(navigationResponse.response) || (!navigationResponse.canShowMIMEType && navigationResponse.forMainFrame); | |
| decisionHandler(shouldDownload ? WKNavigationResponsePolicyDownload : WKNavigationResponsePolicyAllow); | |
| [self validateToolbar]; | |
| } | |
| - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation | |
| { | |
| LOG(@"didStartProvisionalNavigation: %@", navigation); | |
| [self validateToolbar]; | |
| } | |
| - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation | |
| { | |
| LOG(@"didReceiveServerRedirectForProvisionalNavigation: %@", navigation); | |
| } | |
| - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error | |
| { | |
| LOG(@"didFailProvisionalNavigation: %@navigation, error: %@", navigation, error); | |
| } | |
| - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation | |
| { | |
| LOG(@"didCommitNavigation: %@", navigation); | |
| [self updateTitle:nil]; | |
| } | |
| - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation | |
| { | |
| LOG(@"didFinishNavigation: %@", navigation); | |
| #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 270000 | |
| [_refreshController endRefreshing]; | |
| #endif | |
| } | |
| - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *__nullable credential))completionHandler | |
| { | |
| LOG(@"didReceiveAuthenticationChallenge: %@", challenge); | |
| if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic]) { | |
| NSAlert *alert = [[NSAlert alloc] init]; | |
| NSView *container = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 200, 48)]; | |
| NSTextField *userInput = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 24, 200, 24)]; | |
| NSTextField *passwordInput = [[NSSecureTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)]; | |
| [alert setMessageText:[NSString stringWithFormat:@"Log in to %@:%lu.", challenge.protectionSpace.host, challenge.protectionSpace.port]]; | |
| [alert addButtonWithTitle:@"Log in"]; | |
| [alert addButtonWithTitle:@"Cancel"]; | |
| [container addSubview:userInput]; | |
| [container addSubview:passwordInput]; | |
| [alert setAccessoryView:container]; | |
| [userInput setNextKeyView:passwordInput]; | |
| [alert.window setInitialFirstResponder:userInput]; | |
| [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse response) { | |
| [userInput validateEditing]; | |
| if (response == NSAlertFirstButtonReturn) | |
| completionHandler(NSURLSessionAuthChallengeUseCredential, [[NSURLCredential alloc] initWithUser:[userInput stringValue] password:[passwordInput stringValue] persistence:NSURLCredentialPersistenceForSession]); | |
| else | |
| completionHandler(NSURLSessionAuthChallengeRejectProtectionSpace, nil); | |
| }]; | |
| return; | |
| } else if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { | |
| BrowserAppDelegate *appDelegate = [[NSApplication sharedApplication] browserAppDelegate]; | |
| if (appDelegate.settingsController.acceptAllTLSCertificates || (webView.configuration._isControlledByAutomation && appDelegate.automationAcceptsInsecureCertificates)) { | |
| completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]); | |
| return; | |
| } | |
| } | |
| completionHandler(NSURLSessionAuthChallengeRejectProtectionSpace, nil); | |
| } | |
| - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error | |
| { | |
| LOG(@"didFailNavigation: %@, error %@", navigation, error); | |
| } | |
| - (void)webView:(WKWebView *)webView navigationAction:(WKNavigationAction *)navigationAction didBecomeDownload:(WKDownload *)download | |
| { | |
| LOG(@"navigationAction didBecomeDownload: %@", download); | |
| download.delegate = self; | |
| } | |
| - (void)webView:(WKWebView *)webView navigationResponse:(WKNavigationResponse *)navigationResponse didBecomeDownload:(WKDownload *)download | |
| { | |
| LOG(@"navigationResponse didBecomeDownload: %@", download); | |
| download.delegate = self; | |
| } | |
| - (void)_webView:(WKWebView *)webView contextMenuDidCreateDownload:(WKDownload *)download | |
| { | |
| LOG(@"contextMenuDidCreateDownload: %@", download); | |
| download.delegate = self; | |
| } | |
| - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView | |
| { | |
| NSLog(@"WebContent process crashed; reloading"); | |
| [self reload:nil]; | |
| } | |
| - (void)_webView:(WKWebView *)webView renderingProgressDidChange:(_WKRenderingProgressEvents)progressEvents | |
| { | |
| if (progressEvents & _WKRenderingProgressEventFirstLayout) | |
| LOG(@"renderingProgressDidChange: %@", @"first layout"); | |
| if (progressEvents & _WKRenderingProgressEventFirstVisuallyNonEmptyLayout) | |
| LOG(@"renderingProgressDidChange: %@", @"first visually non-empty layout"); | |
| if (progressEvents & _WKRenderingProgressEventFirstPaintWithSignificantArea) | |
| LOG(@"renderingProgressDidChange: %@", @"first paint with significant area"); | |
| if (progressEvents & _WKRenderingProgressEventFirstLayoutAfterSuppressedIncrementalRendering) | |
| LOG(@"renderingProgressDidChange: %@", @"first layout after suppressed incremental rendering"); | |
| if (progressEvents & _WKRenderingProgressEventFirstPaintAfterSuppressedIncrementalRendering) | |
| LOG(@"renderingProgressDidChange: %@", @"first paint after suppressed incremental rendering"); | |
| } | |
| - (void)webView:(WKWebView *)webView shouldLoadIconWithParameters:(_WKLinkIconParameters *)parameters completionHandler:(void (^)(void (^)(NSData*)))completionHandler | |
| { | |
| completionHandler(^void (NSData *data) { | |
| LOG(@"Icon URL %@ received icon data of length %u", parameters.url, (unsigned)data.length); | |
| }); | |
| } | |
| #pragma mark _WKInspectorDelegate | |
| - (void)inspectorDidRequestDisablingSiteIsolation:(_WKInspector *)inspector | |
| { | |
| if (!_webView.configuration.preferences._siteIsolationEnabled) | |
| return; | |
| // Site Isolation can't be toggled on a live page, so reopen the page in a new window without it. | |
| WKWebViewConfiguration *configuration = [_webView.configuration copy]; | |
| configuration.preferences = [configuration.preferences copy]; | |
| configuration.preferences._siteIsolationEnabled = NO; | |
| // A page that another page opened has that page as its related web view, which would put the new window in the | |
| // opener's browsing context group and process, where Site Isolation is on. | |
| #pragma clang diagnostic push | |
| #pragma clang diagnostic ignored "-Wdeprecated-declarations" | |
| configuration._relatedWebView = nil; | |
| #pragma clang diagnostic pop | |
| WK2BrowserWindowController *controller = [[WK2BrowserWindowController alloc] initWithConfiguration:configuration]; | |
| [[[NSApplication sharedApplication] browserAppDelegate] didCreateBrowserWindowController:controller]; | |
| [controller.window makeKeyAndOrderFront:nil]; | |
| // Load the page only once the new inspector can record the load. | |
| controller->_sessionStateToRestoreWhenInspectorLoads = [_webView _sessionState]; | |
| [controller->_webView._inspector show]; | |
| // The windows that this page opened can't reach the new window, so close them rather than leave them looking | |
| // connected to it. | |
| for (WK2BrowserWindowController *openedController in self._browserWindowControllersOpenedWithOpener) | |
| [openedController.window close]; | |
| // Avoid closing this window, and with it this inspector, from inside one of the inspector's own callbacks. | |
| dispatch_async(dispatch_get_main_queue(), ^{ | |
| [self.window close]; | |
| }); | |
| } | |
| - (NSArray<WK2BrowserWindowController *> *)_browserWindowControllersOpenedWithOpener | |
| { | |
| NSSet<BrowserWindowController *> *browserWindowControllers = [[NSApplication sharedApplication] browserAppDelegate].browserWindowControllers; | |
| NSMutableArray<WK2BrowserWindowController *> *openedControllers = [NSMutableArray array]; | |
| NSMutableArray<WK2BrowserWindowController *> *openersToVisit = [NSMutableArray arrayWithObject:self]; | |
| while (openersToVisit.count) { | |
| WK2BrowserWindowController *opener = openersToVisit.lastObject; | |
| [openersToVisit removeLastObject]; | |
| for (BrowserWindowController *browserWindowController in browserWindowControllers) { | |
| if (![browserWindowController isKindOfClass:WK2BrowserWindowController.class]) | |
| continue; | |
| WK2BrowserWindowController *controller = (WK2BrowserWindowController *)browserWindowController; | |
| if (controller->_openerController != opener) | |
| continue; | |
| [openedControllers addObject:controller]; | |
| [openersToVisit addObject:controller]; | |
| } | |
| } | |
| return openedControllers; | |
| } | |
| - (void)inspectorFrontendLoaded:(_WKInspector *)inspector | |
| { | |
| _WKSessionState *sessionState = _sessionStateToRestoreWhenInspectorLoads; | |
| if (!sessionState) | |
| return; | |
| _sessionStateToRestoreWhenInspectorLoads = nil; | |
| [_webView _restoreSessionState:sessionState andNavigate:YES]; | |
| } | |
| #pragma mark WKDownloadDelegate | |
| static NSURL *availableDownloadURLWithFilename(NSString *filename) | |
| { | |
| // FIXME: Under automation, use the folder from browser.setDownloadBehavior when there is one. https://bugs.webkit.org/show_bug.cgi?id=303204 | |
| NSURL *downloadsDirectory = [[NSApplication sharedApplication] browserAppDelegate].downloadsDirectory; | |
| if (!downloadsDirectory) | |
| return nil; | |
| NSURL *candidate = [downloadsDirectory URLByAppendingPathComponent:filename]; | |
| // WebKit refuses a destination that already exists rather than overwriting it, so keep | |
| // looking until the name is free. | |
| NSString *base = candidate.URLByDeletingPathExtension.lastPathComponent; | |
| NSString *extension = candidate.pathExtension; | |
| for (unsigned suffix = 1; [NSFileManager.defaultManager fileExistsAtPath:candidate.path]; ++suffix) { | |
| candidate = [downloadsDirectory URLByAppendingPathComponent:[NSString stringWithFormat:@"%@-%u", base, suffix]]; | |
| if (extension.length) | |
| candidate = [candidate URLByAppendingPathExtension:extension]; | |
| } | |
| return candidate; | |
| } | |
| - (void)download:(WKDownload *)download decideDestinationUsingResponse:(NSURLResponse *)response suggestedFilename:(NSString *)suggestedFilename completionHandler:(void (^)(NSURL *))completionHandler | |
| { | |
| NSURL *destination = availableDownloadURLWithFilename(suggestedFilename.length ? suggestedFilename : @"download"); | |
| if (!destination) { | |
| NSLog(@"Cancelling download of %@: no download folder.", download.originalRequest.URL); | |
| completionHandler(nil); | |
| return; | |
| } | |
| NSLog(@"Downloading %@ to %@", download.originalRequest.URL, destination.path); | |
| completionHandler(destination); | |
| } | |
| - (void)downloadDidFinish:(WKDownload *)download | |
| { | |
| NSLog(@"Finished downloading %@", download.progress.fileURL.path); | |
| } | |
| - (void)download:(WKDownload *)download didFailWithError:(NSError *)error resumeData:(NSData *)resumeData | |
| { | |
| NSLog(@"Failed downloading %@: %@", download.originalRequest.URL, error); | |
| } | |
| #pragma mark Find in Page | |
| static const NSUInteger findMaxMatchCount = 1000; | |
| - (BOOL)_shouldUseFindDelegate | |
| { | |
| SettingsController *settings = [[NSApplication sharedApplication] browserAppDelegate].settingsController; | |
| return settings.useFindDelegate; | |
| } | |
| - (void)_ensureFindDelegateSetup | |
| { | |
| if (_findBar) | |
| return; | |
| _webView._findDelegate = self; | |
| [self _buildFindBar]; | |
| } | |
| - (void)_ensureTextFinderSetup | |
| { | |
| if (_textFinder) | |
| return; | |
| _textFinder = [[MiniBrowserNSTextFinder alloc] init]; | |
| _textFinder.incrementalSearchingEnabled = YES; | |
| _textFinder.incrementalSearchingShouldDimContentView = NO; | |
| _textFinder.client = _webView; | |
| _textFinder.findBarContainer = self; | |
| __weak WKWebView *weakWebView = _webView; | |
| _textFinder.hideInterfaceCallback = ^{ | |
| [weakWebView _hideFindUI]; | |
| }; | |
| } | |
| - (void)_buildFindBar | |
| { | |
| NSVisualEffectView *bar = [[NSVisualEffectView alloc] init]; | |
| bar.translatesAutoresizingMaskIntoConstraints = NO; | |
| bar.material = NSVisualEffectMaterialTitlebar; | |
| bar.blendingMode = NSVisualEffectBlendingModeWithinWindow; | |
| _findBar = bar; | |
| _findSearchField = [[NSSearchField alloc] init]; | |
| _findSearchField.translatesAutoresizingMaskIntoConstraints = NO; | |
| _findSearchField.placeholderString = @"Find in Page"; | |
| _findSearchField.delegate = self; | |
| [_findBar addSubview:_findSearchField]; | |
| NSButton *prevButton = [NSButton buttonWithTitle:@"<" target:self action:@selector(_findPrevious:)]; | |
| prevButton.translatesAutoresizingMaskIntoConstraints = NO; | |
| prevButton.bezelStyle = NSBezelStyleRounded; | |
| [_findBar addSubview:prevButton]; | |
| NSButton *nextButton = [NSButton buttonWithTitle:@">" target:self action:@selector(_findNext:)]; | |
| nextButton.translatesAutoresizingMaskIntoConstraints = NO; | |
| nextButton.bezelStyle = NSBezelStyleRounded; | |
| [_findBar addSubview:nextButton]; | |
| NSButton *doneButton = [NSButton buttonWithTitle:@"Done" target:self action:@selector(_hideFindBar:)]; | |
| doneButton.translatesAutoresizingMaskIntoConstraints = NO; | |
| doneButton.bezelStyle = NSBezelStyleRounded; | |
| [_findBar addSubview:doneButton]; | |
| _findMatchCountLabel = [NSTextField labelWithString:@""]; | |
| _findMatchCountLabel.translatesAutoresizingMaskIntoConstraints = NO; | |
| _findMatchCountLabel.font = [NSFont systemFontOfSize:11]; | |
| _findMatchCountLabel.textColor = [NSColor secondaryLabelColor]; | |
| _findMatchCountLabel.lineBreakMode = NSLineBreakByTruncatingTail; | |
| [_findMatchCountLabel setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow forOrientation:NSLayoutConstraintOrientationHorizontal]; | |
| [_findBar addSubview:_findMatchCountLabel]; | |
| [NSLayoutConstraint activateConstraints:@[ | |
| [_findSearchField.leadingAnchor constraintEqualToAnchor:_findBar.leadingAnchor constant:4], | |
| [_findSearchField.centerYAnchor constraintEqualToAnchor:_findBar.centerYAnchor], | |
| [prevButton.leadingAnchor constraintEqualToAnchor:_findSearchField.trailingAnchor constant:4], | |
| [prevButton.centerYAnchor constraintEqualToAnchor:_findBar.centerYAnchor], | |
| [prevButton.widthAnchor constraintEqualToConstant:30], | |
| [nextButton.leadingAnchor constraintEqualToAnchor:prevButton.trailingAnchor constant:2], | |
| [nextButton.centerYAnchor constraintEqualToAnchor:_findBar.centerYAnchor], | |
| [nextButton.widthAnchor constraintEqualToConstant:30], | |
| [doneButton.leadingAnchor constraintEqualToAnchor:nextButton.trailingAnchor constant:2], | |
| [doneButton.centerYAnchor constraintEqualToAnchor:_findBar.centerYAnchor], | |
| [_findMatchCountLabel.leadingAnchor constraintEqualToAnchor:doneButton.trailingAnchor constant:4], | |
| [_findMatchCountLabel.centerYAnchor constraintEqualToAnchor:_findBar.centerYAnchor], | |
| [_findMatchCountLabel.trailingAnchor constraintLessThanOrEqualToAnchor:_findBar.trailingAnchor constant:-4], | |
| ]]; | |
| } | |
| - (void)_showFindBar | |
| { | |
| if (!_findBarVisible) { | |
| _findBarVisible = YES; | |
| [containerView addSubview:_findBar]; | |
| [NSLayoutConstraint activateConstraints:@[ | |
| [_findBar.topAnchor constraintEqualToAnchor:containerView.safeAreaLayoutGuide.topAnchor], | |
| [_findBar.leadingAnchor constraintEqualToAnchor:containerView.leadingAnchor], | |
| [_findBar.trailingAnchor constraintEqualToAnchor:containerView.trailingAnchor], | |
| [_findBar.heightAnchor constraintEqualToConstant:30], | |
| ]]; | |
| __weak WK2BrowserWindowController *weakSelf = self; | |
| _findBarClickMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskLeftMouseDown handler:^NSEvent *(NSEvent *event) { | |
| WK2BrowserWindowController *strongSelf = weakSelf; | |
| if (!strongSelf) | |
| return event; | |
| NSPoint locationInBar = [strongSelf->_findBar convertPoint:event.locationInWindow fromView:nil]; | |
| if (![strongSelf->_findBar mouse:locationInBar inRect:strongSelf->_findBar.bounds]) | |
| [strongSelf _hideFindBarAndUI]; | |
| return event; | |
| }]; | |
| } | |
| [self.window makeFirstResponder:_findSearchField]; | |
| [_findSearchField selectText:nil]; | |
| } | |
| - (void)_hideFindBarAndUI | |
| { | |
| if (!_findBarVisible) | |
| return; | |
| _findBarVisible = NO; | |
| [NSEvent removeMonitor:_findBarClickMonitor]; | |
| _findBarClickMonitor = nil; | |
| [_findBar removeFromSuperview]; | |
| _findMatchCountLabel.stringValue = @""; | |
| [_webView _hideFindUI]; | |
| [self.window makeFirstResponder:_webView]; | |
| } | |
| - (void)_findStringInDirection:(BOOL)backward | |
| { | |
| NSString *searchString = _findSearchField.stringValue; | |
| if (!searchString.length) | |
| return; | |
| _WKFindOptions options = _WKFindOptionsCaseInsensitive | _WKFindOptionsWrapAround | _WKFindOptionsShowFindIndicator | _WKFindOptionsShowOverlay | _WKFindOptionsDetermineMatchIndex; | |
| if (backward) | |
| options |= _WKFindOptionsBackwards; | |
| [_webView _findString:searchString options:options maxCount:findMaxMatchCount]; | |
| [_findSearchField selectText:nil]; | |
| } | |
| - (IBAction)performTextFinderAction:(id)sender | |
| { | |
| NSInteger tag = [sender tag]; | |
| if (tag == NSTextFinderActionShowFindInterface) { | |
| BOOL shouldUseFindDelegate = [self _shouldUseFindDelegate]; | |
| if (_findBarVisible && shouldUseFindDelegate != _usingFindDelegate) { | |
| if (_usingFindDelegate) | |
| [self _hideFindBarAndUI]; | |
| else { | |
| [_textFinder performAction:NSTextFinderActionHideFindInterface]; | |
| _findBarVisible = NO; | |
| [_textFindBarView removeFromSuperview]; | |
| [_webView _hideFindUI]; | |
| } | |
| } | |
| _usingFindDelegate = shouldUseFindDelegate; | |
| if (_usingFindDelegate) { | |
| [self _ensureFindDelegateSetup]; | |
| [self _showFindBar]; | |
| } else { | |
| [self _ensureTextFinderSetup]; | |
| [_textFinder performAction:NSTextFinderActionShowFindInterface]; | |
| } | |
| return; | |
| } | |
| if (_usingFindDelegate) { | |
| switch (tag) { | |
| case NSTextFinderActionNextMatch: | |
| [self _findStringInDirection:NO]; | |
| break; | |
| case NSTextFinderActionPreviousMatch: | |
| [self _findStringInDirection:YES]; | |
| break; | |
| case NSTextFinderActionHideFindInterface: | |
| [self _hideFindBarAndUI]; | |
| break; | |
| default: | |
| break; | |
| } | |
| } else { | |
| [self _ensureTextFinderSetup]; | |
| [_textFinder performAction:tag]; | |
| } | |
| } | |
| - (void)_findNext:(id)sender | |
| { | |
| [self _findStringInDirection:NO]; | |
| } | |
| - (void)_findPrevious:(id)sender | |
| { | |
| [self _findStringInDirection:YES]; | |
| } | |
| - (void)_hideFindBar:(id)sender | |
| { | |
| [self _hideFindBarAndUI]; | |
| } | |
| - (void)cancelOperation:(id)sender | |
| { | |
| if (_findBarVisible) { | |
| if (_usingFindDelegate) | |
| [self _hideFindBarAndUI]; | |
| else | |
| [_textFinder performAction:NSTextFinderActionHideFindInterface]; | |
| } | |
| } | |
| - (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector | |
| { | |
| if (!_usingFindDelegate || control != _findSearchField) | |
| return NO; | |
| if (commandSelector == @selector(insertNewline:)) { | |
| BOOL shiftDown = !!([NSEvent modifierFlags] & NSEventModifierFlagShift); | |
| [self _findStringInDirection:shiftDown]; | |
| return YES; | |
| } | |
| if (commandSelector == @selector(cancelOperation:)) { | |
| [self _hideFindBarAndUI]; | |
| return YES; | |
| } | |
| return NO; | |
| } | |
| #pragma mark NSSearchFieldDelegate | |
| - (void)controlTextDidChange:(NSNotification *)notification | |
| { | |
| if (!_usingFindDelegate) | |
| return; | |
| NSString *searchString = _findSearchField.stringValue; | |
| if (!searchString.length) { | |
| _findMatchCountLabel.stringValue = @""; | |
| [_webView _hideFindUI]; | |
| return; | |
| } | |
| [_webView _findString:searchString options:_WKFindOptionsCaseInsensitive | _WKFindOptionsWrapAround | _WKFindOptionsShowFindIndicator | _WKFindOptionsShowOverlay | _WKFindOptionsDetermineMatchIndex maxCount:findMaxMatchCount]; | |
| } | |
| #pragma mark _WKFindDelegate | |
| - (void)_updateDisplayedMatchCount:(NSUInteger)matchCount matchIndex:(NSInteger)matchIndex | |
| { | |
| if (!matchCount) | |
| _findMatchCountLabel.stringValue = @"Not found"; | |
| else if (matchCount == 1) | |
| _findMatchCountLabel.stringValue = @"1 match"; | |
| else if (matchCount > findMaxMatchCount) | |
| _findMatchCountLabel.stringValue = [NSString stringWithFormat:@"More than %lu matches", (unsigned long)findMaxMatchCount]; | |
| else if (matchIndex != NSNotFound && matchIndex >= 0) | |
| _findMatchCountLabel.stringValue = [NSString stringWithFormat:@"%lu of %lu", (unsigned long)(matchIndex % matchCount + 1), (unsigned long)matchCount]; | |
| else | |
| _findMatchCountLabel.stringValue = [NSString stringWithFormat:@"%lu matches", (unsigned long)matchCount]; | |
| } | |
| - (void)_webView:(WKWebView *)webView didCountMatches:(NSUInteger)matches forString:(NSString *)string | |
| { | |
| [self _updateDisplayedMatchCount:matches matchIndex:NSNotFound]; | |
| } | |
| - (void)_webView:(WKWebView *)webView didFindMatches:(NSUInteger)matches forString:(NSString *)string withMatchIndex:(NSInteger)matchIndex | |
| { | |
| [self _updateDisplayedMatchCount:matches matchIndex:matchIndex]; | |
| } | |
| - (void)_webView:(WKWebView *)webView didFailToFindString:(NSString *)string | |
| { | |
| [self _updateDisplayedMatchCount:0 matchIndex:NSNotFound]; | |
| } | |
| #pragma mark NSTextFinderBarContainer | |
| - (NSView *)findBarView | |
| { | |
| return _textFindBarView; | |
| } | |
| - (void)setFindBarView:(NSView *)findBarView | |
| { | |
| _textFindBarView = findBarView; | |
| _textFindBarView.autoresizingMask = NSViewMaxYMargin | NSViewWidthSizable; | |
| _textFindBarView.frame = NSMakeRect(0, 0, containerView.bounds.size.width, _textFindBarView.frame.size.height); | |
| _findBarVisible = YES; | |
| } | |
| - (BOOL)isFindBarVisible | |
| { | |
| return _findBarVisible; | |
| } | |
| - (void)setFindBarVisible:(BOOL)findBarVisible | |
| { | |
| _findBarVisible = findBarVisible; | |
| if (findBarVisible) | |
| [containerView addSubview:_textFindBarView]; | |
| else | |
| [_textFindBarView removeFromSuperview]; | |
| } | |
| - (NSView *)contentView | |
| { | |
| return _webView; | |
| } | |
| - (void)findBarViewDidChangeHeight | |
| { | |
| } | |
| - (void)_cloneWindowSiteIsolated:(BOOL)siteIsolated | |
| { | |
| _WKSessionState *sessionState = [_webView _sessionState]; | |
| WKWebViewConfiguration *configuration = _webView.configuration; | |
| _configuration.preferences._siteIsolationEnabled = siteIsolated; | |
| WK2BrowserWindowController *controller = [[WK2BrowserWindowController alloc] initWithConfiguration:configuration]; | |
| [controller.window makeKeyAndOrderFront:self]; | |
| [[[NSApplication sharedApplication] browserAppDelegate] didCreateBrowserWindowController:controller]; | |
| [controller->_webView _restoreSessionState:sessionState andNavigate:YES]; | |
| } | |
| - (IBAction)cloneSiteIsolatedWindow:(id)sender | |
| { | |
| [self _cloneWindowSiteIsolated:YES]; | |
| } | |
| - (IBAction)cloneNonIsolatedWindow:(id)sender | |
| { | |
| [self _cloneWindowSiteIsolated:NO]; | |
| } | |
| - (IBAction)saveAsPDF:(id)sender | |
| { | |
| NSSavePanel *panel = [NSSavePanel savePanel]; | |
| panel.allowedContentTypes = @[ UTTypePDF ]; | |
| [panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) { | |
| if (result != NSModalResponseOK) | |
| return; | |
| [self->_webView createPDFWithConfiguration:nil completionHandler:^(NSData *pdfSnapshotData, NSError *error) { | |
| PDFDocument *pdfDocument = [[PDFDocument alloc] initWithData:pdfSnapshotData]; | |
| [pdfDocument writeToURL:[panel URL]]; | |
| }]; | |
| }]; | |
| } | |
| - (IBAction)saveAsImage:(id)sender | |
| { | |
| NSSavePanel *panel = [NSSavePanel savePanel]; | |
| panel.allowedContentTypes = @[ UTTypeTIFF ]; | |
| [panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) { | |
| if (result != NSModalResponseOK) | |
| return; | |
| [self->_webView takeSnapshotWithConfiguration:nil completionHandler:^(NSImage *snapshot, NSError *error) { | |
| [snapshot.TIFFRepresentation writeToURL:[panel URL] options:0 error:nil]; | |
| }]; | |
| }]; | |
| } | |
| - (IBAction)saveAsWebArchive:(id)sender | |
| { | |
| NSSavePanel *panel = [NSSavePanel savePanel]; | |
| panel.allowedContentTypes = @[ UTTypeWebArchive ]; | |
| [panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) { | |
| if (result != NSModalResponseOK) | |
| return; | |
| [self->_webView createWebArchiveDataWithCompletionHandler:^(NSData *archiveData, NSError *error) { | |
| [archiveData writeToURL:[panel URL] options:0 error:nil]; | |
| }]; | |
| }]; | |
| } | |
| - (IBAction)saveAsCompleteWebPage:(id)sender | |
| { | |
| NSSavePanel *panel = [NSSavePanel savePanel]; | |
| panel.allowedContentTypes = @[ UTTypeDirectory ]; | |
| [panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) { | |
| if (result != NSModalResponseOK) | |
| return; | |
| _WKArchiveConfiguration *archiveConfiguration = [[_WKArchiveConfiguration alloc] init]; | |
| archiveConfiguration.directory = [panel URL]; | |
| archiveConfiguration.suggestedFileName = @"index.html"; | |
| [self->_webView _archiveWithConfiguration:archiveConfiguration completionHandler:^(NSError *error) { | |
| if (error) | |
| NSLog(@"Saving complete web page to '%@' failed", [[panel URL] absoluteString]); | |
| }]; | |
| }]; | |
| } | |
| - (void)_webViewDidRequestPointerLock:(WKWebView *)webView completionHandler:(void (^)(BOOL))completionHandler | |
| { | |
| if (!_pointerLockBanner) { | |
| _pointerLockBanner = [[CATextLayer alloc] init]; | |
| [_pointerLockBanner setString:[[NSAttributedString alloc] initWithString:@"Your mouse pointer is hidden. Press Esc (Escape) once to reveal your mouse pointer." attributes:@{ NSFontAttributeName:[NSFont systemFontOfSize:16], NSForegroundColorAttributeName:NSColor.blackColor }]]; | |
| [_pointerLockBanner setBackgroundColor:NSColor.lightGrayColor.CGColor]; | |
| [_pointerLockBanner setWrapped:YES]; | |
| [_pointerLockBanner setFrame:CGRectMake(0, 0, 0, testHeaderBannerHeight)]; | |
| [_pointerLockBanner setContentsScale:[NSScreen mainScreen].backingScaleFactor]; | |
| } | |
| [webView _setHeaderBannerLayer:_pointerLockBanner]; | |
| completionHandler(YES); | |
| } | |
| - (void)_webViewDidLosePointerLock:(WKWebView *)webView | |
| { | |
| [webView _setHeaderBannerLayer:nil]; | |
| } | |
| #pragma mark WebXR | |
| - (void)_webView:(WKWebView *)webView requestPermissionForXRSessionOrigin:(NSString *)originString mode:(_WKXRSessionMode)mode grantedFeatures:(_WKXRSessionFeatureFlags)grantedFeatures consentRequiredFeatures:(_WKXRSessionFeatureFlags)consentRequiredFeatures consentOptionalFeatures:(_WKXRSessionFeatureFlags)consentOptionalFeatures requiredFeaturesRequested:(_WKXRSessionFeatureFlags)requiredFeaturesRequested optionalFeaturesRequested:(_WKXRSessionFeatureFlags)optionalFeaturesRequested completionHandler:(void (^)(_WKXRSessionFeatureFlags))completionHandler | |
| { | |
| completionHandler(grantedFeatures | consentRequiredFeatures | consentOptionalFeatures); | |
| } | |
| - (NSImage *)windowSnapshotInRect:(CGRect)rect | |
| { | |
| return [_webView _windowSnapshotInRect:rect withOptions:kCGWindowImageBoundsIgnoreFraming]; | |
| } | |
| @end |