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