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