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