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