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