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