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