WKWebView Find-in-page API.
[WebKit-https.git] / Source / WebKit / UIProcess / API / Cocoa / WKWebView.mm
1 /*
2  * Copyright (C) 2014-2019 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 #import "APIFormClient.h"
30 #import "APIPageConfiguration.h"
31 #import "APISerializedScriptValue.h"
32 #import "AttributedString.h"
33 #import "CompletionHandlerCallChecker.h"
34 #import "DiagnosticLoggingClient.h"
35 #import "DynamicViewportSizeUpdate.h"
36 #import "FindClient.h"
37 #import "FullscreenClient.h"
38 #import "GlobalFindInPageState.h"
39 #import "IconLoadingDelegate.h"
40 #import "LegacySessionStateCoding.h"
41 #import "Logging.h"
42 #import "MediaCaptureUtilities.h"
43 #import "NavigationState.h"
44 #import "ObjCObjectGraph.h"
45 #import "PageClient.h"
46 #import "ProvisionalPageProxy.h"
47 #import "RemoteLayerTreeScrollingPerformanceData.h"
48 #import "RemoteLayerTreeTransaction.h"
49 #import "RemoteObjectRegistry.h"
50 #import "RemoteObjectRegistryMessages.h"
51 #import "SafeBrowsingWarning.h"
52 #import "UIDelegate.h"
53 #import "UserMediaProcessManager.h"
54 #import "VersionChecks.h"
55 #import "VideoFullscreenManagerProxy.h"
56 #import "ViewGestureController.h"
57 #import "ViewSnapshotStore.h"
58 #import "WKBackForwardListInternal.h"
59 #import "WKBackForwardListItemInternal.h"
60 #import "WKBrowsingContextHandleInternal.h"
61 #import "WKErrorInternal.h"
62 #import "WKFindConfiguration.h"
63 #import "WKFindResultInternal.h"
64 #import "WKHistoryDelegatePrivate.h"
65 #import "WKLayoutMode.h"
66 #import "WKNSData.h"
67 #import "WKNSURLExtras.h"
68 #import "WKNavigationDelegate.h"
69 #import "WKNavigationInternal.h"
70 #import "WKPDFConfiguration.h"
71 #import "WKPreferencesInternal.h"
72 #import "WKProcessPoolInternal.h"
73 #import "WKSafeBrowsingWarning.h"
74 #import "WKSharedAPICast.h"
75 #import "WKSnapshotConfiguration.h"
76 #import "WKUIDelegate.h"
77 #import "WKUIDelegatePrivate.h"
78 #import "WKUserContentControllerInternal.h"
79 #import "WKWebViewConfigurationInternal.h"
80 #import "WKWebViewContentProvider.h"
81 #import "WKWebpagePreferencesInternal.h"
82 #import "WKWebsiteDataStoreInternal.h"
83 #import "WebBackForwardList.h"
84 #import "WebCertificateInfo.h"
85 #import "WebFullScreenManagerProxy.h"
86 #import "WebPageGroup.h"
87 #import "WebPageProxy.h"
88 #import "WebPreferencesKeys.h"
89 #import "WebProcessPool.h"
90 #import "WebProcessProxy.h"
91 #import "WebURLSchemeHandlerCocoa.h"
92 #import "WebViewImpl.h"
93 #import "_WKActivatedElementInfoInternal.h"
94 #import "_WKDiagnosticLoggingDelegate.h"
95 #import "_WKFindDelegate.h"
96 #import "_WKFrameHandleInternal.h"
97 #import "_WKFullscreenDelegate.h"
98 #import "_WKHitTestResultInternal.h"
99 #import "_WKInputDelegate.h"
100 #import "_WKInspectorInternal.h"
101 #import "_WKRemoteObjectRegistryInternal.h"
102 #import "_WKSessionStateInternal.h"
103 #import "_WKTextInputContextInternal.h"
104 #import "_WKTextManipulationConfiguration.h"
105 #import "_WKTextManipulationDelegate.h"
106 #import "_WKTextManipulationExclusionRule.h"
107 #import "_WKTextManipulationItem.h"
108 #import "_WKTextManipulationToken.h"
109 #import "_WKVisitedLinkStoreInternal.h"
110 #import "_WKWebsitePoliciesInternal.h"
111 #import <WebCore/ElementContext.h>
112 #import <WebCore/GraphicsContextCG.h>
113 #import <WebCore/IOSurface.h>
114 #import <WebCore/JSDOMBinding.h>
115 #import <WebCore/JSDOMExceptionHandling.h>
116 #import <WebCore/LegacySchemeRegistry.h>
117 #import <WebCore/MIMETypeRegistry.h>
118 #import <WebCore/PlatformScreen.h>
119 #import <WebCore/RuntimeApplicationChecks.h>
120 #import <WebCore/SQLiteDatabaseTracker.h>
121 #import <WebCore/Settings.h>
122 #import <WebCore/SharedBuffer.h>
123 #import <WebCore/StringUtilities.h>
124 #import <WebCore/TextManipulationController.h>
125 #import <WebCore/ValidationBubble.h>
126 #import <WebCore/ViewportArguments.h>
127 #import <WebCore/WritingMode.h>
128 #import <WebKit/WKDragDestinationAction.h>
129 #import <pal/spi/cocoa/NSKeyedArchiverSPI.h>
130 #import <pal/spi/mac/NSTextFinderSPI.h>
131 #import <wtf/BlockPtr.h>
132 #import <wtf/HashMap.h>
133 #import <wtf/MathExtras.h>
134 #import <wtf/NeverDestroyed.h>
135 #import <wtf/Optional.h>
136 #import <wtf/RetainPtr.h>
137 #import <wtf/SetForScope.h>
138 #import <wtf/UUID.h>
139 #import <wtf/spi/darwin/dyldSPI.h>
140 #import <wtf/text/TextStream.h>
141
142 #if ENABLE(APPLICATION_MANIFEST)
143 #import "_WKApplicationManifestInternal.h"
144 #endif
145
146 #if ENABLE(DATA_DETECTION)
147 #import "WKDataDetectorTypesInternal.h"
148 #endif
149
150 #if PLATFORM(IOS_FAMILY)
151 #import "FrontBoardServicesSPI.h"
152 #import "InteractionInformationAtPosition.h"
153 #import "InteractionInformationRequest.h"
154 #import "ProcessThrottler.h"
155 #import "RemoteLayerTreeDrawingAreaProxy.h"
156 #import "RemoteScrollingCoordinatorProxy.h"
157 #import "UIKitSPI.h"
158 #import "VideoFullscreenManagerProxy.h"
159 #import "WKContentViewInteraction.h"
160 #import "WKPasswordView.h"
161 #import "WKScrollView.h"
162 #import "WKWebViewContentProviderRegistry.h"
163 #import "_WKWebViewPrintFormatter.h"
164 #import <MobileCoreServices/MobileCoreServices.h>
165 #import <UIKit/UIApplication.h>
166 #import <WebCore/FrameLoaderTypes.h>
167 #import <WebCore/InspectorOverlay.h>
168 #import <WebCore/LocalCurrentTraitCollection.h>
169 #import <WebCore/ScrollableArea.h>
170 #import <WebCore/WebBackgroundTaskController.h>
171 #import <WebCore/WebSQLiteDatabaseTrackerClient.h>
172 #import <pal/spi/cg/CoreGraphicsSPI.h>
173 #import <pal/spi/cocoa/QuartzCoreSPI.h>
174 #import <pal/spi/ios/GraphicsServicesSPI.h>
175 #import <wtf/cocoa/Entitlements.h>
176
177 #define RELEASE_LOG_IF_ALLOWED(...) RELEASE_LOG_IF(_page && _page->isAlwaysOnLoggingAllowed(), ViewState, __VA_ARGS__)
178
179 @interface UIView (UIViewInternal)
180 - (UIViewController *)_viewControllerForAncestor;
181 @end
182
183 @interface UIWindow (UIWindowInternal)
184 - (BOOL)_isHostedInAnotherProcess;
185 @end
186
187 @interface UIViewController (UIViewControllerInternal)
188 - (UIViewController *)_rootAncestorViewController;
189 - (UIViewController *)_viewControllerForSupportedInterfaceOrientations;
190 @end
191
192 #endif // PLATFORM(IOS_FAMILY)
193
194 #if PLATFORM(IOS_FAMILY)
195 static const uint32_t firstSDKVersionWithLinkPreviewEnabledByDefault = 0xA0000;
196 static const Seconds delayBeforeNoVisibleContentsRectsLogging = 1_s;
197 static const Seconds delayBeforeNoCommitsLogging = 5_s;
198 #endif
199
200 #if PLATFORM(MAC)
201 #import "AppKitSPI.h"
202 #import "WKTextFinderClient.h"
203 #import "WKViewInternal.h"
204 #import <WebCore/ColorMac.h>
205
206 @interface WKWebView () <WebViewImplDelegate, NSTextInputClient, NSTextInputClient_Async>
207 @end
208
209 #if HAVE(TOUCH_BAR)
210 @interface WKWebView () <NSTouchBarProvider>
211 @end
212 #endif // HAVE(TOUCH_BAR)
213 #endif // PLATFORM(MAC)
214
215 #if PLATFORM(MAC) && ENABLE(DRAG_SUPPORT)
216
217 @interface WKWebView () <NSFilePromiseProviderDelegate, NSDraggingSource>
218 @end
219
220 #endif
221
222 static HashMap<WebKit::WebPageProxy*, __unsafe_unretained WKWebView *>& pageToViewMap()
223 {
224     static NeverDestroyed<HashMap<WebKit::WebPageProxy*, __unsafe_unretained WKWebView *>> map;
225     return map;
226 }
227
228 WKWebView* fromWebPageProxy(WebKit::WebPageProxy& page)
229 {
230     return pageToViewMap().get(&page);
231 }
232
233 #if PLATFORM(MAC)
234 static _WKOverlayScrollbarStyle toAPIScrollbarStyle(Optional<WebCore::ScrollbarOverlayStyle> coreScrollbarStyle)
235 {
236     if (!coreScrollbarStyle)
237         return _WKOverlayScrollbarStyleAutomatic;
238     
239     switch (coreScrollbarStyle.value()) {
240     case WebCore::ScrollbarOverlayStyleDark:
241         return _WKOverlayScrollbarStyleDark;
242     case WebCore::ScrollbarOverlayStyleLight:
243         return _WKOverlayScrollbarStyleLight;
244     case WebCore::ScrollbarOverlayStyleDefault:
245         return _WKOverlayScrollbarStyleDefault;
246     }
247     ASSERT_NOT_REACHED();
248     return _WKOverlayScrollbarStyleAutomatic;
249 }
250
251 static Optional<WebCore::ScrollbarOverlayStyle> toCoreScrollbarStyle(_WKOverlayScrollbarStyle scrollbarStyle)
252 {
253     switch (scrollbarStyle) {
254     case _WKOverlayScrollbarStyleDark:
255         return WebCore::ScrollbarOverlayStyleDark;
256     case _WKOverlayScrollbarStyleLight:
257         return WebCore::ScrollbarOverlayStyleLight;
258     case _WKOverlayScrollbarStyleDefault:
259         return WebCore::ScrollbarOverlayStyleDefault;
260     case _WKOverlayScrollbarStyleAutomatic:
261         break;
262     }
263     return WTF::nullopt;
264 }
265 #endif
266
267 #define FORWARD_ACTION_TO_WKCONTENTVIEW(_action) \
268     - (void)_action:(id)sender \
269     { \
270         if (self.usesStandardContentView) \
271             [_contentView _action ## ForWebView:sender]; \
272     }
273
274 @implementation WKWebView {
275     std::unique_ptr<WebKit::NavigationState> _navigationState;
276     std::unique_ptr<WebKit::UIDelegate> _uiDelegate;
277     std::unique_ptr<WebKit::IconLoadingDelegate> _iconLoadingDelegate;
278
279     _WKRenderingProgressEvents _observedRenderingProgressEvents;
280
281     WeakObjCPtr<id <_WKInputDelegate>> _inputDelegate;
282
283     Optional<BOOL> _resolutionForShareSheetImmediateCompletionForTesting;
284     RetainPtr<WKSafeBrowsingWarning> _safeBrowsingWarning;
285
286     BOOL _usePlatformFindUI;
287
288     WeakObjCPtr<id <_WKTextManipulationDelegate>> _textManipulationDelegate;
289
290 #if PLATFORM(IOS_FAMILY)
291     RetainPtr<_WKRemoteObjectRegistry> _remoteObjectRegistry;
292
293     RetainPtr<WKScrollView> _scrollView;
294     RetainPtr<WKContentView> _contentView;
295
296 #if ENABLE(FULLSCREEN_API)
297     RetainPtr<WKFullScreenWindowController> _fullScreenWindowController;
298 #endif
299
300     Optional<CGSize> _viewLayoutSizeOverride;
301     Optional<WebCore::FloatSize> _lastSentViewLayoutSize;
302     Optional<CGSize> _maximumUnobscuredSizeOverride;
303     Optional<WebCore::FloatSize> _lastSentMaximumUnobscuredSize;
304
305     CGRect _inputViewBounds;
306     CGFloat _viewportMetaTagWidth;
307     BOOL _viewportMetaTagWidthWasExplicit;
308     BOOL _viewportMetaTagCameFromImageDocument;
309     CGFloat _initialScaleFactor;
310     BOOL _fastClickingIsDisabled;
311
312     BOOL _allowsLinkPreview;
313
314     UIEdgeInsets _obscuredInsets;
315     BOOL _haveSetObscuredInsets;
316     BOOL _isChangingObscuredInsetsInteractively;
317
318     UIEdgeInsets _unobscuredSafeAreaInsets;
319     BOOL _haveSetUnobscuredSafeAreaInsets;
320     BOOL _avoidsUnsafeArea;
321     UIRectEdge _obscuredInsetEdgesAffectedBySafeArea;
322
323     UIInterfaceOrientation _interfaceOrientationOverride;
324     BOOL _overridesInterfaceOrientation;
325     Optional<int32_t> _lastSentDeviceOrientation;
326
327     BOOL _allowsViewportShrinkToFit;
328
329     BOOL _hasCommittedLoadForMainFrame;
330     BOOL _needsResetViewStateAfterCommitLoadForMainFrame;
331     WebKit::TransactionID _firstPaintAfterCommitLoadTransactionID;
332     WebKit::TransactionID _lastTransactionID;
333     WebKit::DynamicViewportUpdateMode _dynamicViewportUpdateMode;
334     WebKit::DynamicViewportSizeUpdateID _currentDynamicViewportSizeUpdateID;
335     CATransform3D _resizeAnimationTransformAdjustments;
336     CGFloat _animatedResizeOriginalContentWidth;
337     RetainPtr<UIView> _resizeAnimationView;
338     CGFloat _lastAdjustmentForScroller;
339     Optional<CGRect> _frozenVisibleContentRect;
340     Optional<CGRect> _frozenUnobscuredContentRect;
341
342     BOOL _commitDidRestoreScrollPosition;
343     Optional<WebCore::FloatPoint> _scrollOffsetToRestore;
344     WebCore::FloatBoxExtent _obscuredInsetsWhenSaved;
345
346     Optional<WebCore::FloatPoint> _unobscuredCenterToRestore;
347     Optional<WebKit::TransactionID> _firstTransactionIDAfterPageRestore;
348     double _scaleToRestore;
349
350     std::unique_ptr<WebKit::ViewGestureController> _gestureController;
351     BOOL _allowsBackForwardNavigationGestures;
352
353     RetainPtr<UIView <WKWebViewContentProvider>> _customContentView;
354     RetainPtr<UIView> _customContentFixedOverlayView;
355
356     RetainPtr<NSTimer> _enclosingScrollViewScrollTimer;
357     BOOL _didScrollSinceLastTimerFire;
358
359     WebCore::Color _scrollViewBackgroundColor;
360
361     // This value tracks the current adjustment added to the bottom inset due to the keyboard sliding out from the bottom
362     // when computing obscured content insets. This is used when updating the visible content rects where we should not
363     // include this adjustment.
364     CGFloat _totalScrollViewBottomInsetAdjustmentForKeyboard;
365     BOOL _currentlyAdjustingScrollViewInsetsForKeyboard;
366
367     BOOL _invokingUIScrollViewDelegateCallback;
368     BOOL _didDeferUpdateVisibleContentRectsForUIScrollViewDelegateCallback;
369     BOOL _didDeferUpdateVisibleContentRectsForAnyReason;
370     BOOL _didDeferUpdateVisibleContentRectsForUnstableScrollView;
371
372     BOOL _waitingForEndAnimatedResize;
373     BOOL _waitingForCommitAfterAnimatedResize;
374
375     Vector<WTF::Function<void ()>> _callbacksDeferredDuringResize;
376     RetainPtr<NSMutableArray> _stableStatePresentationUpdateCallbacks;
377
378     RetainPtr<WKPasswordView> _passwordView;
379
380     BOOL _hasScheduledVisibleRectUpdate;
381     BOOL _visibleContentRectUpdateScheduledFromScrollViewInStableState;
382     Vector<BlockPtr<void ()>> _visibleContentRectUpdateCallbacks;
383
384     _WKDragInteractionPolicy _dragInteractionPolicy;
385
386     // For release-logging for <rdar://problem/39281269>.
387     MonotonicTime _timeOfRequestForVisibleContentRectUpdate;
388     MonotonicTime _timeOfLastVisibleContentRectUpdate;
389
390     Optional<MonotonicTime> _timeOfFirstVisibleContentRectUpdateWithPendingCommit;
391
392     NSUInteger _focusPreservationCount;
393     NSUInteger _activeFocusedStateRetainCount;
394
395     BOOL _hasEnteredDealloc;
396 #endif
397 #if PLATFORM(MAC)
398     std::unique_ptr<WebKit::WebViewImpl> _impl;
399     RetainPtr<WKTextFinderClient> _textFinderClient;
400 #endif
401     _WKSelectionAttributes _selectionAttributes;
402 }
403
404 - (instancetype)initWithFrame:(CGRect)frame
405 {
406     return [self initWithFrame:frame configuration:adoptNS([[WKWebViewConfiguration alloc] init]).get()];
407 }
408
409 - (BOOL)_isValid
410 {
411     return _page && _page->hasRunningProcess();
412 }
413
414 #if PLATFORM(IOS_FAMILY)
415 static int32_t deviceOrientationForUIInterfaceOrientation(UIInterfaceOrientation orientation)
416 {
417     switch (orientation) {
418     case UIInterfaceOrientationUnknown:
419     case UIInterfaceOrientationPortrait:
420         return 0;
421     case UIInterfaceOrientationPortraitUpsideDown:
422         return 180;
423     case UIInterfaceOrientationLandscapeLeft:
424         return -90;
425     case UIInterfaceOrientationLandscapeRight:
426         return 90;
427     }
428 }
429
430 static int32_t deviceOrientation()
431 {
432 ALLOW_DEPRECATED_DECLARATIONS_BEGIN
433     return deviceOrientationForUIInterfaceOrientation([[UIApplication sharedApplication] statusBarOrientation]);
434 ALLOW_DEPRECATED_DECLARATIONS_END
435 }
436
437 - (BOOL)_isShowingVideoPictureInPicture
438 {
439 #if !HAVE(AVKIT)
440     return false;
441 #else
442     if (!_page || !_page->videoFullscreenManager())
443         return false;
444
445     return _page->videoFullscreenManager()->hasMode(WebCore::HTMLMediaElementEnums::VideoFullscreenModePictureInPicture);
446 #endif
447 }
448
449 - (BOOL)_mayAutomaticallyShowVideoPictureInPicture
450 {
451 #if !HAVE(AVKIT)
452     return false;
453 #else
454     if (!_page || !_page->videoFullscreenManager())
455         return false;
456
457     return _page->videoFullscreenManager()->mayAutomaticallyShowVideoPictureInPicture();
458 #endif
459 }
460
461 static bool shouldAllowPictureInPictureMediaPlayback()
462 {
463     static bool shouldAllowPictureInPictureMediaPlayback = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_9_0;
464     return shouldAllowPictureInPictureMediaPlayback;
465 }
466
467 static bool shouldAllowSettingAnyXHRHeaderFromFileURLs()
468 {
469     static bool shouldAllowSettingAnyXHRHeaderFromFileURLs = (WebCore::IOSApplication::isCardiogram() || WebCore::IOSApplication::isNike()) && !linkedOnOrAfter(WebKit::SDKVersion::FirstThatDisallowsSettingAnyXHRHeaderFromFileURLs);
470     return shouldAllowSettingAnyXHRHeaderFromFileURLs;
471 }
472
473 - (void)_incrementFocusPreservationCount
474 {
475     ++_focusPreservationCount;
476 }
477
478 - (void)_decrementFocusPreservationCount
479 {
480     if (_focusPreservationCount)
481         --_focusPreservationCount;
482 }
483
484 - (void)_resetFocusPreservationCount
485 {
486     _focusPreservationCount = 0;
487 }
488
489 - (BOOL)_isRetainingActiveFocusedState
490 {
491     // Focus preservation count fulfills the same role as active focus state count.
492     // However, unlike active focus state, it may be reset to 0 without impacting the
493     // behavior of -_retainActiveFocusedState, and it's harmless to invoke
494     // -_decrementFocusPreservationCount after resetting the count to 0.
495     return _focusPreservationCount || _activeFocusedStateRetainCount;
496 }
497
498 - (BOOL)_effectiveAppearanceIsDark
499 {
500     return self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark;
501 }
502
503 - (BOOL)_effectiveUserInterfaceLevelIsElevated
504 {
505 #if HAVE(OS_DARK_MODE_SUPPORT) && !PLATFORM(WATCHOS)
506     return self.traitCollection.userInterfaceLevel == UIUserInterfaceLevelElevated;
507 #else
508     return NO;
509 #endif
510 }
511
512 #endif // PLATFORM(IOS_FAMILY)
513
514 static bool shouldRequireUserGestureToLoadVideo()
515 {
516 #if PLATFORM(IOS_FAMILY)
517     static bool shouldRequireUserGestureToLoadVideo = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
518     return shouldRequireUserGestureToLoadVideo;
519 #else
520     return false;
521 #endif
522 }
523
524 #if PLATFORM(MAC)
525 static uint32_t convertUserInterfaceDirectionPolicy(WKUserInterfaceDirectionPolicy policy)
526 {
527     switch (policy) {
528     case WKUserInterfaceDirectionPolicyContent:
529         return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content);
530     case WKUserInterfaceDirectionPolicySystem:
531         return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::System);
532     }
533     return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content);
534 }
535
536 static uint32_t convertSystemLayoutDirection(NSUserInterfaceLayoutDirection direction)
537 {
538     switch (direction) {
539     case NSUserInterfaceLayoutDirectionLeftToRight:
540         return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::LTR);
541     case NSUserInterfaceLayoutDirectionRightToLeft:
542         return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::RTL);
543     }
544     return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::LTR);
545 }
546
547 #endif // PLATFORM(MAC)
548
549 static void validate(WKWebViewConfiguration *configuration)
550 {
551     if (!configuration.processPool)
552         [NSException raise:NSInvalidArgumentException format:@"configuration.processPool is nil"];
553     
554     if (!configuration.preferences)
555         [NSException raise:NSInvalidArgumentException format:@"configuration.preferences is nil"];
556     
557     if (!configuration.userContentController)
558         [NSException raise:NSInvalidArgumentException format:@"configuration.userContentController is nil"];
559     
560     if (!configuration.websiteDataStore)
561         [NSException raise:NSInvalidArgumentException format:@"configuration.websiteDataStore is nil"];
562     
563     if (!configuration._visitedLinkStore)
564         [NSException raise:NSInvalidArgumentException format:@"configuration._visitedLinkStore is nil"];
565     
566 #if PLATFORM(IOS_FAMILY)
567     if (!configuration._contentProviderRegistry)
568         [NSException raise:NSInvalidArgumentException format:@"configuration._contentProviderRegistry is nil"];
569 #endif
570 }
571
572 - (void)_initializeWithConfiguration:(WKWebViewConfiguration *)configuration
573 {
574     if (!configuration)
575         [NSException raise:NSInvalidArgumentException format:@"Configuration cannot be nil"];
576
577     _configuration = adoptNS([configuration copy]);
578
579     if (WKWebView *relatedWebView = [_configuration _relatedWebView]) {
580         WKProcessPool *processPool = [_configuration processPool];
581         WKProcessPool *relatedWebViewProcessPool = [relatedWebView->_configuration processPool];
582         if (processPool && processPool != relatedWebViewProcessPool)
583             [NSException raise:NSInvalidArgumentException format:@"Related web view %@ has process pool %@ but configuration specifies a different process pool %@", relatedWebView, relatedWebViewProcessPool, configuration.processPool];
584         if ([relatedWebView->_configuration websiteDataStore] != [_configuration websiteDataStore] && linkedOnOrAfter(WebKit::SDKVersion::FirstWithExceptionsForRelatedWebViewsUsingDifferentDataStores, WebKit::AssumeSafariIsAlwaysLinkedOnAfter::No))
585             [NSException raise:NSInvalidArgumentException format:@"Related web view %@ has data store %@ but configuration specifies a different data store %@", relatedWebView, [relatedWebView->_configuration websiteDataStore], [_configuration websiteDataStore]];
586
587         [_configuration setProcessPool:relatedWebViewProcessPool];
588     }
589
590     validate(_configuration.get());
591
592     WebKit::WebProcessPool& processPool = *[_configuration processPool]->_processPool;
593
594     auto pageConfiguration = [configuration copyPageConfiguration];
595
596     pageConfiguration->setProcessPool(&processPool);
597     pageConfiguration->setPreferences([_configuration preferences]->_preferences.get());
598     if (WKWebView *relatedWebView = [_configuration _relatedWebView])
599         pageConfiguration->setRelatedPage(relatedWebView->_page.get());
600
601     pageConfiguration->setUserContentController([_configuration userContentController]->_userContentControllerProxy.get());
602     pageConfiguration->setVisitedLinkStore([_configuration _visitedLinkStore]->_visitedLinkStore.get());
603     pageConfiguration->setWebsiteDataStore([_configuration websiteDataStore]->_websiteDataStore.get());
604     pageConfiguration->setDefaultWebsitePolicies([_configuration defaultWebpagePreferences]->_websitePolicies.get());
605
606 #if PLATFORM(MAC)
607     if (auto pageGroup = WebKit::toImpl([configuration _pageGroup])) {
608         pageConfiguration->setPageGroup(pageGroup);
609         pageConfiguration->setUserContentController(&pageGroup->userContentController());
610     } else
611 #endif
612     {
613         NSString *groupIdentifier = configuration._groupIdentifier;
614         if (groupIdentifier.length)
615             pageConfiguration->setPageGroup(WebKit::WebPageGroup::create(configuration._groupIdentifier).ptr());
616     }
617
618     pageConfiguration->setAdditionalSupportedImageTypes(WebCore::webCoreStringVectorFromNSStringArray([_configuration _additionalSupportedImageTypes]));
619
620     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::suppressesIncrementalRenderingKey(), WebKit::WebPreferencesStore::Value(!![_configuration suppressesIncrementalRendering]));
621
622     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldRespectImageOrientationKey(), WebKit::WebPreferencesStore::Value(!![_configuration _respectsImageOrientation]));
623 #if !PLATFORM(MAC)
624     // FIXME: Expose WKPreferences._shouldPrintBackgrounds on iOS, adopt it in all iOS clients, and remove this and WKWebViewConfiguration._printsBackgrounds.
625     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldPrintBackgroundsKey(), WebKit::WebPreferencesStore::Value(!![_configuration _printsBackgrounds]));
626 #endif
627     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey(), WebKit::WebPreferencesStore::Value([_configuration _incrementalRenderingSuppressionTimeout]));
628     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::javaScriptMarkupEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsJavaScriptMarkup]));
629     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldConvertPositionStyleOnCopyKey(), WebKit::WebPreferencesStore::Value(!![_configuration _convertsPositionStyleOnCopy]));
630     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::httpEquivEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsMetaRefresh]));
631     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowUniversalAccessFromFileURLsKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowUniversalAccessFromFileURLs]));
632     pageConfiguration->setWaitsForPaintAfterViewDidMoveToWindow([_configuration _waitsForPaintAfterViewDidMoveToWindow]);
633     pageConfiguration->setDrawsBackground([_configuration _drawsBackground]);
634     pageConfiguration->setControlledByAutomation([_configuration _isControlledByAutomation]);
635     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::incompleteImageBorderEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _incompleteImageBorderEnabled]));
636     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldDeferAsynchronousScriptsUntilAfterDocumentLoadKey(), WebKit::WebPreferencesStore::Value(!![_configuration _shouldDeferAsynchronousScriptsUntilAfterDocumentLoad]));
637
638 #if PLATFORM(MAC)
639     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::showsURLsInToolTipsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _showsURLsInToolTips]));
640     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::serviceControlsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _serviceControlsEnabled]));
641     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::imageControlsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _imageControlsEnabled]));
642
643     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::userInterfaceDirectionPolicyKey(), WebKit::WebPreferencesStore::Value(convertUserInterfaceDirectionPolicy([_configuration userInterfaceDirectionPolicy])));
644     // We are in the View's initialization routine, so our client hasn't had time to set our user interface direction.
645     // Therefore, according to the docs[1], "this property contains the value reported by the app's userInterfaceLayoutDirection property."
646     // [1] http://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/index.html#//apple_ref/doc/uid/20000014-SW222
647     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::systemLayoutDirectionKey(), WebKit::WebPreferencesStore::Value(convertSystemLayoutDirection(self.userInterfaceLayoutDirection)));
648 #endif
649
650 #if PLATFORM(IOS_FAMILY)
651     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsInlineMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsInlineMediaPlayback]));
652     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsInlineMediaPlaybackAfterFullscreenKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsInlineMediaPlaybackAfterFullscreen]));
653     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::inlineMediaPlaybackRequiresPlaysInlineAttributeKey(), WebKit::WebPreferencesStore::Value(!![_configuration _inlineMediaPlaybackRequiresPlaysInlineAttribute]));
654     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsPictureInPictureMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback()));
655     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::userInterfaceDirectionPolicyKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content)));
656     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::systemLayoutDirectionKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(WebCore::TextDirection::LTR)));
657     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowSettingAnyXHRHeaderFromFileURLsKey(), WebKit::WebPreferencesStore::Value(shouldAllowSettingAnyXHRHeaderFromFileURLs()));
658     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldDecidePolicyBeforeLoadingQuickLookPreviewKey(), WebKit::WebPreferencesStore::Value(!![_configuration _shouldDecidePolicyBeforeLoadingQuickLookPreview]));
659 #if ENABLE(DEVICE_ORIENTATION)
660     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::deviceOrientationPermissionAPIEnabledKey(), WebKit::WebPreferencesStore::Value(linkedOnOrAfter(WebKit::SDKVersion::FirstWithDeviceOrientationAndMotionPermissionAPI)));
661 #endif
662 #if USE(SYSTEM_PREVIEW)
663     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::systemPreviewEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _systemPreviewEnabled]));
664 #endif
665 #endif
666
667     WKAudiovisualMediaTypes mediaTypesRequiringUserGesture = [_configuration mediaTypesRequiringUserActionForPlayback];
668     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureForVideoPlaybackKey(), WebKit::WebPreferencesStore::Value((mediaTypesRequiringUserGesture & WKAudiovisualMediaTypeVideo) == WKAudiovisualMediaTypeVideo));
669     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureForAudioPlaybackKey(), WebKit::WebPreferencesStore::Value(((mediaTypesRequiringUserGesture & WKAudiovisualMediaTypeAudio) == WKAudiovisualMediaTypeAudio)));
670     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureToLoadVideoKey(), WebKit::WebPreferencesStore::Value(shouldRequireUserGestureToLoadVideo()));
671     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mainContentUserGestureOverrideEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _mainContentUserGestureOverrideEnabled]));
672     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::invisibleAutoplayNotPermittedKey(), WebKit::WebPreferencesStore::Value(!![_configuration _invisibleAutoplayNotPermitted]));
673     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mediaDataLoadsAutomaticallyKey(), WebKit::WebPreferencesStore::Value(!![_configuration _mediaDataLoadsAutomatically]));
674     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::attachmentElementEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _attachmentElementEnabled]));
675
676 #if ENABLE(DATA_DETECTION) && PLATFORM(IOS_FAMILY)
677     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::dataDetectorTypesKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(fromWKDataDetectorTypes([_configuration dataDetectorTypes]))));
678 #endif
679 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
680     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsAirPlayForMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsAirPlayForMediaPlayback]));
681 #endif
682
683 #if ENABLE(APPLE_PAY)
684     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::applePayEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _applePayEnabled]));
685 #endif
686
687     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::needsStorageAccessFromFileURLsQuirkKey(), WebKit::WebPreferencesStore::Value(!![_configuration _needsStorageAccessFromFileURLsQuirk]));
688     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mediaContentTypesRequiringHardwareSupportKey(), WebKit::WebPreferencesStore::Value(String([_configuration _mediaContentTypesRequiringHardwareSupport])));
689     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowMediaContentTypesRequiringHardwareSupportAsFallbackKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowMediaContentTypesRequiringHardwareSupportAsFallback]));
690
691     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::colorFilterEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _colorFilterEnabled]));
692
693     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::editableImagesEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _editableImagesEnabled]));
694     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::undoManagerAPIEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _undoManagerAPIEnabled]));
695
696 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
697     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::legacyEncryptedMediaAPIEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _legacyEncryptedMediaAPIEnabled]));
698 #endif
699
700 #if PLATFORM(IOS_FAMILY) && ENABLE(SERVICE_WORKER)
701     if (!WTF::processHasEntitlement("com.apple.developer.WebKit.ServiceWorkers"))
702         pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::serviceWorkersEnabledKey(), WebKit::WebPreferencesStore::Value(false));
703 #endif
704
705     if (!linkedOnOrAfter(WebKit::SDKVersion::FirstWhereSiteSpecificQuirksAreEnabledByDefault))
706         pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::needsSiteSpecificQuirksKey(), WebKit::WebPreferencesStore::Value(false));
707
708 #if PLATFORM(IOS_FAMILY)
709     CGRect bounds = self.bounds;
710     _scrollView = adoptNS([[WKScrollView alloc] initWithFrame:bounds]);
711     [_scrollView setInternalDelegate:self];
712     [_scrollView setBouncesZoom:YES];
713
714     if ([_scrollView respondsToSelector:@selector(_setAvoidsJumpOnInterruptedBounce:)]) {
715         [_scrollView setTracksImmediatelyWhileDecelerating:NO];
716         [_scrollView _setAvoidsJumpOnInterruptedBounce:YES];
717     }
718
719     if ([_configuration _editableImagesEnabled])
720         [_scrollView panGestureRecognizer].allowedTouchTypes = @[ @(UITouchTypeDirect) ];
721
722     _avoidsUnsafeArea = YES;
723     [self _updateScrollViewInsetAdjustmentBehavior];
724
725     [self addSubview:_scrollView.get()];
726
727     static uint32_t programSDKVersion = dyld_get_program_sdk_version();
728     _allowsLinkPreview = programSDKVersion >= firstSDKVersionWithLinkPreviewEnabledByDefault;
729
730     _contentView = adoptNS([[WKContentView alloc] initWithFrame:bounds processPool:processPool configuration:pageConfiguration.copyRef() webView:self]);
731
732     _page = [_contentView page];
733     [self _dispatchSetDeviceOrientation:deviceOrientation()];
734
735     if (!self.opaque || !pageConfiguration->drawsBackground())
736         [self _setOpaqueInternal:NO];
737
738     [_contentView layer].anchorPoint = CGPointZero;
739     [_contentView setFrame:bounds];
740     [_scrollView addSubview:_contentView.get()];
741     [_scrollView addSubview:[_contentView unscaledView]];
742     [self _updateScrollViewBackground];
743     _obscuredInsetEdgesAffectedBySafeArea = UIRectEdgeTop | UIRectEdgeLeft | UIRectEdgeRight;
744
745     _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
746     _initialScaleFactor = 1;
747
748     if (NSNumber *enabledValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"WebKitFastClickingDisabled"])
749         _fastClickingIsDisabled = enabledValue.boolValue;
750     else {
751 #if PLATFORM(WATCHOS)
752         _fastClickingIsDisabled = YES;
753 #else
754         _fastClickingIsDisabled = NO;
755 #endif
756     }
757
758     [self _frameOrBoundsChanged];
759
760     NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
761     [center addObserver:self selector:@selector(_keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
762     [center addObserver:self selector:@selector(_keyboardDidChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
763     [center addObserver:self selector:@selector(_keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
764     [center addObserver:self selector:@selector(_keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
765     [center addObserver:self selector:@selector(_keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
766     [center addObserver:self selector:@selector(_windowDidRotate:) name:UIWindowDidRotateNotification object:nil];
767     [center addObserver:self selector:@selector(_contentSizeCategoryDidChange:) name:UIContentSizeCategoryDidChangeNotification object:nil];
768     _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
769
770     [center addObserver:self selector:@selector(_accessibilitySettingsDidChange:) name:UIAccessibilityGrayscaleStatusDidChangeNotification object:nil];
771     [center addObserver:self selector:@selector(_accessibilitySettingsDidChange:) name:UIAccessibilityInvertColorsStatusDidChangeNotification object:nil];
772     [center addObserver:self selector:@selector(_accessibilitySettingsDidChange:) name:UIAccessibilityReduceMotionStatusDidChangeNotification object:nil];
773
774     [[_configuration _contentProviderRegistry] addPage:*_page];
775     _page->setForceAlwaysUserScalable([_configuration ignoresViewportScaleLimits]);
776
777     CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), hardwareKeyboardAvailabilityChangedCallback, (CFStringRef)[NSString stringWithUTF8String:kGSEventHardwareKeyboardAvailabilityChangedNotification], nullptr, CFNotificationSuspensionBehaviorCoalesce);
778 #endif
779
780 #if PLATFORM(MAC)
781     _impl = makeUnique<WebKit::WebViewImpl>(self, self, processPool, pageConfiguration.copyRef());
782     _page = &_impl->page();
783
784     _impl->setAutomaticallyAdjustsContentInsets(true);
785     _impl->setRequiresUserActionForEditingControlsManager([configuration _requiresUserActionForEditingControlsManager]);
786 #endif
787
788     if (NSString *applicationNameForUserAgent = configuration.applicationNameForUserAgent)
789         _page->setApplicationNameForUserAgent(applicationNameForUserAgent);
790
791     _page->setApplicationNameForDesktopUserAgent(configuration._applicationNameForDesktopUserAgent);
792
793     _navigationState = makeUnique<WebKit::NavigationState>(self);
794     _page->setNavigationClient(_navigationState->createNavigationClient());
795
796     _uiDelegate = makeUnique<WebKit::UIDelegate>(self);
797     _page->setFindClient(makeUnique<WebKit::FindClient>(self));
798     _page->setDiagnosticLoggingClient(makeUnique<WebKit::DiagnosticLoggingClient>(self));
799
800     _iconLoadingDelegate = makeUnique<WebKit::IconLoadingDelegate>(self);
801
802     _usePlatformFindUI = YES;
803
804     [self _setUpSQLiteDatabaseTrackerClient];
805
806     for (auto& pair : pageConfiguration->urlSchemeHandlers())
807         _page->setURLSchemeHandlerForScheme(WebKit::WebURLSchemeHandlerCocoa::create(static_cast<WebKit::WebURLSchemeHandlerCocoa&>(pair.value.get()).apiHandler()), pair.key);
808
809     pageToViewMap().add(_page.get(), self);
810
811 #if PLATFORM(IOS_FAMILY)
812     _dragInteractionPolicy = _WKDragInteractionPolicyDefault;
813
814     auto timeNow = MonotonicTime::now();
815     _timeOfRequestForVisibleContentRectUpdate = timeNow;
816     _timeOfLastVisibleContentRectUpdate = timeNow;
817     _timeOfFirstVisibleContentRectUpdateWithPendingCommit = timeNow;
818
819 #if PLATFORM(WATCHOS)
820     _allowsViewportShrinkToFit = YES;
821 #else
822     _allowsViewportShrinkToFit = NO;
823 #endif
824 #endif // PLATFORM(IOS_FAMILY)
825 }
826
827 - (void)_setUpSQLiteDatabaseTrackerClient
828 {
829 #if PLATFORM(IOS_FAMILY)
830     WebBackgroundTaskController *controller = [WebBackgroundTaskController sharedController];
831     if (controller.backgroundTaskStartBlock)
832         return;
833
834     controller.backgroundTaskStartBlock = ^NSUInteger (void (^expirationHandler)())
835     {
836         return [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"com.apple.WebKit.DatabaseActivity" expirationHandler:expirationHandler];
837     };
838     controller.backgroundTaskEndBlock = ^(UIBackgroundTaskIdentifier taskIdentifier)
839     {
840         [[UIApplication sharedApplication] endBackgroundTask:taskIdentifier];
841     };
842     controller.invalidBackgroundTaskIdentifier = UIBackgroundTaskInvalid;
843
844     WebCore::SQLiteDatabaseTracker::setClient(&WebCore::WebSQLiteDatabaseTrackerClient::sharedWebSQLiteDatabaseTrackerClient());
845 #endif
846 }
847
848 - (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration
849 {
850     if (!(self = [super initWithFrame:frame]))
851         return nil;
852
853     [self _initializeWithConfiguration:configuration];
854
855     return self;
856 }
857
858 - (instancetype)initWithCoder:(NSCoder *)coder
859 {
860     if (!(self = [super initWithCoder:coder]))
861         return nil;
862
863     WKWebViewConfiguration *configuration = decodeObjectOfClassForKeyFromCoder([WKWebViewConfiguration class], @"configuration", coder);
864     [self _initializeWithConfiguration:configuration];
865
866     self.allowsBackForwardNavigationGestures = [coder decodeBoolForKey:@"allowsBackForwardNavigationGestures"];
867     self.customUserAgent = decodeObjectOfClassForKeyFromCoder([NSString class], @"customUserAgent", coder);
868     self.allowsLinkPreview = [coder decodeBoolForKey:@"allowsLinkPreview"];
869
870 #if PLATFORM(MAC)
871     self.allowsMagnification = [coder decodeBoolForKey:@"allowsMagnification"];
872     self.magnification = [coder decodeDoubleForKey:@"magnification"];
873 #endif
874
875     return self;
876 }
877
878 - (void)encodeWithCoder:(NSCoder *)coder
879 {
880     [super encodeWithCoder:coder];
881
882     [coder encodeObject:_configuration.get() forKey:@"configuration"];
883
884     [coder encodeBool:self.allowsBackForwardNavigationGestures forKey:@"allowsBackForwardNavigationGestures"];
885     [coder encodeObject:self.customUserAgent forKey:@"customUserAgent"];
886     [coder encodeBool:self.allowsLinkPreview forKey:@"allowsLinkPreview"];
887
888 #if PLATFORM(MAC)
889     [coder encodeBool:self.allowsMagnification forKey:@"allowsMagnification"];
890     [coder encodeDouble:self.magnification forKey:@"magnification"];
891 #endif
892 }
893
894 - (void)dealloc
895 {
896 #if PLATFORM(MAC)
897     [_textFinderClient willDestroyView:self];
898 #endif
899
900 #if PLATFORM(IOS_FAMILY)
901     _hasEnteredDealloc = YES;
902
903     [_contentView _webViewDestroyed];
904
905     if (_remoteObjectRegistry)
906         _page->process().processPool().removeMessageReceiver(Messages::RemoteObjectRegistry::messageReceiverName(), _page->identifier());
907 #endif
908
909     _page->close();
910
911 #if PLATFORM(IOS_FAMILY)
912     [_remoteObjectRegistry _invalidate];
913     [[_configuration _contentProviderRegistry] removePage:*_page];
914     [[NSNotificationCenter defaultCenter] removeObserver:self];
915     [_scrollView setInternalDelegate:nil];
916
917     CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), (CFStringRef)[NSString stringWithUTF8String:kGSEventHardwareKeyboardAvailabilityChangedNotification], nullptr);
918 #endif
919
920     pageToViewMap().remove(_page.get());
921
922     [super dealloc];
923 }
924
925 - (id)valueForUndefinedKey:(NSString *)key {
926     if ([key isEqualToString:@"serverTrust"])
927         return (__bridge id)[self serverTrust];
928
929     return [super valueForUndefinedKey:key];
930 }
931
932 - (WKWebViewConfiguration *)configuration
933 {
934     return [[_configuration copy] autorelease];
935 }
936
937 - (WKBackForwardList *)backForwardList
938 {
939     return wrapper(_page->backForwardList());
940 }
941
942 - (id <WKNavigationDelegate>)navigationDelegate
943 {
944     return _navigationState->navigationDelegate().autorelease();
945 }
946
947 - (void)setNavigationDelegate:(id <WKNavigationDelegate>)navigationDelegate
948 {
949     _page->setNavigationClient(_navigationState->createNavigationClient());
950     _navigationState->setNavigationDelegate(navigationDelegate);
951 }
952
953 - (id <WKUIDelegate>)UIDelegate
954 {
955     return _uiDelegate->delegate().autorelease();
956 }
957
958 - (void)setUIDelegate:(id<WKUIDelegate>)UIDelegate
959 {
960     _uiDelegate->setDelegate(UIDelegate);
961 #if ENABLE(CONTEXT_MENUS)
962     _page->setContextMenuClient(_uiDelegate->createContextMenuClient());
963 #endif
964     _page->setUIClient(_uiDelegate->createUIClient());
965 }
966
967 - (id <_WKIconLoadingDelegate>)_iconLoadingDelegate
968 {
969     return _iconLoadingDelegate->delegate().autorelease();
970 }
971
972 - (void)_setIconLoadingDelegate:(id<_WKIconLoadingDelegate>)iconLoadingDelegate
973 {
974     _page->setIconLoadingClient(_iconLoadingDelegate->createIconLoadingClient());
975     _iconLoadingDelegate->setDelegate(iconLoadingDelegate);
976 }
977
978 - (WKNavigation *)loadRequest:(NSURLRequest *)request
979 {
980     return wrapper(_page->loadRequest(request));
981 }
982
983 - (WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL
984 {
985     if (![URL isFileURL])
986         [NSException raise:NSInvalidArgumentException format:@"%@ is not a file URL", URL];
987
988     if (![readAccessURL isFileURL])
989         [NSException raise:NSInvalidArgumentException format:@"%@ is not a file URL", readAccessURL];
990
991     return wrapper(_page->loadFile(URL.absoluteString, readAccessURL.absoluteString));
992 }
993
994 - (WKNavigation *)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
995 {
996     NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
997
998     return [self loadData:data MIMEType:@"text/html" characterEncodingName:@"UTF-8" baseURL:baseURL];
999 }
1000
1001 - (WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL
1002 {
1003     return wrapper(_page->loadData({ static_cast<const uint8_t*>(data.bytes), data.length }, MIMEType, characterEncodingName, baseURL.absoluteString));
1004 }
1005
1006 - (WKNavigation *)goToBackForwardListItem:(WKBackForwardListItem *)item
1007 {
1008     return wrapper(_page->goToBackForwardItem(item._item));
1009 }
1010
1011 - (NSString *)title
1012 {
1013     return _page->pageLoadState().title();
1014 }
1015
1016 - (NSURL *)URL
1017 {
1018     return [NSURL _web_URLWithWTFString:_page->pageLoadState().activeURL()];
1019 }
1020
1021 - (NSURL *)_resourceDirectoryURL
1022 {
1023     return _page->currentResourceDirectoryURL();
1024 }
1025
1026 - (BOOL)isLoading
1027 {
1028     return _page->pageLoadState().isLoading();
1029 }
1030
1031 - (double)estimatedProgress
1032 {
1033     return _page->pageLoadState().estimatedProgress();
1034 }
1035
1036 - (BOOL)hasOnlySecureContent
1037 {
1038     return _page->pageLoadState().hasOnlySecureContent();
1039 }
1040
1041 - (SecTrustRef)serverTrust
1042 {
1043 #if HAVE(SEC_TRUST_SERIALIZATION)
1044     auto certificateInfo = _page->pageLoadState().certificateInfo();
1045     if (!certificateInfo)
1046         return nil;
1047
1048     return certificateInfo->certificateInfo().trust();
1049 #else
1050     return nil;
1051 #endif
1052 }
1053
1054 - (BOOL)canGoBack
1055 {
1056     return _page->pageLoadState().canGoBack();
1057 }
1058
1059 - (BOOL)canGoForward
1060 {
1061     return _page->pageLoadState().canGoForward();
1062 }
1063
1064 - (WKNavigation *)goBack
1065 {
1066     if (self._safeBrowsingWarning)
1067         return [self reload];
1068     return wrapper(_page->goBack());
1069 }
1070
1071 - (WKNavigation *)goForward
1072 {
1073     return wrapper(_page->goForward());
1074 }
1075
1076 - (WKNavigation *)reload
1077 {
1078     OptionSet<WebCore::ReloadOption> reloadOptions;
1079     if (linkedOnOrAfter(WebKit::SDKVersion::FirstWithExpiredOnlyReloadBehavior))
1080         reloadOptions.add(WebCore::ReloadOption::ExpiredOnly);
1081
1082     return wrapper(_page->reload(reloadOptions));
1083 }
1084
1085 - (WKNavigation *)reloadFromOrigin
1086 {
1087     return wrapper(_page->reload(WebCore::ReloadOption::FromOrigin));
1088 }
1089
1090 - (void)stopLoading
1091 {
1092     _page->stopLoading();
1093 }
1094
1095 static WKErrorCode callbackErrorCode(WebKit::CallbackBase::Error error)
1096 {
1097     switch (error) {
1098     case WebKit::CallbackBase::Error::None:
1099         ASSERT_NOT_REACHED();
1100         return WKErrorUnknown;
1101
1102     case WebKit::CallbackBase::Error::Unknown:
1103         return WKErrorUnknown;
1104
1105     case WebKit::CallbackBase::Error::ProcessExited:
1106         return WKErrorWebContentProcessTerminated;
1107
1108     case WebKit::CallbackBase::Error::OwnerWasInvalidated:
1109         return WKErrorWebViewInvalidated;
1110     }
1111 }
1112
1113 - (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *))completionHandler
1114 {
1115     [self _evaluateJavaScript:javaScriptString forceUserGesture:YES completionHandler:completionHandler];
1116 }
1117
1118 - (void)_evaluateJavaScript:(NSString *)javaScriptString forceUserGesture:(BOOL)forceUserGesture completionHandler:(void (^)(id, NSError *))completionHandler
1119 {
1120     auto handler = adoptNS([completionHandler copy]);
1121
1122     _page->runJavaScriptInMainFrame(javaScriptString, forceUserGesture, [handler](API::SerializedScriptValue* serializedScriptValue, bool hadException, const WebCore::ExceptionDetails& details, WebKit::ScriptValueCallback::Error errorCode) {
1123         if (!handler)
1124             return;
1125
1126         if (errorCode != WebKit::ScriptValueCallback::Error::None) {
1127             auto error = createNSError(callbackErrorCode(errorCode));
1128             if (errorCode == WebKit::ScriptValueCallback::Error::OwnerWasInvalidated) {
1129                 // The OwnerWasInvalidated callback is synchronous. We don't want to call the block from within it
1130                 // because that can trigger re-entrancy bugs in WebKit.
1131                 // FIXME: It would be even better if GenericCallback did this for us.
1132                 dispatch_async(dispatch_get_main_queue(), [handler, error] {
1133                     auto rawHandler = (void (^)(id, NSError *))handler.get();
1134                     rawHandler(nil, error.get());
1135                 });
1136                 return;
1137             }
1138
1139             auto rawHandler = (void (^)(id, NSError *))handler.get();
1140             rawHandler(nil, error.get());
1141             return;
1142         }
1143
1144         auto rawHandler = (void (^)(id, NSError *))handler.get();
1145         if (hadException) {
1146             ASSERT(!serializedScriptValue);
1147
1148             RetainPtr<NSMutableDictionary> userInfo = adoptNS([[NSMutableDictionary alloc] init]);
1149
1150             [userInfo setObject:localizedDescriptionForErrorCode(WKErrorJavaScriptExceptionOccurred) forKey:NSLocalizedDescriptionKey];
1151             [userInfo setObject:static_cast<NSString *>(details.message) forKey:_WKJavaScriptExceptionMessageErrorKey];
1152             [userInfo setObject:@(details.lineNumber) forKey:_WKJavaScriptExceptionLineNumberErrorKey];
1153             [userInfo setObject:@(details.columnNumber) forKey:_WKJavaScriptExceptionColumnNumberErrorKey];
1154
1155             if (!details.sourceURL.isEmpty())
1156                 [userInfo setObject:[NSURL _web_URLWithWTFString:details.sourceURL] forKey:_WKJavaScriptExceptionSourceURLErrorKey];
1157
1158             rawHandler(nil, adoptNS([[NSError alloc] initWithDomain:WKErrorDomain code:WKErrorJavaScriptExceptionOccurred userInfo:userInfo.get()]).get());
1159             return;
1160         }
1161
1162         if (!serializedScriptValue) {
1163             rawHandler(nil, createNSError(WKErrorJavaScriptResultTypeIsUnsupported).get());
1164             return;
1165         }
1166
1167         id body = API::SerializedScriptValue::deserialize(serializedScriptValue->internalRepresentation(), 0);
1168         rawHandler(body, nil);
1169     });
1170 }
1171
1172 #if PLATFORM(MAC)
1173 - (void)takeSnapshotWithConfiguration:(WKSnapshotConfiguration *)snapshotConfiguration completionHandler:(void(^)(NSImage *, NSError *))completionHandler
1174 {
1175     CGRect rectInViewCoordinates = snapshotConfiguration && !CGRectIsNull(snapshotConfiguration.rect) ? snapshotConfiguration.rect : self.bounds;
1176     CGFloat snapshotWidth;
1177     if (snapshotConfiguration)
1178         snapshotWidth = snapshotConfiguration.snapshotWidth.doubleValue ?: rectInViewCoordinates.size.width;
1179     else
1180         snapshotWidth = self.bounds.size.width;
1181
1182     auto handler = makeBlockPtr(completionHandler);
1183     CGFloat imageScale = snapshotWidth / rectInViewCoordinates.size.width;
1184     CGFloat imageHeight = imageScale * rectInViewCoordinates.size.height;
1185
1186     // Need to scale by device scale factor or the image will be distorted.
1187     CGFloat deviceScale = _page->deviceScaleFactor();
1188     WebCore::IntSize bitmapSize(snapshotWidth, imageHeight);
1189     bitmapSize.scale(deviceScale, deviceScale);
1190
1191     // Software snapshot will not capture elements rendered with hardware acceleration (WebGL, video, etc).
1192     // This code doesn't consider snapshotConfiguration.afterScreenUpdates since the software snapshot always
1193     // contains recent updates. If we ever have a UI-side snapshot mechanism on macOS, we will need to factor
1194     // in snapshotConfiguration.afterScreenUpdates at that time.
1195     _page->takeSnapshot(WebCore::enclosingIntRect(rectInViewCoordinates), bitmapSize, WebKit::SnapshotOptionsInViewCoordinates, [handler, snapshotWidth, imageHeight](const WebKit::ShareableBitmap::Handle& imageHandle, WebKit::CallbackBase::Error errorCode) {
1196         if (errorCode != WebKit::ScriptValueCallback::Error::None) {
1197             auto error = createNSError(callbackErrorCode(errorCode));
1198             handler(nil, error.get());
1199             return;
1200         }
1201
1202         auto bitmap = WebKit::ShareableBitmap::create(imageHandle, WebKit::SharedMemory::Protection::ReadOnly);
1203         RetainPtr<CGImageRef> cgImage = bitmap ? bitmap->makeCGImage() : nullptr;
1204         RetainPtr<NSImage> nsImage = adoptNS([[NSImage alloc] initWithCGImage:cgImage.get() size:NSMakeSize(snapshotWidth, imageHeight)]);
1205         handler(nsImage.get(), nil);
1206     });
1207 }
1208
1209 #elif PLATFORM(IOS_FAMILY)
1210 - (void)takeSnapshotWithConfiguration:(WKSnapshotConfiguration *)snapshotConfiguration completionHandler:(void(^)(UIImage *, NSError *))completionHandler
1211 {
1212     CGRect rectInViewCoordinates = snapshotConfiguration && !CGRectIsNull(snapshotConfiguration.rect) ? snapshotConfiguration.rect : self.bounds;
1213     CGFloat snapshotWidth;
1214     if (snapshotConfiguration)
1215         snapshotWidth = snapshotConfiguration.snapshotWidth.doubleValue ?: rectInViewCoordinates.size.width;
1216     else
1217         snapshotWidth = self.bounds.size.width;
1218
1219     auto handler = makeBlockPtr(completionHandler);
1220     CGFloat deviceScale = _page->deviceScaleFactor();
1221     RetainPtr<WKWebView> strongSelf = self;
1222     auto callSnapshotRect = [strongSelf, rectInViewCoordinates, snapshotWidth, deviceScale, handler] {
1223         [strongSelf _snapshotRect:rectInViewCoordinates intoImageOfWidth:(snapshotWidth * deviceScale) completionHandler:[strongSelf, handler, deviceScale](CGImageRef snapshotImage) {
1224             RetainPtr<NSError> error;
1225             RetainPtr<UIImage> uiImage;
1226             
1227             if (!snapshotImage)
1228                 error = createNSError(WKErrorUnknown);
1229             else
1230                 uiImage = adoptNS([[UIImage alloc] initWithCGImage:snapshotImage scale:deviceScale orientation:UIImageOrientationUp]);
1231             
1232             handler(uiImage.get(), error.get());
1233         }];
1234     };
1235
1236     if ((snapshotConfiguration && !snapshotConfiguration.afterScreenUpdates) || !linkedOnOrAfter(WebKit::SDKVersion::FirstWithSnapshotAfterScreenUpdates)) {
1237         callSnapshotRect();
1238         return;
1239     }
1240
1241     _page->callAfterNextPresentationUpdate([callSnapshotRect = WTFMove(callSnapshotRect), handler](WebKit::CallbackBase::Error error) {
1242         if (error != WebKit::CallbackBase::Error::None) {
1243             handler(nil, createNSError(WKErrorUnknown).get());
1244             return;
1245         }
1246         callSnapshotRect();
1247     });
1248 }
1249 #endif
1250
1251 - (NSString *)customUserAgent
1252 {
1253     return _page->customUserAgent();
1254 }
1255
1256 - (void)setCustomUserAgent:(NSString *)customUserAgent
1257 {
1258     _page->setCustomUserAgent(customUserAgent);
1259 }
1260
1261 - (WKPageRef)_pageForTesting
1262 {
1263     return toAPI(_page.get());
1264 }
1265
1266 - (WebKit::WebPageProxy *)_page
1267 {
1268     return _page.get();
1269 }
1270
1271 - (BOOL)allowsLinkPreview
1272 {
1273 #if PLATFORM(MAC)
1274     return _impl->allowsLinkPreview();
1275 #elif PLATFORM(IOS_FAMILY)
1276     return _allowsLinkPreview;
1277 #endif
1278 }
1279
1280 - (void)setAllowsLinkPreview:(BOOL)allowsLinkPreview
1281 {
1282 #if PLATFORM(MAC)
1283     _impl->setAllowsLinkPreview(allowsLinkPreview);
1284     return;
1285 #elif PLATFORM(IOS_FAMILY)
1286     if (_allowsLinkPreview == allowsLinkPreview)
1287         return;
1288
1289     _allowsLinkPreview = allowsLinkPreview;
1290
1291 #if HAVE(LINK_PREVIEW)
1292     if (_allowsLinkPreview)
1293         [_contentView _registerPreview];
1294     else
1295         [_contentView _unregisterPreview];
1296     [_contentView _didChangeLinkPreviewAvailability];
1297 #endif // HAVE(LINK_PREVIEW)
1298 #endif // PLATFORM(IOS_FAMILY)
1299 }
1300
1301 - (CGSize)_viewportSizeForCSSViewportUnits
1302 {
1303     return _page->viewportSizeForCSSViewportUnits();
1304 }
1305
1306 - (void)_setViewportSizeForCSSViewportUnits:(CGSize)viewportSize
1307 {
1308     auto viewportSizeForViewportUnits = WebCore::IntSize(viewportSize);
1309     if (viewportSizeForViewportUnits.isEmpty())
1310         [NSException raise:NSInvalidArgumentException format:@"Viewport size should not be empty"];
1311
1312     _page->setViewportSizeForCSSViewportUnits(viewportSizeForViewportUnits);
1313 }
1314
1315 static NSTextAlignment nsTextAlignment(WebKit::TextAlignment alignment)
1316 {
1317     switch (alignment) {
1318     case WebKit::NoAlignment:
1319         return NSTextAlignmentNatural;
1320     case WebKit::LeftAlignment:
1321         return NSTextAlignmentLeft;
1322     case WebKit::RightAlignment:
1323         return NSTextAlignmentRight;
1324     case WebKit::CenterAlignment:
1325         return NSTextAlignmentCenter;
1326     case WebKit::JustifiedAlignment:
1327         return NSTextAlignmentJustified;
1328     }
1329     ASSERT_NOT_REACHED();
1330     return NSTextAlignmentNatural;
1331 }
1332
1333 static NSDictionary *dictionaryRepresentationForEditorState(const WebKit::EditorState& state)
1334 {
1335     if (state.isMissingPostLayoutData)
1336         return @{ @"post-layout-data" : @NO };
1337
1338     auto& postLayoutData = state.postLayoutData();
1339     return @{
1340         @"post-layout-data" : @YES,
1341         @"bold": postLayoutData.typingAttributes & WebKit::AttributeBold ? @YES : @NO,
1342         @"italic": postLayoutData.typingAttributes & WebKit::AttributeItalics ? @YES : @NO,
1343         @"underline": postLayoutData.typingAttributes & WebKit::AttributeUnderline ? @YES : @NO,
1344         @"text-alignment": @(nsTextAlignment(static_cast<WebKit::TextAlignment>(postLayoutData.textAlignment))),
1345         @"text-color": (NSString *)postLayoutData.textColor.cssText()
1346     };
1347 }
1348
1349 static _WKSelectionAttributes selectionAttributes(const WebKit::EditorState& editorState, _WKSelectionAttributes previousAttributes)
1350 {
1351     _WKSelectionAttributes attributes = _WKSelectionAttributeNoSelection;
1352     if (editorState.selectionIsNone)
1353         return attributes;
1354
1355     if (editorState.selectionIsRange)
1356         attributes |= _WKSelectionAttributeIsRange;
1357     else
1358         attributes |= _WKSelectionAttributeIsCaret;
1359
1360     if (!editorState.isMissingPostLayoutData) {
1361 #if PLATFORM(IOS_FAMILY)
1362         if (editorState.postLayoutData().atStartOfSentence)
1363             attributes |= _WKSelectionAttributeAtStartOfSentence;
1364 #endif
1365     } else if (previousAttributes & _WKSelectionAttributeAtStartOfSentence)
1366         attributes |= _WKSelectionAttributeAtStartOfSentence;
1367
1368     return attributes;
1369 }
1370
1371 - (void)_didChangeEditorState
1372 {
1373     auto newSelectionAttributes = selectionAttributes(_page->editorState(), _selectionAttributes);
1374     if (_selectionAttributes != newSelectionAttributes) {
1375         NSString *selectionAttributesKey = NSStringFromSelector(@selector(_selectionAttributes));
1376         [self willChangeValueForKey:selectionAttributesKey];
1377         _selectionAttributes = newSelectionAttributes;
1378         [self didChangeValueForKey:selectionAttributesKey];
1379     }
1380
1381     // FIXME: We should either rename -_webView:editorStateDidChange: to clarify that it's only intended for use when testing,
1382     // or remove it entirely and use -_webView:didChangeFontAttributes: instead once text alignment is supported in the set of
1383     // font attributes.
1384     id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)self.UIDelegate;
1385     if ([uiDelegate respondsToSelector:@selector(_webView:editorStateDidChange:)])
1386         [uiDelegate _webView:self editorStateDidChange:dictionaryRepresentationForEditorState(_page->editorState())];
1387 }
1388
1389 - (_WKSelectionAttributes)_selectionAttributes
1390 {
1391     return _selectionAttributes;
1392 }
1393
1394 - (void)_showSafeBrowsingWarning:(const WebKit::SafeBrowsingWarning&)warning completionHandler:(CompletionHandler<void(Variant<WebKit::ContinueUnsafeLoad, URL>&&)>&&)completionHandler
1395 {
1396     _safeBrowsingWarning = adoptNS([[WKSafeBrowsingWarning alloc] initWithFrame:self.bounds safeBrowsingWarning:warning completionHandler:[weakSelf = WeakObjCPtr<WKWebView>(self), completionHandler = WTFMove(completionHandler)] (auto&& result) mutable {
1397         completionHandler(WTFMove(result));
1398         auto strongSelf = weakSelf.get();
1399         if (!strongSelf)
1400             return;
1401         bool navigatesFrame = WTF::switchOn(result,
1402             [] (WebKit::ContinueUnsafeLoad continueUnsafeLoad) { return continueUnsafeLoad == WebKit::ContinueUnsafeLoad::Yes; },
1403             [] (const URL&) { return true; }
1404         );
1405         bool forMainFrameNavigation = [strongSelf->_safeBrowsingWarning forMainFrameNavigation];
1406         if (navigatesFrame && forMainFrameNavigation) {
1407             // The safe browsing warning will be hidden once the next page is shown.
1408             return;
1409         }
1410         if (!navigatesFrame && strongSelf->_safeBrowsingWarning && !forMainFrameNavigation) {
1411             strongSelf->_page->goBack();
1412             return;
1413         }
1414         [std::exchange(strongSelf->_safeBrowsingWarning, nullptr) removeFromSuperview];
1415     }]);
1416     [self addSubview:_safeBrowsingWarning.get()];
1417 }
1418
1419 - (void)_clearSafeBrowsingWarning
1420 {
1421     [std::exchange(_safeBrowsingWarning, nullptr) removeFromSuperview];
1422 }
1423
1424 - (void)_clearSafeBrowsingWarningIfForMainFrameNavigation
1425 {
1426     if ([_safeBrowsingWarning forMainFrameNavigation])
1427         [self _clearSafeBrowsingWarning];
1428 }
1429
1430 #if ENABLE(ATTACHMENT_ELEMENT)
1431
1432 - (void)_didInsertAttachment:(API::Attachment&)attachment withSource:(NSString *)source
1433 {
1434     id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)self.UIDelegate;
1435     if ([uiDelegate respondsToSelector:@selector(_webView:didInsertAttachment:withSource:)])
1436         [uiDelegate _webView:self didInsertAttachment:wrapper(attachment) withSource:source];
1437 }
1438
1439 - (void)_didRemoveAttachment:(API::Attachment&)attachment
1440 {
1441     id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)self.UIDelegate;
1442     if ([uiDelegate respondsToSelector:@selector(_webView:didRemoveAttachment:)])
1443         [uiDelegate _webView:self didRemoveAttachment:wrapper(attachment)];
1444 }
1445
1446 - (void)_didInvalidateDataForAttachment:(API::Attachment&)attachment
1447 {
1448     id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)self.UIDelegate;
1449     if ([uiDelegate respondsToSelector:@selector(_webView:didInvalidateDataForAttachment:)])
1450         [uiDelegate _webView:self didInvalidateDataForAttachment:wrapper(attachment)];
1451 }
1452
1453 #endif // ENABLE(ATTACHMENT_ELEMENT)
1454
1455 #pragma mark iOS-specific methods
1456
1457 #if PLATFORM(IOS_FAMILY)
1458
1459 - (BOOL)_contentViewIsFirstResponder
1460 {
1461     return self._currentContentView.isFirstResponder;
1462 }
1463
1464 - (BOOL)_shouldAvoidResizingWhenInputViewBoundsChange
1465 {
1466     return [_contentView _shouldAvoidResizingWhenInputViewBoundsChange];
1467 }
1468
1469 - (_WKDragInteractionPolicy)_dragInteractionPolicy
1470 {
1471     return _dragInteractionPolicy;
1472 }
1473
1474 - (void)_setDragInteractionPolicy:(_WKDragInteractionPolicy)policy
1475 {
1476     if (_dragInteractionPolicy == policy)
1477         return;
1478
1479     _dragInteractionPolicy = policy;
1480 #if ENABLE(DRAG_SUPPORT)
1481     [_contentView _didChangeDragInteractionPolicy];
1482 #endif
1483 }
1484
1485 - (void)_populateArchivedSubviews:(NSMutableSet *)encodedViews
1486 {
1487     [super _populateArchivedSubviews:encodedViews];
1488
1489     if (_scrollView)
1490         [encodedViews removeObject:_scrollView.get()];
1491     if (_customContentFixedOverlayView)
1492         [encodedViews removeObject:_customContentFixedOverlayView.get()];
1493 }
1494
1495 - (BOOL)_isBackground
1496 {
1497     if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_isBackground)])
1498         return [_customContentView web_isBackground];
1499     return [_contentView isBackground];
1500 }
1501
1502 - (void)setFrame:(CGRect)frame
1503 {
1504     CGRect oldFrame = self.frame;
1505     [super setFrame:frame];
1506
1507     if (!CGSizeEqualToSize(oldFrame.size, frame.size))
1508         [self _frameOrBoundsChanged];
1509 }
1510
1511 - (void)setBounds:(CGRect)bounds
1512 {
1513     CGRect oldBounds = self.bounds;
1514     [super setBounds:bounds];
1515     [_customContentFixedOverlayView setFrame:self.bounds];
1516
1517     if (!CGSizeEqualToSize(oldBounds.size, bounds.size))
1518         [self _frameOrBoundsChanged];
1519 }
1520
1521 - (void)layoutSubviews
1522 {
1523     [_safeBrowsingWarning setFrame:self.bounds];
1524     [super layoutSubviews];
1525     [self _frameOrBoundsChanged];
1526 }
1527
1528 - (UIScrollView *)scrollView
1529 {
1530     return _scrollView.get();
1531 }
1532
1533 ALLOW_DEPRECATED_DECLARATIONS_BEGIN
1534 - (WKBrowsingContextController *)browsingContextController
1535 {
1536     return [_contentView browsingContextController];
1537 }
1538 ALLOW_DEPRECATED_DECLARATIONS_END
1539
1540 - (BOOL)becomeFirstResponder
1541 {
1542     UIView *currentContentView = self._currentContentView;
1543     if (currentContentView == _contentView && [_contentView superview])
1544         return [_contentView becomeFirstResponderForWebView] || [super becomeFirstResponder];
1545
1546     return [currentContentView becomeFirstResponder] || [super becomeFirstResponder];
1547 }
1548
1549 - (BOOL)canBecomeFirstResponder
1550 {
1551     if (self._currentContentView == _contentView)
1552         return [_contentView canBecomeFirstResponderForWebView];
1553
1554     return YES;
1555 }
1556
1557 - (BOOL)resignFirstResponder
1558 {
1559     if ([_contentView isFirstResponder])
1560         return [_contentView resignFirstResponderForWebView];
1561
1562     return [super resignFirstResponder];
1563 }
1564
1565 FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_ACTION_TO_WKCONTENTVIEW)
1566
1567 - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
1568 {
1569     #define FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW(_action) \
1570         if (action == @selector(_action:)) \
1571             return self.usesStandardContentView && [_contentView canPerformActionForWebView:action withSender:sender];
1572
1573     FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW)
1574     FOR_EACH_PRIVATE_WKCONTENTVIEW_ACTION(FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW)
1575     FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW(_setTextColor:sender)
1576     FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW(_setFontSize:sender)
1577     FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW(_setFont:sender)
1578
1579     #undef FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW
1580
1581     return [super canPerformAction:action withSender:sender];
1582 }
1583
1584 - (id)targetForAction:(SEL)action withSender:(id)sender
1585 {
1586     #define FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_action) \
1587         if (action == @selector(_action:) && self.usesStandardContentView) \
1588             return [_contentView targetForActionForWebView:action withSender:sender];
1589
1590     FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW)
1591     FOR_EACH_PRIVATE_WKCONTENTVIEW_ACTION(FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW)
1592     FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_setTextColor:sender)
1593     FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_setFontSize:sender)
1594     FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_setFont:sender)
1595
1596     #undef FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW
1597
1598     return [super targetForAction:action withSender:sender];
1599 }
1600
1601 - (void)willFinishIgnoringCalloutBarFadeAfterPerformingAction
1602 {
1603     [_contentView willFinishIgnoringCalloutBarFadeAfterPerformingAction];
1604 }
1605
1606 static inline CGFloat floorToDevicePixel(CGFloat input, float deviceScaleFactor)
1607 {
1608     return CGFloor(input * deviceScaleFactor) / deviceScaleFactor;
1609 }
1610
1611 static inline bool pointsEqualInDevicePixels(CGPoint a, CGPoint b, float deviceScaleFactor)
1612 {
1613     return fabs(a.x * deviceScaleFactor - b.x * deviceScaleFactor) < std::numeric_limits<float>::epsilon()
1614         && fabs(a.y * deviceScaleFactor - b.y * deviceScaleFactor) < std::numeric_limits<float>::epsilon();
1615 }
1616
1617 static CGSize roundScrollViewContentSize(const WebKit::WebPageProxy& page, CGSize contentSize)
1618 {
1619     float deviceScaleFactor = page.deviceScaleFactor();
1620     return CGSizeMake(floorToDevicePixel(contentSize.width, deviceScaleFactor), floorToDevicePixel(contentSize.height, deviceScaleFactor));
1621 }
1622
1623 - (UIView *)_currentContentView
1624 {
1625     return _customContentView ? [_customContentView web_contentView] : _contentView.get();
1626 }
1627
1628 - (WKWebViewContentProviderRegistry *)_contentProviderRegistry
1629 {
1630     return [_configuration _contentProviderRegistry];
1631 }
1632
1633 - (WKSelectionGranularity)_selectionGranularity
1634 {
1635     return [_configuration selectionGranularity];
1636 }
1637
1638 - (void)_setHasCustomContentView:(BOOL)pageHasCustomContentView loadedMIMEType:(const WTF::String&)mimeType
1639 {
1640     if (pageHasCustomContentView) {
1641         [_customContentView removeFromSuperview];
1642         [_customContentFixedOverlayView removeFromSuperview];
1643
1644         Class representationClass = [[_configuration _contentProviderRegistry] providerForMIMEType:mimeType];
1645         ASSERT(representationClass);
1646         _customContentView = adoptNS([[representationClass alloc] web_initWithFrame:self.bounds webView:self mimeType:mimeType]);
1647         _customContentFixedOverlayView = adoptNS([[UIView alloc] initWithFrame:self.bounds]);
1648         [_customContentFixedOverlayView layer].name = @"CustomContentFixedOverlay";
1649         [_customContentFixedOverlayView setUserInteractionEnabled:NO];
1650
1651         [[_contentView unscaledView] removeFromSuperview];
1652         [_contentView removeFromSuperview];
1653         [_scrollView addSubview:_customContentView.get()];
1654         [self addSubview:_customContentFixedOverlayView.get()];
1655
1656         [_customContentView web_setMinimumSize:self.bounds.size];
1657         [_customContentView web_setFixedOverlayView:_customContentFixedOverlayView.get()];
1658
1659         _scrollViewBackgroundColor = WebCore::Color();
1660         [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1661         [_scrollView _setScrollEnabledInternal:YES];
1662
1663         [self _setAvoidsUnsafeArea:NO];
1664     } else if (_customContentView) {
1665         [_customContentView removeFromSuperview];
1666         _customContentView = nullptr;
1667
1668         [_customContentFixedOverlayView removeFromSuperview];
1669         _customContentFixedOverlayView = nullptr;
1670
1671         [_scrollView addSubview:_contentView.get()];
1672         [_scrollView addSubview:[_contentView unscaledView]];
1673         [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
1674
1675         [_customContentFixedOverlayView setFrame:self.bounds];
1676         [self addSubview:_customContentFixedOverlayView.get()];
1677     }
1678
1679     if (self.isFirstResponder) {
1680         UIView *currentContentView = self._currentContentView;
1681         if (currentContentView == _contentView ? [_contentView canBecomeFirstResponderForWebView] : currentContentView.canBecomeFirstResponder)
1682             [currentContentView becomeFirstResponder];
1683     }
1684 }
1685
1686 - (void)_didFinishLoadingDataForCustomContentProviderWithSuggestedFilename:(const String&)suggestedFilename data:(NSData *)data
1687 {
1688     ASSERT(_customContentView);
1689     [_customContentView web_setContentProviderData:data suggestedFilename:suggestedFilename];
1690
1691     // FIXME: It may make more sense for custom content providers to invoke this when they're ready,
1692     // because there's no guarantee that all custom content providers will lay out synchronously.
1693     _page->didLayoutForCustomContentProvider();
1694 }
1695
1696 - (void)_handleKeyUIEvent:(::UIEvent *)event
1697 {
1698     // We only want to handle key events from the hardware keyboard when we are
1699     // first responder and a custom content view is installed; otherwise,
1700     // WKContentView will be the first responder and expects to get key events directly.
1701     if ([self isFirstResponder] && event._hidEvent) {
1702         if ([_customContentView respondsToSelector:@selector(web_handleKeyEvent:)]) {
1703             if ([_customContentView web_handleKeyEvent:event])
1704                 return;
1705         }
1706     }
1707
1708     [super _handleKeyUIEvent:event];
1709 }
1710
1711 - (void)_willInvokeUIScrollViewDelegateCallback
1712 {
1713     _invokingUIScrollViewDelegateCallback = YES;
1714 }
1715
1716 - (void)_didInvokeUIScrollViewDelegateCallback
1717 {
1718     _invokingUIScrollViewDelegateCallback = NO;
1719     if (_didDeferUpdateVisibleContentRectsForUIScrollViewDelegateCallback) {
1720         _didDeferUpdateVisibleContentRectsForUIScrollViewDelegateCallback = NO;
1721         [self _scheduleVisibleContentRectUpdate];
1722     }
1723 }
1724
1725 static CGFloat contentZoomScale(WKWebView *webView)
1726 {
1727     CGFloat scale = webView._currentContentView.layer.affineTransform.a;
1728     ASSERT(scale == [webView->_scrollView zoomScale]);
1729     return scale;
1730 }
1731
1732 static WebCore::Color baseScrollViewBackgroundColor(WKWebView *webView)
1733 {
1734     if (webView->_customContentView)
1735         return [webView->_customContentView backgroundColor].CGColor;
1736
1737     if (webView->_gestureController) {
1738         WebCore::Color color = webView->_gestureController->backgroundColorForCurrentSnapshot();
1739         if (color.isValid())
1740             return color;
1741     }
1742
1743     if (!webView->_page)
1744         return { };
1745
1746     return webView->_page->pageExtendedBackgroundColor();
1747 }
1748
1749 static WebCore::Color scrollViewBackgroundColor(WKWebView *webView)
1750 {
1751     if (!webView.opaque)
1752         return WebCore::Color::transparent;
1753
1754 #if HAVE(OS_DARK_MODE_SUPPORT)
1755     WebCore::LocalCurrentTraitCollection localTraitCollection(webView.traitCollection);
1756 #endif
1757
1758     WebCore::Color color = baseScrollViewBackgroundColor(webView);
1759
1760     if (!color.isValid() && webView->_contentView)
1761         color = [webView->_contentView backgroundColor].CGColor;
1762
1763     if (!color.isValid()) {
1764 #if HAVE(OS_DARK_MODE_SUPPORT)
1765         color = UIColor.systemBackgroundColor.CGColor;
1766 #else
1767         color = WebCore::Color::white;
1768 #endif
1769     }
1770
1771     CGFloat zoomScale = contentZoomScale(webView);
1772     CGFloat minimumZoomScale = [webView->_scrollView minimumZoomScale];
1773     if (zoomScale < minimumZoomScale) {
1774         CGFloat slope = 12;
1775         CGFloat opacity = std::max<CGFloat>(1 - slope * (minimumZoomScale - zoomScale), 0);
1776         color = WebCore::colorWithOverrideAlpha(color.rgb(), opacity);
1777     }
1778
1779     return color;
1780 }
1781
1782 - (void)_updateScrollViewBackground
1783 {
1784     WebCore::Color color = scrollViewBackgroundColor(self);
1785
1786     if (_scrollViewBackgroundColor == color)
1787         return;
1788
1789     _scrollViewBackgroundColor = color;
1790
1791     auto uiBackgroundColor = adoptNS([[UIColor alloc] initWithCGColor:cachedCGColor(color)]);
1792     [_scrollView setBackgroundColor:uiBackgroundColor.get()];
1793
1794     // Update the indicator style based on the lightness/darkness of the background color.
1795     double hue, saturation, lightness;
1796     color.getHSL(hue, saturation, lightness);
1797     if (lightness <= .5 && color.isVisible())
1798         [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleWhite];
1799     else
1800         [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleBlack];
1801 }
1802
1803 - (void)_videoControlsManagerDidChange
1804 {
1805 #if ENABLE(FULLSCREEN_API)
1806     if (_fullScreenWindowController)
1807         [_fullScreenWindowController videoControlsManagerDidChange];
1808 #endif
1809 }
1810
1811 - (CGPoint)_initialContentOffsetForScrollView
1812 {
1813     auto combinedUnobscuredAndScrollViewInset = [self _computedContentInset];
1814     return CGPointMake(-combinedUnobscuredAndScrollViewInset.left, -combinedUnobscuredAndScrollViewInset.top);
1815 }
1816
1817 - (CGPoint)_contentOffsetAdjustedForObscuredInset:(CGPoint)point
1818 {
1819     CGPoint result = point;
1820     UIEdgeInsets contentInset = [self _computedObscuredInset];
1821
1822     result.x -= contentInset.left;
1823     result.y -= contentInset.top;
1824
1825     return result;
1826 }
1827
1828 - (UIRectEdge)_effectiveObscuredInsetEdgesAffectedBySafeArea
1829 {
1830     if (![self usesStandardContentView])
1831         return UIRectEdgeAll;
1832     return _obscuredInsetEdgesAffectedBySafeArea;
1833 }
1834
1835 - (UIEdgeInsets)_computedObscuredInset
1836 {
1837     if (!linkedOnOrAfter(WebKit::SDKVersion::FirstWhereScrollViewContentInsetsAreNotObscuringInsets)) {
1838         // For binary compability with third party apps, treat scroll view content insets as obscuring insets when the app is compiled
1839         // against a WebKit version without the fix in r229641.
1840         return [self _computedContentInset];
1841     }
1842
1843     if (_haveSetObscuredInsets)
1844         return _obscuredInsets;
1845
1846 #if PLATFORM(IOS)
1847     if (self._safeAreaShouldAffectObscuredInsets)
1848         return UIEdgeInsetsAdd(UIEdgeInsetsZero, self._scrollViewSystemContentInset, self._effectiveObscuredInsetEdgesAffectedBySafeArea);
1849 #endif
1850
1851     return UIEdgeInsetsZero;
1852 }
1853
1854 - (UIEdgeInsets)_computedContentInset
1855 {
1856     if (_haveSetObscuredInsets)
1857         return _obscuredInsets;
1858
1859     UIEdgeInsets insets = [_scrollView contentInset];
1860
1861 #if PLATFORM(IOS)
1862     if (self._safeAreaShouldAffectObscuredInsets)
1863         insets = UIEdgeInsetsAdd(insets, self._scrollViewSystemContentInset, self._effectiveObscuredInsetEdgesAffectedBySafeArea);
1864 #endif
1865
1866     return insets;
1867 }
1868
1869 - (UIEdgeInsets)_computedUnobscuredSafeAreaInset
1870 {
1871     if (_haveSetUnobscuredSafeAreaInsets)
1872         return _unobscuredSafeAreaInsets;
1873
1874 #if PLATFORM(IOS)
1875     if (!self._safeAreaShouldAffectObscuredInsets)
1876         return self.safeAreaInsets;
1877 #endif
1878
1879     return UIEdgeInsetsZero;
1880 }
1881
1882 - (void)_processWillSwapOrDidExit
1883 {
1884     // FIXME: Which ones of these need to be done in the process swap case and which ones in the exit case?
1885     [self _hidePasswordView];
1886     [self _cancelAnimatedResize];
1887
1888     if (_gestureController)
1889         _gestureController->disconnectFromProcess();
1890
1891     _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
1892     _initialScaleFactor = 1;
1893     _hasCommittedLoadForMainFrame = NO;
1894     _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1895     _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
1896     _waitingForEndAnimatedResize = NO;
1897     _waitingForCommitAfterAnimatedResize = NO;
1898     _animatedResizeOriginalContentWidth = 0;
1899     [_contentView setHidden:NO];
1900     _scrollOffsetToRestore = WTF::nullopt;
1901     _unobscuredCenterToRestore = WTF::nullopt;
1902     _scrollViewBackgroundColor = WebCore::Color();
1903     _invokingUIScrollViewDelegateCallback = NO;
1904     _didDeferUpdateVisibleContentRectsForUIScrollViewDelegateCallback = NO;
1905     _didDeferUpdateVisibleContentRectsForAnyReason = NO;
1906     _didDeferUpdateVisibleContentRectsForUnstableScrollView = NO;
1907     _currentlyAdjustingScrollViewInsetsForKeyboard = NO;
1908     _lastSentViewLayoutSize = WTF::nullopt;
1909     _lastSentMaximumUnobscuredSize = WTF::nullopt;
1910     _lastSentDeviceOrientation = WTF::nullopt;
1911
1912     _frozenVisibleContentRect = WTF::nullopt;
1913     _frozenUnobscuredContentRect = WTF::nullopt;
1914
1915     _firstPaintAfterCommitLoadTransactionID = { };
1916     _firstTransactionIDAfterPageRestore = WTF::nullopt;
1917
1918     _lastTransactionID = { };
1919
1920     _hasScheduledVisibleRectUpdate = NO;
1921     _commitDidRestoreScrollPosition = NO;
1922
1923     _avoidsUnsafeArea = YES;
1924 }
1925
1926 - (void)_processWillSwap
1927 {
1928     RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _processWillSwap]", self);
1929     [self _processWillSwapOrDidExit];
1930 }
1931
1932 - (void)_processDidExit
1933 {
1934     RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _processDidExit]", self);
1935
1936     [self _processWillSwapOrDidExit];
1937
1938     [_contentView setFrame:self.bounds];
1939     [_scrollView setBackgroundColor:[_contentView backgroundColor]];
1940     [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1941     [_scrollView setZoomScale:1];
1942 }
1943
1944 - (void)_didRelaunchProcess
1945 {
1946     RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didRelaunchProcess]", self);
1947     _hasScheduledVisibleRectUpdate = NO;
1948     _visibleContentRectUpdateScheduledFromScrollViewInStableState = YES;
1949     if (_gestureController)
1950         _gestureController->connectToProcess();
1951 }
1952
1953 - (void)_didCommitLoadForMainFrame
1954 {
1955     _firstPaintAfterCommitLoadTransactionID = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1956
1957     _hasCommittedLoadForMainFrame = YES;
1958     _needsResetViewStateAfterCommitLoadForMainFrame = YES;
1959
1960     [_scrollView _stopScrollingAndZoomingAnimations];
1961 }
1962
1963 static CGPoint contentOffsetBoundedInValidRange(UIScrollView *scrollView, CGPoint contentOffset)
1964 {
1965 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1966     UIEdgeInsets contentInsets = scrollView.adjustedContentInset;
1967 #else
1968     UIEdgeInsets contentInsets = scrollView.contentInset;
1969 #endif
1970
1971     CGSize contentSize = scrollView.contentSize;
1972     CGSize scrollViewSize = scrollView.bounds.size;
1973
1974     CGPoint minimumContentOffset = CGPointMake(-contentInsets.left, -contentInsets.top);
1975     CGPoint maximumContentOffset = CGPointMake(std::max(minimumContentOffset.x, contentSize.width + contentInsets.right - scrollViewSize.width), std::max(minimumContentOffset.y, contentSize.height + contentInsets.bottom - scrollViewSize.height));
1976
1977     return CGPointMake(std::max(std::min(contentOffset.x, maximumContentOffset.x), minimumContentOffset.x), std::max(std::min(contentOffset.y, maximumContentOffset.y), minimumContentOffset.y));
1978 }
1979
1980 static void changeContentOffsetBoundedInValidRange(UIScrollView *scrollView, WebCore::FloatPoint contentOffset)
1981 {
1982     scrollView.contentOffset = contentOffsetBoundedInValidRange(scrollView, contentOffset);
1983 }
1984
1985 - (WebCore::FloatRect)visibleRectInViewCoordinates
1986 {
1987     WebCore::FloatRect bounds = self.bounds;
1988     bounds.moveBy([_scrollView contentOffset]);
1989     WebCore::FloatRect contentViewBounds = [_contentView bounds];
1990     bounds.intersect(contentViewBounds);
1991     return bounds;
1992 }
1993
1994 // WebCore stores the page scale factor as float instead of double. When we get a scale from WebCore,
1995 // we need to ignore differences that are within a small rounding error on floats.
1996 static inline bool areEssentiallyEqualAsFloat(float a, float b)
1997 {
1998     return WTF::areEssentiallyEqual(a, b);
1999 }
2000
2001 - (void)_didCommitLayerTreeDuringAnimatedResize:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
2002 {
2003     auto updateID = layerTreeTransaction.dynamicViewportSizeUpdateID();
2004     if (updateID && *updateID == _currentDynamicViewportSizeUpdateID) {
2005         double pageScale = layerTreeTransaction.pageScaleFactor();
2006         WebCore::IntPoint scrollPosition = layerTreeTransaction.scrollPosition();
2007
2008         CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
2009         double currentTargetScale = animatingScaleTarget * [[_contentView layer] transform].m11;
2010         double scale = pageScale / currentTargetScale;
2011         _resizeAnimationTransformAdjustments = CATransform3DMakeScale(scale, scale, 1);
2012
2013         CGPoint newContentOffset = [self _contentOffsetAdjustedForObscuredInset:CGPointMake(scrollPosition.x() * pageScale, scrollPosition.y() * pageScale)];
2014         CGPoint currentContentOffset = [_scrollView contentOffset];
2015
2016         _resizeAnimationTransformAdjustments.m41 = (currentContentOffset.x - newContentOffset.x) / animatingScaleTarget;
2017         _resizeAnimationTransformAdjustments.m42 = (currentContentOffset.y - newContentOffset.y) / animatingScaleTarget;
2018
2019         [_resizeAnimationView layer].sublayerTransform = _resizeAnimationTransformAdjustments;
2020
2021         // If we've already passed endAnimatedResize, immediately complete
2022         // the resize when we have an up-to-date layer tree. Otherwise,
2023         // we will defer completion until endAnimatedResize.
2024         _waitingForCommitAfterAnimatedResize = NO;
2025         if (!_waitingForEndAnimatedResize)
2026             [self _didCompleteAnimatedResize];
2027
2028         return;
2029     }
2030
2031     // If a commit arrives during the live part of a resize but before the
2032     // layer tree takes the current resize into account, it could change the
2033     // WKContentView's size. Update the resizeAnimationView's scale to ensure
2034     // we continue to fill the width of the resize target.
2035
2036     if (_waitingForEndAnimatedResize)
2037         return;
2038
2039     auto newViewLayoutSize = [self activeViewLayoutSize:self.bounds];
2040     CGFloat resizeAnimationViewScale = _animatedResizeOriginalContentWidth / newViewLayoutSize.width();
2041     [[_resizeAnimationView layer] setSublayerTransform:CATransform3DMakeScale(resizeAnimationViewScale, resizeAnimationViewScale, 1)];
2042 }
2043
2044 - (void)_didCommitLayerTree:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
2045 {
2046     if (_didDeferUpdateVisibleContentRectsForUnstableScrollView) {
2047         RELEASE_LOG_IF_ALLOWED("%p (pageProxyID=%llu) -[WKWebView _didCommitLayerTree:] - received a commit (%llu) while deferring visible content rect updates (_dynamicViewportUpdateMode %d, _needsResetViewStateAfterCommitLoadForMainFrame %d (wants commit %llu), sizeChangedSinceLastVisibleContentRectUpdate %d, [_scrollView isZoomBouncing] %d, _currentlyAdjustingScrollViewInsetsForKeyboard %d)",
2048         self, _page->identifier().toUInt64(), layerTreeTransaction.transactionID().toUInt64(), _dynamicViewportUpdateMode, _needsResetViewStateAfterCommitLoadForMainFrame, _firstPaintAfterCommitLoadTransactionID.toUInt64(), [_contentView sizeChangedSinceLastVisibleContentRectUpdate], [_scrollView isZoomBouncing], _currentlyAdjustingScrollViewInsetsForKeyboard);
2049     }
2050
2051     if (_timeOfFirstVisibleContentRectUpdateWithPendingCommit) {
2052         auto timeSinceFirstRequestWithPendingCommit = MonotonicTime::now() - *_timeOfFirstVisibleContentRectUpdateWithPendingCommit;
2053         if (timeSinceFirstRequestWithPendingCommit > delayBeforeNoCommitsLogging)
2054             RELEASE_LOG_IF_ALLOWED("%p (pageProxyID=%llu) -[WKWebView _didCommitLayerTree:] - finally received commit %.2fs after visible content rect update request; transactionID %llu", self, _page->identifier().toUInt64(), timeSinceFirstRequestWithPendingCommit.value(), layerTreeTransaction.transactionID().toUInt64());
2055         _timeOfFirstVisibleContentRectUpdateWithPendingCommit = WTF::nullopt;
2056     }
2057
2058     _lastTransactionID = layerTreeTransaction.transactionID();
2059
2060     if (![self usesStandardContentView])
2061         return;
2062
2063     LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->identifier() << " _didCommitLayerTree:] transactionID " << layerTreeTransaction.transactionID() << " _dynamicViewportUpdateMode " << (int)_dynamicViewportUpdateMode);
2064
2065     bool needUpdateVisibleContentRects = _page->updateLayoutViewportParameters(layerTreeTransaction);
2066
2067     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing) {
2068         [self _didCommitLayerTreeDuringAnimatedResize:layerTreeTransaction];
2069         return;
2070     }
2071
2072     if (_resizeAnimationView)
2073         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didCommitLayerTree:] - dynamicViewportUpdateMode is NotResizing, but still have a live resizeAnimationView (unpaired begin/endAnimatedResize?)", self);
2074
2075     CGSize newContentSize = roundScrollViewContentSize(*_page, [_contentView frame].size);
2076     [_scrollView _setContentSizePreservingContentOffsetDuringRubberband:newContentSize];
2077
2078     [_scrollView setMinimumZoomScale:layerTreeTransaction.minimumScaleFactor()];
2079     [_scrollView setMaximumZoomScale:layerTreeTransaction.maximumScaleFactor()];
2080     [_scrollView _setZoomEnabledInternal:layerTreeTransaction.allowsUserScaling()];
2081 #if ENABLE(ASYNC_SCROLLING)
2082     bool hasDockedInputView = !CGRectIsEmpty(_inputViewBounds);
2083     bool isZoomed = layerTreeTransaction.pageScaleFactor() > layerTreeTransaction.initialScaleFactor();
2084
2085     bool scrollingNeededToRevealUI = false;
2086     if (_maximumUnobscuredSizeOverride) {
2087         auto unobscuredContentRect = _page->unobscuredContentRect();
2088         auto maxUnobscuredSize = _page->maximumUnobscuredSize();
2089         scrollingNeededToRevealUI = maxUnobscuredSize.width() == unobscuredContentRect.width() && maxUnobscuredSize.height() == unobscuredContentRect.height();
2090     }
2091
2092     bool scrollingEnabled = _page->scrollingCoordinatorProxy()->hasScrollableMainFrame() || hasDockedInputView || isZoomed || scrollingNeededToRevealUI;
2093     [_scrollView _setScrollEnabledInternal:scrollingEnabled];
2094 #endif
2095     if (!layerTreeTransaction.scaleWasSetByUIProcess() && ![_scrollView isZooming] && ![_scrollView isZoomBouncing] && ![_scrollView _isAnimatingZoom] && [_scrollView zoomScale] != layerTreeTransaction.pageScaleFactor()) {
2096         LOG_WITH_STREAM(VisibleRects, stream << " updating scroll view with pageScaleFactor " << layerTreeTransaction.pageScaleFactor());
2097         [_scrollView setZoomScale:layerTreeTransaction.pageScaleFactor()];
2098     }
2099
2100     _viewportMetaTagWidth = layerTreeTransaction.viewportMetaTagWidth();
2101     _viewportMetaTagWidthWasExplicit = layerTreeTransaction.viewportMetaTagWidthWasExplicit();
2102     _viewportMetaTagCameFromImageDocument = layerTreeTransaction.viewportMetaTagCameFromImageDocument();
2103     _initialScaleFactor = layerTreeTransaction.initialScaleFactor();
2104     if (_page->inStableState() && layerTreeTransaction.isInStableState() && [_stableStatePresentationUpdateCallbacks count]) {
2105         for (dispatch_block_t action in _stableStatePresentationUpdateCallbacks.get())
2106             action();
2107
2108         [_stableStatePresentationUpdateCallbacks removeAllObjects];
2109         _stableStatePresentationUpdateCallbacks = nil;
2110     }
2111
2112     if (![_contentView _mayDisableDoubleTapGesturesDuringSingleTap])
2113         [_contentView _setDoubleTapGesturesEnabled:self._allowsDoubleTapGestures];
2114
2115     [self _updateScrollViewBackground];
2116     [self _setAvoidsUnsafeArea:layerTreeTransaction.avoidsUnsafeArea()];
2117
2118     if (_gestureController)
2119         _gestureController->setRenderTreeSize(layerTreeTransaction.renderTreeSize());
2120
2121     if (_needsResetViewStateAfterCommitLoadForMainFrame && layerTreeTransaction.transactionID() >= _firstPaintAfterCommitLoadTransactionID) {
2122         _needsResetViewStateAfterCommitLoadForMainFrame = NO;
2123         [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
2124         if (_observedRenderingProgressEvents & _WKRenderingProgressEventFirstPaint)
2125             _navigationState->didFirstPaint();
2126
2127         needUpdateVisibleContentRects = true;
2128     }
2129
2130     if (_firstTransactionIDAfterPageRestore && layerTreeTransaction.transactionID() >= _firstTransactionIDAfterPageRestore.value()) {
2131         if (_scrollOffsetToRestore) {
2132             WebCore::FloatPoint scaledScrollOffset = _scrollOffsetToRestore.value();
2133             _scrollOffsetToRestore = WTF::nullopt;
2134
2135             if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
2136                 scaledScrollOffset.scale(_scaleToRestore);
2137                 WebCore::FloatPoint contentOffsetInScrollViewCoordinates = scaledScrollOffset - WebCore::FloatSize(_obscuredInsetsWhenSaved.left(), _obscuredInsetsWhenSaved.top());
2138
2139                 changeContentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
2140                 _commitDidRestoreScrollPosition = YES;
2141             }
2142
2143             needUpdateVisibleContentRects = true;
2144         }
2145
2146         if (_unobscuredCenterToRestore) {
2147             WebCore::FloatPoint unobscuredCenterToRestore = _unobscuredCenterToRestore.value();
2148             _unobscuredCenterToRestore = WTF::nullopt;
2149
2150             if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
2151                 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, _obscuredInsets);
2152                 WebCore::FloatSize unobscuredContentSizeAtNewScale = WebCore::FloatSize(unobscuredRect.size) / _scaleToRestore;
2153                 WebCore::FloatPoint topLeftInDocumentCoordinates = unobscuredCenterToRestore - unobscuredContentSizeAtNewScale / 2;
2154
2155                 topLeftInDocumentCoordinates.scale(_scaleToRestore);
2156                 topLeftInDocumentCoordinates.moveBy(WebCore::FloatPoint(-_obscuredInsets.left, -_obscuredInsets.top));
2157
2158                 changeContentOffsetBoundedInValidRange(_scrollView.get(), topLeftInDocumentCoordinates);
2159             }
2160
2161             needUpdateVisibleContentRects = true;
2162         }
2163
2164         if (_gestureController)
2165             _gestureController->didRestoreScrollPosition();
2166
2167         _firstTransactionIDAfterPageRestore = WTF::nullopt;
2168     }
2169
2170     if (needUpdateVisibleContentRects)
2171         [self _scheduleVisibleContentRectUpdate];
2172
2173     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
2174         scrollPerfData->didCommitLayerTree([self visibleRectInViewCoordinates]);
2175 }
2176
2177 - (void)_layerTreeCommitComplete
2178 {
2179     _commitDidRestoreScrollPosition = NO;
2180 }
2181
2182 - (void)_couldNotRestorePageState
2183 {
2184     // The gestureController may be waiting for the scroll position to be restored
2185     // in order to remove the swipe snapshot. Since the scroll position could not be
2186     // restored, tell the gestureController it was restored so that it no longer waits
2187     // for it.
2188     if (_gestureController)
2189         _gestureController->didRestoreScrollPosition();
2190 }
2191
2192 - (void)_restorePageScrollPosition:(Optional<WebCore::FloatPoint>)scrollPosition scrollOrigin:(WebCore::FloatPoint)scrollOrigin previousObscuredInset:(WebCore::FloatBoxExtent)obscuredInsets scale:(double)scale
2193 {
2194     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing) {
2195         // Defer scroll position restoration until after the current resize completes.
2196         RetainPtr<WKWebView> retainedSelf = self;
2197         _callbacksDeferredDuringResize.append([retainedSelf, scrollPosition, scrollOrigin, obscuredInsets, scale] {
2198             [retainedSelf _restorePageScrollPosition:scrollPosition scrollOrigin:scrollOrigin previousObscuredInset:obscuredInsets scale:scale];
2199         });
2200         return;
2201     }
2202
2203     if (![self usesStandardContentView])
2204         return;
2205
2206     _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
2207     if (scrollPosition)
2208         _scrollOffsetToRestore = WebCore::ScrollableArea::scrollOffsetFromPosition(WebCore::FloatPoint(scrollPosition.value()), WebCore::toFloatSize(scrollOrigin));
2209     else
2210         _scrollOffsetToRestore = WTF::nullopt;
2211
2212     _obscuredInsetsWhenSaved = obscuredInsets;
2213     _scaleToRestore = scale;
2214 }
2215
2216 - (void)_restorePageStateToUnobscuredCenter:(Optional<WebCore::FloatPoint>)center scale:(double)scale
2217 {
2218     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing) {
2219         // Defer scroll position restoration until after the current resize completes.
2220         RetainPtr<WKWebView> retainedSelf = self;
2221         _callbacksDeferredDuringResize.append([retainedSelf, center, scale] {
2222             [retainedSelf _restorePageStateToUnobscuredCenter:center scale:scale];
2223         });
2224         return;
2225     }
2226
2227     if (![self usesStandardContentView])
2228         return;
2229
2230     _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
2231     _unobscuredCenterToRestore = center;
2232
2233     _scaleToRestore = scale;
2234 }
2235
2236 - (RefPtr<WebKit::ViewSnapshot>)_takeViewSnapshot
2237 {
2238 #if HAVE(CORE_ANIMATION_RENDER_SERVER)
2239     float deviceScale = WebCore::screenScaleFactor();
2240     WebCore::FloatSize snapshotSize(self.bounds.size);
2241     snapshotSize.scale(deviceScale);
2242
2243     CATransform3D transform = CATransform3DMakeScale(deviceScale, deviceScale, 1);
2244
2245 #if HAVE(IOSURFACE)
2246 #if HAVE(IOSURFACE_RGB10)
2247     WebCore::IOSurface::Format snapshotFormat = WebCore::screenSupportsExtendedColor() ? WebCore::IOSurface::Format::RGB10 : WebCore::IOSurface::Format::RGBA;
2248 #else
2249     WebCore::IOSurface::Format snapshotFormat = WebCore::IOSurface::Format::RGBA;
2250 #endif
2251     auto surface = WebCore::IOSurface::create(WebCore::expandedIntSize(snapshotSize), WebCore::sRGBColorSpaceRef(), snapshotFormat);
2252     if (!surface)
2253         return nullptr;
2254     CARenderServerRenderLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, reinterpret_cast<uint64_t>(self.layer), surface->surface(), 0, 0, &transform);
2255
2256 #if HAVE(IOSURFACE_ACCELERATOR)
2257     WebCore::IOSurface::Format compressedFormat = WebCore::IOSurface::Format::YUV422;
2258     if (WebCore::IOSurface::allowConversionFromFormatToFormat(snapshotFormat, compressedFormat)) {
2259         auto viewSnapshot = WebKit::ViewSnapshot::create(nullptr);
2260         WebCore::IOSurface::convertToFormat(WTFMove(surface), WebCore::IOSurface::Format::YUV422, [viewSnapshot = viewSnapshot.copyRef()](std::unique_ptr<WebCore::IOSurface> convertedSurface) {
2261             if (convertedSurface)
2262                 viewSnapshot->setSurface(WTFMove(convertedSurface));
2263         });
2264
2265         return viewSnapshot;
2266     }
2267 #endif // HAVE(IOSURFACE_ACCELERATOR)
2268
2269     return WebKit::ViewSnapshot::create(WTFMove(surface));
2270 #else // HAVE(IOSURFACE)
2271     uint32_t slotID = [WebKit::ViewSnapshotStore::snapshottingContext() createImageSlot:snapshotSize hasAlpha:YES];
2272
2273     if (!slotID)
2274         return nullptr;
2275
2276     CARenderServerCaptureLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, (uint64_t)self.layer, slotID, 0, 0, &transform);
2277     WebCore::IntSize imageSize = WebCore::expandedIntSize(WebCore::FloatSize(snapshotSize));
2278     return WebKit::ViewSnapshot::create(slotID, imageSize, (imageSize.area() * 4).unsafeGet());
2279 #endif // HAVE(IOSURFACE)
2280 #else // HAVE(CORE_ANIMATION_RENDER_SERVER)
2281     return nullptr;
2282 #endif
2283 }
2284
2285 - (void)_zoomToPoint:(WebCore::FloatPoint)point atScale:(double)scale animated:(BOOL)animated
2286 {
2287     CFTimeInterval duration = 0;
2288     CGFloat zoomScale = contentZoomScale(self);
2289
2290     if (animated) {
2291         const double maximumZoomDuration = 0.4;
2292         const double minimumZoomDuration = 0.1;
2293         const double zoomDurationFactor = 0.3;
2294
2295         duration = std::min(fabs(log(zoomScale) - log(scale)) * zoomDurationFactor + minimumZoomDuration, maximumZoomDuration);
2296     }
2297
2298     if (scale != zoomScale)
2299         _page->willStartUserTriggeredZooming();
2300
2301     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToPoint:" << point << " scale: " << scale << " duration:" << duration);
2302
2303     [_scrollView _zoomToCenter:point scale:scale duration:duration];
2304 }
2305
2306 - (void)_zoomToRect:(WebCore::FloatRect)targetRect atScale:(double)scale origin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2307 {
2308     // FIXME: Some of this could be shared with _scrollToRect.
2309     const double visibleRectScaleChange = contentZoomScale(self) / scale;
2310     const WebCore::FloatRect visibleRect([self convertRect:self.bounds toView:self._currentContentView]);
2311     const WebCore::FloatRect unobscuredRect([self _contentRectForUserInteraction]);
2312
2313     const WebCore::FloatSize topLeftObscuredInsetAfterZoom((unobscuredRect.minXMinYCorner() - visibleRect.minXMinYCorner()) * visibleRectScaleChange);
2314     const WebCore::FloatSize bottomRightObscuredInsetAfterZoom((visibleRect.maxXMaxYCorner() - unobscuredRect.maxXMaxYCorner()) * visibleRectScaleChange);
2315
2316     const WebCore::FloatSize unobscuredRectSizeAfterZoom(unobscuredRect.size() * visibleRectScaleChange);
2317
2318     // Center to the target rect.
2319     WebCore::FloatPoint unobscuredRectLocationAfterZoom = targetRect.location() - (unobscuredRectSizeAfterZoom - targetRect.size()) * 0.5;
2320
2321     // Center to the tap point instead in case the target rect won't fit in a direction.
2322     if (targetRect.width() > unobscuredRectSizeAfterZoom.width())
2323         unobscuredRectLocationAfterZoom.setX(origin.x() - unobscuredRectSizeAfterZoom.width() / 2);
2324     if (targetRect.height() > unobscuredRectSizeAfterZoom.height())
2325         unobscuredRectLocationAfterZoom.setY(origin.y() - unobscuredRectSizeAfterZoom.height() / 2);
2326
2327     // We have computed where we want the unobscured rect to be. Now adjust for the obscuring insets.
2328     WebCore::FloatRect visibleRectAfterZoom(unobscuredRectLocationAfterZoom, unobscuredRectSizeAfterZoom);
2329     visibleRectAfterZoom.move(-topLeftObscuredInsetAfterZoom);
2330     visibleRectAfterZoom.expand(topLeftObscuredInsetAfterZoom + bottomRightObscuredInsetAfterZoom);
2331
2332     [self _zoomToPoint:visibleRectAfterZoom.center() atScale:scale animated:animated];
2333 }
2334
2335 static WebCore::FloatPoint constrainContentOffset(WebCore::FloatPoint contentOffset, WebCore::FloatSize contentSize, WebCore::FloatSize unobscuredContentSize)
2336 {
2337     WebCore::FloatSize maximumContentOffset = contentSize - unobscuredContentSize;
2338     return contentOffset.constrainedBetween(WebCore::FloatPoint(), WebCore::FloatPoint(maximumContentOffset));
2339 }
2340
2341 - (void)_scrollToContentScrollPosition:(WebCore::FloatPoint)scrollPosition scrollOrigin:(WebCore::IntPoint)scrollOrigin
2342 {
2343     if (_commitDidRestoreScrollPosition || _dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing)
2344         return;
2345
2346     WebCore::FloatPoint contentOffset = WebCore::ScrollableArea::scrollOffsetFromPosition(scrollPosition, toFloatSize(scrollOrigin));
2347
2348     WebCore::FloatPoint scaledOffset = contentOffset;
2349     CGFloat zoomScale = contentZoomScale(self);
2350     scaledOffset.scale(zoomScale);
2351
2352     CGPoint contentOffsetInScrollViewCoordinates = [self _contentOffsetAdjustedForObscuredInset:scaledOffset];
2353     contentOffsetInScrollViewCoordinates = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
2354
2355     [_scrollView _stopScrollingAndZoomingAnimations];
2356
2357     if (!CGPointEqualToPoint(contentOffsetInScrollViewCoordinates, [_scrollView contentOffset]))
2358         [_scrollView setContentOffset:contentOffsetInScrollViewCoordinates];
2359     else {
2360         // If we haven't changed anything, there would not be any VisibleContentRect update sent to the content.
2361         // The WebProcess would keep the invalid contentOffset as its scroll position.
2362         // To synchronize the WebProcess with what is on screen, we send the VisibleContentRect again.
2363         _page->resendLastVisibleContentRects();
2364     }
2365 }
2366
2367 - (BOOL)_scrollToRect:(WebCore::FloatRect)targetRect origin:(WebCore::FloatPoint)origin minimumScrollDistance:(float)minimumScrollDistance
2368 {
2369     WebCore::FloatRect unobscuredContentRect([self _contentRectForUserInteraction]);
2370     WebCore::FloatPoint unobscuredContentOffset = unobscuredContentRect.location();
2371     WebCore::FloatSize contentSize([self._currentContentView bounds].size);
2372
2373     // Center the target rect in the scroll view.
2374     // If the target doesn't fit in the scroll view, center on the gesture location instead.
2375     WebCore::FloatPoint newUnobscuredContentOffset;
2376     if (targetRect.width() <= unobscuredContentRect.width())
2377         newUnobscuredContentOffset.setX(targetRect.x() - (unobscuredContentRect.width() - targetRect.width()) / 2);
2378     else
2379         newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
2380     if (targetRect.height() <= unobscuredContentRect.height())
2381         newUnobscuredContentOffset.setY(targetRect.y() - (unobscuredContentRect.height() - targetRect.height()) / 2);
2382     else
2383         newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
2384     newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
2385
2386     if (unobscuredContentOffset == newUnobscuredContentOffset) {
2387         if (targetRect.width() > unobscuredContentRect.width())
2388             newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
2389         if (targetRect.height() > unobscuredContentRect.height())
2390             newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
2391         newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
2392     }
2393
2394     WebCore::FloatSize scrollViewOffsetDelta = newUnobscuredContentOffset - unobscuredContentOffset;
2395     scrollViewOffsetDelta.scale(contentZoomScale(self));
2396
2397     float scrollDistance = scrollViewOffsetDelta.diagonalLength();
2398     if (scrollDistance < minimumScrollDistance)
2399         return false;
2400
2401     [_contentView willStartZoomOrScroll];
2402
2403     LOG_WITH_STREAM(VisibleRects, stream << "_scrollToRect: scrolling to " << [_scrollView contentOffset] + scrollViewOffsetDelta);
2404
2405     [_scrollView setContentOffset:([_scrollView contentOffset] + scrollViewOffsetDelta) animated:YES];
2406     return true;
2407 }
2408
2409 - (void)_zoomOutWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2410 {
2411     [self _zoomToPoint:origin atScale:[_scrollView minimumZoomScale] animated:animated];
2412 }
2413
2414 - (void)_zoomToInitialScaleWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2415 {
2416     ASSERT(_initialScaleFactor > 0);
2417     [self _zoomToPoint:origin atScale:_initialScaleFactor animated:animated];
2418 }
2419
2420 // focusedElementRect and selectionRect are both in document coordinates.
2421 - (void)_zoomToFocusRect:(const WebCore::FloatRect&)focusedElementRectInDocumentCoordinates selectionRect:(const WebCore::FloatRect&)selectionRectInDocumentCoordinates insideFixed:(BOOL)insideFixed
2422     fontSize:(float)fontSize minimumScale:(double)minimumScale maximumScale:(double)maximumScale allowScaling:(BOOL)allowScaling forceScroll:(BOOL)forceScroll
2423 {
2424     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToFocusRect:" << focusedElementRectInDocumentCoordinates << " selectionRect:" << selectionRectInDocumentCoordinates);
2425     UNUSED_PARAM(insideFixed);
2426
2427     const double minimumHeightToShowContentAboveKeyboard = 106;
2428     const CFTimeInterval formControlZoomAnimationDuration = 0.25;
2429     const double caretOffsetFromWindowEdge = 8;
2430
2431     UIWindow *window = [_scrollView window];
2432
2433     // Find the portion of the view that is visible on the screen.
2434     UIViewController *topViewController = [[[_scrollView _viewControllerForAncestor] _rootAncestorViewController] _viewControllerForSupportedInterfaceOrientations];
2435     UIView *fullScreenView = topViewController.view;
2436     if (!fullScreenView)
2437         fullScreenView = window;
2438
2439     CGRect unobscuredScrollViewRectInWebViewCoordinates = UIEdgeInsetsInsetRect([self bounds], _obscuredInsets);
2440     CGRect visibleScrollViewBoundsInWebViewCoordinates = CGRectIntersection(unobscuredScrollViewRectInWebViewCoordinates, [fullScreenView convertRect:[fullScreenView bounds] toView:self]);
2441     CGRect formAssistantFrameInWebViewCoordinates = [window convertRect:_inputViewBounds toView:self];
2442     CGRect intersectionBetweenScrollViewAndFormAssistant = CGRectIntersection(visibleScrollViewBoundsInWebViewCoordinates, formAssistantFrameInWebViewCoordinates);
2443     CGSize visibleSize = visibleScrollViewBoundsInWebViewCoordinates.size;
2444
2445     CGFloat visibleOffsetFromTop = 0;
2446     CGFloat minimumDistanceFromKeyboardToTriggerScroll = 0;
2447     if (!CGRectIsEmpty(intersectionBetweenScrollViewAndFormAssistant)) {
2448         CGFloat heightVisibleAboveFormAssistant = CGRectGetMinY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
2449         CGFloat heightVisibleBelowFormAssistant = CGRectGetMaxY(visibleScrollViewBoundsInWebViewCoordinates) - CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant);
2450
2451         if (heightVisibleAboveFormAssistant >= minimumHeightToShowContentAboveKeyboard || heightVisibleBelowFormAssistant < heightVisibleAboveFormAssistant) {
2452             visibleSize.height = heightVisibleAboveFormAssistant;
2453             minimumDistanceFromKeyboardToTriggerScroll = 50;
2454         } else {
2455             visibleSize.height = heightVisibleBelowFormAssistant;
2456             visibleOffsetFromTop = CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
2457         }
2458     }
2459
2460     // Zoom around the element's bounding frame. We use a "standard" size to determine the proper frame.
2461     double currentScale = contentZoomScale(self);
2462     double scale = currentScale;
2463     if (allowScaling) {
2464 #if PLATFORM(WATCHOS)
2465         const CGFloat minimumMarginForZoomingToEntireFocusRectInWebViewCoordinates = 10;
2466         const CGFloat maximumMarginForZoomingToEntireFocusRectInWebViewCoordinates = 35;
2467
2468         CGRect minimumTargetRectInDocumentCoordinates = UIRectInsetEdges(focusedElementRectInDocumentCoordinates, UIRectEdgeAll, -minimumMarginForZoomingToEntireFocusRectInWebViewCoordinates / currentScale);
2469         CGRect maximumTargetRectInDocumentCoordinates = UIRectInsetEdges(focusedElementRectInDocumentCoordinates, UIRectEdgeAll, -maximumMarginForZoomingToEntireFocusRectInWebViewCoordinates / currentScale);
2470
2471         double clampedMaximumTargetScale = clampTo<double>(std::min(visibleSize.width / CGRectGetWidth(minimumTargetRectInDocumentCoordinates), visibleSize.height / CGRectGetHeight(minimumTargetRectInDocumentCoordinates)), minimumScale, maximumScale);
2472         double clampedMinimumTargetScale = clampTo<double>(std::min(visibleSize.width / CGRectGetWidth(maximumTargetRectInDocumentCoordinates), visibleSize.height / CGRectGetHeight(maximumTargetRectInDocumentCoordinates)), minimumScale, maximumScale);
2473         scale = clampTo<double>(currentScale, clampedMinimumTargetScale, clampedMaximumTargetScale);
2474 #else
2475         const double webViewStandardFontSize = 16;
2476         scale = clampTo<double>(webViewStandardFontSize / fontSize, minimumScale, maximumScale);
2477 #endif
2478     }
2479
2480     CGFloat documentWidth = [_contentView bounds].size.width;
2481     scale = CGRound(documentWidth * scale) / documentWidth;
2482
2483     WebCore::FloatRect focusedElementRectInNewScale = focusedElementRectInDocumentCoordinates;
2484     focusedElementRectInNewScale.scale(scale);
2485     focusedElementRectInNewScale.moveBy([_contentView frame].origin);
2486
2487     BOOL selectionRectIsNotNull = !selectionRectInDocumentCoordinates.isZero();
2488     BOOL doNotScrollWhenContentIsAlreadyVisible = !forceScroll || [_contentView _shouldAvoidScrollingWhenFocusedContentIsVisible];
2489     if (doNotScrollWhenContentIsAlreadyVisible) {
2490         CGRect currentlyVisibleRegionInWebViewCoordinates;
2491         currentlyVisibleRegionInWebViewCoordinates.origin = unobscuredScrollViewRectInWebViewCoordinates.origin;
2492         currentlyVisibleRegionInWebViewCoordinates.origin.y += visibleOffsetFromTop;
2493         currentlyVisibleRegionInWebViewCoordinates.size = visibleSize;
2494         currentlyVisibleRegionInWebViewCoordinates.size.height -= minimumDistanceFromKeyboardToTriggerScroll;
2495
2496         // Don't bother scrolling if the entire node is already visible, whether or not we got a selectionRect.
2497         if (CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:focusedElementRectInDocumentCoordinates fromView:_contentView.get()]))
2498             return;
2499
2500         // Don't bother scrolling if we have a valid selectionRect and it is already visible.
2501         if (selectionRectIsNotNull && CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:selectionRectInDocumentCoordinates fromView:_contentView.get()]))
2502             return;
2503     }
2504
2505     // We want to center the focused element within the viewport, with as much spacing on all sides as
2506     // we can get based on the visible area after zooming. The spacing in either dimension is half the
2507     // difference between the size of the DOM node and the size of the visible frame.
2508     // If the element is too wide to be horizontally centered or too tall to be vertically centered, we
2509     // instead scroll such that the left edge or top edge of the element is within the left half or top
2510     // half of the viewport, respectively.
2511     CGFloat horizontalSpaceInWebViewCoordinates = (visibleSize.width - focusedElementRectInNewScale.width()) / 2.0;
2512     CGFloat verticalSpaceInWebViewCoordinates = (visibleSize.height - focusedElementRectInNewScale.height()) / 2.0;
2513
2514     auto topLeft = CGPointZero;
2515     auto scrollViewInsets = [_scrollView _effectiveContentInset];
2516     auto currentTopLeft = [_scrollView contentOffset];
2517
2518     if (_haveSetObscuredInsets) {
2519         currentTopLeft.x += _obscuredInsets.left;
2520         currentTopLeft.y += _obscuredInsets.top;
2521     }
2522
2523     if (horizontalSpaceInWebViewCoordinates > 0)
2524         topLeft.x = focusedElementRectInNewScale.x() - horizontalSpaceInWebViewCoordinates;
2525     else {
2526         auto minimumOffsetToRevealLeftEdge = std::max(-scrollViewInsets.left, focusedElementRectInNewScale.x() - visibleSize.width / 2);
2527         auto maximumOffsetToRevealLeftEdge = focusedElementRectInNewScale.x();
2528         topLeft.x = clampTo<double>(currentTopLeft.x, minimumOffsetToRevealLeftEdge, maximumOffsetToRevealLeftEdge);
2529     }
2530
2531     if (verticalSpaceInWebViewCoordinates > 0)
2532         topLeft.y = focusedElementRectInNewScale.y() - verticalSpaceInWebViewCoordinates;
2533     else {
2534         auto minimumOffsetToRevealTopEdge = std::max(-scrollViewInsets.top, focusedElementRectInNewScale.y() - visibleSize.height / 2);
2535         auto maximumOffsetToRevealTopEdge = focusedElementRectInNewScale.y();
2536         topLeft.y = clampTo<double>(currentTopLeft.y, minimumOffsetToRevealTopEdge, maximumOffsetToRevealTopEdge);
2537     }
2538
2539     topLeft.y -= visibleOffsetFromTop;
2540
2541     WebCore::FloatRect documentBoundsInNewScale = [_contentView bounds];
2542     documentBoundsInNewScale.scale(scale);
2543     documentBoundsInNewScale.moveBy([_contentView frame].origin);
2544
2545     CGFloat minimumAllowableHorizontalOffsetInWebViewCoordinates = -INFINITY;
2546     CGFloat minimumAllowableVerticalOffsetInWebViewCoordinates = -INFINITY;
2547     CGFloat maximumAllowableHorizontalOffsetInWebViewCoordinates = CGRectGetMaxX(documentBoundsInNewScale) - visibleSize.width;
2548     CGFloat maximumAllowableVerticalOffsetInWebViewCoordinates = CGRectGetMaxY(documentBoundsInNewScale) - visibleSize.height;
2549
2550     if (selectionRectIsNotNull) {
2551         WebCore::FloatRect selectionRectInNewScale = selectionRectInDocumentCoordinates;
2552         selectionRectInNewScale.scale(scale);
2553         selectionRectInNewScale.moveBy([_contentView frame].origin);
2554         // Adjust the min and max allowable scroll offsets, such that the selection rect remains visible.
2555         minimumAllowableHorizontalOffsetInWebViewCoordinates = CGRectGetMaxX(selectionRectInNewScale) + caretOffsetFromWindowEdge - visibleSize.width;
2556         minimumAllowableVerticalOffsetInWebViewCoordinates = CGRectGetMaxY(selectionRectInNewScale) + caretOffsetFromWindowEdge - visibleSize.height - visibleOffsetFromTop;
2557         maximumAllowableHorizontalOffsetInWebViewCoordinates = std::min<CGFloat>(maximumAllowableHorizontalOffsetInWebViewCoordinates, CGRectGetMinX(selectionRectInNewScale) - caretOffsetFromWindowEdge);
2558         maximumAllowableVerticalOffsetInWebViewCoordinates = std::min<CGFloat>(maximumAllowableVerticalOffsetInWebViewCoordinates, CGRectGetMinY(selectionRectInNewScale) - caretOffsetFromWindowEdge - visibleOffsetFromTop);
2559     }
2560
2561     // Constrain the left edge in document coordinates so that:
2562     //  - it isn't so small that the scrollVisibleRect isn't visible on the screen
2563     //  - it isn't so great that the document's right edge is less than the right edge of the screen
2564     topLeft.x = clampTo<CGFloat>(topLeft.x, minimumAllowableHorizontalOffsetInWebViewCoordinates, maximumAllowableHorizontalOffsetInWebViewCoordinates);
2565
2566     // Constrain the top edge in document coordinates so that:
2567     //  - it isn't so small that the scrollVisibleRect isn't visible on the screen
2568     //  - it isn't so great that the document's bottom edge is higher than the top of the form assistant
2569     topLeft.y = clampTo<CGFloat>(topLeft.y, minimumAllowableVerticalOffsetInWebViewCoordinates, maximumAllowableVerticalOffsetInWebViewCoordinates);
2570
2571     if (_haveSetObscuredInsets) {
2572         // This looks unintuitive, but is necessary in order to precisely center the focused element in the visible area.
2573         // The top left position already accounts for top and left obscured insets - i.e., a topLeft of (0, 0) corresponds
2574         // to the top- and left-most point below (and to the right of) the top inset area and left inset areas, respectively.
2575         // However, when telling WKScrollView to scroll to a given center position, this center position is computed relative
2576         // to the coordinate space of the scroll view. Thus, to compute our center position from the top left position, we
2577         // need to first move the top left position up and to the left, and then add half the width and height of the content
2578         // area (including obscured insets).
2579         topLeft.x -= _obscuredInsets.left;
2580         topLeft.y -= _obscuredInsets.top;
2581     }
2582
2583     WebCore::FloatPoint newCenter = CGPointMake(topLeft.x + CGRectGetWidth(self.bounds) / 2, topLeft.y + CGRectGetHeight(self.bounds) / 2);
2584
2585     if (scale != currentScale)
2586         _page->willStartUserTriggeredZooming();
2587
2588     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToFocusRect: zooming to " << newCenter << " scale:" << scale);
2589
2590     // The newCenter has been computed in the new scale, but _zoomToCenter expected the center to be in the original scale.
2591     newCenter.scale(1 / scale);
2592     [_scrollView _zoomToCenter:newCenter scale:scale duration:formControlZoomAnimationDuration force:YES];
2593 }
2594
2595 - (double)_initialScaleFactor
2596 {
2597     return _initialScaleFactor;
2598 }
2599
2600 - (double)_contentZoomScale
2601 {
2602     return contentZoomScale(self);
2603 }
2604
2605 - (double)_targetContentZoomScaleForRect:(const WebCore::FloatRect&)targetRect currentScale:(double)currentScale fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale
2606 {
2607     WebCore::FloatSize unobscuredContentSize([self _contentRectForUserInteraction].size);
2608     double horizontalScale = unobscuredContentSize.width() * currentScale / targetRect.width();
2609     double verticalScale = unobscuredContentSize.height() * currentScale / targetRect.height();
2610
2611     horizontalScale = std::min(std::max(horizontalScale, minimumScale), maximumScale);
2612     verticalScale = std::min(std::max(verticalScale, minimumScale), maximumScale);
2613
2614     return fitEntireRect ? std::min(horizontalScale, verticalScale) : horizontalScale;
2615 }
2616
2617 - (BOOL)_zoomToRect:(WebCore::FloatRect)targetRect withOrigin:(WebCore::FloatPoint)origin fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale minimumScrollDistance:(float)minimumScrollDistance
2618 {
2619     const float maximumScaleFactorDeltaForPanScroll = 0.02;
2620
2621     double currentScale = contentZoomScale(self);
2622     double targetScale = [self _targetContentZoomScaleForRect:targetRect currentScale:currentScale fitEntireRect:fitEntireRect minimumScale:minimumScale maximumScale:maximumScale];
2623
2624     if (fabs(targetScale - currentScale) < maximumScaleFactorDeltaForPanScroll) {
2625         if ([self _scrollToRect:targetRect origin:origin minimumScrollDistance:minimumScrollDistance])
2626             return true;
2627     } else if (targetScale != currentScale) {
2628         [self _zoomToRect:targetRect atScale:targetScale origin:origin animated:YES];
2629         return true;
2630     }
2631
2632     return false;
2633 }
2634
2635 - (void)didMoveToWindow
2636 {
2637     _page->activityStateDidChange(WebCore::ActivityState::allFlags());
2638     _page->webViewDidMoveToWindow();
2639 }
2640
2641 - (void)_setOpaqueInternal:(BOOL)opaque
2642 {
2643     [super setOpaque:opaque];
2644
2645     [_contentView setOpaque:opaque];
2646
2647     if (!_page)
2648         return;
2649
2650     Optional<WebCore::Color> backgroundColor;
2651     if (!opaque)
2652         backgroundColor = WebCore::Color(WebCore::Color::transparent);
2653     _page->setBackgroundColor(backgroundColor);
2654
2655     [self _updateScrollViewBackground];
2656 }
2657
2658 - (void)setOpaque:(BOOL)opaque
2659 {
2660     if (opaque == self.opaque)
2661         return;
2662
2663     [self _setOpaqueInternal:opaque];
2664 }
2665
2666 - (void)setBackgroundColor:(UIColor *)backgroundColor
2667 {
2668     [super setBackgroundColor:backgroundColor];
2669     [_contentView setBackgroundColor:backgroundColor];
2670     [self _updateScrollViewBackground];
2671 }
2672
2673 - (BOOL)_allowsDoubleTapGestures
2674 {
2675     if (_fastClickingIsDisabled)
2676         return YES;
2677
2678     // If the page is not user scalable, we don't allow double tap gestures.
2679     if (![_scrollView isZoomEnabled] || [_scrollView minimumZoomScale] >= [_scrollView maximumZoomScale])
2680         return NO;
2681
2682     // If the viewport width was not explicit, we allow double tap gestures.
2683     if (!_viewportMetaTagWidthWasExplicit || _viewportMetaTagCameFromImageDocument)
2684         return YES;
2685
2686     // If the page set a viewport width that wasn't the device width, then it was
2687     // scaled and thus will probably need to zoom.
2688     if (_viewportMetaTagWidth != WebCore::ViewportArguments::ValueDeviceWidth)
2689         return YES;
2690
2691     // At this point, we have a page that asked for width = device-width. However,
2692     // if the content's width and height were large, we might have had to shrink it.
2693     // We'll enable double tap zoom whenever we're not at the actual initial scale.
2694     return !areEssentiallyEqualAsFloat(contentZoomScale(self), _initialScaleFactor);
2695 }
2696
2697 - (BOOL)_stylusTapGestureShouldCreateEditableImage
2698 {
2699     return [_configuration _editableImagesEnabled];
2700 }
2701
2702 #pragma mark - UIScrollViewDelegate
2703
2704 - (BOOL)usesStandardContentView
2705 {
2706     return !_customContentView && !_passwordView;
2707 }
2708
2709 - (CGSize)scrollView:(UIScrollView*)scrollView contentSizeForZoomScale:(CGFloat)scale withProposedSize:(CGSize)proposedSize
2710 {
2711     return roundScrollViewContentSize(*_page, proposedSize);
2712 }
2713
2714 - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
2715 {
2716     ASSERT(_scrollView == scrollView);
2717     return self._currentContentView;
2718 }
2719
2720 - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
2721 {
2722     if (![self usesStandardContentView]) {
2723         if ([_customContentView respondsToSelector:@selector(web_scrollViewWillBeginZooming:withView:)])
2724             [_customContentView web_scrollViewWillBeginZooming:scrollView withView:view];
2725         return;
2726     }
2727
2728     if (scrollView.pinchGestureRecognizer.state == UIGestureRecognizerStateBegan) {
2729         _page->willStartUserTriggeredZooming();
2730         [_contentView scrollViewWillStartPanOrPinchGesture];
2731     }
2732     [_contentView willStartZoomOrScroll];
2733
2734 #if ENABLE(POINTER_EVENTS)
2735     [_contentView cancelPointersForGestureRecognizer:scrollView.pinchGestureRecognizer];
2736 #endif
2737 }
2738
2739 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
2740 {
2741     if (![self usesStandardContentView])
2742         return;
2743
2744     if (scrollView.panGestureRecognizer.state == UIGestureRecognizerStateBegan)
2745         [_contentView scrollViewWillStartPanOrPinchGesture];
2746
2747     [_contentView willStartZoomOrScroll];
2748 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2749     // FIXME: We will want to detect whether snapping will occur before beginning to drag. See WebPageProxy::didCommitLayerTree.
2750     WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2751     ASSERT(scrollView == _scrollView.get());
2752     CGFloat scrollDecelerationFactor = (coordinator && coordinator->shouldSetScrollViewDecelerationRateFast()) ? UIScrollViewDecelerationRateFast : UIScrollViewDecelerationRateNormal;
2753     scrollView.horizontalScrollDecelerationFactor = scrollDecelerationFactor;
2754     scrollView.verticalScrollDecelerationFactor = scrollDecelerationFactor;
2755 #endif
2756 }
2757
2758 - (void)_didFinishScrolling
2759 {
2760     if (![self usesStandardContentView])
2761         return;
2762
2763     [self _scheduleVisibleContentRectUpdate];
2764     [_contentView didFinishScrolling];
2765 }
2766
2767 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
2768 {
2769     // Work around <rdar://problem/16374753> by avoiding deceleration while
2770     // zooming. We'll animate to the right place once the zoom finishes.
2771     if ([scrollView isZooming])
2772         *targetContentOffset = [scrollView contentOffset];
2773 #if ENABLE(POINTER_EVENTS)
2774     else {
2775         if ([_contentView preventsPanningInXAxis])
2776             targetContentOffset->x = scrollView.contentOffset.x;
2777         if ([_contentView preventsPanningInYAxis])
2778             targetContentOffset->y = scrollView.contentOffset.y;
2779     }
2780 #endif
2781 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2782     if (WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy()) {
2783         // FIXME: Here, I'm finding the maximum horizontal/vertical scroll offsets. There's probably a better way to do this.
2784         CGSize maxScrollOffsets = CGSizeMake(scrollView.contentSize.width - scrollView.bounds.size.width, scrollView.contentSize.height - scrollView.bounds.size.height);
2785
2786         UIEdgeInsets obscuredInset;
2787
2788         id<WKUIDelegatePrivate> uiDelegatePrivate = static_cast<id <WKUIDelegatePrivate>>([self UIDelegate]);
2789         if ([uiDelegatePrivate respondsToSelector:@selector(_webView:finalObscuredInsetsForScrollView:withVelocity:targetContentOffset:)])
2790             obscuredInset = [uiDelegatePrivate _webView:self finalObscuredInsetsForScrollView:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
2791         else
2792             obscuredInset = [self _computedObscuredInset];
2793
2794         CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInset);
2795
2796         coordinator->adjustTargetContentOffsetForSnapping(maxScrollOffsets, velocity, unobscuredRect.origin.y, targetContentOffset);
2797     }
2798 #endif
2799 }
2800
2801 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
2802 {
2803     // If we're decelerating, scroll offset will be updated when scrollViewDidFinishDecelerating: is called.
2804     if (!decelerate)
2805         [self _didFinishScrolling];
2806 }
2807
2808 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
2809 {
2810     [self _didFinishScrolling];
2811 }
2812
2813 - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
2814 {
2815     [self _didFinishScrolling];
2816 }
2817
2818 #if ENABLE(POINTER_EVENTS)
2819 - (CGPoint)_scrollView:(UIScrollView *)scrollView adjustedOffsetForOffset:(CGPoint)offset translation:(CGPoint)translation startPoint:(CGPoint)start locationInView:(CGPoint)locationInView horizontalVelocity:(inout double *)hv verticalVelocity:(inout double *)vv
2820 {
2821     if (![_contentView preventsPanningInXAxis] && ![_contentView preventsPanningInYAxis]) {
2822         [_contentView cancelPointersForGestureRecognizer:scrollView.panGestureRecognizer];
2823         return offset;
2824     }
2825
2826     CGPoint adjustedContentOffset = CGPointMake(offset.x, offset.y);
2827     if ([_contentView preventsPanningInXAxis])
2828         adjustedContentOffset.x = start.x;
2829     if ([_contentView preventsPanningInYAxis])
2830         adjustedContentOffset.y = start.y;
2831
2832     if ((![_contentView preventsPanningInXAxis] && adjustedContentOffset.x != start.x)
2833         || (![_contentView preventsPanningInYAxis] && adjustedContentOffset.y != start.y)) {
2834         [_contentView cancelPointersForGestureRecognizer:scrollView.panGestureRecognizer];
2835     }
2836
2837     return adjustedContentOffset;
2838 }
2839 #endif
2840
2841 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
2842 {
2843     if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidScroll:)])
2844         [_customContentView web_scrollViewDidScroll:(UIScrollView *)scrollView];
2845
2846     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2847
2848     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
2849         scrollPerfData->didScroll([self visibleRectInViewCoordinates]);
2850 }
2851
2852 - (void)scrollViewDidZoom:(UIScrollView *)scrollView
2853 {
2854     if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidZoom:)])
2855         [_customContentView web_scrollViewDidZoom:scrollView];
2856
2857     [self _updateScrollViewBackground];
2858     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2859 }
2860
2861 - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
2862 {
2863     if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidEndZooming:withView:atScale:)])
2864         [_customContentView web_scrollViewDidEndZooming:scrollView withView:view atScale:scale];
2865
2866     ASSERT(scrollView == _scrollView);
2867     // FIXME: remove when rdar://problem/36065495 is fixed.
2868     // When rotating with two fingers down, UIScrollView can set a bogus content view position.
2869     // "Center" is top left because we set the anchorPoint to 0,0.
2870     [_contentView setCenter:self.bounds.origin];
2871
2872     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2873     [_contentView didZoomToScale:scale];
2874 }
2875
2876 - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
2877 {
2878     [self _didFinishScrolling];
2879 }
2880
2881 - (void)_scrollViewDidInterruptDecelerating:(UIScrollView *)scrollView
2882 {
2883     if (![self usesStandardContentView])
2884         return;
2885
2886     [_contentView didInterruptScrolling];
2887     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2888 }
2889
2890 - (UIView *)_enclosingViewForExposedRectComputation
2891 {
2892     return [self _scroller];
2893 }
2894
2895 - (CGRect)_visibleRectInEnclosingView:(UIView *)enclosingView
2896 {
2897     if (!enclosingView)
2898         return self.bounds;
2899
2900     CGRect exposedRect = [enclosingView convertRect:enclosingView.bounds toView:self];
2901     return CGRectIntersectsRect(exposedRect, self.bounds) ? CGRectIntersection(exposedRect, self.bounds) : CGRectZero;
2902 }
2903
2904 - (CGRect)_visibleContentRect
2905 {
2906     if (_frozenVisibleContentRect)
2907         return _frozenVisibleContentRect.value();
2908
2909     CGRect visibleRectInContentCoordinates = [self convertRect:self.bounds toView:_contentView.get()];
2910
2911     if (UIView *enclosingView = [self _enclosingViewForExposedRectComputation]) {
2912         CGRect viewVisibleRect = [self _visibleRectInEnclosingView:enclosingView];
2913         CGRect viewVisibleContentRect = [self convertRect:viewVisibleRect toView:_contentView.get()];
2914         visibleRectInContentCoordinates = CGRectIntersection(visibleRectInContentCoordinates, viewVisibleContentRect);
2915     }
2916
2917     return visibleRectInContentCoordinates;
2918 }
2919
2920 // Called when some ancestor UIScrollView scrolls.
2921 - (void)_didScroll
2922 {
2923     [self _scheduleVisibleContentRectUpdateAfterScrollInView:[self _scroller]];
2924
2925     const NSTimeInterval ScrollingEndedTimerInterval = 0.032;
2926     if (!_enclosingScrollViewScrollTimer) {
2927         _enclosingScrollViewScrollTimer = adoptNS([[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:ScrollingEndedTimerInterval]
2928             interval:0 target:self selector:@selector(_enclosingScrollerScrollingEnded:) userInfo:nil repeats:YES]);
2929         [[NSRunLoop mainRunLoop] addTimer:_enclosingScrollViewScrollTimer.get() forMode:NSDefaultRunLoopMode];
2930     }
2931     _didScrollSinceLastTimerFire = YES;
2932 }
2933
2934 - (void)_enclosingScrollerScrollingEnded:(NSTimer *)timer
2935 {
2936     if (_didScrollSinceLastTimerFire) {
2937         _didScrollSinceLastTimerFire = NO;
2938         return;
2939     }
2940
2941     [self _scheduleVisibleContentRectUpdate];
2942     [_enclosingScrollViewScrollTimer invalidate];
2943     _enclosingScrollViewScrollTimer = nil;
2944 }
2945
2946 - (UIEdgeInsets)_scrollViewSystemContentInset
2947 {
2948     // It's not safe to access the scroll view's safeAreaInsets or _systemContentInset from
2949     // inside our layoutSubviews implementation, because they aren't updated until afterwards.
2950     // Instead, depend on the fact that the UIScrollView and WKWebView are in the same coordinate
2951     // space, and map the WKWebView's own insets into the scroll view manually.
2952     return UIEdgeInsetsAdd([_scrollView _contentScrollInset], self.safeAreaInsets, [_scrollView _edgesApplyingSafeAreaInsetsToContentInset]);
2953 }
2954
2955 - (WebCore::FloatSize)activeViewLayoutSize:(const CGRect&)bounds
2956 {
2957     if (_viewLayoutSizeOverride)
2958         return WebCore::FloatSize(_viewLayoutSizeOverride.value());
2959
2960 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2961     return WebCore::FloatSize(UIEdgeInsetsInsetRect(CGRectMake(0, 0, bounds.size.width, bounds.size.height), self._scrollViewSystemContentInset).size);
2962 #else
2963     return WebCore::FloatSize { bounds.size };
2964 #endif
2965 }
2966
2967 - (void)_dispatchSetViewLayoutSize:(WebCore::FloatSize)viewLayoutSize
2968 {
2969     if (_lastSentViewLayoutSize && CGSizeEqualToSize(_lastSentViewLayoutSize.value(), viewLayoutSize))
2970         return;
2971
2972     LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->identifier() << " _dispatchSetViewLayoutSize:] " << viewLayoutSize << " contentZoomScale " << contentZoomScale(self));
2973     _page->setViewportConfigurationViewLayoutSize(viewLayoutSize, _page->layoutSizeScaleFactor(), _page->minimumEffectiveDeviceWidth());
2974     _lastSentViewLayoutSize = viewLayoutSize;
2975 }
2976
2977 - (void)_dispatchSetMaximumUnobscuredSize:(WebCore::FloatSize)maximumUnobscuredSize
2978 {
2979     if (_lastSentMaximumUnobscuredSize && CGSizeEqualToSize(_lastSentMaximumUnobscuredSize.value(), maximumUnobscuredSize))
2980         return;
2981
2982     _page->setMaximumUnobscuredSize(maximumUnobscuredSize);
2983     _lastSentMaximumUnobscuredSize = maximumUnobscuredSize;
2984 }
2985
2986 - (void)_dispatchSetDeviceOrientation:(int32_t)deviceOrientation
2987 {
2988     if (_lastSentDeviceOrientation && _lastSentDeviceOrientation.value() == deviceOrientation)
2989         return;
2990
2991     _page->setDeviceOrientation(deviceOrientation);
2992     _lastSentDeviceOrientation = deviceOrientation;
2993 }
2994
2995 - (void)_frameOrBoundsChanged
2996 {
2997     CGRect bounds = self.bounds;
2998     [_scrollView setFrame:bounds];
2999
3000     if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing) {
3001         if (!_viewLayoutSizeOverride)
3002             [self _dispatchSetViewLayoutSize:[self activeViewLayoutSize:self.bounds]];
3003         if (!_maximumUnobscuredSizeOverride)
3004             [self _dispatchSetMaximumUnobscuredSize:WebCore::FloatSize(bounds.size)];
3005
3006         BOOL sizeChanged = NO;
3007         if (auto drawingArea = _page->drawingArea())
3008             sizeChanged = drawingArea->setSize(WebCore::IntSize(bounds.size));
3009
3010         if (sizeChanged & [self usesStandardContentView])
3011             [_contentView setSizeChangedSinceLastVisibleContentRectUpdate:YES];
3012     }
3013
3014     [_customContentView web_setMinimumSize:bounds.size];
3015     [self _scheduleVisibleContentRectUpdate];
3016 }
3017
3018 // 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.
3019 - (CGRect)_contentRectForUserInteraction
3020 {
3021     // FIXME: handle split keyboard.
3022     UIEdgeInsets obscuredInsets = _obscuredInsets;
3023     obscuredInsets.bottom = std::max(_obscuredInsets.bottom, _inputViewBounds.size.height);
3024     CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInsets);
3025     return [self convertRect:unobscuredRect toView:self._currentContentView];
3026 }
3027
3028 // Ideally UIScrollView would expose this for us: <rdar://problem/21394567>.
3029 - (BOOL)_scrollViewIsRubberBanding
3030 {
3031     float deviceScaleFactor = _page->deviceScaleFactor();
3032
3033     CGPoint contentOffset = [_scrollView contentOffset];
3034     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
3035     return !pointsEqualInDevicePixels(contentOffset, boundedOffset, deviceScaleFactor);
3036 }
3037
3038 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
3039 - (void)safeAreaInsetsDidChange
3040 {
3041     [super safeAreaInsetsDidChange];
3042
3043     [self _scheduleVisibleContentRectUpdate];
3044 }
3045 #endif
3046
3047 - (void)_scheduleVisibleContentRectUpdate
3048 {
3049     // For visible rect updates not associated with a specific UIScrollView, just consider our own scroller.
3050     [self _scheduleVisibleContentRectUpdateAfterScrollInView:_scrollView.get()];
3051 }
3052
3053 - (BOOL)_scrollViewIsInStableState:(UIScrollView *)scrollView
3054 {
3055     BOOL isStableState = !([scrollView isDragging] || [scrollView isDecelerating] || [scrollView isZooming] || [scrollView _isAnimatingZoom] || [scrollView _isScrollingToTop]);
3056
3057     if (isStableState && scrollView == _scrollView.get())
3058         isStableState = !_isChangingObscuredInsetsInteractively;
3059
3060     if (isStableState && scrollView == _scrollView.get())
3061         isStableState = ![self _scrollViewIsRubberBanding];
3062
3063     if (isStableState)
3064         isStableState = !scrollView._isInterruptingDeceleration;
3065
3066     if (NSNumber *stableOverride = self._stableStateOverride)
3067         isStableState = stableOverride.boolValue;
3068
3069     return isStableState;
3070 }
3071
3072 - (void)_addUpdateVisibleContentRectPreCommitHandler
3073 {
3074     if (_hasEnteredDealloc) {
3075         RELEASE_LOG_FAULT(ViewState, "-[WKWebView %p _addUpdateVisibleContentRectPreCommitHandler]: Attempted to add pre-commit handler under -dealloc. Bailing.", self);
3076         return;
3077     }
3078
3079     auto retainedSelf = retainPtr(self);
3080     [CATransaction addCommitHandler:[retainedSelf] {
3081         WKWebView *webView = retainedSelf.get();
3082         if (![webView _isValid]) {
3083             RELEASE_LOG_IF(webView._page && webView._page->isAlwaysOnLoggingAllowed(), ViewState, "In CATransaction preCommitHandler, WKWebView %p is invalid", webView);
3084             return;
3085         }
3086
3087         @try {
3088             [webView _updateVisibleContentRects];
3089         } @catch (NSException *exception) {
3090             RELEASE_LOG_IF(webView._page && webView._page->isAlwaysOnLoggingAllowed(), ViewState, "In CATransaction preCommitHandler, -[WKWebView %p _updateVisibleContentRects] threw an exception", webView);
3091         }
3092         webView->_hasScheduledVisibleRectUpdate = NO;
3093     } forPhase:kCATransactionPhasePreCommit];
3094 }
3095
3096 - (void)_scheduleVisibleContentRectUpdateAfterScrollInView:(UIScrollView *)scrollView
3097 {
3098     _visibleContentRectUpdateScheduledFromScrollViewInStableState = [self _scrollViewIsInStableState:scrollView];
3099
3100     if (_hasScheduledVisibleRectUpdate) {
3101         auto timeNow = MonotonicTime::now();
3102         if ((timeNow - _timeOfRequestForVisibleContentRectUpdate) > delayBeforeNoVisibleContentsRectsLogging) {
3103             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",
3104                 self, (timeNow - _timeOfRequestForVisibleContentRectUpdate).value(), (timeNow - _timeOfLastVisibleContentRectUpdate).value(), [self _isValid]);
3105         }
3106         return;
3107     }
3108
3109     _hasScheduledVisibleRectUpdate = YES;
3110     _timeOfRequestForVisibleContentRectUpdate = MonotonicTime::now();
3111
3112     CATransactionPhase transactionPhase = [CATransaction currentPhase];
3113     if (transactionPhase == kCATransactionPhaseNull || transactionPhase == kCATransactionPhasePreLayout) {
3114         [self _addUpdateVisibleContentRectPreCommitHandler];
3115         return;
3116     }
3117
3118     dispatch_async(dispatch_get_main_queue(), [retainedSelf = retainPtr(self)] {
3119         WKWebView *webView = retainedSelf.get();
3120         if (![webView _isValid])
3121             return;
3122         [webView _addUpdateVisibleContentRectPreCommitHandler];
3123     });
3124 }
3125
3126 static bool scrollViewCanScroll(UIScrollView *scrollView)
3127 {
3128     if (!scrollView)
3129         return NO;
3130
3131     UIEdgeInsets contentInset = scrollView.contentInset;
3132     CGSize contentSize = scrollView.contentSize;
3133     CGSize boundsSize = scrollView.bounds.size;
3134
3135     return (contentSize.width + contentInset.left + contentInset.right) > boundsSize.width
3136         || (contentSize.height + contentInset.top + contentInset.bottom) > boundsSize.height;
3137 }
3138
3139 - (CGRect)_contentBoundsExtendedForRubberbandingWithScale:(CGFloat)scaleFactor
3140 {
3141     CGPoint contentOffset = [_scrollView contentOffset];
3142     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
3143
3144     CGFloat horiontalRubberbandAmountInContentCoordinates = (contentOffset.x - boundedOffset.x) / scaleFactor;
3145     CGFloat verticalRubberbandAmountInContentCoordinates = (contentOffset.y - boundedOffset.y) / scaleFactor;
3146
3147     CGRect extendedBounds = [_contentView bounds];
3148
3149     if (horiontalRubberbandAmountInContentCoordinates < 0) {
3150         extendedBounds.origin.x += horiontalRubberbandAmountInContentCoordinates;
3151         extendedBounds.size.width -= horiontalRubberbandAmountInContentCoordinates;
3152     } else if (horiontalRubberbandAmountInContentCoordinates > 0)
3153         extendedBounds.size.width += horiontalRubberbandAmountInContentCoordinates;
3154
3155     if (verticalRubberbandAmountInContentCoordinates < 0) {
3156         extendedBounds.origin.y += verticalRubberbandAmountInContentCoordinates;
3157         extendedBounds.size.height -= verticalRubberbandAmountInContentCoordinates;
3158     } else if (verticalRubberbandAmountInContentCoordinates > 0)
3159         extendedBounds.size.height += verticalRubberbandAmountInContentCoordinates;
3160
3161     return extendedBounds;
3162 }
3163
3164 - (void)_updateVisibleContentRects
3165 {
3166     BOOL inStableState = _visibleContentRectUpdateScheduledFromScrollViewInStableState;
3167
3168     if (![self usesStandardContentView]) {
3169         [_passwordView setFrame:self.bounds];
3170         [_customContentView web_computedContentInsetDidChange];
3171         _didDeferUpdateVisibleContentRectsForAnyReason = YES;
3172         RELEASE_LOG_IF_ALLOWED("%p (pageProxyID=%llu) -[WKWebView _updateVisibleContentRects:] - usesStandardContentView is NO, bailing", self, _page->identifier().toUInt64());
3173         return;
3174     }
3175
3176     auto timeNow = MonotonicTime::now();
3177     if (_timeOfFirstVisibleContentRectUpdateWithPendingCommit) {
3178         auto timeSinceFirstRequestWithPendingCommit = timeNow - *_timeOfFirstVisibleContentRectUpdateWithPendingCommit;
3179         if (timeSinceFirstRequestWithPendingCommit > delayBeforeNoCommitsLogging)
3180             RELEASE_LOG_IF_ALLOWED("%p (pageProxyID=%llu) -[WKWebView _updateVisibleContentRects:] - have not received a commit %.2fs after visible content rect update; lastTransactionID %llu", self, _page->identifier().toUInt64(), timeSinceFirstRequestWithPendingCommit.value(), _lastTransactionID.toUInt64());
3181     }
3182
3183     if (_invokingUIScrollViewDelegateCallback) {
3184         _didDeferUpdateVisibleContentRectsForUIScrollViewDelegateCallback = YES;
3185         _didDeferUpdateVisibleContentRectsForAnyReason = YES;
3186         RELEASE_LOG_IF_ALLOWED("%p (pageProxyID=%llu) -[WKWebView _updateVisibleContentRects:] - _invokingUIScrollViewDelegateCallback is YES, bailing", self, _page->identifier().toUInt64());
3187         return;
3188     }
3189
3190     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing
3191         || (_needsResetViewStateAfterCommitLoadForMainFrame && ![_contentView sizeChangedSinceLastVisibleContentRectUpdate])
3192         || [_scrollView isZoomBouncing]
3193         || _currentlyAdjustingScrollViewInsetsForKeyboard) {
3194         _didDeferUpdateVisibleContentRectsForAnyReason = YES;
3195         _didDeferUpdateVisibleContentRectsForUnstableScrollView = YES;
3196         RELEASE_LOG_IF_ALLOWED("%p (pageProxyID=%llu) -[WKWebView _updateVisibleContentRects:] - scroll view state is non-stable, bailing (_dynamicViewportUpdateMode %d, _needsResetViewStateAfterCommitLoadForMainFrame %d, sizeChangedSinceLastVisibleContentRectUpdate %d, [_scrollView isZoomBouncing] %d, _currentlyAdjustingScrollViewInsetsForKeyboard %d)",
3197             self, _page->identifier().toUInt64(), _dynamicViewportUpdateMode, _needsResetViewStateAfterCommitLoadForMainFrame, [_contentView sizeChangedSinceLastVisibleContentRectUpdate], [_scrollView isZoomBouncing], _currentlyAdjustingScrollViewInsetsForKeyboard);
3198         return;
3199     }
3200
3201     if (_didDeferUpdateVisibleContentRectsForAnyReason)
3202         RELEASE_LOG_IF_ALLOWED("%p (pageProxyID=%llu) -[WKWebView _updateVisibleContentRects:] - performing first visible content rect update after deferring updates", self, _page->identifier().toUInt64());
3203
3204     _didDeferUpdateVisibleContentRectsForUIScrollViewDelegateCallback = NO;
3205     _didDeferUpdateVisibleContentRectsForUnstableScrollView = NO;
3206     _didDeferUpdateVisibleContentRectsForAnyReason = NO;
3207
3208     CGRect visibleRectInContentCoordinates = [self _visibleContentRect];
3209
3210     UIEdgeInsets computedContentInsetUnadjustedForKeyboard = [self _computedObscuredInset];
3211     if (!_haveSetObscuredInsets)
3212         computedContentInsetUnadjustedForKeyboard.bottom -= _totalScrollViewBottomInsetAdjustmentForKeyboard;
3213
3214     CGFloat scaleFactor = contentZoomScale(self);
3215
3216     CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, computedContentInsetUnadjustedForKeyboard);
3217     CGRect unobscuredRectInContentCoordinates = _frozenUnobscuredContentRect ? _frozenUnobscuredContentRect.value() : [self convertRect:unobscuredRect toView:_contentView.get()];
3218     unobscuredRectInContentCoordinates = CGRectIntersection(unobscuredRectInContentCoordinates, [self _contentBoundsExtendedForRubberbandingWithScale:scaleFactor]);
3219
3220     // The following logic computes the extent to which the bottom, top, left and right content insets are visible.
3221     auto scrollViewInsets = [_scrollView contentInset];
3222     auto scrollViewBounds = [_scrollView bounds];
3223     auto scrollViewContentSize = [_scrollView contentSize];
3224     auto scrollViewOriginIncludingInset = UIEdgeInsetsInsetRect(scrollViewBounds, computedContentInsetUnadjustedForKeyboard).origin;
3225     auto maximumVerticalScrollExtentWithoutRevealingBottomContentInset = scrollViewContentSize.height - CGRectGetHeight(scrollViewBounds);
3226     auto maximumHorizontalScrollExtentWithoutRevealingRightContentInset = scrollViewContentSize.width - CGRectGetWidth(scrollViewBounds);
3227     auto contentInsets = UIEdgeInsetsZero;
3228     if (scrollViewInsets.left > 0 && scrollViewOriginIncludingInset.x < 0)
3229         contentInsets.left = std::min(-scrollViewOriginIncludingInset.x, scrollViewInsets.left) / scaleFactor;
3230
3231     if (scrollViewInsets.top > 0 && scrollViewOriginIncludingInset.y < 0)
3232         contentInsets.top = std::min(-scrollViewOriginIncludingInset.y, scrollViewInsets.top) / scaleFactor;
3233
3234     if (scrollViewInsets.right > 0 && scrollViewOriginIncludingInset.x > maximumHorizontalScrollExtentWithoutRevealingRightContentInset)
3235         contentInsets.right = std::min(scrollViewOriginIncludingInset.x - maximumHorizontalScrollExtentWithoutRevealingRightContentInset, scrollViewInsets.right) / scaleFactor;
3236
3237     if (scrollViewInsets.bottom > 0 && scrollViewOriginIncludingInset.y > maximumVerticalScrollExtentWithoutRevealingBottomContentInset)
3238         contentInsets.bottom = std::min(scrollViewOriginIncludingInset.y - maximumVerticalScrollExtentWithoutRevealingBottomContentInset, scrollViewInsets.bottom) / scaleFactor;
3239
3240 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
3241     if (inStableState) {
3242         WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
3243         if (coordinator && coordinator->hasActiveSnapPoint()) {
3244             CGPoint currentPoint = [_scrollView contentOffset];
3245             CGPoint activePoint = coordinator->nearestActiveContentInsetAdjustedSnapPoint(unobscuredRect.origin.y, currentPoint);
3246
3247             if (!CGPointEqualToPoint(activePoint, currentPoint)) {
3248                 RetainPtr<WKScrollView> strongScrollView = _scrollView;
3249                 dispatch_async(dispatch_get_main_queue(), [strongScrollView, activePoint] {
3250                     [strongScrollView setContentOffset:activePoint animated:NO];
3251                 });
3252             }
3253         }
3254     }
3255 #endif
3256
3257     [_contentView didUpdateVisibleRect:visibleRectInContentCoordinates
3258         unobscuredRect:unobscuredRectInContentCoordinates
3259         contentInsets:contentInsets
3260         unobscuredRectInScrollViewCoordinates:unobscuredRect
3261         obscuredInsets:_obscuredInsets
3262         unobscuredSafeAreaInsets:[self _computedUnobscuredSafeAreaInset]
3263         inputViewBounds:_inputViewBounds
3264         scale:scaleFactor minimumScale:[_scrollView minimumZoomScale]
3265         inStableState:inStableState
3266         isChangingObscuredInsetsInteractively:_isChangingObscuredInsetsInteractively
3267         enclosedInScrollableAncestorView:scrollViewCanScroll([self _scroller])];
3268
3269     while (!_visibleContentRectUpdateCallbacks.isEmpty()) {
3270         auto callback = _visibleContentRectUpdateCallbacks.takeLast();
3271         callback();
3272     }
3273
3274     if ((timeNow - _timeOfRequestForVisibleContentRectUpdate) > delayBeforeNoVisibleContentsRectsLogging)
3275         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] finally ran %.2fs after being scheduled", self, (timeNow - _timeOfRequestForVisibleContentRectUpdate).value());
3276
3277     _timeOfLastVisibleContentRectUpdate = timeNow;
3278     if (!_timeOfFirstVisibleContentRectUpdateWithPendingCommit)
3279         _timeOfFirstVisibleContentRectUpdateWithPendingCommit = timeNow;
3280 }
3281
3282 - (void)_didStartProvisionalLoadForMainFrame
3283 {
3284     if (_gestureController)
3285         _gestureController->didStartProvisionalLoadForMainFrame();
3286 }
3287
3288 static WebCore::FloatSize activeMaximumUnobscuredSize(WKWebView *webView, const CGRect& bounds)
3289 {
3290     return WebCore::FloatSize(webView->_maximumUnobscuredSizeOverride.valueOr(bounds.size));
3291 }
3292
3293 static int32_t activeOrientation(WKWebView *webView)
3294 {
3295     return webView->_overridesInterfaceOrientation ? deviceOrientationForUIInterfaceOrientation(webView->_interfaceOrientationOverride) : webView->_page->deviceOrientation();
3296 }
3297
3298 - (void)_cancelAnimatedResize
3299 {
3300     RELEASE_LOG_IF_ALLOWED("%p (pageProxyID=%llu) -[WKWebView _cancelAnimatedResize] _dynamicViewportUpdateMode %d", self, _page->identifier().toUInt64(), _dynamicViewportUpdateMode);
3301
3302     if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing)
3303         return;
3304
3305     if (!_customContentView) {
3306         if (_resizeAnimationView) {
3307             NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
3308             [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
3309             [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
3310             [_resizeAnimationView removeFromSuperview];
3311             _resizeAnimationView = nil;
3312         }
3313
3314         [_contentView setHidden:NO];
3315         _resizeAnimationTransformAdjustments = CATransform3DIdentity;
3316     }
3317
3318     _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
3319     [self _scheduleVisibleContentRectUpdate];
3320 }
3321
3322 - (void)_didCompleteAnimatedResize
3323 {
3324     if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing)
3325         return;
3326
3327     [_contentView setHidden:NO];
3328
3329     if (!_resizeAnimationView) {
3330         // Paranoia. If _resizeAnimationView is null we'll end up setting a zero scale on the content view.
3331         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didCompleteAnimatedResize:] - _resizeAnimationView is nil", self);
3332         [self _cancelAnimatedResize];
3333         return;
3334     }
3335
3336     RELEASE_LOG_IF_ALLOWED("%p (pageProxyID=%llu) -[WKWebView _didCompleteAnimatedResize]", self, _page->identifier().toUInt64());
3337
3338     NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
3339     [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
3340     [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
3341
3342     CALayer *contentLayer = [_contentView layer];
3343     CGFloat adjustmentScale = _resizeAnimationTransformAdjustments.m11;
3344     contentLayer.sublayerTransform = CATransform3DIdentity;
3345
3346     CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
3347     CATransform3D contentLayerTransform = contentLayer.transform;
3348     CGFloat currentScale = [[_resizeAnimationView layer] transform].m11 * contentLayerTransform.m11;
3349
3350     // We cannot use [UIScrollView setZoomScale:] directly because the UIScrollView delegate would get a callback with
3351     // an invalid contentOffset. The real content offset is only set below.
3352     // Since there is no public API for setting both the zoomScale and the contentOffset, we set the zoomScale manually
3353     // on the zoom layer and then only change the contentOffset.
3354     CGFloat adjustedScale = adjustmentScale * currentScale;
3355     contentLayerTransform.m11 = adjustedScale;
3356     contentLayerTransform.m22 = adjustedScale;
3357     contentLayer.transform = contentLayerTransform;
3358
3359     CGPoint currentScrollOffset = [_scrollView contentOffset];
3360     double horizontalScrollAdjustement = _resizeAnimationTransformAdjustments.m41 * animatingScaleTarget;
3361     double verticalScrollAdjustment = _resizeAnimationTransformAdjustments.m42 * animatingScaleTarget;
3362
3363     [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
3364     [_scrollView setContentOffset:CGPointMake(currentScrollOffset.x - horizontalScrollAdjustement, currentScrollOffset.y - verticalScrollAdjustment)];
3365
3366     [_resizeAnimationView removeFromSuperview];
3367     _resizeAnimationView = nil;
3368     _resizeAnimationTransformAdjustments = CATransform3DIdentity;
3369
3370     _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
3371     [self _scheduleVisibleContentRectUpdate];
3372
3373     CGRect newBounds = self.bounds;
3374     auto newViewLayoutSize = [self activeViewLayoutSize:newBounds];
3375     auto newMaximumUnobscuredSize = activeMaximumUnobscuredSize(self, newBounds);
3376     int32_t newOrientation = activeOrientation(self);
3377
3378     if (!_lastSentViewLayoutSize || newViewLayoutSize != _lastSentViewLayoutSize.value())
3379         [self _dispatchSetViewLayoutSize:newViewLayoutSize];
3380
3381     if (!_lastSentMaximumUnobscuredSize || newMaximumUnobscuredSize != _lastSentMaximumUnobscuredSize.value())
3382         [self _dispatchSetMaximumUnobscuredSize:WebCore::FloatSize(newMaximumUnobscuredSize)];
3383
3384     if (!_lastSentDeviceOrientation || newOrientation != _lastSentDeviceOrientation.value())
3385         [self _dispatchSetDeviceOrientation:newOrientation];
3386
3387     while (!_callbacksDeferredDuringResize.isEmpty())