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