[iOS] REGRESSION (r218144) -[WKContentView targetForAction:withSender:] returns the...
[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) && ENABLE(DRAG_SUPPORT)
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) && ENABLE(DRAG_SUPPORT)
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 #if ENABLE(DRAG_SUPPORT)
1137
1138 - (_WKDragInteractionPolicy)_dragInteractionPolicy
1139 {
1140     return _dragInteractionPolicy;
1141 }
1142
1143 - (void)_setDragInteractionPolicy:(_WKDragInteractionPolicy)policy
1144 {
1145     if (_dragInteractionPolicy == policy)
1146         return;
1147
1148     _dragInteractionPolicy = policy;
1149     [_contentView _didChangeDragInteractionPolicy];
1150 }
1151
1152 #endif
1153
1154 - (void)_populateArchivedSubviews:(NSMutableSet *)encodedViews
1155 {
1156     [super _populateArchivedSubviews:encodedViews];
1157
1158     if (_scrollView)
1159         [encodedViews removeObject:_scrollView.get()];
1160     if (_customContentFixedOverlayView)
1161         [encodedViews removeObject:_customContentFixedOverlayView.get()];
1162 }
1163
1164 - (BOOL)_isBackground
1165 {
1166     if ([self _isDisplayingPDF])
1167         return [(WKPDFView *)_customContentView isBackground];
1168
1169     return [_contentView isBackground];
1170 }
1171
1172 - (void)setFrame:(CGRect)frame
1173 {
1174     CGRect oldFrame = self.frame;
1175     [super setFrame:frame];
1176
1177     if (!CGSizeEqualToSize(oldFrame.size, frame.size))
1178         [self _frameOrBoundsChanged];
1179 }
1180
1181 - (void)setBounds:(CGRect)bounds
1182 {
1183     CGRect oldBounds = self.bounds;
1184     [super setBounds:bounds];
1185     [_customContentFixedOverlayView setFrame:self.bounds];
1186
1187     if (!CGSizeEqualToSize(oldBounds.size, bounds.size))
1188         [self _frameOrBoundsChanged];
1189 }
1190
1191 - (void)layoutSubviews
1192 {
1193     [super layoutSubviews];
1194     [self _frameOrBoundsChanged];
1195 }
1196
1197 - (UIScrollView *)scrollView
1198 {
1199     return _scrollView.get();
1200 }
1201
1202 - (WKBrowsingContextController *)browsingContextController
1203 {
1204     return [_contentView browsingContextController];
1205 }
1206
1207 - (BOOL)becomeFirstResponder
1208 {
1209     UIView *currentContentView = self._currentContentView;
1210     if (currentContentView == _contentView && [_contentView superview])
1211         return [_contentView becomeFirstResponderForWebView] || [super becomeFirstResponder];
1212
1213     return [currentContentView becomeFirstResponder] || [super becomeFirstResponder];
1214 }
1215
1216 - (BOOL)canBecomeFirstResponder
1217 {
1218     if (self._currentContentView == _contentView)
1219         return [_contentView canBecomeFirstResponderForWebView];
1220
1221     return YES;
1222 }
1223
1224 - (BOOL)resignFirstResponder
1225 {
1226     if ([_contentView isFirstResponder])
1227         return [_contentView resignFirstResponderForWebView];
1228
1229     return [super resignFirstResponder];
1230 }
1231
1232 #define FORWARD_ACTION_TO_WKCONTENTVIEW(_action) \
1233     - (void)_action:(id)sender \
1234     { \
1235         if (self.usesStandardContentView) \
1236             [_contentView _action ## ForWebView:sender]; \
1237     }
1238
1239 FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_ACTION_TO_WKCONTENTVIEW)
1240
1241 #undef FORWARD_ACTION_TO_WKCONTENTVIEW
1242
1243 - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
1244 {
1245     #define FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW(_action) \
1246         if (action == @selector(_action:)) \
1247             return self.usesStandardContentView && [_contentView canPerformActionForWebView:action withSender:sender];
1248
1249     FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW)
1250
1251     #undef FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW
1252
1253     return [super canPerformAction:action withSender:sender];
1254 }
1255
1256 - (id)targetForAction:(SEL)action withSender:(id)sender
1257 {
1258     #define FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_action) \
1259         if (action == @selector(_action:) && self.usesStandardContentView) \
1260             return [_contentView targetForActionForWebView:action withSender:sender];
1261
1262     FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW)
1263
1264     #undef FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW
1265
1266     return [super targetForAction:action withSender:sender];
1267 }
1268
1269 static inline CGFloat floorToDevicePixel(CGFloat input, float deviceScaleFactor)
1270 {
1271     return CGFloor(input * deviceScaleFactor) / deviceScaleFactor;
1272 }
1273
1274 static inline bool pointsEqualInDevicePixels(CGPoint a, CGPoint b, float deviceScaleFactor)
1275 {
1276     return fabs(a.x * deviceScaleFactor - b.x * deviceScaleFactor) < std::numeric_limits<float>::epsilon()
1277         && fabs(a.y * deviceScaleFactor - b.y * deviceScaleFactor) < std::numeric_limits<float>::epsilon();
1278 }
1279
1280 static CGSize roundScrollViewContentSize(const WebKit::WebPageProxy& page, CGSize contentSize)
1281 {
1282     float deviceScaleFactor = page.deviceScaleFactor();
1283     return CGSizeMake(floorToDevicePixel(contentSize.width, deviceScaleFactor), floorToDevicePixel(contentSize.height, deviceScaleFactor));
1284 }
1285
1286 - (UIView *)_currentContentView
1287 {
1288     return _customContentView ? _customContentView.get() : _contentView.get();
1289 }
1290
1291 - (WKWebViewContentProviderRegistry *)_contentProviderRegistry
1292 {
1293     return [_configuration _contentProviderRegistry];
1294 }
1295
1296 - (WKSelectionGranularity)_selectionGranularity
1297 {
1298     return [_configuration selectionGranularity];
1299 }
1300
1301 - (BOOL)_allowsBlockSelection
1302 {
1303     return [_configuration _allowsBlockSelection];
1304 }
1305
1306 - (void)_setHasCustomContentView:(BOOL)pageHasCustomContentView loadedMIMEType:(const WTF::String&)mimeType
1307 {
1308     if (pageHasCustomContentView) {
1309         [_customContentView removeFromSuperview];
1310         [_customContentFixedOverlayView removeFromSuperview];
1311
1312         Class representationClass = [[_configuration _contentProviderRegistry] providerForMIMEType:mimeType];
1313         ASSERT(representationClass);
1314         _customContentView = adoptNS([[representationClass alloc] web_initWithFrame:self.bounds webView:self]);
1315         _customContentFixedOverlayView = adoptNS([[UIView alloc] initWithFrame:self.bounds]);
1316         [_customContentFixedOverlayView layer].name = @"CustomContentFixedOverlay";
1317         [_customContentFixedOverlayView setUserInteractionEnabled:NO];
1318
1319         [[_contentView unscaledView] removeFromSuperview];
1320         [_contentView removeFromSuperview];
1321         [_scrollView addSubview:_customContentView.get()];
1322         [self addSubview:_customContentFixedOverlayView.get()];
1323
1324         [_customContentView web_setMinimumSize:self.bounds.size];
1325         [_customContentView web_setFixedOverlayView:_customContentFixedOverlayView.get()];
1326
1327         _scrollViewBackgroundColor = WebCore::Color();
1328         [_scrollView setContentOffset:[self _adjustedContentOffset:CGPointZero]];
1329
1330         [self _setAvoidsUnsafeArea:NO];
1331     } else if (_customContentView) {
1332         [_customContentView removeFromSuperview];
1333         _customContentView = nullptr;
1334
1335         [_customContentFixedOverlayView removeFromSuperview];
1336         _customContentFixedOverlayView = nullptr;
1337
1338         [_scrollView addSubview:_contentView.get()];
1339         [_scrollView addSubview:[_contentView unscaledView]];
1340         [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
1341
1342         [_customContentFixedOverlayView setFrame:self.bounds];
1343         [self addSubview:_customContentFixedOverlayView.get()];
1344     }
1345
1346     if (self.isFirstResponder) {
1347         UIView *currentContentView = self._currentContentView;
1348         if (currentContentView == _contentView ? [_contentView canBecomeFirstResponderForWebView] : currentContentView.canBecomeFirstResponder)
1349             [currentContentView becomeFirstResponder];
1350     }
1351 }
1352
1353 - (void)_didFinishLoadingDataForCustomContentProviderWithSuggestedFilename:(const String&)suggestedFilename data:(NSData *)data
1354 {
1355     ASSERT(_customContentView);
1356     [_customContentView web_setContentProviderData:data suggestedFilename:suggestedFilename];
1357
1358     // FIXME: It may make more sense for custom content providers to invoke this when they're ready,
1359     // because there's no guarantee that all custom content providers will lay out synchronously.
1360     _page->didLayoutForCustomContentProvider();
1361 }
1362
1363 - (void)_willInvokeUIScrollViewDelegateCallback
1364 {
1365     _delayUpdateVisibleContentRects = YES;
1366 }
1367
1368 - (void)_didInvokeUIScrollViewDelegateCallback
1369 {
1370     _delayUpdateVisibleContentRects = NO;
1371     if (_hadDelayedUpdateVisibleContentRects) {
1372         _hadDelayedUpdateVisibleContentRects = NO;
1373         [self _scheduleVisibleContentRectUpdate];
1374     }
1375 }
1376
1377 static CGFloat contentZoomScale(WKWebView *webView)
1378 {
1379     CGFloat scale = webView._currentContentView.layer.affineTransform.a;
1380     ASSERT(scale == [webView->_scrollView zoomScale]);
1381     return scale;
1382 }
1383
1384 static WebCore::Color baseScrollViewBackgroundColor(WKWebView *webView)
1385 {
1386     if (webView->_customContentView)
1387         return [webView->_customContentView backgroundColor].CGColor;
1388
1389     if (webView->_gestureController) {
1390         WebCore::Color color = webView->_gestureController->backgroundColorForCurrentSnapshot();
1391         if (color.isValid())
1392             return color;
1393     }
1394
1395     return webView->_page->pageExtendedBackgroundColor();
1396 }
1397
1398 static WebCore::Color scrollViewBackgroundColor(WKWebView *webView)
1399 {
1400     if (!webView.opaque)
1401         return WebCore::Color::transparent;
1402
1403     WebCore::Color color = baseScrollViewBackgroundColor(webView);
1404
1405     if (!color.isValid())
1406         color = WebCore::Color::white;
1407
1408     CGFloat zoomScale = contentZoomScale(webView);
1409     CGFloat minimumZoomScale = [webView->_scrollView minimumZoomScale];
1410     if (zoomScale < minimumZoomScale) {
1411         CGFloat slope = 12;
1412         CGFloat opacity = std::max<CGFloat>(1 - slope * (minimumZoomScale - zoomScale), 0);
1413         color = WebCore::colorWithOverrideAlpha(color.rgb(), opacity);
1414     }
1415
1416     return color;
1417 }
1418
1419 - (void)_updateScrollViewBackground
1420 {
1421     WebCore::Color color = scrollViewBackgroundColor(self);
1422
1423     if (_scrollViewBackgroundColor == color)
1424         return;
1425
1426     _scrollViewBackgroundColor = color;
1427
1428     auto uiBackgroundColor = adoptNS([[UIColor alloc] initWithCGColor:cachedCGColor(color)]);
1429     [_scrollView setBackgroundColor:uiBackgroundColor.get()];
1430
1431     // Update the indicator style based on the lightness/darkness of the background color.
1432     double hue, saturation, lightness;
1433     color.getHSL(hue, saturation, lightness);
1434     if (lightness <= .5 && color.isVisible())
1435         [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleWhite];
1436     else
1437         [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleDefault];
1438 }
1439
1440 - (CGPoint)_adjustedContentOffset:(CGPoint)point
1441 {
1442     CGPoint result = point;
1443     UIEdgeInsets contentInset = [self _computedContentInset];
1444
1445     result.x -= contentInset.left;
1446     result.y -= contentInset.top;
1447
1448     return result;
1449 }
1450
1451 - (UIRectEdge)_effectiveObscuredInsetEdgesAffectedBySafeArea
1452 {
1453     if (![self usesStandardContentView])
1454         return UIRectEdgeAll;
1455     return _obscuredInsetEdgesAffectedBySafeArea;
1456 }
1457
1458 - (UIEdgeInsets)_computedContentInset
1459 {
1460     if (_haveSetObscuredInsets)
1461         return _obscuredInsets;
1462
1463     UIEdgeInsets insets = [_scrollView contentInset];
1464
1465 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1466     if (self._safeAreaShouldAffectObscuredInsets)
1467         insets = UIEdgeInsetsAdd(insets, [_scrollView _systemContentInset], self._effectiveObscuredInsetEdgesAffectedBySafeArea);
1468 #endif
1469
1470     return insets;
1471 }
1472
1473 - (UIEdgeInsets)_computedUnobscuredSafeAreaInset
1474 {
1475     if (_haveSetUnobscuredSafeAreaInsets)
1476         return _unobscuredSafeAreaInsets;
1477
1478 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1479     if (!self._safeAreaShouldAffectObscuredInsets)
1480         return self.safeAreaInsets;
1481 #endif
1482
1483     return UIEdgeInsetsZero;
1484 }
1485
1486 - (void)_processDidExit
1487 {
1488     [self _hidePasswordView];
1489     if (!_customContentView && _dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
1490         NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
1491         [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
1492         [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
1493         [_resizeAnimationView removeFromSuperview];
1494         _resizeAnimationView = nil;
1495
1496         _resizeAnimationTransformAdjustments = CATransform3DIdentity;
1497     }
1498     [_contentView setFrame:self.bounds];
1499     [_scrollView setBackgroundColor:[UIColor whiteColor]];
1500     [_scrollView setContentOffset:[self _adjustedContentOffset:CGPointZero]];
1501     [_scrollView setZoomScale:1];
1502
1503     _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
1504     _initialScaleFactor = 1;
1505     _hasCommittedLoadForMainFrame = NO;
1506     _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1507     _dynamicViewportUpdateMode = DynamicViewportUpdateMode::NotResizing;
1508     [_contentView setHidden:NO];
1509     _scrollOffsetToRestore = std::nullopt;
1510     _unobscuredCenterToRestore = std::nullopt;
1511     _scrollViewBackgroundColor = WebCore::Color();
1512     _delayUpdateVisibleContentRects = NO;
1513     _hadDelayedUpdateVisibleContentRects = NO;
1514
1515     _frozenVisibleContentRect = std::nullopt;
1516     _frozenUnobscuredContentRect = std::nullopt;
1517
1518     _firstPaintAfterCommitLoadTransactionID = 0;
1519     _firstTransactionIDAfterPageRestore = 0;
1520     _resizeAnimationTransformTransactionID = std::nullopt;
1521
1522     _avoidsUnsafeArea = YES;
1523 }
1524
1525 - (void)_didCommitLoadForMainFrame
1526 {
1527     _firstPaintAfterCommitLoadTransactionID = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1528
1529     _hasCommittedLoadForMainFrame = YES;
1530     _needsResetViewStateAfterCommitLoadForMainFrame = YES;
1531
1532     [_scrollView _stopScrollingAndZoomingAnimations];
1533 }
1534
1535 static CGPoint contentOffsetBoundedInValidRange(UIScrollView *scrollView, CGPoint contentOffset)
1536 {
1537     UIEdgeInsets contentInsets = scrollView.contentInset;
1538     CGSize contentSize = scrollView.contentSize;
1539     CGSize scrollViewSize = scrollView.bounds.size;
1540
1541     CGFloat maxHorizontalOffset = contentSize.width + contentInsets.right - scrollViewSize.width;
1542     contentOffset.x = std::min(maxHorizontalOffset, contentOffset.x);
1543     contentOffset.x = std::max(-contentInsets.left, contentOffset.x);
1544
1545     CGFloat maxVerticalOffset = contentSize.height + contentInsets.bottom - scrollViewSize.height;
1546     contentOffset.y = std::min(maxVerticalOffset, contentOffset.y);
1547     contentOffset.y = std::max(-contentInsets.top, contentOffset.y);
1548     return contentOffset;
1549 }
1550
1551 static void changeContentOffsetBoundedInValidRange(UIScrollView *scrollView, WebCore::FloatPoint contentOffset)
1552 {
1553     scrollView.contentOffset = contentOffsetBoundedInValidRange(scrollView, contentOffset);
1554 }
1555
1556 - (WebCore::FloatRect)visibleRectInViewCoordinates
1557 {
1558     WebCore::FloatRect bounds = self.bounds;
1559     bounds.moveBy([_scrollView contentOffset]);
1560     WebCore::FloatRect contentViewBounds = [_contentView bounds];
1561     bounds.intersect(contentViewBounds);
1562     return bounds;
1563 }
1564
1565 // WebCore stores the page scale factor as float instead of double. When we get a scale from WebCore,
1566 // we need to ignore differences that are within a small rounding error on floats.
1567 static inline bool areEssentiallyEqualAsFloat(float a, float b)
1568 {
1569     return WTF::areEssentiallyEqual(a, b);
1570 }
1571
1572 - (void)_didCommitLayerTree:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
1573 {
1574     if (![self usesStandardContentView])
1575         return;
1576
1577     LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView _didCommitLayerTree:] transactionID " <<  layerTreeTransaction.transactionID() << " _dynamicViewportUpdateMode " << (int)_dynamicViewportUpdateMode);
1578
1579     bool needUpdateVisibleContentRects = _page->updateLayoutViewportParameters(layerTreeTransaction);
1580
1581     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
1582         if (_resizeAnimationTransformTransactionID && layerTreeTransaction.transactionID() >= _resizeAnimationTransformTransactionID.value()) {
1583             _resizeAnimationTransformTransactionID = std::nullopt;
1584             [_resizeAnimationView layer].sublayerTransform = _resizeAnimationTransformAdjustments;
1585             if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::ResizingWithDocumentHidden) {
1586                 [_contentView setHidden:NO];
1587                 [self _endAnimatedResize];
1588             }
1589         }
1590         return;
1591     }
1592
1593     if (_activeAnimatedResizeCount)
1594         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didCommitLayerTree:] - %d animated resizes in flight", self, _activeAnimatedResizeCount);
1595
1596     CGSize newContentSize = roundScrollViewContentSize(*_page, [_contentView frame].size);
1597     [_scrollView _setContentSizePreservingContentOffsetDuringRubberband:newContentSize];
1598
1599     [_scrollView setMinimumZoomScale:layerTreeTransaction.minimumScaleFactor()];
1600     [_scrollView setMaximumZoomScale:layerTreeTransaction.maximumScaleFactor()];
1601     [_scrollView setZoomEnabled:layerTreeTransaction.allowsUserScaling()];
1602     if (!layerTreeTransaction.scaleWasSetByUIProcess() && ![_scrollView isZooming] && ![_scrollView isZoomBouncing] && ![_scrollView _isAnimatingZoom] && [_scrollView zoomScale] != layerTreeTransaction.pageScaleFactor())
1603         [_scrollView setZoomScale:layerTreeTransaction.pageScaleFactor()];
1604
1605     _viewportMetaTagWidth = layerTreeTransaction.viewportMetaTagWidth();
1606     _viewportMetaTagWidthWasExplicit = layerTreeTransaction.viewportMetaTagWidthWasExplicit();
1607     _viewportMetaTagCameFromImageDocument = layerTreeTransaction.viewportMetaTagCameFromImageDocument();
1608     _initialScaleFactor = layerTreeTransaction.initialScaleFactor();
1609     if (_page->inStableState() && layerTreeTransaction.isInStableState() && [_stableStatePresentationUpdateCallbacks count]) {
1610         for (dispatch_block_t action in _stableStatePresentationUpdateCallbacks.get())
1611             action();
1612
1613         [_stableStatePresentationUpdateCallbacks removeAllObjects];
1614         _stableStatePresentationUpdateCallbacks = nil;
1615     }
1616
1617     if (![_contentView _mayDisableDoubleTapGesturesDuringSingleTap])
1618         [_contentView _setDoubleTapGesturesEnabled:self._allowsDoubleTapGestures];
1619
1620     [self _updateScrollViewBackground];
1621     [self _setAvoidsUnsafeArea:layerTreeTransaction.avoidsUnsafeArea()];
1622
1623     if (_gestureController)
1624         _gestureController->setRenderTreeSize(layerTreeTransaction.renderTreeSize());
1625
1626     if (_needsResetViewStateAfterCommitLoadForMainFrame && layerTreeTransaction.transactionID() >= _firstPaintAfterCommitLoadTransactionID) {
1627         _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1628         [_scrollView setContentOffset:[self _adjustedContentOffset:CGPointZero]];
1629         if (_observedRenderingProgressEvents & _WKRenderingProgressEventFirstPaint)
1630             _navigationState->didFirstPaint();
1631
1632         needUpdateVisibleContentRects = true;
1633     }
1634
1635     if (layerTreeTransaction.transactionID() >= _firstTransactionIDAfterPageRestore) {
1636         bool shouldRestoreScrollPosition = false;
1637         if (_scrollOffsetToRestore) {
1638             WebCore::FloatPoint scaledScrollOffset = _scrollOffsetToRestore.value();
1639             _scrollOffsetToRestore = std::nullopt;
1640
1641             if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1642                 scaledScrollOffset.scale(_scaleToRestore);
1643                 WebCore::FloatPoint contentOffsetInScrollViewCoordinates = scaledScrollOffset - WebCore::FloatSize(_obscuredInsetsWhenSaved.left(), _obscuredInsetsWhenSaved.top());
1644
1645                 changeContentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
1646                 _commitDidRestoreScrollPosition = YES;
1647
1648                 shouldRestoreScrollPosition = true;
1649             }
1650
1651             needUpdateVisibleContentRects = true;
1652         }
1653
1654         if (_unobscuredCenterToRestore) {
1655             WebCore::FloatPoint unobscuredCenterToRestore = _unobscuredCenterToRestore.value();
1656             _unobscuredCenterToRestore = std::nullopt;
1657
1658             if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1659                 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, _obscuredInsets);
1660                 WebCore::FloatSize unobscuredContentSizeAtNewScale(unobscuredRect.size.width / _scaleToRestore, unobscuredRect.size.height / _scaleToRestore);
1661                 WebCore::FloatPoint topLeftInDocumentCoordinates(unobscuredCenterToRestore.x() - unobscuredContentSizeAtNewScale.width() / 2, unobscuredCenterToRestore.y() - unobscuredContentSizeAtNewScale.height() / 2);
1662
1663                 topLeftInDocumentCoordinates.scale(_scaleToRestore);
1664                 topLeftInDocumentCoordinates.moveBy(WebCore::FloatPoint(-_obscuredInsets.left, -_obscuredInsets.top));
1665
1666                 changeContentOffsetBoundedInValidRange(_scrollView.get(), topLeftInDocumentCoordinates);
1667
1668                 shouldRestoreScrollPosition = true;
1669             }
1670
1671             needUpdateVisibleContentRects = true;
1672         }
1673
1674         if (shouldRestoreScrollPosition && _gestureController)
1675             _gestureController->didRestoreScrollPosition();
1676     }
1677
1678     if (needUpdateVisibleContentRects)
1679         [self _scheduleVisibleContentRectUpdate];
1680
1681     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
1682         scrollPerfData->didCommitLayerTree([self visibleRectInViewCoordinates]);
1683 }
1684
1685 - (void)_layerTreeCommitComplete
1686 {
1687     _commitDidRestoreScrollPosition = NO;
1688 }
1689
1690 - (void)_dynamicViewportUpdateChangedTargetToScale:(double)newScale position:(CGPoint)newScrollPosition nextValidLayerTreeTransactionID:(uint64_t)nextValidLayerTreeTransactionID
1691 {
1692     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
1693         CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
1694         double currentTargetScale = animatingScaleTarget * [[_contentView layer] transform].m11;
1695         double scale = newScale / currentTargetScale;
1696         _resizeAnimationTransformAdjustments = CATransform3DMakeScale(scale, scale, 1);
1697
1698         CGPoint newContentOffset = [self _adjustedContentOffset:CGPointMake(newScrollPosition.x * newScale, newScrollPosition.y * newScale)];
1699         CGPoint currentContentOffset = [_scrollView contentOffset];
1700
1701         _resizeAnimationTransformAdjustments.m41 = (currentContentOffset.x - newContentOffset.x) / animatingScaleTarget;
1702         _resizeAnimationTransformAdjustments.m42 = (currentContentOffset.y - newContentOffset.y) / animatingScaleTarget;
1703         _resizeAnimationTransformTransactionID = nextValidLayerTreeTransactionID;
1704     }
1705 }
1706
1707 - (void)_couldNotRestorePageState
1708 {
1709     // The gestureController may be waiting for the scroll position to be restored
1710     // in order to remove the swipe snapshot. Since the scroll position could not be
1711     // restored, tell the gestureController it was restored so that it no longer waits
1712     // for it.
1713     if (_gestureController)
1714         _gestureController->didRestoreScrollPosition();
1715 }
1716
1717 - (void)_restorePageScrollPosition:(std::optional<WebCore::FloatPoint>)scrollPosition scrollOrigin:(WebCore::FloatPoint)scrollOrigin previousObscuredInset:(WebCore::FloatBoxExtent)obscuredInsets scale:(double)scale
1718 {
1719     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1720         return;
1721
1722     if (![self usesStandardContentView])
1723         return;
1724
1725     _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1726     if (scrollPosition)
1727         _scrollOffsetToRestore = WebCore::ScrollableArea::scrollOffsetFromPosition(WebCore::FloatPoint(scrollPosition.value()), WebCore::toFloatSize(scrollOrigin));
1728     else
1729         _scrollOffsetToRestore = std::nullopt;
1730
1731     _obscuredInsetsWhenSaved = obscuredInsets;
1732     _scaleToRestore = scale;
1733 }
1734
1735 - (void)_restorePageStateToUnobscuredCenter:(std::optional<WebCore::FloatPoint>)center scale:(double)scale
1736 {
1737     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1738         return;
1739
1740     if (![self usesStandardContentView])
1741         return;
1742
1743     _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1744     _unobscuredCenterToRestore = center.value();
1745
1746     _scaleToRestore = scale;
1747 }
1748
1749 - (RefPtr<WebKit::ViewSnapshot>)_takeViewSnapshot
1750 {
1751     float deviceScale = WebCore::screenScaleFactor();
1752     WebCore::FloatSize snapshotSize(self.bounds.size);
1753     snapshotSize.scale(deviceScale);
1754
1755     CATransform3D transform = CATransform3DMakeScale(deviceScale, deviceScale, 1);
1756
1757 #if USE(IOSURFACE)
1758     WebCore::IOSurface::Format snapshotFormat = WebCore::screenSupportsExtendedColor() ? WebCore::IOSurface::Format::RGB10 : WebCore::IOSurface::Format::RGBA;
1759     auto surface = WebCore::IOSurface::create(WebCore::expandedIntSize(snapshotSize), WebCore::sRGBColorSpaceRef(), snapshotFormat);
1760     if (!surface)
1761         return nullptr;
1762     CARenderServerRenderLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, reinterpret_cast<uint64_t>(self.layer), surface->surface(), 0, 0, &transform);
1763
1764     WebCore::IOSurface::Format compressedFormat = WebCore::IOSurface::Format::YUV422;
1765     if (WebCore::IOSurface::allowConversionFromFormatToFormat(snapshotFormat, compressedFormat)) {
1766         RefPtr<WebKit::ViewSnapshot> viewSnapshot = WebKit::ViewSnapshot::create(nullptr);
1767         WebCore::IOSurface::convertToFormat(WTFMove(surface), WebCore::IOSurface::Format::YUV422, [viewSnapshot](std::unique_ptr<WebCore::IOSurface> convertedSurface) {
1768             if (convertedSurface)
1769                 viewSnapshot->setSurface(WTFMove(convertedSurface));
1770         });
1771
1772         return viewSnapshot;
1773     }
1774
1775     return WebKit::ViewSnapshot::create(WTFMove(surface));
1776 #else
1777     uint32_t slotID = [WebKit::ViewSnapshotStore::snapshottingContext() createImageSlot:snapshotSize hasAlpha:YES];
1778
1779     if (!slotID)
1780         return nullptr;
1781
1782     CARenderServerCaptureLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, (uint64_t)self.layer, slotID, 0, 0, &transform);
1783     WebCore::IntSize imageSize = WebCore::expandedIntSize(WebCore::FloatSize(snapshotSize));
1784     return WebKit::ViewSnapshot::create(slotID, imageSize, (imageSize.area() * 4).unsafeGet());
1785 #endif
1786 }
1787
1788 - (void)_zoomToPoint:(WebCore::FloatPoint)point atScale:(double)scale animated:(BOOL)animated
1789 {
1790     CFTimeInterval duration = 0;
1791     CGFloat zoomScale = contentZoomScale(self);
1792
1793     if (animated) {
1794         const double maximumZoomDuration = 0.4;
1795         const double minimumZoomDuration = 0.1;
1796         const double zoomDurationFactor = 0.3;
1797
1798         duration = std::min(fabs(log(zoomScale) - log(scale)) * zoomDurationFactor + minimumZoomDuration, maximumZoomDuration);
1799     }
1800
1801     if (scale != zoomScale)
1802         _page->willStartUserTriggeredZooming();
1803
1804     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToPoint:" << point << " scale: " << scale << " duration:" << duration);
1805
1806     [_scrollView _zoomToCenter:point scale:scale duration:duration];
1807 }
1808
1809 - (void)_zoomToRect:(WebCore::FloatRect)targetRect atScale:(double)scale origin:(WebCore::FloatPoint)origin animated:(BOOL)animated
1810 {
1811     // FIXME: Some of this could be shared with _scrollToRect.
1812     const double visibleRectScaleChange = contentZoomScale(self) / scale;
1813     const WebCore::FloatRect visibleRect([self convertRect:self.bounds toView:self._currentContentView]);
1814     const WebCore::FloatRect unobscuredRect([self _contentRectForUserInteraction]);
1815
1816     const WebCore::FloatSize topLeftObscuredInsetAfterZoom((unobscuredRect.minXMinYCorner() - visibleRect.minXMinYCorner()) * visibleRectScaleChange);
1817     const WebCore::FloatSize bottomRightObscuredInsetAfterZoom((visibleRect.maxXMaxYCorner() - unobscuredRect.maxXMaxYCorner()) * visibleRectScaleChange);
1818
1819     const WebCore::FloatSize unobscuredRectSizeAfterZoom(unobscuredRect.size() * visibleRectScaleChange);
1820
1821     // Center to the target rect.
1822     WebCore::FloatPoint unobscuredRectLocationAfterZoom = targetRect.location() - (unobscuredRectSizeAfterZoom - targetRect.size()) * 0.5;
1823
1824     // Center to the tap point instead in case the target rect won't fit in a direction.
1825     if (targetRect.width() > unobscuredRectSizeAfterZoom.width())
1826         unobscuredRectLocationAfterZoom.setX(origin.x() - unobscuredRectSizeAfterZoom.width() / 2);
1827     if (targetRect.height() > unobscuredRectSizeAfterZoom.height())
1828         unobscuredRectLocationAfterZoom.setY(origin.y() - unobscuredRectSizeAfterZoom.height() / 2);
1829
1830     // We have computed where we want the unobscured rect to be. Now adjust for the obscuring insets.
1831     WebCore::FloatRect visibleRectAfterZoom(unobscuredRectLocationAfterZoom, unobscuredRectSizeAfterZoom);
1832     visibleRectAfterZoom.move(-topLeftObscuredInsetAfterZoom);
1833     visibleRectAfterZoom.expand(topLeftObscuredInsetAfterZoom + bottomRightObscuredInsetAfterZoom);
1834
1835     [self _zoomToPoint:visibleRectAfterZoom.center() atScale:scale animated:animated];
1836 }
1837
1838 static WebCore::FloatPoint constrainContentOffset(WebCore::FloatPoint contentOffset, WebCore::FloatSize contentSize, WebCore::FloatSize unobscuredContentSize)
1839 {
1840     WebCore::FloatSize maximumContentOffset = contentSize - unobscuredContentSize;
1841     return contentOffset.constrainedBetween(WebCore::FloatPoint(), WebCore::FloatPoint(maximumContentOffset));
1842 }
1843
1844 - (void)_scrollToContentScrollPosition:(WebCore::FloatPoint)scrollPosition scrollOrigin:(WebCore::IntPoint)scrollOrigin
1845 {
1846     if (_commitDidRestoreScrollPosition || _dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1847         return;
1848
1849     WebCore::FloatPoint contentOffset = WebCore::ScrollableArea::scrollOffsetFromPosition(scrollPosition, toFloatSize(scrollOrigin));
1850
1851     WebCore::FloatPoint scaledOffset = contentOffset;
1852     CGFloat zoomScale = contentZoomScale(self);
1853     scaledOffset.scale(zoomScale);
1854
1855     CGPoint contentOffsetInScrollViewCoordinates = [self _adjustedContentOffset:scaledOffset];
1856     contentOffsetInScrollViewCoordinates = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
1857
1858     [_scrollView _stopScrollingAndZoomingAnimations];
1859
1860     if (!CGPointEqualToPoint(contentOffsetInScrollViewCoordinates, [_scrollView contentOffset]))
1861         [_scrollView setContentOffset:contentOffsetInScrollViewCoordinates];
1862     else {
1863         // If we haven't changed anything, there would not be any VisibleContentRect update sent to the content.
1864         // The WebProcess would keep the invalid contentOffset as its scroll position.
1865         // To synchronize the WebProcess with what is on screen, we send the VisibleContentRect again.
1866         _page->resendLastVisibleContentRects();
1867     }
1868 }
1869
1870 - (BOOL)_scrollToRect:(WebCore::FloatRect)targetRect origin:(WebCore::FloatPoint)origin minimumScrollDistance:(float)minimumScrollDistance
1871 {
1872     WebCore::FloatRect unobscuredContentRect([self _contentRectForUserInteraction]);
1873     WebCore::FloatPoint unobscuredContentOffset = unobscuredContentRect.location();
1874     WebCore::FloatSize contentSize([self._currentContentView bounds].size);
1875
1876     // Center the target rect in the scroll view.
1877     // If the target doesn't fit in the scroll view, center on the gesture location instead.
1878     WebCore::FloatPoint newUnobscuredContentOffset;
1879     if (targetRect.width() <= unobscuredContentRect.width())
1880         newUnobscuredContentOffset.setX(targetRect.x() - (unobscuredContentRect.width() - targetRect.width()) / 2);
1881     else
1882         newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
1883     if (targetRect.height() <= unobscuredContentRect.height())
1884         newUnobscuredContentOffset.setY(targetRect.y() - (unobscuredContentRect.height() - targetRect.height()) / 2);
1885     else
1886         newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
1887     newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
1888
1889     if (unobscuredContentOffset == newUnobscuredContentOffset) {
1890         if (targetRect.width() > unobscuredContentRect.width())
1891             newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
1892         if (targetRect.height() > unobscuredContentRect.height())
1893             newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
1894         newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
1895     }
1896
1897     WebCore::FloatSize scrollViewOffsetDelta = newUnobscuredContentOffset - unobscuredContentOffset;
1898     scrollViewOffsetDelta.scale(contentZoomScale(self));
1899
1900     float scrollDistance = scrollViewOffsetDelta.diagonalLength();
1901     if (scrollDistance < minimumScrollDistance)
1902         return false;
1903
1904     [_contentView willStartZoomOrScroll];
1905
1906     LOG_WITH_STREAM(VisibleRects, stream << "_scrollToRect: scrolling to " << [_scrollView contentOffset] + scrollViewOffsetDelta);
1907
1908     [_scrollView setContentOffset:([_scrollView contentOffset] + scrollViewOffsetDelta) animated:YES];
1909     return true;
1910 }
1911
1912 - (void)_scrollByContentOffset:(WebCore::FloatPoint)contentOffsetDelta
1913 {
1914     WebCore::FloatPoint scaledOffsetDelta = contentOffsetDelta;
1915     CGFloat zoomScale = contentZoomScale(self);
1916     scaledOffsetDelta.scale(zoomScale);
1917
1918     CGPoint currentOffset = [_scrollView _isAnimatingScroll] ? [_scrollView _animatedTargetOffset] : [_scrollView contentOffset];
1919     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), currentOffset + scaledOffsetDelta);
1920
1921     if (CGPointEqualToPoint(boundedOffset, currentOffset))
1922         return;
1923     [_contentView willStartZoomOrScroll];
1924
1925     LOG_WITH_STREAM(VisibleRects, stream << "_scrollByContentOffset: scrolling to " << WebCore::FloatPoint(boundedOffset));
1926
1927     [_scrollView setContentOffset:boundedOffset animated:YES];
1928 }
1929
1930 - (void)_zoomOutWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
1931 {
1932     [self _zoomToPoint:origin atScale:[_scrollView minimumZoomScale] animated:animated];
1933 }
1934
1935 - (void)_zoomToInitialScaleWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
1936 {
1937     ASSERT(_initialScaleFactor > 0);
1938     [self _zoomToPoint:origin atScale:_initialScaleFactor animated:animated];
1939 }
1940
1941 // focusedElementRect and selectionRect are both in document coordinates.
1942 - (void)_zoomToFocusRect:(WebCore::FloatRect)focusedElementRectInDocumentCoordinates selectionRect:(WebCore::FloatRect)selectionRectInDocumentCoordinates insideFixed:(BOOL)insideFixed
1943     fontSize:(float)fontSize minimumScale:(double)minimumScale maximumScale:(double)maximumScale allowScaling:(BOOL)allowScaling forceScroll:(BOOL)forceScroll
1944 {
1945     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToFocusRect:" << focusedElementRectInDocumentCoordinates << " selectionRect:" << selectionRectInDocumentCoordinates);
1946     UNUSED_PARAM(insideFixed);
1947
1948     const double WKWebViewStandardFontSize = 16;
1949     const double kMinimumHeightToShowContentAboveKeyboard = 106;
1950     const CFTimeInterval UIWebFormAnimationDuration = 0.25;
1951     const double CaretOffsetFromWindowEdge = 20;
1952
1953     // Zoom around the element's bounding frame. We use a "standard" size to determine the proper frame.
1954     double scale = allowScaling ? std::min(std::max(WKWebViewStandardFontSize / fontSize, minimumScale), maximumScale) : contentZoomScale(self);
1955     CGFloat documentWidth = [_contentView bounds].size.width;
1956     scale = CGRound(documentWidth * scale) / documentWidth;
1957
1958     UIWindow *window = [_scrollView window];
1959
1960     WebCore::FloatRect focusedElementRectInNewScale = focusedElementRectInDocumentCoordinates;
1961     focusedElementRectInNewScale.scale(scale);
1962     focusedElementRectInNewScale.moveBy([_contentView frame].origin);
1963
1964     // Find the portion of the view that is visible on the screen.
1965     UIViewController *topViewController = [[[_scrollView _viewControllerForAncestor] _rootAncestorViewController] _viewControllerForSupportedInterfaceOrientations];
1966     UIView *fullScreenView = topViewController.view;
1967     if (!fullScreenView)
1968         fullScreenView = window;
1969
1970     CGRect unobscuredScrollViewRectInWebViewCoordinates = UIEdgeInsetsInsetRect([self bounds], _obscuredInsets);
1971     CGRect visibleScrollViewBoundsInWebViewCoordinates = CGRectIntersection(unobscuredScrollViewRectInWebViewCoordinates, [fullScreenView convertRect:[fullScreenView bounds] toView:self]);
1972     CGRect formAssistantFrameInWebViewCoordinates = [window convertRect:_inputViewBounds toView:self];
1973     CGRect intersectionBetweenScrollViewAndFormAssistant = CGRectIntersection(visibleScrollViewBoundsInWebViewCoordinates, formAssistantFrameInWebViewCoordinates);
1974     CGSize visibleSize = visibleScrollViewBoundsInWebViewCoordinates.size;
1975
1976     CGFloat visibleOffsetFromTop = 0;
1977     if (!CGRectIsEmpty(intersectionBetweenScrollViewAndFormAssistant)) {
1978         CGFloat heightVisibleAboveFormAssistant = CGRectGetMinY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
1979         CGFloat heightVisibleBelowFormAssistant = CGRectGetMaxY(visibleScrollViewBoundsInWebViewCoordinates) - CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant);
1980
1981         if (heightVisibleAboveFormAssistant >= kMinimumHeightToShowContentAboveKeyboard || heightVisibleBelowFormAssistant < heightVisibleAboveFormAssistant)
1982             visibleSize.height = heightVisibleAboveFormAssistant;
1983         else {
1984             visibleSize.height = heightVisibleBelowFormAssistant;
1985             visibleOffsetFromTop = CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
1986         }
1987     }
1988
1989     BOOL selectionRectIsNotNull = !selectionRectInDocumentCoordinates.isZero();
1990     if (!forceScroll) {
1991         CGRect currentlyVisibleRegionInWebViewCoordinates;
1992         currentlyVisibleRegionInWebViewCoordinates.origin = unobscuredScrollViewRectInWebViewCoordinates.origin;
1993         currentlyVisibleRegionInWebViewCoordinates.origin.y += visibleOffsetFromTop;
1994         currentlyVisibleRegionInWebViewCoordinates.size = visibleSize;
1995
1996         // Don't bother scrolling if the entire node is already visible, whether or not we got a selectionRect.
1997         if (CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:focusedElementRectInDocumentCoordinates fromView:_contentView.get()]))
1998             return;
1999
2000         // Don't bother scrolling if we have a valid selectionRect and it is already visible.
2001         if (selectionRectIsNotNull && CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:selectionRectInDocumentCoordinates fromView:_contentView.get()]))
2002             return;
2003     }
2004
2005     // We want to zoom to the left/top corner of the DOM node, with as much spacing on all sides as we
2006     // can get based on the visible area after zooming (workingFrame).  The spacing in either dimension is half the
2007     // difference between the size of the DOM node and the size of the visible frame.
2008     CGFloat horizontalSpaceInWebViewCoordinates = std::max((visibleSize.width - focusedElementRectInNewScale.width()) / 2.0, 0.0);
2009     CGFloat verticalSpaceInWebViewCoordinates = std::max((visibleSize.height - focusedElementRectInNewScale.height()) / 2.0, 0.0);
2010
2011     CGPoint topLeft;
2012     topLeft.x = focusedElementRectInNewScale.x() - horizontalSpaceInWebViewCoordinates;
2013     topLeft.y = focusedElementRectInNewScale.y() - verticalSpaceInWebViewCoordinates - visibleOffsetFromTop;
2014
2015     CGFloat minimumAllowableHorizontalOffsetInWebViewCoordinates = -INFINITY;
2016     CGFloat minimumAllowableVerticalOffsetInWebViewCoordinates = -INFINITY;
2017     if (selectionRectIsNotNull) {
2018         WebCore::FloatRect selectionRectInNewScale = selectionRectInDocumentCoordinates;
2019         selectionRectInNewScale.scale(scale);
2020         selectionRectInNewScale.moveBy([_contentView frame].origin);
2021         minimumAllowableHorizontalOffsetInWebViewCoordinates = CGRectGetMaxX(selectionRectInNewScale) + CaretOffsetFromWindowEdge - visibleSize.width;
2022         minimumAllowableVerticalOffsetInWebViewCoordinates = CGRectGetMaxY(selectionRectInNewScale) + CaretOffsetFromWindowEdge - visibleSize.height - visibleOffsetFromTop;
2023     }
2024
2025     WebCore::FloatRect documentBoundsInNewScale = [_contentView bounds];
2026     documentBoundsInNewScale.scale(scale);
2027     documentBoundsInNewScale.moveBy([_contentView frame].origin);
2028
2029     // Constrain the left edge in document coordinates so that:
2030     //  - it isn't so small that the scrollVisibleRect isn't visible on the screen
2031     //  - it isn't so great that the document's right edge is less than the right edge of the screen
2032     if (selectionRectIsNotNull && topLeft.x < minimumAllowableHorizontalOffsetInWebViewCoordinates)
2033         topLeft.x = minimumAllowableHorizontalOffsetInWebViewCoordinates;
2034     else {
2035         CGFloat maximumAllowableHorizontalOffset = CGRectGetMaxX(documentBoundsInNewScale) - visibleSize.width;
2036         if (topLeft.x > maximumAllowableHorizontalOffset)
2037             topLeft.x = maximumAllowableHorizontalOffset;
2038     }
2039
2040     // Constrain the top edge in document coordinates so that:
2041     //  - it isn't so small that the scrollVisibleRect isn't visible on the screen
2042     //  - it isn't so great that the document's bottom edge is higher than the top of the form assistant
2043     if (selectionRectIsNotNull && topLeft.y < minimumAllowableVerticalOffsetInWebViewCoordinates)
2044         topLeft.y = minimumAllowableVerticalOffsetInWebViewCoordinates;
2045     else {
2046         CGFloat maximumAllowableVerticalOffset = CGRectGetMaxY(documentBoundsInNewScale) - visibleSize.height;
2047         if (topLeft.y > maximumAllowableVerticalOffset)
2048             topLeft.y = maximumAllowableVerticalOffset;
2049     }
2050
2051     WebCore::FloatPoint newCenter = CGPointMake(topLeft.x + unobscuredScrollViewRectInWebViewCoordinates.size.width / 2.0, topLeft.y + unobscuredScrollViewRectInWebViewCoordinates.size.height / 2.0);
2052
2053     if (scale != contentZoomScale(self))
2054         _page->willStartUserTriggeredZooming();
2055
2056     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToFocusRect: zooming to " << newCenter << " scale:" << scale);
2057
2058     // The newCenter has been computed in the new scale, but _zoomToCenter expected the center to be in the original scale.
2059     newCenter.scale(1 / scale);
2060     [_scrollView _zoomToCenter:newCenter
2061                         scale:scale
2062                      duration:UIWebFormAnimationDuration
2063                         force:YES];
2064 }
2065
2066 - (CGFloat)_targetContentZoomScaleForRect:(const WebCore::FloatRect&)targetRect currentScale:(double)currentScale fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale
2067 {
2068     WebCore::FloatSize unobscuredContentSize([self _contentRectForUserInteraction].size);
2069     double horizontalScale = unobscuredContentSize.width() * currentScale / targetRect.width();
2070     double verticalScale = unobscuredContentSize.height() * currentScale / targetRect.height();
2071
2072     horizontalScale = std::min(std::max(horizontalScale, minimumScale), maximumScale);
2073     verticalScale = std::min(std::max(verticalScale, minimumScale), maximumScale);
2074
2075     return fitEntireRect ? std::min(horizontalScale, verticalScale) : horizontalScale;
2076 }
2077
2078 - (BOOL)_zoomToRect:(WebCore::FloatRect)targetRect withOrigin:(WebCore::FloatPoint)origin fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale minimumScrollDistance:(float)minimumScrollDistance
2079 {
2080     const float maximumScaleFactorDeltaForPanScroll = 0.02;
2081
2082     double currentScale = contentZoomScale(self);
2083     double targetScale = [self _targetContentZoomScaleForRect:targetRect currentScale:currentScale fitEntireRect:fitEntireRect minimumScale:minimumScale maximumScale:maximumScale];
2084
2085     if (fabs(targetScale - currentScale) < maximumScaleFactorDeltaForPanScroll) {
2086         if ([self _scrollToRect:targetRect origin:origin minimumScrollDistance:minimumScrollDistance])
2087             return true;
2088     } else if (targetScale != currentScale) {
2089         [self _zoomToRect:targetRect atScale:targetScale origin:origin animated:YES];
2090         return true;
2091     }
2092
2093     return false;
2094 }
2095
2096 - (void)didMoveToWindow
2097 {
2098     _page->activityStateDidChange(WebCore::ActivityState::AllFlags);
2099 }
2100
2101 - (void)setOpaque:(BOOL)opaque
2102 {
2103     BOOL oldOpaque = self.opaque;
2104
2105     [super setOpaque:opaque];
2106     [_contentView setOpaque:opaque];
2107
2108     if (oldOpaque == opaque)
2109         return;
2110
2111     if (!_page)
2112         return;
2113
2114     _page->setDrawsBackground(opaque);
2115     [self _updateScrollViewBackground];
2116 }
2117
2118 - (void)setBackgroundColor:(UIColor *)backgroundColor
2119 {
2120     [super setBackgroundColor:backgroundColor];
2121     [_contentView setBackgroundColor:backgroundColor];
2122 }
2123
2124 - (BOOL)_allowsDoubleTapGestures
2125 {
2126     if (_fastClickingIsDisabled)
2127         return YES;
2128
2129     // If the page is not user scalable, we don't allow double tap gestures.
2130     if (![_scrollView isZoomEnabled] || [_scrollView minimumZoomScale] >= [_scrollView maximumZoomScale])
2131         return NO;
2132
2133     // If the viewport width was not explicit, we allow double tap gestures.
2134     if (!_viewportMetaTagWidthWasExplicit || _viewportMetaTagCameFromImageDocument)
2135         return YES;
2136
2137     // If the page set a viewport width that wasn't the device width, then it was
2138     // scaled and thus will probably need to zoom.
2139     if (_viewportMetaTagWidth != WebCore::ViewportArguments::ValueDeviceWidth)
2140         return YES;
2141
2142     // At this point, we have a page that asked for width = device-width. However,
2143     // if the content's width and height were large, we might have had to shrink it.
2144     // Since we'll enable double tap zoom whenever we're not at the actual
2145     // initial scale, this simply becomes a test of the current scale against 1.
2146     return !areEssentiallyEqualAsFloat(contentZoomScale(self), 1);
2147 }
2148
2149 #pragma mark - UIScrollViewDelegate
2150
2151 - (BOOL)usesStandardContentView
2152 {
2153     return !_customContentView && !_passwordView;
2154 }
2155
2156 - (CGSize)scrollView:(UIScrollView*)scrollView contentSizeForZoomScale:(CGFloat)scale withProposedSize:(CGSize)proposedSize
2157 {
2158     return roundScrollViewContentSize(*_page, proposedSize);
2159 }
2160
2161 - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
2162 {
2163     ASSERT(_scrollView == scrollView);
2164
2165     if (_customContentView)
2166         return _customContentView.get();
2167
2168     return _contentView.get();
2169 }
2170
2171 - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
2172 {
2173     if (![self usesStandardContentView])
2174         return;
2175
2176     if (scrollView.pinchGestureRecognizer.state == UIGestureRecognizerStateBegan) {
2177         _page->willStartUserTriggeredZooming();
2178         [_contentView scrollViewWillStartPanOrPinchGesture];
2179     }
2180     [_contentView willStartZoomOrScroll];
2181 }
2182
2183 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
2184 {
2185     if (![self usesStandardContentView])
2186         return;
2187
2188     if (scrollView.panGestureRecognizer.state == UIGestureRecognizerStateBegan)
2189         [_contentView scrollViewWillStartPanOrPinchGesture];
2190
2191     [_contentView willStartZoomOrScroll];
2192 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2193     // FIXME: We will want to detect whether snapping will occur before beginning to drag. See WebPageProxy::didCommitLayerTree.
2194     WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2195     ASSERT(scrollView == _scrollView.get());
2196     CGFloat scrollDecelerationFactor = (coordinator && coordinator->shouldSetScrollViewDecelerationRateFast()) ? UIScrollViewDecelerationRateFast : UIScrollViewDecelerationRateNormal;
2197     scrollView.horizontalScrollDecelerationFactor = scrollDecelerationFactor;
2198     scrollView.verticalScrollDecelerationFactor = scrollDecelerationFactor;
2199 #endif
2200 }
2201
2202 - (void)_didFinishScrolling
2203 {
2204     if (![self usesStandardContentView])
2205         return;
2206
2207     [self _scheduleVisibleContentRectUpdate];
2208     [_contentView didFinishScrolling];
2209 }
2210
2211 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
2212 {
2213     // Work around <rdar://problem/16374753> by avoiding deceleration while
2214     // zooming. We'll animate to the right place once the zoom finishes.
2215     if ([scrollView isZooming])
2216         *targetContentOffset = [scrollView contentOffset];
2217 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2218     if (WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy()) {
2219         // FIXME: Here, I'm finding the maximum horizontal/vertical scroll offsets. There's probably a better way to do this.
2220         CGSize maxScrollOffsets = CGSizeMake(scrollView.contentSize.width - scrollView.bounds.size.width, scrollView.contentSize.height - scrollView.bounds.size.height);
2221
2222         CGRect fullViewRect = self.bounds;
2223
2224         UIEdgeInsets contentInset;
2225
2226         id<WKUIDelegatePrivate> uiDelegatePrivate = static_cast<id <WKUIDelegatePrivate>>([self UIDelegate]);
2227         if ([uiDelegatePrivate respondsToSelector:@selector(_webView:finalObscuredInsetsForScrollView:withVelocity:targetContentOffset:)])
2228             contentInset = [uiDelegatePrivate _webView:self finalObscuredInsetsForScrollView:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
2229         else
2230             contentInset = [self _computedContentInset];
2231
2232         CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, contentInset);
2233
2234         coordinator->adjustTargetContentOffsetForSnapping(maxScrollOffsets, velocity, unobscuredRect.origin.y, targetContentOffset);
2235     }
2236 #endif
2237 }
2238
2239 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
2240 {
2241     // If we're decelerating, scroll offset will be updated when scrollViewDidFinishDecelerating: is called.
2242     if (!decelerate)
2243         [self _didFinishScrolling];
2244 }
2245
2246 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
2247 {
2248     [self _didFinishScrolling];
2249 }
2250
2251 - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
2252 {
2253     [self _didFinishScrolling];
2254 }
2255
2256 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
2257 {
2258     if (![self usesStandardContentView])
2259         [_customContentView scrollViewDidScroll:(UIScrollView *)scrollView];
2260
2261     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2262
2263     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
2264         scrollPerfData->didScroll([self visibleRectInViewCoordinates]);
2265 }
2266
2267 - (void)scrollViewDidZoom:(UIScrollView *)scrollView
2268 {
2269     [self _updateScrollViewBackground];
2270     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2271 }
2272
2273 - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
2274 {
2275     ASSERT(scrollView == _scrollView);
2276     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2277     [_contentView didZoomToScale:scale];
2278 }
2279
2280 - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
2281 {
2282     [self _didFinishScrolling];
2283 }
2284
2285 - (void)_scrollViewDidInterruptDecelerating:(UIScrollView *)scrollView
2286 {
2287     if (![self usesStandardContentView])
2288         return;
2289
2290     [_contentView didInterruptScrolling];
2291     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2292 }
2293
2294 - (UIView *)_enclosingViewForExposedRectComputation
2295 {
2296     return [self _scroller];
2297 }
2298
2299 - (CGRect)_visibleRectInEnclosingView:(UIView *)enclosingView
2300 {
2301     if (!enclosingView)
2302         return self.bounds;
2303
2304     CGRect exposedRect = [enclosingView convertRect:enclosingView.bounds toView:self];
2305     return CGRectIntersectsRect(exposedRect, self.bounds) ? CGRectIntersection(exposedRect, self.bounds) : CGRectZero;
2306 }
2307
2308 - (CGRect)_visibleContentRect
2309 {
2310     if (_frozenVisibleContentRect)
2311         return _frozenVisibleContentRect.value();
2312
2313     CGRect visibleRectInContentCoordinates = [self convertRect:self.bounds toView:_contentView.get()];
2314
2315     if (UIView *enclosingView = [self _enclosingViewForExposedRectComputation]) {
2316         CGRect viewVisibleRect = [self _visibleRectInEnclosingView:enclosingView];
2317         CGRect viewVisibleContentRect = [self convertRect:viewVisibleRect toView:_contentView.get()];
2318         visibleRectInContentCoordinates = CGRectIntersection(visibleRectInContentCoordinates, viewVisibleContentRect);
2319     }
2320
2321     return visibleRectInContentCoordinates;
2322 }
2323
2324 // Called when some ancestor UIScrollView scrolls.
2325 - (void)_didScroll
2326 {
2327     [self _scheduleVisibleContentRectUpdateAfterScrollInView:[self _scroller]];
2328
2329     const NSTimeInterval ScrollingEndedTimerInterval = 0.032;
2330     if (!_enclosingScrollViewScrollTimer) {
2331         _enclosingScrollViewScrollTimer = adoptNS([[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:ScrollingEndedTimerInterval]
2332             interval:0 target:self selector:@selector(_enclosingScrollerScrollingEnded:) userInfo:nil repeats:YES]);
2333         [[NSRunLoop mainRunLoop] addTimer:_enclosingScrollViewScrollTimer.get() forMode:NSDefaultRunLoopMode];
2334     }
2335     _didScrollSinceLastTimerFire = YES;
2336 }
2337
2338 - (void)_enclosingScrollerScrollingEnded:(NSTimer *)timer
2339 {
2340     if (_didScrollSinceLastTimerFire) {
2341         _didScrollSinceLastTimerFire = NO;
2342         return;
2343     }
2344
2345     [self _scheduleVisibleContentRectUpdate];
2346     [_enclosingScrollViewScrollTimer invalidate];
2347     _enclosingScrollViewScrollTimer = nil;
2348 }
2349
2350 static WebCore::FloatSize activeMinimumLayoutSize(WKWebView *webView, const CGRect& bounds)
2351 {
2352     if (webView->_overridesMinimumLayoutSize)
2353         return WebCore::FloatSize(webView->_minimumLayoutSizeOverride);
2354
2355 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2356     UIEdgeInsets systemContentInset = [webView->_scrollView _systemContentInset];
2357     return WebCore::FloatSize(UIEdgeInsetsInsetRect(CGRectMake(0, 0, bounds.size.width, bounds.size.height), systemContentInset).size);
2358 #else
2359     return WebCore::FloatSize(bounds.size);
2360 #endif
2361 }
2362
2363 - (void)_dispatchSetMinimumLayoutSize:(WebCore::FloatSize)minimumLayoutSize
2364 {
2365     if (_lastSentMinimumLayoutSize && CGSizeEqualToSize(_lastSentMinimumLayoutSize.value(), minimumLayoutSize))
2366         return;
2367
2368     _page->setViewportConfigurationMinimumLayoutSize(minimumLayoutSize);
2369     _lastSentMinimumLayoutSize = minimumLayoutSize;
2370 }
2371
2372 - (void)_dispatchSetMaximumUnobscuredSize:(WebCore::FloatSize)maximumUnobscuredSize
2373 {
2374     if (_lastSentMaximumUnobscuredSize && CGSizeEqualToSize(_lastSentMaximumUnobscuredSize.value(), maximumUnobscuredSize))
2375         return;
2376
2377     _page->setMaximumUnobscuredSize(maximumUnobscuredSize);
2378     _lastSentMaximumUnobscuredSize = maximumUnobscuredSize;
2379 }
2380
2381 - (void)_dispatchSetDeviceOrientation:(int32_t)deviceOrientation
2382 {
2383     if (_lastSentDeviceOrientation && _lastSentDeviceOrientation.value() == deviceOrientation)
2384         return;
2385
2386     _page->setDeviceOrientation(deviceOrientation);
2387     _lastSentDeviceOrientation = deviceOrientation;
2388 }
2389
2390 - (void)_frameOrBoundsChanged
2391 {
2392     CGRect bounds = self.bounds;
2393     [_scrollView setFrame:bounds];
2394
2395     if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing) {
2396         if (!_overridesMinimumLayoutSize)
2397             [self _dispatchSetMinimumLayoutSize:activeMinimumLayoutSize(self, self.bounds)];
2398         if (!_overridesMaximumUnobscuredSize)
2399             [self _dispatchSetMaximumUnobscuredSize:WebCore::FloatSize(bounds.size)];
2400
2401         BOOL sizeChanged = NO;
2402         if (auto drawingArea = _page->drawingArea())
2403             sizeChanged = drawingArea->setSize(WebCore::IntSize(bounds.size), WebCore::IntSize(), WebCore::IntSize());
2404
2405         if (sizeChanged & [self usesStandardContentView])
2406             [_contentView setSizeChangedSinceLastVisibleContentRectUpdate:YES];
2407     }
2408
2409     [_customContentView web_setMinimumSize:bounds.size];
2410     [self _scheduleVisibleContentRectUpdate];
2411 }
2412
2413 // 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.
2414 - (CGRect)_contentRectForUserInteraction
2415 {
2416     // FIXME: handle split keyboard.
2417     UIEdgeInsets obscuredInsets = _obscuredInsets;
2418     obscuredInsets.bottom = std::max(_obscuredInsets.bottom, _inputViewBounds.size.height);
2419     CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInsets);
2420     return [self convertRect:unobscuredRect toView:self._currentContentView];
2421 }
2422
2423 // Ideally UIScrollView would expose this for us: <rdar://problem/21394567>.
2424 - (BOOL)_scrollViewIsRubberBanding
2425 {
2426     float deviceScaleFactor = _page->deviceScaleFactor();
2427
2428     CGPoint contentOffset = [_scrollView contentOffset];
2429     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
2430     return !pointsEqualInDevicePixels(contentOffset, boundedOffset, deviceScaleFactor);
2431 }
2432
2433 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2434 - (void)safeAreaInsetsDidChange
2435 {
2436     [super safeAreaInsetsDidChange];
2437
2438     [self _scheduleVisibleContentRectUpdate];
2439 }
2440 #endif
2441
2442 - (void)_scheduleVisibleContentRectUpdate
2443 {
2444     // For visible rect updates not associated with a specific UIScrollView, just consider our own scroller.
2445     [self _scheduleVisibleContentRectUpdateAfterScrollInView:_scrollView.get()];
2446 }
2447
2448 - (BOOL)_scrollViewIsInStableState:(UIScrollView *)scrollView
2449 {
2450     BOOL isStableState = !([scrollView isDragging] || [scrollView isDecelerating] || [scrollView isZooming] || [scrollView _isAnimatingZoom] || [scrollView _isScrollingToTop]);
2451
2452     if (isStableState && scrollView == _scrollView.get())
2453         isStableState = !_isChangingObscuredInsetsInteractively;
2454
2455     if (isStableState && scrollView == _scrollView.get())
2456         isStableState = ![self _scrollViewIsRubberBanding];
2457
2458     if (isStableState)
2459         isStableState = !scrollView._isInterruptingDeceleration;
2460
2461     if (NSNumber *stableOverride = self._stableStateOverride)
2462         isStableState = stableOverride.boolValue;
2463
2464     return isStableState;
2465 }
2466
2467 - (void)_addUpdateVisibleContentRectPreCommitHandler
2468 {
2469     auto retainedSelf = retainPtr(self);
2470     [CATransaction addCommitHandler:[retainedSelf] {
2471         WKWebView *webView = retainedSelf.get();
2472         if (![webView _isValid])
2473             return;
2474         [webView _updateVisibleContentRects];
2475         webView->_hasScheduledVisibleRectUpdate = NO;
2476     } forPhase:kCATransactionPhasePreCommit];
2477 }
2478
2479 - (void)_scheduleVisibleContentRectUpdateAfterScrollInView:(UIScrollView *)scrollView
2480 {
2481     _visibleContentRectUpdateScheduledFromScrollViewInStableState = [self _scrollViewIsInStableState:scrollView];
2482
2483     if (_hasScheduledVisibleRectUpdate)
2484         return;
2485
2486     _hasScheduledVisibleRectUpdate = YES;
2487
2488 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2489     CATransactionPhase transactionPhase = [CATransaction currentPhase];
2490     if (transactionPhase == kCATransactionPhaseNull || transactionPhase == kCATransactionPhasePreLayout) {
2491         [self _addUpdateVisibleContentRectPreCommitHandler];
2492         return;
2493     }
2494 #endif
2495
2496     dispatch_async(dispatch_get_main_queue(), [retainedSelf = retainPtr(self)] {
2497         WKWebView *webView = retainedSelf.get();
2498         if (![webView _isValid])
2499             return;
2500         [webView _addUpdateVisibleContentRectPreCommitHandler];
2501     });
2502 }
2503
2504 static bool scrollViewCanScroll(UIScrollView *scrollView)
2505 {
2506     if (!scrollView)
2507         return NO;
2508
2509     UIEdgeInsets contentInset = scrollView.contentInset;
2510     CGSize contentSize = scrollView.contentSize;
2511     CGSize boundsSize = scrollView.bounds.size;
2512
2513     return (contentSize.width + contentInset.left + contentInset.right) > boundsSize.width
2514         || (contentSize.height + contentInset.top + contentInset.bottom) > boundsSize.height;
2515 }
2516
2517 - (CGRect)_contentBoundsExtendedForRubberbandingWithScale:(CGFloat)scaleFactor
2518 {
2519     CGPoint contentOffset = [_scrollView contentOffset];
2520     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
2521
2522     CGFloat horiontalRubberbandAmountInContentCoordinates = (contentOffset.x - boundedOffset.x) / scaleFactor;
2523     CGFloat verticalRubberbandAmountInContentCoordinates = (contentOffset.y - boundedOffset.y) / scaleFactor;
2524
2525     CGRect extendedBounds = [_contentView bounds];
2526
2527     if (horiontalRubberbandAmountInContentCoordinates < 0) {
2528         extendedBounds.origin.x += horiontalRubberbandAmountInContentCoordinates;
2529         extendedBounds.size.width -= horiontalRubberbandAmountInContentCoordinates;
2530     } else if (horiontalRubberbandAmountInContentCoordinates > 0)
2531         extendedBounds.size.width += horiontalRubberbandAmountInContentCoordinates;
2532
2533     if (verticalRubberbandAmountInContentCoordinates < 0) {
2534         extendedBounds.origin.y += verticalRubberbandAmountInContentCoordinates;
2535         extendedBounds.size.height -= verticalRubberbandAmountInContentCoordinates;
2536     } else if (verticalRubberbandAmountInContentCoordinates > 0)
2537         extendedBounds.size.height += verticalRubberbandAmountInContentCoordinates;
2538
2539     return extendedBounds;
2540 }
2541
2542 - (void)_updateVisibleContentRects
2543 {
2544     BOOL inStableState = _visibleContentRectUpdateScheduledFromScrollViewInStableState;
2545
2546     if (![self usesStandardContentView]) {
2547         [_passwordView setFrame:self.bounds];
2548         [_customContentView web_computedContentInsetDidChange];
2549         return;
2550     }
2551
2552     if (_delayUpdateVisibleContentRects) {
2553         _hadDelayedUpdateVisibleContentRects = YES;
2554         return;
2555     }
2556
2557     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing
2558         || (_needsResetViewStateAfterCommitLoadForMainFrame && ![_contentView sizeChangedSinceLastVisibleContentRectUpdate])
2559         || [_scrollView isZoomBouncing]
2560         || _currentlyAdjustingScrollViewInsetsForKeyboard)
2561         return;
2562
2563     CGRect fullViewRect = self.bounds;
2564     CGRect visibleRectInContentCoordinates = [self _visibleContentRect];
2565
2566     UIEdgeInsets computedContentInsetUnadjustedForKeyboard = [self _computedContentInset];
2567     if (!_haveSetObscuredInsets)
2568         computedContentInsetUnadjustedForKeyboard.bottom -= _totalScrollViewBottomInsetAdjustmentForKeyboard;
2569
2570     CGFloat scaleFactor = contentZoomScale(self);
2571
2572     CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, computedContentInsetUnadjustedForKeyboard);
2573     CGRect unobscuredRectInContentCoordinates = _frozenUnobscuredContentRect ? _frozenUnobscuredContentRect.value() : [self convertRect:unobscuredRect toView:_contentView.get()];
2574     unobscuredRectInContentCoordinates = CGRectIntersection(unobscuredRectInContentCoordinates, [self _contentBoundsExtendedForRubberbandingWithScale:scaleFactor]);
2575
2576 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2577     if (inStableState) {
2578         WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2579         if (coordinator && coordinator->hasActiveSnapPoint()) {
2580             CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, computedContentInsetUnadjustedForKeyboard);
2581
2582             CGPoint currentPoint = [_scrollView contentOffset];
2583             CGPoint activePoint = coordinator->nearestActiveContentInsetAdjustedSnapPoint(unobscuredRect.origin.y, currentPoint);
2584
2585             if (!CGPointEqualToPoint(activePoint, currentPoint)) {
2586                 RetainPtr<WKScrollView> strongScrollView = _scrollView;
2587                 dispatch_async(dispatch_get_main_queue(), [strongScrollView, activePoint] {
2588                     [strongScrollView setContentOffset:activePoint animated:NO];
2589                 });
2590             }
2591         }
2592     }
2593 #endif
2594
2595     [_contentView didUpdateVisibleRect:visibleRectInContentCoordinates
2596         unobscuredRect:unobscuredRectInContentCoordinates
2597         unobscuredRectInScrollViewCoordinates:unobscuredRect
2598         obscuredInsets:_obscuredInsets
2599         unobscuredSafeAreaInsets:[self _computedUnobscuredSafeAreaInset]
2600         inputViewBounds:_inputViewBounds
2601         scale:scaleFactor minimumScale:[_scrollView minimumZoomScale]
2602         inStableState:inStableState
2603         isChangingObscuredInsetsInteractively:_isChangingObscuredInsetsInteractively
2604         enclosedInScrollableAncestorView:scrollViewCanScroll([self _scroller])];
2605
2606     while (!_visibleContentRectUpdateCallbacks.isEmpty()) {
2607         auto callback = _visibleContentRectUpdateCallbacks.takeLast();
2608         callback();
2609     }
2610 }
2611
2612 - (void)_didFinishLoadForMainFrame
2613 {
2614     if (_gestureController)
2615         _gestureController->didFinishLoadForMainFrame();
2616 }
2617
2618 - (void)_didFailLoadForMainFrame
2619 {
2620     if (_gestureController)
2621         _gestureController->didFailLoadForMainFrame();
2622 }
2623
2624 - (void)_didSameDocumentNavigationForMainFrame:(WebKit::SameDocumentNavigationType)navigationType
2625 {
2626     [_customContentView web_didSameDocumentNavigation:toAPI(navigationType)];
2627
2628     if (_gestureController)
2629         _gestureController->didSameDocumentNavigationForMainFrame(navigationType);
2630 }
2631
2632 - (void)_keyboardChangedWithInfo:(NSDictionary *)keyboardInfo adjustScrollView:(BOOL)adjustScrollView
2633 {
2634     NSValue *endFrameValue = [keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
2635     if (!endFrameValue)
2636         return;
2637
2638     // The keyboard rect is always in screen coordinates. In the view services case the window does not
2639     // have the interface orientation rotation transformation; its host does. So, it makes no sense to
2640     // clip the keyboard rect against its screen.
2641     if ([[self window] _isHostedInAnotherProcess])
2642         _inputViewBounds = [self.window convertRect:[endFrameValue CGRectValue] fromWindow:nil];
2643     else
2644         _inputViewBounds = [self.window convertRect:CGRectIntersection([endFrameValue CGRectValue], self.window.screen.bounds) fromWindow:nil];
2645
2646     if (adjustScrollView) {
2647         CGFloat bottomInsetBeforeAdjustment = [_scrollView contentInset].bottom;
2648         SetForScope<BOOL> insetAdjustmentGuard(_currentlyAdjustingScrollViewInsetsForKeyboard, YES);
2649         [_scrollView _adjustForAutomaticKeyboardInfo:keyboardInfo animated:YES lastAdjustment:&_lastAdjustmentForScroller];
2650         CGFloat bottomInsetAfterAdjustment = [_scrollView contentInset].bottom;
2651         if (bottomInsetBeforeAdjustment != bottomInsetAfterAdjustment)
2652             _totalScrollViewBottomInsetAdjustmentForKeyboard += bottomInsetAfterAdjustment - bottomInsetBeforeAdjustment;
2653     }
2654
2655     [self _scheduleVisibleContentRectUpdate];
2656 }
2657
2658 - (BOOL)_shouldUpdateKeyboardWithInfo:(NSDictionary *)keyboardInfo
2659 {
2660     if ([_contentView isAssistingNode])
2661         return YES;
2662
2663     NSNumber *isLocalKeyboard = [keyboardInfo valueForKey:UIKeyboardIsLocalUserInfoKey];
2664     return isLocalKeyboard && !isLocalKeyboard.boolValue;
2665 }
2666
2667 - (void)_keyboardWillChangeFrame:(NSNotification *)notification
2668 {
2669     if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
2670         [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
2671 }
2672
2673 - (void)_keyboardDidChangeFrame:(NSNotification *)notification
2674 {
2675     [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:NO];
2676 }
2677
2678 - (void)_keyboardWillShow:(NSNotification *)notification
2679 {
2680     if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
2681         [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
2682
2683     _page->setIsKeyboardAnimatingIn(true);
2684 }
2685
2686 - (void)_keyboardDidShow:(NSNotification *)notification
2687 {
2688     _page->setIsKeyboardAnimatingIn(false);
2689 }
2690
2691 - (void)_keyboardWillHide:(NSNotification *)notification
2692 {
2693     // Ignore keyboard will hide notifications sent during rotation. They're just there for
2694     // backwards compatibility reasons and processing the will hide notification would
2695     // temporarily screw up the the unobscured view area.
2696     if ([[UIPeripheralHost sharedInstance] rotationState])
2697         return;
2698
2699     [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
2700 }
2701
2702 - (void)_windowDidRotate:(NSNotification *)notification
2703 {
2704     if (!_overridesInterfaceOrientation)
2705         [self _dispatchSetDeviceOrientation:deviceOrientation()];
2706 }
2707
2708 - (void)_contentSizeCategoryDidChange:(NSNotification *)notification
2709 {
2710     _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
2711 }
2712
2713 - (NSString *)_contentSizeCategory
2714 {
2715     return [[UIApplication sharedApplication] preferredContentSizeCategory];
2716 }
2717
2718 - (void)_accessibilitySettingsDidChange:(NSNotification *)notification
2719 {
2720     _page->accessibilitySettingsDidChange();
2721 }
2722
2723 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
2724 {
2725     if (_allowsBackForwardNavigationGestures == allowsBackForwardNavigationGestures)
2726         return;
2727
2728     _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
2729
2730     if (allowsBackForwardNavigationGestures) {
2731         if (!_gestureController) {
2732             _gestureController = std::make_unique<WebKit::ViewGestureController>(*_page);
2733             _gestureController->installSwipeHandler(self, [self scrollView]);
2734             if (WKWebView *alternateWebView = [_configuration _alternateWebViewForNavigationGestures])
2735                 _gestureController->setAlternateBackForwardListSourcePage(alternateWebView->_page.get());
2736         }
2737     } else
2738         _gestureController = nullptr;
2739
2740     _page->setShouldRecordNavigationSnapshots(allowsBackForwardNavigationGestures);
2741 }
2742
2743 - (BOOL)allowsBackForwardNavigationGestures
2744 {
2745     return _allowsBackForwardNavigationGestures;
2746 }
2747
2748 - (BOOL)_isNavigationSwipeGestureRecognizer:(UIGestureRecognizer *)recognizer
2749 {
2750     if (!_gestureController)
2751         return NO;
2752     return _gestureController->isNavigationSwipeGestureRecognizer(recognizer);
2753 }
2754
2755 - (void)_navigationGestureDidBegin
2756 {
2757     // During a back/forward swipe, there's a view interposed between this view and the content view that has
2758     // an offset and animation on it, which results in computing incorrect rectangles. Work around by using
2759     // frozen rects during swipes.
2760     CGRect fullViewRect = self.bounds;
2761     CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, [self _computedContentInset]);
2762
2763     _frozenVisibleContentRect = [self convertRect:fullViewRect toView:_contentView.get()];
2764     _frozenUnobscuredContentRect = [self convertRect:unobscuredRect toView:_contentView.get()];
2765
2766     LOG_WITH_STREAM(VisibleRects, stream << "_navigationGestureDidBegin: freezing visibleContentRect " << WebCore::FloatRect(_frozenVisibleContentRect.value()) << " UnobscuredContentRect " << WebCore::FloatRect(_frozenUnobscuredContentRect.value()));
2767 }
2768
2769 - (void)_navigationGestureDidEnd
2770 {
2771     _frozenVisibleContentRect = std::nullopt;
2772     _frozenUnobscuredContentRect = std::nullopt;
2773 }
2774
2775 - (void)_showPasswordViewWithDocumentName:(NSString *)documentName passwordHandler:(void (^)(NSString *))passwordHandler
2776 {
2777     ASSERT(!_passwordView);
2778     _passwordView = adoptNS([[WKPasswordView alloc] initWithFrame:self.bounds documentName:documentName]);
2779     [_passwordView setUserDidEnterPassword:passwordHandler];
2780     [_passwordView showInScrollView:_scrollView.get()];
2781     self._currentContentView.hidden = YES;
2782 }
2783
2784 - (void)_hidePasswordView
2785 {
2786     if (!_passwordView)
2787         return;
2788
2789     self._currentContentView.hidden = NO;
2790     [_passwordView hide];
2791     _passwordView = nil;
2792 }
2793
2794 - (WKPasswordView *)_passwordView
2795 {
2796     return _passwordView.get();
2797 }
2798
2799 - (void)_updateScrollViewInsetAdjustmentBehavior
2800 {
2801 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2802     if (![_scrollView _contentInsetAdjustmentBehaviorWasExternallyOverridden])
2803         [_scrollView _setContentInsetAdjustmentBehaviorInternal:self._safeAreaShouldAffectObscuredInsets ? UIScrollViewContentInsetAdjustmentAlways : UIScrollViewContentInsetAdjustmentNever];
2804 #endif
2805 }
2806
2807 - (void)_setAvoidsUnsafeArea:(BOOL)avoidsUnsafeArea
2808 {
2809     if (_avoidsUnsafeArea == avoidsUnsafeArea)
2810         return;
2811
2812     _avoidsUnsafeArea = avoidsUnsafeArea;
2813
2814     [self _updateScrollViewInsetAdjustmentBehavior];
2815     [self _scheduleVisibleContentRectUpdate];
2816
2817     id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)[self UIDelegate];
2818     if ([uiDelegate respondsToSelector:@selector(_webView:didChangeSafeAreaShouldAffectObscuredInsets:)])
2819         [uiDelegate _webView:self didChangeSafeAreaShouldAffectObscuredInsets:avoidsUnsafeArea];
2820 }
2821
2822 #endif // PLATFORM(IOS)
2823
2824 #pragma mark OS X-specific methods
2825
2826 #if PLATFORM(MAC)
2827
2828 - (BOOL)acceptsFirstResponder
2829 {
2830     return _impl->acceptsFirstResponder();
2831 }
2832
2833 - (BOOL)becomeFirstResponder
2834 {
2835     return _impl->becomeFirstResponder();
2836 }
2837
2838 - (BOOL)resignFirstResponder
2839 {
2840     return _impl->resignFirstResponder();
2841 }
2842
2843 - (void)viewWillStartLiveResize
2844 {
2845     _impl->viewWillStartLiveResize();
2846 }
2847
2848 - (void)viewDidEndLiveResize
2849 {
2850     _impl->viewDidEndLiveResize();
2851 }
2852
2853 - (BOOL)isFlipped
2854 {
2855     return YES;
2856 }
2857
2858 - (NSSize)intrinsicContentSize
2859 {
2860     return NSSizeFromCGSize(_impl->intrinsicContentSize());
2861 }
2862
2863 - (void)prepareContentInRect:(NSRect)rect
2864 {
2865     _impl->prepareContentInRect(NSRectToCGRect(rect));
2866 }
2867
2868 - (void)setFrameSize:(NSSize)size
2869 {
2870     [super setFrameSize:size];
2871     _impl->setFrameSize(NSSizeToCGSize(size));
2872 }
2873
2874 - (void)renewGState
2875 {
2876     _impl->renewGState();
2877     [super renewGState];
2878 }
2879
2880 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _impl->executeEditCommandForSelector(_cmd); }
2881
2882 WEBCORE_COMMAND(alignCenter)
2883 WEBCORE_COMMAND(alignJustified)
2884 WEBCORE_COMMAND(alignLeft)
2885 WEBCORE_COMMAND(alignRight)
2886 WEBCORE_COMMAND(copy)
2887 WEBCORE_COMMAND(cut)
2888 WEBCORE_COMMAND(delete)
2889 WEBCORE_COMMAND(deleteBackward)
2890 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
2891 WEBCORE_COMMAND(deleteForward)
2892 WEBCORE_COMMAND(deleteToBeginningOfLine)
2893 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
2894 WEBCORE_COMMAND(deleteToEndOfLine)
2895 WEBCORE_COMMAND(deleteToEndOfParagraph)
2896 WEBCORE_COMMAND(deleteToMark)
2897 WEBCORE_COMMAND(deleteWordBackward)
2898 WEBCORE_COMMAND(deleteWordForward)
2899 WEBCORE_COMMAND(ignoreSpelling)
2900 WEBCORE_COMMAND(indent)
2901 WEBCORE_COMMAND(insertBacktab)
2902 WEBCORE_COMMAND(insertLineBreak)
2903 WEBCORE_COMMAND(insertNewline)
2904 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
2905 WEBCORE_COMMAND(insertParagraphSeparator)
2906 WEBCORE_COMMAND(insertTab)
2907 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
2908 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
2909 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
2910 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
2911 WEBCORE_COMMAND(moveBackward)
2912 WEBCORE_COMMAND(moveBackwardAndModifySelection)
2913 WEBCORE_COMMAND(moveDown)
2914 WEBCORE_COMMAND(moveDownAndModifySelection)
2915 WEBCORE_COMMAND(moveForward)
2916 WEBCORE_COMMAND(moveForwardAndModifySelection)
2917 WEBCORE_COMMAND(moveLeft)
2918 WEBCORE_COMMAND(moveLeftAndModifySelection)
2919 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
2920 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
2921 WEBCORE_COMMAND(moveRight)
2922 WEBCORE_COMMAND(moveRightAndModifySelection)
2923 WEBCORE_COMMAND(moveToBeginningOfDocument)
2924 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
2925 WEBCORE_COMMAND(moveToBeginningOfLine)
2926 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
2927 WEBCORE_COMMAND(moveToBeginningOfParagraph)
2928 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
2929 WEBCORE_COMMAND(moveToBeginningOfSentence)
2930 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
2931 WEBCORE_COMMAND(moveToEndOfDocument)
2932 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
2933 WEBCORE_COMMAND(moveToEndOfLine)
2934 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
2935 WEBCORE_COMMAND(moveToEndOfParagraph)
2936 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
2937 WEBCORE_COMMAND(moveToEndOfSentence)
2938 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
2939 WEBCORE_COMMAND(moveToLeftEndOfLine)
2940 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
2941 WEBCORE_COMMAND(moveToRightEndOfLine)
2942 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
2943 WEBCORE_COMMAND(moveUp)
2944 WEBCORE_COMMAND(moveUpAndModifySelection)
2945 WEBCORE_COMMAND(moveWordBackward)
2946 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
2947 WEBCORE_COMMAND(moveWordForward)
2948 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
2949 WEBCORE_COMMAND(moveWordLeft)
2950 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
2951 WEBCORE_COMMAND(moveWordRight)
2952 WEBCORE_COMMAND(moveWordRightAndModifySelection)
2953 WEBCORE_COMMAND(outdent)
2954 WEBCORE_COMMAND(pageDown)
2955 WEBCORE_COMMAND(pageDownAndModifySelection)
2956 WEBCORE_COMMAND(pageUp)
2957 WEBCORE_COMMAND(pageUpAndModifySelection)
2958 WEBCORE_COMMAND(paste)
2959 WEBCORE_COMMAND(pasteAsPlainText)
2960 WEBCORE_COMMAND(scrollPageDown)
2961 WEBCORE_COMMAND(scrollPageUp)
2962 WEBCORE_COMMAND(scrollLineDown)
2963 WEBCORE_COMMAND(scrollLineUp)
2964 WEBCORE_COMMAND(scrollToBeginningOfDocument)
2965 WEBCORE_COMMAND(scrollToEndOfDocument)
2966 WEBCORE_COMMAND(selectAll)
2967 WEBCORE_COMMAND(selectLine)
2968 WEBCORE_COMMAND(selectParagraph)
2969 WEBCORE_COMMAND(selectSentence)
2970 WEBCORE_COMMAND(selectToMark)
2971 WEBCORE_COMMAND(selectWord)
2972 WEBCORE_COMMAND(setMark)
2973 WEBCORE_COMMAND(subscript)
2974 WEBCORE_COMMAND(superscript)
2975 WEBCORE_COMMAND(swapWithMark)
2976 WEBCORE_COMMAND(takeFindStringFromSelection)
2977 WEBCORE_COMMAND(transpose)
2978 WEBCORE_COMMAND(underline)
2979 WEBCORE_COMMAND(unscript)
2980 WEBCORE_COMMAND(yank)
2981 WEBCORE_COMMAND(yankAndSelect)
2982
2983 #undef WEBCORE_COMMAND
2984
2985 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
2986 {
2987     return _impl->writeSelectionToPasteboard(pasteboard, types);
2988 }
2989
2990 - (void)centerSelectionInVisibleArea:(id)sender
2991 {
2992     _impl->centerSelectionInVisibleArea();
2993 }
2994
2995 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
2996 {
2997     return _impl->validRequestorForSendAndReturnTypes(sendType, returnType);
2998 }
2999
3000 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
3001 {
3002     return _impl->readSelectionFromPasteboard(pasteboard);
3003 }
3004
3005 - (void)changeFont:(id)sender
3006 {
3007     _impl->changeFontFromFontPanel();
3008 }
3009
3010 - (IBAction)startSpeaking:(id)sender
3011 {
3012     _impl->startSpeaking();
3013 }
3014
3015 - (IBAction)stopSpeaking:(id)sender
3016 {
3017     _impl->stopSpeaking(sender);
3018 }
3019
3020 - (IBAction)showGuessPanel:(id)sender
3021 {
3022     _impl->showGuessPanel(sender);
3023 }
3024
3025 - (IBAction)checkSpelling:(id)sender
3026 {
3027     _impl->checkSpelling();
3028 }
3029
3030 - (void)changeSpelling:(id)sender
3031 {
3032     _impl->changeSpelling(sender);
3033 }
3034
3035 - (IBAction)toggleContinuousSpellChecking:(id)sender
3036 {
3037     _impl->toggleContinuousSpellChecking();
3038 }
3039
3040 - (BOOL)isGrammarCheckingEnabled
3041 {
3042     return _impl->isGrammarCheckingEnabled();
3043 }
3044
3045 - (void)setGrammarCheckingEnabled:(BOOL)flag
3046 {
3047     _impl->setGrammarCheckingEnabled(flag);
3048 }
3049
3050 - (IBAction)toggleGrammarChecking:(id)sender
3051 {
3052     _impl->toggleGrammarChecking();
3053 }
3054
3055 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
3056 {
3057     _impl->toggleAutomaticSpellingCorrection();
3058 }
3059
3060 - (void)orderFrontSubstitutionsPanel:(id)sender
3061 {
3062     _impl->orderFrontSubstitutionsPanel(sender);
3063 }
3064
3065 - (IBAction)toggleSmartInsertDelete:(id)sender
3066 {
3067     _impl->toggleSmartInsertDelete();
3068 }
3069
3070 - (BOOL)isAutomaticQuoteSubstitutionEnabled
3071 {
3072     return _impl->isAutomaticQuoteSubstitutionEnabled();
3073 }
3074
3075 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
3076 {
3077     _impl->setAutomaticQuoteSubstitutionEnabled(flag);
3078 }
3079
3080 - (void)toggleAutomaticQuoteSubstitution:(id)sender
3081 {
3082     _impl->toggleAutomaticQuoteSubstitution();
3083 }
3084
3085 - (BOOL)isAutomaticDashSubstitutionEnabled
3086 {
3087     return _impl->isAutomaticDashSubstitutionEnabled();
3088 }
3089
3090 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
3091 {
3092     _impl->setAutomaticDashSubstitutionEnabled(flag);
3093 }
3094
3095 - (void)toggleAutomaticDashSubstitution:(id)sender
3096 {
3097     _impl->toggleAutomaticDashSubstitution();
3098 }
3099
3100 - (BOOL)isAutomaticLinkDetectionEnabled
3101 {
3102     return _impl->isAutomaticLinkDetectionEnabled();
3103 }
3104
3105 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
3106 {
3107     _impl->setAutomaticLinkDetectionEnabled(flag);
3108 }
3109
3110 - (void)toggleAutomaticLinkDetection:(id)sender
3111 {
3112     _impl->toggleAutomaticLinkDetection();
3113 }
3114
3115 - (BOOL)isAutomaticTextReplacementEnabled
3116 {
3117     return _impl->isAutomaticTextReplacementEnabled();
3118 }
3119
3120 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
3121 {
3122     _impl->setAutomaticTextReplacementEnabled(flag);
3123 }
3124
3125 - (void)toggleAutomaticTextReplacement:(id)sender
3126 {
3127     _impl->toggleAutomaticTextReplacement();
3128 }
3129
3130 - (void)uppercaseWord:(id)sender
3131 {
3132     _impl->uppercaseWord();
3133 }
3134
3135 - (void)lowercaseWord:(id)sender
3136 {
3137     _impl->lowercaseWord();
3138 }
3139
3140 - (void)capitalizeWord:(id)sender
3141 {
3142     _impl->capitalizeWord();
3143 }
3144
3145 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
3146 {
3147     return _impl->wantsKeyDownForEvent(event);
3148 }
3149
3150 - (void)scrollWheel:(NSEvent *)event
3151 {
3152     _impl->scrollWheel(event);
3153 }
3154
3155 - (void)swipeWithEvent:(NSEvent *)event
3156 {
3157     _impl->swipeWithEvent(event);
3158 }
3159
3160 - (void)mouseMoved:(NSEvent *)event
3161 {
3162     _impl->mouseMoved(event);
3163 }
3164
3165 - (void)mouseDown:(NSEvent *)event
3166 {
3167     _impl->mouseDown(event);
3168 }
3169
3170 - (void)mouseUp:(NSEvent *)event
3171 {
3172     _impl->mouseUp(event);
3173 }
3174
3175 - (void)mouseDragged:(NSEvent *)event
3176 {
3177     _impl->mouseDragged(event);
3178 }
3179
3180 - (void)mouseEntered:(NSEvent *)event
3181 {
3182     _impl->mouseEntered(event);
3183 }
3184
3185 - (void)mouseExited:(NSEvent *)event
3186 {
3187     _impl->mouseExited(event);
3188 }
3189
3190 - (void)otherMouseDown:(NSEvent *)event
3191 {
3192     _impl->otherMouseDown(event);
3193 }
3194
3195 - (void)otherMouseDragged:(NSEvent *)event
3196 {
3197     _impl->otherMouseDragged(event);
3198 }
3199
3200 - (void)otherMouseUp:(NSEvent *)event
3201 {
3202     _impl->otherMouseUp(event);
3203 }
3204
3205 - (void)rightMouseDown:(NSEvent *)event
3206 {
3207     _impl->rightMouseDown(event);
3208 }
3209
3210 - (void)rightMouseDragged:(NSEvent *)event
3211 {
3212     _impl->rightMouseDragged(event);
3213 }
3214
3215 - (void)rightMouseUp:(NSEvent *)event
3216 {
3217     _impl->rightMouseUp(event);
3218 }
3219
3220 - (void)pressureChangeWithEvent:(NSEvent *)event
3221 {
3222     _impl->pressureChangeWithEvent(event);
3223 }
3224
3225 - (BOOL)acceptsFirstMouse:(NSEvent *)event
3226 {
3227     return _impl->acceptsFirstMouse(event);
3228 }
3229
3230 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
3231 {
3232     return _impl->shouldDelayWindowOrderingForEvent(event);
3233 }
3234
3235 - (void)doCommandBySelector:(SEL)selector
3236 {
3237     _impl->doCommandBySelector(selector);
3238 }
3239
3240 - (void)insertText:(id)string
3241 {
3242     _impl->insertText(string);
3243 }
3244
3245 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
3246 {
3247     _impl->insertText(string, replacementRange);
3248 }
3249
3250 - (NSTextInputContext *)inputContext
3251 {
3252     if (!_impl)
3253         return nil;
3254     return _impl->inputContext();
3255 }
3256
3257 - (BOOL)performKeyEquivalent:(NSEvent *)event
3258 {
3259     return _impl->performKeyEquivalent(event);
3260 }
3261
3262 - (void)keyUp:(NSEvent *)theEvent
3263 {
3264     _impl->keyUp(theEvent);
3265 }
3266
3267 - (void)keyDown:(NSEvent *)theEvent
3268 {
3269     _impl->keyDown(theEvent);
3270 }
3271
3272 - (void)flagsChanged:(NSEvent *)theEvent
3273 {
3274     _impl->flagsChanged(theEvent);
3275 }
3276
3277 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelectedRange replacementRange:(NSRange)replacementRange
3278 {
3279     _impl->setMarkedText(string, newSelectedRange, replacementRange);
3280 }
3281
3282 - (void)unmarkText
3283 {
3284     _impl->unmarkText();
3285 }
3286
3287 - (NSRange)selectedRange
3288 {
3289     return _impl->selectedRange();
3290 }
3291
3292 - (BOOL)hasMarkedText
3293 {
3294     return _impl->hasMarkedText();
3295 }
3296
3297 - (NSRange)markedRange
3298 {
3299     return _impl->markedRange();
3300 }
3301
3302 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange
3303 {
3304     return _impl->attributedSubstringForProposedRange(nsRange, actualRange);
3305 }
3306
3307 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
3308 {
3309     return _impl->characterIndexForPoint(thePoint);
3310 }
3311
3312 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
3313 {
3314     return _impl->firstRectForCharacterRange(theRange, actualRange);
3315 }
3316
3317 - (void)selectedRangeWithCompletionHandler:(void(^)(NSRange selectedRange))completionHandlerPtr
3318 {
3319     _impl->selectedRangeWithCompletionHandler(completionHandlerPtr);
3320 }
3321
3322 - (void)markedRangeWithCompletionHandler:(void(^)(NSRange markedRange))completionHandlerPtr
3323 {
3324     _impl->markedRangeWithCompletionHandler(completionHandlerPtr);
3325 }
3326
3327 - (void)hasMarkedTextWithCompletionHandler:(void(^)(BOOL hasMarkedText))completionHandlerPtr
3328 {
3329     _impl->hasMarkedTextWithCompletionHandler(completionHandlerPtr);
3330 }
3331
3332 - (void)attributedSubstringForProposedRange:(NSRange)nsRange completionHandler:(void(^)(NSAttributedString *attrString, NSRange actualRange))completionHandlerPtr
3333 {
3334     _impl->attributedSubstringForProposedRange(nsRange, completionHandlerPtr);
3335 }
3336
3337 - (void)firstRectForCharacterRange:(NSRange)theRange completionHandler:(void(^)(NSRect firstRect, NSRange actualRange))completionHandlerPtr
3338 {
3339     _impl->firstRectForCharacterRange(theRange, completionHandlerPtr);
3340 }
3341
3342 - (void)characterIndexForPoint:(NSPoint)thePoint completionHandler:(void(^)(NSUInteger))completionHandlerPtr
3343 {
3344     _impl->characterIndexForPoint(thePoint, completionHandlerPtr);
3345 }
3346
3347 - (NSArray *)validAttributesForMarkedText
3348 {
3349     return _impl->validAttributesForMarkedText();
3350 }
3351
3352 #if ENABLE(DRAG_SUPPORT)
3353 - (void)draggedImage:(NSImage *)image endedAt:(NSPoint)endPoint operation:(NSDragOperation)operation
3354 {
3355     _impl->draggedImage(image, NSPointToCGPoint(endPoint), operation);
3356 }
3357
3358 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
3359 {
3360     return _impl->draggingEntered(draggingInfo);
3361 }
3362
3363 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
3364 {
3365     return _impl->draggingUpdated(draggingInfo);
3366 }
3367
3368 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
3369 {
3370     _impl->draggingExited(draggingInfo);
3371 }
3372
3373 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
3374 {
3375     return _impl->prepareForDragOperation(draggingInfo);
3376 }
3377
3378 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
3379 {
3380     return _impl->performDragOperation(draggingInfo);
3381 }
3382
3383 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
3384 {
3385     return _impl->hitTestForDragTypes(NSPointToCGPoint(*point), types);
3386 }
3387 #endif // ENABLE(DRAG_SUPPORT)
3388
3389 - (BOOL)_windowResizeMouseLocationIsInVisibleScrollerThumb:(NSPoint)point
3390 {
3391     return _impl->windowResizeMouseLocationIsInVisibleScrollerThumb(NSPointToCGPoint(point));
3392 }
3393
3394 - (void)viewWillMoveToWindow:(NSWindow *)window
3395 {
3396     _impl->viewWillMoveToWindow(window);
3397 }
3398
3399 - (void)viewDidMoveToWindow
3400 {
3401     _impl->viewDidMoveToWindow();
3402 }
3403
3404 - (void)drawRect:(NSRect)rect
3405 {
3406     _impl->drawRect(NSRectToCGRect(rect));
3407 }
3408
3409 - (BOOL)isOpaque
3410 {
3411     return _impl->isOpaque();
3412 }
3413
3414 - (BOOL)mouseDownCanMoveWindow
3415 {
3416     return WebKit::WebViewImpl::mouseDownCanMoveWindow();
3417 }
3418
3419 - (void)viewDidHide
3420 {
3421     _impl->viewDidHide();
3422 }
3423
3424 - (void)viewDidUnhide
3425 {
3426     _impl->viewDidUnhide();
3427 }
3428
3429 - (void)viewDidChangeBackingProperties
3430 {
3431     _impl->viewDidChangeBackingProperties();
3432 }
3433
3434 - (void)_activeSpaceDidChange:(NSNotification *)notification
3435 {
3436     _impl->activeSpaceDidChange();
3437 }
3438
3439 - (id)accessibilityFocusedUIElement
3440 {
3441     return _impl->accessibilityFocusedUIElement();
3442 }
3443
3444 - (BOOL)accessibilityIsIgnored
3445 {
3446     return _impl->accessibilityIsIgnored();
3447 }
3448
3449 - (id)accessibilityHitTest:(NSPoint)point
3450 {
3451     return _impl->accessibilityHitTest(NSPointToCGPoint(point));
3452 }
3453
3454 - (id)accessibilityAttributeValue:(NSString *)attribute
3455 {
3456     return _impl->accessibilityAttributeValue(attribute);
3457 }
3458
3459 - (NSView *)hitTest:(NSPoint)point
3460 {
3461     if (!_impl)
3462         return [super hitTest:point];
3463     return _impl->hitTest(NSPointToCGPoint(point));
3464 }
3465
3466 - (NSInteger)conversationIdentifier
3467 {
3468     return (NSInteger)self;
3469 }
3470
3471 - (void)quickLookWithEvent:(NSEvent *)event
3472 {
3473     _impl->quickLookWithEvent(event);
3474 }
3475
3476 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
3477 {
3478     return _impl->addTrackingRect(NSRectToCGRect(rect), owner, data, assumeInside);
3479 }
3480
3481 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
3482 {
3483     return _impl->addTrackingRectWithTrackingNum(NSRectToCGRect(rect), owner, data, assumeInside, tag);
3484 }
3485
3486 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
3487 {
3488     CGRect *cgRects = (CGRect *)calloc(1, sizeof(CGRect));
3489     for (int i = 0; i < count; i++)
3490         cgRects[i] = NSRectToCGRect(rects[i]);
3491     _impl->addTrackingRectsWithTrackingNums(cgRects, owner, userDataList, assumeInsideList, trackingNums, count);
3492     free(cgRects);
3493 }
3494
3495 - (void)removeTrackingRect:(NSTrackingRectTag)tag
3496 {
3497     if (!_impl)
3498         return;
3499     _impl->removeTrackingRect(tag);
3500 }
3501
3502 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
3503 {
3504     if (!_impl)
3505         return;
3506     _impl->removeTrackingRects(tags, count);
3507 }
3508
3509 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
3510 {
3511     return _impl->stringForToolTip(tag);
3512 }
3513
3514 - (void)pasteboardChangedOwner:(NSPasteboard *)pasteboard
3515 {
3516     _impl->pasteboardChangedOwner(pasteboard);
3517 }
3518
3519 - (void)pasteboard:(NSPasteboard *)pasteboard provideDataForType:(NSString *)type
3520 {
3521     _impl->provideDataForPasteboard(pasteboard, type);
3522 }
3523