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