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