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