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