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