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