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