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