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