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