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