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