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