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