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