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