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