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