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