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