Tweak _showSafeBrowsingWarningWithTitle SPI
[WebKit-https.git] / Source / WebKit / UIProcess / API / Cocoa / WKWebView.mm
1 /*
2  * Copyright (C) 2014-2018 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #import "config.h"
27 #import "WKWebViewInternal.h"
28
29 #if WK_API_ENABLED
30
31 #import "APIFormClient.h"
32 #import "APIPageConfiguration.h"
33 #import "APISerializedScriptValue.h"
34 #import "CompletionHandlerCallChecker.h"
35 #import "DiagnosticLoggingClient.h"
36 #import "DynamicViewportSizeUpdate.h"
37 #import "FindClient.h"
38 #import "FrontBoardServicesSPI.h"
39 #import "FullscreenClient.h"
40 #import "IconLoadingDelegate.h"
41 #import "LegacySessionStateCoding.h"
42 #import "Logging.h"
43 #import "NavigationState.h"
44 #import "ObjCObjectGraph.h"
45 #import "PageClient.h"
46 #import "RemoteLayerTreeScrollingPerformanceData.h"
47 #import "RemoteLayerTreeTransaction.h"
48 #import "RemoteObjectRegistry.h"
49 #import "RemoteObjectRegistryMessages.h"
50 #import "SafeBrowsingWarning.h"
51 #import "StringUtilities.h"
52 #import "UIDelegate.h"
53 #import "UserMediaProcessManager.h"
54 #import "VersionChecks.h"
55 #import "ViewGestureController.h"
56 #import "ViewSnapshotStore.h"
57 #import "WKBackForwardListInternal.h"
58 #import "WKBackForwardListItemInternal.h"
59 #import "WKBrowsingContextHandleInternal.h"
60 #import "WKDragDestinationAction.h"
61 #import "WKErrorInternal.h"
62 #import "WKHistoryDelegatePrivate.h"
63 #import "WKLayoutMode.h"
64 #import "WKNSData.h"
65 #import "WKNSURLExtras.h"
66 #import "WKNavigationDelegate.h"
67 #import "WKNavigationInternal.h"
68 #import "WKPreferencesInternal.h"
69 #import "WKProcessPoolInternal.h"
70 #import "WKSafeBrowsingWarning.h"
71 #import "WKSharedAPICast.h"
72 #import "WKSnapshotConfiguration.h"
73 #import "WKUIDelegate.h"
74 #import "WKUIDelegatePrivate.h"
75 #import "WKUserContentControllerInternal.h"
76 #import "WKWebViewConfigurationInternal.h"
77 #import "WKWebViewContentProvider.h"
78 #import "WKWebsiteDataStoreInternal.h"
79 #import "WebBackForwardList.h"
80 #import "WebCertificateInfo.h"
81 #import "WebFullScreenManagerProxy.h"
82 #import "WebPageGroup.h"
83 #import "WebPageProxy.h"
84 #import "WebPreferencesKeys.h"
85 #import "WebProcessPool.h"
86 #import "WebProcessProxy.h"
87 #import "WebURLSchemeHandlerCocoa.h"
88 #import "WebViewImpl.h"
89 #import "_WKActivatedElementInfoInternal.h"
90 #import "_WKDiagnosticLoggingDelegate.h"
91 #import "_WKFindDelegate.h"
92 #import "_WKFrameHandleInternal.h"
93 #import "_WKFullscreenDelegate.h"
94 #import "_WKHitTestResultInternal.h"
95 #import "_WKInputDelegate.h"
96 #import "_WKInspectorInternal.h"
97 #import "_WKRemoteObjectRegistryInternal.h"
98 #import "_WKSessionStateInternal.h"
99 #import "_WKVisitedLinkStoreInternal.h"
100 #import "_WKWebsitePoliciesInternal.h"
101 #import <WebCore/GraphicsContextCG.h>
102 #import <WebCore/IOSurface.h>
103 #import <WebCore/JSDOMBinding.h>
104 #import <WebCore/JSDOMExceptionHandling.h>
105 #import <WebCore/MIMETypeRegistry.h>
106 #import <WebCore/PlatformScreen.h>
107 #import <WebCore/RuntimeApplicationChecks.h>
108 #import <WebCore/SQLiteDatabaseTracker.h>
109 #import <WebCore/SchemeRegistry.h>
110 #import <WebCore/Settings.h>
111 #import <WebCore/SharedBuffer.h>
112 #import <WebCore/ValidationBubble.h>
113 #import <WebCore/ViewportArguments.h>
114 #import <WebCore/WritingMode.h>
115 #import <pal/spi/cocoa/NSKeyedArchiverSPI.h>
116 #import <pal/spi/mac/NSTextFinderSPI.h>
117 #import <wtf/BlockPtr.h>
118 #import <wtf/HashMap.h>
119 #import <wtf/MathExtras.h>
120 #import <wtf/NeverDestroyed.h>
121 #import <wtf/Optional.h>
122 #import <wtf/RetainPtr.h>
123 #import <wtf/SetForScope.h>
124 #import <wtf/UUID.h>
125 #import <wtf/spi/darwin/dyldSPI.h>
126 #import <wtf/text/TextStream.h>
127
128 #if ENABLE(APPLICATION_MANIFEST)
129 #import "_WKApplicationManifestInternal.h"
130 #endif
131
132 #if ENABLE(DATA_DETECTION)
133 #import "WKDataDetectorTypesInternal.h"
134 #endif
135
136 #if PLATFORM(IOS_FAMILY)
137 #import "InteractionInformationAtPosition.h"
138 #import "InteractionInformationRequest.h"
139 #import "ProcessThrottler.h"
140 #import "RemoteLayerTreeDrawingAreaProxy.h"
141 #import "RemoteScrollingCoordinatorProxy.h"
142 #import "UIKitSPI.h"
143 #import "VideoFullscreenManagerProxy.h"
144 #import "WKContentViewInteraction.h"
145 #import "WKPasswordView.h"
146 #import "WKScrollView.h"
147 #import "WKWebViewContentProviderRegistry.h"
148 #import "_WKWebViewPrintFormatter.h"
149 #import <MobileCoreServices/MobileCoreServices.h>
150 #import <UIKit/UIApplication.h>
151 #import <WebCore/FrameLoaderTypes.h>
152 #import <WebCore/InspectorOverlay.h>
153 #import <WebCore/ScrollableArea.h>
154 #import <WebCore/WebBackgroundTaskController.h>
155 #import <WebCore/WebSQLiteDatabaseTrackerClient.h>
156 #import <pal/spi/cg/CoreGraphicsSPI.h>
157 #import <pal/spi/cocoa/QuartzCoreSPI.h>
158 #import <pal/spi/ios/GraphicsServicesSPI.h>
159 #import <wtf/cocoa/Entitlements.h>
160
161 #define RELEASE_LOG_IF_ALLOWED(...) RELEASE_LOG_IF(_page && _page->isAlwaysOnLoggingAllowed(), ViewState, __VA_ARGS__)
162
163 @interface UIView (UIViewInternal)
164 - (UIViewController *)_viewControllerForAncestor;
165 @end
166
167 @interface UIWindow (UIWindowInternal)
168 - (BOOL)_isHostedInAnotherProcess;
169 @end
170
171 @interface UIViewController (UIViewControllerInternal)
172 - (UIViewController *)_rootAncestorViewController;
173 - (UIViewController *)_viewControllerForSupportedInterfaceOrientations;
174 @end
175
176 #endif // PLATFORM(IOS_FAMILY)
177
178 #if PLATFORM(IOS_FAMILY)
179 static const uint32_t firstSDKVersionWithLinkPreviewEnabledByDefault = 0xA0000;
180 static const Seconds delayBeforeNoVisibleContentsRectsLogging = 1_s;
181 #endif
182
183 #if PLATFORM(MAC)
184 #import "AppKitSPI.h"
185 #import "WKTextFinderClient.h"
186 #import "WKViewInternal.h"
187 #import <WebCore/ColorMac.h>
188
189 @interface WKWebView () <WebViewImplDelegate, NSTextInputClient, NSTextInputClient_Async>
190 @end
191
192 #if HAVE(TOUCH_BAR)
193 @interface WKWebView () <NSTouchBarProvider>
194 @end
195 #endif // HAVE(TOUCH_BAR)
196 #endif // PLATFORM(MAC)
197
198 #if ENABLE(ACCESSIBILITY_EVENTS)
199 #include <wtf/darwin/WeakLinking.h>
200 #if __has_include(<AccessibilitySupport.h>)
201 #include <AccessibilitySupport.h>
202 #else
203 extern "C" {
204 CFStringRef kAXSWebAccessibilityEventsEnabledNotification;
205 Boolean _AXSWebAccessibilityEventsEnabled();
206 }
207 #endif
208 #endif
209
210 #if PLATFORM(MAC) && ENABLE(DRAG_SUPPORT)
211
212 @interface WKWebView () <NSFilePromiseProviderDelegate, NSDraggingSource>
213 @end
214
215 #endif
216
217 static HashMap<WebKit::WebPageProxy*, __unsafe_unretained WKWebView *>& pageToViewMap()
218 {
219     static NeverDestroyed<HashMap<WebKit::WebPageProxy*, __unsafe_unretained WKWebView *>> map;
220     return map;
221 }
222
223 WKWebView* fromWebPageProxy(WebKit::WebPageProxy& page)
224 {
225     return pageToViewMap().get(&page);
226 }
227
228 #if PLATFORM(MAC)
229 static _WKOverlayScrollbarStyle toAPIScrollbarStyle(std::optional<WebCore::ScrollbarOverlayStyle> coreScrollbarStyle)
230 {
231     if (!coreScrollbarStyle)
232         return _WKOverlayScrollbarStyleAutomatic;
233     
234     switch (coreScrollbarStyle.value()) {
235     case WebCore::ScrollbarOverlayStyleDark:
236         return _WKOverlayScrollbarStyleDark;
237     case WebCore::ScrollbarOverlayStyleLight:
238         return _WKOverlayScrollbarStyleLight;
239     case WebCore::ScrollbarOverlayStyleDefault:
240         return _WKOverlayScrollbarStyleDefault;
241     }
242     ASSERT_NOT_REACHED();
243     return _WKOverlayScrollbarStyleAutomatic;
244 }
245
246 static std::optional<WebCore::ScrollbarOverlayStyle> toCoreScrollbarStyle(_WKOverlayScrollbarStyle scrollbarStyle)
247 {
248     switch (scrollbarStyle) {
249     case _WKOverlayScrollbarStyleDark:
250         return WebCore::ScrollbarOverlayStyleDark;
251     case _WKOverlayScrollbarStyleLight:
252         return WebCore::ScrollbarOverlayStyleLight;
253     case _WKOverlayScrollbarStyleDefault:
254         return WebCore::ScrollbarOverlayStyleDefault;
255     case _WKOverlayScrollbarStyleAutomatic:
256         break;
257     }
258     return std::nullopt;
259 }
260 #endif
261
262 #define FORWARD_ACTION_TO_WKCONTENTVIEW(_action) \
263     - (void)_action:(id)sender \
264     { \
265         if (self.usesStandardContentView) \
266             [_contentView _action ## ForWebView:sender]; \
267     }
268
269 @implementation WKWebView {
270     std::unique_ptr<WebKit::NavigationState> _navigationState;
271     std::unique_ptr<WebKit::UIDelegate> _uiDelegate;
272     std::unique_ptr<WebKit::IconLoadingDelegate> _iconLoadingDelegate;
273
274     _WKRenderingProgressEvents _observedRenderingProgressEvents;
275
276     WeakObjCPtr<id <_WKInputDelegate>> _inputDelegate;
277
278     std::optional<BOOL> _resolutionForShareSheetImmediateCompletionForTesting;
279     RetainPtr<WKSafeBrowsingWarning> _safeBrowsingWarning;
280
281 #if PLATFORM(IOS_FAMILY)
282     RetainPtr<_WKRemoteObjectRegistry> _remoteObjectRegistry;
283
284     RetainPtr<WKScrollView> _scrollView;
285     RetainPtr<WKContentView> _contentView;
286
287 #if ENABLE(FULLSCREEN_API)
288     RetainPtr<WKFullScreenWindowController> _fullScreenWindowController;
289 #endif
290
291     BOOL _overridesViewLayoutSize;
292     CGSize _viewLayoutSizeOverride;
293     std::optional<WebCore::FloatSize> _lastSentViewLayoutSize;
294     BOOL _overridesMaximumUnobscuredSize;
295     CGSize _maximumUnobscuredSizeOverride;
296     std::optional<WebCore::FloatSize> _lastSentMaximumUnobscuredSize;
297     CGRect _inputViewBounds;
298     CGFloat _viewportMetaTagWidth;
299     BOOL _viewportMetaTagWidthWasExplicit;
300     BOOL _viewportMetaTagCameFromImageDocument;
301     CGFloat _initialScaleFactor;
302     BOOL _fastClickingIsDisabled;
303
304     BOOL _allowsLinkPreview;
305
306     UIEdgeInsets _obscuredInsets;
307     BOOL _haveSetObscuredInsets;
308     BOOL _isChangingObscuredInsetsInteractively;
309
310     UIEdgeInsets _unobscuredSafeAreaInsets;
311     BOOL _haveSetUnobscuredSafeAreaInsets;
312     BOOL _avoidsUnsafeArea;
313     UIRectEdge _obscuredInsetEdgesAffectedBySafeArea;
314
315     UIInterfaceOrientation _interfaceOrientationOverride;
316     BOOL _overridesInterfaceOrientation;
317     std::optional<int32_t> _lastSentDeviceOrientation;
318
319     BOOL _allowsViewportShrinkToFit;
320
321     BOOL _hasCommittedLoadForMainFrame;
322     BOOL _needsResetViewStateAfterCommitLoadForMainFrame;
323     uint64_t _firstPaintAfterCommitLoadTransactionID;
324     WebKit::DynamicViewportUpdateMode _dynamicViewportUpdateMode;
325     WebKit::DynamicViewportSizeUpdateID _currentDynamicViewportSizeUpdateID;
326     CATransform3D _resizeAnimationTransformAdjustments;
327     CGFloat _animatedResizeOriginalContentWidth;
328     RetainPtr<UIView> _resizeAnimationView;
329     CGFloat _lastAdjustmentForScroller;
330     std::optional<CGRect> _frozenVisibleContentRect;
331     std::optional<CGRect> _frozenUnobscuredContentRect;
332
333     BOOL _commitDidRestoreScrollPosition;
334     std::optional<WebCore::FloatPoint> _scrollOffsetToRestore;
335     WebCore::FloatBoxExtent _obscuredInsetsWhenSaved;
336
337     std::optional<WebCore::FloatPoint> _unobscuredCenterToRestore;
338     std::optional<uint64_t> _firstTransactionIDAfterPageRestore;
339     double _scaleToRestore;
340
341     std::unique_ptr<WebKit::ViewGestureController> _gestureController;
342     BOOL _allowsBackForwardNavigationGestures;
343
344     RetainPtr<UIView <WKWebViewContentProvider>> _customContentView;
345     RetainPtr<UIView> _customContentFixedOverlayView;
346
347     RetainPtr<NSTimer> _enclosingScrollViewScrollTimer;
348     BOOL _didScrollSinceLastTimerFire;
349
350     WebCore::Color _scrollViewBackgroundColor;
351
352     // This value tracks the current adjustment added to the bottom inset due to the keyboard sliding out from the bottom
353     // when computing obscured content insets. This is used when updating the visible content rects where we should not
354     // include this adjustment.
355     CGFloat _totalScrollViewBottomInsetAdjustmentForKeyboard;
356     BOOL _currentlyAdjustingScrollViewInsetsForKeyboard;
357
358     BOOL _delayUpdateVisibleContentRects;
359     BOOL _hadDelayedUpdateVisibleContentRects;
360
361     BOOL _waitingForEndAnimatedResize;
362     BOOL _waitingForCommitAfterAnimatedResize;
363
364     Vector<WTF::Function<void ()>> _callbacksDeferredDuringResize;
365     RetainPtr<NSMutableArray> _stableStatePresentationUpdateCallbacks;
366
367     RetainPtr<WKPasswordView> _passwordView;
368
369     BOOL _hasScheduledVisibleRectUpdate;
370     BOOL _visibleContentRectUpdateScheduledFromScrollViewInStableState;
371     Vector<BlockPtr<void ()>> _visibleContentRectUpdateCallbacks;
372
373     _WKDragInteractionPolicy _dragInteractionPolicy;
374
375     // For release-logging for <rdar://problem/39281269>.
376     MonotonicTime _timeOfRequestForVisibleContentRectUpdate;
377     MonotonicTime _timeOfLastVisibleContentRectUpdate;
378
379     NSUInteger _focusPreservationCount;
380     NSUInteger _activeFocusedStateRetainCount;
381 #endif
382 #if PLATFORM(MAC)
383     std::unique_ptr<WebKit::WebViewImpl> _impl;
384     RetainPtr<WKTextFinderClient> _textFinderClient;
385 #endif
386 }
387
388 - (instancetype)initWithFrame:(CGRect)frame
389 {
390     return [self initWithFrame:frame configuration:adoptNS([[WKWebViewConfiguration alloc] init]).get()];
391 }
392
393 - (BOOL)_isValid
394 {
395     return _page && _page->isValid();
396 }
397
398 #if PLATFORM(IOS_FAMILY)
399 static int32_t deviceOrientationForUIInterfaceOrientation(UIInterfaceOrientation orientation)
400 {
401     switch (orientation) {
402     case UIInterfaceOrientationUnknown:
403     case UIInterfaceOrientationPortrait:
404         return 0;
405     case UIInterfaceOrientationPortraitUpsideDown:
406         return 180;
407     case UIInterfaceOrientationLandscapeLeft:
408         return -90;
409     case UIInterfaceOrientationLandscapeRight:
410         return 90;
411     }
412 }
413
414 static int32_t deviceOrientation()
415 {
416     return deviceOrientationForUIInterfaceOrientation([[UIApplication sharedApplication] statusBarOrientation]);
417 }
418
419 - (BOOL)_isShowingVideoPictureInPicture
420 {
421 #if !HAVE(AVKIT)
422     return false;
423 #else
424     if (!_page || !_page->videoFullscreenManager())
425         return false;
426
427     return _page->videoFullscreenManager()->hasMode(WebCore::HTMLMediaElementEnums::VideoFullscreenModePictureInPicture);
428 #endif
429 }
430
431 - (BOOL)_mayAutomaticallyShowVideoPictureInPicture
432 {
433 #if !HAVE(AVKIT)
434     return false;
435 #else
436     if (!_page || !_page->videoFullscreenManager())
437         return false;
438
439     return _page->videoFullscreenManager()->mayAutomaticallyShowVideoPictureInPicture();
440 #endif
441 }
442
443 static bool shouldAllowPictureInPictureMediaPlayback()
444 {
445     static bool shouldAllowPictureInPictureMediaPlayback = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_9_0;
446     return shouldAllowPictureInPictureMediaPlayback;
447 }
448
449 static bool shouldAllowSettingAnyXHRHeaderFromFileURLs()
450 {
451     static bool shouldAllowSettingAnyXHRHeaderFromFileURLs = (WebCore::IOSApplication::isCardiogram() || WebCore::IOSApplication::isNike()) && !linkedOnOrAfter(WebKit::SDKVersion::FirstThatDisallowsSettingAnyXHRHeaderFromFileURLs);
452     return shouldAllowSettingAnyXHRHeaderFromFileURLs;
453 }
454
455 - (void)_incrementFocusPreservationCount
456 {
457     ++_focusPreservationCount;
458 }
459
460 - (void)_decrementFocusPreservationCount
461 {
462     if (_focusPreservationCount)
463         --_focusPreservationCount;
464 }
465
466 - (void)_resetFocusPreservationCount
467 {
468     _focusPreservationCount = 0;
469 }
470
471 - (BOOL)_isRetainingActiveFocusedState
472 {
473     // Focus preservation count fulfills the same role as active focus state count.
474     // However, unlike active focus state, it may be reset to 0 without impacting the
475     // behavior of -_retainActiveFocusedState, and it's harmless to invoke
476     // -_decrementFocusPreservationCount after resetting the count to 0.
477     return _focusPreservationCount || _activeFocusedStateRetainCount;
478 }
479
480 #endif
481
482 static bool shouldRequireUserGestureToLoadVideo()
483 {
484 #if PLATFORM(IOS_FAMILY)
485     static bool shouldRequireUserGestureToLoadVideo = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
486     return shouldRequireUserGestureToLoadVideo;
487 #else
488     return false;
489 #endif
490 }
491
492 #if PLATFORM(MAC)
493 static uint32_t convertUserInterfaceDirectionPolicy(WKUserInterfaceDirectionPolicy policy)
494 {
495     switch (policy) {
496     case WKUserInterfaceDirectionPolicyContent:
497         return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content);
498     case WKUserInterfaceDirectionPolicySystem:
499         return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::System);
500     }
501     return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content);
502 }
503
504 static uint32_t convertSystemLayoutDirection(NSUserInterfaceLayoutDirection direction)
505 {
506     switch (direction) {
507     case NSUserInterfaceLayoutDirectionLeftToRight:
508         return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::LTR);
509     case NSUserInterfaceLayoutDirectionRightToLeft:
510         return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::RTL);
511     }
512     return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::LTR);
513 }
514
515 #endif // PLATFORM(MAC)
516
517 static void validate(WKWebViewConfiguration *configuration)
518 {
519     if (!configuration.processPool)
520         [NSException raise:NSInvalidArgumentException format:@"configuration.processPool is nil"];
521     
522     if (!configuration.preferences)
523         [NSException raise:NSInvalidArgumentException format:@"configuration.preferences is nil"];
524     
525     if (!configuration.userContentController)
526         [NSException raise:NSInvalidArgumentException format:@"configuration.userContentController is nil"];
527     
528     if (!configuration.websiteDataStore)
529         [NSException raise:NSInvalidArgumentException format:@"configuration.websiteDataStore is nil"];
530     
531     if (!configuration._visitedLinkStore)
532         [NSException raise:NSInvalidArgumentException format:@"configuration._visitedLinkStore is nil"];
533     
534 #if PLATFORM(IOS_FAMILY)
535     if (!configuration._contentProviderRegistry)
536         [NSException raise:NSInvalidArgumentException format:@"configuration._contentProviderRegistry is nil"];
537 #endif
538 }
539
540 - (void)_initializeWithConfiguration:(WKWebViewConfiguration *)configuration
541 {
542     if (!configuration)
543         [NSException raise:NSInvalidArgumentException format:@"Configuration cannot be nil"];
544
545     _configuration = adoptNS([configuration copy]);
546
547     if (WKWebView *relatedWebView = [_configuration _relatedWebView]) {
548         WKProcessPool *processPool = [_configuration processPool];
549         WKProcessPool *relatedWebViewProcessPool = [relatedWebView->_configuration processPool];
550         if (processPool && processPool != relatedWebViewProcessPool)
551             [NSException raise:NSInvalidArgumentException format:@"Related web view %@ has process pool %@ but configuration specifies a different process pool %@", relatedWebView, relatedWebViewProcessPool, configuration.processPool];
552
553         [_configuration setProcessPool:relatedWebViewProcessPool];
554     }
555
556     validate(_configuration.get());
557
558     WebKit::WebProcessPool& processPool = *[_configuration processPool]->_processPool;
559     processPool.setResourceLoadStatisticsEnabled(configuration.websiteDataStore._resourceLoadStatisticsEnabled);
560
561     auto pageConfiguration = [configuration copyPageConfiguration];
562
563     pageConfiguration->setProcessPool(&processPool);
564     pageConfiguration->setPreferences([_configuration preferences]->_preferences.get());
565     if (WKWebView *relatedWebView = [_configuration _relatedWebView])
566         pageConfiguration->setRelatedPage(relatedWebView->_page.get());
567
568     pageConfiguration->setUserContentController([_configuration userContentController]->_userContentControllerProxy.get());
569     pageConfiguration->setVisitedLinkStore([_configuration _visitedLinkStore]->_visitedLinkStore.get());
570     pageConfiguration->setWebsiteDataStore([_configuration websiteDataStore]->_websiteDataStore.get());
571
572 #if PLATFORM(MAC)
573     if (auto pageGroup = WebKit::toImpl([configuration _pageGroup])) {
574         pageConfiguration->setPageGroup(pageGroup);
575         pageConfiguration->setUserContentController(&pageGroup->userContentController());
576     } else
577 #endif
578     {
579         NSString *groupIdentifier = configuration._groupIdentifier;
580         if (groupIdentifier.length)
581             pageConfiguration->setPageGroup(WebKit::WebPageGroup::create(configuration._groupIdentifier).ptr());
582     }
583
584     pageConfiguration->setAdditionalSupportedImageTypes(WebKit::webCoreStringVectorFromNSStringArray([_configuration _additionalSupportedImageTypes]));
585
586     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::suppressesIncrementalRenderingKey(), WebKit::WebPreferencesStore::Value(!![_configuration suppressesIncrementalRendering]));
587
588     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldRespectImageOrientationKey(), WebKit::WebPreferencesStore::Value(!![_configuration _respectsImageOrientation]));
589     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldPrintBackgroundsKey(), WebKit::WebPreferencesStore::Value(!![_configuration _printsBackgrounds]));
590     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey(), WebKit::WebPreferencesStore::Value([_configuration _incrementalRenderingSuppressionTimeout]));
591     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::javaScriptMarkupEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsJavaScriptMarkup]));
592     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldConvertPositionStyleOnCopyKey(), WebKit::WebPreferencesStore::Value(!![_configuration _convertsPositionStyleOnCopy]));
593     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::httpEquivEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsMetaRefresh]));
594     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowUniversalAccessFromFileURLsKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowUniversalAccessFromFileURLs]));
595     pageConfiguration->setWaitsForPaintAfterViewDidMoveToWindow([_configuration _waitsForPaintAfterViewDidMoveToWindow]);
596     pageConfiguration->setDrawsBackground([_configuration _drawsBackground]);
597     pageConfiguration->setControlledByAutomation([_configuration _isControlledByAutomation]);
598     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::incompleteImageBorderEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _incompleteImageBorderEnabled]));
599     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldDeferAsynchronousScriptsUntilAfterDocumentLoadKey(), WebKit::WebPreferencesStore::Value(!![_configuration _shouldDeferAsynchronousScriptsUntilAfterDocumentLoad]));
600
601 #if PLATFORM(MAC)
602     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::showsURLsInToolTipsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _showsURLsInToolTips]));
603     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::serviceControlsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _serviceControlsEnabled]));
604     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::imageControlsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _imageControlsEnabled]));
605
606     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::userInterfaceDirectionPolicyKey(), WebKit::WebPreferencesStore::Value(convertUserInterfaceDirectionPolicy([_configuration userInterfaceDirectionPolicy])));
607     // We are in the View's initialization routine, so our client hasn't had time to set our user interface direction.
608     // Therefore, according to the docs[1], "this property contains the value reported by the app's userInterfaceLayoutDirection property."
609     // [1] http://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/index.html#//apple_ref/doc/uid/20000014-SW222
610     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::systemLayoutDirectionKey(), WebKit::WebPreferencesStore::Value(convertSystemLayoutDirection(self.userInterfaceLayoutDirection)));
611 #endif
612
613 #if PLATFORM(IOS_FAMILY)
614     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsInlineMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsInlineMediaPlayback]));
615     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsInlineMediaPlaybackAfterFullscreenKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsInlineMediaPlaybackAfterFullscreen]));
616     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::inlineMediaPlaybackRequiresPlaysInlineAttributeKey(), WebKit::WebPreferencesStore::Value(!![_configuration _inlineMediaPlaybackRequiresPlaysInlineAttribute]));
617     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsPictureInPictureMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback()));
618     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::userInterfaceDirectionPolicyKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content)));
619     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::systemLayoutDirectionKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(WebCore::TextDirection::LTR)));
620     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowSettingAnyXHRHeaderFromFileURLsKey(), WebKit::WebPreferencesStore::Value(shouldAllowSettingAnyXHRHeaderFromFileURLs()));
621 #if USE(SYSTEM_PREVIEW)
622     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::systemPreviewEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _systemPreviewEnabled]));
623 #endif
624 #endif
625
626     WKAudiovisualMediaTypes mediaTypesRequiringUserGesture = [_configuration mediaTypesRequiringUserActionForPlayback];
627     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureForVideoPlaybackKey(), WebKit::WebPreferencesStore::Value((mediaTypesRequiringUserGesture & WKAudiovisualMediaTypeVideo) == WKAudiovisualMediaTypeVideo));
628     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureForAudioPlaybackKey(), WebKit::WebPreferencesStore::Value(((mediaTypesRequiringUserGesture & WKAudiovisualMediaTypeAudio) == WKAudiovisualMediaTypeAudio)));
629     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureToLoadVideoKey(), WebKit::WebPreferencesStore::Value(shouldRequireUserGestureToLoadVideo()));
630     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mainContentUserGestureOverrideEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _mainContentUserGestureOverrideEnabled]));
631     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::invisibleAutoplayNotPermittedKey(), WebKit::WebPreferencesStore::Value(!![_configuration _invisibleAutoplayNotPermitted]));
632     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mediaDataLoadsAutomaticallyKey(), WebKit::WebPreferencesStore::Value(!![_configuration _mediaDataLoadsAutomatically]));
633     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::attachmentElementEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _attachmentElementEnabled]));
634
635 #if ENABLE(DATA_DETECTION) && PLATFORM(IOS_FAMILY)
636     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::dataDetectorTypesKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(fromWKDataDetectorTypes([_configuration dataDetectorTypes]))));
637 #endif
638 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
639     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsAirPlayForMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsAirPlayForMediaPlayback]));
640 #endif
641
642 #if ENABLE(APPLE_PAY)
643     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::applePayEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _applePayEnabled]));
644 #endif
645
646     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::needsStorageAccessFromFileURLsQuirkKey(), WebKit::WebPreferencesStore::Value(!![_configuration _needsStorageAccessFromFileURLsQuirk]));
647     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mediaContentTypesRequiringHardwareSupportKey(), WebKit::WebPreferencesStore::Value(String([_configuration _mediaContentTypesRequiringHardwareSupport])));
648     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowMediaContentTypesRequiringHardwareSupportAsFallbackKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowMediaContentTypesRequiringHardwareSupportAsFallback]));
649
650     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::colorFilterEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _colorFilterEnabled]));
651
652     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::editableImagesEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _editableImagesEnabled]));
653
654 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
655     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::legacyEncryptedMediaAPIEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _legacyEncryptedMediaAPIEnabled]));
656 #endif
657
658 #if PLATFORM(IOS_FAMILY) && ENABLE(SERVICE_WORKER)
659     if (!WTF::processHasEntitlement("com.apple.developer.WebKit.ServiceWorkers"))
660         pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::serviceWorkersEnabledKey(), WebKit::WebPreferencesStore::Value(false));
661 #endif
662
663 #if PLATFORM(IOS_FAMILY)
664     CGRect bounds = self.bounds;
665     _scrollView = adoptNS([[WKScrollView alloc] initWithFrame:bounds]);
666     [_scrollView setInternalDelegate:self];
667     [_scrollView setBouncesZoom:YES];
668
669     _avoidsUnsafeArea = YES;
670     [self _updateScrollViewInsetAdjustmentBehavior];
671
672     [self addSubview:_scrollView.get()];
673
674     static uint32_t programSDKVersion = dyld_get_program_sdk_version();
675     _allowsLinkPreview = programSDKVersion >= firstSDKVersionWithLinkPreviewEnabledByDefault;
676
677     _contentView = adoptNS([[WKContentView alloc] initWithFrame:bounds processPool:processPool configuration:pageConfiguration.copyRef() webView:self]);
678
679     _page = [_contentView page];
680     [self _dispatchSetDeviceOrientation:deviceOrientation()];
681     _page->setDrawsBackground(self.opaque);
682
683     [_contentView layer].anchorPoint = CGPointZero;
684     [_contentView setFrame:bounds];
685     [_scrollView addSubview:_contentView.get()];
686     [_scrollView addSubview:[_contentView unscaledView]];
687     [self _updateScrollViewBackground];
688     _obscuredInsetEdgesAffectedBySafeArea = UIRectEdgeTop | UIRectEdgeLeft | UIRectEdgeRight;
689
690     _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
691     _initialScaleFactor = 1;
692
693     if (NSNumber *enabledValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"WebKitFastClickingDisabled"])
694         _fastClickingIsDisabled = enabledValue.boolValue;
695     else {
696 #if PLATFORM(WATCHOS)
697         _fastClickingIsDisabled = YES;
698 #else
699         _fastClickingIsDisabled = NO;
700 #endif
701     }
702
703     [self _frameOrBoundsChanged];
704
705     NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
706     [center addObserver:self selector:@selector(_keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
707     [center addObserver:self selector:@selector(_keyboardDidChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
708     [center addObserver:self selector:@selector(_keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
709     [center addObserver:self selector:@selector(_keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
710     [center addObserver:self selector:@selector(_keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
711     [center addObserver:self selector:@selector(_windowDidRotate:) name:UIWindowDidRotateNotification object:nil];
712     [center addObserver:self selector:@selector(_contentSizeCategoryDidChange:) name:UIContentSizeCategoryDidChangeNotification object:nil];
713     _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
714
715     [center addObserver:self selector:@selector(_accessibilitySettingsDidChange:) name:UIAccessibilityGrayscaleStatusDidChangeNotification object:nil];
716     [center addObserver:self selector:@selector(_accessibilitySettingsDidChange:) name:UIAccessibilityInvertColorsStatusDidChangeNotification object:nil];
717     [center addObserver:self selector:@selector(_accessibilitySettingsDidChange:) name:UIAccessibilityReduceMotionStatusDidChangeNotification object:nil];
718
719     [[_configuration _contentProviderRegistry] addPage:*_page];
720     _page->setForceAlwaysUserScalable([_configuration ignoresViewportScaleLimits]);
721
722     CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), hardwareKeyboardAvailabilityChangedCallback, (CFStringRef)[NSString stringWithUTF8String:kGSEventHardwareKeyboardAvailabilityChangedNotification], nullptr, CFNotificationSuspensionBehaviorCoalesce);
723 #endif
724
725 #if PLATFORM(MAC)
726     _impl = std::make_unique<WebKit::WebViewImpl>(self, self, processPool, pageConfiguration.copyRef());
727     _page = &_impl->page();
728
729     _impl->setAutomaticallyAdjustsContentInsets(true);
730     _impl->setRequiresUserActionForEditingControlsManager([configuration _requiresUserActionForEditingControlsManager]);
731 #endif
732
733 #if ENABLE(ACCESSIBILITY_EVENTS)
734     // Check _AXSWebAccessibilityEventsEnabled here to avoid compiler optimizing
735     // out the null check of kAXSWebAccessibilityEventsEnabledNotification.
736     if (!isNullFunctionPointer(_AXSWebAccessibilityEventsEnabled))
737         CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), accessibilityEventsEnabledChangedCallback, kAXSWebAccessibilityEventsEnabledNotification, 0, CFNotificationSuspensionBehaviorDeliverImmediately);
738     [self _updateAccessibilityEventsEnabled];
739 #endif
740
741     if (NSString *applicationNameForUserAgent = configuration.applicationNameForUserAgent)
742         _page->setApplicationNameForUserAgent(applicationNameForUserAgent);
743
744     _navigationState = std::make_unique<WebKit::NavigationState>(self);
745     _page->setNavigationClient(_navigationState->createNavigationClient());
746
747     _uiDelegate = std::make_unique<WebKit::UIDelegate>(self);
748     _page->setFindClient(std::make_unique<WebKit::FindClient>(self));
749     _page->setDiagnosticLoggingClient(std::make_unique<WebKit::DiagnosticLoggingClient>(self));
750
751     _iconLoadingDelegate = std::make_unique<WebKit::IconLoadingDelegate>(self);
752
753     [self _setUpSQLiteDatabaseTrackerClient];
754
755     for (auto& pair : pageConfiguration->urlSchemeHandlers())
756         _page->setURLSchemeHandlerForScheme(WebKit::WebURLSchemeHandlerCocoa::create(static_cast<WebKit::WebURLSchemeHandlerCocoa&>(pair.value.get()).apiHandler()), pair.key);
757
758     pageToViewMap().add(_page.get(), self);
759
760 #if PLATFORM(IOS_FAMILY)
761     _dragInteractionPolicy = _WKDragInteractionPolicyDefault;
762
763     _timeOfRequestForVisibleContentRectUpdate = MonotonicTime::now();
764     _timeOfLastVisibleContentRectUpdate = MonotonicTime::now();
765 #if PLATFORM(WATCHOS)
766     _allowsViewportShrinkToFit = YES;
767 #else
768     _allowsViewportShrinkToFit = NO;
769 #endif
770 #endif // PLATFORM(IOS_FAMILY)
771 }
772
773 - (void)_setUpSQLiteDatabaseTrackerClient
774 {
775 #if PLATFORM(IOS_FAMILY)
776     WebBackgroundTaskController *controller = [WebBackgroundTaskController sharedController];
777     if (controller.backgroundTaskStartBlock)
778         return;
779
780     controller.backgroundTaskStartBlock = ^NSUInteger (void (^expirationHandler)())
781     {
782         return [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"com.apple.WebKit.DatabaseActivity" expirationHandler:expirationHandler];
783     };
784     controller.backgroundTaskEndBlock = ^(UIBackgroundTaskIdentifier taskIdentifier)
785     {
786         [[UIApplication sharedApplication] endBackgroundTask:taskIdentifier];
787     };
788     controller.invalidBackgroundTaskIdentifier = UIBackgroundTaskInvalid;
789
790     WebCore::SQLiteDatabaseTracker::setClient(&WebCore::WebSQLiteDatabaseTrackerClient::sharedWebSQLiteDatabaseTrackerClient());
791 #endif
792 }
793
794 - (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration
795 {
796     if (!(self = [super initWithFrame:frame]))
797         return nil;
798
799     [self _initializeWithConfiguration:configuration];
800
801     return self;
802 }
803
804 - (instancetype)initWithCoder:(NSCoder *)coder
805 {
806     if (!(self = [super initWithCoder:coder]))
807         return nil;
808
809     WKWebViewConfiguration *configuration = decodeObjectOfClassForKeyFromCoder([WKWebViewConfiguration class], @"configuration", coder);
810     [self _initializeWithConfiguration:configuration];
811
812     self.allowsBackForwardNavigationGestures = [coder decodeBoolForKey:@"allowsBackForwardNavigationGestures"];
813     self.customUserAgent = decodeObjectOfClassForKeyFromCoder([NSString class], @"customUserAgent", coder);
814     self.allowsLinkPreview = [coder decodeBoolForKey:@"allowsLinkPreview"];
815
816 #if PLATFORM(MAC)
817     self.allowsMagnification = [coder decodeBoolForKey:@"allowsMagnification"];
818     self.magnification = [coder decodeDoubleForKey:@"magnification"];
819 #endif
820
821     return self;
822 }
823
824 - (void)encodeWithCoder:(NSCoder *)coder
825 {
826     [super encodeWithCoder:coder];
827
828     [coder encodeObject:_configuration.get() forKey:@"configuration"];
829
830     [coder encodeBool:self.allowsBackForwardNavigationGestures forKey:@"allowsBackForwardNavigationGestures"];
831     [coder encodeObject:self.customUserAgent forKey:@"customUserAgent"];
832     [coder encodeBool:self.allowsLinkPreview forKey:@"allowsLinkPreview"];
833
834 #if PLATFORM(MAC)
835     [coder encodeBool:self.allowsMagnification forKey:@"allowsMagnification"];
836     [coder encodeDouble:self.magnification forKey:@"magnification"];
837 #endif
838 }
839
840 - (void)dealloc
841 {
842 #if PLATFORM(MAC)
843     [_textFinderClient willDestroyView:self];
844 #endif
845
846 #if PLATFORM(IOS_FAMILY)
847     [_contentView _webViewDestroyed];
848
849     if (_remoteObjectRegistry)
850         _page->process().processPool().removeMessageReceiver(Messages::RemoteObjectRegistry::messageReceiverName(), _page->pageID());
851 #endif
852
853     _page->close();
854
855 #if PLATFORM(IOS_FAMILY)
856     [_remoteObjectRegistry _invalidate];
857     [[_configuration _contentProviderRegistry] removePage:*_page];
858     [[NSNotificationCenter defaultCenter] removeObserver:self];
859     [_scrollView setInternalDelegate:nil];
860
861     CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), (CFStringRef)[NSString stringWithUTF8String:kGSEventHardwareKeyboardAvailabilityChangedNotification], nullptr);
862 #endif
863
864 #if ENABLE(ACCESSIBILITY_EVENTS)
865     CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), nullptr, nullptr);
866 #endif
867
868     pageToViewMap().remove(_page.get());
869
870     [super dealloc];
871 }
872
873 - (id)valueForUndefinedKey:(NSString *)key {
874     if ([key isEqualToString:@"serverTrust"])
875         return (__bridge id)[self serverTrust];
876
877     return [super valueForUndefinedKey:key];
878 }
879
880 - (WKWebViewConfiguration *)configuration
881 {
882     return [[_configuration copy] autorelease];
883 }
884
885 - (WKBackForwardList *)backForwardList
886 {
887     return wrapper(_page->backForwardList());
888 }
889
890 - (id <WKNavigationDelegate>)navigationDelegate
891 {
892     return _navigationState->navigationDelegate().autorelease();
893 }
894
895 - (void)setNavigationDelegate:(id <WKNavigationDelegate>)navigationDelegate
896 {
897     _page->setNavigationClient(_navigationState->createNavigationClient());
898     _navigationState->setNavigationDelegate(navigationDelegate);
899 }
900
901 - (id <WKUIDelegate>)UIDelegate
902 {
903     return _uiDelegate->delegate().autorelease();
904 }
905
906 - (void)setUIDelegate:(id<WKUIDelegate>)UIDelegate
907 {
908     _uiDelegate->setDelegate(UIDelegate);
909 #if ENABLE(CONTEXT_MENUS)
910     _page->setContextMenuClient(_uiDelegate->createContextMenuClient());
911 #endif
912     _page->setUIClient(_uiDelegate->createUIClient());
913 }
914
915 - (id <_WKIconLoadingDelegate>)_iconLoadingDelegate
916 {
917     return _iconLoadingDelegate->delegate().autorelease();
918 }
919
920 - (void)_setIconLoadingDelegate:(id<_WKIconLoadingDelegate>)iconLoadingDelegate
921 {
922     _page->setIconLoadingClient(_iconLoadingDelegate->createIconLoadingClient());
923     _iconLoadingDelegate->setDelegate(iconLoadingDelegate);
924 }
925
926 - (WKNavigation *)loadRequest:(NSURLRequest *)request
927 {
928     return wrapper(_page->loadRequest(request));
929 }
930
931 - (WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL
932 {
933     if (![URL isFileURL])
934         [NSException raise:NSInvalidArgumentException format:@"%@ is not a file URL", URL];
935
936     if (![readAccessURL isFileURL])
937         [NSException raise:NSInvalidArgumentException format:@"%@ is not a file URL", readAccessURL];
938
939     return wrapper(_page->loadFile([URL _web_originalDataAsWTFString], [readAccessURL _web_originalDataAsWTFString]));
940 }
941
942 - (WKNavigation *)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
943 {
944     NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
945
946     return [self loadData:data MIMEType:@"text/html" characterEncodingName:@"UTF-8" baseURL:baseURL];
947 }
948
949 - (WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL
950 {
951     return wrapper(_page->loadData({ static_cast<const uint8_t*>(data.bytes), data.length }, MIMEType, characterEncodingName, baseURL.absoluteString));
952 }
953
954 - (WKNavigation *)goToBackForwardListItem:(WKBackForwardListItem *)item
955 {
956     return wrapper(_page->goToBackForwardItem(item._item));
957 }
958
959 - (NSString *)title
960 {
961     return _page->pageLoadState().title();
962 }
963
964 - (NSURL *)URL
965 {
966     return [NSURL _web_URLWithWTFString:_page->pageLoadState().activeURL()];
967 }
968
969 - (BOOL)isLoading
970 {
971     return _page->pageLoadState().isLoading();
972 }
973
974 - (double)estimatedProgress
975 {
976     return _page->pageLoadState().estimatedProgress();
977 }
978
979 - (BOOL)hasOnlySecureContent
980 {
981     return _page->pageLoadState().hasOnlySecureContent();
982 }
983
984 - (SecTrustRef)serverTrust
985 {
986 #if HAVE(SEC_TRUST_SERIALIZATION)
987     auto certificateInfo = _page->pageLoadState().certificateInfo();
988     if (!certificateInfo)
989         return nil;
990
991     return certificateInfo->certificateInfo().trust();
992 #else
993     return nil;
994 #endif
995 }
996
997 - (BOOL)canGoBack
998 {
999     return _page->pageLoadState().canGoBack();
1000 }
1001
1002 - (BOOL)canGoForward
1003 {
1004     return _page->pageLoadState().canGoForward();
1005 }
1006
1007 - (WKNavigation *)goBack
1008 {
1009     return wrapper(_page->goBack());
1010 }
1011
1012 - (WKNavigation *)goForward
1013 {
1014     return wrapper(_page->goForward());
1015 }
1016
1017 - (WKNavigation *)reload
1018 {
1019     OptionSet<WebCore::ReloadOption> reloadOptions;
1020     if (linkedOnOrAfter(WebKit::SDKVersion::FirstWithExpiredOnlyReloadBehavior))
1021         reloadOptions.add(WebCore::ReloadOption::ExpiredOnly);
1022
1023     return wrapper(_page->reload(reloadOptions));
1024 }
1025
1026 - (WKNavigation *)reloadFromOrigin
1027 {
1028     return wrapper(_page->reload(WebCore::ReloadOption::FromOrigin));
1029 }
1030
1031 - (void)stopLoading
1032 {
1033     _page->stopLoading();
1034 }
1035
1036 static WKErrorCode callbackErrorCode(WebKit::CallbackBase::Error error)
1037 {
1038     switch (error) {
1039     case WebKit::CallbackBase::Error::None:
1040         ASSERT_NOT_REACHED();
1041         return WKErrorUnknown;
1042
1043     case WebKit::CallbackBase::Error::Unknown:
1044         return WKErrorUnknown;
1045
1046     case WebKit::CallbackBase::Error::ProcessExited:
1047         return WKErrorWebContentProcessTerminated;
1048
1049     case WebKit::CallbackBase::Error::OwnerWasInvalidated:
1050         return WKErrorWebViewInvalidated;
1051     }
1052 }
1053
1054 - (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *))completionHandler
1055 {
1056     [self _evaluateJavaScript:javaScriptString forceUserGesture:YES completionHandler:completionHandler];
1057 }
1058
1059 - (void)_evaluateJavaScript:(NSString *)javaScriptString forceUserGesture:(BOOL)forceUserGesture completionHandler:(void (^)(id, NSError *))completionHandler
1060 {
1061     auto handler = adoptNS([completionHandler copy]);
1062
1063     _page->runJavaScriptInMainFrame(javaScriptString, forceUserGesture, [handler](API::SerializedScriptValue* serializedScriptValue, bool hadException, const WebCore::ExceptionDetails& details, WebKit::ScriptValueCallback::Error errorCode) {
1064         if (!handler)
1065             return;
1066
1067         if (errorCode != WebKit::ScriptValueCallback::Error::None) {
1068             auto error = createNSError(callbackErrorCode(errorCode));
1069             if (errorCode == WebKit::ScriptValueCallback::Error::OwnerWasInvalidated) {
1070                 // The OwnerWasInvalidated callback is synchronous. We don't want to call the block from within it
1071                 // because that can trigger re-entrancy bugs in WebKit.
1072                 // FIXME: It would be even better if GenericCallback did this for us.
1073                 dispatch_async(dispatch_get_main_queue(), [handler, error] {
1074                     auto rawHandler = (void (^)(id, NSError *))handler.get();
1075                     rawHandler(nil, error.get());
1076                 });
1077                 return;
1078             }
1079
1080             auto rawHandler = (void (^)(id, NSError *))handler.get();
1081             rawHandler(nil, error.get());
1082             return;
1083         }
1084
1085         auto rawHandler = (void (^)(id, NSError *))handler.get();
1086         if (hadException) {
1087             ASSERT(!serializedScriptValue);
1088
1089             RetainPtr<NSMutableDictionary> userInfo = adoptNS([[NSMutableDictionary alloc] init]);
1090
1091             [userInfo setObject:localizedDescriptionForErrorCode(WKErrorJavaScriptExceptionOccurred) forKey:NSLocalizedDescriptionKey];
1092             [userInfo setObject:static_cast<NSString *>(details.message) forKey:_WKJavaScriptExceptionMessageErrorKey];
1093             [userInfo setObject:@(details.lineNumber) forKey:_WKJavaScriptExceptionLineNumberErrorKey];
1094             [userInfo setObject:@(details.columnNumber) forKey:_WKJavaScriptExceptionColumnNumberErrorKey];
1095
1096             if (!details.sourceURL.isEmpty())
1097                 [userInfo setObject:[NSURL _web_URLWithWTFString:details.sourceURL] forKey:_WKJavaScriptExceptionSourceURLErrorKey];
1098
1099             rawHandler(nil, adoptNS([[NSError alloc] initWithDomain:WKErrorDomain code:WKErrorJavaScriptExceptionOccurred userInfo:userInfo.get()]).get());
1100             return;
1101         }
1102
1103         if (!serializedScriptValue) {
1104             rawHandler(nil, createNSError(WKErrorJavaScriptResultTypeIsUnsupported).get());
1105             return;
1106         }
1107
1108         id body = API::SerializedScriptValue::deserialize(serializedScriptValue->internalRepresentation(), 0);
1109         rawHandler(body, nil);
1110     });
1111 }
1112
1113 #if PLATFORM(MAC)
1114 - (void)takeSnapshotWithConfiguration:(WKSnapshotConfiguration *)snapshotConfiguration completionHandler:(void(^)(NSImage *, NSError *))completionHandler
1115 {
1116     CGRect rectInViewCoordinates = snapshotConfiguration && !CGRectIsNull(snapshotConfiguration.rect) ? snapshotConfiguration.rect : self.bounds;
1117     CGFloat snapshotWidth;
1118     if (snapshotConfiguration)
1119         snapshotWidth = snapshotConfiguration.snapshotWidth.doubleValue ?: rectInViewCoordinates.size.width;
1120     else
1121         snapshotWidth = self.bounds.size.width;
1122
1123     auto handler = makeBlockPtr(completionHandler);
1124     CGFloat imageScale = snapshotWidth / rectInViewCoordinates.size.width;
1125     CGFloat imageHeight = imageScale * rectInViewCoordinates.size.height;
1126
1127     // Need to scale by device scale factor or the image will be distorted.
1128     CGFloat deviceScale = _page->deviceScaleFactor();
1129     WebCore::IntSize bitmapSize(snapshotWidth, imageHeight);
1130     bitmapSize.scale(deviceScale, deviceScale);
1131
1132     // Software snapshot will not capture elements rendered with hardware acceleration (WebGL, video, etc).
1133     _page->takeSnapshot(WebCore::enclosingIntRect(rectInViewCoordinates), bitmapSize, WebKit::SnapshotOptionsInViewCoordinates, [handler, snapshotWidth, imageHeight](const WebKit::ShareableBitmap::Handle& imageHandle, WebKit::CallbackBase::Error errorCode) {
1134         if (errorCode != WebKit::ScriptValueCallback::Error::None) {
1135             auto error = createNSError(callbackErrorCode(errorCode));
1136             handler(nil, error.get());
1137             return;
1138         }
1139
1140         RefPtr<WebKit::ShareableBitmap> bitmap = WebKit::ShareableBitmap::create(imageHandle, WebKit::SharedMemory::Protection::ReadOnly);
1141         RetainPtr<CGImageRef> cgImage = bitmap ? bitmap->makeCGImage() : nullptr;
1142         RetainPtr<NSImage> nsImage = adoptNS([[NSImage alloc] initWithCGImage:cgImage.get() size:NSMakeSize(snapshotWidth, imageHeight)]);
1143         handler(nsImage.get(), nil);
1144     });
1145 }
1146
1147 #elif PLATFORM(IOS_FAMILY)
1148 - (void)takeSnapshotWithConfiguration:(WKSnapshotConfiguration *)snapshotConfiguration completionHandler:(void(^)(UIImage *, NSError *))completionHandler
1149 {
1150     CGRect rectInViewCoordinates = snapshotConfiguration && !CGRectIsNull(snapshotConfiguration.rect) ? snapshotConfiguration.rect : self.bounds;
1151     CGFloat snapshotWidth;
1152     if (snapshotConfiguration)
1153         snapshotWidth = snapshotConfiguration.snapshotWidth.doubleValue ?: rectInViewCoordinates.size.width;
1154     else
1155         snapshotWidth = self.bounds.size.width;
1156
1157     auto handler = makeBlockPtr(completionHandler);
1158     CGFloat deviceScale = _page->deviceScaleFactor();
1159
1160     [self _snapshotRect:rectInViewCoordinates intoImageOfWidth:(snapshotWidth * deviceScale) completionHandler:^(CGImageRef snapshotImage) {
1161         RetainPtr<NSError> error;
1162         RetainPtr<UIImage> uiImage;
1163
1164         if (!snapshotImage)
1165             error = createNSError(WKErrorUnknown);
1166         else
1167             uiImage = adoptNS([[UIImage alloc] initWithCGImage:snapshotImage scale:deviceScale orientation:UIImageOrientationUp]);
1168
1169         handler(uiImage.get(), error.get());
1170     }];
1171 }
1172 #endif
1173
1174 - (NSString *)customUserAgent
1175 {
1176     return _page->customUserAgent();
1177 }
1178
1179 - (void)setCustomUserAgent:(NSString *)customUserAgent
1180 {
1181     _page->setCustomUserAgent(customUserAgent);
1182 }
1183
1184 - (WKPageRef)_pageForTesting
1185 {
1186     return toAPI(_page.get());
1187 }
1188
1189 - (WebKit::WebPageProxy *)_page
1190 {
1191     return _page.get();
1192 }
1193
1194 - (BOOL)allowsLinkPreview
1195 {
1196 #if PLATFORM(MAC)
1197     return _impl->allowsLinkPreview();
1198 #elif PLATFORM(IOS_FAMILY)
1199     return _allowsLinkPreview;
1200 #endif
1201 }
1202
1203 - (void)setAllowsLinkPreview:(BOOL)allowsLinkPreview
1204 {
1205 #if PLATFORM(MAC)
1206     _impl->setAllowsLinkPreview(allowsLinkPreview);
1207     return;
1208 #elif PLATFORM(IOS_FAMILY)
1209     if (_allowsLinkPreview == allowsLinkPreview)
1210         return;
1211
1212     _allowsLinkPreview = allowsLinkPreview;
1213
1214 #if HAVE(LINK_PREVIEW)
1215     if (_allowsLinkPreview)
1216         [_contentView _registerPreview];
1217     else
1218         [_contentView _unregisterPreview];
1219 #endif // HAVE(LINK_PREVIEW)
1220 #endif // PLATFORM(IOS_FAMILY)
1221 }
1222
1223 - (CGSize)_viewportSizeForCSSViewportUnits
1224 {
1225     return _page->viewportSizeForCSSViewportUnits();
1226 }
1227
1228 - (void)_setViewportSizeForCSSViewportUnits:(CGSize)viewportSize
1229 {
1230     auto viewportSizeForViewportUnits = WebCore::IntSize(viewportSize);
1231     if (viewportSizeForViewportUnits.isEmpty())
1232         [NSException raise:NSInvalidArgumentException format:@"Viewport size should not be empty"];
1233
1234     _page->setViewportSizeForCSSViewportUnits(viewportSizeForViewportUnits);
1235 }
1236
1237 static NSTextAlignment nsTextAlignment(WebKit::TextAlignment alignment)
1238 {
1239     switch (alignment) {
1240     case WebKit::NoAlignment:
1241         return NSTextAlignmentNatural;
1242     case WebKit::LeftAlignment:
1243         return NSTextAlignmentLeft;
1244     case WebKit::RightAlignment:
1245         return NSTextAlignmentRight;
1246     case WebKit::CenterAlignment:
1247         return NSTextAlignmentCenter;
1248     case WebKit::JustifiedAlignment:
1249         return NSTextAlignmentJustified;
1250     }
1251     ASSERT_NOT_REACHED();
1252     return NSTextAlignmentNatural;
1253 }
1254
1255 static NSDictionary *dictionaryRepresentationForEditorState(const WebKit::EditorState& state)
1256 {
1257     if (state.isMissingPostLayoutData)
1258         return @{ @"post-layout-data" : @NO };
1259
1260     auto& postLayoutData = state.postLayoutData();
1261     return @{
1262         @"post-layout-data" : @YES,
1263         @"bold": postLayoutData.typingAttributes & WebKit::AttributeBold ? @YES : @NO,
1264         @"italic": postLayoutData.typingAttributes & WebKit::AttributeItalics ? @YES : @NO,
1265         @"underline": postLayoutData.typingAttributes & WebKit::AttributeUnderline ? @YES : @NO,
1266         @"text-alignment": @(nsTextAlignment(static_cast<WebKit::TextAlignment>(postLayoutData.textAlignment))),
1267         @"text-color": (NSString *)postLayoutData.textColor.cssText()
1268     };
1269 }
1270
1271 - (void)_didChangeEditorState
1272 {
1273     id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)self.UIDelegate;
1274
1275     // FIXME: We should either rename -_webView:editorStateDidChange: to clarify that it's only intended for use when testing,
1276     // or remove it entirely and use -_webView:didChangeFontAttributes: instead once text alignment is supported in the set of
1277     // font attributes.
1278     if ([uiDelegate respondsToSelector:@selector(_webView:editorStateDidChange:)])
1279         [uiDelegate _webView:self editorStateDidChange:dictionaryRepresentationForEditorState(_page->editorState())];
1280 }
1281
1282 - (void)_showSafeBrowsingWarning:(const WebKit::SafeBrowsingWarning&)warning completionHandler:(CompletionHandler<void(Variant<WebKit::ContinueUnsafeLoad, WebCore::URL>&&)>&&)completionHandler
1283 {
1284     _safeBrowsingWarning = adoptNS([[WKSafeBrowsingWarning alloc] initWithFrame:self.bounds safeBrowsingWarning:warning completionHandler:[weakSelf = WeakObjCPtr<WKWebView>(self), completionHandler = WTFMove(completionHandler)] (auto&& result) mutable {
1285         if (auto strongSelf = weakSelf.get())
1286             [std::exchange(strongSelf->_safeBrowsingWarning, nullptr) removeFromSuperview];
1287         completionHandler(WTFMove(result));
1288     }]);
1289     [self addSubview:_safeBrowsingWarning.get()];
1290 }
1291
1292 - (void)_clearSafeBrowsingWarning
1293 {
1294     [std::exchange(_safeBrowsingWarning, nullptr) removeFromSuperview];
1295 }
1296
1297 #if ENABLE(ATTACHMENT_ELEMENT)
1298
1299 - (void)_didInsertAttachment:(API::Attachment&)attachment withSource:(NSString *)source
1300 {
1301     id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)self.UIDelegate;
1302     if ([uiDelegate respondsToSelector:@selector(_webView:didInsertAttachment:withSource:)])
1303         [uiDelegate _webView:self didInsertAttachment:wrapper(attachment) withSource:source];
1304 }
1305
1306 - (void)_didRemoveAttachment:(API::Attachment&)attachment
1307 {
1308     id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)self.UIDelegate;
1309     if ([uiDelegate respondsToSelector:@selector(_webView:didRemoveAttachment:)])
1310         [uiDelegate _webView:self didRemoveAttachment:wrapper(attachment)];
1311 }
1312
1313 #endif // ENABLE(ATTACHMENT_ELEMENT)
1314
1315 #pragma mark iOS-specific methods
1316
1317 #if PLATFORM(IOS_FAMILY)
1318
1319 - (_WKDragInteractionPolicy)_dragInteractionPolicy
1320 {
1321     return _dragInteractionPolicy;
1322 }
1323
1324 - (void)_setDragInteractionPolicy:(_WKDragInteractionPolicy)policy
1325 {
1326     if (_dragInteractionPolicy == policy)
1327         return;
1328
1329     _dragInteractionPolicy = policy;
1330 #if ENABLE(DRAG_SUPPORT)
1331     [_contentView _didChangeDragInteractionPolicy];
1332 #endif
1333 }
1334
1335 - (void)_populateArchivedSubviews:(NSMutableSet *)encodedViews
1336 {
1337     [super _populateArchivedSubviews:encodedViews];
1338
1339     if (_scrollView)
1340         [encodedViews removeObject:_scrollView.get()];
1341     if (_customContentFixedOverlayView)
1342         [encodedViews removeObject:_customContentFixedOverlayView.get()];
1343 }
1344
1345 - (BOOL)_isBackground
1346 {
1347     if ([self _isDisplayingPDF])
1348         return [_customContentView web_isBackground];
1349     return [_contentView isBackground];
1350 }
1351
1352 - (void)setFrame:(CGRect)frame
1353 {
1354     CGRect oldFrame = self.frame;
1355     [super setFrame:frame];
1356
1357     if (!CGSizeEqualToSize(oldFrame.size, frame.size))
1358         [self _frameOrBoundsChanged];
1359 }
1360
1361 - (void)setBounds:(CGRect)bounds
1362 {
1363     CGRect oldBounds = self.bounds;
1364     [super setBounds:bounds];
1365     [_customContentFixedOverlayView setFrame:self.bounds];
1366
1367     if (!CGSizeEqualToSize(oldBounds.size, bounds.size))
1368         [self _frameOrBoundsChanged];
1369 }
1370
1371 - (void)layoutSubviews
1372 {
1373     [_safeBrowsingWarning setFrame:self.bounds];
1374     [super layoutSubviews];
1375     [self _frameOrBoundsChanged];
1376 }
1377
1378 - (UIScrollView *)scrollView
1379 {
1380     return _scrollView.get();
1381 }
1382
1383 ALLOW_DEPRECATED_DECLARATIONS_BEGIN
1384 - (WKBrowsingContextController *)browsingContextController
1385 {
1386     return [_contentView browsingContextController];
1387 }
1388 ALLOW_DEPRECATED_DECLARATIONS_END
1389
1390 - (BOOL)becomeFirstResponder
1391 {
1392     UIView *currentContentView = self._currentContentView;
1393     if (currentContentView == _contentView && [_contentView superview])
1394         return [_contentView becomeFirstResponderForWebView] || [super becomeFirstResponder];
1395
1396     return [currentContentView becomeFirstResponder] || [super becomeFirstResponder];
1397 }
1398
1399 - (BOOL)canBecomeFirstResponder
1400 {
1401     if (self._currentContentView == _contentView)
1402         return [_contentView canBecomeFirstResponderForWebView];
1403
1404     return YES;
1405 }
1406
1407 - (BOOL)resignFirstResponder
1408 {
1409     if ([_contentView isFirstResponder])
1410         return [_contentView resignFirstResponderForWebView];
1411
1412     return [super resignFirstResponder];
1413 }
1414
1415 FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_ACTION_TO_WKCONTENTVIEW)
1416
1417 - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
1418 {
1419     #define FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW(_action) \
1420         if (action == @selector(_action:)) \
1421             return self.usesStandardContentView && [_contentView canPerformActionForWebView:action withSender:sender];
1422
1423     FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW)
1424     FOR_EACH_PRIVATE_WKCONTENTVIEW_ACTION(FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW)
1425     FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW(setTextColor:sender)
1426     FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW(setFontSize:sender)
1427     FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW(setFont:sender)
1428     FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW(_setTextColor:sender)
1429     FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW(_setFontSize:sender)
1430     FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW(_setFont:sender)
1431
1432     #undef FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW
1433
1434     return [super canPerformAction:action withSender:sender];
1435 }
1436
1437 - (id)targetForAction:(SEL)action withSender:(id)sender
1438 {
1439     #define FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_action) \
1440         if (action == @selector(_action:) && self.usesStandardContentView) \
1441             return [_contentView targetForActionForWebView:action withSender:sender];
1442
1443     FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW)
1444     FOR_EACH_PRIVATE_WKCONTENTVIEW_ACTION(FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW)
1445     FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(setTextColor:sender)
1446     FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(setFontSize:sender)
1447     FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(setFont:sender)
1448     FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_setTextColor:sender)
1449     FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_setFontSize:sender)
1450     FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_setFont:sender)
1451
1452     #undef FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW
1453
1454     return [super targetForAction:action withSender:sender];
1455 }
1456
1457 - (void)setFont:(UIFont *)font sender:(id)sender
1458 {
1459     [_contentView setFontForWebView:font sender:sender];
1460 }
1461
1462 - (void)setTextColor:(UIColor *)color sender:(id)sender
1463 {
1464     [_contentView setTextColorForWebView:color sender:sender];
1465 }
1466
1467 - (void)setFontSize:(CGFloat)fontSize sender:(id)sender
1468 {
1469     [_contentView setFontSizeForWebView:fontSize sender:sender];
1470 }
1471
1472 static inline CGFloat floorToDevicePixel(CGFloat input, float deviceScaleFactor)
1473 {
1474     return CGFloor(input * deviceScaleFactor) / deviceScaleFactor;
1475 }
1476
1477 static inline bool pointsEqualInDevicePixels(CGPoint a, CGPoint b, float deviceScaleFactor)
1478 {
1479     return fabs(a.x * deviceScaleFactor - b.x * deviceScaleFactor) < std::numeric_limits<float>::epsilon()
1480         && fabs(a.y * deviceScaleFactor - b.y * deviceScaleFactor) < std::numeric_limits<float>::epsilon();
1481 }
1482
1483 static CGSize roundScrollViewContentSize(const WebKit::WebPageProxy& page, CGSize contentSize)
1484 {
1485     float deviceScaleFactor = page.deviceScaleFactor();
1486     return CGSizeMake(floorToDevicePixel(contentSize.width, deviceScaleFactor), floorToDevicePixel(contentSize.height, deviceScaleFactor));
1487 }
1488
1489 - (UIView *)_currentContentView
1490 {
1491     return _customContentView ? [_customContentView web_contentView] : _contentView.get();
1492 }
1493
1494 - (WKWebViewContentProviderRegistry *)_contentProviderRegistry
1495 {
1496     return [_configuration _contentProviderRegistry];
1497 }
1498
1499 - (WKSelectionGranularity)_selectionGranularity
1500 {
1501     return [_configuration selectionGranularity];
1502 }
1503
1504 - (void)_setHasCustomContentView:(BOOL)pageHasCustomContentView loadedMIMEType:(const WTF::String&)mimeType
1505 {
1506     if (pageHasCustomContentView) {
1507         [_customContentView removeFromSuperview];
1508         [_customContentFixedOverlayView removeFromSuperview];
1509
1510         Class representationClass = [[_configuration _contentProviderRegistry] providerForMIMEType:mimeType];
1511         ASSERT(representationClass);
1512         _customContentView = adoptNS([[representationClass alloc] web_initWithFrame:self.bounds webView:self mimeType:mimeType]);
1513         _customContentFixedOverlayView = adoptNS([[UIView alloc] initWithFrame:self.bounds]);
1514         [_customContentFixedOverlayView layer].name = @"CustomContentFixedOverlay";
1515         [_customContentFixedOverlayView setUserInteractionEnabled:NO];
1516
1517         [[_contentView unscaledView] removeFromSuperview];
1518         [_contentView removeFromSuperview];
1519         [_scrollView addSubview:_customContentView.get()];
1520         [self addSubview:_customContentFixedOverlayView.get()];
1521
1522         [_customContentView web_setMinimumSize:self.bounds.size];
1523         [_customContentView web_setFixedOverlayView:_customContentFixedOverlayView.get()];
1524
1525         _scrollViewBackgroundColor = WebCore::Color();
1526         [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1527
1528         [self _setAvoidsUnsafeArea:NO];
1529     } else if (_customContentView) {
1530         [_customContentView removeFromSuperview];
1531         _customContentView = nullptr;
1532
1533         [_customContentFixedOverlayView removeFromSuperview];
1534         _customContentFixedOverlayView = nullptr;
1535
1536         [_scrollView addSubview:_contentView.get()];
1537         [_scrollView addSubview:[_contentView unscaledView]];
1538         [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
1539
1540         [_customContentFixedOverlayView setFrame:self.bounds];
1541         [self addSubview:_customContentFixedOverlayView.get()];
1542     }
1543
1544     if (self.isFirstResponder) {
1545         UIView *currentContentView = self._currentContentView;
1546         if (currentContentView == _contentView ? [_contentView canBecomeFirstResponderForWebView] : currentContentView.canBecomeFirstResponder)
1547             [currentContentView becomeFirstResponder];
1548     }
1549 }
1550
1551 - (void)_didFinishLoadingDataForCustomContentProviderWithSuggestedFilename:(const String&)suggestedFilename data:(NSData *)data
1552 {
1553     ASSERT(_customContentView);
1554     [_customContentView web_setContentProviderData:data suggestedFilename:suggestedFilename];
1555
1556     // FIXME: It may make more sense for custom content providers to invoke this when they're ready,
1557     // because there's no guarantee that all custom content providers will lay out synchronously.
1558     _page->didLayoutForCustomContentProvider();
1559 }
1560
1561 - (void)_handleKeyUIEvent:(::UIEvent *)event
1562 {
1563     // We only want to handle key events from the hardware keyboard when we are
1564     // first responder and a custom content view is installed; otherwise,
1565     // WKContentView will be the first responder and expects to get key events directly.
1566     if ([self isFirstResponder] && event._hidEvent) {
1567         if ([_customContentView respondsToSelector:@selector(web_handleKeyEvent:)]) {
1568             if ([_customContentView web_handleKeyEvent:event])
1569                 return;
1570         }
1571     }
1572
1573     [super _handleKeyUIEvent:event];
1574 }
1575
1576 - (void)_willInvokeUIScrollViewDelegateCallback
1577 {
1578     _delayUpdateVisibleContentRects = YES;
1579 }
1580
1581 - (void)_didInvokeUIScrollViewDelegateCallback
1582 {
1583     _delayUpdateVisibleContentRects = NO;
1584     if (_hadDelayedUpdateVisibleContentRects) {
1585         _hadDelayedUpdateVisibleContentRects = NO;
1586         [self _scheduleVisibleContentRectUpdate];
1587     }
1588 }
1589
1590 static CGFloat contentZoomScale(WKWebView *webView)
1591 {
1592     CGFloat scale = webView._currentContentView.layer.affineTransform.a;
1593     ASSERT(scale == [webView->_scrollView zoomScale]);
1594     return scale;
1595 }
1596
1597 static WebCore::Color baseScrollViewBackgroundColor(WKWebView *webView)
1598 {
1599     if (webView->_customContentView)
1600         return [webView->_customContentView backgroundColor].CGColor;
1601
1602     if (webView->_gestureController) {
1603         WebCore::Color color = webView->_gestureController->backgroundColorForCurrentSnapshot();
1604         if (color.isValid())
1605             return color;
1606     }
1607
1608     return webView->_page->pageExtendedBackgroundColor();
1609 }
1610
1611 static WebCore::Color scrollViewBackgroundColor(WKWebView *webView)
1612 {
1613     if (!webView.opaque)
1614         return WebCore::Color::transparent;
1615
1616     WebCore::Color color = baseScrollViewBackgroundColor(webView);
1617
1618     if (!color.isValid())
1619         color = WebCore::Color::white;
1620
1621     CGFloat zoomScale = contentZoomScale(webView);
1622     CGFloat minimumZoomScale = [webView->_scrollView minimumZoomScale];
1623     if (zoomScale < minimumZoomScale) {
1624         CGFloat slope = 12;
1625         CGFloat opacity = std::max<CGFloat>(1 - slope * (minimumZoomScale - zoomScale), 0);
1626         color = WebCore::colorWithOverrideAlpha(color.rgb(), opacity);
1627     }
1628
1629     return color;
1630 }
1631
1632 - (void)_updateScrollViewBackground
1633 {
1634     WebCore::Color color = scrollViewBackgroundColor(self);
1635
1636     if (_scrollViewBackgroundColor == color)
1637         return;
1638
1639     _scrollViewBackgroundColor = color;
1640
1641     auto uiBackgroundColor = adoptNS([[UIColor alloc] initWithCGColor:cachedCGColor(color)]);
1642     [_scrollView setBackgroundColor:uiBackgroundColor.get()];
1643
1644     // Update the indicator style based on the lightness/darkness of the background color.
1645     double hue, saturation, lightness;
1646     color.getHSL(hue, saturation, lightness);
1647     if (lightness <= .5 && color.isVisible())
1648         [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleWhite];
1649     else
1650         [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleDefault];
1651 }
1652
1653 - (void)_videoControlsManagerDidChange
1654 {
1655 #if ENABLE(FULLSCREEN_API)
1656     if (_fullScreenWindowController)
1657         [_fullScreenWindowController videoControlsManagerDidChange];
1658 #endif
1659 }
1660
1661 - (CGPoint)_initialContentOffsetForScrollView
1662 {
1663     auto combinedUnobscuredAndScrollViewInset = [self _computedContentInset];
1664     return CGPointMake(-combinedUnobscuredAndScrollViewInset.left, -combinedUnobscuredAndScrollViewInset.top);
1665 }
1666
1667 - (CGPoint)_contentOffsetAdjustedForObscuredInset:(CGPoint)point
1668 {
1669     CGPoint result = point;
1670     UIEdgeInsets contentInset = [self _computedObscuredInset];
1671
1672     result.x -= contentInset.left;
1673     result.y -= contentInset.top;
1674
1675     return result;
1676 }
1677
1678 - (UIRectEdge)_effectiveObscuredInsetEdgesAffectedBySafeArea
1679 {
1680     if (![self usesStandardContentView])
1681         return UIRectEdgeAll;
1682     return _obscuredInsetEdgesAffectedBySafeArea;
1683 }
1684
1685 - (UIEdgeInsets)_computedObscuredInset
1686 {
1687     if (!linkedOnOrAfter(WebKit::SDKVersion::FirstWhereScrollViewContentInsetsAreNotObscuringInsets)) {
1688         // For binary compability with third party apps, treat scroll view content insets as obscuring insets when the app is compiled
1689         // against a WebKit version without the fix in r229641.
1690         return [self _computedContentInset];
1691     }
1692
1693     if (_haveSetObscuredInsets)
1694         return _obscuredInsets;
1695
1696 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1697     if (self._safeAreaShouldAffectObscuredInsets)
1698         return UIEdgeInsetsAdd(UIEdgeInsetsZero, self._scrollViewSystemContentInset, self._effectiveObscuredInsetEdgesAffectedBySafeArea);
1699 #endif
1700
1701     return UIEdgeInsetsZero;
1702 }
1703
1704 - (UIEdgeInsets)_computedContentInset
1705 {
1706     if (_haveSetObscuredInsets)
1707         return _obscuredInsets;
1708
1709     UIEdgeInsets insets = [_scrollView contentInset];
1710
1711 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1712     if (self._safeAreaShouldAffectObscuredInsets)
1713         insets = UIEdgeInsetsAdd(insets, self._scrollViewSystemContentInset, self._effectiveObscuredInsetEdgesAffectedBySafeArea);
1714 #endif
1715
1716     return insets;
1717 }
1718
1719 - (UIEdgeInsets)_computedUnobscuredSafeAreaInset
1720 {
1721     if (_haveSetUnobscuredSafeAreaInsets)
1722         return _unobscuredSafeAreaInsets;
1723
1724 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1725     if (!self._safeAreaShouldAffectObscuredInsets)
1726         return self.safeAreaInsets;
1727 #endif
1728
1729     return UIEdgeInsetsZero;
1730 }
1731
1732 - (void)_processWillSwapOrDidExit
1733 {
1734     // FIXME: Which ones of these need to be done in the process swap case and which ones in the exit case?
1735     [self _hidePasswordView];
1736     [self _cancelAnimatedResize];
1737
1738     _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
1739     _initialScaleFactor = 1;
1740     _hasCommittedLoadForMainFrame = NO;
1741     _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1742     _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
1743     _waitingForEndAnimatedResize = NO;
1744     _waitingForCommitAfterAnimatedResize = NO;
1745     _animatedResizeOriginalContentWidth = 0;
1746     [_contentView setHidden:NO];
1747     _scrollOffsetToRestore = std::nullopt;
1748     _unobscuredCenterToRestore = std::nullopt;
1749     _scrollViewBackgroundColor = WebCore::Color();
1750     _delayUpdateVisibleContentRects = NO;
1751     _hadDelayedUpdateVisibleContentRects = NO;
1752     _currentlyAdjustingScrollViewInsetsForKeyboard = NO;
1753     _lastSentViewLayoutSize = std::nullopt;
1754     _lastSentMaximumUnobscuredSize = std::nullopt;
1755     _lastSentDeviceOrientation = std::nullopt;
1756
1757     _frozenVisibleContentRect = std::nullopt;
1758     _frozenUnobscuredContentRect = std::nullopt;
1759
1760     _firstPaintAfterCommitLoadTransactionID = 0;
1761     _firstTransactionIDAfterPageRestore = std::nullopt;
1762
1763     _hasScheduledVisibleRectUpdate = NO;
1764     _commitDidRestoreScrollPosition = NO;
1765
1766     _avoidsUnsafeArea = YES;
1767 }
1768
1769 - (void)_processWillSwap
1770 {
1771     RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _processWillSwap]", self);
1772     [self _processWillSwapOrDidExit];
1773 }
1774
1775 - (void)_processDidExit
1776 {
1777     RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _processDidExit]", self);
1778
1779     [self _processWillSwapOrDidExit];
1780
1781     [_contentView setFrame:self.bounds];
1782     [_scrollView setBackgroundColor:[UIColor whiteColor]];
1783     [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1784     [_scrollView setZoomScale:1];
1785     
1786 }
1787
1788 - (void)_didRelaunchProcess
1789 {
1790     RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didRelaunchProcess]", self);
1791     _hasScheduledVisibleRectUpdate = NO;
1792     _visibleContentRectUpdateScheduledFromScrollViewInStableState = YES;
1793 }
1794
1795 - (void)_didCommitLoadForMainFrame
1796 {
1797     _firstPaintAfterCommitLoadTransactionID = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1798
1799     _hasCommittedLoadForMainFrame = YES;
1800     _needsResetViewStateAfterCommitLoadForMainFrame = YES;
1801
1802     [_scrollView _stopScrollingAndZoomingAnimations];
1803 }
1804
1805 static CGPoint contentOffsetBoundedInValidRange(UIScrollView *scrollView, CGPoint contentOffset)
1806 {
1807 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1808     UIEdgeInsets contentInsets = scrollView.adjustedContentInset;
1809 #else
1810     UIEdgeInsets contentInsets = scrollView.contentInset;
1811 #endif
1812
1813     CGSize contentSize = scrollView.contentSize;
1814     CGSize scrollViewSize = scrollView.bounds.size;
1815
1816     CGPoint minimumContentOffset = CGPointMake(-contentInsets.left, -contentInsets.top);
1817     CGPoint maximumContentOffset = CGPointMake(std::max(minimumContentOffset.x, contentSize.width + contentInsets.right - scrollViewSize.width), std::max(minimumContentOffset.y, contentSize.height + contentInsets.bottom - scrollViewSize.height));
1818
1819     return CGPointMake(std::max(std::min(contentOffset.x, maximumContentOffset.x), minimumContentOffset.x), std::max(std::min(contentOffset.y, maximumContentOffset.y), minimumContentOffset.y));
1820 }
1821
1822 static void changeContentOffsetBoundedInValidRange(UIScrollView *scrollView, WebCore::FloatPoint contentOffset)
1823 {
1824     scrollView.contentOffset = contentOffsetBoundedInValidRange(scrollView, contentOffset);
1825 }
1826
1827 - (WebCore::FloatRect)visibleRectInViewCoordinates
1828 {
1829     WebCore::FloatRect bounds = self.bounds;
1830     bounds.moveBy([_scrollView contentOffset]);
1831     WebCore::FloatRect contentViewBounds = [_contentView bounds];
1832     bounds.intersect(contentViewBounds);
1833     return bounds;
1834 }
1835
1836 // WebCore stores the page scale factor as float instead of double. When we get a scale from WebCore,
1837 // we need to ignore differences that are within a small rounding error on floats.
1838 static inline bool areEssentiallyEqualAsFloat(float a, float b)
1839 {
1840     return WTF::areEssentiallyEqual(a, b);
1841 }
1842
1843 - (void)_didCommitLayerTreeDuringAnimatedResize:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
1844 {
1845     auto updateID = layerTreeTransaction.dynamicViewportSizeUpdateID();
1846     if (updateID && *updateID == _currentDynamicViewportSizeUpdateID) {
1847         double pageScale = layerTreeTransaction.pageScaleFactor();
1848         WebCore::IntPoint scrollPosition = layerTreeTransaction.scrollPosition();
1849
1850         CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
1851         double currentTargetScale = animatingScaleTarget * [[_contentView layer] transform].m11;
1852         double scale = pageScale / currentTargetScale;
1853         _resizeAnimationTransformAdjustments = CATransform3DMakeScale(scale, scale, 1);
1854
1855         CGPoint newContentOffset = [self _contentOffsetAdjustedForObscuredInset:CGPointMake(scrollPosition.x() * pageScale, scrollPosition.y() * pageScale)];
1856         CGPoint currentContentOffset = [_scrollView contentOffset];
1857
1858         _resizeAnimationTransformAdjustments.m41 = (currentContentOffset.x - newContentOffset.x) / animatingScaleTarget;
1859         _resizeAnimationTransformAdjustments.m42 = (currentContentOffset.y - newContentOffset.y) / animatingScaleTarget;
1860
1861         [_resizeAnimationView layer].sublayerTransform = _resizeAnimationTransformAdjustments;
1862
1863         // If we've already passed endAnimatedResize, immediately complete
1864         // the resize when we have an up-to-date layer tree. Otherwise,
1865         // we will defer completion until endAnimatedResize.
1866         _waitingForCommitAfterAnimatedResize = NO;
1867         if (!_waitingForEndAnimatedResize)
1868             [self _didCompleteAnimatedResize];
1869
1870         return;
1871     }
1872
1873     // If a commit arrives during the live part of a resize but before the
1874     // layer tree takes the current resize into account, it could change the
1875     // WKContentView's size. Update the resizeAnimationView's scale to ensure
1876     // we continue to fill the width of the resize target.
1877
1878     if (_waitingForEndAnimatedResize)
1879         return;
1880
1881     auto newViewLayoutSize = [self activeViewLayoutSize:self.bounds];
1882     CGFloat resizeAnimationViewScale = _animatedResizeOriginalContentWidth / newViewLayoutSize.width();
1883     [[_resizeAnimationView layer] setSublayerTransform:CATransform3DMakeScale(resizeAnimationViewScale, resizeAnimationViewScale, 1)];
1884 }
1885
1886 - (void)_didCommitLayerTree:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
1887 {
1888     if (![self usesStandardContentView])
1889         return;
1890
1891     LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _didCommitLayerTree:] transactionID " <<  layerTreeTransaction.transactionID() << " _dynamicViewportUpdateMode " << (int)_dynamicViewportUpdateMode);
1892
1893     bool needUpdateVisibleContentRects = _page->updateLayoutViewportParameters(layerTreeTransaction);
1894
1895     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing) {
1896         [self _didCommitLayerTreeDuringAnimatedResize:layerTreeTransaction];
1897         return;
1898     }
1899
1900     if (_resizeAnimationView)
1901         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didCommitLayerTree:] - dynamicViewportUpdateMode is NotResizing, but still have a live resizeAnimationView (unpaired begin/endAnimatedResize?)", self);
1902
1903     CGSize newContentSize = roundScrollViewContentSize(*_page, [_contentView frame].size);
1904     [_scrollView _setContentSizePreservingContentOffsetDuringRubberband:newContentSize];
1905
1906     [_scrollView setMinimumZoomScale:layerTreeTransaction.minimumScaleFactor()];
1907     [_scrollView setMaximumZoomScale:layerTreeTransaction.maximumScaleFactor()];
1908     [_scrollView setZoomEnabled:layerTreeTransaction.allowsUserScaling()];
1909     if (!layerTreeTransaction.scaleWasSetByUIProcess() && ![_scrollView isZooming] && ![_scrollView isZoomBouncing] && ![_scrollView _isAnimatingZoom] && [_scrollView zoomScale] != layerTreeTransaction.pageScaleFactor()) {
1910         LOG_WITH_STREAM(VisibleRects, stream << " updating scroll view with pageScaleFactor " << layerTreeTransaction.pageScaleFactor());
1911         [_scrollView setZoomScale:layerTreeTransaction.pageScaleFactor()];
1912     }
1913
1914     _viewportMetaTagWidth = layerTreeTransaction.viewportMetaTagWidth();
1915     _viewportMetaTagWidthWasExplicit = layerTreeTransaction.viewportMetaTagWidthWasExplicit();
1916     _viewportMetaTagCameFromImageDocument = layerTreeTransaction.viewportMetaTagCameFromImageDocument();
1917     _initialScaleFactor = layerTreeTransaction.initialScaleFactor();
1918     if (_page->inStableState() && layerTreeTransaction.isInStableState() && [_stableStatePresentationUpdateCallbacks count]) {
1919         for (dispatch_block_t action in _stableStatePresentationUpdateCallbacks.get())
1920             action();
1921
1922         [_stableStatePresentationUpdateCallbacks removeAllObjects];
1923         _stableStatePresentationUpdateCallbacks = nil;
1924     }
1925
1926     if (![_contentView _mayDisableDoubleTapGesturesDuringSingleTap])
1927         [_contentView _setDoubleTapGesturesEnabled:self._allowsDoubleTapGestures];
1928
1929     [self _updateScrollViewBackground];
1930     [self _setAvoidsUnsafeArea:layerTreeTransaction.avoidsUnsafeArea()];
1931
1932     if (_gestureController)
1933         _gestureController->setRenderTreeSize(layerTreeTransaction.renderTreeSize());
1934
1935     if (_needsResetViewStateAfterCommitLoadForMainFrame && layerTreeTransaction.transactionID() >= _firstPaintAfterCommitLoadTransactionID) {
1936         _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1937         [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1938         if (_observedRenderingProgressEvents & _WKRenderingProgressEventFirstPaint)
1939             _navigationState->didFirstPaint();
1940
1941         needUpdateVisibleContentRects = true;
1942     }
1943
1944     if (_firstTransactionIDAfterPageRestore && layerTreeTransaction.transactionID() >= _firstTransactionIDAfterPageRestore.value()) {
1945         if (_scrollOffsetToRestore) {
1946             WebCore::FloatPoint scaledScrollOffset = _scrollOffsetToRestore.value();
1947             _scrollOffsetToRestore = std::nullopt;
1948
1949             if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1950                 scaledScrollOffset.scale(_scaleToRestore);
1951                 WebCore::FloatPoint contentOffsetInScrollViewCoordinates = scaledScrollOffset - WebCore::FloatSize(_obscuredInsetsWhenSaved.left(), _obscuredInsetsWhenSaved.top());
1952
1953                 changeContentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
1954                 _commitDidRestoreScrollPosition = YES;
1955             }
1956
1957             needUpdateVisibleContentRects = true;
1958         }
1959
1960         if (_unobscuredCenterToRestore) {
1961             WebCore::FloatPoint unobscuredCenterToRestore = _unobscuredCenterToRestore.value();
1962             _unobscuredCenterToRestore = std::nullopt;
1963
1964             if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1965                 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, _obscuredInsets);
1966                 WebCore::FloatSize unobscuredContentSizeAtNewScale = WebCore::FloatSize(unobscuredRect.size) / _scaleToRestore;
1967                 WebCore::FloatPoint topLeftInDocumentCoordinates = unobscuredCenterToRestore - unobscuredContentSizeAtNewScale / 2;
1968
1969                 topLeftInDocumentCoordinates.scale(_scaleToRestore);
1970                 topLeftInDocumentCoordinates.moveBy(WebCore::FloatPoint(-_obscuredInsets.left, -_obscuredInsets.top));
1971
1972                 changeContentOffsetBoundedInValidRange(_scrollView.get(), topLeftInDocumentCoordinates);
1973             }
1974
1975             needUpdateVisibleContentRects = true;
1976         }
1977
1978         if (_gestureController)
1979             _gestureController->didRestoreScrollPosition();
1980
1981         _firstTransactionIDAfterPageRestore = std::nullopt;
1982     }
1983
1984     if (needUpdateVisibleContentRects)
1985         [self _scheduleVisibleContentRectUpdate];
1986
1987     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
1988         scrollPerfData->didCommitLayerTree([self visibleRectInViewCoordinates]);
1989 }
1990
1991 - (void)_layerTreeCommitComplete
1992 {
1993     _commitDidRestoreScrollPosition = NO;
1994 }
1995
1996 - (void)_couldNotRestorePageState
1997 {
1998     // The gestureController may be waiting for the scroll position to be restored
1999     // in order to remove the swipe snapshot. Since the scroll position could not be
2000     // restored, tell the gestureController it was restored so that it no longer waits
2001     // for it.
2002     if (_gestureController)
2003         _gestureController->didRestoreScrollPosition();
2004 }
2005
2006 - (void)_restorePageScrollPosition:(std::optional<WebCore::FloatPoint>)scrollPosition scrollOrigin:(WebCore::FloatPoint)scrollOrigin previousObscuredInset:(WebCore::FloatBoxExtent)obscuredInsets scale:(double)scale
2007 {
2008     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing)
2009         return;
2010
2011     if (![self usesStandardContentView])
2012         return;
2013
2014     _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
2015     if (scrollPosition)
2016         _scrollOffsetToRestore = WebCore::ScrollableArea::scrollOffsetFromPosition(WebCore::FloatPoint(scrollPosition.value()), WebCore::toFloatSize(scrollOrigin));
2017     else
2018         _scrollOffsetToRestore = std::nullopt;
2019
2020     _obscuredInsetsWhenSaved = obscuredInsets;
2021     _scaleToRestore = scale;
2022 }
2023
2024 - (void)_restorePageStateToUnobscuredCenter:(std::optional<WebCore::FloatPoint>)center scale:(double)scale
2025 {
2026     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing)
2027         return;
2028
2029     if (![self usesStandardContentView])
2030         return;
2031
2032     _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
2033     _unobscuredCenterToRestore = center.value();
2034
2035     _scaleToRestore = scale;
2036 }
2037
2038 - (RefPtr<WebKit::ViewSnapshot>)_takeViewSnapshot
2039 {
2040 #if HAVE(CORE_ANIMATION_RENDER_SERVER)
2041     float deviceScale = WebCore::screenScaleFactor();
2042     WebCore::FloatSize snapshotSize(self.bounds.size);
2043     snapshotSize.scale(deviceScale);
2044
2045     CATransform3D transform = CATransform3DMakeScale(deviceScale, deviceScale, 1);
2046
2047 #if HAVE(IOSURFACE)
2048     WebCore::IOSurface::Format snapshotFormat = WebCore::screenSupportsExtendedColor() ? WebCore::IOSurface::Format::RGB10 : WebCore::IOSurface::Format::RGBA;
2049     auto surface = WebCore::IOSurface::create(WebCore::expandedIntSize(snapshotSize), WebCore::sRGBColorSpaceRef(), snapshotFormat);
2050     if (!surface)
2051         return nullptr;
2052     CARenderServerRenderLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, reinterpret_cast<uint64_t>(self.layer), surface->surface(), 0, 0, &transform);
2053
2054 #if HAVE(IOSURFACE_ACCELERATOR)
2055     WebCore::IOSurface::Format compressedFormat = WebCore::IOSurface::Format::YUV422;
2056     if (WebCore::IOSurface::allowConversionFromFormatToFormat(snapshotFormat, compressedFormat)) {
2057         RefPtr<WebKit::ViewSnapshot> viewSnapshot = WebKit::ViewSnapshot::create(nullptr);
2058         WebCore::IOSurface::convertToFormat(WTFMove(surface), WebCore::IOSurface::Format::YUV422, [viewSnapshot](std::unique_ptr<WebCore::IOSurface> convertedSurface) {
2059             if (convertedSurface)
2060                 viewSnapshot->setSurface(WTFMove(convertedSurface));
2061         });
2062
2063         return viewSnapshot;
2064     }
2065 #endif // HAVE(IOSURFACE_ACCELERATOR)
2066
2067     return WebKit::ViewSnapshot::create(WTFMove(surface));
2068 #else // HAVE(IOSURFACE)
2069     uint32_t slotID = [WebKit::ViewSnapshotStore::snapshottingContext() createImageSlot:snapshotSize hasAlpha:YES];
2070
2071     if (!slotID)
2072         return nullptr;
2073
2074     CARenderServerCaptureLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, (uint64_t)self.layer, slotID, 0, 0, &transform);
2075     WebCore::IntSize imageSize = WebCore::expandedIntSize(WebCore::FloatSize(snapshotSize));
2076     return WebKit::ViewSnapshot::create(slotID, imageSize, (imageSize.area() * 4).unsafeGet());
2077 #endif // HAVE(IOSURFACE)
2078 #else // HAVE(CORE_ANIMATION_RENDER_SERVER)
2079     return nullptr;
2080 #endif
2081 }
2082
2083 - (void)_zoomToPoint:(WebCore::FloatPoint)point atScale:(double)scale animated:(BOOL)animated
2084 {
2085     CFTimeInterval duration = 0;
2086     CGFloat zoomScale = contentZoomScale(self);
2087
2088     if (animated) {
2089         const double maximumZoomDuration = 0.4;
2090         const double minimumZoomDuration = 0.1;
2091         const double zoomDurationFactor = 0.3;
2092
2093         duration = std::min(fabs(log(zoomScale) - log(scale)) * zoomDurationFactor + minimumZoomDuration, maximumZoomDuration);
2094     }
2095
2096     if (scale != zoomScale)
2097         _page->willStartUserTriggeredZooming();
2098
2099     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToPoint:" << point << " scale: " << scale << " duration:" << duration);
2100
2101     [_scrollView _zoomToCenter:point scale:scale duration:duration];
2102 }
2103
2104 - (void)_zoomToRect:(WebCore::FloatRect)targetRect atScale:(double)scale origin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2105 {
2106     // FIXME: Some of this could be shared with _scrollToRect.
2107     const double visibleRectScaleChange = contentZoomScale(self) / scale;
2108     const WebCore::FloatRect visibleRect([self convertRect:self.bounds toView:self._currentContentView]);
2109     const WebCore::FloatRect unobscuredRect([self _contentRectForUserInteraction]);
2110
2111     const WebCore::FloatSize topLeftObscuredInsetAfterZoom((unobscuredRect.minXMinYCorner() - visibleRect.minXMinYCorner()) * visibleRectScaleChange);
2112     const WebCore::FloatSize bottomRightObscuredInsetAfterZoom((visibleRect.maxXMaxYCorner() - unobscuredRect.maxXMaxYCorner()) * visibleRectScaleChange);
2113
2114     const WebCore::FloatSize unobscuredRectSizeAfterZoom(unobscuredRect.size() * visibleRectScaleChange);
2115
2116     // Center to the target rect.
2117     WebCore::FloatPoint unobscuredRectLocationAfterZoom = targetRect.location() - (unobscuredRectSizeAfterZoom - targetRect.size()) * 0.5;
2118
2119     // Center to the tap point instead in case the target rect won't fit in a direction.
2120     if (targetRect.width() > unobscuredRectSizeAfterZoom.width())
2121         unobscuredRectLocationAfterZoom.setX(origin.x() - unobscuredRectSizeAfterZoom.width() / 2);
2122     if (targetRect.height() > unobscuredRectSizeAfterZoom.height())
2123         unobscuredRectLocationAfterZoom.setY(origin.y() - unobscuredRectSizeAfterZoom.height() / 2);
2124
2125     // We have computed where we want the unobscured rect to be. Now adjust for the obscuring insets.
2126     WebCore::FloatRect visibleRectAfterZoom(unobscuredRectLocationAfterZoom, unobscuredRectSizeAfterZoom);
2127     visibleRectAfterZoom.move(-topLeftObscuredInsetAfterZoom);
2128     visibleRectAfterZoom.expand(topLeftObscuredInsetAfterZoom + bottomRightObscuredInsetAfterZoom);
2129
2130     [self _zoomToPoint:visibleRectAfterZoom.center() atScale:scale animated:animated];
2131 }
2132
2133 static WebCore::FloatPoint constrainContentOffset(WebCore::FloatPoint contentOffset, WebCore::FloatSize contentSize, WebCore::FloatSize unobscuredContentSize)
2134 {
2135     WebCore::FloatSize maximumContentOffset = contentSize - unobscuredContentSize;
2136     return contentOffset.constrainedBetween(WebCore::FloatPoint(), WebCore::FloatPoint(maximumContentOffset));
2137 }
2138
2139 - (void)_scrollToContentScrollPosition:(WebCore::FloatPoint)scrollPosition scrollOrigin:(WebCore::IntPoint)scrollOrigin
2140 {
2141     if (_commitDidRestoreScrollPosition || _dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing)
2142         return;
2143
2144     WebCore::FloatPoint contentOffset = WebCore::ScrollableArea::scrollOffsetFromPosition(scrollPosition, toFloatSize(scrollOrigin));
2145
2146     WebCore::FloatPoint scaledOffset = contentOffset;
2147     CGFloat zoomScale = contentZoomScale(self);
2148     scaledOffset.scale(zoomScale);
2149
2150     CGPoint contentOffsetInScrollViewCoordinates = [self _contentOffsetAdjustedForObscuredInset:scaledOffset];
2151     contentOffsetInScrollViewCoordinates = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
2152
2153     [_scrollView _stopScrollingAndZoomingAnimations];
2154
2155     if (!CGPointEqualToPoint(contentOffsetInScrollViewCoordinates, [_scrollView contentOffset]))
2156         [_scrollView setContentOffset:contentOffsetInScrollViewCoordinates];
2157     else {
2158         // If we haven't changed anything, there would not be any VisibleContentRect update sent to the content.
2159         // The WebProcess would keep the invalid contentOffset as its scroll position.
2160         // To synchronize the WebProcess with what is on screen, we send the VisibleContentRect again.
2161         _page->resendLastVisibleContentRects();
2162     }
2163 }
2164
2165 - (BOOL)_scrollToRect:(WebCore::FloatRect)targetRect origin:(WebCore::FloatPoint)origin minimumScrollDistance:(float)minimumScrollDistance
2166 {
2167     WebCore::FloatRect unobscuredContentRect([self _contentRectForUserInteraction]);
2168     WebCore::FloatPoint unobscuredContentOffset = unobscuredContentRect.location();
2169     WebCore::FloatSize contentSize([self._currentContentView bounds].size);
2170
2171     // Center the target rect in the scroll view.
2172     // If the target doesn't fit in the scroll view, center on the gesture location instead.
2173     WebCore::FloatPoint newUnobscuredContentOffset;
2174     if (targetRect.width() <= unobscuredContentRect.width())
2175         newUnobscuredContentOffset.setX(targetRect.x() - (unobscuredContentRect.width() - targetRect.width()) / 2);
2176     else
2177         newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
2178     if (targetRect.height() <= unobscuredContentRect.height())
2179         newUnobscuredContentOffset.setY(targetRect.y() - (unobscuredContentRect.height() - targetRect.height()) / 2);
2180     else
2181         newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
2182     newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
2183
2184     if (unobscuredContentOffset == newUnobscuredContentOffset) {
2185         if (targetRect.width() > unobscuredContentRect.width())
2186             newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
2187         if (targetRect.height() > unobscuredContentRect.height())
2188             newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
2189         newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
2190     }
2191
2192     WebCore::FloatSize scrollViewOffsetDelta = newUnobscuredContentOffset - unobscuredContentOffset;
2193     scrollViewOffsetDelta.scale(contentZoomScale(self));
2194
2195     float scrollDistance = scrollViewOffsetDelta.diagonalLength();
2196     if (scrollDistance < minimumScrollDistance)
2197         return false;
2198
2199     [_contentView willStartZoomOrScroll];
2200
2201     LOG_WITH_STREAM(VisibleRects, stream << "_scrollToRect: scrolling to " << [_scrollView contentOffset] + scrollViewOffsetDelta);
2202
2203     [_scrollView setContentOffset:([_scrollView contentOffset] + scrollViewOffsetDelta) animated:YES];
2204     return true;
2205 }
2206
2207 - (void)_zoomOutWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2208 {
2209     [self _zoomToPoint:origin atScale:[_scrollView minimumZoomScale] animated:animated];
2210 }
2211
2212 - (void)_zoomToInitialScaleWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2213 {
2214     ASSERT(_initialScaleFactor > 0);
2215     [self _zoomToPoint:origin atScale:_initialScaleFactor animated:animated];
2216 }
2217
2218 // focusedElementRect and selectionRect are both in document coordinates.
2219 - (void)_zoomToFocusRect:(WebCore::FloatRect)focusedElementRectInDocumentCoordinates selectionRect:(WebCore::FloatRect)selectionRectInDocumentCoordinates insideFixed:(BOOL)insideFixed
2220     fontSize:(float)fontSize minimumScale:(double)minimumScale maximumScale:(double)maximumScale allowScaling:(BOOL)allowScaling forceScroll:(BOOL)forceScroll
2221 {
2222     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToFocusRect:" << focusedElementRectInDocumentCoordinates << " selectionRect:" << selectionRectInDocumentCoordinates);
2223     UNUSED_PARAM(insideFixed);
2224
2225     const double minimumHeightToShowContentAboveKeyboard = 106;
2226     const CFTimeInterval formControlZoomAnimationDuration = 0.25;
2227     const double caretOffsetFromWindowEdge = 20;
2228
2229     UIWindow *window = [_scrollView window];
2230
2231     // Find the portion of the view that is visible on the screen.
2232     UIViewController *topViewController = [[[_scrollView _viewControllerForAncestor] _rootAncestorViewController] _viewControllerForSupportedInterfaceOrientations];
2233     UIView *fullScreenView = topViewController.view;
2234     if (!fullScreenView)
2235         fullScreenView = window;
2236
2237     CGRect unobscuredScrollViewRectInWebViewCoordinates = UIEdgeInsetsInsetRect([self bounds], _obscuredInsets);
2238     CGRect visibleScrollViewBoundsInWebViewCoordinates = CGRectIntersection(unobscuredScrollViewRectInWebViewCoordinates, [fullScreenView convertRect:[fullScreenView bounds] toView:self]);
2239     CGRect formAssistantFrameInWebViewCoordinates = [window convertRect:_inputViewBounds toView:self];
2240     CGRect intersectionBetweenScrollViewAndFormAssistant = CGRectIntersection(visibleScrollViewBoundsInWebViewCoordinates, formAssistantFrameInWebViewCoordinates);
2241     CGSize visibleSize = visibleScrollViewBoundsInWebViewCoordinates.size;
2242
2243     CGFloat visibleOffsetFromTop = 0;
2244     if (!CGRectIsEmpty(intersectionBetweenScrollViewAndFormAssistant)) {
2245         CGFloat heightVisibleAboveFormAssistant = CGRectGetMinY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
2246         CGFloat heightVisibleBelowFormAssistant = CGRectGetMaxY(visibleScrollViewBoundsInWebViewCoordinates) - CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant);
2247
2248         if (heightVisibleAboveFormAssistant >= minimumHeightToShowContentAboveKeyboard || heightVisibleBelowFormAssistant < heightVisibleAboveFormAssistant)
2249             visibleSize.height = heightVisibleAboveFormAssistant;
2250         else {
2251             visibleSize.height = heightVisibleBelowFormAssistant;
2252             visibleOffsetFromTop = CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
2253         }
2254     }
2255
2256     // Zoom around the element's bounding frame. We use a "standard" size to determine the proper frame.
2257     double currentScale = contentZoomScale(self);
2258     double scale = currentScale;
2259     if (allowScaling) {
2260 #if PLATFORM(WATCHOS)
2261         const CGFloat minimumMarginForZoomingToEntireFocusRectInWebViewCoordinates = 10;
2262         const CGFloat maximumMarginForZoomingToEntireFocusRectInWebViewCoordinates = 35;
2263
2264         CGRect minimumTargetRectInDocumentCoordinates = UIRectInsetEdges(focusedElementRectInDocumentCoordinates, UIRectEdgeAll, -minimumMarginForZoomingToEntireFocusRectInWebViewCoordinates / currentScale);
2265         CGRect maximumTargetRectInDocumentCoordinates = UIRectInsetEdges(focusedElementRectInDocumentCoordinates, UIRectEdgeAll, -maximumMarginForZoomingToEntireFocusRectInWebViewCoordinates / currentScale);
2266
2267         double clampedMaximumTargetScale = clampTo<double>(std::min(visibleSize.width / CGRectGetWidth(minimumTargetRectInDocumentCoordinates), visibleSize.height / CGRectGetHeight(minimumTargetRectInDocumentCoordinates)), minimumScale, maximumScale);
2268         double clampedMinimumTargetScale = clampTo<double>(std::min(visibleSize.width / CGRectGetWidth(maximumTargetRectInDocumentCoordinates), visibleSize.height / CGRectGetHeight(maximumTargetRectInDocumentCoordinates)), minimumScale, maximumScale);
2269         scale = clampTo<double>(currentScale, clampedMinimumTargetScale, clampedMaximumTargetScale);
2270 #else
2271         const double webViewStandardFontSize = 16;
2272         scale = clampTo<double>(webViewStandardFontSize / fontSize, minimumScale, maximumScale);
2273 #endif
2274     }
2275
2276     CGFloat documentWidth = [_contentView bounds].size.width;
2277     scale = CGRound(documentWidth * scale) / documentWidth;
2278
2279     WebCore::FloatRect focusedElementRectInNewScale = focusedElementRectInDocumentCoordinates;
2280     focusedElementRectInNewScale.scale(scale);
2281     focusedElementRectInNewScale.moveBy([_contentView frame].origin);
2282
2283     BOOL selectionRectIsNotNull = !selectionRectInDocumentCoordinates.isZero();
2284     if (!forceScroll) {
2285         CGRect currentlyVisibleRegionInWebViewCoordinates;
2286         currentlyVisibleRegionInWebViewCoordinates.origin = unobscuredScrollViewRectInWebViewCoordinates.origin;
2287         currentlyVisibleRegionInWebViewCoordinates.origin.y += visibleOffsetFromTop;
2288         currentlyVisibleRegionInWebViewCoordinates.size = visibleSize;
2289
2290         // Don't bother scrolling if the entire node is already visible, whether or not we got a selectionRect.
2291         if (CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:focusedElementRectInDocumentCoordinates fromView:_contentView.get()]))
2292             return;
2293
2294         // Don't bother scrolling if we have a valid selectionRect and it is already visible.
2295         if (selectionRectIsNotNull && CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:selectionRectInDocumentCoordinates fromView:_contentView.get()]))
2296             return;
2297     }
2298
2299     // We want to zoom to the left/top corner of the DOM node, with as much spacing on all sides as we
2300     // can get based on the visible area after zooming (workingFrame).  The spacing in either dimension is half the
2301     // difference between the size of the DOM node and the size of the visible frame.
2302     CGFloat horizontalSpaceInWebViewCoordinates = std::max((visibleSize.width - focusedElementRectInNewScale.width()) / 2.0, 0.0);
2303     CGFloat verticalSpaceInWebViewCoordinates = std::max((visibleSize.height - focusedElementRectInNewScale.height()) / 2.0, 0.0);
2304
2305     CGPoint topLeft;
2306     topLeft.x = focusedElementRectInNewScale.x() - horizontalSpaceInWebViewCoordinates;
2307     topLeft.y = focusedElementRectInNewScale.y() - verticalSpaceInWebViewCoordinates - visibleOffsetFromTop;
2308
2309     CGFloat minimumAllowableHorizontalOffsetInWebViewCoordinates = -INFINITY;
2310     CGFloat minimumAllowableVerticalOffsetInWebViewCoordinates = -INFINITY;
2311     if (selectionRectIsNotNull) {
2312         WebCore::FloatRect selectionRectInNewScale = selectionRectInDocumentCoordinates;
2313         selectionRectInNewScale.scale(scale);
2314         selectionRectInNewScale.moveBy([_contentView frame].origin);
2315         minimumAllowableHorizontalOffsetInWebViewCoordinates = CGRectGetMaxX(selectionRectInNewScale) + caretOffsetFromWindowEdge - visibleSize.width;
2316         minimumAllowableVerticalOffsetInWebViewCoordinates = CGRectGetMaxY(selectionRectInNewScale) + caretOffsetFromWindowEdge - visibleSize.height - visibleOffsetFromTop;
2317     }
2318
2319     WebCore::FloatRect documentBoundsInNewScale = [_contentView bounds];
2320     documentBoundsInNewScale.scale(scale);
2321     documentBoundsInNewScale.moveBy([_contentView frame].origin);
2322
2323     // Constrain the left edge in document coordinates so that:
2324     //  - it isn't so small that the scrollVisibleRect isn't visible on the screen
2325     //  - it isn't so great that the document's right edge is less than the right edge of the screen
2326     if (selectionRectIsNotNull && topLeft.x < minimumAllowableHorizontalOffsetInWebViewCoordinates)
2327         topLeft.x = minimumAllowableHorizontalOffsetInWebViewCoordinates;
2328     else {
2329         CGFloat maximumAllowableHorizontalOffset = CGRectGetMaxX(documentBoundsInNewScale) - visibleSize.width;
2330         if (topLeft.x > maximumAllowableHorizontalOffset)
2331             topLeft.x = maximumAllowableHorizontalOffset;
2332     }
2333
2334     // Constrain the top edge in document coordinates so that:
2335     //  - it isn't so small that the scrollVisibleRect isn't visible on the screen
2336     //  - it isn't so great that the document's bottom edge is higher than the top of the form assistant
2337     if (selectionRectIsNotNull && topLeft.y < minimumAllowableVerticalOffsetInWebViewCoordinates)
2338         topLeft.y = minimumAllowableVerticalOffsetInWebViewCoordinates;
2339     else {
2340         CGFloat maximumAllowableVerticalOffset = CGRectGetMaxY(documentBoundsInNewScale) - visibleSize.height;
2341         if (topLeft.y > maximumAllowableVerticalOffset)
2342             topLeft.y = maximumAllowableVerticalOffset;
2343     }
2344
2345     WebCore::FloatPoint newCenter = CGPointMake(topLeft.x + unobscuredScrollViewRectInWebViewCoordinates.size.width / 2.0, topLeft.y + unobscuredScrollViewRectInWebViewCoordinates.size.height / 2.0);
2346
2347     if (scale != currentScale)
2348         _page->willStartUserTriggeredZooming();
2349
2350     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToFocusRect: zooming to " << newCenter << " scale:" << scale);
2351
2352     // The newCenter has been computed in the new scale, but _zoomToCenter expected the center to be in the original scale.
2353     newCenter.scale(1 / scale);
2354     [_scrollView _zoomToCenter:newCenter scale:scale duration:formControlZoomAnimationDuration force:YES];
2355 }
2356
2357 - (CGFloat)_targetContentZoomScaleForRect:(const WebCore::FloatRect&)targetRect currentScale:(double)currentScale fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale
2358 {
2359     WebCore::FloatSize unobscuredContentSize([self _contentRectForUserInteraction].size);
2360     double horizontalScale = unobscuredContentSize.width() * currentScale / targetRect.width();
2361     double verticalScale = unobscuredContentSize.height() * currentScale / targetRect.height();
2362
2363     horizontalScale = std::min(std::max(horizontalScale, minimumScale), maximumScale);
2364     verticalScale = std::min(std::max(verticalScale, minimumScale), maximumScale);
2365
2366     return fitEntireRect ? std::min(horizontalScale, verticalScale) : horizontalScale;
2367 }
2368
2369 - (BOOL)_zoomToRect:(WebCore::FloatRect)targetRect withOrigin:(WebCore::FloatPoint)origin fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale minimumScrollDistance:(float)minimumScrollDistance
2370 {
2371     const float maximumScaleFactorDeltaForPanScroll = 0.02;
2372
2373     double currentScale = contentZoomScale(self);
2374     double targetScale = [self _targetContentZoomScaleForRect:targetRect currentScale:currentScale fitEntireRect:fitEntireRect minimumScale:minimumScale maximumScale:maximumScale];
2375
2376     if (fabs(targetScale - currentScale) < maximumScaleFactorDeltaForPanScroll) {
2377         if ([self _scrollToRect:targetRect origin:origin minimumScrollDistance:minimumScrollDistance])
2378             return true;
2379     } else if (targetScale != currentScale) {
2380         [self _zoomToRect:targetRect atScale:targetScale origin:origin animated:YES];
2381         return true;
2382     }
2383
2384     return false;
2385 }
2386
2387 - (void)didMoveToWindow
2388 {
2389     _page->activityStateDidChange(WebCore::ActivityState::allFlags());
2390 }
2391
2392 - (void)setOpaque:(BOOL)opaque
2393 {
2394     BOOL oldOpaque = self.opaque;
2395
2396     [super setOpaque:opaque];
2397     [_contentView setOpaque:opaque];
2398
2399     if (oldOpaque == opaque)
2400         return;
2401
2402     if (!_page)
2403         return;
2404
2405     _page->setDrawsBackground(opaque);
2406     [self _updateScrollViewBackground];
2407 }
2408
2409 - (void)setBackgroundColor:(UIColor *)backgroundColor
2410 {
2411     [super setBackgroundColor:backgroundColor];
2412     [_contentView setBackgroundColor:backgroundColor];
2413 }
2414
2415 - (BOOL)_allowsDoubleTapGestures
2416 {
2417     if (_fastClickingIsDisabled)
2418         return YES;
2419
2420     // If the page is not user scalable, we don't allow double tap gestures.
2421     if (![_scrollView isZoomEnabled] || [_scrollView minimumZoomScale] >= [_scrollView maximumZoomScale])
2422         return NO;
2423
2424     // If the viewport width was not explicit, we allow double tap gestures.
2425     if (!_viewportMetaTagWidthWasExplicit || _viewportMetaTagCameFromImageDocument)
2426         return YES;
2427
2428     // If the page set a viewport width that wasn't the device width, then it was
2429     // scaled and thus will probably need to zoom.
2430     if (_viewportMetaTagWidth != WebCore::ViewportArguments::ValueDeviceWidth)
2431         return YES;
2432
2433     // At this point, we have a page that asked for width = device-width. However,
2434     // if the content's width and height were large, we might have had to shrink it.
2435     // Since we'll enable double tap zoom whenever we're not at the actual
2436     // initial scale, this simply becomes a test of the current scale against 1.
2437     return !areEssentiallyEqualAsFloat(contentZoomScale(self), 1);
2438 }
2439
2440 #pragma mark - UIScrollViewDelegate
2441
2442 - (BOOL)usesStandardContentView
2443 {
2444     return !_customContentView && !_passwordView;
2445 }
2446
2447 - (CGSize)scrollView:(UIScrollView*)scrollView contentSizeForZoomScale:(CGFloat)scale withProposedSize:(CGSize)proposedSize
2448 {
2449     return roundScrollViewContentSize(*_page, proposedSize);
2450 }
2451
2452 - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
2453 {
2454     ASSERT(_scrollView == scrollView);
2455     return self._currentContentView;
2456 }
2457
2458 - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
2459 {
2460     if (![self usesStandardContentView]) {
2461         if ([_customContentView respondsToSelector:@selector(web_scrollViewWillBeginZooming:withView:)])
2462             [_customContentView web_scrollViewWillBeginZooming:scrollView withView:view];
2463         return;
2464     }
2465
2466     if (scrollView.pinchGestureRecognizer.state == UIGestureRecognizerStateBegan) {
2467         _page->willStartUserTriggeredZooming();
2468         [_contentView scrollViewWillStartPanOrPinchGesture];
2469     }
2470     [_contentView willStartZoomOrScroll];
2471 }
2472
2473 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
2474 {
2475     if (![self usesStandardContentView])
2476         return;
2477
2478     if (scrollView.panGestureRecognizer.state == UIGestureRecognizerStateBegan)
2479         [_contentView scrollViewWillStartPanOrPinchGesture];
2480
2481     [_contentView willStartZoomOrScroll];
2482 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2483     // FIXME: We will want to detect whether snapping will occur before beginning to drag. See WebPageProxy::didCommitLayerTree.
2484     WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2485     ASSERT(scrollView == _scrollView.get());
2486     CGFloat scrollDecelerationFactor = (coordinator && coordinator->shouldSetScrollViewDecelerationRateFast()) ? UIScrollViewDecelerationRateFast : UIScrollViewDecelerationRateNormal;
2487     scrollView.horizontalScrollDecelerationFactor = scrollDecelerationFactor;
2488     scrollView.verticalScrollDecelerationFactor = scrollDecelerationFactor;
2489 #endif
2490 }
2491
2492 - (void)_didFinishScrolling
2493 {
2494     if (![self usesStandardContentView])
2495         return;
2496
2497     [self _scheduleVisibleContentRectUpdate];
2498     [_contentView didFinishScrolling];
2499 }
2500
2501 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
2502 {
2503     // Work around <rdar://problem/16374753> by avoiding deceleration while
2504     // zooming. We'll animate to the right place once the zoom finishes.
2505     if ([scrollView isZooming])
2506         *targetContentOffset = [scrollView contentOffset];
2507 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2508     if (WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy()) {
2509         // FIXME: Here, I'm finding the maximum horizontal/vertical scroll offsets. There's probably a better way to do this.
2510         CGSize maxScrollOffsets = CGSizeMake(scrollView.contentSize.width - scrollView.bounds.size.width, scrollView.contentSize.height - scrollView.bounds.size.height);
2511
2512         UIEdgeInsets obscuredInset;
2513
2514         id<WKUIDelegatePrivate> uiDelegatePrivate = static_cast<id <WKUIDelegatePrivate>>([self UIDelegate]);
2515         if ([uiDelegatePrivate respondsToSelector:@selector(_webView:finalObscuredInsetsForScrollView:withVelocity:targetContentOffset:)])
2516             obscuredInset = [uiDelegatePrivate _webView:self finalObscuredInsetsForScrollView:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
2517         else
2518             obscuredInset = [self _computedObscuredInset];
2519
2520         CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInset);
2521
2522         coordinator->adjustTargetContentOffsetForSnapping(maxScrollOffsets, velocity, unobscuredRect.origin.y, targetContentOffset);
2523     }
2524 #endif
2525 }
2526
2527 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
2528 {
2529     // If we're decelerating, scroll offset will be updated when scrollViewDidFinishDecelerating: is called.
2530     if (!decelerate)
2531         [self _didFinishScrolling];
2532 }
2533
2534 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
2535 {
2536     [self _didFinishScrolling];
2537 }
2538
2539 - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
2540 {
2541     [self _didFinishScrolling];
2542 }
2543
2544 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
2545 {
2546     if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidScroll:)])
2547         [_customContentView web_scrollViewDidScroll:(UIScrollView *)scrollView];
2548
2549     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2550
2551     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
2552         scrollPerfData->didScroll([self visibleRectInViewCoordinates]);
2553 }
2554
2555 - (void)scrollViewDidZoom:(UIScrollView *)scrollView
2556 {
2557     if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidZoom:)])
2558         [_customContentView web_scrollViewDidZoom:scrollView];
2559
2560     [self _updateScrollViewBackground];
2561     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2562 }
2563
2564 - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
2565 {
2566     if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidEndZooming:withView:atScale:)])
2567         [_customContentView web_scrollViewDidEndZooming:scrollView withView:view atScale:scale];
2568
2569     ASSERT(scrollView == _scrollView);
2570     // FIXME: remove when rdar://problem/36065495 is fixed.
2571     // When rotating with two fingers down, UIScrollView can set a bogus content view position.
2572     // "Center" is top left because we set the anchorPoint to 0,0.
2573     [_contentView setCenter:self.bounds.origin];
2574
2575     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2576     [_contentView didZoomToScale:scale];
2577 }
2578
2579 - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
2580 {
2581     [self _didFinishScrolling];
2582 }
2583
2584 - (void)_scrollViewDidInterruptDecelerating:(UIScrollView *)scrollView
2585 {
2586     if (![self usesStandardContentView])
2587         return;
2588
2589     [_contentView didInterruptScrolling];
2590     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2591 }
2592
2593 - (UIView *)_enclosingViewForExposedRectComputation
2594 {
2595     return [self _scroller];
2596 }
2597
2598 - (CGRect)_visibleRectInEnclosingView:(UIView *)enclosingView
2599 {
2600     if (!enclosingView)
2601         return self.bounds;
2602
2603     CGRect exposedRect = [enclosingView convertRect:enclosingView.bounds toView:self];
2604     return CGRectIntersectsRect(exposedRect, self.bounds) ? CGRectIntersection(exposedRect, self.bounds) : CGRectZero;
2605 }
2606
2607 - (CGRect)_visibleContentRect
2608 {
2609     if (_frozenVisibleContentRect)
2610         return _frozenVisibleContentRect.value();
2611
2612     CGRect visibleRectInContentCoordinates = [self convertRect:self.bounds toView:_contentView.get()];
2613
2614     if (UIView *enclosingView = [self _enclosingViewForExposedRectComputation]) {
2615         CGRect viewVisibleRect = [self _visibleRectInEnclosingView:enclosingView];
2616         CGRect viewVisibleContentRect = [self convertRect:viewVisibleRect toView:_contentView.get()];
2617         visibleRectInContentCoordinates = CGRectIntersection(visibleRectInContentCoordinates, viewVisibleContentRect);
2618     }
2619
2620     return visibleRectInContentCoordinates;
2621 }
2622
2623 // Called when some ancestor UIScrollView scrolls.
2624 - (void)_didScroll
2625 {
2626     [self _scheduleVisibleContentRectUpdateAfterScrollInView:[self _scroller]];
2627
2628     const NSTimeInterval ScrollingEndedTimerInterval = 0.032;
2629     if (!_enclosingScrollViewScrollTimer) {
2630         _enclosingScrollViewScrollTimer = adoptNS([[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:ScrollingEndedTimerInterval]
2631             interval:0 target:self selector:@selector(_enclosingScrollerScrollingEnded:) userInfo:nil repeats:YES]);
2632         [[NSRunLoop mainRunLoop] addTimer:_enclosingScrollViewScrollTimer.get() forMode:NSDefaultRunLoopMode];
2633     }
2634     _didScrollSinceLastTimerFire = YES;
2635 }
2636
2637 - (void)_enclosingScrollerScrollingEnded:(NSTimer *)timer
2638 {
2639     if (_didScrollSinceLastTimerFire) {
2640         _didScrollSinceLastTimerFire = NO;
2641         return;
2642     }
2643
2644     [self _scheduleVisibleContentRectUpdate];
2645     [_enclosingScrollViewScrollTimer invalidate];
2646     _enclosingScrollViewScrollTimer = nil;
2647 }
2648
2649 - (UIEdgeInsets)_scrollViewSystemContentInset
2650 {
2651     // It's not safe to access the scroll view's safeAreaInsets or _systemContentInset from
2652     // inside our layoutSubviews implementation, because they aren't updated until afterwards.
2653     // Instead, depend on the fact that the UIScrollView and WKWebView are in the same coordinate
2654     // space, and map the WKWebView's own insets into the scroll view manually.
2655     return UIEdgeInsetsAdd([_scrollView _contentScrollInset], self.safeAreaInsets, [_scrollView _edgesApplyingSafeAreaInsetsToContentInset]);
2656 }
2657
2658 - (WebCore::FloatSize)activeViewLayoutSize:(const CGRect&)bounds
2659 {
2660     if (_overridesViewLayoutSize)
2661         return WebCore::FloatSize(_viewLayoutSizeOverride);
2662
2663 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2664     return WebCore::FloatSize(UIEdgeInsetsInsetRect(CGRectMake(0, 0, bounds.size.width, bounds.size.height), self._scrollViewSystemContentInset).size);
2665 #else
2666     return WebCore::FloatSize { bounds.size };
2667 #endif
2668 }
2669
2670 - (void)_dispatchSetViewLayoutSize:(WebCore::FloatSize)viewLayoutSize
2671 {
2672     if (_lastSentViewLayoutSize && CGSizeEqualToSize(_lastSentViewLayoutSize.value(), viewLayoutSize))
2673         return;
2674
2675     LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _dispatchSetViewLayoutSize:] " << viewLayoutSize << " contentZoomScale " << contentZoomScale(self));
2676     _page->setViewportConfigurationViewLayoutSize(viewLayoutSize, _page->layoutSizeScaleFactor());
2677     _lastSentViewLayoutSize = viewLayoutSize;
2678 }
2679
2680 - (void)_dispatchSetMaximumUnobscuredSize:(WebCore::FloatSize)maximumUnobscuredSize
2681 {
2682     if (_lastSentMaximumUnobscuredSize && CGSizeEqualToSize(_lastSentMaximumUnobscuredSize.value(), maximumUnobscuredSize))
2683         return;
2684
2685     _page->setMaximumUnobscuredSize(maximumUnobscuredSize);
2686     _lastSentMaximumUnobscuredSize = maximumUnobscuredSize;
2687 }
2688
2689 - (void)_dispatchSetDeviceOrientation:(int32_t)deviceOrientation
2690 {
2691     if (_lastSentDeviceOrientation && _lastSentDeviceOrientation.value() == deviceOrientation)
2692         return;
2693
2694     _page->setDeviceOrientation(deviceOrientation);
2695     _lastSentDeviceOrientation = deviceOrientation;
2696 }
2697
2698 - (void)_frameOrBoundsChanged
2699 {
2700     CGRect bounds = self.bounds;
2701     [_scrollView setFrame:bounds];
2702
2703     if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing) {
2704         if (!_overridesViewLayoutSize)
2705             [self _dispatchSetViewLayoutSize:[self activeViewLayoutSize:self.bounds]];
2706         if (!_overridesMaximumUnobscuredSize)
2707             [self _dispatchSetMaximumUnobscuredSize:WebCore::FloatSize(bounds.size)];
2708
2709         BOOL sizeChanged = NO;
2710         if (auto drawingArea = _page->drawingArea())
2711             sizeChanged = drawingArea->setSize(WebCore::IntSize(bounds.size));
2712
2713         if (sizeChanged & [self usesStandardContentView])
2714             [_contentView setSizeChangedSinceLastVisibleContentRectUpdate:YES];
2715     }
2716
2717     [_customContentView web_setMinimumSize:bounds.size];
2718     [self _scheduleVisibleContentRectUpdate];
2719 }
2720
2721 // Unobscured content rect where the user can interact. When the keyboard is up, this should be the area above or below the keyboard, wherever there is enough space.
2722 - (CGRect)_contentRectForUserInteraction
2723 {
2724     // FIXME: handle split keyboard.
2725     UIEdgeInsets obscuredInsets = _obscuredInsets;
2726     obscuredInsets.bottom = std::max(_obscuredInsets.bottom, _inputViewBounds.size.height);
2727     CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInsets);
2728     return [self convertRect:unobscuredRect toView:self._currentContentView];
2729 }
2730
2731 // Ideally UIScrollView would expose this for us: <rdar://problem/21394567>.
2732 - (BOOL)_scrollViewIsRubberBanding
2733 {
2734     float deviceScaleFactor = _page->deviceScaleFactor();
2735
2736     CGPoint contentOffset = [_scrollView contentOffset];
2737     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
2738     return !pointsEqualInDevicePixels(contentOffset, boundedOffset, deviceScaleFactor);
2739 }
2740
2741 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2742 - (void)safeAreaInsetsDidChange
2743 {
2744     [super safeAreaInsetsDidChange];
2745
2746     [self _scheduleVisibleContentRectUpdate];
2747 }
2748 #endif
2749
2750 - (void)_scheduleVisibleContentRectUpdate
2751 {
2752     // For visible rect updates not associated with a specific UIScrollView, just consider our own scroller.
2753     [self _scheduleVisibleContentRectUpdateAfterScrollInView:_scrollView.get()];
2754 }
2755
2756 - (BOOL)_scrollViewIsInStableState:(UIScrollView *)scrollView
2757 {
2758     BOOL isStableState = !([scrollView isDragging] || [scrollView isDecelerating] || [scrollView isZooming] || [scrollView _isAnimatingZoom] || [scrollView _isScrollingToTop]);
2759
2760     if (isStableState && scrollView == _scrollView.get())
2761         isStableState = !_isChangingObscuredInsetsInteractively;
2762
2763     if (isStableState && scrollView == _scrollView.get())
2764         isStableState = ![self _scrollViewIsRubberBanding];
2765
2766     if (isStableState)
2767         isStableState = !scrollView._isInterruptingDeceleration;
2768
2769     if (NSNumber *stableOverride = self._stableStateOverride)
2770         isStableState = stableOverride.boolValue;
2771
2772     return isStableState;
2773 }
2774
2775 - (void)_addUpdateVisibleContentRectPreCommitHandler
2776 {
2777     auto retainedSelf = retainPtr(self);
2778     [CATransaction addCommitHandler:[retainedSelf] {
2779         WKWebView *webView = retainedSelf.get();
2780         if (![webView _isValid]) {
2781             RELEASE_LOG_IF(webView._page && webView._page->isAlwaysOnLoggingAllowed(), ViewState, "In CATransaction preCommitHandler, WKWebView %p is invalid", webView);
2782             return;
2783         }
2784
2785         @try {
2786             [webView _updateVisibleContentRects];
2787         } @catch (NSException *exception) {
2788             RELEASE_LOG_IF(webView._page && webView._page->isAlwaysOnLoggingAllowed(), ViewState, "In CATransaction preCommitHandler, -[WKWebView %p _updateVisibleContentRects] threw an exception", webView);
2789         }
2790         webView->_hasScheduledVisibleRectUpdate = NO;
2791     } forPhase:kCATransactionPhasePreCommit];
2792 }
2793
2794 - (void)_scheduleVisibleContentRectUpdateAfterScrollInView:(UIScrollView *)scrollView
2795 {
2796     _visibleContentRectUpdateScheduledFromScrollViewInStableState = [self _scrollViewIsInStableState:scrollView];
2797
2798     if (_hasScheduledVisibleRectUpdate) {
2799         auto timeNow = MonotonicTime::now();
2800         if ((timeNow - _timeOfRequestForVisibleContentRectUpdate) > delayBeforeNoVisibleContentsRectsLogging) {
2801             RELEASE_LOG_IF_ALLOWED("-[WKWebView %p _scheduleVisibleContentRectUpdateAfterScrollInView]: _hasScheduledVisibleRectUpdate is true but haven't updated visible content rects for %.2fs (last update was %.2fs ago) - valid %d",
2802                 self, (timeNow - _timeOfRequestForVisibleContentRectUpdate).value(), (timeNow - _timeOfLastVisibleContentRectUpdate).value(), [self _isValid]);
2803         }
2804         return;
2805     }
2806
2807     _hasScheduledVisibleRectUpdate = YES;
2808     _timeOfRequestForVisibleContentRectUpdate = MonotonicTime::now();
2809
2810     CATransactionPhase transactionPhase = [CATransaction currentPhase];
2811     if (transactionPhase == kCATransactionPhaseNull || transactionPhase == kCATransactionPhasePreLayout) {
2812         [self _addUpdateVisibleContentRectPreCommitHandler];
2813         return;
2814     }
2815
2816     dispatch_async(dispatch_get_main_queue(), [retainedSelf = retainPtr(self)] {
2817         WKWebView *webView = retainedSelf.get();
2818         if (![webView _isValid])
2819             return;
2820         [webView _addUpdateVisibleContentRectPreCommitHandler];
2821     });
2822 }
2823
2824 static bool scrollViewCanScroll(UIScrollView *scrollView)
2825 {
2826     if (!scrollView)
2827         return NO;
2828
2829     UIEdgeInsets contentInset = scrollView.contentInset;
2830     CGSize contentSize = scrollView.contentSize;
2831     CGSize boundsSize = scrollView.bounds.size;
2832
2833     return (contentSize.width + contentInset.left + contentInset.right) > boundsSize.width
2834         || (contentSize.height + contentInset.top + contentInset.bottom) > boundsSize.height;
2835 }
2836
2837 - (CGRect)_contentBoundsExtendedForRubberbandingWithScale:(CGFloat)scaleFactor
2838 {
2839     CGPoint contentOffset = [_scrollView contentOffset];
2840     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
2841
2842     CGFloat horiontalRubberbandAmountInContentCoordinates = (contentOffset.x - boundedOffset.x) / scaleFactor;
2843     CGFloat verticalRubberbandAmountInContentCoordinates = (contentOffset.y - boundedOffset.y) / scaleFactor;
2844
2845     CGRect extendedBounds = [_contentView bounds];
2846
2847     if (horiontalRubberbandAmountInContentCoordinates < 0) {
2848         extendedBounds.origin.x += horiontalRubberbandAmountInContentCoordinates;
2849         extendedBounds.size.width -= horiontalRubberbandAmountInContentCoordinates;
2850     } else if (horiontalRubberbandAmountInContentCoordinates > 0)
2851         extendedBounds.size.width += horiontalRubberbandAmountInContentCoordinates;
2852
2853     if (verticalRubberbandAmountInContentCoordinates < 0) {
2854         extendedBounds.origin.y += verticalRubberbandAmountInContentCoordinates;
2855         extendedBounds.size.height -= verticalRubberbandAmountInContentCoordinates;
2856     } else if (verticalRubberbandAmountInContentCoordinates > 0)
2857         extendedBounds.size.height += verticalRubberbandAmountInContentCoordinates;
2858
2859     return extendedBounds;
2860 }
2861
2862 - (void)_updateVisibleContentRects
2863 {
2864     BOOL inStableState = _visibleContentRectUpdateScheduledFromScrollViewInStableState;
2865
2866     if (![self usesStandardContentView]) {
2867         [_passwordView setFrame:self.bounds];
2868         [_customContentView web_computedContentInsetDidChange];
2869         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] - usesStandardContentView is NO, bailing", self);
2870         return;
2871     }
2872
2873     if (_delayUpdateVisibleContentRects) {
2874         _hadDelayedUpdateVisibleContentRects = YES;
2875         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] - _delayUpdateVisibleContentRects is YES, bailing", self);
2876         return;
2877     }
2878
2879     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing
2880         || (_needsResetViewStateAfterCommitLoadForMainFrame && ![_contentView sizeChangedSinceLastVisibleContentRectUpdate])
2881         || [_scrollView isZoomBouncing]
2882         || _currentlyAdjustingScrollViewInsetsForKeyboard) {
2883         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] - scroll view state is non-stable, bailing (_dynamicViewportUpdateMode %d, _needsResetViewStateAfterCommitLoadForMainFrame %d, sizeChangedSinceLastVisibleContentRectUpdate %d, [_scrollView isZoomBouncing] %d, _currentlyAdjustingScrollViewInsetsForKeyboard %d)",
2884             self, _dynamicViewportUpdateMode, _needsResetViewStateAfterCommitLoadForMainFrame, [_contentView sizeChangedSinceLastVisibleContentRectUpdate], [_scrollView isZoomBouncing], _currentlyAdjustingScrollViewInsetsForKeyboard);
2885         return;
2886     }
2887
2888     CGRect visibleRectInContentCoordinates = [self _visibleContentRect];
2889
2890     UIEdgeInsets computedContentInsetUnadjustedForKeyboard = [self _computedObscuredInset];
2891     if (!_haveSetObscuredInsets)
2892         computedContentInsetUnadjustedForKeyboard.bottom -= _totalScrollViewBottomInsetAdjustmentForKeyboard;
2893
2894     CGFloat scaleFactor = contentZoomScale(self);
2895
2896     CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, computedContentInsetUnadjustedForKeyboard);
2897     CGRect unobscuredRectInContentCoordinates = _frozenUnobscuredContentRect ? _frozenUnobscuredContentRect.value() : [self convertRect:unobscuredRect toView:_contentView.get()];
2898     unobscuredRectInContentCoordinates = CGRectIntersection(unobscuredRectInContentCoordinates, [self _contentBoundsExtendedForRubberbandingWithScale:scaleFactor]);
2899
2900 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2901     if (inStableState) {
2902         WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2903         if (coordinator && coordinator->hasActiveSnapPoint()) {
2904             CGPoint currentPoint = [_scrollView contentOffset];
2905             CGPoint activePoint = coordinator->nearestActiveContentInsetAdjustedSnapPoint(unobscuredRect.origin.y, currentPoint);
2906
2907             if (!CGPointEqualToPoint(activePoint, currentPoint)) {
2908                 RetainPtr<WKScrollView> strongScrollView = _scrollView;
2909                 dispatch_async(dispatch_get_main_queue(), [strongScrollView, activePoint] {
2910                     [strongScrollView setContentOffset:activePoint animated:NO];
2911                 });
2912             }
2913         }
2914     }
2915 #endif
2916
2917     [_contentView didUpdateVisibleRect:visibleRectInContentCoordinates
2918         unobscuredRect:unobscuredRectInContentCoordinates
2919         unobscuredRectInScrollViewCoordinates:unobscuredRect
2920         obscuredInsets:_obscuredInsets
2921         unobscuredSafeAreaInsets:[self _computedUnobscuredSafeAreaInset]
2922         inputViewBounds:_inputViewBounds
2923         scale:scaleFactor minimumScale:[_scrollView minimumZoomScale]
2924         inStableState:inStableState
2925         isChangingObscuredInsetsInteractively:_isChangingObscuredInsetsInteractively
2926         enclosedInScrollableAncestorView:scrollViewCanScroll([self _scroller])];
2927
2928     while (!_visibleContentRectUpdateCallbacks.isEmpty()) {
2929         auto callback = _visibleContentRectUpdateCallbacks.takeLast();
2930         callback();
2931     }
2932     
2933     auto timeNow = MonotonicTime::now();
2934     if ((timeNow - _timeOfRequestForVisibleContentRectUpdate) > delayBeforeNoVisibleContentsRectsLogging)
2935         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] finally ran %.2fs after being scheduled", self, (timeNow - _timeOfRequestForVisibleContentRectUpdate).value());
2936
2937     _timeOfLastVisibleContentRectUpdate = timeNow;
2938 }
2939
2940 - (void)_didStartProvisionalLoadForMainFrame
2941 {
2942     if (_gestureController)
2943         _gestureController->didStartProvisionalLoadForMainFrame();
2944 }
2945
2946 static WebCore::FloatSize activeMaximumUnobscuredSize(WKWebView *webView, const CGRect& bounds)
2947 {
2948     return WebCore::FloatSize(webView->_overridesMaximumUnobscuredSize ? webView->_maximumUnobscuredSizeOverride : bounds.size);
2949 }
2950
2951 static int32_t activeOrientation(WKWebView *webView)
2952 {
2953     return webView->_overridesInterfaceOrientation ? deviceOrientationForUIInterfaceOrientation(webView->_interfaceOrientationOverride) : webView->_page->deviceOrientation();
2954 }
2955
2956 - (void)_cancelAnimatedResize
2957 {
2958     LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _cancelAnimatedResize:] " << " _dynamicViewportUpdateMode " << (int)_dynamicViewportUpdateMode);
2959     if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing)
2960         return;
2961
2962     if (!_customContentView) {
2963         if (_resizeAnimationView) {
2964             NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
2965             [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
2966             [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
2967             [_resizeAnimationView removeFromSuperview];
2968             _resizeAnimationView = nil;
2969         }
2970
2971         [_contentView setHidden:NO];
2972         _resizeAnimationTransformAdjustments = CATransform3DIdentity;
2973     }
2974
2975     _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
2976     [self _scheduleVisibleContentRectUpdate];
2977 }
2978
2979 - (void)_didCompleteAnimatedResize
2980 {
2981     if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing)
2982         return;
2983
2984     [_contentView setHidden:NO];
2985
2986     if (!_resizeAnimationView) {
2987         // Paranoia. If _resizeAnimationView is null we'll end up setting a zero scale on the content view.
2988         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didCompleteAnimatedResize:] - _resizeAnimationView is nil", self);
2989         [self _cancelAnimatedResize];
2990         return;
2991     }
2992
2993     NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
2994     [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
2995     [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
2996
2997     CALayer *contentLayer = [_contentView layer];
2998     CGFloat adjustmentScale = _resizeAnimationTransformAdjustments.m11;
2999     contentLayer.sublayerTransform = CATransform3DIdentity;
3000
3001     CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
3002     CATransform3D contentLayerTransform = contentLayer.transform;
3003     CGFloat currentScale = [[_resizeAnimationView layer] transform].m11 * contentLayerTransform.m11;
3004
3005     // We cannot use [UIScrollView setZoomScale:] directly because the UIScrollView delegate would get a callback with
3006     // an invalid contentOffset. The real content offset is only set below.
3007     // Since there is no public API for setting both the zoomScale and the contentOffset, we set the zoomScale manually
3008     // on the zoom layer and then only change the contentOffset.
3009     CGFloat adjustedScale = adjustmentScale * currentScale;
3010     contentLayerTransform.m11 = adjustedScale;
3011     contentLayerTransform.m22 = adjustedScale;
3012     contentLayer.transform = contentLayerTransform;
3013
3014     CGPoint currentScrollOffset = [_scrollView contentOffset];
3015     double horizontalScrollAdjustement = _resizeAnimationTransformAdjustments.m41 * animatingScaleTarget;
3016     double verticalScrollAdjustment = _resizeAnimationTransformAdjustments.m42 * animatingScaleTarget;
3017
3018     [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
3019     [_scrollView setContentOffset:CGPointMake(currentScrollOffset.x - horizontalScrollAdjustement, currentScrollOffset.y - verticalScrollAdjustment)];
3020
3021     [_resizeAnimationView removeFromSuperview];
3022     _resizeAnimationView = nil;
3023     _resizeAnimationTransformAdjustments = CATransform3DIdentity;
3024
3025     _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
3026     [self _scheduleVisibleContentRectUpdate];
3027
3028     CGRect newBounds = self.bounds;
3029     auto newViewLayoutSize = [self activeViewLayoutSize:newBounds];
3030     auto newMaximumUnobscuredSize = activeMaximumUnobscuredSize(self, newBounds);
3031     int32_t newOrientation = activeOrientation(self);
3032
3033     if (!_lastSentViewLayoutSize || newViewLayoutSize != _lastSentViewLayoutSize.value())
3034         [self _dispatchSetViewLayoutSize:newViewLayoutSize];
3035
3036     if (!_lastSentMaximumUnobscuredSize || newMaximumUnobscuredSize != _lastSentMaximumUnobscuredSize.value())
3037         [self _dispatchSetMaximumUnobscuredSize:WebCore::FloatSize(newMaximumUnobscuredSize)];
3038
3039     if (!_lastSentDeviceOrientation || newOrientation != _lastSentDeviceOrientation.value())
3040         [self _dispatchSetDeviceOrientation:newOrientation];
3041
3042     while (!_callbacksDeferredDuringResize.isEmpty())
3043         _callbacksDeferredDuringResize.takeLast()();
3044 }
3045
3046 - (void)_didFinishLoadForMainFrame
3047 {
3048     if (_gestureController)
3049         _gestureController->didFinishLoadForMainFrame();
3050 }
3051
3052 - (void)_didFailLoadForMainFrame
3053 {
3054     if (_gestureController)
3055         _gestureController->didFailLoadForMainFrame();
3056 }
3057
3058 - (void)_didSameDocumentNavigationForMainFrame:(WebKit::SameDocumentNavigationType)navigationType
3059 {
3060     [_customContentView web_didSameDocumentNavigation:toAPI(navigationType)];
3061
3062     if (_gestureController)
3063         _gestureController->didSameDocumentNavigationForMainFrame(navigationType);
3064 }
3065
3066 - (void)_keyboardChangedWithInfo:(NSDictionary *)keyboardInfo adjustScrollView:(BOOL)adjustScrollView
3067 {
3068     NSValue *endFrameValue = [keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
3069     if (!endFrameValue)
3070         return;
3071
3072     // The keyboard rect is always in screen coordinates. In the view services case the window does not
3073     // have the interface orientation rotation transformation; its host does. So, it makes no sense to
3074     // clip the keyboard rect against its screen.
3075     if ([[self window] _isHostedInAnotherProcess])
3076         _inputViewBounds = [self.window convertRect:[endFrameValue CGRectValue] fromWindow:nil];
3077     else
3078         _inputViewBounds = [self.window convertRect:CGRectIntersection([endFrameValue CGRectValue], self.window.screen.bounds) fromWindow:nil];
3079
3080     if (adjustScrollView) {
3081         CGFloat bottomInsetBeforeAdjustment = [_scrollView contentInset].bottom;
3082         SetForScope<BOOL> insetAdjustmentGuard(_currentlyAdjustingScrollViewInsetsForKeyboard, YES);
3083         [_scrollView _adjustForAutomaticKeyboardInfo:keyboardInfo animated:YES lastAdjustment:&_lastAdjustmentForScroller];
3084         CGFloat bottomInsetAfterAdjustment = [_scrollView contentInset].bottom;
3085         if (bottomInsetBeforeAdjustment != bottomInsetAfterAdjustment)
3086             _totalScrollViewBottomInsetAdjustmentForKeyboard += bottomInsetAfterAdjustment - bottomInsetBeforeAdjustment;
3087     }
3088
3089     [self _scheduleVisibleContentRectUpdate];
3090 }
3091
3092 - (BOOL)_shouldUpdateKeyboardWithInfo:(NSDictionary *)keyboardInfo
3093 {
3094     if ([_contentView isAssistingNode])
3095         return YES;
3096
3097     NSNumber *isLocalKeyboard = [keyboardInfo valueForKey:UIKeyboardIsLocalUserInfoKey];
3098     return isLocalKeyboard && !isLocalKeyboard.boolValue;
3099 }
3100
3101 - (void)_keyboardWillChangeFrame:(NSNotification *)notification
3102 {
3103     if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
3104         [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
3105 }
3106
3107 - (void)_keyboardDidChangeFrame:(NSNotification *)notification
3108 {
3109     [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:NO];
3110 }
3111
3112 - (void)_keyboardWillShow:(NSNotification *)notification
3113 {
3114     if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
3115         [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
3116
3117     _page->setIsKeyboardAnimatingIn(true);
3118 }
3119
3120 - (void)_keyboardDidShow:(NSNotification *)notification
3121 {
3122     _page->setIsKeyboardAnimatingIn(false);
3123 }
3124
3125 - (void)_keyboardWillHide:(NSNotification *)notification
3126 {
3127     // Ignore keyboard will hide notifications sent during rotation. They're just there for
3128     // backwards compatibility reasons and processing the will hide notification would
3129     // temporarily screw up the unobscured view area.
3130     if ([[UIPeripheralHost sharedInstance] rotationState])
3131         return;
3132
3133     [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
3134 }
3135
3136 static void hardwareKeyboardAvailabilityChangedCallback(CFNotificationCenterRef, void* observer, CFStringRef, const void*, CFDictionaryRef)
3137 {
3138     ASSERT(observer);
3139     WKWebView *webView = (__bridge WKWebView *)observer;
3140     webView._page->hardwareKeyboardAvailabilityChanged();
3141 }
3142
3143 - (void)_windowDidRotate:(NSNotification *)notification
3144 {
3145     if (!_overridesInterfaceOrientation)
3146         [self _dispatchSetDeviceOrientation:deviceOrientation()];
3147 }
3148
3149 - (void)_contentSizeCategoryDidChange:(NSNotification *)notification
3150 {
3151     _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
3152 }
3153
3154 - (NSString *)_contentSizeCategory
3155 {
3156     return [[UIApplication sharedApplication] preferredContentSizeCategory];
3157 }
3158
3159 - (void)_accessibilitySettingsDidChange:(NSNotification *)notification
3160 {
3161     _page->accessibilitySettingsDidChange();
3162 }
3163
3164 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
3165 {
3166     if (_allowsBackForwardNavigationGestures == allowsBackForwardNavigationGestures)
3167         return;
3168
3169     _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
3170
3171     if (allowsBackForwardNavigationGestures && !_gestureController) {
3172         _gestureController = std::make_unique<WebKit::ViewGestureController>(*_page);
3173         _gestureController->installSwipeHandler(self, [self scrollView]);
3174         if (WKWebView *alternateWebView = [_configuration _alternateWebViewForNavigationGestures])
3175             _gestureController->setAlternateBackForwardListSourcePage(alternateWebView->_page.get());
3176     }
3177
3178     if (_gestureController)
3179         _gestureController->setSwipeGestureEnabled(allowsBackForwardNavigationGestures);
3180
3181     _page->setShouldRecordNavigationSnapshots(allowsBackForwardNavigationGestures);
3182 }
3183
3184 - (BOOL)allowsBackForwardNavigationGestures
3185 {
3186     return _allowsBackForwardNavigationGestures;
3187 }
3188
3189 - (BOOL)_isNavigationSwipeGestureRecognizer:(UIGestureRecognizer *)recognizer
3190 {
3191     if (!_gestureController)
3192         return NO;
3193     return _gestureController->isNavigationSwipeGestureRecognizer(recognizer);
3194 }
3195
3196 - (void)_navigationGestureDidBegin
3197 {
3198     // During a back/forward swipe, there's a view interposed between this view and the content view that has
3199     // an offset and animation on it, which results in computing incorrect rectangles. Work around by using
3200     // frozen rects during swipes.
3201     CGRect fullViewRect = self.bounds;
3202     CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, [self _computedObscuredInset]);
3203
3204     _frozenVisibleContentRect = [self convertRect:fullViewRect toView:_contentView.get()];
3205     _frozenUnobscuredContentRect = [self convertRect:unobscuredRect toView:_contentView.get()];
3206
3207     LOG_WITH_STREAM(VisibleRects, stream << "_navigationGestureDidBegin: freezing visibleContentRect " << WebCore::FloatRect(_frozenVisibleContentRect.value()) << " UnobscuredContentRect " << WebCore::FloatRect(_frozenUnobscuredContentRect.value()));
3208 }
3209
3210 - (void)_navigationGestureDidEnd
3211 {
3212     _frozenVisibleContentRect = std::nullopt;
3213     _frozenUnobscuredContentRect = std::nullopt;
3214 }
3215
3216 - (void)_showPasswordViewWithDocumentName:(NSString *)documentName passwordHandler:(void (^)(NSString *))passwordHandler
3217 {
3218     ASSERT(!_passwordView);
3219     _passwordView = adoptNS([[WKPasswordView alloc] initWithFrame:self.bounds documentName:documentName]);
3220     [_passwordView setUserDidEnterPassword:passwordHandler];
3221     [_passwordView showInScrollView:_scrollView.get()];
3222     self._currentContentView.hidden = YES;
3223 }
3224
3225 - (void)_hidePasswordView
3226 {
3227     if (!_passwordView)
3228         return;
3229
3230     self._currentContentView.hidden = NO;
3231     [_passwordView hide];
3232     _passwordView = nil;
3233 }
3234
3235 - (WKPasswordView *)_passwordView
3236 {
3237     return _passwordView.get();
3238 }
3239
3240 - (void)_updateScrollViewInsetAdjustmentBehavior
3241 {
3242 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
3243     if (![_scrollView _contentInsetAdjustmentBehaviorWasExternallyOverridden])
3244         [_scrollView _setContentInsetAdjustmentBehaviorInternal:self._safeAreaShouldAffectObscuredInsets ? UIScrollViewContentInsetAdjustmentAlways : UIScrollViewContentInsetAdjustmentNever];
3245 #endif
3246 }
3247
3248 - (void)_setAvoidsUnsafeArea:(BOOL)avoidsUnsafeArea
3249 {
3250     if (_avoidsUnsafeArea == avoidsUnsafeArea)
3251         return;
3252
3253     _avoidsUnsafeArea = avoidsUnsafeArea;
3254
3255     [self _updateScrollViewInsetAdjustmentBehavior];
3256     [self _scheduleVisibleContentRectUpdate];
3257
3258     id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)[self UIDelegate];
3259     if ([uiDelegate respondsToSelector:@selector(_webView:didChangeSafeAreaShouldAffectObscuredInsets:)])
3260         [uiDelegate _webView:self didChangeSafeAreaShouldAffectObscuredInsets:avoidsUnsafeArea];
3261 }
3262
3263 - (BOOL)_haveSetObscuredInsets
3264 {
3265     return _haveSetObscuredInsets;
3266 }
3267
3268 #endif // PLATFORM(IOS_FAMILY)
3269
3270 #if ENABLE(ACCESSIBILITY_EVENTS)
3271
3272 static void accessibilityEventsEnabledChangedCallback(CFNotificationCenterRef, void* observer, CFStringRef, const void*, CFDictionaryRef)
3273 {
3274     ASSERT(observer);
3275     WKWebView *webview = (__bridge WKWebView *)observer;
3276     [webview _updateAccessibilityEventsEnabled];
3277 }
3278
3279 - (void)_updateAccessibilityEventsEnabled
3280 {
3281     if (!isNullFunctionPointer(_AXSWebAccessibilityEventsEnabled))
3282         _page->updateAccessibilityEventsEnabled(_AXSWebAccessibilityEventsEnabled());
3283 }
3284
3285 #endif
3286
3287 #pragma mark OS X-specific methods
3288
3289 #if PLATFORM(MAC)
3290
3291 - (BOOL)acceptsFirstResponder
3292 {
3293     return _impl->acceptsFirstResponder();
3294 }
3295
3296 - (BOOL)becomeFirstResponder
3297 {
3298     return _impl->becomeFirstResponder();
3299 }
3300
3301 - (BOOL)resignFirstResponder
3302 {
3303     return _impl->resignFirstResponder();
3304 }
3305
3306 - (void)viewWillStartLiveResize
3307 {
3308     _impl->viewWillStartLiveResize();
3309 }
3310
3311 - (void)viewDidEndLiveResize
3312 {
3313     _impl->viewDidEndLiveResize();
3314 }
3315
3316 - (BOOL)isFlipped
3317 {
3318     return YES;
3319 }
3320
3321 - (NSSize)intrinsicContentSize
3322 {
3323     return NSSizeFromCGSize(_impl->intrinsicContentSize());
3324 }
3325
3326 - (void)prepareContentInRect:(NSRect)rect
3327 {
3328     _impl->prepareContentInRect(NSRectToCGRect(rect));
3329 }
3330
3331 - (void)setFrameSize:(NSSize)size
3332 {
3333     [super setFrameSize:size];
3334     [_safeBrowsingWarning setFrame:self.bounds];
3335     _impl->setFrameSize(NSSizeToCGSize(size));
3336 }
3337
3338 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
3339 - (void)renewGState
3340 IGNORE_WARNINGS_END
3341 {
3342     _impl->renewGState();
3343     [super renewGState];
3344 }
3345
3346 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _impl->executeEditCommandForSelector(_cmd); }
3347
3348 WEBCORE_COMMAND(alignCenter)
3349 WEBCORE_COMMAND(alignJustified)
3350 WEBCORE_COMMAND(alignLeft)
3351 WEBCORE_COMMAND(alignRight)
3352 WEBCORE_COMMAND(copy)
3353 WEBCORE_COMMAND(cut)
3354 WEBCORE_COMMAND(delete)
3355 WEBCORE_COMMAND(deleteBackward)
3356 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
3357 WEBCORE_COMMAND(deleteForward)
3358 WEBCORE_COMMAND(deleteToBeginningOfLine)
3359 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
3360 WEBCORE_COMMAND(deleteToEndOfLine)
3361 WEBCORE_COMMAND(deleteToEndOfParagraph)
3362 WEBCORE_COMMAND(deleteToMark)
3363 WEBCORE_COMMAND(deleteWordBackward)
3364 WEBCORE_COMMAND(deleteWordForward)
3365 WEBCORE_COMMAND(ignoreSpelling)
3366 WEBCORE_COMMAND(indent)
3367 WEBCORE_COMMAND(insertBacktab)
3368 WEBCORE_COMMAND(insertLineBreak)
3369 WEBCORE_COMMAND(insertNewline)
3370 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
3371 WEBCORE_COMMAND(insertParagraphSeparator)
3372 WEBCORE_COMMAND(insertTab)
3373 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
3374 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
3375 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
3376 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
3377 WEBCORE_COMMAND(moveBackward)
3378 WEBCORE_COMMAND(moveBackwardAndModifySelection)
3379 WEBCORE_COMMAND(moveDown)
3380 WEBCORE_COMMAND(moveDownAndModifySelection)
3381 WEBCORE_COMMAND(moveForward)
3382 WEBCORE_COMMAND(moveForwardAndModifySelection)
3383 WEBCORE_COMMAND(moveLeft)
3384 WEBCORE_COMMAND(moveLeftAndModifySelection)
3385 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
3386 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
3387 WEBCORE_COMMAND(moveRight)
3388 WEBCORE_COMMAND(moveRightAndModifySelection)
3389 WEBCORE_COMMAND(moveToBeginningOfDocument)
3390 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
3391 WEBCORE_COMMAND(moveToBeginningOfLine)
3392 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
3393 WEBCORE_COMMAND(moveToBeginningOfParagraph)
3394 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
3395 WEBCORE_COMMAND(moveToBeginningOfSentence)
3396 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
3397 WEBCORE_COMMAND(moveToEndOfDocument)
3398 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
3399 WEBCORE_COMMAND(moveToEndOfLine)
3400 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
3401 WEBCORE_COMMAND(moveToEndOfParagraph)
3402 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
3403 WEBCORE_COMMAND(moveToEndOfSentence)
3404 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
3405 WEBCORE_COMMAND(moveToLeftEndOfLine)
3406 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
3407 WEBCORE_COMMAND(moveToRightEndOfLine)
3408 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
3409 WEBCORE_COMMAND(moveUp)
3410 WEBCORE_COMMAND(moveUpAndModifySelection)
3411 WEBCORE_COMMAND(moveWordBackward)
3412 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
3413 WEBCORE_COMMAND(moveWordForward)
3414 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
3415 WEBCORE_COMMAND(moveWordLeft)
3416 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
3417 WEBCORE_COMMAND(moveWordRight)
3418 WEBCORE_COMMAND(moveWordRightAndModifySelection)
3419 WEBCORE_COMMAND(outdent)
3420 WEBCORE_COMMAND(pageDown)
3421 WEBCORE_COMMAND(pageDownAndModifySelection)
3422 WEBCORE_COMMAND(pageUp)
3423 WEBCORE_COMMAND(pageUpAndModifySelection)
3424 WEBCORE_COMMAND(paste)
3425 WEBCORE_COMMAND(pasteAsPlainText)
3426 WEBCORE_COMMAND(scrollPageDown)
3427 WEBCORE_COMMAND(scrollPageUp)
3428 WEBCORE_COMMAND(scrollLineDown)
3429 WEBCORE_COMMAND(scrollLineUp)
3430 WEBCORE_COMMAND(scrollToBeginningOfDocument)
3431 WEBCORE_COMMAND(scrollToEndOfDocument)
3432 WEBCORE_COMMAND(selectAll)
3433 WEBCORE_COMMAND(selectLine)
3434 WEBCORE_COMMAND(selectParagraph)
3435 WEBCORE_COMMAND(selectSentence)
3436 WEBCORE_COMMAND(selectToMark)
3437 WEBCORE_COMMAND(selectWord)
3438 WEBCORE_COMMAND(setMark)
3439 WEBCORE_COMMAND(subscript)
3440 WEBCORE_COMMAND(superscript)
3441 WEBCORE_COMMAND(swapWithMark)
3442 WEBCORE_COMMAND(takeFindStringFromSelection)
3443 WEBCORE_COMMAND(transpose)
3444 WEBCORE_COMMAND(underline)
3445 WEBCORE_COMMAND(unscript)
3446 WEBCORE_COMMAND(yank)
3447 WEBCORE_COMMAND(yankAndSelect)
3448
3449 #undef WEBCORE_COMMAND
3450
3451 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
3452 {
3453     return _impl->writeSelectionToPasteboard(pasteboard, types);
3454 }
3455
3456 - (void)centerSelectionInVisibleArea:(id)sender
3457 {
3458     _impl->centerSelectionInVisibleArea();
3459 }
3460
3461 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
3462 {
3463     return _impl->validRequestorForSendAndReturnTypes(sendType, returnType);
3464 }
3465
3466 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
3467 {
3468     return _impl->readSelectionFromPasteboard(pasteboard);
3469 }
3470
3471 - (void)changeFont:(id)sender
3472 {
3473     _impl->changeFontFromFontManager();
3474 }
3475
3476 - (void)changeColor:(id)sender
3477 {
3478     _impl->changeFontColorFromSender(sender);
3479 }
3480
3481 - (void)changeAttributes:(id)sender
3482 {
3483     _impl->changeFontAttributesFromSender(sender);
3484 }
3485
3486 - (IBAction)startSpeaking:(id)sender
3487 {
3488     _impl->startSpeaking();
3489 }
3490
3491 - (IBAction)stopSpeaking:(id)sender
3492 {
3493     _impl->stopSpeaking(sender);
3494 }
3495
3496 - (IBAction)showGuessPanel:(id)sender
3497 {
3498     _impl->showGuessPanel(sender);
3499 }
3500
3501 - (IBAction)checkSpelling:(id)sender
3502 {
3503     _impl->checkSpelling();
3504 }
3505
3506 - (void)changeSpelling:(id)sender
3507 {
3508     _impl->changeSpelling(sender);
3509 }
3510
3511 - (IBAction)toggleContinuousSpellChecking:(id)sender
3512 {
3513     _impl->toggleContinuousSpellChecking();
3514 }
3515
3516 - (BOOL)isGrammarCheckingEnabled
3517 {
3518     return _impl->isGrammarCheckingEnabled();
3519 }
3520
3521 - (void)setGrammarCheckingEnabled:(BOOL)flag
3522 {
3523     _impl->setGrammarCheckingEnabled(flag);
3524 }
3525
3526 - (IBAction)toggleGrammarChecking:(id)sender
3527 {
3528     _impl->toggleGrammarChecking();
3529 }
3530
3531 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
3532 {
3533     _impl->toggleAutomaticSpellingCorrection();
3534 }
3535
3536 - (void)orderFrontSubstitutionsPanel:(id)sender
3537 {
3538     _impl->orderFrontSubstitutionsPanel(sender);
3539 }
3540
3541 - (IBAction)toggleSmartInsertDelete:(id)sender
3542 {
3543     _impl->toggleSmartInsertDelete();
3544 }
3545
3546 - (BOOL)isAutomaticQuoteSubstitutionEnabled
3547 {
3548     return _impl->isAutomaticQuoteSubstitutionEnabled();
3549 }
3550
3551 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
3552 {
3553     _impl->setAutomaticQuoteSubstitutionEnabled(flag);
3554 }
3555
3556 - (void)toggleAutomaticQuoteSubstitution:(id)sender
3557 {
3558     _impl->toggleAutomaticQuoteSubstitution();
3559 }
3560
3561 - (BOOL)isAutomaticDashSubstitutionEnabled
3562 {
3563     return _impl->isAutomaticDashSubstitutionEnabled();
3564 }
3565
3566 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
3567 {
3568     _impl->setAutomaticDashSubstitutionEnabled(flag);
3569 }
3570
3571 - (void)toggleAutomaticDashSubstitution:(id)sender
3572 {
3573     _impl->toggleAutomaticDashSubstitution();
3574 }
3575
3576 - (BOOL)isAutomaticLinkDetectionEnabled
3577 {
3578     return _impl->isAutomaticLinkDetectionEnabled();
3579 }
3580
3581 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
3582 {
3583     _impl->setAutomaticLinkDetectionEnabled(flag);
3584 }
3585
3586 - (void)toggleAutomaticLinkDetection:(id)sender
3587 {
3588     _impl->toggleAutomaticLinkDetection();
3589 }
3590
3591 - (BOOL)isAutomaticTextReplacementEnabled
3592 {
3593     return _impl->isAutomaticTextReplacementEnabled();
3594 }
3595
3596 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
3597 {
3598     _impl->setAutomaticTextReplacementEnabled(flag);
3599 }
3600
3601 - (void)toggleAutomaticTextReplacement:(id)sender
3602 {
3603     _impl->toggleAutomaticTextReplacement();
3604 }
3605
3606 - (void)uppercaseWord:(id)sender
3607 {
3608     _impl->uppercaseWord();
3609 }
3610
3611 - (void)lowercaseWord:(id)sender
3612 {
3613     _impl->lowercaseWord();
3614 }
3615
3616 - (void)capitalizeWord:(id)sender
3617 {
3618     _impl->capitalizeWord();
3619 }
3620
3621 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
3622 {
3623     return _impl->wantsKeyDownForEvent(event);
3624 }
3625
3626 - (void)scrollWheel:(NSEvent *)event
3627 {
3628     _impl->scrollWheel(event);
3629 }
3630
3631 - (void)swipeWithEvent:(NSEvent *)event
3632 {
3633     _impl->swipeWithEvent(event);
3634 }
3635
3636 - (void)mouseMoved:(NSEvent *)event
3637 {
3638     _impl->mouseMoved(event);
3639 }
3640
3641 - (void)mouseDown:(NSEvent *)event
3642 {
3643     _impl->mouseDown(event);
3644 }
3645
3646 - (void)mouseUp:(NSEvent *)event
3647 {
3648     _impl->mouseUp(event);
3649 }
3650
3651 - (void)mouseDragged:(NSEvent *)event
3652 {
3653     _impl->mouseDragged(event);
3654 }
3655
3656 - (void)mouseEntered:(NSEvent *)event
3657 {
3658     _impl->mouseEntered(event);
3659 }
3660
3661 - (void)mouseExited:(NSEvent *)event
3662 {
3663     _impl->mouseExited(event);
3664 }
3665
3666 - (void)otherMouseDown:(NSEvent *)event
3667 {
3668     _impl->otherMouseDown(event);
3669 }
3670
3671 - (void)otherMouseDragged:(NSEvent *)event
3672 {
3673     _impl->otherMouseDragged(event);
3674 }
3675
3676 - (void)otherMouseUp:(NSEvent *)event
3677 {
3678     _impl->otherMouseUp(event);
3679 }
3680
3681 - (void)rightMouseDown:(NSEvent *)event
3682 {
3683     _impl->rightMouseDown(event);
3684 }
3685
3686 - (void)rightMouseDragged:(NSEvent *)event
3687 {
3688     _impl->rightMouseDragged(event);
3689 }
3690
3691 - (void)rightMouseUp:(NSEvent *)event
3692 {
3693     _impl->rightMouseUp(event);
3694 }
3695
3696 - (void)pressureChangeWithEvent:(NSEvent *)event
3697 {
3698     _impl->pressureChangeWithEvent(event);
3699 }
3700
3701 - (BOOL)acceptsFirstMouse:(NSEvent *)event
3702 {
3703     return _impl->acceptsFirstMouse(event);
3704 }
3705
3706 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
3707 {
3708     return _impl->shouldDelayWindowOrderingForEvent(event);
3709 }
3710
3711 - (void)doCommandBySelector:(SEL)selector
3712 {
3713     _impl->doCommandBySelector(selector);
3714 }
3715
3716 - (void)insertText:(id)string
3717 {
3718     _impl->insertText(string);
3719 }
3720
3721 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
3722 {
3723     _impl->insertText(string, replacementRange);
3724 }
3725
3726 - (NSTextInputContext *)inputContext
3727 {
3728     if (!_impl)
3729         return nil;
3730     return _impl->inputContext();
3731 }
3732
3733 - (BOOL)performKeyEquivalent:(NSEvent *)event
3734 {
3735     return _impl->performKeyEquivalent(event);
3736 }
3737
3738 - (void)keyUp:(NSEvent *)theEvent
3739 {
3740     _impl->keyUp(theEvent);
3741 }
3742
3743 - (void)keyDown:(NSEvent *)theEvent
3744 {
3745     _impl->keyDown(theEvent);
3746 }
3747
3748 - (void)flagsChanged:(NSEvent *)theEvent
3749 {
3750     _impl->flagsChanged(theEvent);
3751 }
3752
3753 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelectedRange replacementRange:(NSRange)replacementRange
3754 {
3755     _impl->setMarkedText(string, newSelectedRange, replacementRange);
3756 }
3757
3758 - (void)unmarkText
3759 {
3760     _impl->unmarkText();
3761 }
3762
3763 - (NSRange)selectedRange
3764 {
3765     return _impl->selectedRange();
3766 }
3767
3768 - (BOOL)hasMarkedText
3769 {
3770     return _impl->hasMarkedText();
3771 }
3772
3773 - (NSRange)markedRange
3774 {
3775     return _impl->markedRange();
3776 }
3777
3778 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange
3779 {
3780     return _impl->attributedSubstringForProposedRange(nsRange, actualRange);
3781 }
3782
3783 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
3784 {
3785     return _impl->characterIndexForPoint(thePoint);
3786 }
3787
3788 - (void)typingAttributesWithCompletionHandler:(void(^)(NSDictionary<NSString *, id> *))completion
3789 {
3790     _impl->typingAttributesWithCompletionHandler(completion);
3791 }
3792
3793 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
3794 {
3795     return _impl->firstRectForCharacterRange(theRange, actualRange);
3796 }
3797
3798 - (void)selectedRangeWithCompletionHandler:(void(^)(NSRange selectedRange))completionHandlerPtr
3799 {
3800     _impl->selectedRangeWithCompletionHandler(completionHandlerPtr);
3801 }
3802
3803 - (void)markedRangeWithCompletionHandler:(void(^)(NSRange markedRange))completionHandlerPtr
3804 {
3805     _impl->markedRangeWithCompletionHandler(completionHandlerPtr);
3806 }
3807
3808 - (void)hasMarkedTextWithCompletionHandler:(void(^)(BOOL hasMarkedText))completionHandlerPtr
3809 {
3810     _impl->hasMarkedTextWithCompletionHandler(completionHandlerPtr);
3811 }
3812
3813 - (void)attributedSubstringForProposedRange:(NSRange)nsRange completionHandler:(void(^)(NSAttributedString *attrString, NSRange actualRange))completionHandlerPtr
3814 {
3815     _impl->attributedSubstringForProposedRange(nsRange, completionHandlerPtr);
3816 }
3817
3818 - (void)firstRectForCharacterRange:(NSRange)theRange completionHandler:(void(^)(NSRect firstRect, NSRange actualRange))completionHandlerPtr
3819 {
3820     _impl->firstRectForCharacterRange(theRange, completionHandlerPtr);
3821 }
3822
3823 - (void)characterIndexForPoint:(NSPoint)thePoint completionHandler:(void(^)(NSUInteger))completionHandlerPtr
3824 {
3825     _impl->characterIndexForPoint(thePoint, completionHandlerPtr);
3826 }
3827
3828 - (NSArray *)validAttributesForMarkedText
3829 {
3830     return _impl->validAttributesForMarkedText();
3831 }
3832
3833 #if ENABLE(DRAG_SUPPORT)
3834 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
3835 - (void)draggedImage:(NSImage *)image endedAt:(NSPoint)endPoint operation:(NSDragOperation)operation
3836 IGNORE_WARNINGS_END
3837 {
3838     _impl->draggedImage(image, NSPointToCGPoint(endPoint), operation);
3839 }
3840
3841 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
3842 {
3843     return _impl->draggingEntered(draggingInfo);
3844 }
3845
3846 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
3847 {
3848     return _impl->draggingUpdated(draggingInfo);
3849 }
3850
3851 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
3852 {
3853     _impl->draggingExited(draggingInfo);
3854 }
3855
3856 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
3857 {
3858     return _impl->prepareForDragOperation(draggingInfo);
3859 }
3860
3861 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
3862 {
3863     return _impl->performDragOperation(draggingInfo);
3864 }
3865
3866 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
3867 {
3868     return _impl->hitTestForDragTypes(NSPointToCGPoint(*point), types);
3869 }
3870 #endif // ENABLE(DRAG_SUPPORT)
3871
3872 - (BOOL)_windowResizeMouseLocationIsInVisibleScrollerThumb:(NSPoint)point
3873 {
3874     return _impl->windowResizeMouseLocationIsInVisibleScrollerThumb(NSPointToCGPoint(point));
3875 }
3876
3877 - (void)viewWillMoveToWindow:(NSWindow *)window
3878 {
3879     _impl->viewWillMoveToWindow(window);
3880 }
3881
3882 - (void)viewDidMoveToWindow
3883 {
3884     _impl->viewDidMoveToWindow();
3885 }
3886
3887 - (void)drawRect:(NSRect)rect
3888 {
3889     _impl->drawRect(NSRectToCGRect(rect));
3890 }
3891
3892 - (BOOL)isOpaque
3893 {
3894     return _impl->isOpaque();
3895 }
3896
3897 - (BOOL)mouseDownCanMoveWindow
3898 {
3899     return WebKit::WebViewImpl::mouseDownCanMoveWindow();
3900 }
3901
3902 - (void)viewDidHide
3903 {
3904     _impl->viewDidHide();
3905 }
3906
3907 - (void)viewDidUnhide
3908 {
3909     _impl->viewDidUnhide();
3910 }
3911
3912 - (void)viewDidChangeBackingProperties
3913 {
3914     _impl->viewDidChangeBackingProperties();
3915 }
3916
3917 - (void)_activeSpaceDidChange:(NSNotification *)notification
3918 {
3919     _impl->activeSpaceDidChange();
3920 }
3921
3922 - (id)accessibilityFocusedUIElement
3923 {
3924     return _impl->accessibilityFocusedUIElement();
3925 }
3926
3927 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
3928 - (BOOL)accessibilityIsIgnored
3929 IGNORE_WARNINGS_END
3930 {
3931     return _impl->accessibilityIsIgnored();
3932 }
3933
3934 - (id)accessibilityHitTest:(NSPoint)point
3935 {
3936     return _impl->accessibilityHitTest(NSPointToCGPoint(point));
3937 }
3938
3939 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
3940 - (id)accessibilityAttributeValue:(NSString *)attribute
3941 IGNORE_WARNINGS_END
3942 {
3943     return _impl->accessibilityAttributeValue(attribute);
3944 }
3945
3946 - (NSView *)hitTest:(NSPoint)point
3947 {
3948     if (!_impl)
3949         return [super hitTest:point];
3950     return _impl->hitTest(NSPointToCGPoint(point));
3951 }
3952
3953 - (NSInteger)conversationIdentifier
3954 {
3955     return (NSInteger)self;
3956 }
3957
3958 - (void)quickLookWithEvent:(NSEvent *)event
3959 {
3960     _impl->quickLookWithEvent(event);
3961 }
3962
3963 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
3964 {
3965     return _impl->addTrackingRect(NSRectToCGRect(rect), owner, data, assumeInside);
3966 }
3967
3968 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
3969 {
3970     return _impl->addTrackingRectWithTrackingNum(NSRectToCGRect(rect), owner, data, assumeInside, tag);
3971 }
3972
3973 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
3974 {
3975     CGRect *cgRects = (CGRect *)calloc(1, sizeof(CGRect));
3976     for (int i = 0; i < count; i++)
3977         cgRects[i] = NSRectToCGRect(rects[i]);
3978     _impl->addTrackingRectsWithTrackingNums(cgRects, owner, userDataList, assumeInsideList, trackingNums, count);
3979     free(cgRects);
3980 }
3981
3982 - (void)removeTrackingRect:(NSTrackingRectTag)tag
3983 {
3984     if (!_impl)
3985         return;
3986     _impl->removeTrackingRect(tag);
3987 }
3988
3989 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
3990 {
3991     if (!_impl)
3992         return;
3993     _impl->removeTrackingRects(tags, count);
3994 }
3995
3996 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
3997 {
3998     return _impl->stringForToolTip(tag);
3999 }
4000
4001 - (void)pasteboardChangedOwner:(NSPasteboard *)pasteboard
4002 {
4003     _impl->pasteboardChangedOwner(pasteboard);
4004 }
4005
4006 - (void)pasteboard:(NSPasteboard *)pasteboard provideDataForType:(NSString *)type
4007 {
4008     _impl->provideDataForPasteboard(pasteboard, type);
4009 }
4010
4011 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
4012 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
4013 IGNORE_WARNINGS_END
4014 {
4015     return _impl->namesOfPromisedFilesDroppedAtDestination(dropDestination);
4016 }
4017
4018 - (BOOL)wantsUpdateLayer
4019 {
4020     return WebKit::WebViewImpl::wantsUpdateLayer();
4021 }
4022
4023 - (void)updateLayer
4024 {
4025     _impl->updateLayer();
4026 }
4027
4028 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
4029 {
4030     _impl->setAllowsBackForwardNavigationGestures(allowsBackForwardNavigationGestures);
4031 }
4032
4033 - (BOOL)allowsBackForwardNavigationGestures
4034 {
4035     return _impl->allowsBackForwardNavigationGestures();
4036 }
4037
4038 - (void)smartMagnifyWithEvent:(NSEvent *)event
4039 {
4040     _impl->smartMagnifyWithEvent(event);
4041 }
4042
4043 - (void)setMagnification:(double)magnification centeredAtPoint:(NSPoint)point
4044 {
4045     _impl->setMagnification(magnification, NSPointToCGPoint(point));
4046 }
4047
4048 - (void)setMagnification:(double)magnification
4049 {
4050     _impl->setMagnification(magnification);
4051 }
4052
4053 - (double)magnification
4054 {
4055     return _impl->magnification();
4056 }
4057
4058 - (void)setAllowsMagnification:(BOOL)allowsMagnification
4059 {
4060     _impl->setAllowsMagnification(allowsMagnification);
4061 }
4062
4063 - (BOOL)allowsMagnification
4064 {
4065     return _impl->allowsMagnification();
4066 }
4067
4068 - (void)magnifyWithEvent:(NSEvent *)event
4069 {
4070     _impl->magnifyWithEvent(event);
4071 }
4072
4073 #if ENABLE(MAC_GESTURE_EVENTS)
4074 - (void)rotateWithEvent:(NSEvent *)event
4075 {
4076     _impl->rotateWithEvent(event);
4077 }
4078 #endif
4079
4080 - (WKTextFinderClient *)_ensureTextFinderClient
4081 {
4082     if (!_textFinderClient)
4083         _textFinderClient = adoptNS([[WKTextFinderClient alloc] initWithPage:*_page view:self]);
4084     return _textFinderClient.get();
4085 }
4086
4087 - (void)findMatchesForString:(NSString *)targetString relativeToMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)relativeMatch findOptions:(NSTextFinderAsynchronousDocumentFindOptions)findOptions maxResults:(NSUInteger)maxResults resultCollector:(void (^)(NSArray *matches, BOOL didWrap))resultCollector
4088 {
4089     [[self _ensureTextFinderClient] findMatchesForString:targetString relativeToMatch:relativeMatch findOptions:findOptions maxResults:maxResults resultCollector:resultCollector];
4090 }
4091
4092 - (NSView *)documentContainerView
4093 {
4094     return self;
4095 }
4096
4097 - (void)getSelectedText:(void (^)(NSString *selectedTextString))completionHandler