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