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