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