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