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