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