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