[iOS] Remove some unnecessary editing SPI after <rdar://problem/46047546>
[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(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 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 WTF::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     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     Optional<WebCore::FloatSize> _lastSentViewLayoutSize;
287     BOOL _overridesMaximumUnobscuredSize;
288     CGSize _maximumUnobscuredSizeOverride;
289     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     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     Optional<CGRect> _frozenVisibleContentRect;
324     Optional<CGRect> _frozenUnobscuredContentRect;
325
326     BOOL _commitDidRestoreScrollPosition;
327     Optional<WebCore::FloatPoint> _scrollOffsetToRestore;
328     WebCore::FloatBoxExtent _obscuredInsetsWhenSaved;
329
330     Optional<WebCore::FloatPoint> _unobscuredCenterToRestore;
331     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         auto 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
1452     #undef FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW
1453
1454     return [super canPerformAction:action withSender:sender];
1455 }
1456
1457 - (id)targetForAction:(SEL)action withSender:(id)sender
1458 {
1459     #define FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_action) \
1460         if (action == @selector(_action:) && self.usesStandardContentView) \
1461             return [_contentView targetForActionForWebView:action withSender:sender];
1462
1463     FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW)
1464     FOR_EACH_PRIVATE_WKCONTENTVIEW_ACTION(FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW)
1465     FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_setTextColor:sender)
1466     FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_setFontSize:sender)
1467     FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_setFont:sender)
1468
1469     #undef FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW
1470
1471     return [super targetForAction:action withSender:sender];
1472 }
1473
1474 static inline CGFloat floorToDevicePixel(CGFloat input, float deviceScaleFactor)
1475 {
1476     return CGFloor(input * deviceScaleFactor) / deviceScaleFactor;
1477 }
1478
1479 static inline bool pointsEqualInDevicePixels(CGPoint a, CGPoint b, float deviceScaleFactor)
1480 {
1481     return fabs(a.x * deviceScaleFactor - b.x * deviceScaleFactor) < std::numeric_limits<float>::epsilon()
1482         && fabs(a.y * deviceScaleFactor - b.y * deviceScaleFactor) < std::numeric_limits<float>::epsilon();
1483 }
1484
1485 static CGSize roundScrollViewContentSize(const WebKit::WebPageProxy& page, CGSize contentSize)
1486 {
1487     float deviceScaleFactor = page.deviceScaleFactor();
1488     return CGSizeMake(floorToDevicePixel(contentSize.width, deviceScaleFactor), floorToDevicePixel(contentSize.height, deviceScaleFactor));
1489 }
1490
1491 - (UIView *)_currentContentView
1492 {
1493     return _customContentView ? [_customContentView web_contentView] : _contentView.get();
1494 }
1495
1496 - (WKWebViewContentProviderRegistry *)_contentProviderRegistry
1497 {
1498     return [_configuration _contentProviderRegistry];
1499 }
1500
1501 - (WKSelectionGranularity)_selectionGranularity
1502 {
1503     return [_configuration selectionGranularity];
1504 }
1505
1506 - (void)_setHasCustomContentView:(BOOL)pageHasCustomContentView loadedMIMEType:(const WTF::String&)mimeType
1507 {
1508     if (pageHasCustomContentView) {
1509         [_customContentView removeFromSuperview];
1510         [_customContentFixedOverlayView removeFromSuperview];
1511
1512         Class representationClass = [[_configuration _contentProviderRegistry] providerForMIMEType:mimeType];
1513         ASSERT(representationClass);
1514         _customContentView = adoptNS([[representationClass alloc] web_initWithFrame:self.bounds webView:self mimeType:mimeType]);
1515         _customContentFixedOverlayView = adoptNS([[UIView alloc] initWithFrame:self.bounds]);
1516         [_customContentFixedOverlayView layer].name = @"CustomContentFixedOverlay";
1517         [_customContentFixedOverlayView setUserInteractionEnabled:NO];
1518
1519         [[_contentView unscaledView] removeFromSuperview];
1520         [_contentView removeFromSuperview];
1521         [_scrollView addSubview:_customContentView.get()];
1522         [self addSubview:_customContentFixedOverlayView.get()];
1523
1524         [_customContentView web_setMinimumSize:self.bounds.size];
1525         [_customContentView web_setFixedOverlayView:_customContentFixedOverlayView.get()];
1526
1527         _scrollViewBackgroundColor = WebCore::Color();
1528         [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1529
1530         [self _setAvoidsUnsafeArea:NO];
1531     } else if (_customContentView) {
1532         [_customContentView removeFromSuperview];
1533         _customContentView = nullptr;
1534
1535         [_customContentFixedOverlayView removeFromSuperview];
1536         _customContentFixedOverlayView = nullptr;
1537
1538         [_scrollView addSubview:_contentView.get()];
1539         [_scrollView addSubview:[_contentView unscaledView]];
1540         [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
1541
1542         [_customContentFixedOverlayView setFrame:self.bounds];
1543         [self addSubview:_customContentFixedOverlayView.get()];
1544     }
1545
1546     if (self.isFirstResponder) {
1547         UIView *currentContentView = self._currentContentView;
1548         if (currentContentView == _contentView ? [_contentView canBecomeFirstResponderForWebView] : currentContentView.canBecomeFirstResponder)
1549             [currentContentView becomeFirstResponder];
1550     }
1551 }
1552
1553 - (void)_didFinishLoadingDataForCustomContentProviderWithSuggestedFilename:(const String&)suggestedFilename data:(NSData *)data
1554 {
1555     ASSERT(_customContentView);
1556     [_customContentView web_setContentProviderData:data suggestedFilename:suggestedFilename];
1557
1558     // FIXME: It may make more sense for custom content providers to invoke this when they're ready,
1559     // because there's no guarantee that all custom content providers will lay out synchronously.
1560     _page->didLayoutForCustomContentProvider();
1561 }
1562
1563 - (void)_handleKeyUIEvent:(::UIEvent *)event
1564 {
1565     // We only want to handle key events from the hardware keyboard when we are
1566     // first responder and a custom content view is installed; otherwise,
1567     // WKContentView will be the first responder and expects to get key events directly.
1568     if ([self isFirstResponder] && event._hidEvent) {
1569         if ([_customContentView respondsToSelector:@selector(web_handleKeyEvent:)]) {
1570             if ([_customContentView web_handleKeyEvent:event])
1571                 return;
1572         }
1573     }
1574
1575     [super _handleKeyUIEvent:event];
1576 }
1577
1578 - (void)_willInvokeUIScrollViewDelegateCallback
1579 {
1580     _delayUpdateVisibleContentRects = YES;
1581 }
1582
1583 - (void)_didInvokeUIScrollViewDelegateCallback
1584 {
1585     _delayUpdateVisibleContentRects = NO;
1586     if (_hadDelayedUpdateVisibleContentRects) {
1587         _hadDelayedUpdateVisibleContentRects = NO;
1588         [self _scheduleVisibleContentRectUpdate];
1589     }
1590 }
1591
1592 static CGFloat contentZoomScale(WKWebView *webView)
1593 {
1594     CGFloat scale = webView._currentContentView.layer.affineTransform.a;
1595     ASSERT(scale == [webView->_scrollView zoomScale]);
1596     return scale;
1597 }
1598
1599 static WebCore::Color baseScrollViewBackgroundColor(WKWebView *webView)
1600 {
1601     if (webView->_customContentView)
1602         return [webView->_customContentView backgroundColor].CGColor;
1603
1604     if (webView->_gestureController) {
1605         WebCore::Color color = webView->_gestureController->backgroundColorForCurrentSnapshot();
1606         if (color.isValid())
1607             return color;
1608     }
1609
1610     return webView->_page->pageExtendedBackgroundColor();
1611 }
1612
1613 static WebCore::Color scrollViewBackgroundColor(WKWebView *webView)
1614 {
1615     if (!webView.opaque)
1616         return WebCore::Color::transparent;
1617
1618     WebCore::Color color = baseScrollViewBackgroundColor(webView);
1619
1620     if (!color.isValid())
1621         color = WebCore::Color::white;
1622
1623     CGFloat zoomScale = contentZoomScale(webView);
1624     CGFloat minimumZoomScale = [webView->_scrollView minimumZoomScale];
1625     if (zoomScale < minimumZoomScale) {
1626         CGFloat slope = 12;
1627         CGFloat opacity = std::max<CGFloat>(1 - slope * (minimumZoomScale - zoomScale), 0);
1628         color = WebCore::colorWithOverrideAlpha(color.rgb(), opacity);
1629     }
1630
1631     return color;
1632 }
1633
1634 - (void)_updateScrollViewBackground
1635 {
1636     WebCore::Color color = scrollViewBackgroundColor(self);
1637
1638     if (_scrollViewBackgroundColor == color)
1639         return;
1640
1641     _scrollViewBackgroundColor = color;
1642
1643     auto uiBackgroundColor = adoptNS([[UIColor alloc] initWithCGColor:cachedCGColor(color)]);
1644     [_scrollView setBackgroundColor:uiBackgroundColor.get()];
1645
1646     // Update the indicator style based on the lightness/darkness of the background color.
1647     double hue, saturation, lightness;
1648     color.getHSL(hue, saturation, lightness);
1649     if (lightness <= .5 && color.isVisible())
1650         [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleWhite];
1651     else
1652         [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleDefault];
1653 }
1654
1655 - (void)_videoControlsManagerDidChange
1656 {
1657 #if ENABLE(FULLSCREEN_API)
1658     if (_fullScreenWindowController)
1659         [_fullScreenWindowController videoControlsManagerDidChange];
1660 #endif
1661 }
1662
1663 - (CGPoint)_initialContentOffsetForScrollView
1664 {
1665     auto combinedUnobscuredAndScrollViewInset = [self _computedContentInset];
1666     return CGPointMake(-combinedUnobscuredAndScrollViewInset.left, -combinedUnobscuredAndScrollViewInset.top);
1667 }
1668
1669 - (CGPoint)_contentOffsetAdjustedForObscuredInset:(CGPoint)point
1670 {
1671     CGPoint result = point;
1672     UIEdgeInsets contentInset = [self _computedObscuredInset];
1673
1674     result.x -= contentInset.left;
1675     result.y -= contentInset.top;
1676
1677     return result;
1678 }
1679
1680 - (UIRectEdge)_effectiveObscuredInsetEdgesAffectedBySafeArea
1681 {
1682     if (![self usesStandardContentView])
1683         return UIRectEdgeAll;
1684     return _obscuredInsetEdgesAffectedBySafeArea;
1685 }
1686
1687 - (UIEdgeInsets)_computedObscuredInset
1688 {
1689     if (!linkedOnOrAfter(WebKit::SDKVersion::FirstWhereScrollViewContentInsetsAreNotObscuringInsets)) {
1690         // For binary compability with third party apps, treat scroll view content insets as obscuring insets when the app is compiled
1691         // against a WebKit version without the fix in r229641.
1692         return [self _computedContentInset];
1693     }
1694
1695     if (_haveSetObscuredInsets)
1696         return _obscuredInsets;
1697
1698 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1699     if (self._safeAreaShouldAffectObscuredInsets)
1700         return UIEdgeInsetsAdd(UIEdgeInsetsZero, self._scrollViewSystemContentInset, self._effectiveObscuredInsetEdgesAffectedBySafeArea);
1701 #endif
1702
1703     return UIEdgeInsetsZero;
1704 }
1705
1706 - (UIEdgeInsets)_computedContentInset
1707 {
1708     if (_haveSetObscuredInsets)
1709         return _obscuredInsets;
1710
1711     UIEdgeInsets insets = [_scrollView contentInset];
1712
1713 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1714     if (self._safeAreaShouldAffectObscuredInsets)
1715         insets = UIEdgeInsetsAdd(insets, self._scrollViewSystemContentInset, self._effectiveObscuredInsetEdgesAffectedBySafeArea);
1716 #endif
1717
1718     return insets;
1719 }
1720
1721 - (UIEdgeInsets)_computedUnobscuredSafeAreaInset
1722 {
1723     if (_haveSetUnobscuredSafeAreaInsets)
1724         return _unobscuredSafeAreaInsets;
1725
1726 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1727     if (!self._safeAreaShouldAffectObscuredInsets)
1728         return self.safeAreaInsets;
1729 #endif
1730
1731     return UIEdgeInsetsZero;
1732 }
1733
1734 - (void)_processWillSwapOrDidExit
1735 {
1736     // FIXME: Which ones of these need to be done in the process swap case and which ones in the exit case?
1737     [self _hidePasswordView];
1738     [self _cancelAnimatedResize];
1739
1740     _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
1741     _initialScaleFactor = 1;
1742     _hasCommittedLoadForMainFrame = NO;
1743     _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1744     _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
1745     _waitingForEndAnimatedResize = NO;
1746     _waitingForCommitAfterAnimatedResize = NO;
1747     _animatedResizeOriginalContentWidth = 0;
1748     [_contentView setHidden:NO];
1749     _scrollOffsetToRestore = WTF::nullopt;
1750     _unobscuredCenterToRestore = WTF::nullopt;
1751     _scrollViewBackgroundColor = WebCore::Color();
1752     _delayUpdateVisibleContentRects = NO;
1753     _hadDelayedUpdateVisibleContentRects = NO;
1754     _currentlyAdjustingScrollViewInsetsForKeyboard = NO;
1755     _lastSentViewLayoutSize = WTF::nullopt;
1756     _lastSentMaximumUnobscuredSize = WTF::nullopt;
1757     _lastSentDeviceOrientation = WTF::nullopt;
1758
1759     _frozenVisibleContentRect = WTF::nullopt;
1760     _frozenUnobscuredContentRect = WTF::nullopt;
1761
1762     _firstPaintAfterCommitLoadTransactionID = 0;
1763     _firstTransactionIDAfterPageRestore = WTF::nullopt;
1764
1765     _hasScheduledVisibleRectUpdate = NO;
1766     _commitDidRestoreScrollPosition = NO;
1767
1768     _avoidsUnsafeArea = YES;
1769 }
1770
1771 - (void)_processWillSwap
1772 {
1773     RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _processWillSwap]", self);
1774     [self _processWillSwapOrDidExit];
1775 }
1776
1777 - (void)_processDidExit
1778 {
1779     RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _processDidExit]", self);
1780
1781     [self _processWillSwapOrDidExit];
1782
1783     [_contentView setFrame:self.bounds];
1784     [_scrollView setBackgroundColor:[UIColor whiteColor]];
1785     [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1786     [_scrollView setZoomScale:1];
1787     
1788 }
1789
1790 - (void)_didRelaunchProcess
1791 {
1792     RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didRelaunchProcess]", self);
1793     _hasScheduledVisibleRectUpdate = NO;
1794     _visibleContentRectUpdateScheduledFromScrollViewInStableState = YES;
1795 }
1796
1797 - (void)_didCommitLoadForMainFrame
1798 {
1799     _firstPaintAfterCommitLoadTransactionID = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1800
1801     _hasCommittedLoadForMainFrame = YES;
1802     _needsResetViewStateAfterCommitLoadForMainFrame = YES;
1803
1804     [_scrollView _stopScrollingAndZoomingAnimations];
1805 }
1806
1807 static CGPoint contentOffsetBoundedInValidRange(UIScrollView *scrollView, CGPoint contentOffset)
1808 {
1809 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1810     UIEdgeInsets contentInsets = scrollView.adjustedContentInset;
1811 #else
1812     UIEdgeInsets contentInsets = scrollView.contentInset;
1813 #endif
1814
1815     CGSize contentSize = scrollView.contentSize;
1816     CGSize scrollViewSize = scrollView.bounds.size;
1817
1818     CGPoint minimumContentOffset = CGPointMake(-contentInsets.left, -contentInsets.top);
1819     CGPoint maximumContentOffset = CGPointMake(std::max(minimumContentOffset.x, contentSize.width + contentInsets.right - scrollViewSize.width), std::max(minimumContentOffset.y, contentSize.height + contentInsets.bottom - scrollViewSize.height));
1820
1821     return CGPointMake(std::max(std::min(contentOffset.x, maximumContentOffset.x), minimumContentOffset.x), std::max(std::min(contentOffset.y, maximumContentOffset.y), minimumContentOffset.y));
1822 }
1823
1824 static void changeContentOffsetBoundedInValidRange(UIScrollView *scrollView, WebCore::FloatPoint contentOffset)
1825 {
1826     scrollView.contentOffset = contentOffsetBoundedInValidRange(scrollView, contentOffset);
1827 }
1828
1829 - (WebCore::FloatRect)visibleRectInViewCoordinates
1830 {
1831     WebCore::FloatRect bounds = self.bounds;
1832     bounds.moveBy([_scrollView contentOffset]);
1833     WebCore::FloatRect contentViewBounds = [_contentView bounds];
1834     bounds.intersect(contentViewBounds);
1835     return bounds;
1836 }
1837
1838 // WebCore stores the page scale factor as float instead of double. When we get a scale from WebCore,
1839 // we need to ignore differences that are within a small rounding error on floats.
1840 static inline bool areEssentiallyEqualAsFloat(float a, float b)
1841 {
1842     return WTF::areEssentiallyEqual(a, b);
1843 }
1844
1845 - (void)_didCommitLayerTreeDuringAnimatedResize:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
1846 {
1847     auto updateID = layerTreeTransaction.dynamicViewportSizeUpdateID();
1848     if (updateID && *updateID == _currentDynamicViewportSizeUpdateID) {
1849         double pageScale = layerTreeTransaction.pageScaleFactor();
1850         WebCore::IntPoint scrollPosition = layerTreeTransaction.scrollPosition();
1851
1852         CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
1853         double currentTargetScale = animatingScaleTarget * [[_contentView layer] transform].m11;
1854         double scale = pageScale / currentTargetScale;
1855         _resizeAnimationTransformAdjustments = CATransform3DMakeScale(scale, scale, 1);
1856
1857         CGPoint newContentOffset = [self _contentOffsetAdjustedForObscuredInset:CGPointMake(scrollPosition.x() * pageScale, scrollPosition.y() * pageScale)];
1858         CGPoint currentContentOffset = [_scrollView contentOffset];
1859
1860         _resizeAnimationTransformAdjustments.m41 = (currentContentOffset.x - newContentOffset.x) / animatingScaleTarget;
1861         _resizeAnimationTransformAdjustments.m42 = (currentContentOffset.y - newContentOffset.y) / animatingScaleTarget;
1862
1863         [_resizeAnimationView layer].sublayerTransform = _resizeAnimationTransformAdjustments;
1864
1865         // If we've already passed endAnimatedResize, immediately complete
1866         // the resize when we have an up-to-date layer tree. Otherwise,
1867         // we will defer completion until endAnimatedResize.
1868         _waitingForCommitAfterAnimatedResize = NO;
1869         if (!_waitingForEndAnimatedResize)
1870             [self _didCompleteAnimatedResize];
1871
1872         return;
1873     }
1874
1875     // If a commit arrives during the live part of a resize but before the
1876     // layer tree takes the current resize into account, it could change the
1877     // WKContentView's size. Update the resizeAnimationView's scale to ensure
1878     // we continue to fill the width of the resize target.
1879
1880     if (_waitingForEndAnimatedResize)
1881         return;
1882
1883     auto newViewLayoutSize = [self activeViewLayoutSize:self.bounds];
1884     CGFloat resizeAnimationViewScale = _animatedResizeOriginalContentWidth / newViewLayoutSize.width();
1885     [[_resizeAnimationView layer] setSublayerTransform:CATransform3DMakeScale(resizeAnimationViewScale, resizeAnimationViewScale, 1)];
1886 }
1887
1888 - (void)_didCommitLayerTree:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
1889 {
1890     if (![self usesStandardContentView])
1891         return;
1892
1893     LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _didCommitLayerTree:] transactionID " <<  layerTreeTransaction.transactionID() << " _dynamicViewportUpdateMode " << (int)_dynamicViewportUpdateMode);
1894
1895     bool needUpdateVisibleContentRects = _page->updateLayoutViewportParameters(layerTreeTransaction);
1896
1897     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing) {
1898         [self _didCommitLayerTreeDuringAnimatedResize:layerTreeTransaction];
1899         return;
1900     }
1901
1902     if (_resizeAnimationView)
1903         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didCommitLayerTree:] - dynamicViewportUpdateMode is NotResizing, but still have a live resizeAnimationView (unpaired begin/endAnimatedResize?)", self);
1904
1905     CGSize newContentSize = roundScrollViewContentSize(*_page, [_contentView frame].size);
1906     [_scrollView _setContentSizePreservingContentOffsetDuringRubberband:newContentSize];
1907
1908     [_scrollView setMinimumZoomScale:layerTreeTransaction.minimumScaleFactor()];
1909     [_scrollView setMaximumZoomScale:layerTreeTransaction.maximumScaleFactor()];
1910     [_scrollView setZoomEnabled:layerTreeTransaction.allowsUserScaling()];
1911     if (!layerTreeTransaction.scaleWasSetByUIProcess() && ![_scrollView isZooming] && ![_scrollView isZoomBouncing] && ![_scrollView _isAnimatingZoom] && [_scrollView zoomScale] != layerTreeTransaction.pageScaleFactor()) {
1912         LOG_WITH_STREAM(VisibleRects, stream << " updating scroll view with pageScaleFactor " << layerTreeTransaction.pageScaleFactor());
1913         [_scrollView setZoomScale:layerTreeTransaction.pageScaleFactor()];
1914     }
1915
1916     _viewportMetaTagWidth = layerTreeTransaction.viewportMetaTagWidth();
1917     _viewportMetaTagWidthWasExplicit = layerTreeTransaction.viewportMetaTagWidthWasExplicit();
1918     _viewportMetaTagCameFromImageDocument = layerTreeTransaction.viewportMetaTagCameFromImageDocument();
1919     _initialScaleFactor = layerTreeTransaction.initialScaleFactor();
1920     if (_page->inStableState() && layerTreeTransaction.isInStableState() && [_stableStatePresentationUpdateCallbacks count]) {
1921         for (dispatch_block_t action in _stableStatePresentationUpdateCallbacks.get())
1922             action();
1923
1924         [_stableStatePresentationUpdateCallbacks removeAllObjects];
1925         _stableStatePresentationUpdateCallbacks = nil;
1926     }
1927
1928     if (![_contentView _mayDisableDoubleTapGesturesDuringSingleTap])
1929         [_contentView _setDoubleTapGesturesEnabled:self._allowsDoubleTapGestures];
1930
1931     [self _updateScrollViewBackground];
1932     [self _setAvoidsUnsafeArea:layerTreeTransaction.avoidsUnsafeArea()];
1933
1934     if (_gestureController)
1935         _gestureController->setRenderTreeSize(layerTreeTransaction.renderTreeSize());
1936
1937     if (_needsResetViewStateAfterCommitLoadForMainFrame && layerTreeTransaction.transactionID() >= _firstPaintAfterCommitLoadTransactionID) {
1938         _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1939         [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1940         if (_observedRenderingProgressEvents & _WKRenderingProgressEventFirstPaint)
1941             _navigationState->didFirstPaint();
1942
1943         needUpdateVisibleContentRects = true;
1944     }
1945
1946     if (_firstTransactionIDAfterPageRestore && layerTreeTransaction.transactionID() >= _firstTransactionIDAfterPageRestore.value()) {
1947         if (_scrollOffsetToRestore) {
1948             WebCore::FloatPoint scaledScrollOffset = _scrollOffsetToRestore.value();
1949             _scrollOffsetToRestore = WTF::nullopt;
1950
1951             if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1952                 scaledScrollOffset.scale(_scaleToRestore);
1953                 WebCore::FloatPoint contentOffsetInScrollViewCoordinates = scaledScrollOffset - WebCore::FloatSize(_obscuredInsetsWhenSaved.left(), _obscuredInsetsWhenSaved.top());
1954
1955                 changeContentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
1956                 _commitDidRestoreScrollPosition = YES;
1957             }
1958
1959             needUpdateVisibleContentRects = true;
1960         }
1961
1962         if (_unobscuredCenterToRestore) {
1963             WebCore::FloatPoint unobscuredCenterToRestore = _unobscuredCenterToRestore.value();
1964             _unobscuredCenterToRestore = WTF::nullopt;
1965
1966             if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1967                 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, _obscuredInsets);
1968                 WebCore::FloatSize unobscuredContentSizeAtNewScale = WebCore::FloatSize(unobscuredRect.size) / _scaleToRestore;
1969                 WebCore::FloatPoint topLeftInDocumentCoordinates = unobscuredCenterToRestore - unobscuredContentSizeAtNewScale / 2;
1970
1971                 topLeftInDocumentCoordinates.scale(_scaleToRestore);
1972                 topLeftInDocumentCoordinates.moveBy(WebCore::FloatPoint(-_obscuredInsets.left, -_obscuredInsets.top));
1973
1974                 changeContentOffsetBoundedInValidRange(_scrollView.get(), topLeftInDocumentCoordinates);
1975             }
1976
1977             needUpdateVisibleContentRects = true;
1978         }
1979
1980         if (_gestureController)
1981             _gestureController->didRestoreScrollPosition();
1982
1983         _firstTransactionIDAfterPageRestore = WTF::nullopt;
1984     }
1985
1986     if (needUpdateVisibleContentRects)
1987         [self _scheduleVisibleContentRectUpdate];
1988
1989     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
1990         scrollPerfData->didCommitLayerTree([self visibleRectInViewCoordinates]);
1991 }
1992
1993 - (void)_layerTreeCommitComplete
1994 {
1995     _commitDidRestoreScrollPosition = NO;
1996 }
1997
1998 - (void)_couldNotRestorePageState
1999 {
2000     // The gestureController may be waiting for the scroll position to be restored
2001     // in order to remove the swipe snapshot. Since the scroll position could not be
2002     // restored, tell the gestureController it was restored so that it no longer waits
2003     // for it.
2004     if (_gestureController)
2005         _gestureController->didRestoreScrollPosition();
2006 }
2007
2008 - (void)_restorePageScrollPosition:(Optional<WebCore::FloatPoint>)scrollPosition scrollOrigin:(WebCore::FloatPoint)scrollOrigin previousObscuredInset:(WebCore::FloatBoxExtent)obscuredInsets scale:(double)scale
2009 {
2010     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing)
2011         return;
2012
2013     if (![self usesStandardContentView])
2014         return;
2015
2016     _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
2017     if (scrollPosition)
2018         _scrollOffsetToRestore = WebCore::ScrollableArea::scrollOffsetFromPosition(WebCore::FloatPoint(scrollPosition.value()), WebCore::toFloatSize(scrollOrigin));
2019     else
2020         _scrollOffsetToRestore = WTF::nullopt;
2021
2022     _obscuredInsetsWhenSaved = obscuredInsets;
2023     _scaleToRestore = scale;
2024 }
2025
2026 - (void)_restorePageStateToUnobscuredCenter:(Optional<WebCore::FloatPoint>)center scale:(double)scale
2027 {
2028     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing)
2029         return;
2030
2031     if (![self usesStandardContentView])
2032         return;
2033
2034     _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
2035     _unobscuredCenterToRestore = center;
2036
2037     _scaleToRestore = scale;
2038 }
2039
2040 - (RefPtr<WebKit::ViewSnapshot>)_takeViewSnapshot
2041 {
2042 #if HAVE(CORE_ANIMATION_RENDER_SERVER)
2043     float deviceScale = WebCore::screenScaleFactor();
2044     WebCore::FloatSize snapshotSize(self.bounds.size);
2045     snapshotSize.scale(deviceScale);
2046
2047     CATransform3D transform = CATransform3DMakeScale(deviceScale, deviceScale, 1);
2048
2049 #if HAVE(IOSURFACE)
2050     WebCore::IOSurface::Format snapshotFormat = WebCore::screenSupportsExtendedColor() ? WebCore::IOSurface::Format::RGB10 : WebCore::IOSurface::Format::RGBA;
2051     auto surface = WebCore::IOSurface::create(WebCore::expandedIntSize(snapshotSize), WebCore::sRGBColorSpaceRef(), snapshotFormat);
2052     if (!surface)
2053         return nullptr;
2054     CARenderServerRenderLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, reinterpret_cast<uint64_t>(self.layer), surface->surface(), 0, 0, &transform);
2055
2056 #if HAVE(IOSURFACE_ACCELERATOR)
2057     WebCore::IOSurface::Format compressedFormat = WebCore::IOSurface::Format::YUV422;
2058     if (WebCore::IOSurface::allowConversionFromFormatToFormat(snapshotFormat, compressedFormat)) {
2059         auto viewSnapshot = WebKit::ViewSnapshot::create(nullptr);
2060         WebCore::IOSurface::convertToFormat(WTFMove(surface), WebCore::IOSurface::Format::YUV422, [viewSnapshot = viewSnapshot.copyRef()](std::unique_ptr<WebCore::IOSurface> convertedSurface) {
2061             if (convertedSurface)
2062                 viewSnapshot->setSurface(WTFMove(convertedSurface));
2063         });
2064
2065         return viewSnapshot;
2066     }
2067 #endif // HAVE(IOSURFACE_ACCELERATOR)
2068
2069     return WebKit::ViewSnapshot::create(WTFMove(surface));
2070 #else // HAVE(IOSURFACE)
2071     uint32_t slotID = [WebKit::ViewSnapshotStore::snapshottingContext() createImageSlot:snapshotSize hasAlpha:YES];
2072
2073     if (!slotID)
2074         return nullptr;
2075
2076     CARenderServerCaptureLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, (uint64_t)self.layer, slotID, 0, 0, &transform);
2077     WebCore::IntSize imageSize = WebCore::expandedIntSize(WebCore::FloatSize(snapshotSize));
2078     return WebKit::ViewSnapshot::create(slotID, imageSize, (imageSize.area() * 4).unsafeGet());
2079 #endif // HAVE(IOSURFACE)
2080 #else // HAVE(CORE_ANIMATION_RENDER_SERVER)
2081     return nullptr;
2082 #endif
2083 }
2084
2085 - (void)_zoomToPoint:(WebCore::FloatPoint)point atScale:(double)scale animated:(BOOL)animated
2086 {
2087     CFTimeInterval duration = 0;
2088     CGFloat zoomScale = contentZoomScale(self);
2089
2090     if (animated) {
2091         const double maximumZoomDuration = 0.4;
2092         const double minimumZoomDuration = 0.1;
2093         const double zoomDurationFactor = 0.3;
2094
2095         duration = std::min(fabs(log(zoomScale) - log(scale)) * zoomDurationFactor + minimumZoomDuration, maximumZoomDuration);
2096     }
2097
2098     if (scale != zoomScale)
2099         _page->willStartUserTriggeredZooming();
2100
2101     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToPoint:" << point << " scale: " << scale << " duration:" << duration);
2102
2103     [_scrollView _zoomToCenter:point scale:scale duration:duration];
2104 }
2105
2106 - (void)_zoomToRect:(WebCore::FloatRect)targetRect atScale:(double)scale origin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2107 {
2108     // FIXME: Some of this could be shared with _scrollToRect.
2109     const double visibleRectScaleChange = contentZoomScale(self) / scale;
2110     const WebCore::FloatRect visibleRect([self convertRect:self.bounds toView:self._currentContentView]);
2111     const WebCore::FloatRect unobscuredRect([self _contentRectForUserInteraction]);
2112
2113     const WebCore::FloatSize topLeftObscuredInsetAfterZoom((unobscuredRect.minXMinYCorner() - visibleRect.minXMinYCorner()) * visibleRectScaleChange);
2114     const WebCore::FloatSize bottomRightObscuredInsetAfterZoom((visibleRect.maxXMaxYCorner() - unobscuredRect.maxXMaxYCorner()) * visibleRectScaleChange);
2115
2116     const WebCore::FloatSize unobscuredRectSizeAfterZoom(unobscuredRect.size() * visibleRectScaleChange);
2117
2118     // Center to the target rect.
2119     WebCore::FloatPoint unobscuredRectLocationAfterZoom = targetRect.location() - (unobscuredRectSizeAfterZoom - targetRect.size()) * 0.5;
2120
2121     // Center to the tap point instead in case the target rect won't fit in a direction.
2122     if (targetRect.width() > unobscuredRectSizeAfterZoom.width())
2123         unobscuredRectLocationAfterZoom.setX(origin.x() - unobscuredRectSizeAfterZoom.width() / 2);
2124     if (targetRect.height() > unobscuredRectSizeAfterZoom.height())
2125         unobscuredRectLocationAfterZoom.setY(origin.y() - unobscuredRectSizeAfterZoom.height() / 2);
2126
2127     // We have computed where we want the unobscured rect to be. Now adjust for the obscuring insets.
2128     WebCore::FloatRect visibleRectAfterZoom(unobscuredRectLocationAfterZoom, unobscuredRectSizeAfterZoom);
2129     visibleRectAfterZoom.move(-topLeftObscuredInsetAfterZoom);
2130     visibleRectAfterZoom.expand(topLeftObscuredInsetAfterZoom + bottomRightObscuredInsetAfterZoom);
2131
2132     [self _zoomToPoint:visibleRectAfterZoom.center() atScale:scale animated:animated];
2133 }
2134
2135 static WebCore::FloatPoint constrainContentOffset(WebCore::FloatPoint contentOffset, WebCore::FloatSize contentSize, WebCore::FloatSize unobscuredContentSize)
2136 {
2137     WebCore::FloatSize maximumContentOffset = contentSize - unobscuredContentSize;
2138     return contentOffset.constrainedBetween(WebCore::FloatPoint(), WebCore::FloatPoint(maximumContentOffset));
2139 }
2140
2141 - (void)_scrollToContentScrollPosition:(WebCore::FloatPoint)scrollPosition scrollOrigin:(WebCore::IntPoint)scrollOrigin
2142 {
2143     if (_commitDidRestoreScrollPosition || _dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing)
2144         return;
2145
2146     WebCore::FloatPoint contentOffset = WebCore::ScrollableArea::scrollOffsetFromPosition(scrollPosition, toFloatSize(scrollOrigin));
2147
2148     WebCore::FloatPoint scaledOffset = contentOffset;
2149     CGFloat zoomScale = contentZoomScale(self);
2150     scaledOffset.scale(zoomScale);
2151
2152     CGPoint contentOffsetInScrollViewCoordinates = [self _contentOffsetAdjustedForObscuredInset:scaledOffset];
2153     contentOffsetInScrollViewCoordinates = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
2154
2155     [_scrollView _stopScrollingAndZoomingAnimations];
2156
2157     if (!CGPointEqualToPoint(contentOffsetInScrollViewCoordinates, [_scrollView contentOffset]))
2158         [_scrollView setContentOffset:contentOffsetInScrollViewCoordinates];
2159     else {
2160         // If we haven't changed anything, there would not be any VisibleContentRect update sent to the content.
2161         // The WebProcess would keep the invalid contentOffset as its scroll position.
2162         // To synchronize the WebProcess with what is on screen, we send the VisibleContentRect again.
2163         _page->resendLastVisibleContentRects();
2164     }
2165 }
2166
2167 - (BOOL)_scrollToRect:(WebCore::FloatRect)targetRect origin:(WebCore::FloatPoint)origin minimumScrollDistance:(float)minimumScrollDistance
2168 {
2169     WebCore::FloatRect unobscuredContentRect([self _contentRectForUserInteraction]);
2170     WebCore::FloatPoint unobscuredContentOffset = unobscuredContentRect.location();
2171     WebCore::FloatSize contentSize([self._currentContentView bounds].size);
2172
2173     // Center the target rect in the scroll view.
2174     // If the target doesn't fit in the scroll view, center on the gesture location instead.
2175     WebCore::FloatPoint newUnobscuredContentOffset;
2176     if (targetRect.width() <= unobscuredContentRect.width())
2177         newUnobscuredContentOffset.setX(targetRect.x() - (unobscuredContentRect.width() - targetRect.width()) / 2);
2178     else
2179         newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
2180     if (targetRect.height() <= unobscuredContentRect.height())
2181         newUnobscuredContentOffset.setY(targetRect.y() - (unobscuredContentRect.height() - targetRect.height()) / 2);
2182     else
2183         newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
2184     newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
2185
2186     if (unobscuredContentOffset == newUnobscuredContentOffset) {
2187         if (targetRect.width() > unobscuredContentRect.width())
2188             newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
2189         if (targetRect.height() > unobscuredContentRect.height())
2190             newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
2191         newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
2192     }
2193
2194     WebCore::FloatSize scrollViewOffsetDelta = newUnobscuredContentOffset - unobscuredContentOffset;
2195     scrollViewOffsetDelta.scale(contentZoomScale(self));
2196
2197     float scrollDistance = scrollViewOffsetDelta.diagonalLength();
2198     if (scrollDistance < minimumScrollDistance)
2199         return false;
2200
2201     [_contentView willStartZoomOrScroll];
2202
2203     LOG_WITH_STREAM(VisibleRects, stream << "_scrollToRect: scrolling to " << [_scrollView contentOffset] + scrollViewOffsetDelta);
2204
2205     [_scrollView setContentOffset:([_scrollView contentOffset] + scrollViewOffsetDelta) animated:YES];
2206     return true;
2207 }
2208
2209 - (void)_zoomOutWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2210 {
2211     [self _zoomToPoint:origin atScale:[_scrollView minimumZoomScale] animated:animated];
2212 }
2213
2214 - (void)_zoomToInitialScaleWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2215 {
2216     ASSERT(_initialScaleFactor > 0);
2217     [self _zoomToPoint:origin atScale:_initialScaleFactor animated:animated];
2218 }
2219
2220 // focusedElementRect and selectionRect are both in document coordinates.
2221 - (void)_zoomToFocusRect:(const WebCore::FloatRect&)focusedElementRectInDocumentCoordinates selectionRect:(const WebCore::FloatRect&)selectionRectInDocumentCoordinates insideFixed:(BOOL)insideFixed
2222     fontSize:(float)fontSize minimumScale:(double)minimumScale maximumScale:(double)maximumScale allowScaling:(BOOL)allowScaling forceScroll:(BOOL)forceScroll
2223 {
2224     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToFocusRect:" << focusedElementRectInDocumentCoordinates << " selectionRect:" << selectionRectInDocumentCoordinates);
2225     UNUSED_PARAM(insideFixed);
2226
2227     const double minimumHeightToShowContentAboveKeyboard = 106;
2228     const CFTimeInterval formControlZoomAnimationDuration = 0.25;
2229     const double caretOffsetFromWindowEdge = 8;
2230
2231     UIWindow *window = [_scrollView window];
2232
2233     // Find the portion of the view that is visible on the screen.
2234     UIViewController *topViewController = [[[_scrollView _viewControllerForAncestor] _rootAncestorViewController] _viewControllerForSupportedInterfaceOrientations];
2235     UIView *fullScreenView = topViewController.view;
2236     if (!fullScreenView)
2237         fullScreenView = window;
2238
2239     CGRect unobscuredScrollViewRectInWebViewCoordinates = UIEdgeInsetsInsetRect([self bounds], _obscuredInsets);
2240     CGRect visibleScrollViewBoundsInWebViewCoordinates = CGRectIntersection(unobscuredScrollViewRectInWebViewCoordinates, [fullScreenView convertRect:[fullScreenView bounds] toView:self]);
2241     CGRect formAssistantFrameInWebViewCoordinates = [window convertRect:_inputViewBounds toView:self];
2242     CGRect intersectionBetweenScrollViewAndFormAssistant = CGRectIntersection(visibleScrollViewBoundsInWebViewCoordinates, formAssistantFrameInWebViewCoordinates);
2243     CGSize visibleSize = visibleScrollViewBoundsInWebViewCoordinates.size;
2244
2245     CGFloat visibleOffsetFromTop = 0;
2246     if (!CGRectIsEmpty(intersectionBetweenScrollViewAndFormAssistant)) {
2247         CGFloat heightVisibleAboveFormAssistant = CGRectGetMinY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
2248         CGFloat heightVisibleBelowFormAssistant = CGRectGetMaxY(visibleScrollViewBoundsInWebViewCoordinates) - CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant);
2249
2250         if (heightVisibleAboveFormAssistant >= minimumHeightToShowContentAboveKeyboard || heightVisibleBelowFormAssistant < heightVisibleAboveFormAssistant)
2251             visibleSize.height = heightVisibleAboveFormAssistant;
2252         else {
2253             visibleSize.height = heightVisibleBelowFormAssistant;
2254             visibleOffsetFromTop = CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
2255         }
2256     }
2257
2258     // Zoom around the element's bounding frame. We use a "standard" size to determine the proper frame.
2259     double currentScale = contentZoomScale(self);
2260     double scale = currentScale;
2261     if (allowScaling) {
2262 #if PLATFORM(WATCHOS)
2263         const CGFloat minimumMarginForZoomingToEntireFocusRectInWebViewCoordinates = 10;
2264         const CGFloat maximumMarginForZoomingToEntireFocusRectInWebViewCoordinates = 35;
2265
2266         CGRect minimumTargetRectInDocumentCoordinates = UIRectInsetEdges(focusedElementRectInDocumentCoordinates, UIRectEdgeAll, -minimumMarginForZoomingToEntireFocusRectInWebViewCoordinates / currentScale);
2267         CGRect maximumTargetRectInDocumentCoordinates = UIRectInsetEdges(focusedElementRectInDocumentCoordinates, UIRectEdgeAll, -maximumMarginForZoomingToEntireFocusRectInWebViewCoordinates / currentScale);
2268
2269         double clampedMaximumTargetScale = clampTo<double>(std::min(visibleSize.width / CGRectGetWidth(minimumTargetRectInDocumentCoordinates), visibleSize.height / CGRectGetHeight(minimumTargetRectInDocumentCoordinates)), minimumScale, maximumScale);
2270         double clampedMinimumTargetScale = clampTo<double>(std::min(visibleSize.width / CGRectGetWidth(maximumTargetRectInDocumentCoordinates), visibleSize.height / CGRectGetHeight(maximumTargetRectInDocumentCoordinates)), minimumScale, maximumScale);
2271         scale = clampTo<double>(currentScale, clampedMinimumTargetScale, clampedMaximumTargetScale);
2272 #else
2273         const double webViewStandardFontSize = 16;
2274         scale = clampTo<double>(webViewStandardFontSize / fontSize, minimumScale, maximumScale);
2275 #endif
2276     }
2277
2278     CGFloat documentWidth = [_contentView bounds].size.width;
2279     scale = CGRound(documentWidth * scale) / documentWidth;
2280
2281     WebCore::FloatRect focusedElementRectInNewScale = focusedElementRectInDocumentCoordinates;
2282     focusedElementRectInNewScale.scale(scale);
2283     focusedElementRectInNewScale.moveBy([_contentView frame].origin);
2284
2285     BOOL selectionRectIsNotNull = !selectionRectInDocumentCoordinates.isZero();
2286     if (!forceScroll) {
2287         CGRect currentlyVisibleRegionInWebViewCoordinates;
2288         currentlyVisibleRegionInWebViewCoordinates.origin = unobscuredScrollViewRectInWebViewCoordinates.origin;
2289         currentlyVisibleRegionInWebViewCoordinates.origin.y += visibleOffsetFromTop;
2290         currentlyVisibleRegionInWebViewCoordinates.size = visibleSize;
2291
2292         // Don't bother scrolling if the entire node is already visible, whether or not we got a selectionRect.
2293         if (CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:focusedElementRectInDocumentCoordinates fromView:_contentView.get()]))
2294             return;
2295
2296         // Don't bother scrolling if we have a valid selectionRect and it is already visible.
2297         if (selectionRectIsNotNull && CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:selectionRectInDocumentCoordinates fromView:_contentView.get()]))
2298             return;
2299     }
2300
2301     // We want to center the focused element within the viewport, with as much spacing on all sides as
2302     // we can get based on the visible area after zooming. The spacing in either dimension is half the
2303     // difference between the size of the DOM node and the size of the visible frame.
2304     // If the element is too wide to be horizontally centered or too tall to be vertically centered, we
2305     // instead scroll such that the left edge or top edge of the element is within the left half or top
2306     // half of the viewport, respectively.
2307     CGFloat horizontalSpaceInWebViewCoordinates = (visibleSize.width - focusedElementRectInNewScale.width()) / 2.0;
2308     CGFloat verticalSpaceInWebViewCoordinates = (visibleSize.height - focusedElementRectInNewScale.height()) / 2.0;
2309
2310     auto topLeft = CGPointZero;
2311     auto scrollViewInsets = [_scrollView _effectiveContentInset];
2312     auto currentTopLeft = [_scrollView contentOffset];
2313
2314     if (_haveSetObscuredInsets) {
2315         currentTopLeft.x += _obscuredInsets.left;
2316         currentTopLeft.y += _obscuredInsets.top;
2317     }
2318
2319     if (horizontalSpaceInWebViewCoordinates > 0)
2320         topLeft.x = focusedElementRectInNewScale.x() - horizontalSpaceInWebViewCoordinates;
2321     else {
2322         auto minimumOffsetToRevealLeftEdge = std::max(-scrollViewInsets.left, focusedElementRectInNewScale.x() - visibleSize.width / 2);
2323         auto maximumOffsetToRevealLeftEdge = focusedElementRectInNewScale.x();
2324         topLeft.x = clampTo<double>(currentTopLeft.x, minimumOffsetToRevealLeftEdge, maximumOffsetToRevealLeftEdge);
2325     }
2326
2327     if (verticalSpaceInWebViewCoordinates > 0)
2328         topLeft.y = focusedElementRectInNewScale.y() - verticalSpaceInWebViewCoordinates;
2329     else {
2330         auto minimumOffsetToRevealTopEdge = std::max(-scrollViewInsets.top, focusedElementRectInNewScale.y() - visibleSize.height / 2);
2331         auto maximumOffsetToRevealTopEdge = focusedElementRectInNewScale.y();
2332         topLeft.y = clampTo<double>(currentTopLeft.y, minimumOffsetToRevealTopEdge, maximumOffsetToRevealTopEdge);
2333     }
2334
2335     topLeft.y -= visibleOffsetFromTop;
2336
2337     WebCore::FloatRect documentBoundsInNewScale = [_contentView bounds];
2338     documentBoundsInNewScale.scale(scale);
2339     documentBoundsInNewScale.moveBy([_contentView frame].origin);
2340
2341     CGFloat minimumAllowableHorizontalOffsetInWebViewCoordinates = -INFINITY;
2342     CGFloat minimumAllowableVerticalOffsetInWebViewCoordinates = -INFINITY;
2343     CGFloat maximumAllowableHorizontalOffsetInWebViewCoordinates = CGRectGetMaxX(documentBoundsInNewScale) - visibleSize.width;
2344     CGFloat maximumAllowableVerticalOffsetInWebViewCoordinates = CGRectGetMaxY(documentBoundsInNewScale) - visibleSize.height;
2345
2346     if (selectionRectIsNotNull) {
2347         WebCore::FloatRect selectionRectInNewScale = selectionRectInDocumentCoordinates;
2348         selectionRectInNewScale.scale(scale);
2349         selectionRectInNewScale.moveBy([_contentView frame].origin);
2350         // Adjust the min and max allowable scroll offsets, such that the selection rect remains visible.
2351         minimumAllowableHorizontalOffsetInWebViewCoordinates = CGRectGetMaxX(selectionRectInNewScale) + caretOffsetFromWindowEdge - visibleSize.width;
2352         minimumAllowableVerticalOffsetInWebViewCoordinates = CGRectGetMaxY(selectionRectInNewScale) + caretOffsetFromWindowEdge - visibleSize.height - visibleOffsetFromTop;
2353         maximumAllowableHorizontalOffsetInWebViewCoordinates = std::min<CGFloat>(maximumAllowableHorizontalOffsetInWebViewCoordinates, CGRectGetMinX(selectionRectInNewScale) - caretOffsetFromWindowEdge);
2354         maximumAllowableVerticalOffsetInWebViewCoordinates = std::min<CGFloat>(maximumAllowableVerticalOffsetInWebViewCoordinates, CGRectGetMinY(selectionRectInNewScale) - caretOffsetFromWindowEdge - visibleOffsetFromTop);
2355     }
2356
2357     // Constrain the left edge in document coordinates so that:
2358     //  - it isn't so small that the scrollVisibleRect isn't visible on the screen
2359     //  - it isn't so great that the document's right edge is less than the right edge of the screen
2360     topLeft.x = clampTo<CGFloat>(topLeft.x, minimumAllowableHorizontalOffsetInWebViewCoordinates, maximumAllowableHorizontalOffsetInWebViewCoordinates);
2361
2362     // Constrain the top edge in document coordinates so that:
2363     //  - it isn't so small that the scrollVisibleRect isn't visible on the screen
2364     //  - it isn't so great that the document's bottom edge is higher than the top of the form assistant
2365     topLeft.y = clampTo<CGFloat>(topLeft.y, minimumAllowableVerticalOffsetInWebViewCoordinates, maximumAllowableVerticalOffsetInWebViewCoordinates);
2366
2367     if (_haveSetObscuredInsets) {
2368         // This looks unintuitive, but is necessary in order to precisely center the focused element in the visible area.
2369         // The top left position already accounts for top and left obscured insets - i.e., a topLeft of (0, 0) corresponds
2370         // to the top- and left-most point below (and to the right of) the top inset area and left inset areas, respectively.
2371         // However, when telling WKScrollView to scroll to a given center position, this center position is computed relative
2372         // to the coordinate space of the scroll view. Thus, to compute our center position from the top left position, we
2373         // need to first move the top left position up and to the left, and then add half the width and height of the content
2374         // area (including obscured insets).
2375         topLeft.x -= _obscuredInsets.left;
2376         topLeft.y -= _obscuredInsets.top;
2377     }
2378
2379     WebCore::FloatPoint newCenter = CGPointMake(topLeft.x + CGRectGetWidth(self.bounds) / 2, topLeft.y + CGRectGetHeight(self.bounds) / 2);
2380
2381     if (scale != currentScale)
2382         _page->willStartUserTriggeredZooming();
2383
2384     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToFocusRect: zooming to " << newCenter << " scale:" << scale);
2385
2386     // The newCenter has been computed in the new scale, but _zoomToCenter expected the center to be in the original scale.
2387     newCenter.scale(1 / scale);
2388     [_scrollView _zoomToCenter:newCenter scale:scale duration:formControlZoomAnimationDuration force:YES];
2389 }
2390
2391 - (CGFloat)_targetContentZoomScaleForRect:(const WebCore::FloatRect&)targetRect currentScale:(double)currentScale fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale
2392 {
2393     WebCore::FloatSize unobscuredContentSize([self _contentRectForUserInteraction].size);
2394     double horizontalScale = unobscuredContentSize.width() * currentScale / targetRect.width();
2395     double verticalScale = unobscuredContentSize.height() * currentScale / targetRect.height();
2396
2397     horizontalScale = std::min(std::max(horizontalScale, minimumScale), maximumScale);
2398     verticalScale = std::min(std::max(verticalScale, minimumScale), maximumScale);
2399
2400     return fitEntireRect ? std::min(horizontalScale, verticalScale) : horizontalScale;
2401 }
2402
2403 - (BOOL)_zoomToRect:(WebCore::FloatRect)targetRect withOrigin:(WebCore::FloatPoint)origin fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale minimumScrollDistance:(float)minimumScrollDistance
2404 {
2405     const float maximumScaleFactorDeltaForPanScroll = 0.02;
2406
2407     double currentScale = contentZoomScale(self);
2408     double targetScale = [self _targetContentZoomScaleForRect:targetRect currentScale:currentScale fitEntireRect:fitEntireRect minimumScale:minimumScale maximumScale:maximumScale];
2409
2410     if (fabs(targetScale - currentScale) < maximumScaleFactorDeltaForPanScroll) {
2411         if ([self _scrollToRect:targetRect origin:origin minimumScrollDistance:minimumScrollDistance])
2412             return true;
2413     } else if (targetScale != currentScale) {
2414         [self _zoomToRect:targetRect atScale:targetScale origin:origin animated:YES];
2415         return true;
2416     }
2417
2418     return false;
2419 }
2420
2421 - (void)didMoveToWindow
2422 {
2423     _page->activityStateDidChange(WebCore::ActivityState::allFlags());
2424 }
2425
2426 - (void)setOpaque:(BOOL)opaque
2427 {
2428     BOOL oldOpaque = self.opaque;
2429
2430     [super setOpaque:opaque];
2431     [_contentView setOpaque:opaque];
2432
2433     if (oldOpaque == opaque)
2434         return;
2435
2436     if (!_page)
2437         return;
2438
2439     _page->setDrawsBackground(opaque);
2440     [self _updateScrollViewBackground];
2441 }
2442
2443 - (void)setBackgroundColor:(UIColor *)backgroundColor
2444 {
2445     [super setBackgroundColor:backgroundColor];
2446     [_contentView setBackgroundColor:backgroundColor];
2447 }
2448
2449 - (BOOL)_allowsDoubleTapGestures
2450 {
2451     if (_fastClickingIsDisabled)
2452         return YES;
2453
2454     // If the page is not user scalable, we don't allow double tap gestures.
2455     if (![_scrollView isZoomEnabled] || [_scrollView minimumZoomScale] >= [_scrollView maximumZoomScale])
2456         return NO;
2457
2458     // If the viewport width was not explicit, we allow double tap gestures.
2459     if (!_viewportMetaTagWidthWasExplicit || _viewportMetaTagCameFromImageDocument)
2460         return YES;
2461
2462     // If the page set a viewport width that wasn't the device width, then it was
2463     // scaled and thus will probably need to zoom.
2464     if (_viewportMetaTagWidth != WebCore::ViewportArguments::ValueDeviceWidth)
2465         return YES;
2466
2467     // At this point, we have a page that asked for width = device-width. However,
2468     // if the content's width and height were large, we might have had to shrink it.
2469     // Since we'll enable double tap zoom whenever we're not at the actual
2470     // initial scale, this simply becomes a test of the current scale against 1.
2471     return !areEssentiallyEqualAsFloat(contentZoomScale(self), 1);
2472 }
2473
2474 - (BOOL)_stylusTapGestureShouldCreateEditableImage
2475 {
2476     return [_configuration _editableImagesEnabled];
2477 }
2478
2479 #pragma mark - UIScrollViewDelegate
2480
2481 - (BOOL)usesStandardContentView
2482 {
2483     return !_customContentView && !_passwordView;
2484 }
2485
2486 - (CGSize)scrollView:(UIScrollView*)scrollView contentSizeForZoomScale:(CGFloat)scale withProposedSize:(CGSize)proposedSize
2487 {
2488     return roundScrollViewContentSize(*_page, proposedSize);
2489 }
2490
2491 - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
2492 {
2493     ASSERT(_scrollView == scrollView);
2494     return self._currentContentView;
2495 }
2496
2497 - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
2498 {
2499     if (![self usesStandardContentView]) {
2500         if ([_customContentView respondsToSelector:@selector(web_scrollViewWillBeginZooming:withView:)])
2501             [_customContentView web_scrollViewWillBeginZooming:scrollView withView:view];
2502         return;
2503     }
2504
2505     if (scrollView.pinchGestureRecognizer.state == UIGestureRecognizerStateBegan) {
2506         _page->willStartUserTriggeredZooming();
2507         [_contentView scrollViewWillStartPanOrPinchGesture];
2508     }
2509     [_contentView willStartZoomOrScroll];
2510 }
2511
2512 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
2513 {
2514     if (![self usesStandardContentView])
2515         return;
2516
2517     if (scrollView.panGestureRecognizer.state == UIGestureRecognizerStateBegan)
2518         [_contentView scrollViewWillStartPanOrPinchGesture];
2519
2520     [_contentView willStartZoomOrScroll];
2521 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2522     // FIXME: We will want to detect whether snapping will occur before beginning to drag. See WebPageProxy::didCommitLayerTree.
2523     WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2524     ASSERT(scrollView == _scrollView.get());
2525     CGFloat scrollDecelerationFactor = (coordinator && coordinator->shouldSetScrollViewDecelerationRateFast()) ? UIScrollViewDecelerationRateFast : UIScrollViewDecelerationRateNormal;
2526     scrollView.horizontalScrollDecelerationFactor = scrollDecelerationFactor;
2527     scrollView.verticalScrollDecelerationFactor = scrollDecelerationFactor;
2528 #endif
2529 }
2530
2531 - (void)_didFinishScrolling
2532 {
2533     if (![self usesStandardContentView])
2534         return;
2535
2536     [self _scheduleVisibleContentRectUpdate];
2537     [_contentView didFinishScrolling];
2538 }
2539
2540 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
2541 {
2542     // Work around <rdar://problem/16374753> by avoiding deceleration while
2543     // zooming. We'll animate to the right place once the zoom finishes.
2544     if ([scrollView isZooming])
2545         *targetContentOffset = [scrollView contentOffset];
2546 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2547     if (WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy()) {
2548         // FIXME: Here, I'm finding the maximum horizontal/vertical scroll offsets. There's probably a better way to do this.
2549         CGSize maxScrollOffsets = CGSizeMake(scrollView.contentSize.width - scrollView.bounds.size.width, scrollView.contentSize.height - scrollView.bounds.size.height);
2550
2551         UIEdgeInsets obscuredInset;
2552
2553         id<WKUIDelegatePrivate> uiDelegatePrivate = static_cast<id <WKUIDelegatePrivate>>([self UIDelegate]);
2554         if ([uiDelegatePrivate respondsToSelector:@selector(_webView:finalObscuredInsetsForScrollView:withVelocity:targetContentOffset:)])
2555             obscuredInset = [uiDelegatePrivate _webView:self finalObscuredInsetsForScrollView:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
2556         else
2557             obscuredInset = [self _computedObscuredInset];
2558
2559         CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInset);
2560
2561         coordinator->adjustTargetContentOffsetForSnapping(maxScrollOffsets, velocity, unobscuredRect.origin.y, targetContentOffset);
2562     }
2563 #endif
2564 }
2565
2566 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
2567 {
2568     // If we're decelerating, scroll offset will be updated when scrollViewDidFinishDecelerating: is called.
2569     if (!decelerate)
2570         [self _didFinishScrolling];
2571 }
2572
2573 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
2574 {
2575     [self _didFinishScrolling];
2576 }
2577
2578 - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
2579 {
2580     [self _didFinishScrolling];
2581 }
2582
2583 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
2584 {
2585     if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidScroll:)])
2586         [_customContentView web_scrollViewDidScroll:(UIScrollView *)scrollView];
2587
2588     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2589
2590     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
2591         scrollPerfData->didScroll([self visibleRectInViewCoordinates]);
2592 }
2593
2594 - (void)scrollViewDidZoom:(UIScrollView *)scrollView
2595 {
2596     if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidZoom:)])
2597         [_customContentView web_scrollViewDidZoom:scrollView];
2598
2599     [self _updateScrollViewBackground];
2600     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2601 }
2602
2603 - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
2604 {
2605     if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidEndZooming:withView:atScale:)])
2606         [_customContentView web_scrollViewDidEndZooming:scrollView withView:view atScale:scale];
2607
2608     ASSERT(scrollView == _scrollView);
2609     // FIXME: remove when rdar://problem/36065495 is fixed.
2610     // When rotating with two fingers down, UIScrollView can set a bogus content view position.
2611     // "Center" is top left because we set the anchorPoint to 0,0.
2612     [_contentView setCenter:self.bounds.origin];
2613
2614     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2615     [_contentView didZoomToScale:scale];
2616 }
2617
2618 - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
2619 {
2620     [self _didFinishScrolling];
2621 }
2622
2623 - (void)_scrollViewDidInterruptDecelerating:(UIScrollView *)scrollView
2624 {
2625     if (![self usesStandardContentView])
2626         return;
2627
2628     [_contentView didInterruptScrolling];
2629     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2630 }
2631
2632 - (UIView *)_enclosingViewForExposedRectComputation
2633 {
2634     return [self _scroller];
2635 }
2636
2637 - (CGRect)_visibleRectInEnclosingView:(UIView *)enclosingView
2638 {
2639     if (!enclosingView)
2640         return self.bounds;
2641
2642     CGRect exposedRect = [enclosingView convertRect:enclosingView.bounds toView:self];
2643     return CGRectIntersectsRect(exposedRect, self.bounds) ? CGRectIntersection(exposedRect, self.bounds) : CGRectZero;
2644 }
2645
2646 - (CGRect)_visibleContentRect
2647 {
2648     if (_frozenVisibleContentRect)
2649         return _frozenVisibleContentRect.value();
2650
2651     CGRect visibleRectInContentCoordinates = [self convertRect:self.bounds toView:_contentView.get()];
2652
2653     if (UIView *enclosingView = [self _enclosingViewForExposedRectComputation]) {
2654         CGRect viewVisibleRect = [self _visibleRectInEnclosingView:enclosingView];
2655         CGRect viewVisibleContentRect = [self convertRect:viewVisibleRect toView:_contentView.get()];
2656         visibleRectInContentCoordinates = CGRectIntersection(visibleRectInContentCoordinates, viewVisibleContentRect);
2657     }
2658
2659     return visibleRectInContentCoordinates;
2660 }
2661
2662 // Called when some ancestor UIScrollView scrolls.
2663 - (void)_didScroll
2664 {
2665     [self _scheduleVisibleContentRectUpdateAfterScrollInView:[self _scroller]];
2666
2667     const NSTimeInterval ScrollingEndedTimerInterval = 0.032;
2668     if (!_enclosingScrollViewScrollTimer) {
2669         _enclosingScrollViewScrollTimer = adoptNS([[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:ScrollingEndedTimerInterval]
2670             interval:0 target:self selector:@selector(_enclosingScrollerScrollingEnded:) userInfo:nil repeats:YES]);
2671         [[NSRunLoop mainRunLoop] addTimer:_enclosingScrollViewScrollTimer.get() forMode:NSDefaultRunLoopMode];
2672     }
2673     _didScrollSinceLastTimerFire = YES;
2674 }
2675
2676 - (void)_enclosingScrollerScrollingEnded:(NSTimer *)timer
2677 {
2678     if (_didScrollSinceLastTimerFire) {
2679         _didScrollSinceLastTimerFire = NO;
2680         return;
2681     }
2682
2683     [self _scheduleVisibleContentRectUpdate];
2684     [_enclosingScrollViewScrollTimer invalidate];
2685     _enclosingScrollViewScrollTimer = nil;
2686 }
2687
2688 - (UIEdgeInsets)_scrollViewSystemContentInset
2689 {
2690     // It's not safe to access the scroll view's safeAreaInsets or _systemContentInset from
2691     // inside our layoutSubviews implementation, because they aren't updated until afterwards.
2692     // Instead, depend on the fact that the UIScrollView and WKWebView are in the same coordinate
2693     // space, and map the WKWebView's own insets into the scroll view manually.
2694     return UIEdgeInsetsAdd([_scrollView _contentScrollInset], self.safeAreaInsets, [_scrollView _edgesApplyingSafeAreaInsetsToContentInset]);
2695 }
2696
2697 - (WebCore::FloatSize)activeViewLayoutSize:(const CGRect&)bounds
2698 {
2699     if (_overridesViewLayoutSize)
2700         return WebCore::FloatSize(_viewLayoutSizeOverride);
2701
2702 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2703     return WebCore::FloatSize(UIEdgeInsetsInsetRect(CGRectMake(0, 0, bounds.size.width, bounds.size.height), self._scrollViewSystemContentInset).size);
2704 #else
2705     return WebCore::FloatSize { bounds.size };
2706 #endif
2707 }
2708
2709 - (void)_dispatchSetViewLayoutSize:(WebCore::FloatSize)viewLayoutSize
2710 {
2711     if (_lastSentViewLayoutSize && CGSizeEqualToSize(_lastSentViewLayoutSize.value(), viewLayoutSize))
2712         return;
2713
2714     LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _dispatchSetViewLayoutSize:] " << viewLayoutSize << " contentZoomScale " << contentZoomScale(self));
2715     _page->setViewportConfigurationViewLayoutSize(viewLayoutSize, _page->layoutSizeScaleFactor(), _minimumEffectiveDeviceWidth);
2716     _lastSentViewLayoutSize = viewLayoutSize;
2717 }
2718
2719 - (void)_dispatchSetMaximumUnobscuredSize:(WebCore::FloatSize)maximumUnobscuredSize
2720 {
2721     if (_lastSentMaximumUnobscuredSize && CGSizeEqualToSize(_lastSentMaximumUnobscuredSize.value(), maximumUnobscuredSize))
2722         return;
2723
2724     _page->setMaximumUnobscuredSize(maximumUnobscuredSize);
2725     _lastSentMaximumUnobscuredSize = maximumUnobscuredSize;
2726 }
2727
2728 - (void)_dispatchSetDeviceOrientation:(int32_t)deviceOrientation
2729 {
2730     if (_lastSentDeviceOrientation && _lastSentDeviceOrientation.value() == deviceOrientation)
2731         return;
2732
2733     _page->setDeviceOrientation(deviceOrientation);
2734     _lastSentDeviceOrientation = deviceOrientation;
2735 }
2736
2737 - (void)_frameOrBoundsChanged
2738 {
2739     CGRect bounds = self.bounds;
2740     [_scrollView setFrame:bounds];
2741
2742     if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing) {
2743         if (!_overridesViewLayoutSize)
2744             [self _dispatchSetViewLayoutSize:[self activeViewLayoutSize:self.bounds]];
2745         if (!_overridesMaximumUnobscuredSize)
2746             [self _dispatchSetMaximumUnobscuredSize:WebCore::FloatSize(bounds.size)];
2747
2748         BOOL sizeChanged = NO;
2749         if (auto drawingArea = _page->drawingArea())
2750             sizeChanged = drawingArea->setSize(WebCore::IntSize(bounds.size));
2751
2752         if (sizeChanged & [self usesStandardContentView])
2753             [_contentView setSizeChangedSinceLastVisibleContentRectUpdate:YES];
2754     }
2755
2756     [_customContentView web_setMinimumSize:bounds.size];
2757     [self _scheduleVisibleContentRectUpdate];
2758 }
2759
2760 // 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.
2761 - (CGRect)_contentRectForUserInteraction
2762 {
2763     // FIXME: handle split keyboard.
2764     UIEdgeInsets obscuredInsets = _obscuredInsets;
2765     obscuredInsets.bottom = std::max(_obscuredInsets.bottom, _inputViewBounds.size.height);
2766     CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInsets);
2767     return [self convertRect:unobscuredRect toView:self._currentContentView];
2768 }
2769
2770 // Ideally UIScrollView would expose this for us: <rdar://problem/21394567>.
2771 - (BOOL)_scrollViewIsRubberBanding
2772 {
2773     float deviceScaleFactor = _page->deviceScaleFactor();
2774
2775     CGPoint contentOffset = [_scrollView contentOffset];
2776     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
2777     return !pointsEqualInDevicePixels(contentOffset, boundedOffset, deviceScaleFactor);
2778 }
2779
2780 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2781 - (void)safeAreaInsetsDidChange
2782 {
2783     [super safeAreaInsetsDidChange];
2784
2785     [self _scheduleVisibleContentRectUpdate];
2786 }
2787 #endif
2788
2789 - (void)_scheduleVisibleContentRectUpdate
2790 {
2791     // For visible rect updates not associated with a specific UIScrollView, just consider our own scroller.
2792     [self _scheduleVisibleContentRectUpdateAfterScrollInView:_scrollView.get()];
2793 }
2794
2795 - (BOOL)_scrollViewIsInStableState:(UIScrollView *)scrollView
2796 {
2797     BOOL isStableState = !([scrollView isDragging] || [scrollView isDecelerating] || [scrollView isZooming] || [scrollView _isAnimatingZoom] || [scrollView _isScrollingToTop]);
2798
2799     if (isStableState && scrollView == _scrollView.get())
2800         isStableState = !_isChangingObscuredInsetsInteractively;
2801
2802     if (isStableState && scrollView == _scrollView.get())
2803         isStableState = ![self _scrollViewIsRubberBanding];
2804
2805     if (isStableState)
2806         isStableState = !scrollView._isInterruptingDeceleration;
2807
2808     if (NSNumber *stableOverride = self._stableStateOverride)
2809         isStableState = stableOverride.boolValue;
2810
2811     return isStableState;
2812 }
2813
2814 - (void)_addUpdateVisibleContentRectPreCommitHandler
2815 {
2816     auto retainedSelf = retainPtr(self);
2817     [CATransaction addCommitHandler:[retainedSelf] {
2818         WKWebView *webView = retainedSelf.get();
2819         if (![webView _isValid]) {
2820             RELEASE_LOG_IF(webView._page && webView._page->isAlwaysOnLoggingAllowed(), ViewState, "In CATransaction preCommitHandler, WKWebView %p is invalid", webView);
2821             return;
2822         }
2823
2824         @try {
2825             [webView _updateVisibleContentRects];
2826         } @catch (NSException *exception) {
2827             RELEASE_LOG_IF(webView._page && webView._page->isAlwaysOnLoggingAllowed(), ViewState, "In CATransaction preCommitHandler, -[WKWebView %p _updateVisibleContentRects] threw an exception", webView);
2828         }
2829         webView->_hasScheduledVisibleRectUpdate = NO;
2830     } forPhase:kCATransactionPhasePreCommit];
2831 }
2832
2833 - (void)_scheduleVisibleContentRectUpdateAfterScrollInView:(UIScrollView *)scrollView
2834 {
2835     _visibleContentRectUpdateScheduledFromScrollViewInStableState = [self _scrollViewIsInStableState:scrollView];
2836
2837     if (_hasScheduledVisibleRectUpdate) {
2838         auto timeNow = MonotonicTime::now();
2839         if ((timeNow - _timeOfRequestForVisibleContentRectUpdate) > delayBeforeNoVisibleContentsRectsLogging) {
2840             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",
2841                 self, (timeNow - _timeOfRequestForVisibleContentRectUpdate).value(), (timeNow - _timeOfLastVisibleContentRectUpdate).value(), [self _isValid]);
2842         }
2843         return;
2844     }
2845
2846     _hasScheduledVisibleRectUpdate = YES;
2847     _timeOfRequestForVisibleContentRectUpdate = MonotonicTime::now();
2848
2849     CATransactionPhase transactionPhase = [CATransaction currentPhase];
2850     if (transactionPhase == kCATransactionPhaseNull || transactionPhase == kCATransactionPhasePreLayout) {
2851         [self _addUpdateVisibleContentRectPreCommitHandler];
2852         return;
2853     }
2854
2855     dispatch_async(dispatch_get_main_queue(), [retainedSelf = retainPtr(self)] {
2856         WKWebView *webView = retainedSelf.get();
2857         if (![webView _isValid])
2858             return;
2859         [webView _addUpdateVisibleContentRectPreCommitHandler];
2860     });
2861 }
2862
2863 static bool scrollViewCanScroll(UIScrollView *scrollView)
2864 {
2865     if (!scrollView)
2866         return NO;
2867
2868     UIEdgeInsets contentInset = scrollView.contentInset;
2869     CGSize contentSize = scrollView.contentSize;
2870     CGSize boundsSize = scrollView.bounds.size;
2871
2872     return (contentSize.width + contentInset.left + contentInset.right) > boundsSize.width
2873         || (contentSize.height + contentInset.top + contentInset.bottom) > boundsSize.height;
2874 }
2875
2876 - (CGRect)_contentBoundsExtendedForRubberbandingWithScale:(CGFloat)scaleFactor
2877 {
2878     CGPoint contentOffset = [_scrollView contentOffset];
2879     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
2880
2881     CGFloat horiontalRubberbandAmountInContentCoordinates = (contentOffset.x - boundedOffset.x) / scaleFactor;
2882     CGFloat verticalRubberbandAmountInContentCoordinates = (contentOffset.y - boundedOffset.y) / scaleFactor;
2883
2884     CGRect extendedBounds = [_contentView bounds];
2885
2886     if (horiontalRubberbandAmountInContentCoordinates < 0) {
2887         extendedBounds.origin.x += horiontalRubberbandAmountInContentCoordinates;
2888         extendedBounds.size.width -= horiontalRubberbandAmountInContentCoordinates;
2889     } else if (horiontalRubberbandAmountInContentCoordinates > 0)
2890         extendedBounds.size.width += horiontalRubberbandAmountInContentCoordinates;
2891
2892     if (verticalRubberbandAmountInContentCoordinates < 0) {
2893         extendedBounds.origin.y += verticalRubberbandAmountInContentCoordinates;
2894         extendedBounds.size.height -= verticalRubberbandAmountInContentCoordinates;
2895     } else if (verticalRubberbandAmountInContentCoordinates > 0)
2896         extendedBounds.size.height += verticalRubberbandAmountInContentCoordinates;
2897
2898     return extendedBounds;
2899 }
2900
2901 - (void)_updateVisibleContentRects
2902 {
2903     BOOL inStableState = _visibleContentRectUpdateScheduledFromScrollViewInStableState;
2904
2905     if (![self usesStandardContentView]) {
2906         [_passwordView setFrame:self.bounds];
2907         [_customContentView web_computedContentInsetDidChange];
2908         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] - usesStandardContentView is NO, bailing", self);
2909         return;
2910     }
2911
2912     if (_delayUpdateVisibleContentRects) {
2913         _hadDelayedUpdateVisibleContentRects = YES;
2914         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] - _delayUpdateVisibleContentRects is YES, bailing", self);
2915         return;
2916     }
2917
2918     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing
2919         || (_needsResetViewStateAfterCommitLoadForMainFrame && ![_contentView sizeChangedSinceLastVisibleContentRectUpdate])
2920         || [_scrollView isZoomBouncing]
2921         || _currentlyAdjustingScrollViewInsetsForKeyboard) {
2922         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)",
2923             self, _dynamicViewportUpdateMode, _needsResetViewStateAfterCommitLoadForMainFrame, [_contentView sizeChangedSinceLastVisibleContentRectUpdate], [_scrollView isZoomBouncing], _currentlyAdjustingScrollViewInsetsForKeyboard);
2924         return;
2925     }
2926
2927     CGRect visibleRectInContentCoordinates = [self _visibleContentRect];
2928
2929     UIEdgeInsets computedContentInsetUnadjustedForKeyboard = [self _computedObscuredInset];
2930     if (!_haveSetObscuredInsets)
2931         computedContentInsetUnadjustedForKeyboard.bottom -= _totalScrollViewBottomInsetAdjustmentForKeyboard;
2932
2933     CGFloat scaleFactor = contentZoomScale(self);
2934
2935     CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, computedContentInsetUnadjustedForKeyboard);
2936     CGRect unobscuredRectInContentCoordinates = _frozenUnobscuredContentRect ? _frozenUnobscuredContentRect.value() : [self convertRect:unobscuredRect toView:_contentView.get()];
2937     unobscuredRectInContentCoordinates = CGRectIntersection(unobscuredRectInContentCoordinates, [self _contentBoundsExtendedForRubberbandingWithScale:scaleFactor]);
2938
2939 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2940     if (inStableState) {
2941         WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2942         if (coordinator && coordinator->hasActiveSnapPoint()) {
2943             CGPoint currentPoint = [_scrollView contentOffset];
2944             CGPoint activePoint = coordinator->nearestActiveContentInsetAdjustedSnapPoint(unobscuredRect.origin.y, currentPoint);
2945
2946             if (!CGPointEqualToPoint(activePoint, currentPoint)) {
2947                 RetainPtr<WKScrollView> strongScrollView = _scrollView;
2948                 dispatch_async(dispatch_get_main_queue(), [strongScrollView, activePoint] {
2949                     [strongScrollView setContentOffset:activePoint animated:NO];
2950                 });
2951             }
2952         }
2953     }
2954 #endif
2955
2956     [_contentView didUpdateVisibleRect:visibleRectInContentCoordinates
2957         unobscuredRect:unobscuredRectInContentCoordinates
2958         unobscuredRectInScrollViewCoordinates:unobscuredRect
2959         obscuredInsets:_obscuredInsets
2960         unobscuredSafeAreaInsets:[self _computedUnobscuredSafeAreaInset]
2961         inputViewBounds:_inputViewBounds
2962         scale:scaleFactor minimumScale:[_scrollView minimumZoomScale]
2963         inStableState:inStableState
2964         isChangingObscuredInsetsInteractively:_isChangingObscuredInsetsInteractively
2965         enclosedInScrollableAncestorView:scrollViewCanScroll([self _scroller])];
2966
2967     while (!_visibleContentRectUpdateCallbacks.isEmpty()) {
2968         auto callback = _visibleContentRectUpdateCallbacks.takeLast();
2969         callback();
2970     }
2971     
2972     auto timeNow = MonotonicTime::now();
2973     if ((timeNow - _timeOfRequestForVisibleContentRectUpdate) > delayBeforeNoVisibleContentsRectsLogging)
2974         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] finally ran %.2fs after being scheduled", self, (timeNow - _timeOfRequestForVisibleContentRectUpdate).value());
2975
2976     _timeOfLastVisibleContentRectUpdate = timeNow;
2977 }
2978
2979 - (void)_didStartProvisionalLoadForMainFrame
2980 {
2981     if (_gestureController)
2982         _gestureController->didStartProvisionalLoadForMainFrame();
2983 }
2984
2985 static WebCore::FloatSize activeMaximumUnobscuredSize(WKWebView *webView, const CGRect& bounds)
2986 {
2987     return WebCore::FloatSize(webView->_overridesMaximumUnobscuredSize ? webView->_maximumUnobscuredSizeOverride : bounds.size);
2988 }
2989
2990 static int32_t activeOrientation(WKWebView *webView)
2991 {
2992     return webView->_overridesInterfaceOrientation ? deviceOrientationForUIInterfaceOrientation(webView->_interfaceOrientationOverride) : webView->_page->deviceOrientation();
2993 }
2994
2995 - (void)_cancelAnimatedResize
2996 {
2997     LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _cancelAnimatedResize:] " << " _dynamicViewportUpdateMode " << (int)_dynamicViewportUpdateMode);
2998     if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing)
2999         return;
3000
3001     if (!_customContentView) {
3002         if (_resizeAnimationView) {
3003             NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
3004             [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
3005             [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
3006             [_resizeAnimationView removeFromSuperview];
3007             _resizeAnimationView = nil;
3008         }
3009
3010         [_contentView setHidden:NO];
3011         _resizeAnimationTransformAdjustments = CATransform3DIdentity;
3012     }
3013
3014     _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
3015     [self _scheduleVisibleContentRectUpdate];
3016 }
3017
3018 - (void)_didCompleteAnimatedResize
3019 {
3020     if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing)
3021         return;
3022
3023     [_contentView setHidden:NO];
3024
3025     if (!_resizeAnimationView) {
3026         // Paranoia. If _resizeAnimationView is null we'll end up setting a zero scale on the content view.
3027         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didCompleteAnimatedResize:] - _resizeAnimationView is nil", self);
3028         [self _cancelAnimatedResize];
3029         return;
3030     }
3031
3032     NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
3033     [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
3034     [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
3035
3036     CALayer *contentLayer = [_contentView layer];
3037     CGFloat adjustmentScale = _resizeAnimationTransformAdjustments.m11;
3038     contentLayer.sublayerTransform = CATransform3DIdentity;
3039
3040     CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
3041     CATransform3D contentLayerTransform = contentLayer.transform;
3042     CGFloat currentScale = [[_resizeAnimationView layer] transform].m11 * contentLayerTransform.m11;
3043
3044     // We cannot use [UIScrollView setZoomScale:] directly because the UIScrollView delegate would get a callback with
3045     // an invalid contentOffset. The real content offset is only set below.
3046     // Since there is no public API for setting both the zoomScale and the contentOffset, we set the zoomScale manually
3047     // on the zoom layer and then only change the contentOffset.
3048     CGFloat adjustedScale = adjustmentScale * currentScale;
3049     contentLayerTransform.m11 = adjustedScale;
3050     contentLayerTransform.m22 = adjustedScale;
3051     contentLayer.transform = contentLayerTransform;
3052
3053     CGPoint currentScrollOffset = [_scrollView contentOffset];
3054     double horizontalScrollAdjustement = _resizeAnimationTransformAdjustments.m41 * animatingScaleTarget;
3055     double verticalScrollAdjustment = _resizeAnimationTransformAdjustments.m42 * animatingScaleTarget;
3056
3057     [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
3058     [_scrollView setContentOffset:CGPointMake(currentScrollOffset.x - horizontalScrollAdjustement, currentScrollOffset.y - verticalScrollAdjustment)];
3059
3060     [_resizeAnimationView removeFromSuperview];
3061     _resizeAnimationView = nil;
3062     _resizeAnimationTransformAdjustments = CATransform3DIdentity;
3063
3064     _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
3065     [self _scheduleVisibleContentRectUpdate];
3066
3067     CGRect newBounds = self.bounds;
3068     auto newViewLayoutSize = [self activeViewLayoutSize:newBounds];
3069     auto newMaximumUnobscuredSize = activeMaximumUnobscuredSize(self, newBounds);
3070     int32_t newOrientation = activeOrientation(self);
3071
3072     if (!_lastSentViewLayoutSize || newViewLayoutSize != _lastSentViewLayoutSize.value())
3073         [self _dispatchSetViewLayoutSize:newViewLayoutSize];
3074
3075     if (!_lastSentMaximumUnobscuredSize || newMaximumUnobscuredSize != _lastSentMaximumUnobscuredSize.value())
3076         [self _dispatchSetMaximumUnobscuredSize:WebCore::FloatSize(newMaximumUnobscuredSize)];
3077
3078     if (!_lastSentDeviceOrientation || newOrientation != _lastSentDeviceOrientation.value())
3079         [self _dispatchSetDeviceOrientation:newOrientation];
3080
3081     while (!_callbacksDeferredDuringResize.isEmpty())
3082         _callbacksDeferredDuringResize.takeLast()();
3083 }
3084
3085 - (void)_didFinishLoadForMainFrame
3086 {
3087     if (_gestureController)
3088         _gestureController->didFinishLoadForMainFrame();
3089 }
3090
3091 - (void)_didFailLoadForMainFrame
3092 {
3093     if (_gestureController)
3094         _gestureController->didFailLoadForMainFrame();
3095 }
3096
3097 - (void)_didSameDocumentNavigationForMainFrame:(WebKit::SameDocumentNavigationType)navigationType
3098 {
3099     [_customContentView web_didSameDocumentNavigation:toAPI(navigationType)];
3100
3101     if (_gestureController)
3102         _gestureController->didSameDocumentNavigationForMainFrame(navigationType);
3103 }
3104
3105 - (void)_keyboardChangedWithInfo:(NSDictionary *)keyboardInfo adjustScrollView:(BOOL)adjustScrollView
3106 {
3107     NSValue *endFrameValue = [keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
3108     if (!endFrameValue)
3109         return;
3110
3111     // The keyboard rect is always in screen coordinates. In the view services case the window does not
3112     // have the interface orientation rotation transformation; its host does. So, it makes no sense to
3113     // clip the keyboard rect against its screen.
3114     if ([[self window] _isHostedInAnotherProcess])
3115         _inputViewBounds = [self.window convertRect:[endFrameValue CGRectValue] fromWindow:nil];
3116     else
3117         _inputViewBounds = [self.window convertRect:CGRectIntersection([endFrameValue CGRectValue], self.window.screen.bounds) fromWindow:nil];
3118
3119     if (adjustScrollView) {
3120         CGFloat bottomInsetBeforeAdjustment = [_scrollView contentInset].bottom;
3121         SetForScope<BOOL> insetAdjustmentGuard(_currentlyAdjustingScrollViewInsetsForKeyboard, YES);
3122         [_scrollView _adjustForAutomaticKeyboardInfo:keyboardInfo animated:YES lastAdjustment:&_lastAdjustmentForScroller];
3123         CGFloat bottomInsetAfterAdjustment = [_scrollView contentInset].bottom;
3124         if (bottomInsetBeforeAdjustment != bottomInsetAfterAdjustment)
3125             _totalScrollViewBottomInsetAdjustmentForKeyboard += bottomInsetAfterAdjustment - bottomInsetBeforeAdjustment;
3126     }
3127
3128     [self _scheduleVisibleContentRectUpdate];
3129 }
3130
3131 - (BOOL)_shouldUpdateKeyboardWithInfo:(NSDictionary *)keyboardInfo
3132 {
3133     if ([_contentView isFocusingElement])
3134         return YES;
3135
3136     NSNumber *isLocalKeyboard = [keyboardInfo valueForKey:UIKeyboardIsLocalUserInfoKey];
3137     return isLocalKeyboard && !isLocalKeyboard.boolValue;
3138 }
3139
3140 - (void)_keyboardWillChangeFrame:(NSNotification *)notification
3141 {
3142     if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
3143         [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
3144 }
3145
3146 - (void)_keyboardDidChangeFrame:(NSNotification *)notification
3147 {
3148     [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:NO];
3149 }
3150
3151 - (void)_keyboardWillShow:(NSNotification *)notification
3152 {
3153     if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
3154         [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
3155
3156     _page->setIsKeyboardAnimatingIn(true);
3157 }
3158
3159 - (void)_keyboardDidShow:(NSNotification *)notification
3160 {
3161     _page->setIsKeyboardAnimatingIn(false);
3162 }
3163
3164 - (void)_keyboardWillHide:(NSNotification *)notification
3165 {
3166     // Ignore keyboard will hide notifications sent during rotation. They're just there for
3167     // backwards compatibility reasons and processing the will hide notification would
3168     // temporarily screw up the unobscured view area.
3169     if ([[UIPeripheralHost sharedInstance] rotationState])
3170         return;
3171
3172     [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
3173 }
3174
3175 static void hardwareKeyboardAvailabilityChangedCallback(CFNotificationCenterRef, void* observer, CFStringRef, const void*, CFDictionaryRef)
3176 {
3177     ASSERT(observer);
3178     WKWebView *webView = (__bridge WKWebView *)observer;
3179     webView._page->hardwareKeyboardAvailabilityChanged();
3180 }
3181
3182 - (void)_windowDidRotate:(NSNotification *)notification
3183 {
3184     if (!_overridesInterfaceOrientation)
3185         [self _dispatchSetDeviceOrientation:deviceOrientation()];
3186 }
3187
3188 - (void)_contentSizeCategoryDidChange:(NSNotification *)notification
3189 {
3190     _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
3191 }
3192
3193 - (NSString *)_contentSizeCategory
3194 {
3195     return [[UIApplication sharedApplication] preferredContentSizeCategory];
3196 }
3197
3198 - (void)_accessibilitySettingsDidChange:(NSNotification *)notification
3199 {
3200     _page->accessibilitySettingsDidChange();
3201 }
3202
3203 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
3204 {
3205     if (_allowsBackForwardNavigationGestures == allowsBackForwardNavigationGestures)
3206         return;
3207
3208     _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
3209
3210     if (allowsBackForwardNavigationGestures && !_gestureController) {
3211         _gestureController = std::make_unique<WebKit::ViewGestureController>(*_page);
3212         _gestureController->installSwipeHandler(self, [self scrollView]);
3213         if (WKWebView *alternateWebView = [_configuration _alternateWebViewForNavigationGestures])
3214             _gestureController->setAlternateBackForwardListSourcePage(alternateWebView->_page.get());
3215     }
3216
3217     if (_gestureController)
3218         _gestureController->setSwipeGestureEnabled(allowsBackForwardNavigationGestures);
3219
3220     _page->setShouldRecordNavigationSnapshots(allowsBackForwardNavigationGestures);
3221 }
3222
3223 - (BOOL)allowsBackForwardNavigationGestures
3224 {
3225     return _allowsBackForwardNavigationGestures;
3226 }
3227
3228 - (BOOL)_isNavigationSwipeGestureRecognizer:(UIGestureRecognizer *)recognizer
3229 {
3230     if (!_gestureController)
3231         return NO;
3232     return _gestureController->isNavigationSwipeGestureRecognizer(recognizer);
3233 }
3234
3235 - (void)_navigationGestureDidBegin
3236 {
3237     // During a back/forward swipe, there's a view interposed between this view and the content view that has
3238     // an offset and animation on it, which results in computing incorrect rectangles. Work around by using
3239     // frozen rects during swipes.
3240     CGRect fullViewRect = self.bounds;
3241     CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, [self _computedObscuredInset]);
3242
3243     _frozenVisibleContentRect = [self convertRect:fullViewRect toView:_contentView.get()];
3244     _frozenUnobscuredContentRect = [self convertRect:unobscuredRect toView:_contentView.get()];
3245
3246     LOG_WITH_STREAM(VisibleRects, stream << "_navigationGestureDidBegin: freezing visibleContentRect " << WebCore::FloatRect(_frozenVisibleContentRect.value()) << " UnobscuredContentRect " << WebCore::FloatRect(_frozenUnobscuredContentRect.value()));
3247 }
3248
3249 - (void)_navigationGestureDidEnd
3250 {
3251     _frozenVisibleContentRect = WTF::nullopt;
3252     _frozenUnobscuredContentRect = WTF::nullopt;
3253 }
3254
3255 - (void)_showPasswordViewWithDocumentName:(NSString *)documentName passwordHandler:(void (^)(NSString *))passwordHandler
3256 {
3257     ASSERT(!_passwordView);
3258     _passwordView = adoptNS([[WKPasswordView alloc] initWithFrame:self.bounds documentName:documentName]);
3259     [_passwordView setUserDidEnterPassword:passwordHandler];
3260     [_passwordView showInScrollView:_scrollView.get()];
3261     self._currentContentView.hidden = YES;
3262 }
3263
3264 - (void)_hidePasswordView
3265 {
3266     if (!_passwordView)
3267         return;
3268
3269     self._currentContentView.hidden = NO;
3270     [_passwordView hide];
3271     _passwordView = nil;
3272 }
3273
3274 - (WKPasswordView *)_passwordView
3275 {
3276     return _passwordView.get();
3277 }
3278
3279 - (void)_updateScrollViewInsetAdjustmentBehavior
3280 {
3281 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
3282     if (![_scrollView _contentInsetAdjustmentBehaviorWasExternallyOverridden])
3283         [_scrollView _setContentInsetAdjustmentBehaviorInternal:self._safeAreaShouldAffectObscuredInsets ? UIScrollViewContentInsetAdjustmentAlways : UIScrollViewContentInsetAdjustmentNever];
3284 #endif
3285 }
3286
3287 - (void)_setAvoidsUnsafeArea:(BOOL)avoidsUnsafeArea
3288 {
3289     if (_avoidsUnsafeArea == avoidsUnsafeArea)
3290         return;
3291
3292     _avoidsUnsafeArea = avoidsUnsafeArea;
3293
3294     [self _updateScrollViewInsetAdjustmentBehavior];
3295     [self _scheduleVisibleContentRectUpdate];
3296
3297     id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)[self UIDelegate];
3298     if ([uiDelegate respondsToSelector:@selector(_webView:didChangeSafeAreaShouldAffectObscuredInsets:)])
3299         [uiDelegate _webView:self didChangeSafeAreaShouldAffectObscuredInsets:avoidsUnsafeArea];
3300 }
3301
3302 - (BOOL)_haveSetObscuredInsets
3303 {
3304     return _haveSetObscuredInsets;
3305 }
3306
3307 #endif // PLATFORM(IOS_FAMILY)
3308
3309 #if ENABLE(ACCESSIBILITY_EVENTS)
3310
3311 static void accessibilityEventsEnabledChangedCallback(CFNotificationCenterRef, void* observer, CFStringRef, const void*, CFDictionaryRef)
3312 {
3313     ASSERT(observer);
3314     WKWebView *webview = (__bridge WKWebView *)observer;
3315     [webview _updateAccessibilityEventsEnabled];
3316 }
3317
3318 - (void)_updateAccessibilityEventsEnabled
3319 {
3320     if (!isNullFunctionPointer(_AXSWebAccessibilityEventsEnabled))
3321         _page->updateAccessibilityEventsEnabled(_AXSWebAccessibilityEventsEnabled());
3322 }
3323
3324 #endif
3325
3326 #pragma mark OS X-specific methods
3327
3328 #if PLATFORM(MAC)
3329
3330 - (BOOL)acceptsFirstResponder
3331 {
3332     return _impl->acceptsFirstResponder();
3333 }
3334
3335 - (BOOL)becomeFirstResponder
3336 {
3337     return _impl->becomeFirstResponder();
3338 }
3339
3340 - (BOOL)resignFirstResponder
3341 {
3342     return _impl->resignFirstResponder();
3343 }
3344
3345 - (void)viewWillStartLiveResize
3346 {
3347     _impl->viewWillStartLiveResize();
3348 }
3349
3350 - (void)viewDidEndLiveResize
3351 {
3352     _impl->viewDidEndLiveResize();
3353 }
3354
3355 - (BOOL)isFlipped
3356 {
3357     return YES;
3358 }
3359
3360 - (NSSize)intrinsicContentSize
3361 {
3362     return NSSizeFromCGSize(_impl->intrinsicContentSize());
3363 }
3364
3365 - (void)prepareContentInRect:(NSRect)rect
3366 {
3367     _impl->prepareContentInRect(NSRectToCGRect(rect));
3368 }
3369
3370 - (void)setFrameSize:(NSSize)size
3371 {
3372     [super setFrameSize:size];
3373     [_safeBrowsingWarning setFrame:self.bounds];
3374     _impl->setFrameSize(NSSizeToCGSize(size));
3375 }
3376
3377 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
3378 - (void)renewGState
3379 IGNORE_WARNINGS_END
3380 {
3381     _impl->renewGState();
3382     [super renewGState];
3383 }
3384
3385 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _impl->executeEditCommandForSelector(_cmd); }
3386
3387 WEBCORE_COMMAND(alignCenter)
3388 WEBCORE_COMMAND(alignJustified)
3389 WEBCORE_COMMAND(alignLeft)
3390 WEBCORE_COMMAND(alignRight)
3391 WEBCORE_COMMAND(copy)
3392 WEBCORE_COMMAND(cut)
3393 WEBCORE_COMMAND(delete)
3394 WEBCORE_COMMAND(deleteBackward)
3395 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
3396 WEBCORE_COMMAND(deleteForward)
3397 WEBCORE_COMMAND(deleteToBeginningOfLine)
3398 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
3399 WEBCORE_COMMAND(deleteToEndOfLine)
3400 WEBCORE_COMMAND(deleteToEndOfParagraph)
3401 WEBCORE_COMMAND(deleteToMark)
3402 WEBCORE_COMMAND(deleteWordBackward)
3403 WEBCORE_COMMAND(deleteWordForward)
3404 WEBCORE_COMMAND(ignoreSpelling)
3405 WEBCORE_COMMAND(indent)
3406 WEBCORE_COMMAND(insertBacktab)
3407 WEBCORE_COMMAND(insertLineBreak)
3408 WEBCORE_COMMAND(insertNewline)
3409 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
3410 WEBCORE_COMMAND(insertParagraphSeparator)
3411 WEBCORE_COMMAND(insertTab)
3412 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
3413 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
3414 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
3415 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
3416 WEBCORE_COMMAND(moveBackward)
3417 WEBCORE_COMMAND(moveBackwardAndModifySelection)
3418 WEBCORE_COMMAND(moveDown)
3419 WEBCORE_COMMAND(moveDownAndModifySelection)
3420 WEBCORE_COMMAND(moveForward)
3421 WEBCORE_COMMAND(moveForwardAndModifySelection)
3422 WEBCORE_COMMAND(moveLeft)
3423 WEBCORE_COMMAND(moveLeftAndModifySelection)
3424 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
3425 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
3426 WEBCORE_COMMAND(moveRight)
3427 WEBCORE_COMMAND(moveRightAndModifySelection)
3428 WEBCORE_COMMAND(moveToBeginningOfDocument)
3429 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
3430 WEBCORE_COMMAND(moveToBeginningOfLine)
3431 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
3432 WEBCORE_COMMAND(moveToBeginningOfParagraph)
3433 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
3434 WEBCORE_COMMAND(moveToBeginningOfSentence)
3435 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
3436 WEBCORE_COMMAND(moveToEndOfDocument)
3437 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
3438 WEBCORE_COMMAND(moveToEndOfLine)
3439 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
3440 WEBCORE_COMMAND(moveToEndOfParagraph)
3441 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
3442 WEBCORE_COMMAND(moveToEndOfSentence)
3443 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
3444 WEBCORE_COMMAND(moveToLeftEndOfLine)
3445 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
3446 WEBCORE_COMMAND(moveToRightEndOfLine)
3447 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
3448 WEBCORE_COMMAND(moveUp)
3449 WEBCORE_COMMAND(moveUpAndModifySelection)
3450 WEBCORE_COMMAND(moveWordBackward)
3451 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
3452 WEBCORE_COMMAND(moveWordForward)
3453 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
3454 WEBCORE_COMMAND(moveWordLeft)
3455 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
3456 WEBCORE_COMMAND(moveWordRight)
3457 WEBCORE_COMMAND(moveWordRightAndModifySelection)
3458 WEBCORE_COMMAND(outdent)
3459 WEBCORE_COMMAND(pageDown)
3460 WEBCORE_COMMAND(pageDownAndModifySelection)
3461 WEBCORE_COMMAND(pageUp)
3462 WEBCORE_COMMAND(pageUpAndModifySelection)
3463 WEBCORE_COMMAND(paste)
3464 WEBCORE_COMMAND(pasteAsPlainText)
3465 WEBCORE_COMMAND(scrollPageDown)
3466 WEBCORE_COMMAND(scrollPageUp)
3467 WEBCORE_COMMAND(scrollLineDown)
3468 WEBCORE_COMMAND(scrollLineUp)
3469 WEBCORE_COMMAND(scrollToBeginningOfDocument)
3470 WEBCORE_COMMAND(scrollToEndOfDocument)
3471 WEBCORE_COMMAND(selectAll)
3472 WEBCORE_COMMAND(selectLine)
3473 WEBCORE_COMMAND(selectParagraph)
3474 WEBCORE_COMMAND(selectSentence)
3475 WEBCORE_COMMAND(selectToMark)
3476 WEBCORE_COMMAND(selectWord)
3477 WEBCORE_COMMAND(setMark)
3478 WEBCORE_COMMAND(subscript)
3479 WEBCORE_COMMAND(superscript)
3480 WEBCORE_COMMAND(swapWithMark)
3481 WEBCORE_COMMAND(takeFindStringFromSelection)
3482 WEBCORE_COMMAND(transpose)
3483 WEBCORE_COMMAND(underline)
3484 WEBCORE_COMMAND(unscript)
3485 WEBCORE_COMMAND(yank)
3486 WEBCORE_COMMAND(yankAndSelect)
3487
3488 #undef WEBCORE_COMMAND
3489
3490 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
3491 {
3492     return _impl->writeSelectionToPasteboard(pasteboard, types);
3493 }
3494
3495 - (void)centerSelectionInVisibleArea:(id)sender
3496 {
3497     _impl->centerSelectionInVisibleArea();
3498 }
3499
3500 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
3501 {
3502     return _impl->validRequestorForSendAndReturnTypes(sendType, returnType);
3503 }
3504
3505 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
3506 {
3507     return _impl->readSelectionFromPasteboard(pasteboard);
3508 }
3509
3510 - (void)changeFont:(id)sender
3511 {
3512     _impl->changeFontFromFontManager();
3513 }
3514
3515 - (void)changeColor:(id)sender
3516 {
3517     _impl->changeFontColorFromSender(sender);
3518 }
3519
3520 - (void)changeAttributes:(id)sender
3521 {
3522     _impl->changeFontAttributesFromSender(sender);
3523 }
3524
3525 - (IBAction)startSpeaking:(id)sender
3526 {
3527     _impl->startSpeaking();
3528 }
3529
3530 - (IBAction)stopSpeaking:(id)sender
3531 {
3532     _impl->stopSpeaking(sender);
3533 }
3534
3535 - (IBAction)showGuessPanel:(id)sender
3536 {
3537     _impl->showGuessPanel(sender);
3538 }
3539
3540 - (IBAction)checkSpelling:(id)sender
3541 {
3542     _impl->checkSpelling();
3543 }
3544
3545 - (void)changeSpelling:(id)sender
3546 {
3547     _impl->changeSpelling(sender);
3548 }
3549
3550 - (IBAction)toggleContinuousSpellChecking:(id)sender
3551 {
3552     _impl->toggleContinuousSpellChecking();
3553 }
3554
3555 - (BOOL)isGrammarCheckingEnabled
3556 {
3557     return _impl->isGrammarCheckingEnabled();
3558 }
3559
3560 - (void)setGrammarCheckingEnabled:(BOOL)flag
3561 {
3562     _impl->setGrammarCheckingEnabled(flag);
3563 }
3564
3565 - (IBAction)toggleGrammarChecking:(id)sender
3566 {
3567     _impl->toggleGrammarChecking();
3568 }
3569
3570 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
3571 {
3572     _impl->toggleAutomaticSpellingCorrection();
3573 }
3574
3575 - (void)orderFrontSubstitutionsPanel:(id)sender
3576 {
3577     _impl->orderFrontSubstitutionsPanel(sender);
3578 }
3579
3580 - (IBAction)toggleSmartInsertDelete:(id)sender
3581 {
3582     _impl->toggleSmartInsertDelete();
3583 }
3584
3585 - (BOOL)isAutomaticQuoteSubstitutionEnabled
3586 {
3587     return _impl->isAutomaticQuoteSubstitutionEnabled();
3588 }
3589
3590 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
3591 {
3592     _impl->setAutomaticQuoteSubstitutionEnabled(flag);
3593 }
3594
3595 - (void)toggleAutomaticQuoteSubstitution:(id)sender
3596 {
3597     _impl->toggleAutomaticQuoteSubstitution();
3598 }
3599
3600 - (BOOL)isAutomaticDashSubstitutionEnabled
3601 {
3602     return _impl->isAutomaticDashSubstitutionEnabled();
3603 }
3604
3605 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
3606 {
3607     _impl->setAutomaticDashSubstitutionEnabled(flag);
3608 }
3609
3610 - (void)toggleAutomaticDashSubstitution:(id)sender
3611 {
3612     _impl->toggleAutomaticDashSubstitution();
3613 }
3614
3615 - (BOOL)isAutomaticLinkDetectionEnabled
3616 {
3617     return _impl->isAutomaticLinkDetectionEnabled();
3618 }
3619
3620 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
3621 {
3622     _impl->setAutomaticLinkDetectionEnabled(flag);
3623 }
3624
3625 - (void)toggleAutomaticLinkDetection:(id)sender
3626 {
3627     _impl->toggleAutomaticLinkDetection();
3628 }
3629
3630 - (BOOL)isAutomaticTextReplacementEnabled
3631 {
3632     return _impl->isAutomaticTextReplacementEnabled();
3633 }
3634
3635 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
3636 {
3637     _impl->setAutomaticTextReplacementEnabled(flag);
3638 }
3639
3640 - (void)toggleAutomaticTextReplacement:(id)sender
3641 {
3642     _impl->toggleAutomaticTextReplacement();
3643 }
3644
3645 - (void)uppercaseWord:(id)sender
3646 {
3647     _impl->uppercaseWord();
3648 }
3649
3650 - (void)lowercaseWord:(id)sender
3651 {
3652     _impl->lowercaseWord();
3653 }
3654
3655 - (void)capitalizeWord:(id)sender
3656 {
3657     _impl->capitalizeWord();
3658 }
3659
3660 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
3661 {
3662     return _impl->wantsKeyDownForEvent(event);
3663 }
3664
3665 - (void)scrollWheel:(NSEvent *)event
3666 {
3667     _impl->scrollWheel(event);
3668 }
3669
3670 - (void)swipeWithEvent:(NSEvent *)event
3671 {
3672     _impl->swipeWithEvent(event);
3673 }
3674
3675 - (void)mouseMoved:(NSEvent *)event
3676 {
3677     _impl->mouseMoved(event);
3678 }
3679
3680 - (void)mouseDown:(NSEvent *)event
3681 {
3682     _impl->mouseDown(event);
3683 }
3684
3685 - (void)mouseUp:(NSEvent *)event
3686 {
3687     _impl->mouseUp(event);
3688 }
3689
3690 - (void)mouseDragged:(NSEvent *)event
3691 {
3692     _impl->mouseDragged(event);
3693 }
3694
3695 - (void)mouseEntered:(NSEvent *)event
3696 {
3697     _impl->mouseEntered(event);
3698 }
3699
3700 - (void)mouseExited:(NSEvent *)event
3701 {
3702     _impl->mouseExited(event);
3703 }
3704
3705 - (void)otherMouseDown:(NSEvent *)event
3706 {
3707     _impl->otherMouseDown(event);
3708 }
3709
3710 - (void)otherMouseDragged:(NSEvent *)event
3711 {
3712     _impl->otherMouseDragged(event);
3713 }
3714
3715 - (void)otherMouseUp:(NSEvent *)event
3716 {
3717     _impl->otherMouseUp(event);
3718 }
3719
3720 - (void)rightMouseDown:(NSEvent *)event
3721 {
3722     _impl->rightMouseDown(event);
3723 }
3724
3725 - (void)rightMouseDragged:(NSEvent *)event
3726 {
3727     _impl->rightMouseDragged(event);
3728 }
3729
3730 - (void)rightMouseUp:(NSEvent *)event
3731 {
3732     _impl->rightMouseUp(event);
3733 }
3734
3735 - (void)pressureChangeWithEvent:(NSEvent *)event
3736 {
3737     _impl->pressureChangeWithEvent(event);
3738 }
3739
3740 - (BOOL)acceptsFirstMouse:(NSEvent *)event
3741 {
3742     return _impl->acceptsFirstMouse(event);
3743 }
3744
3745 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
3746 {
3747     return _impl->shouldDelayWindowOrderingForEvent(event);
3748 }
3749
3750 - (void)doCommandBySelector:(SEL)selector
3751 {
3752     _impl->doCommandBySelector(selector);
3753 }
3754
3755 - (void)insertText:(id)string
3756 {
3757     _impl->insertText(string);
3758 }
3759
3760 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
3761 {
3762     _impl->insertText(string, replacementRange);
3763 }
3764
3765 - (NSTextInputContext *)inputContext
3766 {
3767     if (!_impl)
3768         return nil;
3769     return _impl->inputContext();
3770 }
3771
3772 - (BOOL)performKeyEquivalent:(NSEvent *)event
3773 {
3774     return _impl->performKeyEquivalent(event);
3775 }
3776
3777 - (void)keyUp:(NSEvent *)theEvent
3778 {
3779     _impl->keyUp(theEvent);
3780 }
3781
3782 - (void)keyDown:(NSEvent *)theEvent
3783 {
3784     _impl->keyDown(theEvent);
3785 }
3786
3787 - (void)flagsChanged:(NSEvent *)theEvent
3788 {
3789     _impl->flagsChanged(theEvent);
3790 }
3791
3792 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelectedRange replacementRange:(NSRange)replacementRange
3793 {
3794     _impl->setMarkedText(string, newSelectedRange, replacementRange);
3795 }
3796
3797 - (void)unmarkText
3798 {
3799     _impl->unmarkText();
3800 }
3801
3802 - (NSRange)selectedRange
3803 {
3804     return _impl->selectedRange();
3805 }
3806
3807 - (BOOL)hasMarkedText
3808 {
3809     return _impl->hasMarkedText();
3810 }
3811
3812 - (NSRange)markedRange
3813 {
3814     return _impl->markedRange();
3815 }
3816
3817 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange
3818 {
3819     return _impl->attributedSubstringForProposedRange(nsRange, actualRange);
3820 }
3821
3822 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
3823 {
3824     return _impl->characterIndexForPoint(thePoint);
3825 }
3826
3827 - (void)typingAttributesWithCompletionHandler:(void(^)(NSDictionary<NSString *, id> *))completion
3828 {
3829     _impl->typingAttributesWithCompletionHandler(completion);
3830 }
3831
3832 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
3833 {
3834     return _impl->firstRectForCharacterRange(theRange, actualRange);
3835 }
3836
3837 - (void)selectedRangeWithCompletionHandler:(void(^)(NSRange selectedRange))completionHandlerPtr
3838 {
3839     _impl->selectedRangeWithCompletionHandler(completionHandlerPtr);
3840 }
3841
3842 - (void)markedRangeWithCompletionHandler:(void(^)(NSRange markedRange))completionHandlerPtr
3843 {
3844     _impl->markedRangeWithCompletionHandler(completionHandlerPtr);
3845 }
3846
3847 - (void)hasMarkedTextWithCompletionHandler:(void(^)(BOOL hasMarkedText))completionHandlerPtr
3848 {
3849     _impl->hasMarkedTextWithCompletionHandler(completionHandlerPtr);
3850 }
3851
3852 - (void)attributedSubstringForProposedRange:(NSRange)nsRange completionHandler:(void(^)(NSAttributedString *attrString, NSRange actualRange))completionHandlerPtr
3853 {
3854     _impl->attributedSubstringForProposedRange(nsRange, completionHandlerPtr);
3855 }
3856
3857 - (void)firstRectForCharacterRange:(NSRange)theRange completionHandler:(void(^)(NSRect firstRect, NSRange actualRange))completionHandlerPtr
3858 {
3859     _impl->firstRectForCharacterRange(theRange, completionHandlerPtr);
3860 }
3861
3862 - (void)characterIndexForPoint:(NSPoint)thePoint completionHandler:(void(^)(NSUInteger))completionHandlerPtr
3863 {
3864     _impl->characterIndexForPoint(thePoint, completionHandlerPtr);
3865 }
3866
3867 - (NSArray *)validAttributesForMarkedText
3868 {
3869     return _impl->validAttributesForMarkedText();
3870 }
3871
3872 #if ENABLE(DRAG_SUPPORT)
3873 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
3874 - (void)draggedImage:(NSImage *)image endedAt:(NSPoint)endPoint operation:(NSDragOperation)operation
3875 IGNORE_WARNINGS_END
3876 {
3877     _impl->draggedImage(image, NSPointToCGPoint(endPoint), operation);
3878 }
3879
3880 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
3881 {
3882     return _impl->draggingEntered(draggingInfo);
3883 }
3884
3885 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
3886 {
3887     return _impl->draggingUpdated(draggingInfo);
3888 }
3889
3890 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
3891 {
3892     _impl->draggingExited(draggingInfo);
3893 }
3894
3895 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
3896 {
3897     return _impl->prepareForDragOperation(draggingInfo);
3898 }
3899
3900 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
3901 {
3902     return _impl->performDragOperation(draggingInfo);
3903 }
3904
3905 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
3906 {
3907     return _impl->hitTestForDragTypes(NSPointToCGPoint(*point), types);
3908 }
3909 #endif // ENABLE(DRAG_SUPPORT)
3910
3911 - (BOOL)_windowResizeMouseLocationIsInVisibleScrollerThumb:(NSPoint)point
3912 {
3913     return _impl->windowResizeMouseLocationIsInVisibleScrollerThumb(NSPointToCGPoint(point));
3914 }
3915
3916 - (void)viewWillMoveToWindow:(NSWindow *)window
3917 {
3918     _impl->viewWillMoveToWindow(window);
3919 }
3920
3921 - (void)viewDidMoveToWindow
3922 {
3923     _impl->viewDidMoveToWindow();
3924 }
3925
3926 - (void)drawRect:(NSRect)rect
3927 {
3928     _impl->drawRect(NSRectToCGRect(rect));
3929 }
3930
3931 - (BOOL)isOpaque
3932 {
3933     return _impl->isOpaque();
3934 }
3935
3936 - (BOOL)mouseDownCanMoveWindow
3937 {
3938     return WebKit::WebViewImpl::mouseDownCanMoveWindow();
3939 }
3940
3941 - (void)viewDidHide
3942 {
3943     _impl->viewDidHide();
3944 }
3945
3946 - (void)viewDidUnhide
3947 {
3948     _impl->viewDidUnhide();
3949 }
3950
3951 - (void)viewDidChangeBackingProperties
3952 {
3953     _impl->viewDidChangeBackingProperties();
3954 }
3955
3956 - (void)_activeSpaceDidChange:(NSNotification *)notification
3957 {
3958     _impl->activeSpaceDidChange();
3959 }
3960
3961 - (id)accessibilityFocusedUIElement
3962 {
3963     return _impl->accessibilityFocusedUIElement();
3964 }
3965
3966 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
3967 - (BOOL)accessibilityIsIgnored
3968 IGNORE_WARNINGS_END
3969 {
3970     return _impl->accessibilityIsIgnored();
3971 }
3972
3973 - (id)accessibilityHitTest:(NSPoint)point
3974 {
3975     return _impl->accessibilityHitTest(NSPointToCGPoint(point));
3976 }
3977
3978 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
3979 - (id)accessibilityAttributeValue:(NSString *)attribute
3980 IGNORE_WARNINGS_END
3981 {
3982     return _impl->accessibilityAttributeValue(attribute);
3983 }
3984
3985 - (NSView *)hitTest:(NSPoint)point
3986 {
3987     if (!_impl)
3988         return [super hitTest:point];
3989     return _impl->hitTest(NSPointToCGPoint(point));
3990 }
3991
3992 - (NSInteger)conversationIdentifier
3993 {
3994     return (NSInteger)self;
3995 }
3996
3997 - (void)quickLookWithEvent:(NSEvent *)event
3998 {
3999     _impl->quickLookWithEvent(event);
4000 }
4001
4002 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
4003 {
4004     return _impl->addTrackingRect(NSRectToCGRect(rect), owner, data, assumeInside);
4005 }
4006
4007 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
4008 {
4009     return _impl->addTrackingRectWithTrackingNum(NSRectToCGRect(rect), owner, data, assumeInside, tag);
4010 }
4011
4012 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
4013 {
4014     CGRect *cgRects = (CGRect *)calloc(1, sizeof(CGRect));
4015     for (int i = 0; i < count; i++)
4016         cgRects[i] = NSRectToCGRect(rects[i]);
4017     _impl->addTrackingRectsWithTrackingNums(cgRects, owner, userDataList, assumeInsideList, trackingNums, count);
4018     free(cgRects);
4019 }
4020
4021 - (void)removeTrackingRect:(NSTrackingRectTag)tag
4022 {
4023     if (!_impl)
4024         return;
4025     _impl->removeTrackingRect(tag);
4026 }
4027
4028 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
4029 {
4030     if (!_impl)
4031         return;
4032     _impl->removeTrackingRects(tags, count);
4033 }
4034
4035 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
4036 {
4037     return _impl->stringForToolTip(tag);
4038 }
4039
4040 - (void)pasteboardChangedOwner:(NSPasteboard *)pasteboard
4041 {
4042     _impl->pasteboardChangedOwner(pasteboard);
4043 }
4044
4045 - (void)pasteboard:(NSPasteboard *)pasteboard provideDataForType:(NSString *)type
4046 {
4047     _impl->provideDataForPasteboard(pasteboard, type);
4048 }
4049
4050 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
4051 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
4052 IGNORE_WARNINGS_END
4053 {
4054     return _impl->namesOfPromisedFilesDroppedAtDestination(dropDestination);
4055 }
4056
4057 - (BOOL)wantsUpdateLayer
4058 {
4059     return WebKit::WebViewImpl::wantsUpdateLayer();
4060 }
4061
4062 - (void)updateLayer
4063 {
4064     _impl->updateLayer();
4065 }
4066
4067 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
4068 {
4069     _impl->setAllowsBackForwardNavigationGestures(allowsBackForwardNavigationGestures);
4070 }
4071
4072 - (BOOL)allowsBackForwardNavigationGestures
4073 {
4074     return _impl->allowsBackForwardNavigationGestures();
4075 }
4076
4077 - (void)smartMagnifyWithEvent:(NSEvent *)event
4078 {
4079     _impl->smartMagnifyWithEvent(event);
4080 }