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