Cleanup: Extraneous platform guarding of -_setUpSQLiteDatabaseTrackerClient
[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_FAMILY)
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_FAMILY)
172
173 #if PLATFORM(IOS_FAMILY)
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     std::optional<BOOL> _resolutionForShareSheetImmediateCompletionForTesting;
267
268 #if PLATFORM(IOS_FAMILY)
269     RetainPtr<_WKRemoteObjectRegistry> _remoteObjectRegistry;
270
271     RetainPtr<WKScrollView> _scrollView;
272     RetainPtr<WKContentView> _contentView;
273
274 #if ENABLE(FULLSCREEN_API)
275     RetainPtr<WKFullScreenWindowController> _fullScreenWindowController;
276 #endif
277
278     BOOL _overridesViewLayoutSize;
279     CGSize _viewLayoutSizeOverride;
280     std::optional<WebCore::FloatSize> _lastSentViewLayoutSize;
281     BOOL _overridesMaximumUnobscuredSize;
282     CGSize _maximumUnobscuredSizeOverride;
283     std::optional<WebCore::FloatSize> _lastSentMaximumUnobscuredSize;
284     CGRect _inputViewBounds;
285     CGFloat _viewportMetaTagWidth;
286     BOOL _viewportMetaTagWidthWasExplicit;
287     BOOL _viewportMetaTagCameFromImageDocument;
288     CGFloat _initialScaleFactor;
289     BOOL _fastClickingIsDisabled;
290
291     BOOL _allowsLinkPreview;
292
293     UIEdgeInsets _obscuredInsets;
294     BOOL _haveSetObscuredInsets;
295     BOOL _isChangingObscuredInsetsInteractively;
296
297     UIEdgeInsets _unobscuredSafeAreaInsets;
298     BOOL _haveSetUnobscuredSafeAreaInsets;
299     BOOL _avoidsUnsafeArea;
300     UIRectEdge _obscuredInsetEdgesAffectedBySafeArea;
301
302     UIInterfaceOrientation _interfaceOrientationOverride;
303     BOOL _overridesInterfaceOrientation;
304     std::optional<int32_t> _lastSentDeviceOrientation;
305
306     BOOL _allowsViewportShrinkToFit;
307
308     BOOL _hasCommittedLoadForMainFrame;
309     BOOL _needsResetViewStateAfterCommitLoadForMainFrame;
310     uint64_t _firstPaintAfterCommitLoadTransactionID;
311     WebKit::DynamicViewportUpdateMode _dynamicViewportUpdateMode;
312     WebKit::DynamicViewportSizeUpdateID _currentDynamicViewportSizeUpdateID;
313     CATransform3D _resizeAnimationTransformAdjustments;
314     CGFloat _animatedResizeOriginalContentWidth;
315     RetainPtr<UIView> _resizeAnimationView;
316     CGFloat _lastAdjustmentForScroller;
317     std::optional<CGRect> _frozenVisibleContentRect;
318     std::optional<CGRect> _frozenUnobscuredContentRect;
319
320     BOOL _commitDidRestoreScrollPosition;
321     std::optional<WebCore::FloatPoint> _scrollOffsetToRestore;
322     WebCore::FloatBoxExtent _obscuredInsetsWhenSaved;
323
324     std::optional<WebCore::FloatPoint> _unobscuredCenterToRestore;
325     std::optional<uint64_t> _firstTransactionIDAfterPageRestore;
326     double _scaleToRestore;
327
328     std::unique_ptr<WebKit::ViewGestureController> _gestureController;
329     BOOL _allowsBackForwardNavigationGestures;
330
331     RetainPtr<UIView <WKWebViewContentProvider>> _customContentView;
332     RetainPtr<UIView> _customContentFixedOverlayView;
333
334     RetainPtr<NSTimer> _enclosingScrollViewScrollTimer;
335     BOOL _didScrollSinceLastTimerFire;
336
337     WebCore::Color _scrollViewBackgroundColor;
338
339     // This value tracks the current adjustment added to the bottom inset due to the keyboard sliding out from the bottom
340     // when computing obscured content insets. This is used when updating the visible content rects where we should not
341     // include this adjustment.
342     CGFloat _totalScrollViewBottomInsetAdjustmentForKeyboard;
343     BOOL _currentlyAdjustingScrollViewInsetsForKeyboard;
344
345     BOOL _delayUpdateVisibleContentRects;
346     BOOL _hadDelayedUpdateVisibleContentRects;
347
348     BOOL _waitingForEndAnimatedResize;
349     BOOL _waitingForCommitAfterAnimatedResize;
350
351     Vector<WTF::Function<void ()>> _callbacksDeferredDuringResize;
352     RetainPtr<NSMutableArray> _stableStatePresentationUpdateCallbacks;
353
354     RetainPtr<WKPasswordView> _passwordView;
355
356     BOOL _hasScheduledVisibleRectUpdate;
357     BOOL _visibleContentRectUpdateScheduledFromScrollViewInStableState;
358     Vector<BlockPtr<void ()>> _visibleContentRectUpdateCallbacks;
359
360     _WKDragInteractionPolicy _dragInteractionPolicy;
361
362     // For release-logging for <rdar://problem/39281269>.
363     MonotonicTime _timeOfRequestForVisibleContentRectUpdate;
364     MonotonicTime _timeOfLastVisibleContentRectUpdate;
365
366     NSUInteger _focusPreservationCount;
367     NSUInteger _activeFocusedStateRetainCount;
368 #endif
369 #if PLATFORM(MAC)
370     std::unique_ptr<WebKit::WebViewImpl> _impl;
371     RetainPtr<WKTextFinderClient> _textFinderClient;
372 #endif
373 }
374
375 - (instancetype)initWithFrame:(CGRect)frame
376 {
377     return [self initWithFrame:frame configuration:adoptNS([[WKWebViewConfiguration alloc] init]).get()];
378 }
379
380 - (BOOL)_isValid
381 {
382     return _page && _page->isValid();
383 }
384
385 #if PLATFORM(IOS_FAMILY)
386 static int32_t deviceOrientationForUIInterfaceOrientation(UIInterfaceOrientation orientation)
387 {
388     switch (orientation) {
389     case UIInterfaceOrientationUnknown:
390     case UIInterfaceOrientationPortrait:
391         return 0;
392     case UIInterfaceOrientationPortraitUpsideDown:
393         return 180;
394     case UIInterfaceOrientationLandscapeLeft:
395         return -90;
396     case UIInterfaceOrientationLandscapeRight:
397         return 90;
398     }
399 }
400
401 static int32_t deviceOrientation()
402 {
403     return deviceOrientationForUIInterfaceOrientation([[UIApplication sharedApplication] statusBarOrientation]);
404 }
405
406 - (BOOL)_isShowingVideoPictureInPicture
407 {
408 #if !HAVE(AVKIT)
409     return false;
410 #else
411     if (!_page || !_page->videoFullscreenManager())
412         return false;
413
414     return _page->videoFullscreenManager()->hasMode(WebCore::HTMLMediaElementEnums::VideoFullscreenModePictureInPicture);
415 #endif
416 }
417
418 - (BOOL)_mayAutomaticallyShowVideoPictureInPicture
419 {
420 #if !HAVE(AVKIT)
421     return false;
422 #else
423     if (!_page || !_page->videoFullscreenManager())
424         return false;
425
426     return _page->videoFullscreenManager()->mayAutomaticallyShowVideoPictureInPicture();
427 #endif
428 }
429
430 static bool shouldAllowPictureInPictureMediaPlayback()
431 {
432     static bool shouldAllowPictureInPictureMediaPlayback = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_9_0;
433     return shouldAllowPictureInPictureMediaPlayback;
434 }
435
436 static bool shouldAllowSettingAnyXHRHeaderFromFileURLs()
437 {
438     static bool shouldAllowSettingAnyXHRHeaderFromFileURLs = (WebCore::IOSApplication::isCardiogram() || WebCore::IOSApplication::isNike()) && !linkedOnOrAfter(WebKit::SDKVersion::FirstThatDisallowsSettingAnyXHRHeaderFromFileURLs);
439     return shouldAllowSettingAnyXHRHeaderFromFileURLs;
440 }
441
442 - (void)_incrementFocusPreservationCount
443 {
444     ++_focusPreservationCount;
445 }
446
447 - (void)_decrementFocusPreservationCount
448 {
449     if (_focusPreservationCount)
450         --_focusPreservationCount;
451 }
452
453 - (void)_resetFocusPreservationCount
454 {
455     _focusPreservationCount = 0;
456 }
457
458 - (BOOL)_isRetainingActiveFocusedState
459 {
460     // Focus preservation count fulfills the same role as active focus state count.
461     // However, unlike active focus state, it may be reset to 0 without impacting the
462     // behavior of -_retainActiveFocusedState, and it's harmless to invoke
463     // -_decrementFocusPreservationCount after resetting the count to 0.
464     return _focusPreservationCount || _activeFocusedStateRetainCount;
465 }
466
467 #endif
468
469 static bool shouldRequireUserGestureToLoadVideo()
470 {
471 #if PLATFORM(IOS_FAMILY)
472     static bool shouldRequireUserGestureToLoadVideo = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
473     return shouldRequireUserGestureToLoadVideo;
474 #else
475     return false;
476 #endif
477 }
478
479 #if PLATFORM(MAC)
480 static uint32_t convertUserInterfaceDirectionPolicy(WKUserInterfaceDirectionPolicy policy)
481 {
482     switch (policy) {
483     case WKUserInterfaceDirectionPolicyContent:
484         return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content);
485     case WKUserInterfaceDirectionPolicySystem:
486         return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::System);
487     }
488     return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content);
489 }
490
491 static uint32_t convertSystemLayoutDirection(NSUserInterfaceLayoutDirection direction)
492 {
493     switch (direction) {
494     case NSUserInterfaceLayoutDirectionLeftToRight:
495         return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::LTR);
496     case NSUserInterfaceLayoutDirectionRightToLeft:
497         return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::RTL);
498     }
499     return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::LTR);
500 }
501
502 #endif // PLATFORM(MAC)
503
504 static void validate(WKWebViewConfiguration *configuration)
505 {
506     if (!configuration.processPool)
507         [NSException raise:NSInvalidArgumentException format:@"configuration.processPool is nil"];
508     
509     if (!configuration.preferences)
510         [NSException raise:NSInvalidArgumentException format:@"configuration.preferences is nil"];
511     
512     if (!configuration.userContentController)
513         [NSException raise:NSInvalidArgumentException format:@"configuration.userContentController is nil"];
514     
515     if (!configuration.websiteDataStore)
516         [NSException raise:NSInvalidArgumentException format:@"configuration.websiteDataStore is nil"];
517     
518     if (!configuration._visitedLinkStore)
519         [NSException raise:NSInvalidArgumentException format:@"configuration._visitedLinkStore is nil"];
520     
521 #if PLATFORM(IOS_FAMILY)
522     if (!configuration._contentProviderRegistry)
523         [NSException raise:NSInvalidArgumentException format:@"configuration._contentProviderRegistry is nil"];
524 #endif
525 }
526
527 - (void)_initializeWithConfiguration:(WKWebViewConfiguration *)configuration
528 {
529     if (!configuration)
530         [NSException raise:NSInvalidArgumentException format:@"Configuration cannot be nil"];
531
532     _configuration = adoptNS([configuration copy]);
533
534     if (WKWebView *relatedWebView = [_configuration _relatedWebView]) {
535         WKProcessPool *processPool = [_configuration processPool];
536         WKProcessPool *relatedWebViewProcessPool = [relatedWebView->_configuration processPool];
537         if (processPool && processPool != relatedWebViewProcessPool)
538             [NSException raise:NSInvalidArgumentException format:@"Related web view %@ has process pool %@ but configuration specifies a different process pool %@", relatedWebView, relatedWebViewProcessPool, configuration.processPool];
539
540         [_configuration setProcessPool:relatedWebViewProcessPool];
541     }
542
543     validate(_configuration.get());
544
545     WebKit::WebProcessPool& processPool = *[_configuration processPool]->_processPool;
546     processPool.setResourceLoadStatisticsEnabled(configuration.websiteDataStore._resourceLoadStatisticsEnabled);
547
548     auto pageConfiguration = [configuration copyPageConfiguration];
549
550     pageConfiguration->setProcessPool(&processPool);
551     pageConfiguration->setPreferences([_configuration preferences]->_preferences.get());
552     if (WKWebView *relatedWebView = [_configuration _relatedWebView])
553         pageConfiguration->setRelatedPage(relatedWebView->_page.get());
554
555     pageConfiguration->setUserContentController([_configuration userContentController]->_userContentControllerProxy.get());
556     pageConfiguration->setVisitedLinkStore([_configuration _visitedLinkStore]->_visitedLinkStore.get());
557     pageConfiguration->setWebsiteDataStore([_configuration websiteDataStore]->_websiteDataStore.get());
558
559 #if PLATFORM(MAC)
560     if (auto pageGroup = WebKit::toImpl([configuration _pageGroup])) {
561         pageConfiguration->setPageGroup(pageGroup);
562         pageConfiguration->setUserContentController(&pageGroup->userContentController());
563     } else
564 #endif
565     {
566         NSString *groupIdentifier = configuration._groupIdentifier;
567         if (groupIdentifier.length)
568             pageConfiguration->setPageGroup(WebKit::WebPageGroup::create(configuration._groupIdentifier).ptr());
569     }
570
571     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::suppressesIncrementalRenderingKey(), WebKit::WebPreferencesStore::Value(!![_configuration suppressesIncrementalRendering]));
572
573     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldRespectImageOrientationKey(), WebKit::WebPreferencesStore::Value(!![_configuration _respectsImageOrientation]));
574     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldPrintBackgroundsKey(), WebKit::WebPreferencesStore::Value(!![_configuration _printsBackgrounds]));
575     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey(), WebKit::WebPreferencesStore::Value([_configuration _incrementalRenderingSuppressionTimeout]));
576     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::javaScriptMarkupEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsJavaScriptMarkup]));
577     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldConvertPositionStyleOnCopyKey(), WebKit::WebPreferencesStore::Value(!![_configuration _convertsPositionStyleOnCopy]));
578     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::httpEquivEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsMetaRefresh]));
579     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowUniversalAccessFromFileURLsKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowUniversalAccessFromFileURLs]));
580     pageConfiguration->setWaitsForPaintAfterViewDidMoveToWindow([_configuration _waitsForPaintAfterViewDidMoveToWindow]);
581     pageConfiguration->setDrawsBackground([_configuration _drawsBackground]);
582     pageConfiguration->setControlledByAutomation([_configuration _isControlledByAutomation]);
583     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::incompleteImageBorderEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _incompleteImageBorderEnabled]));
584     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldDeferAsynchronousScriptsUntilAfterDocumentLoadKey(), WebKit::WebPreferencesStore::Value(!![_configuration _shouldDeferAsynchronousScriptsUntilAfterDocumentLoad]));
585
586 #if PLATFORM(MAC)
587     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::showsURLsInToolTipsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _showsURLsInToolTips]));
588     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::serviceControlsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _serviceControlsEnabled]));
589     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::imageControlsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _imageControlsEnabled]));
590
591     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::userInterfaceDirectionPolicyKey(), WebKit::WebPreferencesStore::Value(convertUserInterfaceDirectionPolicy([_configuration userInterfaceDirectionPolicy])));
592     // We are in the View's initialization routine, so our client hasn't had time to set our user interface direction.
593     // Therefore, according to the docs[1], "this property contains the value reported by the app's userInterfaceLayoutDirection property."
594     // [1] http://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/index.html#//apple_ref/doc/uid/20000014-SW222
595     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::systemLayoutDirectionKey(), WebKit::WebPreferencesStore::Value(convertSystemLayoutDirection(self.userInterfaceLayoutDirection)));
596 #endif
597
598 #if PLATFORM(IOS_FAMILY)
599     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsInlineMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsInlineMediaPlayback]));
600     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsInlineMediaPlaybackAfterFullscreenKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsInlineMediaPlaybackAfterFullscreen]));
601     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::inlineMediaPlaybackRequiresPlaysInlineAttributeKey(), WebKit::WebPreferencesStore::Value(!![_configuration _inlineMediaPlaybackRequiresPlaysInlineAttribute]));
602     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsPictureInPictureMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback()));
603     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::userInterfaceDirectionPolicyKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content)));
604     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::systemLayoutDirectionKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(WebCore::TextDirection::LTR)));
605     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowSettingAnyXHRHeaderFromFileURLsKey(), WebKit::WebPreferencesStore::Value(shouldAllowSettingAnyXHRHeaderFromFileURLs()));
606 #if USE(SYSTEM_PREVIEW)
607     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::systemPreviewEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _systemPreviewEnabled]));
608 #endif
609 #endif
610
611     WKAudiovisualMediaTypes mediaTypesRequiringUserGesture = [_configuration mediaTypesRequiringUserActionForPlayback];
612     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureForVideoPlaybackKey(), WebKit::WebPreferencesStore::Value((mediaTypesRequiringUserGesture & WKAudiovisualMediaTypeVideo) == WKAudiovisualMediaTypeVideo));
613     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureForAudioPlaybackKey(), WebKit::WebPreferencesStore::Value(((mediaTypesRequiringUserGesture & WKAudiovisualMediaTypeAudio) == WKAudiovisualMediaTypeAudio)));
614     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureToLoadVideoKey(), WebKit::WebPreferencesStore::Value(shouldRequireUserGestureToLoadVideo()));
615     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mainContentUserGestureOverrideEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _mainContentUserGestureOverrideEnabled]));
616     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::invisibleAutoplayNotPermittedKey(), WebKit::WebPreferencesStore::Value(!![_configuration _invisibleAutoplayNotPermitted]));
617     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mediaDataLoadsAutomaticallyKey(), WebKit::WebPreferencesStore::Value(!![_configuration _mediaDataLoadsAutomatically]));
618     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::attachmentElementEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _attachmentElementEnabled]));
619
620 #if ENABLE(DATA_DETECTION) && PLATFORM(IOS_FAMILY)
621     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::dataDetectorTypesKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(fromWKDataDetectorTypes([_configuration dataDetectorTypes]))));
622 #endif
623 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
624     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsAirPlayForMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsAirPlayForMediaPlayback]));
625 #endif
626
627 #if ENABLE(APPLE_PAY)
628     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::applePayEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _applePayEnabled]));
629 #endif
630
631     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::needsStorageAccessFromFileURLsQuirkKey(), WebKit::WebPreferencesStore::Value(!![_configuration _needsStorageAccessFromFileURLsQuirk]));
632     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mediaContentTypesRequiringHardwareSupportKey(), WebKit::WebPreferencesStore::Value(String([_configuration _mediaContentTypesRequiringHardwareSupport])));
633     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowMediaContentTypesRequiringHardwareSupportAsFallbackKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowMediaContentTypesRequiringHardwareSupportAsFallback]));
634
635     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::colorFilterEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _colorFilterEnabled]));
636
637 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
638     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::legacyEncryptedMediaAPIEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _legacyEncryptedMediaAPIEnabled]));
639 #endif
640
641 #if PLATFORM(IOS_FAMILY) && ENABLE(SERVICE_WORKER)
642     if (!WTF::processHasEntitlement("com.apple.developer.WebKit.ServiceWorkers"))
643         pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::serviceWorkersEnabledKey(), WebKit::WebPreferencesStore::Value(false));
644 #endif
645
646 #if PLATFORM(IOS_FAMILY)
647     CGRect bounds = self.bounds;
648     _scrollView = adoptNS([[WKScrollView alloc] initWithFrame:bounds]);
649     [_scrollView setInternalDelegate:self];
650     [_scrollView setBouncesZoom:YES];
651
652     _avoidsUnsafeArea = YES;
653     [self _updateScrollViewInsetAdjustmentBehavior];
654
655     [self addSubview:_scrollView.get()];
656
657     static uint32_t programSDKVersion = dyld_get_program_sdk_version();
658     _allowsLinkPreview = programSDKVersion >= firstSDKVersionWithLinkPreviewEnabledByDefault;
659
660     _contentView = adoptNS([[WKContentView alloc] initWithFrame:bounds processPool:processPool configuration:pageConfiguration.copyRef() webView:self]);
661
662     _page = [_contentView page];
663     [self _dispatchSetDeviceOrientation:deviceOrientation()];
664     _page->setDrawsBackground(self.opaque);
665
666     [_contentView layer].anchorPoint = CGPointZero;
667     [_contentView setFrame:bounds];
668     [_scrollView addSubview:_contentView.get()];
669     [_scrollView addSubview:[_contentView unscaledView]];
670     [self _updateScrollViewBackground];
671     _obscuredInsetEdgesAffectedBySafeArea = UIRectEdgeTop | UIRectEdgeLeft | UIRectEdgeRight;
672
673     _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
674     _initialScaleFactor = 1;
675
676     if (NSNumber *enabledValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"WebKitFastClickingDisabled"])
677         _fastClickingIsDisabled = enabledValue.boolValue;
678     else {
679 #if PLATFORM(WATCHOS)
680         _fastClickingIsDisabled = YES;
681 #else
682         _fastClickingIsDisabled = NO;
683 #endif
684     }
685
686     [self _frameOrBoundsChanged];
687
688     NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
689     [center addObserver:self selector:@selector(_keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
690     [center addObserver:self selector:@selector(_keyboardDidChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
691     [center addObserver:self selector:@selector(_keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
692     [center addObserver:self selector:@selector(_keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
693     [center addObserver:self selector:@selector(_keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
694     [center addObserver:self selector:@selector(_windowDidRotate:) name:UIWindowDidRotateNotification object:nil];
695     [center addObserver:self selector:@selector(_contentSizeCategoryDidChange:) name:UIContentSizeCategoryDidChangeNotification object:nil];
696     _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
697
698     [center addObserver:self selector:@selector(_accessibilitySettingsDidChange:) name:UIAccessibilityGrayscaleStatusDidChangeNotification object:nil];
699     [center addObserver:self selector:@selector(_accessibilitySettingsDidChange:) name:UIAccessibilityInvertColorsStatusDidChangeNotification object:nil];
700     [center addObserver:self selector:@selector(_accessibilitySettingsDidChange:) name:UIAccessibilityReduceMotionStatusDidChangeNotification object:nil];
701
702     [[_configuration _contentProviderRegistry] addPage:*_page];
703     _page->setForceAlwaysUserScalable([_configuration ignoresViewportScaleLimits]);
704 #endif
705
706 #if PLATFORM(MAC)
707     _impl = std::make_unique<WebKit::WebViewImpl>(self, self, processPool, pageConfiguration.copyRef());
708     _page = &_impl->page();
709
710     _impl->setAutomaticallyAdjustsContentInsets(true);
711     _impl->setRequiresUserActionForEditingControlsManager([configuration _requiresUserActionForEditingControlsManager]);
712 #endif
713
714 #if ENABLE(ACCESSIBILITY_EVENTS)
715     // Check _AXSWebAccessibilityEventsEnabled here to avoid compiler optimizing
716     // out the null check of kAXSWebAccessibilityEventsEnabledNotification.
717     if (!isNullFunctionPointer(_AXSWebAccessibilityEventsEnabled))
718         CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), accessibilityEventsEnabledChangedCallback, kAXSWebAccessibilityEventsEnabledNotification, 0, CFNotificationSuspensionBehaviorDeliverImmediately);
719     [self _updateAccessibilityEventsEnabled];
720 #endif
721
722     if (NSString *applicationNameForUserAgent = configuration.applicationNameForUserAgent)
723         _page->setApplicationNameForUserAgent(applicationNameForUserAgent);
724
725     _navigationState = std::make_unique<WebKit::NavigationState>(self);
726     _page->setNavigationClient(_navigationState->createNavigationClient());
727
728     _uiDelegate = std::make_unique<WebKit::UIDelegate>(self);
729     _page->setFindClient(std::make_unique<WebKit::FindClient>(self));
730     _page->setDiagnosticLoggingClient(std::make_unique<WebKit::DiagnosticLoggingClient>(self));
731
732     _iconLoadingDelegate = std::make_unique<WebKit::IconLoadingDelegate>(self);
733
734     [self _setUpSQLiteDatabaseTrackerClient];
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_FAMILY)
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_FAMILY)
752 }
753
754 - (void)_setUpSQLiteDatabaseTrackerClient
755 {
756 #if PLATFORM(IOS_FAMILY)
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_FAMILY)
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_FAMILY)
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_FAMILY)
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_FAMILY)
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_FAMILY)
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_FAMILY)
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_FAMILY)
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)_handleKeyUIEvent:(::UIEvent *)event
1527 {
1528     // We only want to handle key events from the hardware keyboard when we are
1529     // first responder and a custom content view is installed; otherwise,
1530     // WKContentView will be the first responder and expects to get key events directly.
1531     if ([self isFirstResponder] && event._hidEvent) {
1532         if ([_customContentView respondsToSelector:@selector(web_handleKeyEvent:)]) {
1533             if ([_customContentView web_handleKeyEvent:event])
1534                 return;
1535         }
1536     }
1537
1538     [super _handleKeyUIEvent:event];
1539 }
1540
1541 - (void)_willInvokeUIScrollViewDelegateCallback
1542 {
1543     _delayUpdateVisibleContentRects = YES;
1544 }
1545
1546 - (void)_didInvokeUIScrollViewDelegateCallback
1547 {
1548     _delayUpdateVisibleContentRects = NO;
1549     if (_hadDelayedUpdateVisibleContentRects) {
1550         _hadDelayedUpdateVisibleContentRects = NO;
1551         [self _scheduleVisibleContentRectUpdate];
1552     }
1553 }
1554
1555 static CGFloat contentZoomScale(WKWebView *webView)
1556 {
1557     CGFloat scale = webView._currentContentView.layer.affineTransform.a;
1558     ASSERT(scale == [webView->_scrollView zoomScale]);
1559     return scale;
1560 }
1561
1562 static WebCore::Color baseScrollViewBackgroundColor(WKWebView *webView)
1563 {
1564     if (webView->_customContentView)
1565         return [webView->_customContentView backgroundColor].CGColor;
1566
1567     if (webView->_gestureController) {
1568         WebCore::Color color = webView->_gestureController->backgroundColorForCurrentSnapshot();
1569         if (color.isValid())
1570             return color;
1571     }
1572
1573     return webView->_page->pageExtendedBackgroundColor();
1574 }
1575
1576 static WebCore::Color scrollViewBackgroundColor(WKWebView *webView)
1577 {
1578     if (!webView.opaque)
1579         return WebCore::Color::transparent;
1580
1581     WebCore::Color color = baseScrollViewBackgroundColor(webView);
1582
1583     if (!color.isValid())
1584         color = WebCore::Color::white;
1585
1586     CGFloat zoomScale = contentZoomScale(webView);
1587     CGFloat minimumZoomScale = [webView->_scrollView minimumZoomScale];
1588     if (zoomScale < minimumZoomScale) {
1589         CGFloat slope = 12;
1590         CGFloat opacity = std::max<CGFloat>(1 - slope * (minimumZoomScale - zoomScale), 0);
1591         color = WebCore::colorWithOverrideAlpha(color.rgb(), opacity);
1592     }
1593
1594     return color;
1595 }
1596
1597 - (void)_updateScrollViewBackground
1598 {
1599     WebCore::Color color = scrollViewBackgroundColor(self);
1600
1601     if (_scrollViewBackgroundColor == color)
1602         return;
1603
1604     _scrollViewBackgroundColor = color;
1605
1606     auto uiBackgroundColor = adoptNS([[UIColor alloc] initWithCGColor:cachedCGColor(color)]);
1607     [_scrollView setBackgroundColor:uiBackgroundColor.get()];
1608
1609     // Update the indicator style based on the lightness/darkness of the background color.
1610     double hue, saturation, lightness;
1611     color.getHSL(hue, saturation, lightness);
1612     if (lightness <= .5 && color.isVisible())
1613         [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleWhite];
1614     else
1615         [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleDefault];
1616 }
1617
1618 - (void)_videoControlsManagerDidChange
1619 {
1620 #if ENABLE(FULLSCREEN_API)
1621     if (_fullScreenWindowController)
1622         [_fullScreenWindowController videoControlsManagerDidChange];
1623 #endif
1624 }
1625
1626 - (CGPoint)_initialContentOffsetForScrollView
1627 {
1628     auto combinedUnobscuredAndScrollViewInset = [self _computedContentInset];
1629     return CGPointMake(-combinedUnobscuredAndScrollViewInset.left, -combinedUnobscuredAndScrollViewInset.top);
1630 }
1631
1632 - (CGPoint)_contentOffsetAdjustedForObscuredInset:(CGPoint)point
1633 {
1634     CGPoint result = point;
1635     UIEdgeInsets contentInset = [self _computedObscuredInset];
1636
1637     result.x -= contentInset.left;
1638     result.y -= contentInset.top;
1639
1640     return result;
1641 }
1642
1643 - (UIRectEdge)_effectiveObscuredInsetEdgesAffectedBySafeArea
1644 {
1645     if (![self usesStandardContentView])
1646         return UIRectEdgeAll;
1647     return _obscuredInsetEdgesAffectedBySafeArea;
1648 }
1649
1650 - (UIEdgeInsets)_computedObscuredInset
1651 {
1652     if (!linkedOnOrAfter(WebKit::SDKVersion::FirstWhereScrollViewContentInsetsAreNotObscuringInsets)) {
1653         // For binary compability with third party apps, treat scroll view content insets as obscuring insets when the app is compiled
1654         // against a WebKit version without the fix in r229641.
1655         return [self _computedContentInset];
1656     }
1657
1658     if (_haveSetObscuredInsets)
1659         return _obscuredInsets;
1660
1661 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1662     if (self._safeAreaShouldAffectObscuredInsets)
1663         return UIEdgeInsetsAdd(UIEdgeInsetsZero, self._scrollViewSystemContentInset, self._effectiveObscuredInsetEdgesAffectedBySafeArea);
1664 #endif
1665
1666     return UIEdgeInsetsZero;
1667 }
1668
1669 - (UIEdgeInsets)_computedContentInset
1670 {
1671     if (_haveSetObscuredInsets)
1672         return _obscuredInsets;
1673
1674     UIEdgeInsets insets = [_scrollView contentInset];
1675
1676 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1677     if (self._safeAreaShouldAffectObscuredInsets)
1678         insets = UIEdgeInsetsAdd(insets, self._scrollViewSystemContentInset, self._effectiveObscuredInsetEdgesAffectedBySafeArea);
1679 #endif
1680
1681     return insets;
1682 }
1683
1684 - (UIEdgeInsets)_computedUnobscuredSafeAreaInset
1685 {
1686     if (_haveSetUnobscuredSafeAreaInsets)
1687         return _unobscuredSafeAreaInsets;
1688
1689 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1690     if (!self._safeAreaShouldAffectObscuredInsets)
1691         return self.safeAreaInsets;
1692 #endif
1693
1694     return UIEdgeInsetsZero;
1695 }
1696
1697 - (void)_processWillSwapOrDidExit
1698 {
1699     // FIXME: Which ones of these need to be done in the process swap case and which ones in the exit case?
1700     [self _hidePasswordView];
1701     [self _cancelAnimatedResize];
1702
1703     _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
1704     _initialScaleFactor = 1;
1705     _hasCommittedLoadForMainFrame = NO;
1706     _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1707     _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
1708     _waitingForEndAnimatedResize = NO;
1709     _waitingForCommitAfterAnimatedResize = NO;
1710     _animatedResizeOriginalContentWidth = 0;
1711     [_contentView setHidden:NO];
1712     _scrollOffsetToRestore = std::nullopt;
1713     _unobscuredCenterToRestore = std::nullopt;
1714     _scrollViewBackgroundColor = WebCore::Color();
1715     _delayUpdateVisibleContentRects = NO;
1716     _hadDelayedUpdateVisibleContentRects = NO;
1717     _currentlyAdjustingScrollViewInsetsForKeyboard = NO;
1718     _lastSentViewLayoutSize = std::nullopt;
1719     _lastSentMaximumUnobscuredSize = std::nullopt;
1720     _lastSentDeviceOrientation = std::nullopt;
1721
1722     _frozenVisibleContentRect = std::nullopt;
1723     _frozenUnobscuredContentRect = std::nullopt;
1724
1725     _firstPaintAfterCommitLoadTransactionID = 0;
1726     _firstTransactionIDAfterPageRestore = std::nullopt;
1727
1728     _hasScheduledVisibleRectUpdate = NO;
1729     _commitDidRestoreScrollPosition = NO;
1730
1731     _avoidsUnsafeArea = YES;
1732 }
1733
1734 - (void)_processWillSwap
1735 {
1736     RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _processWillSwap]", self);
1737     [self _processWillSwapOrDidExit];
1738 }
1739
1740 - (void)_processDidExit
1741 {
1742     RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _processDidExit]", self);
1743
1744     [self _processWillSwapOrDidExit];
1745
1746     [_contentView setFrame:self.bounds];
1747     [_scrollView setBackgroundColor:[UIColor whiteColor]];
1748     [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1749     [_scrollView setZoomScale:1];
1750     
1751 }
1752
1753 - (void)_didRelaunchProcess
1754 {
1755     RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didRelaunchProcess]", self);
1756     _hasScheduledVisibleRectUpdate = NO;
1757     _visibleContentRectUpdateScheduledFromScrollViewInStableState = YES;
1758 }
1759
1760 - (void)_didCommitLoadForMainFrame
1761 {
1762     _firstPaintAfterCommitLoadTransactionID = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1763
1764     _hasCommittedLoadForMainFrame = YES;
1765     _needsResetViewStateAfterCommitLoadForMainFrame = YES;
1766
1767     [_scrollView _stopScrollingAndZoomingAnimations];
1768 }
1769
1770 static CGPoint contentOffsetBoundedInValidRange(UIScrollView *scrollView, CGPoint contentOffset)
1771 {
1772 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1773     UIEdgeInsets contentInsets = scrollView.adjustedContentInset;
1774 #else
1775     UIEdgeInsets contentInsets = scrollView.contentInset;
1776 #endif
1777
1778     CGSize contentSize = scrollView.contentSize;
1779     CGSize scrollViewSize = scrollView.bounds.size;
1780
1781     CGPoint minimumContentOffset = CGPointMake(-contentInsets.left, -contentInsets.top);
1782     CGPoint maximumContentOffset = CGPointMake(std::max(minimumContentOffset.x, contentSize.width + contentInsets.right - scrollViewSize.width), std::max(minimumContentOffset.y, contentSize.height + contentInsets.bottom - scrollViewSize.height));
1783
1784     return CGPointMake(std::max(std::min(contentOffset.x, maximumContentOffset.x), minimumContentOffset.x), std::max(std::min(contentOffset.y, maximumContentOffset.y), minimumContentOffset.y));
1785 }
1786
1787 static void changeContentOffsetBoundedInValidRange(UIScrollView *scrollView, WebCore::FloatPoint contentOffset)
1788 {
1789     scrollView.contentOffset = contentOffsetBoundedInValidRange(scrollView, contentOffset);
1790 }
1791
1792 - (WebCore::FloatRect)visibleRectInViewCoordinates
1793 {
1794     WebCore::FloatRect bounds = self.bounds;
1795     bounds.moveBy([_scrollView contentOffset]);
1796     WebCore::FloatRect contentViewBounds = [_contentView bounds];
1797     bounds.intersect(contentViewBounds);
1798     return bounds;
1799 }
1800
1801 // WebCore stores the page scale factor as float instead of double. When we get a scale from WebCore,
1802 // we need to ignore differences that are within a small rounding error on floats.
1803 static inline bool areEssentiallyEqualAsFloat(float a, float b)
1804 {
1805     return WTF::areEssentiallyEqual(a, b);
1806 }
1807
1808 - (void)_didCommitLayerTreeDuringAnimatedResize:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
1809 {
1810     auto updateID = layerTreeTransaction.dynamicViewportSizeUpdateID();
1811     if (updateID && *updateID == _currentDynamicViewportSizeUpdateID) {
1812         double pageScale = layerTreeTransaction.pageScaleFactor();
1813         WebCore::IntPoint scrollPosition = layerTreeTransaction.scrollPosition();
1814
1815         CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
1816         double currentTargetScale = animatingScaleTarget * [[_contentView layer] transform].m11;
1817         double scale = pageScale / currentTargetScale;
1818         _resizeAnimationTransformAdjustments = CATransform3DMakeScale(scale, scale, 1);
1819
1820         CGPoint newContentOffset = [self _contentOffsetAdjustedForObscuredInset:CGPointMake(scrollPosition.x() * pageScale, scrollPosition.y() * pageScale)];
1821         CGPoint currentContentOffset = [_scrollView contentOffset];
1822
1823         _resizeAnimationTransformAdjustments.m41 = (currentContentOffset.x - newContentOffset.x) / animatingScaleTarget;
1824         _resizeAnimationTransformAdjustments.m42 = (currentContentOffset.y - newContentOffset.y) / animatingScaleTarget;
1825
1826         [_resizeAnimationView layer].sublayerTransform = _resizeAnimationTransformAdjustments;
1827
1828         // If we've already passed endAnimatedResize, immediately complete
1829         // the resize when we have an up-to-date layer tree. Otherwise,
1830         // we will defer completion until endAnimatedResize.
1831         _waitingForCommitAfterAnimatedResize = NO;
1832         if (!_waitingForEndAnimatedResize)
1833             [self _didCompleteAnimatedResize];
1834
1835         return;
1836     }
1837
1838     // If a commit arrives during the live part of a resize but before the
1839     // layer tree takes the current resize into account, it could change the
1840     // WKContentView's size. Update the resizeAnimationView's scale to ensure
1841     // we continue to fill the width of the resize target.
1842
1843     if (_waitingForEndAnimatedResize)
1844         return;
1845
1846     auto newViewLayoutSize = [self activeViewLayoutSize:self.bounds];
1847     CGFloat resizeAnimationViewScale = _animatedResizeOriginalContentWidth / newViewLayoutSize.width();
1848     [[_resizeAnimationView layer] setSublayerTransform:CATransform3DMakeScale(resizeAnimationViewScale, resizeAnimationViewScale, 1)];
1849 }
1850
1851 - (void)_didCommitLayerTree:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
1852 {
1853     if (![self usesStandardContentView])
1854         return;
1855
1856     LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _didCommitLayerTree:] transactionID " <<  layerTreeTransaction.transactionID() << " _dynamicViewportUpdateMode " << (int)_dynamicViewportUpdateMode);
1857
1858     bool needUpdateVisibleContentRects = _page->updateLayoutViewportParameters(layerTreeTransaction);
1859
1860     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing) {
1861         [self _didCommitLayerTreeDuringAnimatedResize:layerTreeTransaction];
1862         return;
1863     }
1864
1865     if (_resizeAnimationView)
1866         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didCommitLayerTree:] - dynamicViewportUpdateMode is NotResizing, but still have a live resizeAnimationView (unpaired begin/endAnimatedResize?)", self);
1867
1868     CGSize newContentSize = roundScrollViewContentSize(*_page, [_contentView frame].size);
1869     [_scrollView _setContentSizePreservingContentOffsetDuringRubberband:newContentSize];
1870
1871     [_scrollView setMinimumZoomScale:layerTreeTransaction.minimumScaleFactor()];
1872     [_scrollView setMaximumZoomScale:layerTreeTransaction.maximumScaleFactor()];
1873     [_scrollView setZoomEnabled:layerTreeTransaction.allowsUserScaling()];
1874     if (!layerTreeTransaction.scaleWasSetByUIProcess() && ![_scrollView isZooming] && ![_scrollView isZoomBouncing] && ![_scrollView _isAnimatingZoom] && [_scrollView zoomScale] != layerTreeTransaction.pageScaleFactor()) {
1875         LOG_WITH_STREAM(VisibleRects, stream << " updating scroll view with pageScaleFactor " << layerTreeTransaction.pageScaleFactor());
1876         [_scrollView setZoomScale:layerTreeTransaction.pageScaleFactor()];
1877     }
1878
1879     _viewportMetaTagWidth = layerTreeTransaction.viewportMetaTagWidth();
1880     _viewportMetaTagWidthWasExplicit = layerTreeTransaction.viewportMetaTagWidthWasExplicit();
1881     _viewportMetaTagCameFromImageDocument = layerTreeTransaction.viewportMetaTagCameFromImageDocument();
1882     _initialScaleFactor = layerTreeTransaction.initialScaleFactor();
1883     if (_page->inStableState() && layerTreeTransaction.isInStableState() && [_stableStatePresentationUpdateCallbacks count]) {
1884         for (dispatch_block_t action in _stableStatePresentationUpdateCallbacks.get())
1885             action();
1886
1887         [_stableStatePresentationUpdateCallbacks removeAllObjects];
1888         _stableStatePresentationUpdateCallbacks = nil;
1889     }
1890
1891     if (![_contentView _mayDisableDoubleTapGesturesDuringSingleTap])
1892         [_contentView _setDoubleTapGesturesEnabled:self._allowsDoubleTapGestures];
1893
1894     [self _updateScrollViewBackground];
1895     [self _setAvoidsUnsafeArea:layerTreeTransaction.avoidsUnsafeArea()];
1896
1897     if (_gestureController)
1898         _gestureController->setRenderTreeSize(layerTreeTransaction.renderTreeSize());
1899
1900     if (_needsResetViewStateAfterCommitLoadForMainFrame && layerTreeTransaction.transactionID() >= _firstPaintAfterCommitLoadTransactionID) {
1901         _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1902         [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1903         if (_observedRenderingProgressEvents & _WKRenderingProgressEventFirstPaint)
1904             _navigationState->didFirstPaint();
1905
1906         needUpdateVisibleContentRects = true;
1907     }
1908
1909     if (_firstTransactionIDAfterPageRestore && layerTreeTransaction.transactionID() >= _firstTransactionIDAfterPageRestore.value()) {
1910         if (_scrollOffsetToRestore) {
1911             WebCore::FloatPoint scaledScrollOffset = _scrollOffsetToRestore.value();
1912             _scrollOffsetToRestore = std::nullopt;
1913
1914             if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1915                 scaledScrollOffset.scale(_scaleToRestore);
1916                 WebCore::FloatPoint contentOffsetInScrollViewCoordinates = scaledScrollOffset - WebCore::FloatSize(_obscuredInsetsWhenSaved.left(), _obscuredInsetsWhenSaved.top());
1917
1918                 changeContentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
1919                 _commitDidRestoreScrollPosition = YES;
1920             }
1921
1922             needUpdateVisibleContentRects = true;
1923         }
1924
1925         if (_unobscuredCenterToRestore) {
1926             WebCore::FloatPoint unobscuredCenterToRestore = _unobscuredCenterToRestore.value();
1927             _unobscuredCenterToRestore = std::nullopt;
1928
1929             if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1930                 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, _obscuredInsets);
1931                 WebCore::FloatSize unobscuredContentSizeAtNewScale = WebCore::FloatSize(unobscuredRect.size) / _scaleToRestore;
1932                 WebCore::FloatPoint topLeftInDocumentCoordinates = unobscuredCenterToRestore - unobscuredContentSizeAtNewScale / 2;
1933
1934                 topLeftInDocumentCoordinates.scale(_scaleToRestore);
1935                 topLeftInDocumentCoordinates.moveBy(WebCore::FloatPoint(-_obscuredInsets.left, -_obscuredInsets.top));
1936
1937                 changeContentOffsetBoundedInValidRange(_scrollView.get(), topLeftInDocumentCoordinates);
1938             }
1939
1940             needUpdateVisibleContentRects = true;
1941         }
1942
1943         if (_gestureController)
1944             _gestureController->didRestoreScrollPosition();
1945
1946         _firstTransactionIDAfterPageRestore = std::nullopt;
1947     }
1948
1949     if (needUpdateVisibleContentRects)
1950         [self _scheduleVisibleContentRectUpdate];
1951
1952     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
1953         scrollPerfData->didCommitLayerTree([self visibleRectInViewCoordinates]);
1954 }
1955
1956 - (void)_layerTreeCommitComplete
1957 {
1958     _commitDidRestoreScrollPosition = NO;
1959 }
1960
1961 - (void)_couldNotRestorePageState
1962 {
1963     // The gestureController may be waiting for the scroll position to be restored
1964     // in order to remove the swipe snapshot. Since the scroll position could not be
1965     // restored, tell the gestureController it was restored so that it no longer waits
1966     // for it.
1967     if (_gestureController)
1968         _gestureController->didRestoreScrollPosition();
1969 }
1970
1971 - (void)_restorePageScrollPosition:(std::optional<WebCore::FloatPoint>)scrollPosition scrollOrigin:(WebCore::FloatPoint)scrollOrigin previousObscuredInset:(WebCore::FloatBoxExtent)obscuredInsets scale:(double)scale
1972 {
1973     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing)
1974         return;
1975
1976     if (![self usesStandardContentView])
1977         return;
1978
1979     _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1980     if (scrollPosition)
1981         _scrollOffsetToRestore = WebCore::ScrollableArea::scrollOffsetFromPosition(WebCore::FloatPoint(scrollPosition.value()), WebCore::toFloatSize(scrollOrigin));
1982     else
1983         _scrollOffsetToRestore = std::nullopt;
1984
1985     _obscuredInsetsWhenSaved = obscuredInsets;
1986     _scaleToRestore = scale;
1987 }
1988
1989 - (void)_restorePageStateToUnobscuredCenter:(std::optional<WebCore::FloatPoint>)center scale:(double)scale
1990 {
1991     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing)
1992         return;
1993
1994     if (![self usesStandardContentView])
1995         return;
1996
1997     _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1998     _unobscuredCenterToRestore = center.value();
1999
2000     _scaleToRestore = scale;
2001 }
2002
2003 - (RefPtr<WebKit::ViewSnapshot>)_takeViewSnapshot
2004 {
2005 #if HAVE(CORE_ANIMATION_RENDER_SERVER)
2006     float deviceScale = WebCore::screenScaleFactor();
2007     WebCore::FloatSize snapshotSize(self.bounds.size);
2008     snapshotSize.scale(deviceScale);
2009
2010     CATransform3D transform = CATransform3DMakeScale(deviceScale, deviceScale, 1);
2011
2012 #if HAVE(IOSURFACE)
2013     WebCore::IOSurface::Format snapshotFormat = WebCore::screenSupportsExtendedColor() ? WebCore::IOSurface::Format::RGB10 : WebCore::IOSurface::Format::RGBA;
2014     auto surface = WebCore::IOSurface::create(WebCore::expandedIntSize(snapshotSize), WebCore::sRGBColorSpaceRef(), snapshotFormat);
2015     if (!surface)
2016         return nullptr;
2017     CARenderServerRenderLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, reinterpret_cast<uint64_t>(self.layer), surface->surface(), 0, 0, &transform);
2018
2019 #if HAVE(IOSURFACE_ACCELERATOR)
2020     WebCore::IOSurface::Format compressedFormat = WebCore::IOSurface::Format::YUV422;
2021     if (WebCore::IOSurface::allowConversionFromFormatToFormat(snapshotFormat, compressedFormat)) {
2022         RefPtr<WebKit::ViewSnapshot> viewSnapshot = WebKit::ViewSnapshot::create(nullptr);
2023         WebCore::IOSurface::convertToFormat(WTFMove(surface), WebCore::IOSurface::Format::YUV422, [viewSnapshot](std::unique_ptr<WebCore::IOSurface> convertedSurface) {
2024             if (convertedSurface)
2025                 viewSnapshot->setSurface(WTFMove(convertedSurface));
2026         });
2027
2028         return viewSnapshot;
2029     }
2030 #endif // HAVE(IOSURFACE_ACCELERATOR)
2031
2032     return WebKit::ViewSnapshot::create(WTFMove(surface));
2033 #else // HAVE(IOSURFACE)
2034     uint32_t slotID = [WebKit::ViewSnapshotStore::snapshottingContext() createImageSlot:snapshotSize hasAlpha:YES];
2035
2036     if (!slotID)
2037         return nullptr;
2038
2039     CARenderServerCaptureLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, (uint64_t)self.layer, slotID, 0, 0, &transform);
2040     WebCore::IntSize imageSize = WebCore::expandedIntSize(WebCore::FloatSize(snapshotSize));
2041     return WebKit::ViewSnapshot::create(slotID, imageSize, (imageSize.area() * 4).unsafeGet());
2042 #endif // HAVE(IOSURFACE)
2043 #else // HAVE(CORE_ANIMATION_RENDER_SERVER)
2044     return nullptr;
2045 #endif
2046 }
2047
2048 - (void)_zoomToPoint:(WebCore::FloatPoint)point atScale:(double)scale animated:(BOOL)animated
2049 {
2050     CFTimeInterval duration = 0;
2051     CGFloat zoomScale = contentZoomScale(self);
2052
2053     if (animated) {
2054         const double maximumZoomDuration = 0.4;
2055         const double minimumZoomDuration = 0.1;
2056         const double zoomDurationFactor = 0.3;
2057
2058         duration = std::min(fabs(log(zoomScale) - log(scale)) * zoomDurationFactor + minimumZoomDuration, maximumZoomDuration);
2059     }
2060
2061     if (scale != zoomScale)
2062         _page->willStartUserTriggeredZooming();
2063
2064     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToPoint:" << point << " scale: " << scale << " duration:" << duration);
2065
2066     [_scrollView _zoomToCenter:point scale:scale duration:duration];
2067 }
2068
2069 - (void)_zoomToRect:(WebCore::FloatRect)targetRect atScale:(double)scale origin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2070 {
2071     // FIXME: Some of this could be shared with _scrollToRect.
2072     const double visibleRectScaleChange = contentZoomScale(self) / scale;
2073     const WebCore::FloatRect visibleRect([self convertRect:self.bounds toView:self._currentContentView]);
2074     const WebCore::FloatRect unobscuredRect([self _contentRectForUserInteraction]);
2075
2076     const WebCore::FloatSize topLeftObscuredInsetAfterZoom((unobscuredRect.minXMinYCorner() - visibleRect.minXMinYCorner()) * visibleRectScaleChange);
2077     const WebCore::FloatSize bottomRightObscuredInsetAfterZoom((visibleRect.maxXMaxYCorner() - unobscuredRect.maxXMaxYCorner()) * visibleRectScaleChange);
2078
2079     const WebCore::FloatSize unobscuredRectSizeAfterZoom(unobscuredRect.size() * visibleRectScaleChange);
2080
2081     // Center to the target rect.
2082     WebCore::FloatPoint unobscuredRectLocationAfterZoom = targetRect.location() - (unobscuredRectSizeAfterZoom - targetRect.size()) * 0.5;
2083
2084     // Center to the tap point instead in case the target rect won't fit in a direction.
2085     if (targetRect.width() > unobscuredRectSizeAfterZoom.width())
2086         unobscuredRectLocationAfterZoom.setX(origin.x() - unobscuredRectSizeAfterZoom.width() / 2);
2087     if (targetRect.height() > unobscuredRectSizeAfterZoom.height())
2088         unobscuredRectLocationAfterZoom.setY(origin.y() - unobscuredRectSizeAfterZoom.height() / 2);
2089
2090     // We have computed where we want the unobscured rect to be. Now adjust for the obscuring insets.
2091     WebCore::FloatRect visibleRectAfterZoom(unobscuredRectLocationAfterZoom, unobscuredRectSizeAfterZoom);
2092     visibleRectAfterZoom.move(-topLeftObscuredInsetAfterZoom);
2093     visibleRectAfterZoom.expand(topLeftObscuredInsetAfterZoom + bottomRightObscuredInsetAfterZoom);
2094
2095     [self _zoomToPoint:visibleRectAfterZoom.center() atScale:scale animated:animated];
2096 }
2097
2098 static WebCore::FloatPoint constrainContentOffset(WebCore::FloatPoint contentOffset, WebCore::FloatSize contentSize, WebCore::FloatSize unobscuredContentSize)
2099 {
2100     WebCore::FloatSize maximumContentOffset = contentSize - unobscuredContentSize;
2101     return contentOffset.constrainedBetween(WebCore::FloatPoint(), WebCore::FloatPoint(maximumContentOffset));
2102 }
2103
2104 - (void)_scrollToContentScrollPosition:(WebCore::FloatPoint)scrollPosition scrollOrigin:(WebCore::IntPoint)scrollOrigin
2105 {
2106     if (_commitDidRestoreScrollPosition || _dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing)
2107         return;
2108
2109     WebCore::FloatPoint contentOffset = WebCore::ScrollableArea::scrollOffsetFromPosition(scrollPosition, toFloatSize(scrollOrigin));
2110
2111     WebCore::FloatPoint scaledOffset = contentOffset;
2112     CGFloat zoomScale = contentZoomScale(self);
2113     scaledOffset.scale(zoomScale);
2114
2115     CGPoint contentOffsetInScrollViewCoordinates = [self _contentOffsetAdjustedForObscuredInset:scaledOffset];
2116     contentOffsetInScrollViewCoordinates = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
2117
2118     [_scrollView _stopScrollingAndZoomingAnimations];
2119
2120     if (!CGPointEqualToPoint(contentOffsetInScrollViewCoordinates, [_scrollView contentOffset]))
2121         [_scrollView setContentOffset:contentOffsetInScrollViewCoordinates];
2122     else {
2123         // If we haven't changed anything, there would not be any VisibleContentRect update sent to the content.
2124         // The WebProcess would keep the invalid contentOffset as its scroll position.
2125         // To synchronize the WebProcess with what is on screen, we send the VisibleContentRect again.
2126         _page->resendLastVisibleContentRects();
2127     }
2128 }
2129
2130 - (BOOL)_scrollToRect:(WebCore::FloatRect)targetRect origin:(WebCore::FloatPoint)origin minimumScrollDistance:(float)minimumScrollDistance
2131 {
2132     WebCore::FloatRect unobscuredContentRect([self _contentRectForUserInteraction]);
2133     WebCore::FloatPoint unobscuredContentOffset = unobscuredContentRect.location();
2134     WebCore::FloatSize contentSize([self._currentContentView bounds].size);
2135
2136     // Center the target rect in the scroll view.
2137     // If the target doesn't fit in the scroll view, center on the gesture location instead.
2138     WebCore::FloatPoint newUnobscuredContentOffset;
2139     if (targetRect.width() <= unobscuredContentRect.width())
2140         newUnobscuredContentOffset.setX(targetRect.x() - (unobscuredContentRect.width() - targetRect.width()) / 2);
2141     else
2142         newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
2143     if (targetRect.height() <= unobscuredContentRect.height())
2144         newUnobscuredContentOffset.setY(targetRect.y() - (unobscuredContentRect.height() - targetRect.height()) / 2);
2145     else
2146         newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
2147     newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
2148
2149     if (unobscuredContentOffset == newUnobscuredContentOffset) {
2150         if (targetRect.width() > unobscuredContentRect.width())
2151             newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
2152         if (targetRect.height() > unobscuredContentRect.height())
2153             newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
2154         newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
2155     }
2156
2157     WebCore::FloatSize scrollViewOffsetDelta = newUnobscuredContentOffset - unobscuredContentOffset;
2158     scrollViewOffsetDelta.scale(contentZoomScale(self));
2159
2160     float scrollDistance = scrollViewOffsetDelta.diagonalLength();
2161     if (scrollDistance < minimumScrollDistance)
2162         return false;
2163
2164     [_contentView willStartZoomOrScroll];
2165
2166     LOG_WITH_STREAM(VisibleRects, stream << "_scrollToRect: scrolling to " << [_scrollView contentOffset] + scrollViewOffsetDelta);
2167
2168     [_scrollView setContentOffset:([_scrollView contentOffset] + scrollViewOffsetDelta) animated:YES];
2169     return true;
2170 }
2171
2172 - (void)_zoomOutWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2173 {
2174     [self _zoomToPoint:origin atScale:[_scrollView minimumZoomScale] animated:animated];
2175 }
2176
2177 - (void)_zoomToInitialScaleWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2178 {
2179     ASSERT(_initialScaleFactor > 0);
2180     [self _zoomToPoint:origin atScale:_initialScaleFactor animated:animated];
2181 }
2182
2183 // focusedElementRect and selectionRect are both in document coordinates.
2184 - (void)_zoomToFocusRect:(WebCore::FloatRect)focusedElementRectInDocumentCoordinates selectionRect:(WebCore::FloatRect)selectionRectInDocumentCoordinates insideFixed:(BOOL)insideFixed
2185     fontSize:(float)fontSize minimumScale:(double)minimumScale maximumScale:(double)maximumScale allowScaling:(BOOL)allowScaling forceScroll:(BOOL)forceScroll
2186 {
2187     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToFocusRect:" << focusedElementRectInDocumentCoordinates << " selectionRect:" << selectionRectInDocumentCoordinates);
2188     UNUSED_PARAM(insideFixed);
2189
2190     const double minimumHeightToShowContentAboveKeyboard = 106;
2191     const CFTimeInterval formControlZoomAnimationDuration = 0.25;
2192     const double caretOffsetFromWindowEdge = 20;
2193
2194     UIWindow *window = [_scrollView window];
2195
2196     // Find the portion of the view that is visible on the screen.
2197     UIViewController *topViewController = [[[_scrollView _viewControllerForAncestor] _rootAncestorViewController] _viewControllerForSupportedInterfaceOrientations];
2198     UIView *fullScreenView = topViewController.view;
2199     if (!fullScreenView)
2200         fullScreenView = window;
2201
2202     CGRect unobscuredScrollViewRectInWebViewCoordinates = UIEdgeInsetsInsetRect([self bounds], _obscuredInsets);
2203     CGRect visibleScrollViewBoundsInWebViewCoordinates = CGRectIntersection(unobscuredScrollViewRectInWebViewCoordinates, [fullScreenView convertRect:[fullScreenView bounds] toView:self]);
2204     CGRect formAssistantFrameInWebViewCoordinates = [window convertRect:_inputViewBounds toView:self];
2205     CGRect intersectionBetweenScrollViewAndFormAssistant = CGRectIntersection(visibleScrollViewBoundsInWebViewCoordinates, formAssistantFrameInWebViewCoordinates);
2206     CGSize visibleSize = visibleScrollViewBoundsInWebViewCoordinates.size;
2207
2208     CGFloat visibleOffsetFromTop = 0;
2209     if (!CGRectIsEmpty(intersectionBetweenScrollViewAndFormAssistant)) {
2210         CGFloat heightVisibleAboveFormAssistant = CGRectGetMinY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
2211         CGFloat heightVisibleBelowFormAssistant = CGRectGetMaxY(visibleScrollViewBoundsInWebViewCoordinates) - CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant);
2212
2213         if (heightVisibleAboveFormAssistant >= minimumHeightToShowContentAboveKeyboard || heightVisibleBelowFormAssistant < heightVisibleAboveFormAssistant)
2214             visibleSize.height = heightVisibleAboveFormAssistant;
2215         else {
2216             visibleSize.height = heightVisibleBelowFormAssistant;
2217             visibleOffsetFromTop = CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
2218         }
2219     }
2220
2221     // Zoom around the element's bounding frame. We use a "standard" size to determine the proper frame.
2222     double currentScale = contentZoomScale(self);
2223     double scale = currentScale;
2224     if (allowScaling) {
2225 #if PLATFORM(WATCHOS)
2226         const CGFloat minimumMarginForZoomingToEntireFocusRectInWebViewCoordinates = 10;
2227         const CGFloat maximumMarginForZoomingToEntireFocusRectInWebViewCoordinates = 35;
2228
2229         CGRect minimumTargetRectInDocumentCoordinates = UIRectInsetEdges(focusedElementRectInDocumentCoordinates, UIRectEdgeAll, -minimumMarginForZoomingToEntireFocusRectInWebViewCoordinates / currentScale);
2230         CGRect maximumTargetRectInDocumentCoordinates = UIRectInsetEdges(focusedElementRectInDocumentCoordinates, UIRectEdgeAll, -maximumMarginForZoomingToEntireFocusRectInWebViewCoordinates / currentScale);
2231
2232         double clampedMaximumTargetScale = clampTo<double>(std::min(visibleSize.width / CGRectGetWidth(minimumTargetRectInDocumentCoordinates), visibleSize.height / CGRectGetHeight(minimumTargetRectInDocumentCoordinates)), minimumScale, maximumScale);
2233         double clampedMinimumTargetScale = clampTo<double>(std::min(visibleSize.width / CGRectGetWidth(maximumTargetRectInDocumentCoordinates), visibleSize.height / CGRectGetHeight(maximumTargetRectInDocumentCoordinates)), minimumScale, maximumScale);
2234         scale = clampTo<double>(currentScale, clampedMinimumTargetScale, clampedMaximumTargetScale);
2235 #else
2236         const double webViewStandardFontSize = 16;
2237         scale = clampTo<double>(webViewStandardFontSize / fontSize, minimumScale, maximumScale);
2238 #endif
2239     }
2240
2241     CGFloat documentWidth = [_contentView bounds].size.width;
2242     scale = CGRound(documentWidth * scale) / documentWidth;
2243
2244     WebCore::FloatRect focusedElementRectInNewScale = focusedElementRectInDocumentCoordinates;
2245     focusedElementRectInNewScale.scale(scale);
2246     focusedElementRectInNewScale.moveBy([_contentView frame].origin);
2247
2248     BOOL selectionRectIsNotNull = !selectionRectInDocumentCoordinates.isZero();
2249     if (!forceScroll) {
2250         CGRect currentlyVisibleRegionInWebViewCoordinates;
2251         currentlyVisibleRegionInWebViewCoordinates.origin = unobscuredScrollViewRectInWebViewCoordinates.origin;
2252         currentlyVisibleRegionInWebViewCoordinates.origin.y += visibleOffsetFromTop;
2253         currentlyVisibleRegionInWebViewCoordinates.size = visibleSize;
2254
2255         // Don't bother scrolling if the entire node is already visible, whether or not we got a selectionRect.
2256         if (CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:focusedElementRectInDocumentCoordinates fromView:_contentView.get()]))
2257             return;
2258
2259         // Don't bother scrolling if we have a valid selectionRect and it is already visible.
2260         if (selectionRectIsNotNull && CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:selectionRectInDocumentCoordinates fromView:_contentView.get()]))
2261             return;
2262     }
2263
2264     // We want to zoom to the left/top corner of the DOM node, with as much spacing on all sides as we
2265     // can get based on the visible area after zooming (workingFrame).  The spacing in either dimension is half the
2266     // difference between the size of the DOM node and the size of the visible frame.
2267     CGFloat horizontalSpaceInWebViewCoordinates = std::max((visibleSize.width - focusedElementRectInNewScale.width()) / 2.0, 0.0);
2268     CGFloat verticalSpaceInWebViewCoordinates = std::max((visibleSize.height - focusedElementRectInNewScale.height()) / 2.0, 0.0);
2269
2270     CGPoint topLeft;
2271     topLeft.x = focusedElementRectInNewScale.x() - horizontalSpaceInWebViewCoordinates;
2272     topLeft.y = focusedElementRectInNewScale.y() - verticalSpaceInWebViewCoordinates - visibleOffsetFromTop;
2273
2274     CGFloat minimumAllowableHorizontalOffsetInWebViewCoordinates = -INFINITY;
2275     CGFloat minimumAllowableVerticalOffsetInWebViewCoordinates = -INFINITY;
2276     if (selectionRectIsNotNull) {
2277         WebCore::FloatRect selectionRectInNewScale = selectionRectInDocumentCoordinates;
2278         selectionRectInNewScale.scale(scale);
2279         selectionRectInNewScale.moveBy([_contentView frame].origin);
2280         minimumAllowableHorizontalOffsetInWebViewCoordinates = CGRectGetMaxX(selectionRectInNewScale) + caretOffsetFromWindowEdge - visibleSize.width;
2281         minimumAllowableVerticalOffsetInWebViewCoordinates = CGRectGetMaxY(selectionRectInNewScale) + caretOffsetFromWindowEdge - visibleSize.height - visibleOffsetFromTop;
2282     }
2283
2284     WebCore::FloatRect documentBoundsInNewScale = [_contentView bounds];
2285     documentBoundsInNewScale.scale(scale);
2286     documentBoundsInNewScale.moveBy([_contentView frame].origin);
2287
2288     // Constrain the left edge in document coordinates so that:
2289     //  - it isn't so small that the scrollVisibleRect isn't visible on the screen
2290     //  - it isn't so great that the document's right edge is less than the right edge of the screen
2291     if (selectionRectIsNotNull && topLeft.x < minimumAllowableHorizontalOffsetInWebViewCoordinates)
2292         topLeft.x = minimumAllowableHorizontalOffsetInWebViewCoordinates;
2293     else {
2294         CGFloat maximumAllowableHorizontalOffset = CGRectGetMaxX(documentBoundsInNewScale) - visibleSize.width;
2295         if (topLeft.x > maximumAllowableHorizontalOffset)
2296             topLeft.x = maximumAllowableHorizontalOffset;
2297     }
2298
2299     // Constrain the top edge in document coordinates so that:
2300     //  - it isn't so small that the scrollVisibleRect isn't visible on the screen
2301     //  - it isn't so great that the document's bottom edge is higher than the top of the form assistant
2302     if (selectionRectIsNotNull && topLeft.y < minimumAllowableVerticalOffsetInWebViewCoordinates)
2303         topLeft.y = minimumAllowableVerticalOffsetInWebViewCoordinates;
2304     else {
2305         CGFloat maximumAllowableVerticalOffset = CGRectGetMaxY(documentBoundsInNewScale) - visibleSize.height;
2306         if (topLeft.y > maximumAllowableVerticalOffset)
2307             topLeft.y = maximumAllowableVerticalOffset;
2308     }
2309
2310     WebCore::FloatPoint newCenter = CGPointMake(topLeft.x + unobscuredScrollViewRectInWebViewCoordinates.size.width / 2.0, topLeft.y + unobscuredScrollViewRectInWebViewCoordinates.size.height / 2.0);
2311
2312     if (scale != currentScale)
2313         _page->willStartUserTriggeredZooming();
2314
2315     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToFocusRect: zooming to " << newCenter << " scale:" << scale);
2316
2317     // The newCenter has been computed in the new scale, but _zoomToCenter expected the center to be in the original scale.
2318     newCenter.scale(1 / scale);
2319     [_scrollView _zoomToCenter:newCenter scale:scale duration:formControlZoomAnimationDuration force:YES];
2320 }
2321
2322 - (CGFloat)_targetContentZoomScaleForRect:(const WebCore::FloatRect&)targetRect currentScale:(double)currentScale fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale
2323 {
2324     WebCore::FloatSize unobscuredContentSize([self _contentRectForUserInteraction].size);
2325     double horizontalScale = unobscuredContentSize.width() * currentScale / targetRect.width();
2326     double verticalScale = unobscuredContentSize.height() * currentScale / targetRect.height();
2327
2328     horizontalScale = std::min(std::max(horizontalScale, minimumScale), maximumScale);
2329     verticalScale = std::min(std::max(verticalScale, minimumScale), maximumScale);
2330
2331     return fitEntireRect ? std::min(horizontalScale, verticalScale) : horizontalScale;
2332 }
2333
2334 - (BOOL)_zoomToRect:(WebCore::FloatRect)targetRect withOrigin:(WebCore::FloatPoint)origin fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale minimumScrollDistance:(float)minimumScrollDistance
2335 {
2336     const float maximumScaleFactorDeltaForPanScroll = 0.02;
2337
2338     double currentScale = contentZoomScale(self);
2339     double targetScale = [self _targetContentZoomScaleForRect:targetRect currentScale:currentScale fitEntireRect:fitEntireRect minimumScale:minimumScale maximumScale:maximumScale];
2340
2341     if (fabs(targetScale - currentScale) < maximumScaleFactorDeltaForPanScroll) {
2342         if ([self _scrollToRect:targetRect origin:origin minimumScrollDistance:minimumScrollDistance])
2343             return true;
2344     } else if (targetScale != currentScale) {
2345         [self _zoomToRect:targetRect atScale:targetScale origin:origin animated:YES];
2346         return true;
2347     }
2348
2349     return false;
2350 }
2351
2352 - (void)didMoveToWindow
2353 {
2354     _page->activityStateDidChange(WebCore::ActivityState::allFlags());
2355 }
2356
2357 - (void)setOpaque:(BOOL)opaque
2358 {
2359     BOOL oldOpaque = self.opaque;
2360
2361     [super setOpaque:opaque];
2362     [_contentView setOpaque:opaque];
2363
2364     if (oldOpaque == opaque)
2365         return;
2366
2367     if (!_page)
2368         return;
2369
2370     _page->setDrawsBackground(opaque);
2371     [self _updateScrollViewBackground];
2372 }
2373
2374 - (void)setBackgroundColor:(UIColor *)backgroundColor
2375 {
2376     [super setBackgroundColor:backgroundColor];
2377     [_contentView setBackgroundColor:backgroundColor];
2378 }
2379
2380 - (BOOL)_allowsDoubleTapGestures
2381 {
2382     if (_fastClickingIsDisabled)
2383         return YES;
2384
2385     // If the page is not user scalable, we don't allow double tap gestures.
2386     if (![_scrollView isZoomEnabled] || [_scrollView minimumZoomScale] >= [_scrollView maximumZoomScale])
2387         return NO;
2388
2389     // If the viewport width was not explicit, we allow double tap gestures.
2390     if (!_viewportMetaTagWidthWasExplicit || _viewportMetaTagCameFromImageDocument)
2391         return YES;
2392
2393     // If the page set a viewport width that wasn't the device width, then it was
2394     // scaled and thus will probably need to zoom.
2395     if (_viewportMetaTagWidth != WebCore::ViewportArguments::ValueDeviceWidth)
2396         return YES;
2397
2398     // At this point, we have a page that asked for width = device-width. However,
2399     // if the content's width and height were large, we might have had to shrink it.
2400     // Since we'll enable double tap zoom whenever we're not at the actual
2401     // initial scale, this simply becomes a test of the current scale against 1.
2402     return !areEssentiallyEqualAsFloat(contentZoomScale(self), 1);
2403 }
2404
2405 #pragma mark - UIScrollViewDelegate
2406
2407 - (BOOL)usesStandardContentView
2408 {
2409     return !_customContentView && !_passwordView;
2410 }
2411
2412 - (CGSize)scrollView:(UIScrollView*)scrollView contentSizeForZoomScale:(CGFloat)scale withProposedSize:(CGSize)proposedSize
2413 {
2414     return roundScrollViewContentSize(*_page, proposedSize);
2415 }
2416
2417 - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
2418 {
2419     ASSERT(_scrollView == scrollView);
2420     return self._currentContentView;
2421 }
2422
2423 - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
2424 {
2425     if (![self usesStandardContentView]) {
2426         if ([_customContentView respondsToSelector:@selector(web_scrollViewWillBeginZooming:withView:)])
2427             [_customContentView web_scrollViewWillBeginZooming:scrollView withView:view];
2428         return;
2429     }
2430
2431     if (scrollView.pinchGestureRecognizer.state == UIGestureRecognizerStateBegan) {
2432         _page->willStartUserTriggeredZooming();
2433         [_contentView scrollViewWillStartPanOrPinchGesture];
2434     }
2435     [_contentView willStartZoomOrScroll];
2436 }
2437
2438 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
2439 {
2440     if (![self usesStandardContentView])
2441         return;
2442
2443     if (scrollView.panGestureRecognizer.state == UIGestureRecognizerStateBegan)
2444         [_contentView scrollViewWillStartPanOrPinchGesture];
2445
2446     [_contentView willStartZoomOrScroll];
2447 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2448     // FIXME: We will want to detect whether snapping will occur before beginning to drag. See WebPageProxy::didCommitLayerTree.
2449     WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2450     ASSERT(scrollView == _scrollView.get());
2451     CGFloat scrollDecelerationFactor = (coordinator && coordinator->shouldSetScrollViewDecelerationRateFast()) ? UIScrollViewDecelerationRateFast : UIScrollViewDecelerationRateNormal;
2452     scrollView.horizontalScrollDecelerationFactor = scrollDecelerationFactor;
2453     scrollView.verticalScrollDecelerationFactor = scrollDecelerationFactor;
2454 #endif
2455 }
2456
2457 - (void)_didFinishScrolling
2458 {
2459     if (![self usesStandardContentView])
2460         return;
2461
2462     [self _scheduleVisibleContentRectUpdate];
2463     [_contentView didFinishScrolling];
2464 }
2465
2466 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
2467 {
2468     // Work around <rdar://problem/16374753> by avoiding deceleration while
2469     // zooming. We'll animate to the right place once the zoom finishes.
2470     if ([scrollView isZooming])
2471         *targetContentOffset = [scrollView contentOffset];
2472 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2473     if (WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy()) {
2474         // FIXME: Here, I'm finding the maximum horizontal/vertical scroll offsets. There's probably a better way to do this.
2475         CGSize maxScrollOffsets = CGSizeMake(scrollView.contentSize.width - scrollView.bounds.size.width, scrollView.contentSize.height - scrollView.bounds.size.height);
2476
2477         UIEdgeInsets obscuredInset;
2478
2479         id<WKUIDelegatePrivate> uiDelegatePrivate = static_cast<id <WKUIDelegatePrivate>>([self UIDelegate]);
2480         if ([uiDelegatePrivate respondsToSelector:@selector(_webView:finalObscuredInsetsForScrollView:withVelocity:targetContentOffset:)])
2481             obscuredInset = [uiDelegatePrivate _webView:self finalObscuredInsetsForScrollView:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
2482         else
2483             obscuredInset = [self _computedObscuredInset];
2484
2485         CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInset);
2486
2487         coordinator->adjustTargetContentOffsetForSnapping(maxScrollOffsets, velocity, unobscuredRect.origin.y, targetContentOffset);
2488     }
2489 #endif
2490 }
2491
2492 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
2493 {
2494     // If we're decelerating, scroll offset will be updated when scrollViewDidFinishDecelerating: is called.
2495     if (!decelerate)
2496         [self _didFinishScrolling];
2497 }
2498
2499 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
2500 {
2501     [self _didFinishScrolling];
2502 }
2503
2504 - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
2505 {
2506     [self _didFinishScrolling];
2507 }
2508
2509 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
2510 {
2511     if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidScroll:)])
2512         [_customContentView web_scrollViewDidScroll:(UIScrollView *)scrollView];
2513
2514     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2515
2516     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
2517         scrollPerfData->didScroll([self visibleRectInViewCoordinates]);
2518 }
2519
2520 - (void)scrollViewDidZoom:(UIScrollView *)scrollView
2521 {
2522     if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidZoom:)])
2523         [_customContentView web_scrollViewDidZoom:scrollView];
2524
2525     [self _updateScrollViewBackground];
2526     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2527 }
2528
2529 - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
2530 {
2531     if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidEndZooming:withView:atScale:)])
2532         [_customContentView web_scrollViewDidEndZooming:scrollView withView:view atScale:scale];
2533
2534     ASSERT(scrollView == _scrollView);
2535     // FIXME: remove when rdar://problem/36065495 is fixed.
2536     // When rotating with two fingers down, UIScrollView can set a bogus content view position.
2537     // "Center" is top left because we set the anchorPoint to 0,0.
2538     [_contentView setCenter:self.bounds.origin];
2539
2540     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2541     [_contentView didZoomToScale:scale];
2542 }
2543
2544 - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
2545 {
2546     [self _didFinishScrolling];
2547 }
2548
2549 - (void)_scrollViewDidInterruptDecelerating:(UIScrollView *)scrollView
2550 {
2551     if (![self usesStandardContentView])
2552         return;
2553
2554     [_contentView didInterruptScrolling];
2555     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2556 }
2557
2558 - (UIView *)_enclosingViewForExposedRectComputation
2559 {
2560     return [self _scroller];
2561 }
2562
2563 - (CGRect)_visibleRectInEnclosingView:(UIView *)enclosingView
2564 {
2565     if (!enclosingView)
2566         return self.bounds;
2567
2568     CGRect exposedRect = [enclosingView convertRect:enclosingView.bounds toView:self];
2569     return CGRectIntersectsRect(exposedRect, self.bounds) ? CGRectIntersection(exposedRect, self.bounds) : CGRectZero;
2570 }
2571
2572 - (CGRect)_visibleContentRect
2573 {
2574     if (_frozenVisibleContentRect)
2575         return _frozenVisibleContentRect.value();
2576
2577     CGRect visibleRectInContentCoordinates = [self convertRect:self.bounds toView:_contentView.get()];
2578
2579     if (UIView *enclosingView = [self _enclosingViewForExposedRectComputation]) {
2580         CGRect viewVisibleRect = [self _visibleRectInEnclosingView:enclosingView];
2581         CGRect viewVisibleContentRect = [self convertRect:viewVisibleRect toView:_contentView.get()];
2582         visibleRectInContentCoordinates = CGRectIntersection(visibleRectInContentCoordinates, viewVisibleContentRect);
2583     }
2584
2585     return visibleRectInContentCoordinates;
2586 }
2587
2588 // Called when some ancestor UIScrollView scrolls.
2589 - (void)_didScroll
2590 {
2591     [self _scheduleVisibleContentRectUpdateAfterScrollInView:[self _scroller]];
2592
2593     const NSTimeInterval ScrollingEndedTimerInterval = 0.032;
2594     if (!_enclosingScrollViewScrollTimer) {
2595         _enclosingScrollViewScrollTimer = adoptNS([[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:ScrollingEndedTimerInterval]
2596             interval:0 target:self selector:@selector(_enclosingScrollerScrollingEnded:) userInfo:nil repeats:YES]);
2597         [[NSRunLoop mainRunLoop] addTimer:_enclosingScrollViewScrollTimer.get() forMode:NSDefaultRunLoopMode];
2598     }
2599     _didScrollSinceLastTimerFire = YES;
2600 }
2601
2602 - (void)_enclosingScrollerScrollingEnded:(NSTimer *)timer
2603 {
2604     if (_didScrollSinceLastTimerFire) {
2605         _didScrollSinceLastTimerFire = NO;
2606         return;
2607     }
2608
2609     [self _scheduleVisibleContentRectUpdate];
2610     [_enclosingScrollViewScrollTimer invalidate];
2611     _enclosingScrollViewScrollTimer = nil;
2612 }
2613
2614 - (UIEdgeInsets)_scrollViewSystemContentInset
2615 {
2616     // It's not safe to access the scroll view's safeAreaInsets or _systemContentInset from
2617     // inside our layoutSubviews implementation, because they aren't updated until afterwards.
2618     // Instead, depend on the fact that the UIScrollView and WKWebView are in the same coordinate
2619     // space, and map the WKWebView's own insets into the scroll view manually.
2620     return UIEdgeInsetsAdd([_scrollView _contentScrollInset], self.safeAreaInsets, [_scrollView _edgesApplyingSafeAreaInsetsToContentInset]);
2621 }
2622
2623 - (WebCore::FloatSize)activeViewLayoutSize:(const CGRect&)bounds
2624 {
2625     if (_overridesViewLayoutSize)
2626         return WebCore::FloatSize(_viewLayoutSizeOverride);
2627
2628 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2629     return WebCore::FloatSize(UIEdgeInsetsInsetRect(CGRectMake(0, 0, bounds.size.width, bounds.size.height), self._scrollViewSystemContentInset).size);
2630 #else
2631     return WebCore::FloatSize { bounds.size };
2632 #endif
2633 }
2634
2635 - (void)_dispatchSetViewLayoutSize:(WebCore::FloatSize)viewLayoutSize
2636 {
2637     if (_lastSentViewLayoutSize && CGSizeEqualToSize(_lastSentViewLayoutSize.value(), viewLayoutSize))
2638         return;
2639
2640     LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _dispatchSetViewLayoutSize:] " << viewLayoutSize << " contentZoomScale " << contentZoomScale(self));
2641     _page->setViewportConfigurationViewLayoutSize(viewLayoutSize, _page->layoutSizeScaleFactor());
2642     _lastSentViewLayoutSize = viewLayoutSize;
2643 }
2644
2645 - (void)_dispatchSetMaximumUnobscuredSize:(WebCore::FloatSize)maximumUnobscuredSize
2646 {
2647     if (_lastSentMaximumUnobscuredSize && CGSizeEqualToSize(_lastSentMaximumUnobscuredSize.value(), maximumUnobscuredSize))
2648         return;
2649
2650     _page->setMaximumUnobscuredSize(maximumUnobscuredSize);
2651     _lastSentMaximumUnobscuredSize = maximumUnobscuredSize;
2652 }
2653
2654 - (void)_dispatchSetDeviceOrientation:(int32_t)deviceOrientation
2655 {
2656     if (_lastSentDeviceOrientation && _lastSentDeviceOrientation.value() == deviceOrientation)
2657         return;
2658
2659     _page->setDeviceOrientation(deviceOrientation);
2660     _lastSentDeviceOrientation = deviceOrientation;
2661 }
2662
2663 - (void)_frameOrBoundsChanged
2664 {
2665     CGRect bounds = self.bounds;
2666     [_scrollView setFrame:bounds];
2667
2668     if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing) {
2669         if (!_overridesViewLayoutSize)
2670             [self _dispatchSetViewLayoutSize:[self activeViewLayoutSize:self.bounds]];
2671         if (!_overridesMaximumUnobscuredSize)
2672             [self _dispatchSetMaximumUnobscuredSize:WebCore::FloatSize(bounds.size)];
2673
2674         BOOL sizeChanged = NO;
2675         if (auto drawingArea = _page->drawingArea())
2676             sizeChanged = drawingArea->setSize(WebCore::IntSize(bounds.size));
2677
2678         if (sizeChanged & [self usesStandardContentView])
2679             [_contentView setSizeChangedSinceLastVisibleContentRectUpdate:YES];
2680     }
2681
2682     [_customContentView web_setMinimumSize:bounds.size];
2683     [self _scheduleVisibleContentRectUpdate];
2684 }
2685
2686 // 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.
2687 - (CGRect)_contentRectForUserInteraction
2688 {
2689     // FIXME: handle split keyboard.
2690     UIEdgeInsets obscuredInsets = _obscuredInsets;
2691     obscuredInsets.bottom = std::max(_obscuredInsets.bottom, _inputViewBounds.size.height);
2692     CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInsets);
2693     return [self convertRect:unobscuredRect toView:self._currentContentView];
2694 }
2695
2696 // Ideally UIScrollView would expose this for us: <rdar://problem/21394567>.
2697 - (BOOL)_scrollViewIsRubberBanding
2698 {
2699     float deviceScaleFactor = _page->deviceScaleFactor();
2700
2701     CGPoint contentOffset = [_scrollView contentOffset];
2702     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
2703     return !pointsEqualInDevicePixels(contentOffset, boundedOffset, deviceScaleFactor);
2704 }
2705
2706 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2707 - (void)safeAreaInsetsDidChange
2708 {
2709     [super safeAreaInsetsDidChange];
2710
2711     [self _scheduleVisibleContentRectUpdate];
2712 }
2713 #endif
2714
2715 - (void)_scheduleVisibleContentRectUpdate
2716 {
2717     // For visible rect updates not associated with a specific UIScrollView, just consider our own scroller.
2718     [self _scheduleVisibleContentRectUpdateAfterScrollInView:_scrollView.get()];
2719 }
2720
2721 - (BOOL)_scrollViewIsInStableState:(UIScrollView *)scrollView
2722 {
2723     BOOL isStableState = !([scrollView isDragging] || [scrollView isDecelerating] || [scrollView isZooming] || [scrollView _isAnimatingZoom] || [scrollView _isScrollingToTop]);
2724
2725     if (isStableState && scrollView == _scrollView.get())
2726         isStableState = !_isChangingObscuredInsetsInteractively;
2727
2728     if (isStableState && scrollView == _scrollView.get())
2729         isStableState = ![self _scrollViewIsRubberBanding];
2730
2731     if (isStableState)
2732         isStableState = !scrollView._isInterruptingDeceleration;
2733
2734     if (NSNumber *stableOverride = self._stableStateOverride)
2735         isStableState = stableOverride.boolValue;
2736
2737     return isStableState;
2738 }
2739
2740 - (void)_addUpdateVisibleContentRectPreCommitHandler
2741 {
2742     auto retainedSelf = retainPtr(self);
2743     [CATransaction addCommitHandler:[retainedSelf] {
2744         WKWebView *webView = retainedSelf.get();
2745         if (![webView _isValid]) {
2746             RELEASE_LOG_IF(webView._page && webView._page->isAlwaysOnLoggingAllowed(), ViewState, "In CATransaction preCommitHandler, WKWebView %p is invalid", webView);
2747             return;
2748         }
2749
2750         @try {
2751             [webView _updateVisibleContentRects];
2752         } @catch (NSException *exception) {
2753             RELEASE_LOG_IF(webView._page && webView._page->isAlwaysOnLoggingAllowed(), ViewState, "In CATransaction preCommitHandler, -[WKWebView %p _updateVisibleContentRects] threw an exception", webView);
2754         }
2755         webView->_hasScheduledVisibleRectUpdate = NO;
2756     } forPhase:kCATransactionPhasePreCommit];
2757 }
2758
2759 - (void)_scheduleVisibleContentRectUpdateAfterScrollInView:(UIScrollView *)scrollView
2760 {
2761     _visibleContentRectUpdateScheduledFromScrollViewInStableState = [self _scrollViewIsInStableState:scrollView];
2762
2763     if (_hasScheduledVisibleRectUpdate) {
2764         auto timeNow = MonotonicTime::now();
2765         if ((timeNow - _timeOfRequestForVisibleContentRectUpdate) > delayBeforeNoVisibleContentsRectsLogging) {
2766             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",
2767                 self, (timeNow - _timeOfRequestForVisibleContentRectUpdate).value(), (timeNow - _timeOfLastVisibleContentRectUpdate).value(), [self _isValid]);
2768         }
2769         return;
2770     }
2771
2772     _hasScheduledVisibleRectUpdate = YES;
2773     _timeOfRequestForVisibleContentRectUpdate = MonotonicTime::now();
2774
2775     CATransactionPhase transactionPhase = [CATransaction currentPhase];
2776     if (transactionPhase == kCATransactionPhaseNull || transactionPhase == kCATransactionPhasePreLayout) {
2777         [self _addUpdateVisibleContentRectPreCommitHandler];
2778         return;
2779     }
2780
2781     dispatch_async(dispatch_get_main_queue(), [retainedSelf = retainPtr(self)] {
2782         WKWebView *webView = retainedSelf.get();
2783         if (![webView _isValid])
2784             return;
2785         [webView _addUpdateVisibleContentRectPreCommitHandler];
2786     });
2787 }
2788
2789 static bool scrollViewCanScroll(UIScrollView *scrollView)
2790 {
2791     if (!scrollView)
2792         return NO;
2793
2794     UIEdgeInsets contentInset = scrollView.contentInset;
2795     CGSize contentSize = scrollView.contentSize;
2796     CGSize boundsSize = scrollView.bounds.size;
2797
2798     return (contentSize.width + contentInset.left + contentInset.right) > boundsSize.width
2799         || (contentSize.height + contentInset.top + contentInset.bottom) > boundsSize.height;
2800 }
2801
2802 - (CGRect)_contentBoundsExtendedForRubberbandingWithScale:(CGFloat)scaleFactor
2803 {
2804     CGPoint contentOffset = [_scrollView contentOffset];
2805     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
2806
2807     CGFloat horiontalRubberbandAmountInContentCoordinates = (contentOffset.x - boundedOffset.x) / scaleFactor;
2808     CGFloat verticalRubberbandAmountInContentCoordinates = (contentOffset.y - boundedOffset.y) / scaleFactor;
2809
2810     CGRect extendedBounds = [_contentView bounds];
2811
2812     if (horiontalRubberbandAmountInContentCoordinates < 0) {
2813         extendedBounds.origin.x += horiontalRubberbandAmountInContentCoordinates;
2814         extendedBounds.size.width -= horiontalRubberbandAmountInContentCoordinates;
2815     } else if (horiontalRubberbandAmountInContentCoordinates > 0)
2816         extendedBounds.size.width += horiontalRubberbandAmountInContentCoordinates;
2817
2818     if (verticalRubberbandAmountInContentCoordinates < 0) {
2819         extendedBounds.origin.y += verticalRubberbandAmountInContentCoordinates;
2820         extendedBounds.size.height -= verticalRubberbandAmountInContentCoordinates;
2821     } else if (verticalRubberbandAmountInContentCoordinates > 0)
2822         extendedBounds.size.height += verticalRubberbandAmountInContentCoordinates;
2823
2824     return extendedBounds;
2825 }
2826
2827 - (void)_updateVisibleContentRects
2828 {
2829     BOOL inStableState = _visibleContentRectUpdateScheduledFromScrollViewInStableState;
2830
2831     if (![self usesStandardContentView]) {
2832         [_passwordView setFrame:self.bounds];
2833         [_customContentView web_computedContentInsetDidChange];
2834         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] - usesStandardContentView is NO, bailing", self);
2835         return;
2836     }
2837
2838     if (_delayUpdateVisibleContentRects) {
2839         _hadDelayedUpdateVisibleContentRects = YES;
2840         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] - _delayUpdateVisibleContentRects is YES, bailing", self);
2841         return;
2842     }
2843
2844     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing
2845         || (_needsResetViewStateAfterCommitLoadForMainFrame && ![_contentView sizeChangedSinceLastVisibleContentRectUpdate])
2846         || [_scrollView isZoomBouncing]
2847         || _currentlyAdjustingScrollViewInsetsForKeyboard) {
2848         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)",
2849             self, _dynamicViewportUpdateMode, _needsResetViewStateAfterCommitLoadForMainFrame, [_contentView sizeChangedSinceLastVisibleContentRectUpdate], [_scrollView isZoomBouncing], _currentlyAdjustingScrollViewInsetsForKeyboard);
2850         return;
2851     }
2852
2853     CGRect visibleRectInContentCoordinates = [self _visibleContentRect];
2854
2855     UIEdgeInsets computedContentInsetUnadjustedForKeyboard = [self _computedObscuredInset];
2856     if (!_haveSetObscuredInsets)
2857         computedContentInsetUnadjustedForKeyboard.bottom -= _totalScrollViewBottomInsetAdjustmentForKeyboard;
2858
2859     CGFloat scaleFactor = contentZoomScale(self);
2860
2861     CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, computedContentInsetUnadjustedForKeyboard);
2862     CGRect unobscuredRectInContentCoordinates = _frozenUnobscuredContentRect ? _frozenUnobscuredContentRect.value() : [self convertRect:unobscuredRect toView:_contentView.get()];
2863     unobscuredRectInContentCoordinates = CGRectIntersection(unobscuredRectInContentCoordinates, [self _contentBoundsExtendedForRubberbandingWithScale:scaleFactor]);
2864
2865 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2866     if (inStableState) {
2867         WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2868         if (coordinator && coordinator->hasActiveSnapPoint()) {
2869             CGPoint currentPoint = [_scrollView contentOffset];
2870             CGPoint activePoint = coordinator->nearestActiveContentInsetAdjustedSnapPoint(unobscuredRect.origin.y, currentPoint);
2871
2872             if (!CGPointEqualToPoint(activePoint, currentPoint)) {
2873                 RetainPtr<WKScrollView> strongScrollView = _scrollView;
2874                 dispatch_async(dispatch_get_main_queue(), [strongScrollView, activePoint] {
2875                     [strongScrollView setContentOffset:activePoint animated:NO];
2876                 });
2877             }
2878         }
2879     }
2880 #endif
2881
2882     [_contentView didUpdateVisibleRect:visibleRectInContentCoordinates
2883         unobscuredRect:unobscuredRectInContentCoordinates
2884         unobscuredRectInScrollViewCoordinates:unobscuredRect
2885         obscuredInsets:_obscuredInsets
2886         unobscuredSafeAreaInsets:[self _computedUnobscuredSafeAreaInset]
2887         inputViewBounds:_inputViewBounds
2888         scale:scaleFactor minimumScale:[_scrollView minimumZoomScale]
2889         inStableState:inStableState
2890         isChangingObscuredInsetsInteractively:_isChangingObscuredInsetsInteractively
2891         enclosedInScrollableAncestorView:scrollViewCanScroll([self _scroller])];
2892
2893     while (!_visibleContentRectUpdateCallbacks.isEmpty()) {
2894         auto callback = _visibleContentRectUpdateCallbacks.takeLast();
2895         callback();
2896     }
2897     
2898     auto timeNow = MonotonicTime::now();
2899     if ((timeNow - _timeOfRequestForVisibleContentRectUpdate) > delayBeforeNoVisibleContentsRectsLogging)
2900         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] finally ran %.2fs after being scheduled", self, (timeNow - _timeOfRequestForVisibleContentRectUpdate).value());
2901
2902     _timeOfLastVisibleContentRectUpdate = timeNow;
2903 }
2904
2905 - (void)_didStartProvisionalLoadForMainFrame
2906 {
2907     if (_gestureController)
2908         _gestureController->didStartProvisionalLoadForMainFrame();
2909 }
2910
2911 static WebCore::FloatSize activeMaximumUnobscuredSize(WKWebView *webView, const CGRect& bounds)
2912 {
2913     return WebCore::FloatSize(webView->_overridesMaximumUnobscuredSize ? webView->_maximumUnobscuredSizeOverride : bounds.size);
2914 }
2915
2916 static int32_t activeOrientation(WKWebView *webView)
2917 {
2918     return webView->_overridesInterfaceOrientation ? deviceOrientationForUIInterfaceOrientation(webView->_interfaceOrientationOverride) : webView->_page->deviceOrientation();
2919 }
2920
2921 - (void)_cancelAnimatedResize
2922 {
2923     LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _cancelAnimatedResize:] " << " _dynamicViewportUpdateMode " << (int)_dynamicViewportUpdateMode);
2924     if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing)
2925         return;
2926
2927     if (!_customContentView) {
2928         if (_resizeAnimationView) {
2929             NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
2930             [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
2931             [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
2932             [_resizeAnimationView removeFromSuperview];
2933             _resizeAnimationView = nil;
2934         }
2935
2936         [_contentView setHidden:NO];
2937         _resizeAnimationTransformAdjustments = CATransform3DIdentity;
2938     }
2939
2940     _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
2941     [self _scheduleVisibleContentRectUpdate];
2942 }
2943
2944 - (void)_didCompleteAnimatedResize
2945 {
2946     if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing)
2947         return;
2948
2949     [_contentView setHidden:NO];
2950
2951     if (!_resizeAnimationView) {
2952         // Paranoia. If _resizeAnimationView is null we'll end up setting a zero scale on the content view.
2953         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didCompleteAnimatedResize:] - _resizeAnimationView is nil", self);
2954         [self _cancelAnimatedResize];
2955         return;
2956     }
2957
2958     NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
2959     [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
2960     [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
2961
2962     CALayer *contentLayer = [_contentView layer];
2963     CGFloat adjustmentScale = _resizeAnimationTransformAdjustments.m11;
2964     contentLayer.sublayerTransform = CATransform3DIdentity;
2965
2966     CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
2967     CATransform3D contentLayerTransform = contentLayer.transform;
2968     CGFloat currentScale = [[_resizeAnimationView layer] transform].m11 * contentLayerTransform.m11;
2969
2970     // We cannot use [UIScrollView setZoomScale:] directly because the UIScrollView delegate would get a callback with
2971     // an invalid contentOffset. The real content offset is only set below.
2972     // Since there is no public API for setting both the zoomScale and the contentOffset, we set the zoomScale manually
2973     // on the zoom layer and then only change the contentOffset.
2974     CGFloat adjustedScale = adjustmentScale * currentScale;
2975     contentLayerTransform.m11 = adjustedScale;
2976     contentLayerTransform.m22 = adjustedScale;
2977     contentLayer.transform = contentLayerTransform;
2978
2979     CGPoint currentScrollOffset = [_scrollView contentOffset];
2980     double horizontalScrollAdjustement = _resizeAnimationTransformAdjustments.m41 * animatingScaleTarget;
2981     double verticalScrollAdjustment = _resizeAnimationTransformAdjustments.m42 * animatingScaleTarget;
2982
2983     [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
2984     [_scrollView setContentOffset:CGPointMake(currentScrollOffset.x - horizontalScrollAdjustement, currentScrollOffset.y - verticalScrollAdjustment)];
2985
2986     [_resizeAnimationView removeFromSuperview];
2987     _resizeAnimationView = nil;
2988     _resizeAnimationTransformAdjustments = CATransform3DIdentity;
2989
2990     _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
2991     [self _scheduleVisibleContentRectUpdate];
2992
2993     CGRect newBounds = self.bounds;
2994     auto newViewLayoutSize = [self activeViewLayoutSize:newBounds];
2995     auto newMaximumUnobscuredSize = activeMaximumUnobscuredSize(self, newBounds);
2996     int32_t newOrientation = activeOrientation(self);
2997
2998     if (!_lastSentViewLayoutSize || newViewLayoutSize != _lastSentViewLayoutSize.value())
2999         [self _dispatchSetViewLayoutSize:newViewLayoutSize];
3000
3001     if (!_lastSentMaximumUnobscuredSize || newMaximumUnobscuredSize != _lastSentMaximumUnobscuredSize.value())
3002         [self _dispatchSetMaximumUnobscuredSize:WebCore::FloatSize(newMaximumUnobscuredSize)];
3003
3004     if (!_lastSentDeviceOrientation || newOrientation != _lastSentDeviceOrientation.value())
3005         [self _dispatchSetDeviceOrientation:newOrientation];
3006
3007     while (!_callbacksDeferredDuringResize.isEmpty())
3008         _callbacksDeferredDuringResize.takeLast()();
3009 }
3010
3011 - (void)_didFinishLoadForMainFrame
3012 {
3013     if (_gestureController)
3014         _gestureController->didFinishLoadForMainFrame();
3015 }
3016
3017 - (void)_didFailLoadForMainFrame
3018 {
3019     if (_gestureController)
3020         _gestureController->didFailLoadForMainFrame();
3021 }
3022
3023 - (void)_didSameDocumentNavigationForMainFrame:(WebKit::SameDocumentNavigationType)navigationType
3024 {
3025     [_customContentView web_didSameDocumentNavigation:toAPI(navigationType)];
3026
3027     if (_gestureController)
3028         _gestureController->didSameDocumentNavigationForMainFrame(navigationType);
3029 }
3030
3031 - (void)_keyboardChangedWithInfo:(NSDictionary *)keyboardInfo adjustScrollView:(BOOL)adjustScrollView
3032 {
3033     NSValue *endFrameValue = [keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
3034     if (!endFrameValue)
3035         return;
3036
3037     // The keyboard rect is always in screen coordinates. In the view services case the window does not
3038     // have the interface orientation rotation transformation; its host does. So, it makes no sense to
3039     // clip the keyboard rect against its screen.
3040     if ([[self window] _isHostedInAnotherProcess])
3041         _inputViewBounds = [self.window convertRect:[endFrameValue CGRectValue] fromWindow:nil];
3042     else
3043         _inputViewBounds = [self.window convertRect:CGRectIntersection([endFrameValue CGRectValue], self.window.screen.bounds) fromWindow:nil];
3044
3045     if (adjustScrollView) {
3046         CGFloat bottomInsetBeforeAdjustment = [_scrollView contentInset].bottom;
3047         SetForScope<BOOL> insetAdjustmentGuard(_currentlyAdjustingScrollViewInsetsForKeyboard, YES);
3048         [_scrollView _adjustForAutomaticKeyboardInfo:keyboardInfo animated:YES lastAdjustment:&_lastAdjustmentForScroller];
3049         CGFloat bottomInsetAfterAdjustment = [_scrollView contentInset].bottom;
3050         if (bottomInsetBeforeAdjustment != bottomInsetAfterAdjustment)
3051             _totalScrollViewBottomInsetAdjustmentForKeyboard += bottomInsetAfterAdjustment - bottomInsetBeforeAdjustment;
3052     }
3053
3054     [self _scheduleVisibleContentRectUpdate];
3055 }
3056
3057 - (BOOL)_shouldUpdateKeyboardWithInfo:(NSDictionary *)keyboardInfo
3058 {
3059     if ([_contentView isAssistingNode])
3060         return YES;
3061
3062     NSNumber *isLocalKeyboard = [keyboardInfo valueForKey:UIKeyboardIsLocalUserInfoKey];
3063     return isLocalKeyboard && !isLocalKeyboard.boolValue;
3064 }
3065
3066 - (void)_keyboardWillChangeFrame:(NSNotification *)notification
3067 {
3068     if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
3069         [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
3070 }
3071
3072 - (void)_keyboardDidChangeFrame:(NSNotification *)notification
3073 {
3074     [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:NO];
3075 }
3076
3077 - (void)_keyboardWillShow:(NSNotification *)notification
3078 {
3079     if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
3080         [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
3081
3082     _page->setIsKeyboardAnimatingIn(true);
3083 }
3084
3085 - (void)_keyboardDidShow:(NSNotification *)notification
3086 {
3087     _page->setIsKeyboardAnimatingIn(false);
3088 }
3089
3090 - (void)_keyboardWillHide:(NSNotification *)notification
3091 {
3092     // Ignore keyboard will hide notifications sent during rotation. They're just there for
3093     // backwards compatibility reasons and processing the will hide notification would
3094     // temporarily screw up the unobscured view area.
3095     if ([[UIPeripheralHost sharedInstance] rotationState])
3096         return;
3097
3098     [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
3099 }
3100
3101 - (void)_windowDidRotate:(NSNotification *)notification
3102 {
3103     if (!_overridesInterfaceOrientation)
3104         [self _dispatchSetDeviceOrientation:deviceOrientation()];
3105 }
3106
3107 - (void)_contentSizeCategoryDidChange:(NSNotification *)notification
3108 {
3109     _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
3110 }
3111
3112 - (NSString *)_contentSizeCategory
3113 {
3114     return [[UIApplication sharedApplication] preferredContentSizeCategory];
3115 }
3116
3117 - (void)_accessibilitySettingsDidChange:(NSNotification *)notification
3118 {
3119     _page->accessibilitySettingsDidChange();
3120 }
3121
3122 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
3123 {
3124     if (_allowsBackForwardNavigationGestures == allowsBackForwardNavigationGestures)
3125         return;
3126
3127     _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
3128
3129     if (allowsBackForwardNavigationGestures && !_gestureController) {
3130         _gestureController = std::make_unique<WebKit::ViewGestureController>(*_page);
3131         _gestureController->installSwipeHandler(self, [self scrollView]);
3132         if (WKWebView *alternateWebView = [_configuration _alternateWebViewForNavigationGestures])
3133             _gestureController->setAlternateBackForwardListSourcePage(alternateWebView->_page.get());
3134     }
3135
3136     if (_gestureController)
3137         _gestureController->setSwipeGestureEnabled(allowsBackForwardNavigationGestures);
3138
3139     _page->setShouldRecordNavigationSnapshots(allowsBackForwardNavigationGestures);
3140 }
3141
3142 - (BOOL)allowsBackForwardNavigationGestures
3143 {
3144     return _allowsBackForwardNavigationGestures;
3145 }
3146
3147 - (BOOL)_isNavigationSwipeGestureRecognizer:(UIGestureRecognizer *)recognizer
3148 {
3149     if (!_gestureController)
3150         return NO;
3151     return _gestureController->isNavigationSwipeGestureRecognizer(recognizer);
3152 }
3153
3154 - (void)_navigationGestureDidBegin
3155 {
3156     // During a back/forward swipe, there's a view interposed between this view and the content view that has
3157     // an offset and animation on it, which results in computing incorrect rectangles. Work around by using
3158     // frozen rects during swipes.
3159     CGRect fullViewRect = self.bounds;
3160     CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, [self _computedObscuredInset]);
3161
3162     _frozenVisibleContentRect = [self convertRect:fullViewRect toView:_contentView.get()];
3163     _frozenUnobscuredContentRect = [self convertRect:unobscuredRect toView:_contentView.get()];
3164
3165     LOG_WITH_STREAM(VisibleRects, stream << "_navigationGestureDidBegin: freezing visibleContentRect " << WebCore::FloatRect(_frozenVisibleContentRect.value()) << " UnobscuredContentRect " << WebCore::FloatRect(_frozenUnobscuredContentRect.value()));
3166 }
3167
3168 - (void)_navigationGestureDidEnd
3169 {
3170     _frozenVisibleContentRect = std::nullopt;
3171     _frozenUnobscuredContentRect = std::nullopt;
3172 }
3173
3174 - (void)_showPasswordViewWithDocumentName:(NSString *)documentName passwordHandler:(void (^)(NSString *))passwordHandler
3175 {
3176     ASSERT(!_passwordView);
3177     _passwordView = adoptNS([[WKPasswordView alloc] initWithFrame:self.bounds documentName:documentName]);
3178     [_passwordView setUserDidEnterPassword:passwordHandler];
3179     [_passwordView showInScrollView:_scrollView.get()];
3180     self._currentContentView.hidden = YES;
3181 }
3182
3183 - (void)_hidePasswordView
3184 {
3185     if (!_passwordView)
3186         return;
3187
3188     self._currentContentView.hidden = NO;
3189     [_passwordView hide];
3190     _passwordView = nil;
3191 }
3192
3193 - (WKPasswordView *)_passwordView
3194 {
3195     return _passwordView.get();
3196 }
3197
3198 - (void)_updateScrollViewInsetAdjustmentBehavior
3199 {
3200 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
3201     if (![_scrollView _contentInsetAdjustmentBehaviorWasExternallyOverridden])
3202         [_scrollView _setContentInsetAdjustmentBehaviorInternal:self._safeAreaShouldAffectObscuredInsets ? UIScrollViewContentInsetAdjustmentAlways : UIScrollViewContentInsetAdjustmentNever];
3203 #endif
3204 }
3205
3206 - (void)_setAvoidsUnsafeArea:(BOOL)avoidsUnsafeArea
3207 {
3208     if (_avoidsUnsafeArea == avoidsUnsafeArea)
3209         return;
3210
3211     _avoidsUnsafeArea = avoidsUnsafeArea;
3212
3213     [self _updateScrollViewInsetAdjustmentBehavior];
3214     [self _scheduleVisibleContentRectUpdate];
3215
3216     id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)[self UIDelegate];
3217     if ([uiDelegate respondsToSelector:@selector(_webView:didChangeSafeAreaShouldAffectObscuredInsets:)])
3218         [uiDelegate _webView:self didChangeSafeAreaShouldAffectObscuredInsets:avoidsUnsafeArea];
3219 }
3220
3221 - (BOOL)_haveSetObscuredInsets
3222 {
3223     return _haveSetObscuredInsets;
3224 }
3225
3226 #endif // PLATFORM(IOS_FAMILY)
3227
3228 #if ENABLE(ACCESSIBILITY_EVENTS)
3229
3230 static void accessibilityEventsEnabledChangedCallback(CFNotificationCenterRef, void* observer, CFStringRef, const void*, CFDictionaryRef)
3231 {
3232     ASSERT(observer);
3233     WKWebView *webview = (__bridge WKWebView *)observer;
3234     [webview _updateAccessibilityEventsEnabled];
3235 }
3236
3237 - (void)_updateAccessibilityEventsEnabled
3238 {
3239     if (!isNullFunctionPointer(_AXSWebAccessibilityEventsEnabled))
3240         _page->updateAccessibilityEventsEnabled(_AXSWebAccessibilityEventsEnabled());
3241 }
3242
3243 #endif
3244
3245 #pragma mark OS X-specific methods
3246
3247 #if PLATFORM(MAC)
3248
3249 - (BOOL)acceptsFirstResponder
3250 {
3251     return _impl->acceptsFirstResponder();
3252 }
3253
3254 - (BOOL)becomeFirstResponder
3255 {
3256     return _impl->becomeFirstResponder();
3257 }
3258
3259 - (BOOL)resignFirstResponder
3260 {
3261     return _impl->resignFirstResponder();
3262 }
3263
3264 - (void)viewWillStartLiveResize
3265 {
3266     _impl->viewWillStartLiveResize();
3267 }
3268
3269 - (void)viewDidEndLiveResize
3270 {
3271     _impl->viewDidEndLiveResize();
3272 }
3273
3274 - (BOOL)isFlipped
3275 {
3276     return YES;
3277 }
3278
3279 - (NSSize)intrinsicContentSize
3280 {
3281     return NSSizeFromCGSize(_impl->intrinsicContentSize());
3282 }
3283
3284 - (void)prepareContentInRect:(NSRect)rect
3285 {
3286     _impl->prepareContentInRect(NSRectToCGRect(rect));
3287 }
3288
3289 - (void)setFrameSize:(NSSize)size
3290 {
3291     [super setFrameSize:size];
3292     _impl->setFrameSize(NSSizeToCGSize(size));
3293 }
3294
3295 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
3296 - (void)renewGState
3297 IGNORE_WARNINGS_END
3298 {
3299     _impl->renewGState();
3300     [super renewGState];
3301 }
3302
3303 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _impl->executeEditCommandForSelector(_cmd); }
3304
3305 WEBCORE_COMMAND(alignCenter)
3306 WEBCORE_COMMAND(alignJustified)
3307 WEBCORE_COMMAND(alignLeft)
3308 WEBCORE_COMMAND(alignRight)
3309 WEBCORE_COMMAND(copy)
3310 WEBCORE_COMMAND(cut)
3311 WEBCORE_COMMAND(delete)
3312 WEBCORE_COMMAND(deleteBackward)
3313 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
3314 WEBCORE_COMMAND(deleteForward)
3315 WEBCORE_COMMAND(deleteToBeginningOfLine)
3316 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
3317 WEBCORE_COMMAND(deleteToEndOfLine)
3318 WEBCORE_COMMAND(deleteToEndOfParagraph)
3319 WEBCORE_COMMAND(deleteToMark)
3320 WEBCORE_COMMAND(deleteWordBackward)
3321 WEBCORE_COMMAND(deleteWordForward)
3322 WEBCORE_COMMAND(ignoreSpelling)
3323 WEBCORE_COMMAND(indent)
3324 WEBCORE_COMMAND(insertBacktab)
3325 WEBCORE_COMMAND(insertLineBreak)
3326 WEBCORE_COMMAND(insertNewline)
3327 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
3328 WEBCORE_COMMAND(insertParagraphSeparator)
3329 WEBCORE_COMMAND(insertTab)
3330 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
3331 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
3332 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
3333 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
3334 WEBCORE_COMMAND(moveBackward)
3335 WEBCORE_COMMAND(moveBackwardAndModifySelection)
3336 WEBCORE_COMMAND(moveDown)
3337 WEBCORE_COMMAND(moveDownAndModifySelection)
3338 WEBCORE_COMMAND(moveForward)
3339 WEBCORE_COMMAND(moveForwardAndModifySelection)
3340 WEBCORE_COMMAND(moveLeft)
3341 WEBCORE_COMMAND(moveLeftAndModifySelection)
3342 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
3343 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
3344 WEBCORE_COMMAND(moveRight)
3345 WEBCORE_COMMAND(moveRightAndModifySelection)
3346 WEBCORE_COMMAND(moveToBeginningOfDocument)
3347 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
3348 WEBCORE_COMMAND(moveToBeginningOfLine)
3349 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
3350 WEBCORE_COMMAND(moveToBeginningOfParagraph)
3351 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
3352 WEBCORE_COMMAND(moveToBeginningOfSentence)
3353 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
3354 WEBCORE_COMMAND(moveToEndOfDocument)
3355 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
3356 WEBCORE_COMMAND(moveToEndOfLine)
3357 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
3358 WEBCORE_COMMAND(moveToEndOfParagraph)
3359 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
3360 WEBCORE_COMMAND(moveToEndOfSentence)
3361 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
3362 WEBCORE_COMMAND(moveToLeftEndOfLine)
3363 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
3364 WEBCORE_COMMAND(moveToRightEndOfLine)
3365 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
3366 WEBCORE_COMMAND(moveUp)
3367 WEBCORE_COMMAND(moveUpAndModifySelection)
3368 WEBCORE_COMMAND(moveWordBackward)
3369 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
3370 WEBCORE_COMMAND(moveWordForward)
3371 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
3372 WEBCORE_COMMAND(moveWordLeft)
3373 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
3374 WEBCORE_COMMAND(moveWordRight)
3375 WEBCORE_COMMAND(moveWordRightAndModifySelection)
3376 WEBCORE_COMMAND(outdent)
3377 WEBCORE_COMMAND(pageDown)
3378 WEBCORE_COMMAND(pageDownAndModifySelection)
3379 WEBCORE_COMMAND(pageUp)
3380 WEBCORE_COMMAND(pageUpAndModifySelection)
3381 WEBCORE_COMMAND(paste)
3382 WEBCORE_COMMAND(pasteAsPlainText)
3383 WEBCORE_COMMAND(scrollPageDown)
3384 WEBCORE_COMMAND(scrollPageUp)
3385 WEBCORE_COMMAND(scrollLineDown)
3386 WEBCORE_COMMAND(scrollLineUp)
3387 WEBCORE_COMMAND(scrollToBeginningOfDocument)
3388 WEBCORE_COMMAND(scrollToEndOfDocument)
3389 WEBCORE_COMMAND(selectAll)
3390 WEBCORE_COMMAND(selectLine)
3391 WEBCORE_COMMAND(selectParagraph)
3392 WEBCORE_COMMAND(selectSentence)
3393 WEBCORE_COMMAND(selectToMark)
3394 WEBCORE_COMMAND(selectWord)
3395 WEBCORE_COMMAND(setMark)
3396 WEBCORE_COMMAND(subscript)
3397 WEBCORE_COMMAND(superscript)
3398 WEBCORE_COMMAND(swapWithMark)
3399 WEBCORE_COMMAND(takeFindStringFromSelection)
3400 WEBCORE_COMMAND(transpose)
3401 WEBCORE_COMMAND(underline)
3402 WEBCORE_COMMAND(unscript)
3403 WEBCORE_COMMAND(yank)
3404 WEBCORE_COMMAND(yankAndSelect)
3405
3406 #undef WEBCORE_COMMAND
3407
3408 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
3409 {
3410     return _impl->writeSelectionToPasteboard(pasteboard, types);
3411 }
3412
3413 - (void)centerSelectionInVisibleArea:(id)sender
3414 {
3415     _impl->centerSelectionInVisibleArea();
3416 }
3417
3418 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
3419 {
3420     return _impl->validRequestorForSendAndReturnTypes(sendType, returnType);
3421 }
3422
3423 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
3424 {
3425     return _impl->readSelectionFromPasteboard(pasteboard);
3426 }
3427
3428 - (void)changeFont:(id)sender
3429 {
3430     _impl->changeFontFromFontManager();
3431 }
3432
3433 - (void)changeColor:(id)sender
3434 {
3435     _impl->changeFontColorFromSender(sender);
3436 }
3437
3438 - (void)changeAttributes:(id)sender
3439 {
3440     _impl->changeFontAttributesFromSender(sender);
3441 }
3442
3443 - (IBAction)startSpeaking:(id)sender
3444 {
3445     _impl->startSpeaking();
3446 }
3447
3448 - (IBAction)stopSpeaking:(id)sender
3449 {
3450     _impl->stopSpeaking(sender);
3451 }
3452
3453 - (IBAction)showGuessPanel:(id)sender
3454 {
3455     _impl->showGuessPanel(sender);
3456 }
3457
3458 - (IBAction)checkSpelling:(id)sender
3459 {
3460     _impl->checkSpelling();
3461 }
3462
3463 - (void)changeSpelling:(id)sender
3464 {
3465     _impl->changeSpelling(sender);
3466 }
3467
3468 - (IBAction)toggleContinuousSpellChecking:(id)sender
3469 {
3470     _impl->toggleContinuousSpellChecking();
3471 }
3472
3473 - (BOOL)isGrammarCheckingEnabled
3474 {
3475     return _impl->isGrammarCheckingEnabled();
3476 }
3477
3478 - (void)setGrammarCheckingEnabled:(BOOL)flag
3479 {
3480     _impl->setGrammarCheckingEnabled(flag);
3481 }
3482
3483 - (IBAction)toggleGrammarChecking:(id)sender
3484 {
3485     _impl->toggleGrammarChecking();
3486 }
3487
3488 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
3489 {
3490     _impl->toggleAutomaticSpellingCorrection();
3491 }
3492
3493 - (void)orderFrontSubstitutionsPanel:(id)sender
3494 {
3495     _impl->orderFrontSubstitutionsPanel(sender);
3496 }
3497
3498 - (IBAction)toggleSmartInsertDelete:(id)sender
3499 {
3500     _impl->toggleSmartInsertDelete();
3501 }
3502
3503 - (BOOL)isAutomaticQuoteSubstitutionEnabled
3504 {
3505     return _impl->isAutomaticQuoteSubstitutionEnabled();
3506 }
3507
3508 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
3509 {
3510     _impl->setAutomaticQuoteSubstitutionEnabled(flag);
3511 }
3512
3513 - (void)toggleAutomaticQuoteSubstitution:(id)sender
3514 {
3515     _impl->toggleAutomaticQuoteSubstitution();
3516 }
3517
3518 - (BOOL)isAutomaticDashSubstitutionEnabled
3519 {
3520     return _impl->isAutomaticDashSubstitutionEnabled();
3521 }
3522
3523 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
3524 {
3525     _impl->setAutomaticDashSubstitutionEnabled(flag);
3526 }
3527
3528 - (void)toggleAutomaticDashSubstitution:(id)sender
3529 {
3530     _impl->toggleAutomaticDashSubstitution();
3531 }
3532
3533 - (BOOL)isAutomaticLinkDetectionEnabled
3534 {
3535     return _impl->isAutomaticLinkDetectionEnabled();
3536 }
3537
3538 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
3539 {
3540     _impl->setAutomaticLinkDetectionEnabled(flag);
3541 }
3542
3543 - (void)toggleAutomaticLinkDetection:(id)sender
3544 {
3545     _impl->toggleAutomaticLinkDetection();
3546 }
3547
3548 - (BOOL)isAutomaticTextReplacementEnabled
3549 {
3550     return _impl->isAutomaticTextReplacementEnabled();
3551 }
3552
3553 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
3554 {
3555     _impl->setAutomaticTextReplacementEnabled(flag);
3556 }
3557
3558 - (void)toggleAutomaticTextReplacement:(id)sender
3559 {
3560     _impl->toggleAutomaticTextReplacement();
3561 }
3562
3563 - (void)uppercaseWord:(id)sender
3564 {
3565     _impl->uppercaseWord();
3566 }
3567
3568 - (void)lowercaseWord:(id)sender
3569 {
3570     _impl->lowercaseWord();
3571 }
3572
3573 - (void)capitalizeWord:(id)sender
3574 {
3575     _impl->capitalizeWord();
3576 }
3577
3578 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
3579 {
3580     return _impl->wantsKeyDownForEvent(event);
3581 }
3582
3583 - (void)scrollWheel:(NSEvent *)event
3584 {
3585     _impl->scrollWheel(event);
3586 }
3587
3588 - (void)swipeWithEvent:(NSEvent *)event
3589 {
3590     _impl->swipeWithEvent(event);
3591 }
3592
3593 - (void)mouseMoved:(NSEvent *)event
3594 {
3595     _impl->mouseMoved(event);
3596 }
3597
3598 - (void)mouseDown:(NSEvent *)event
3599 {
3600     _impl->mouseDown(event);
3601 }
3602
3603 - (void)mouseUp:(NSEvent *)event
3604 {
3605     _impl->mouseUp(event);
3606 }
3607
3608 - (void)mouseDragged:(NSEvent *)event
3609 {
3610     _impl->mouseDragged(event);
3611 }
3612
3613 - (void)mouseEntered:(NSEvent *)event
3614 {
3615     _impl->mouseEntered(event);
3616 }
3617
3618 - (void)mouseExited:(NSEvent *)event
3619 {
3620     _impl->mouseExited(event);
3621 }
3622
3623 - (void)otherMouseDown:(NSEvent *)event
3624 {
3625     _impl->otherMouseDown(event);
3626 }
3627
3628 - (void)otherMouseDragged:(NSEvent *)event
3629 {
3630     _impl->otherMouseDragged(event);
3631 }
3632
3633 - (void)otherMouseUp:(NSEvent *)event
3634 {
3635     _impl->otherMouseUp(event);
3636 }
3637
3638 - (void)rightMouseDown:(NSEvent *)event
3639 {
3640     _impl->rightMouseDown(event);
3641 }
3642
3643 - (void)rightMouseDragged:(NSEvent *)event
3644 {
3645     _impl->rightMouseDragged(event);
3646 }
3647
3648 - (void)rightMouseUp:(NSEvent *)event
3649 {
3650     _impl->rightMouseUp(event);
3651 }
3652
3653 - (void)pressureChangeWithEvent:(NSEvent *)event
3654 {
3655     _impl->pressureChangeWithEvent(event);
3656 }
3657
3658 - (BOOL)acceptsFirstMouse:(NSEvent *)event
3659 {
3660     return _impl->acceptsFirstMouse(event);
3661 }
3662
3663 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
3664 {
3665     return _impl->shouldDelayWindowOrderingForEvent(event);
3666 }
3667
3668 - (void)doCommandBySelector:(SEL)selector
3669 {
3670     _impl->doCommandBySelector(selector);
3671 }
3672
3673 - (void)insertText:(id)string
3674 {
3675     _impl->insertText(string);
3676 }
3677
3678 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
3679 {
3680     _impl->insertText(string, replacementRange);
3681 }
3682
3683 - (NSTextInputContext *)inputContext
3684 {
3685     if (!_impl)
3686         return nil;
3687     return _impl->inputContext();
3688 }
3689
3690 - (BOOL)performKeyEquivalent:(NSEvent *)event
3691 {
3692     return _impl->performKeyEquivalent(event);
3693 }
3694
3695 - (void)keyUp:(NSEvent *)theEvent
3696 {
3697     _impl->keyUp(theEvent);
3698 }
3699
3700 - (void)keyDown:(NSEvent *)theEvent
3701 {
3702     _impl->keyDown(theEvent);
3703 }
3704
3705 - (void)flagsChanged:(NSEvent *)theEvent
3706 {
3707     _impl->flagsChanged(theEvent);
3708 }
3709
3710 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelectedRange replacementRange:(NSRange)replacementRange
3711 {
3712     _impl->setMarkedText(string, newSelectedRange, replacementRange);
3713 }
3714
3715 - (void)unmarkText
3716 {
3717     _impl->unmarkText();
3718 }
3719
3720 - (NSRange)selectedRange
3721 {
3722     return _impl->selectedRange();
3723 }
3724
3725 - (BOOL)hasMarkedText
3726 {
3727     return _impl->hasMarkedText();
3728 }
3729
3730 - (NSRange)markedRange
3731 {
3732     return _impl->markedRange();
3733 }
3734
3735 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange
3736 {
3737     return _impl->attributedSubstringForProposedRange(nsRange, actualRange);
3738 }
3739
3740 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
3741 {
3742     return _impl->characterIndexForPoint(thePoint);
3743 }
3744
3745 - (void)typingAttributesWithCompletionHandler:(void(^)(NSDictionary<NSString *, id> *))completion
3746 {
3747     _impl->typingAttributesWithCompletionHandler(completion);
3748 }
3749
3750 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
3751 {
3752     return _impl->firstRectForCharacterRange(theRange, actualRange);
3753 }
3754
3755 - (void)selectedRangeWithCompletionHandler:(void(^)(NSRange selectedRange))completionHandlerPtr
3756 {
3757     _impl->selectedRangeWithCompletionHandler(completionHandlerPtr);
3758 }
3759
3760 - (void)markedRangeWithCompletionHandler:(void(^)(NSRange markedRange))completionHandlerPtr
3761 {
3762     _impl->markedRangeWithCompletionHandler(completionHandlerPtr);
3763 }
3764
3765 - (void)hasMarkedTextWithCompletionHandler:(void(^)(BOOL hasMarkedText))completionHandlerPtr
3766 {
3767     _impl->hasMarkedTextWithCompletionHandler(completionHandlerPtr);
3768 }
3769
3770 - (void)attributedSubstringForProposedRange:(NSRange)nsRange completionHandler:(void(^)(NSAttributedString *attrString, NSRange actualRange))completionHandlerPtr
3771 {
3772     _impl->attributedSubstringForProposedRange(nsRange, completionHandlerPtr);
3773 }
3774
3775 - (void)firstRectForCharacterRange:(NSRange)theRange completionHandler:(void(^)(NSRect firstRect, NSRange actualRange))completionHandlerPtr
3776 {
3777     _impl->firstRectForCharacterRange(theRange, completionHandlerPtr);
3778 }
3779
3780 - (void)characterIndexForPoint:(NSPoint)thePoint completionHandler:(void(^)(NSUInteger))completionHandlerPtr
3781 {
3782     _impl->characterIndexForPoint(thePoint, completionHandlerPtr);
3783 }
3784
3785 - (NSArray *)validAttributesForMarkedText
3786 {
3787     return _impl->validAttributesForMarkedText();
3788 }
3789
3790 #if ENABLE(DRAG_SUPPORT)
3791 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
3792 - (void)draggedImage:(NSImage *)image endedAt:(NSPoint)endPoint operation:(NSDragOperation)operation
3793 IGNORE_WARNINGS_END
3794 {
3795     _impl->draggedImage(image, NSPointToCGPoint(endPoint), operation);
3796 }
3797
3798 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
3799 {
3800     return _impl->draggingEntered(draggingInfo);
3801 }
3802
3803 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
3804 {
3805     return _impl->draggingUpdated(draggingInfo);
3806 }
3807
3808 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
3809 {
3810     _impl->draggingExited(draggingInfo);
3811 }
3812
3813 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
3814 {
3815     return _impl->prepareForDragOperation(draggingInfo);
3816 }
3817
3818 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
3819 {
3820     return _impl->performDragOperation(draggingInfo);
3821 }
3822
3823 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
3824 {
3825     return _impl->hitTestForDragTypes(NSPointToCGPoint(*point), types);
3826 }
3827 #endif // ENABLE(DRAG_SUPPORT)
3828
3829 - (BOOL)_windowResizeMouseLocationIsInVisibleScrollerThumb:(NSPoint)point
3830 {
3831     return _impl->windowResizeMouseLocationIsInVisibleScrollerThumb(NSPointToCGPoint(point));
3832 }
3833
3834 - (void)viewWillMoveToWindow:(NSWindow *)window
3835 {
3836     _impl->viewWillMoveToWindow(window);
3837 }
3838
3839 - (void)viewDidMoveToWindow
3840 {
3841     _impl->viewDidMoveToWindow();
3842 }
3843
3844 - (void)drawRect:(NSRect)rect
3845 {
3846     _impl->drawRect(NSRectToCGRect(rect));
3847 }
3848
3849 - (BOOL)isOpaque
3850 {
3851     return _impl->isOpaque();
3852 }
3853
3854 - (BOOL)mouseDownCanMoveWindow
3855 {
3856     return WebKit::WebViewImpl::mouseDownCanMoveWindow();
3857 }
3858
3859 - (void)viewDidHide
3860 {
3861     _impl->viewDidHide();
3862 }
3863
3864 - (void)viewDidUnhide
3865 {
3866     _impl->viewDidUnhide();
3867 }
3868
3869 - (void)viewDidChangeBackingProperties
3870 {
3871     _impl->viewDidChangeBackingProperties();
3872 }
3873
3874 - (void)_activeSpaceDidChange:(NSNotification *)notification
3875 {
3876     _impl->activeSpaceDidChange();
3877 }
3878
3879 - (id)accessibilityFocusedUIElement
3880 {
3881     return _impl->accessibilityFocusedUIElement();
3882 }
3883
3884 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
3885 - (BOOL)accessibilityIsIgnored
3886 IGNORE_WARNINGS_END
3887 {
3888     return _impl->accessibilityIsIgnored();
3889 }
3890
3891 - (id)accessibilityHitTest:(NSPoint)point
3892 {
3893     return _impl->accessibilityHitTest(NSPointToCGPoint(point));
3894 }
3895
3896 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
3897 - (id)accessibilityAttributeValue:(NSString *)attribute
3898 IGNORE_WARNINGS_END
3899 {
3900     return _impl->accessibilityAttributeValue(attribute);
3901 }
3902
3903 - (NSView *)hitTest:(NSPoint)point
3904 {
3905     if (!_impl)
3906         return [super hitTest:point];
3907     return _impl->hitTest(NSPointToCGPoint(point));
3908 }
3909
3910 - (NSInteger)conversationIdentifier
3911 {
3912     return (NSInteger)self;
3913 }
3914
3915 - (void)quickLookWithEvent:(NSEvent *)event
3916 {
3917     _impl->quickLookWithEvent(event);
3918 }
3919
3920 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
3921 {
3922     return _impl->addTrackingRect(NSRectToCGRect(rect), owner, data, assumeInside);
3923 }
3924
3925 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
3926 {
3927     return _impl->addTrackingRectWithTrackingNum(NSRectToCGRect(rect), owner, data, assumeInside, tag);
3928 }
3929
3930 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
3931 {
3932     CGRect *cgRects = (CGRect *)calloc(1, sizeof(CGRect));
3933     for (int i = 0; i < count; i++)
3934         cgRects[i] = NSRectToCGRect(rects[i]);
3935     _impl->addTrackingRectsWithTrackingNums(cgRects, owner, userDataList, assumeInsideList, trackingNums, count);
3936     free(cgRects);
3937 }
3938
3939 - (void)removeTrackingRect:(NSTrackingRectTag)tag
3940 {
3941     if (!_impl)
3942         return;
3943     _impl->removeTrackingRect(tag);
3944 }
3945
3946 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
3947 {
3948     if (!_impl)
3949         return;
3950     _impl->removeTrackingRects(tags, count);
3951 }
3952
3953 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
3954 {
3955     return _impl->stringForToolTip(tag);
3956 }
3957
3958 - (void)pasteboardChangedOwner:(NSPasteboard *)pasteboard
3959 {
3960     _impl->pasteboardChangedOwner(pasteboard);
3961 }
3962
3963 - (void)pasteboard:(NSPasteboard *)pasteboard provideDataForType:(NSString *)type
3964 {
3965     _impl->provideDataForPasteboard(pasteboard, type);
3966 }
3967
3968 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
3969 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
3970 IGNORE_WARNINGS_END
3971 {
3972     return _impl->namesOfPromisedFilesDroppedAtDestination(dropDestination);
3973 }
3974
3975 - (BOOL)wantsUpdateLayer
3976 {
3977     return WebKit::WebViewImpl::wantsUpdateLayer();
3978 }
3979
3980 - (void)updateLayer
3981 {
3982     _impl->updateLayer();
3983 }
3984
3985 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
3986 {
3987     _impl->setAllowsBackForwardNavigationGestures(allowsBackForwardNavigationGestures);
3988 }
3989
3990 - (BOOL)allowsBackForwardNavigationGestures
3991 {
3992     return _impl->allowsBackForwardNavigationGestures();
3993 }
3994
3995 - (void)smartMagnifyWithEvent:(NSEvent *)event
3996 {
3997     _impl->smartMagnifyWithEvent(event);
3998 }
3999
4000 - (void)setMagnification:(double)magnification centeredAtPoint:(NSPoint)point
4001 {
4002     _impl->setMagnification(magnification, NSPointToCGPoint(point));
4003 }
4004
4005 - (void)setMagnification:(double)magnification
4006 {
4007     _impl->setMagnification(magnification);
4008 }
4009
4010 - (double)magnification
4011 {
4012     return _impl->magnification();
4013 }
4014
4015 - (void)setAllowsMagnification:(BOOL)allowsMagnification
4016 {
4017     _impl->setAllowsMagnification(allowsMagnification);
4018 }
4019
4020 - (BOOL)allowsMagnification
4021 {
4022     return _impl->allowsMagnification();
4023 }
4024
4025 - (void)magnifyWithEvent:(NSEvent *)event
4026 {
4027     _impl->magnifyWithEvent(event);
4028 }
4029
4030 #if ENABLE(MAC_GESTURE_EVENTS)
4031 - (void)rotateWithEvent:(NSEvent *)event
4032 {
4033     _impl->rotateWithEvent(event);
4034 }
4035 #endif
4036
4037 - (WKTextFinderClient *)_ensureTextFinderClient
4038 {
4039     if (!_textFinderClient)
4040         _textFinderClient = adoptNS([[WKTextFinderClient alloc] initWithPage:*_page view:self]);
4041     return _textFinderClient.get();
4042 }
4043
4044 - (void)findMatchesForString:(NSString *)targetString relativeToMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)relativeMatch findOptions:(NSTextFinderAsynchronousDocumentFindOptions)findOptions maxResults:(NSUInteger)maxResults resultCollector:(void (^)(NSArray *matches, BOOL didWrap))resultCollector
4045 {
4046     [[self _ensureTextFinderClient] findMatchesForString:targetString relativeToMatch:relativeMatch findOptions:findOptions maxResults:maxResults resultCollector:resultCollector];
4047 }
4048
4049 - (NSView *)documentContainerView
4050 {
4051     return self;
4052 }
4053
4054 - (void)getSelectedText:(void (^)(NSString *selectedTextString))completionHandler
4055 {
4056     [[self _ensureTextFinderClient] getSelectedText:completionHandler];
4057 }
4058
4059 - (void)selectFindMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)findMatch completionHandler:(void (^)(void))completionHandler
4060 {
4061     [[self _ensureTextFinderClient] selectFindMatch:findMatch completionHandler:completionHandler];
4062 }
4063
4064 - (NSTextInputContext *)_web_superInputContext
4065 {
4066     return [super inputContext];
4067 }
4068
4069 - (void)_web_superQuickLookWithEvent:(NSEvent *)event
4070 {
4071     [super quickLookWithEvent:event];
4072 }
4073
4074 - (void)_web_superSwipeWithEvent:(NSEvent *)event
4075 {
4076     [super swipeWithEvent:event];
4077 }
4078
4079 - (void)_web_superMagnifyWithEvent:(NSEvent *)event
4080 {
4081     [super magnifyWithEvent:event];
4082 }
4083
4084 - (void)_web_superSmartMagnifyWithEvent:(NSEvent *)event
4085 {
4086     [super smartMagnifyWithEvent:event];
4087 }
4088
4089 - (void)_web_superRemoveTrackingRect:(NSTrackingRectTag)tag
4090 {
4091     [super removeTrackingRect:tag];
4092 }
4093
4094 - (id)_web_superAccessibilityAttributeValue:(NSString *)attribute
4095 {
4096     ALLOW_DEPRECATED_DECLARATIONS_BEGIN
4097     return [super accessibilityAttributeValue:attribute];
4098     ALLOW_DEPRECATED_DECLARATIONS_END
4099 }
4100
4101 - (void)_web_superDoCommandBySelector:(SEL)selector
4102 {
4103     [super doCommandBySelector:selector];
4104 }
4105
4106 - (BOOL)_web_superPerformKeyEquivalent:(NSEvent *)event
4107 {
41