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