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