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