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