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