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