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