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