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