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