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