2 * Copyright (C) 2014-2018 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
27 #import "WKWebViewInternal.h"
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 "GlobalFindInPageState.h"
41 #import "IconLoadingDelegate.h"
42 #import "LegacySessionStateCoding.h"
44 #import "MediaCaptureUtilities.h"
45 #import "NavigationState.h"
46 #import "ObjCObjectGraph.h"
47 #import "PageClient.h"
48 #import "ProvisionalPageProxy.h"
49 #import "RemoteLayerTreeScrollingPerformanceData.h"
50 #import "RemoteLayerTreeTransaction.h"
51 #import "RemoteObjectRegistry.h"
52 #import "RemoteObjectRegistryMessages.h"
53 #import "SafeBrowsingWarning.h"
54 #import "StringUtilities.h"
55 #import "UIDelegate.h"
56 #import "UserMediaProcessManager.h"
57 #import "VersionChecks.h"
58 #import "ViewGestureController.h"
59 #import "ViewSnapshotStore.h"
60 #import "WKBackForwardListInternal.h"
61 #import "WKBackForwardListItemInternal.h"
62 #import "WKBrowsingContextHandleInternal.h"
63 #import "WKDragDestinationAction.h"
64 #import "WKErrorInternal.h"
65 #import "WKHistoryDelegatePrivate.h"
66 #import "WKLayoutMode.h"
68 #import "WKNSURLExtras.h"
69 #import "WKNavigationDelegate.h"
70 #import "WKNavigationInternal.h"
71 #import "WKPreferencesInternal.h"
72 #import "WKProcessPoolInternal.h"
73 #import "WKSafeBrowsingWarning.h"
74 #import "WKSharedAPICast.h"
75 #import "WKSnapshotConfiguration.h"
76 #import "WKUIDelegate.h"
77 #import "WKUIDelegatePrivate.h"
78 #import "WKUserContentControllerInternal.h"
79 #import "WKWebViewConfigurationInternal.h"
80 #import "WKWebViewContentProvider.h"
81 #import "WKWebsiteDataStoreInternal.h"
82 #import "WebBackForwardList.h"
83 #import "WebCertificateInfo.h"
84 #import "WebFullScreenManagerProxy.h"
85 #import "WebPageGroup.h"
86 #import "WebPageProxy.h"
87 #import "WebPreferencesKeys.h"
88 #import "WebProcessPool.h"
89 #import "WebProcessProxy.h"
90 #import "WebURLSchemeHandlerCocoa.h"
91 #import "WebViewImpl.h"
92 #import "_WKActivatedElementInfoInternal.h"
93 #import "_WKDiagnosticLoggingDelegate.h"
94 #import "_WKFindDelegate.h"
95 #import "_WKFrameHandleInternal.h"
96 #import "_WKFullscreenDelegate.h"
97 #import "_WKHitTestResultInternal.h"
98 #import "_WKInputDelegate.h"
99 #import "_WKInspectorInternal.h"
100 #import "_WKRemoteObjectRegistryInternal.h"
101 #import "_WKSessionStateInternal.h"
102 #import "_WKVisitedLinkStoreInternal.h"
103 #import "_WKWebsitePoliciesInternal.h"
104 #import <WebCore/GraphicsContextCG.h>
105 #import <WebCore/IOSurface.h>
106 #import <WebCore/JSDOMBinding.h>
107 #import <WebCore/JSDOMExceptionHandling.h>
108 #import <WebCore/MIMETypeRegistry.h>
109 #import <WebCore/PlatformScreen.h>
110 #import <WebCore/RuntimeApplicationChecks.h>
111 #import <WebCore/SQLiteDatabaseTracker.h>
112 #import <WebCore/SchemeRegistry.h>
113 #import <WebCore/Settings.h>
114 #import <WebCore/SharedBuffer.h>
115 #import <WebCore/ValidationBubble.h>
116 #import <WebCore/ViewportArguments.h>
117 #import <WebCore/WritingMode.h>
118 #import <pal/spi/cocoa/NSKeyedArchiverSPI.h>
119 #import <pal/spi/mac/NSTextFinderSPI.h>
120 #import <wtf/BlockPtr.h>
121 #import <wtf/HashMap.h>
122 #import <wtf/MathExtras.h>
123 #import <wtf/NeverDestroyed.h>
124 #import <wtf/Optional.h>
125 #import <wtf/RetainPtr.h>
126 #import <wtf/SetForScope.h>
128 #import <wtf/spi/darwin/dyldSPI.h>
129 #import <wtf/text/TextStream.h>
131 #if ENABLE(APPLICATION_MANIFEST)
132 #import "_WKApplicationManifestInternal.h"
135 #if ENABLE(DATA_DETECTION)
136 #import "WKDataDetectorTypesInternal.h"
139 #if PLATFORM(IOS_FAMILY)
140 #import "InteractionInformationAtPosition.h"
141 #import "InteractionInformationRequest.h"
142 #import "ProcessThrottler.h"
143 #import "RemoteLayerTreeDrawingAreaProxy.h"
144 #import "RemoteScrollingCoordinatorProxy.h"
146 #import "VideoFullscreenManagerProxy.h"
147 #import "WKContentViewInteraction.h"
148 #import "WKPasswordView.h"
149 #import "WKScrollView.h"
150 #import "WKWebViewContentProviderRegistry.h"
151 #import "_WKWebViewPrintFormatter.h"
152 #import <MobileCoreServices/MobileCoreServices.h>
153 #import <UIKit/UIApplication.h>
154 #import <WebCore/FrameLoaderTypes.h>
155 #import <WebCore/InspectorOverlay.h>
156 #import <WebCore/ScrollableArea.h>
157 #import <WebCore/WebBackgroundTaskController.h>
158 #import <WebCore/WebSQLiteDatabaseTrackerClient.h>
159 #import <pal/spi/cg/CoreGraphicsSPI.h>
160 #import <pal/spi/cocoa/QuartzCoreSPI.h>
161 #import <pal/spi/ios/GraphicsServicesSPI.h>
162 #import <wtf/cocoa/Entitlements.h>
164 #define RELEASE_LOG_IF_ALLOWED(...) RELEASE_LOG_IF(_page && _page->isAlwaysOnLoggingAllowed(), ViewState, __VA_ARGS__)
166 @interface UIView (UIViewInternal)
167 - (UIViewController *)_viewControllerForAncestor;
170 @interface UIWindow (UIWindowInternal)
171 - (BOOL)_isHostedInAnotherProcess;
174 @interface UIViewController (UIViewControllerInternal)
175 - (UIViewController *)_rootAncestorViewController;
176 - (UIViewController *)_viewControllerForSupportedInterfaceOrientations;
179 #endif // PLATFORM(IOS_FAMILY)
181 #if PLATFORM(IOS_FAMILY)
182 static const uint32_t firstSDKVersionWithLinkPreviewEnabledByDefault = 0xA0000;
183 static const Seconds delayBeforeNoVisibleContentsRectsLogging = 1_s;
187 #import "AppKitSPI.h"
188 #import "WKTextFinderClient.h"
189 #import "WKViewInternal.h"
190 #import <WebCore/ColorMac.h>
192 @interface WKWebView () <WebViewImplDelegate, NSTextInputClient, NSTextInputClient_Async>
196 @interface WKWebView () <NSTouchBarProvider>
198 #endif // HAVE(TOUCH_BAR)
199 #endif // PLATFORM(MAC)
201 #if ENABLE(ACCESSIBILITY_EVENTS)
202 #import "AccessibilitySupportSPI.h"
203 #import <wtf/darwin/WeakLinking.h>
206 #if PLATFORM(MAC) && ENABLE(DRAG_SUPPORT)
208 @interface WKWebView () <NSFilePromiseProviderDelegate, NSDraggingSource>
213 static HashMap<WebKit::WebPageProxy*, __unsafe_unretained WKWebView *>& pageToViewMap()
215 static NeverDestroyed<HashMap<WebKit::WebPageProxy*, __unsafe_unretained WKWebView *>> map;
219 WKWebView* fromWebPageProxy(WebKit::WebPageProxy& page)
221 return pageToViewMap().get(&page);
225 static _WKOverlayScrollbarStyle toAPIScrollbarStyle(Optional<WebCore::ScrollbarOverlayStyle> coreScrollbarStyle)
227 if (!coreScrollbarStyle)
228 return _WKOverlayScrollbarStyleAutomatic;
230 switch (coreScrollbarStyle.value()) {
231 case WebCore::ScrollbarOverlayStyleDark:
232 return _WKOverlayScrollbarStyleDark;
233 case WebCore::ScrollbarOverlayStyleLight:
234 return _WKOverlayScrollbarStyleLight;
235 case WebCore::ScrollbarOverlayStyleDefault:
236 return _WKOverlayScrollbarStyleDefault;
238 ASSERT_NOT_REACHED();
239 return _WKOverlayScrollbarStyleAutomatic;
242 static Optional<WebCore::ScrollbarOverlayStyle> toCoreScrollbarStyle(_WKOverlayScrollbarStyle scrollbarStyle)
244 switch (scrollbarStyle) {
245 case _WKOverlayScrollbarStyleDark:
246 return WebCore::ScrollbarOverlayStyleDark;
247 case _WKOverlayScrollbarStyleLight:
248 return WebCore::ScrollbarOverlayStyleLight;
249 case _WKOverlayScrollbarStyleDefault:
250 return WebCore::ScrollbarOverlayStyleDefault;
251 case _WKOverlayScrollbarStyleAutomatic:
258 #define FORWARD_ACTION_TO_WKCONTENTVIEW(_action) \
259 - (void)_action:(id)sender \
261 if (self.usesStandardContentView) \
262 [_contentView _action ## ForWebView:sender]; \
265 @implementation WKWebView {
266 std::unique_ptr<WebKit::NavigationState> _navigationState;
267 std::unique_ptr<WebKit::UIDelegate> _uiDelegate;
268 std::unique_ptr<WebKit::IconLoadingDelegate> _iconLoadingDelegate;
270 _WKRenderingProgressEvents _observedRenderingProgressEvents;
272 WeakObjCPtr<id <_WKInputDelegate>> _inputDelegate;
274 Optional<BOOL> _resolutionForShareSheetImmediateCompletionForTesting;
275 RetainPtr<WKSafeBrowsingWarning> _safeBrowsingWarning;
277 #if PLATFORM(IOS_FAMILY)
278 RetainPtr<_WKRemoteObjectRegistry> _remoteObjectRegistry;
280 RetainPtr<WKScrollView> _scrollView;
281 RetainPtr<WKContentView> _contentView;
283 #if ENABLE(FULLSCREEN_API)
284 RetainPtr<WKFullScreenWindowController> _fullScreenWindowController;
287 BOOL _overridesViewLayoutSize;
288 CGSize _viewLayoutSizeOverride;
289 Optional<WebCore::FloatSize> _lastSentViewLayoutSize;
290 BOOL _overridesMaximumUnobscuredSize;
291 CGSize _maximumUnobscuredSizeOverride;
292 Optional<WebCore::FloatSize> _lastSentMaximumUnobscuredSize;
293 CGRect _inputViewBounds;
294 CGFloat _viewportMetaTagWidth;
295 BOOL _viewportMetaTagWidthWasExplicit;
296 BOOL _viewportMetaTagCameFromImageDocument;
297 CGFloat _initialScaleFactor;
298 BOOL _fastClickingIsDisabled;
300 BOOL _allowsLinkPreview;
302 UIEdgeInsets _obscuredInsets;
303 BOOL _haveSetObscuredInsets;
304 BOOL _isChangingObscuredInsetsInteractively;
306 UIEdgeInsets _unobscuredSafeAreaInsets;
307 BOOL _haveSetUnobscuredSafeAreaInsets;
308 BOOL _avoidsUnsafeArea;
309 UIRectEdge _obscuredInsetEdgesAffectedBySafeArea;
311 UIInterfaceOrientation _interfaceOrientationOverride;
312 BOOL _overridesInterfaceOrientation;
313 Optional<int32_t> _lastSentDeviceOrientation;
315 BOOL _allowsViewportShrinkToFit;
317 BOOL _hasCommittedLoadForMainFrame;
318 BOOL _needsResetViewStateAfterCommitLoadForMainFrame;
319 uint64_t _firstPaintAfterCommitLoadTransactionID;
320 WebKit::DynamicViewportUpdateMode _dynamicViewportUpdateMode;
321 WebKit::DynamicViewportSizeUpdateID _currentDynamicViewportSizeUpdateID;
322 CATransform3D _resizeAnimationTransformAdjustments;
323 CGFloat _animatedResizeOriginalContentWidth;
324 RetainPtr<UIView> _resizeAnimationView;
325 CGFloat _lastAdjustmentForScroller;
326 Optional<CGRect> _frozenVisibleContentRect;
327 Optional<CGRect> _frozenUnobscuredContentRect;
329 BOOL _commitDidRestoreScrollPosition;
330 Optional<WebCore::FloatPoint> _scrollOffsetToRestore;
331 WebCore::FloatBoxExtent _obscuredInsetsWhenSaved;
333 Optional<WebCore::FloatPoint> _unobscuredCenterToRestore;
334 Optional<uint64_t> _firstTransactionIDAfterPageRestore;
335 double _scaleToRestore;
337 std::unique_ptr<WebKit::ViewGestureController> _gestureController;
338 BOOL _allowsBackForwardNavigationGestures;
340 RetainPtr<UIView <WKWebViewContentProvider>> _customContentView;
341 RetainPtr<UIView> _customContentFixedOverlayView;
343 RetainPtr<NSTimer> _enclosingScrollViewScrollTimer;
344 BOOL _didScrollSinceLastTimerFire;
346 WebCore::Color _scrollViewBackgroundColor;
348 // This value tracks the current adjustment added to the bottom inset due to the keyboard sliding out from the bottom
349 // when computing obscured content insets. This is used when updating the visible content rects where we should not
350 // include this adjustment.
351 CGFloat _totalScrollViewBottomInsetAdjustmentForKeyboard;
352 BOOL _currentlyAdjustingScrollViewInsetsForKeyboard;
354 BOOL _delayUpdateVisibleContentRects;
355 BOOL _hadDelayedUpdateVisibleContentRects;
357 BOOL _waitingForEndAnimatedResize;
358 BOOL _waitingForCommitAfterAnimatedResize;
360 Vector<WTF::Function<void ()>> _callbacksDeferredDuringResize;
361 RetainPtr<NSMutableArray> _stableStatePresentationUpdateCallbacks;
363 RetainPtr<WKPasswordView> _passwordView;
365 BOOL _hasScheduledVisibleRectUpdate;
366 BOOL _visibleContentRectUpdateScheduledFromScrollViewInStableState;
367 Vector<BlockPtr<void ()>> _visibleContentRectUpdateCallbacks;
369 _WKDragInteractionPolicy _dragInteractionPolicy;
371 // For release-logging for <rdar://problem/39281269>.
372 MonotonicTime _timeOfRequestForVisibleContentRectUpdate;
373 MonotonicTime _timeOfLastVisibleContentRectUpdate;
375 NSUInteger _focusPreservationCount;
376 NSUInteger _activeFocusedStateRetainCount;
379 std::unique_ptr<WebKit::WebViewImpl> _impl;
380 RetainPtr<WKTextFinderClient> _textFinderClient;
382 _WKSelectionAttributes _selectionAttributes;
383 CGFloat _minimumEffectiveDeviceWidth;
386 - (instancetype)initWithFrame:(CGRect)frame
388 return [self initWithFrame:frame configuration:adoptNS([[WKWebViewConfiguration alloc] init]).get()];
393 return _page && _page->isValid();
396 #if PLATFORM(IOS_FAMILY)
397 static int32_t deviceOrientationForUIInterfaceOrientation(UIInterfaceOrientation orientation)
399 switch (orientation) {
400 case UIInterfaceOrientationUnknown:
401 case UIInterfaceOrientationPortrait:
403 case UIInterfaceOrientationPortraitUpsideDown:
405 case UIInterfaceOrientationLandscapeLeft:
407 case UIInterfaceOrientationLandscapeRight:
412 static int32_t deviceOrientation()
414 return deviceOrientationForUIInterfaceOrientation([[UIApplication sharedApplication] statusBarOrientation]);
417 - (BOOL)_isShowingVideoPictureInPicture
422 if (!_page || !_page->videoFullscreenManager())
425 return _page->videoFullscreenManager()->hasMode(WebCore::HTMLMediaElementEnums::VideoFullscreenModePictureInPicture);
429 - (BOOL)_mayAutomaticallyShowVideoPictureInPicture
434 if (!_page || !_page->videoFullscreenManager())
437 return _page->videoFullscreenManager()->mayAutomaticallyShowVideoPictureInPicture();
441 static bool shouldAllowPictureInPictureMediaPlayback()
443 static bool shouldAllowPictureInPictureMediaPlayback = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_9_0;
444 return shouldAllowPictureInPictureMediaPlayback;
447 static bool shouldAllowSettingAnyXHRHeaderFromFileURLs()
449 static bool shouldAllowSettingAnyXHRHeaderFromFileURLs = (WebCore::IOSApplication::isCardiogram() || WebCore::IOSApplication::isNike()) && !linkedOnOrAfter(WebKit::SDKVersion::FirstThatDisallowsSettingAnyXHRHeaderFromFileURLs);
450 return shouldAllowSettingAnyXHRHeaderFromFileURLs;
453 - (void)_incrementFocusPreservationCount
455 ++_focusPreservationCount;
458 - (void)_decrementFocusPreservationCount
460 if (_focusPreservationCount)
461 --_focusPreservationCount;
464 - (void)_resetFocusPreservationCount
466 _focusPreservationCount = 0;
469 - (BOOL)_isRetainingActiveFocusedState
471 // Focus preservation count fulfills the same role as active focus state count.
472 // However, unlike active focus state, it may be reset to 0 without impacting the
473 // behavior of -_retainActiveFocusedState, and it's harmless to invoke
474 // -_decrementFocusPreservationCount after resetting the count to 0.
475 return _focusPreservationCount || _activeFocusedStateRetainCount;
480 #if USE(APPLE_INTERNAL_SDK)
481 #include <WebKitAdditions/WKWebViewInternalAdditions.mm>
484 static bool shouldRequireUserGestureToLoadVideo()
486 #if PLATFORM(IOS_FAMILY)
487 static bool shouldRequireUserGestureToLoadVideo = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
488 return shouldRequireUserGestureToLoadVideo;
495 static uint32_t convertUserInterfaceDirectionPolicy(WKUserInterfaceDirectionPolicy policy)
498 case WKUserInterfaceDirectionPolicyContent:
499 return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content);
500 case WKUserInterfaceDirectionPolicySystem:
501 return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::System);
503 return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content);
506 static uint32_t convertSystemLayoutDirection(NSUserInterfaceLayoutDirection direction)
509 case NSUserInterfaceLayoutDirectionLeftToRight:
510 return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::LTR);
511 case NSUserInterfaceLayoutDirectionRightToLeft:
512 return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::RTL);
514 return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::LTR);
517 #endif // PLATFORM(MAC)
519 static void validate(WKWebViewConfiguration *configuration)
521 if (!configuration.processPool)
522 [NSException raise:NSInvalidArgumentException format:@"configuration.processPool is nil"];
524 if (!configuration.preferences)
525 [NSException raise:NSInvalidArgumentException format:@"configuration.preferences is nil"];
527 if (!configuration.userContentController)
528 [NSException raise:NSInvalidArgumentException format:@"configuration.userContentController is nil"];
530 if (!configuration.websiteDataStore)
531 [NSException raise:NSInvalidArgumentException format:@"configuration.websiteDataStore is nil"];
533 if (!configuration._visitedLinkStore)
534 [NSException raise:NSInvalidArgumentException format:@"configuration._visitedLinkStore is nil"];
536 #if PLATFORM(IOS_FAMILY)
537 if (!configuration._contentProviderRegistry)
538 [NSException raise:NSInvalidArgumentException format:@"configuration._contentProviderRegistry is nil"];
542 - (void)_initializeWithConfiguration:(WKWebViewConfiguration *)configuration
545 [NSException raise:NSInvalidArgumentException format:@"Configuration cannot be nil"];
547 _configuration = adoptNS([configuration copy]);
549 if (WKWebView *relatedWebView = [_configuration _relatedWebView]) {
550 WKProcessPool *processPool = [_configuration processPool];
551 WKProcessPool *relatedWebViewProcessPool = [relatedWebView->_configuration processPool];
552 if (processPool && processPool != relatedWebViewProcessPool)
553 [NSException raise:NSInvalidArgumentException format:@"Related web view %@ has process pool %@ but configuration specifies a different process pool %@", relatedWebView, relatedWebViewProcessPool, configuration.processPool];
555 [_configuration setProcessPool:relatedWebViewProcessPool];
558 validate(_configuration.get());
560 WebKit::WebProcessPool& processPool = *[_configuration processPool]->_processPool;
561 processPool.setResourceLoadStatisticsEnabled(configuration.websiteDataStore._resourceLoadStatisticsEnabled);
563 auto pageConfiguration = [configuration copyPageConfiguration];
565 pageConfiguration->setProcessPool(&processPool);
566 pageConfiguration->setPreferences([_configuration preferences]->_preferences.get());
567 if (WKWebView *relatedWebView = [_configuration _relatedWebView])
568 pageConfiguration->setRelatedPage(relatedWebView->_page.get());
570 pageConfiguration->setUserContentController([_configuration userContentController]->_userContentControllerProxy.get());
571 pageConfiguration->setVisitedLinkStore([_configuration _visitedLinkStore]->_visitedLinkStore.get());
572 pageConfiguration->setWebsiteDataStore([_configuration websiteDataStore]->_websiteDataStore.get());
575 if (auto pageGroup = WebKit::toImpl([configuration _pageGroup])) {
576 pageConfiguration->setPageGroup(pageGroup);
577 pageConfiguration->setUserContentController(&pageGroup->userContentController());
581 NSString *groupIdentifier = configuration._groupIdentifier;
582 if (groupIdentifier.length)
583 pageConfiguration->setPageGroup(WebKit::WebPageGroup::create(configuration._groupIdentifier).ptr());
586 pageConfiguration->setAdditionalSupportedImageTypes(WebKit::webCoreStringVectorFromNSStringArray([_configuration _additionalSupportedImageTypes]));
588 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::suppressesIncrementalRenderingKey(), WebKit::WebPreferencesStore::Value(!![_configuration suppressesIncrementalRendering]));
590 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldRespectImageOrientationKey(), WebKit::WebPreferencesStore::Value(!![_configuration _respectsImageOrientation]));
591 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldPrintBackgroundsKey(), WebKit::WebPreferencesStore::Value(!![_configuration _printsBackgrounds]));
592 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey(), WebKit::WebPreferencesStore::Value([_configuration _incrementalRenderingSuppressionTimeout]));
593 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::javaScriptMarkupEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsJavaScriptMarkup]));
594 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldConvertPositionStyleOnCopyKey(), WebKit::WebPreferencesStore::Value(!![_configuration _convertsPositionStyleOnCopy]));
595 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::httpEquivEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsMetaRefresh]));
596 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowUniversalAccessFromFileURLsKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowUniversalAccessFromFileURLs]));
597 pageConfiguration->setWaitsForPaintAfterViewDidMoveToWindow([_configuration _waitsForPaintAfterViewDidMoveToWindow]);
598 pageConfiguration->setDrawsBackground([_configuration _drawsBackground]);
599 pageConfiguration->setControlledByAutomation([_configuration _isControlledByAutomation]);
600 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::incompleteImageBorderEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _incompleteImageBorderEnabled]));
601 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldDeferAsynchronousScriptsUntilAfterDocumentLoadKey(), WebKit::WebPreferencesStore::Value(!![_configuration _shouldDeferAsynchronousScriptsUntilAfterDocumentLoad]));
604 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::showsURLsInToolTipsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _showsURLsInToolTips]));
605 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::serviceControlsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _serviceControlsEnabled]));
606 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::imageControlsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _imageControlsEnabled]));
608 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::userInterfaceDirectionPolicyKey(), WebKit::WebPreferencesStore::Value(convertUserInterfaceDirectionPolicy([_configuration userInterfaceDirectionPolicy])));
609 // We are in the View's initialization routine, so our client hasn't had time to set our user interface direction.
610 // Therefore, according to the docs[1], "this property contains the value reported by the app's userInterfaceLayoutDirection property."
611 // [1] http://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/index.html#//apple_ref/doc/uid/20000014-SW222
612 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::systemLayoutDirectionKey(), WebKit::WebPreferencesStore::Value(convertSystemLayoutDirection(self.userInterfaceLayoutDirection)));
615 #if PLATFORM(IOS_FAMILY)
616 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsInlineMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsInlineMediaPlayback]));
617 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsInlineMediaPlaybackAfterFullscreenKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsInlineMediaPlaybackAfterFullscreen]));
618 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::inlineMediaPlaybackRequiresPlaysInlineAttributeKey(), WebKit::WebPreferencesStore::Value(!![_configuration _inlineMediaPlaybackRequiresPlaysInlineAttribute]));
619 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsPictureInPictureMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback()));
620 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::userInterfaceDirectionPolicyKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content)));
621 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::systemLayoutDirectionKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(WebCore::TextDirection::LTR)));
622 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowSettingAnyXHRHeaderFromFileURLsKey(), WebKit::WebPreferencesStore::Value(shouldAllowSettingAnyXHRHeaderFromFileURLs()));
623 #if USE(SYSTEM_PREVIEW)
624 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::systemPreviewEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _systemPreviewEnabled]));
628 WKAudiovisualMediaTypes mediaTypesRequiringUserGesture = [_configuration mediaTypesRequiringUserActionForPlayback];
629 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureForVideoPlaybackKey(), WebKit::WebPreferencesStore::Value((mediaTypesRequiringUserGesture & WKAudiovisualMediaTypeVideo) == WKAudiovisualMediaTypeVideo));
630 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureForAudioPlaybackKey(), WebKit::WebPreferencesStore::Value(((mediaTypesRequiringUserGesture & WKAudiovisualMediaTypeAudio) == WKAudiovisualMediaTypeAudio)));
631 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureToLoadVideoKey(), WebKit::WebPreferencesStore::Value(shouldRequireUserGestureToLoadVideo()));
632 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mainContentUserGestureOverrideEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _mainContentUserGestureOverrideEnabled]));
633 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::invisibleAutoplayNotPermittedKey(), WebKit::WebPreferencesStore::Value(!![_configuration _invisibleAutoplayNotPermitted]));
634 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mediaDataLoadsAutomaticallyKey(), WebKit::WebPreferencesStore::Value(!![_configuration _mediaDataLoadsAutomatically]));
635 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::attachmentElementEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _attachmentElementEnabled]));
637 #if ENABLE(DATA_DETECTION) && PLATFORM(IOS_FAMILY)
638 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::dataDetectorTypesKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(fromWKDataDetectorTypes([_configuration dataDetectorTypes]))));
640 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
641 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsAirPlayForMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsAirPlayForMediaPlayback]));
644 #if ENABLE(APPLE_PAY)
645 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::applePayEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _applePayEnabled]));
648 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::needsStorageAccessFromFileURLsQuirkKey(), WebKit::WebPreferencesStore::Value(!![_configuration _needsStorageAccessFromFileURLsQuirk]));
649 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mediaContentTypesRequiringHardwareSupportKey(), WebKit::WebPreferencesStore::Value(String([_configuration _mediaContentTypesRequiringHardwareSupport])));
650 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowMediaContentTypesRequiringHardwareSupportAsFallbackKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowMediaContentTypesRequiringHardwareSupportAsFallback]));
652 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::colorFilterEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _colorFilterEnabled]));
654 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::editableImagesEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _editableImagesEnabled]));
655 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::undoManagerAPIEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _undoManagerAPIEnabled]));
657 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
658 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::legacyEncryptedMediaAPIEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _legacyEncryptedMediaAPIEnabled]));
661 #if PLATFORM(IOS_FAMILY) && ENABLE(SERVICE_WORKER)
662 if (!WTF::processHasEntitlement("com.apple.developer.WebKit.ServiceWorkers"))
663 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::serviceWorkersEnabledKey(), WebKit::WebPreferencesStore::Value(false));
666 #if PLATFORM(IOS_FAMILY)
667 CGRect bounds = self.bounds;
668 _scrollView = adoptNS([[WKScrollView alloc] initWithFrame:bounds]);
669 [_scrollView setInternalDelegate:self];
670 [_scrollView setBouncesZoom:YES];
672 if ([_configuration _editableImagesEnabled])
673 [_scrollView panGestureRecognizer].allowedTouchTypes = @[ @(UITouchTypeDirect) ];
675 _avoidsUnsafeArea = YES;
676 [self _updateScrollViewInsetAdjustmentBehavior];
678 [self addSubview:_scrollView.get()];
680 static uint32_t programSDKVersion = dyld_get_program_sdk_version();
681 _allowsLinkPreview = programSDKVersion >= firstSDKVersionWithLinkPreviewEnabledByDefault;
683 _contentView = adoptNS([[WKContentView alloc] initWithFrame:bounds processPool:processPool configuration:pageConfiguration.copyRef() webView:self]);
685 _page = [_contentView page];
686 [self _dispatchSetDeviceOrientation:deviceOrientation()];
687 _page->setDrawsBackground(self.opaque);
689 [_contentView layer].anchorPoint = CGPointZero;
690 [_contentView setFrame:bounds];
691 [_scrollView addSubview:_contentView.get()];
692 [_scrollView addSubview:[_contentView unscaledView]];
693 [self _updateScrollViewBackground];
694 _obscuredInsetEdgesAffectedBySafeArea = UIRectEdgeTop | UIRectEdgeLeft | UIRectEdgeRight;
696 _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
697 _initialScaleFactor = 1;
699 if (NSNumber *enabledValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"WebKitFastClickingDisabled"])
700 _fastClickingIsDisabled = enabledValue.boolValue;
702 #if PLATFORM(WATCHOS)
703 _fastClickingIsDisabled = YES;
705 _fastClickingIsDisabled = NO;
709 [self _frameOrBoundsChanged];
711 NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
712 [center addObserver:self selector:@selector(_keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
713 [center addObserver:self selector:@selector(_keyboardDidChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
714 [center addObserver:self selector:@selector(_keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
715 [center addObserver:self selector:@selector(_keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
716 [center addObserver:self selector:@selector(_keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
717 [center addObserver:self selector:@selector(_windowDidRotate:) name:UIWindowDidRotateNotification object:nil];
718 [center addObserver:self selector:@selector(_contentSizeCategoryDidChange:) name:UIContentSizeCategoryDidChangeNotification object:nil];
719 _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
721 [center addObserver:self selector:@selector(_accessibilitySettingsDidChange:) name:UIAccessibilityGrayscaleStatusDidChangeNotification object:nil];
722 [center addObserver:self selector:@selector(_accessibilitySettingsDidChange:) name:UIAccessibilityInvertColorsStatusDidChangeNotification object:nil];
723 [center addObserver:self selector:@selector(_accessibilitySettingsDidChange:) name:UIAccessibilityReduceMotionStatusDidChangeNotification object:nil];
725 [[_configuration _contentProviderRegistry] addPage:*_page];
726 _page->setForceAlwaysUserScalable([_configuration ignoresViewportScaleLimits]);
728 CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), hardwareKeyboardAvailabilityChangedCallback, (CFStringRef)[NSString stringWithUTF8String:kGSEventHardwareKeyboardAvailabilityChangedNotification], nullptr, CFNotificationSuspensionBehaviorCoalesce);
732 _impl = std::make_unique<WebKit::WebViewImpl>(self, self, processPool, pageConfiguration.copyRef());
733 _page = &_impl->page();
735 _impl->setAutomaticallyAdjustsContentInsets(true);
736 _impl->setRequiresUserActionForEditingControlsManager([configuration _requiresUserActionForEditingControlsManager]);
739 #if ENABLE(ACCESSIBILITY_EVENTS)
740 // Check _AXSWebAccessibilityEventsEnabled here to avoid compiler optimizing
741 // out the null check of kAXSWebAccessibilityEventsEnabledNotification.
742 if (!isNullFunctionPointer(_AXSWebAccessibilityEventsEnabled))
743 CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), accessibilityEventsEnabledChangedCallback, kAXSWebAccessibilityEventsEnabledNotification, 0, CFNotificationSuspensionBehaviorDeliverImmediately);
744 [self _updateAccessibilityEventsEnabled];
747 if (NSString *applicationNameForUserAgent = configuration.applicationNameForUserAgent)
748 _page->setApplicationNameForUserAgent(applicationNameForUserAgent);
750 _navigationState = std::make_unique<WebKit::NavigationState>(self);
751 _page->setNavigationClient(_navigationState->createNavigationClient());
753 _uiDelegate = std::make_unique<WebKit::UIDelegate>(self);
754 _page->setFindClient(std::make_unique<WebKit::FindClient>(self));
755 _page->setDiagnosticLoggingClient(std::make_unique<WebKit::DiagnosticLoggingClient>(self));
757 _iconLoadingDelegate = std::make_unique<WebKit::IconLoadingDelegate>(self);
759 [self _setUpSQLiteDatabaseTrackerClient];
761 for (auto& pair : pageConfiguration->urlSchemeHandlers())
762 _page->setURLSchemeHandlerForScheme(WebKit::WebURLSchemeHandlerCocoa::create(static_cast<WebKit::WebURLSchemeHandlerCocoa&>(pair.value.get()).apiHandler()), pair.key);
764 pageToViewMap().add(_page.get(), self);
766 #if PLATFORM(IOS_FAMILY)
767 _dragInteractionPolicy = _WKDragInteractionPolicyDefault;
769 _timeOfRequestForVisibleContentRectUpdate = MonotonicTime::now();
770 _timeOfLastVisibleContentRectUpdate = MonotonicTime::now();
771 #if PLATFORM(WATCHOS)
772 _allowsViewportShrinkToFit = YES;
774 _allowsViewportShrinkToFit = NO;
776 #endif // PLATFORM(IOS_FAMILY)
779 - (void)_setUpSQLiteDatabaseTrackerClient
781 #if PLATFORM(IOS_FAMILY)
782 WebBackgroundTaskController *controller = [WebBackgroundTaskController sharedController];
783 if (controller.backgroundTaskStartBlock)
786 controller.backgroundTaskStartBlock = ^NSUInteger (void (^expirationHandler)())
788 return [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"com.apple.WebKit.DatabaseActivity" expirationHandler:expirationHandler];
790 controller.backgroundTaskEndBlock = ^(UIBackgroundTaskIdentifier taskIdentifier)
792 [[UIApplication sharedApplication] endBackgroundTask:taskIdentifier];
794 controller.invalidBackgroundTaskIdentifier = UIBackgroundTaskInvalid;
796 WebCore::SQLiteDatabaseTracker::setClient(&WebCore::WebSQLiteDatabaseTrackerClient::sharedWebSQLiteDatabaseTrackerClient());
800 - (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration
802 if (!(self = [super initWithFrame:frame]))
805 [self _initializeWithConfiguration:configuration];
810 - (instancetype)initWithCoder:(NSCoder *)coder
812 if (!(self = [super initWithCoder:coder]))
815 WKWebViewConfiguration *configuration = decodeObjectOfClassForKeyFromCoder([WKWebViewConfiguration class], @"configuration", coder);
816 [self _initializeWithConfiguration:configuration];
818 self.allowsBackForwardNavigationGestures = [coder decodeBoolForKey:@"allowsBackForwardNavigationGestures"];
819 self.customUserAgent = decodeObjectOfClassForKeyFromCoder([NSString class], @"customUserAgent", coder);
820 self.allowsLinkPreview = [coder decodeBoolForKey:@"allowsLinkPreview"];
823 self.allowsMagnification = [coder decodeBoolForKey:@"allowsMagnification"];
824 self.magnification = [coder decodeDoubleForKey:@"magnification"];
830 - (void)encodeWithCoder:(NSCoder *)coder
832 [super encodeWithCoder:coder];
834 [coder encodeObject:_configuration.get() forKey:@"configuration"];
836 [coder encodeBool:self.allowsBackForwardNavigationGestures forKey:@"allowsBackForwardNavigationGestures"];
837 [coder encodeObject:self.customUserAgent forKey:@"customUserAgent"];
838 [coder encodeBool:self.allowsLinkPreview forKey:@"allowsLinkPreview"];
841 [coder encodeBool:self.allowsMagnification forKey:@"allowsMagnification"];
842 [coder encodeDouble:self.magnification forKey:@"magnification"];
849 [_textFinderClient willDestroyView:self];
852 #if PLATFORM(IOS_FAMILY)
853 [_contentView _webViewDestroyed];
855 if (_remoteObjectRegistry)
856 _page->process().processPool().removeMessageReceiver(Messages::RemoteObjectRegistry::messageReceiverName(), _page->pageID());
861 #if PLATFORM(IOS_FAMILY)
862 [_remoteObjectRegistry _invalidate];
863 [[_configuration _contentProviderRegistry] removePage:*_page];
864 [[NSNotificationCenter defaultCenter] removeObserver:self];
865 [_scrollView setInternalDelegate:nil];
867 CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), (CFStringRef)[NSString stringWithUTF8String:kGSEventHardwareKeyboardAvailabilityChangedNotification], nullptr);
870 #if ENABLE(ACCESSIBILITY_EVENTS)
871 CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), nullptr, nullptr);
874 pageToViewMap().remove(_page.get());
879 - (id)valueForUndefinedKey:(NSString *)key {
880 if ([key isEqualToString:@"serverTrust"])
881 return (__bridge id)[self serverTrust];
883 return [super valueForUndefinedKey:key];
886 - (WKWebViewConfiguration *)configuration
888 return [[_configuration copy] autorelease];
891 - (WKBackForwardList *)backForwardList
893 return wrapper(_page->backForwardList());
896 - (id <WKNavigationDelegate>)navigationDelegate
898 return _navigationState->navigationDelegate().autorelease();
901 - (void)setNavigationDelegate:(id <WKNavigationDelegate>)navigationDelegate
903 _page->setNavigationClient(_navigationState->createNavigationClient());
904 _navigationState->setNavigationDelegate(navigationDelegate);
907 - (id <WKUIDelegate>)UIDelegate
909 return _uiDelegate->delegate().autorelease();
912 - (void)setUIDelegate:(id<WKUIDelegate>)UIDelegate
914 _uiDelegate->setDelegate(UIDelegate);
915 #if ENABLE(CONTEXT_MENUS)
916 _page->setContextMenuClient(_uiDelegate->createContextMenuClient());
918 _page->setUIClient(_uiDelegate->createUIClient());
921 - (id <_WKIconLoadingDelegate>)_iconLoadingDelegate
923 return _iconLoadingDelegate->delegate().autorelease();
926 - (void)_setIconLoadingDelegate:(id<_WKIconLoadingDelegate>)iconLoadingDelegate
928 _page->setIconLoadingClient(_iconLoadingDelegate->createIconLoadingClient());
929 _iconLoadingDelegate->setDelegate(iconLoadingDelegate);
932 - (WKNavigation *)loadRequest:(NSURLRequest *)request
934 return wrapper(_page->loadRequest(request));
937 - (WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL
939 if (![URL isFileURL])
940 [NSException raise:NSInvalidArgumentException format:@"%@ is not a file URL", URL];
942 if (![readAccessURL isFileURL])
943 [NSException raise:NSInvalidArgumentException format:@"%@ is not a file URL", readAccessURL];
945 return wrapper(_page->loadFile([URL _web_originalDataAsWTFString], [readAccessURL _web_originalDataAsWTFString]));
948 - (WKNavigation *)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
950 NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
952 return [self loadData:data MIMEType:@"text/html" characterEncodingName:@"UTF-8" baseURL:baseURL];
955 - (WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL
957 return wrapper(_page->loadData({ static_cast<const uint8_t*>(data.bytes), data.length }, MIMEType, characterEncodingName, baseURL.absoluteString));
960 - (WKNavigation *)goToBackForwardListItem:(WKBackForwardListItem *)item
962 return wrapper(_page->goToBackForwardItem(item._item));
967 return _page->pageLoadState().title();
972 return [NSURL _web_URLWithWTFString:_page->pageLoadState().activeURL()];
977 return _page->pageLoadState().isLoading();
980 - (double)estimatedProgress
982 return _page->pageLoadState().estimatedProgress();
985 - (BOOL)hasOnlySecureContent
987 return _page->pageLoadState().hasOnlySecureContent();
990 - (SecTrustRef)serverTrust
992 #if HAVE(SEC_TRUST_SERIALIZATION)
993 auto certificateInfo = _page->pageLoadState().certificateInfo();
994 if (!certificateInfo)
997 return certificateInfo->certificateInfo().trust();
1005 return _page->pageLoadState().canGoBack();
1008 - (BOOL)canGoForward
1010 return _page->pageLoadState().canGoForward();
1013 - (WKNavigation *)goBack
1015 if (self._safeBrowsingWarning)
1016 return [self reload];
1017 return wrapper(_page->goBack());
1020 - (WKNavigation *)goForward
1022 return wrapper(_page->goForward());
1025 - (WKNavigation *)reload
1027 OptionSet<WebCore::ReloadOption> reloadOptions;
1028 if (linkedOnOrAfter(WebKit::SDKVersion::FirstWithExpiredOnlyReloadBehavior))
1029 reloadOptions.add(WebCore::ReloadOption::ExpiredOnly);
1031 return wrapper(_page->reload(reloadOptions));
1034 - (WKNavigation *)reloadFromOrigin
1036 return wrapper(_page->reload(WebCore::ReloadOption::FromOrigin));
1041 _page->stopLoading();
1044 static WKErrorCode callbackErrorCode(WebKit::CallbackBase::Error error)
1047 case WebKit::CallbackBase::Error::None:
1048 ASSERT_NOT_REACHED();
1049 return WKErrorUnknown;
1051 case WebKit::CallbackBase::Error::Unknown:
1052 return WKErrorUnknown;
1054 case WebKit::CallbackBase::Error::ProcessExited:
1055 return WKErrorWebContentProcessTerminated;
1057 case WebKit::CallbackBase::Error::OwnerWasInvalidated:
1058 return WKErrorWebViewInvalidated;
1062 - (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *))completionHandler
1064 [self _evaluateJavaScript:javaScriptString forceUserGesture:YES completionHandler:completionHandler];
1067 - (void)_evaluateJavaScript:(NSString *)javaScriptString forceUserGesture:(BOOL)forceUserGesture completionHandler:(void (^)(id, NSError *))completionHandler
1069 auto handler = adoptNS([completionHandler copy]);
1071 _page->runJavaScriptInMainFrame(javaScriptString, forceUserGesture, [handler](API::SerializedScriptValue* serializedScriptValue, bool hadException, const WebCore::ExceptionDetails& details, WebKit::ScriptValueCallback::Error errorCode) {
1075 if (errorCode != WebKit::ScriptValueCallback::Error::None) {
1076 auto error = createNSError(callbackErrorCode(errorCode));
1077 if (errorCode == WebKit::ScriptValueCallback::Error::OwnerWasInvalidated) {
1078 // The OwnerWasInvalidated callback is synchronous. We don't want to call the block from within it
1079 // because that can trigger re-entrancy bugs in WebKit.
1080 // FIXME: It would be even better if GenericCallback did this for us.
1081 dispatch_async(dispatch_get_main_queue(), [handler, error] {
1082 auto rawHandler = (void (^)(id, NSError *))handler.get();
1083 rawHandler(nil, error.get());
1088 auto rawHandler = (void (^)(id, NSError *))handler.get();
1089 rawHandler(nil, error.get());
1093 auto rawHandler = (void (^)(id, NSError *))handler.get();
1095 ASSERT(!serializedScriptValue);
1097 RetainPtr<NSMutableDictionary> userInfo = adoptNS([[NSMutableDictionary alloc] init]);
1099 [userInfo setObject:localizedDescriptionForErrorCode(WKErrorJavaScriptExceptionOccurred) forKey:NSLocalizedDescriptionKey];
1100 [userInfo setObject:static_cast<NSString *>(details.message) forKey:_WKJavaScriptExceptionMessageErrorKey];
1101 [userInfo setObject:@(details.lineNumber) forKey:_WKJavaScriptExceptionLineNumberErrorKey];
1102 [userInfo setObject:@(details.columnNumber) forKey:_WKJavaScriptExceptionColumnNumberErrorKey];
1104 if (!details.sourceURL.isEmpty())
1105 [userInfo setObject:[NSURL _web_URLWithWTFString:details.sourceURL] forKey:_WKJavaScriptExceptionSourceURLErrorKey];
1107 rawHandler(nil, adoptNS([[NSError alloc] initWithDomain:WKErrorDomain code:WKErrorJavaScriptExceptionOccurred userInfo:userInfo.get()]).get());
1111 if (!serializedScriptValue) {
1112 rawHandler(nil, createNSError(WKErrorJavaScriptResultTypeIsUnsupported).get());
1116 id body = API::SerializedScriptValue::deserialize(serializedScriptValue->internalRepresentation(), 0);
1117 rawHandler(body, nil);
1122 - (void)takeSnapshotWithConfiguration:(WKSnapshotConfiguration *)snapshotConfiguration completionHandler:(void(^)(NSImage *, NSError *))completionHandler
1124 CGRect rectInViewCoordinates = snapshotConfiguration && !CGRectIsNull(snapshotConfiguration.rect) ? snapshotConfiguration.rect : self.bounds;
1125 CGFloat snapshotWidth;
1126 if (snapshotConfiguration)
1127 snapshotWidth = snapshotConfiguration.snapshotWidth.doubleValue ?: rectInViewCoordinates.size.width;
1129 snapshotWidth = self.bounds.size.width;
1131 auto handler = makeBlockPtr(completionHandler);
1132 CGFloat imageScale = snapshotWidth / rectInViewCoordinates.size.width;
1133 CGFloat imageHeight = imageScale * rectInViewCoordinates.size.height;
1135 // Need to scale by device scale factor or the image will be distorted.
1136 CGFloat deviceScale = _page->deviceScaleFactor();
1137 WebCore::IntSize bitmapSize(snapshotWidth, imageHeight);
1138 bitmapSize.scale(deviceScale, deviceScale);
1140 // Software snapshot will not capture elements rendered with hardware acceleration (WebGL, video, etc).
1141 _page->takeSnapshot(WebCore::enclosingIntRect(rectInViewCoordinates), bitmapSize, WebKit::SnapshotOptionsInViewCoordinates, [handler, snapshotWidth, imageHeight](const WebKit::ShareableBitmap::Handle& imageHandle, WebKit::CallbackBase::Error errorCode) {
1142 if (errorCode != WebKit::ScriptValueCallback::Error::None) {
1143 auto error = createNSError(callbackErrorCode(errorCode));
1144 handler(nil, error.get());
1148 auto bitmap = WebKit::ShareableBitmap::create(imageHandle, WebKit::SharedMemory::Protection::ReadOnly);
1149 RetainPtr<CGImageRef> cgImage = bitmap ? bitmap->makeCGImage() : nullptr;
1150 RetainPtr<NSImage> nsImage = adoptNS([[NSImage alloc] initWithCGImage:cgImage.get() size:NSMakeSize(snapshotWidth, imageHeight)]);
1151 handler(nsImage.get(), nil);
1155 #elif PLATFORM(IOS_FAMILY)
1156 - (void)takeSnapshotWithConfiguration:(WKSnapshotConfiguration *)snapshotConfiguration completionHandler:(void(^)(UIImage *, NSError *))completionHandler
1158 CGRect rectInViewCoordinates = snapshotConfiguration && !CGRectIsNull(snapshotConfiguration.rect) ? snapshotConfiguration.rect : self.bounds;
1159 CGFloat snapshotWidth;
1160 if (snapshotConfiguration)
1161 snapshotWidth = snapshotConfiguration.snapshotWidth.doubleValue ?: rectInViewCoordinates.size.width;
1163 snapshotWidth = self.bounds.size.width;
1165 auto handler = makeBlockPtr(completionHandler);
1166 CGFloat deviceScale = _page->deviceScaleFactor();
1168 [self _snapshotRect:rectInViewCoordinates intoImageOfWidth:(snapshotWidth * deviceScale) completionHandler:^(CGImageRef snapshotImage) {
1169 RetainPtr<NSError> error;
1170 RetainPtr<UIImage> uiImage;
1173 error = createNSError(WKErrorUnknown);
1175 uiImage = adoptNS([[UIImage alloc] initWithCGImage:snapshotImage scale:deviceScale orientation:UIImageOrientationUp]);
1177 handler(uiImage.get(), error.get());
1182 - (NSString *)customUserAgent
1184 return _page->customUserAgent();
1187 - (void)setCustomUserAgent:(NSString *)customUserAgent
1189 _page->setCustomUserAgent(customUserAgent);
1192 - (WKPageRef)_pageForTesting
1194 return toAPI(_page.get());
1197 - (WebKit::WebPageProxy *)_page
1202 - (BOOL)allowsLinkPreview
1205 return _impl->allowsLinkPreview();
1206 #elif PLATFORM(IOS_FAMILY)
1207 return _allowsLinkPreview;
1211 - (void)setAllowsLinkPreview:(BOOL)allowsLinkPreview
1214 _impl->setAllowsLinkPreview(allowsLinkPreview);
1216 #elif PLATFORM(IOS_FAMILY)
1217 if (_allowsLinkPreview == allowsLinkPreview)
1220 _allowsLinkPreview = allowsLinkPreview;
1222 #if HAVE(LINK_PREVIEW)
1223 if (_allowsLinkPreview)
1224 [_contentView _registerPreview];
1226 [_contentView _unregisterPreview];
1227 #endif // HAVE(LINK_PREVIEW)
1228 #endif // PLATFORM(IOS_FAMILY)
1231 - (CGSize)_viewportSizeForCSSViewportUnits
1233 return _page->viewportSizeForCSSViewportUnits();
1236 - (void)_setViewportSizeForCSSViewportUnits:(CGSize)viewportSize
1238 auto viewportSizeForViewportUnits = WebCore::IntSize(viewportSize);
1239 if (viewportSizeForViewportUnits.isEmpty())
1240 [NSException raise:NSInvalidArgumentException format:@"Viewport size should not be empty"];
1242 _page->setViewportSizeForCSSViewportUnits(viewportSizeForViewportUnits);
1245 static NSTextAlignment nsTextAlignment(WebKit::TextAlignment alignment)
1247 switch (alignment) {
1248 case WebKit::NoAlignment:
1249 return NSTextAlignmentNatural;
1250 case WebKit::LeftAlignment:
1251 return NSTextAlignmentLeft;
1252 case WebKit::RightAlignment:
1253 return NSTextAlignmentRight;
1254 case WebKit::CenterAlignment:
1255 return NSTextAlignmentCenter;
1256 case WebKit::JustifiedAlignment:
1257 return NSTextAlignmentJustified;
1259 ASSERT_NOT_REACHED();
1260 return NSTextAlignmentNatural;
1263 static NSDictionary *dictionaryRepresentationForEditorState(const WebKit::EditorState& state)
1265 if (state.isMissingPostLayoutData)
1266 return @{ @"post-layout-data" : @NO };
1268 auto& postLayoutData = state.postLayoutData();
1270 @"post-layout-data" : @YES,
1271 @"bold": postLayoutData.typingAttributes & WebKit::AttributeBold ? @YES : @NO,
1272 @"italic": postLayoutData.typingAttributes & WebKit::AttributeItalics ? @YES : @NO,
1273 @"underline": postLayoutData.typingAttributes & WebKit::AttributeUnderline ? @YES : @NO,
1274 @"text-alignment": @(nsTextAlignment(static_cast<WebKit::TextAlignment>(postLayoutData.textAlignment))),
1275 @"text-color": (NSString *)postLayoutData.textColor.cssText()
1279 static _WKSelectionAttributes selectionAttributes(const WebKit::EditorState& editorState, _WKSelectionAttributes previousAttributes)
1281 _WKSelectionAttributes attributes = _WKSelectionAttributeNoSelection;
1282 if (editorState.selectionIsNone)
1285 if (editorState.selectionIsRange)
1286 attributes |= _WKSelectionAttributeIsRange;
1288 attributes |= _WKSelectionAttributeIsCaret;
1290 if (!editorState.isMissingPostLayoutData) {
1291 #if PLATFORM(IOS_FAMILY)
1292 if (editorState.postLayoutData().atStartOfSentence)
1293 attributes |= _WKSelectionAttributeAtStartOfSentence;
1295 } else if (previousAttributes & _WKSelectionAttributeAtStartOfSentence)
1296 attributes |= _WKSelectionAttributeAtStartOfSentence;
1301 - (void)_didChangeEditorState
1303 auto newSelectionAttributes = selectionAttributes(_page->editorState(), _selectionAttributes);
1304 if (_selectionAttributes != newSelectionAttributes) {
1305 NSString *selectionAttributesKey = NSStringFromSelector(@selector(_selectionAttributes));
1306 [self willChangeValueForKey:selectionAttributesKey];
1307 _selectionAttributes = newSelectionAttributes;
1308 [self didChangeValueForKey:selectionAttributesKey];
1311 // FIXME: We should either rename -_webView:editorStateDidChange: to clarify that it's only intended for use when testing,
1312 // or remove it entirely and use -_webView:didChangeFontAttributes: instead once text alignment is supported in the set of
1314 id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)self.UIDelegate;
1315 if ([uiDelegate respondsToSelector:@selector(_webView:editorStateDidChange:)])
1316 [uiDelegate _webView:self editorStateDidChange:dictionaryRepresentationForEditorState(_page->editorState())];
1319 - (_WKSelectionAttributes)_selectionAttributes
1321 return _selectionAttributes;
1324 - (void)_showSafeBrowsingWarning:(const WebKit::SafeBrowsingWarning&)warning completionHandler:(CompletionHandler<void(Variant<WebKit::ContinueUnsafeLoad, URL>&&)>&&)completionHandler
1326 _safeBrowsingWarning = adoptNS([[WKSafeBrowsingWarning alloc] initWithFrame:self.bounds safeBrowsingWarning:warning completionHandler:[weakSelf = WeakObjCPtr<WKWebView>(self), completionHandler = WTFMove(completionHandler)] (auto&& result) mutable {
1327 completionHandler(WTFMove(result));
1328 auto strongSelf = weakSelf.get();
1331 bool navigatesMainFrame = WTF::switchOn(result,
1332 [] (WebKit::ContinueUnsafeLoad continueUnsafeLoad) { return continueUnsafeLoad == WebKit::ContinueUnsafeLoad::Yes; },
1333 [] (const URL&) { return true; }
1335 if (navigatesMainFrame && [strongSelf->_safeBrowsingWarning forMainFrameNavigation])
1337 [std::exchange(strongSelf->_safeBrowsingWarning, nullptr) removeFromSuperview];
1339 [self addSubview:_safeBrowsingWarning.get()];
1342 - (void)_clearSafeBrowsingWarning
1344 [std::exchange(_safeBrowsingWarning, nullptr) removeFromSuperview];
1347 - (void)_clearSafeBrowsingWarningIfForMainFrameNavigation
1349 if ([_safeBrowsingWarning forMainFrameNavigation])
1350 [self _clearSafeBrowsingWarning];
1353 #if ENABLE(ATTACHMENT_ELEMENT)
1355 - (void)_didInsertAttachment:(API::Attachment&)attachment withSource:(NSString *)source
1357 id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)self.UIDelegate;
1358 if ([uiDelegate respondsToSelector:@selector(_webView:didInsertAttachment:withSource:)])
1359 [uiDelegate _webView:self didInsertAttachment:wrapper(attachment) withSource:source];
1362 - (void)_didRemoveAttachment:(API::Attachment&)attachment
1364 id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)self.UIDelegate;
1365 if ([uiDelegate respondsToSelector:@selector(_webView:didRemoveAttachment:)])
1366 [uiDelegate _webView:self didRemoveAttachment:wrapper(attachment)];
1369 - (void)_didInvalidateDataForAttachment:(API::Attachment&)attachment
1371 id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)self.UIDelegate;
1372 if ([uiDelegate respondsToSelector:@selector(_webView:didInvalidateDataForAttachment:)])
1373 [uiDelegate _webView:self didInvalidateDataForAttachment:wrapper(attachment)];
1376 #endif // ENABLE(ATTACHMENT_ELEMENT)
1378 #pragma mark iOS-specific methods
1380 #if PLATFORM(IOS_FAMILY)
1382 - (BOOL)_contentViewIsFirstResponder
1384 return self._currentContentView.isFirstResponder;
1387 - (_WKDragInteractionPolicy)_dragInteractionPolicy
1389 return _dragInteractionPolicy;
1392 - (void)_setDragInteractionPolicy:(_WKDragInteractionPolicy)policy
1394 if (_dragInteractionPolicy == policy)
1397 _dragInteractionPolicy = policy;
1398 #if ENABLE(DRAG_SUPPORT)
1399 [_contentView _didChangeDragInteractionPolicy];
1403 - (void)_populateArchivedSubviews:(NSMutableSet *)encodedViews
1405 [super _populateArchivedSubviews:encodedViews];
1408 [encodedViews removeObject:_scrollView.get()];
1409 if (_customContentFixedOverlayView)
1410 [encodedViews removeObject:_customContentFixedOverlayView.get()];
1413 - (BOOL)_isBackground
1415 if ([self _isDisplayingPDF])
1416 return [_customContentView web_isBackground];
1417 return [_contentView isBackground];
1420 - (void)setFrame:(CGRect)frame
1422 CGRect oldFrame = self.frame;
1423 [super setFrame:frame];
1425 if (!CGSizeEqualToSize(oldFrame.size, frame.size))
1426 [self _frameOrBoundsChanged];
1429 - (void)setBounds:(CGRect)bounds
1431 CGRect oldBounds = self.bounds;
1432 [super setBounds:bounds];
1433 [_customContentFixedOverlayView setFrame:self.bounds];
1435 if (!CGSizeEqualToSize(oldBounds.size, bounds.size))
1436 [self _frameOrBoundsChanged];
1439 - (void)layoutSubviews
1441 [_safeBrowsingWarning setFrame:self.bounds];
1442 [super layoutSubviews];
1443 [self _frameOrBoundsChanged];
1446 - (UIScrollView *)scrollView
1448 return _scrollView.get();
1451 ALLOW_DEPRECATED_DECLARATIONS_BEGIN
1452 - (WKBrowsingContextController *)browsingContextController
1454 return [_contentView browsingContextController];
1456 ALLOW_DEPRECATED_DECLARATIONS_END
1458 - (BOOL)becomeFirstResponder
1460 UIView *currentContentView = self._currentContentView;
1461 if (currentContentView == _contentView && [_contentView superview])
1462 return [_contentView becomeFirstResponderForWebView] || [super becomeFirstResponder];
1464 return [currentContentView becomeFirstResponder] || [super becomeFirstResponder];
1467 - (BOOL)canBecomeFirstResponder
1469 if (self._currentContentView == _contentView)
1470 return [_contentView canBecomeFirstResponderForWebView];
1475 - (BOOL)resignFirstResponder
1477 if ([_contentView isFirstResponder])
1478 return [_contentView resignFirstResponderForWebView];
1480 return [super resignFirstResponder];
1483 FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_ACTION_TO_WKCONTENTVIEW)
1485 - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
1487 #define FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW(_action) \
1488 if (action == @selector(_action:)) \
1489 return self.usesStandardContentView && [_contentView canPerformActionForWebView:action withSender:sender];
1491 FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW)
1492 FOR_EACH_PRIVATE_WKCONTENTVIEW_ACTION(FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW)
1493 FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW(_setTextColor:sender)
1494 FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW(_setFontSize:sender)
1495 FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW(_setFont:sender)
1497 #undef FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW
1499 return [super canPerformAction:action withSender:sender];
1502 - (id)targetForAction:(SEL)action withSender:(id)sender
1504 #define FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_action) \
1505 if (action == @selector(_action:) && self.usesStandardContentView) \
1506 return [_contentView targetForActionForWebView:action withSender:sender];
1508 FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW)
1509 FOR_EACH_PRIVATE_WKCONTENTVIEW_ACTION(FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW)
1510 FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_setTextColor:sender)
1511 FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_setFontSize:sender)
1512 FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_setFont:sender)
1514 #undef FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW
1516 return [super targetForAction:action withSender:sender];
1519 static inline CGFloat floorToDevicePixel(CGFloat input, float deviceScaleFactor)
1521 return CGFloor(input * deviceScaleFactor) / deviceScaleFactor;
1524 static inline bool pointsEqualInDevicePixels(CGPoint a, CGPoint b, float deviceScaleFactor)
1526 return fabs(a.x * deviceScaleFactor - b.x * deviceScaleFactor) < std::numeric_limits<float>::epsilon()
1527 && fabs(a.y * deviceScaleFactor - b.y * deviceScaleFactor) < std::numeric_limits<float>::epsilon();
1530 static CGSize roundScrollViewContentSize(const WebKit::WebPageProxy& page, CGSize contentSize)
1532 float deviceScaleFactor = page.deviceScaleFactor();
1533 return CGSizeMake(floorToDevicePixel(contentSize.width, deviceScaleFactor), floorToDevicePixel(contentSize.height, deviceScaleFactor));
1536 - (UIView *)_currentContentView
1538 return _customContentView ? [_customContentView web_contentView] : _contentView.get();
1541 - (WKWebViewContentProviderRegistry *)_contentProviderRegistry
1543 return [_configuration _contentProviderRegistry];
1546 - (WKSelectionGranularity)_selectionGranularity
1548 return [_configuration selectionGranularity];
1551 - (void)_setHasCustomContentView:(BOOL)pageHasCustomContentView loadedMIMEType:(const WTF::String&)mimeType
1553 if (pageHasCustomContentView) {
1554 [_customContentView removeFromSuperview];
1555 [_customContentFixedOverlayView removeFromSuperview];
1557 Class representationClass = [[_configuration _contentProviderRegistry] providerForMIMEType:mimeType];
1558 ASSERT(representationClass);
1559 _customContentView = adoptNS([[representationClass alloc] web_initWithFrame:self.bounds webView:self mimeType:mimeType]);
1560 _customContentFixedOverlayView = adoptNS([[UIView alloc] initWithFrame:self.bounds]);
1561 [_customContentFixedOverlayView layer].name = @"CustomContentFixedOverlay";
1562 [_customContentFixedOverlayView setUserInteractionEnabled:NO];
1564 [[_contentView unscaledView] removeFromSuperview];
1565 [_contentView removeFromSuperview];
1566 [_scrollView addSubview:_customContentView.get()];
1567 [self addSubview:_customContentFixedOverlayView.get()];
1569 [_customContentView web_setMinimumSize:self.bounds.size];
1570 [_customContentView web_setFixedOverlayView:_customContentFixedOverlayView.get()];
1572 _scrollViewBackgroundColor = WebCore::Color();
1573 [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1575 [self _setAvoidsUnsafeArea:NO];
1576 } else if (_customContentView) {
1577 [_customContentView removeFromSuperview];
1578 _customContentView = nullptr;
1580 [_customContentFixedOverlayView removeFromSuperview];
1581 _customContentFixedOverlayView = nullptr;
1583 [_scrollView addSubview:_contentView.get()];
1584 [_scrollView addSubview:[_contentView unscaledView]];
1585 [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
1587 [_customContentFixedOverlayView setFrame:self.bounds];
1588 [self addSubview:_customContentFixedOverlayView.get()];
1591 if (self.isFirstResponder) {
1592 UIView *currentContentView = self._currentContentView;
1593 if (currentContentView == _contentView ? [_contentView canBecomeFirstResponderForWebView] : currentContentView.canBecomeFirstResponder)
1594 [currentContentView becomeFirstResponder];
1598 - (void)_didFinishLoadingDataForCustomContentProviderWithSuggestedFilename:(const String&)suggestedFilename data:(NSData *)data
1600 ASSERT(_customContentView);
1601 [_customContentView web_setContentProviderData:data suggestedFilename:suggestedFilename];
1603 // FIXME: It may make more sense for custom content providers to invoke this when they're ready,
1604 // because there's no guarantee that all custom content providers will lay out synchronously.
1605 _page->didLayoutForCustomContentProvider();
1608 - (void)_handleKeyUIEvent:(::UIEvent *)event
1610 // We only want to handle key events from the hardware keyboard when we are
1611 // first responder and a custom content view is installed; otherwise,
1612 // WKContentView will be the first responder and expects to get key events directly.
1613 if ([self isFirstResponder] && event._hidEvent) {
1614 if ([_customContentView respondsToSelector:@selector(web_handleKeyEvent:)]) {
1615 if ([_customContentView web_handleKeyEvent:event])
1620 [super _handleKeyUIEvent:event];
1623 - (void)_willInvokeUIScrollViewDelegateCallback
1625 _delayUpdateVisibleContentRects = YES;
1628 - (void)_didInvokeUIScrollViewDelegateCallback
1630 _delayUpdateVisibleContentRects = NO;
1631 if (_hadDelayedUpdateVisibleContentRects) {
1632 _hadDelayedUpdateVisibleContentRects = NO;
1633 [self _scheduleVisibleContentRectUpdate];
1637 static CGFloat contentZoomScale(WKWebView *webView)
1639 CGFloat scale = webView._currentContentView.layer.affineTransform.a;
1640 ASSERT(scale == [webView->_scrollView zoomScale]);
1644 static WebCore::Color baseScrollViewBackgroundColor(WKWebView *webView)
1646 if (webView->_customContentView)
1647 return [webView->_customContentView backgroundColor].CGColor;
1649 if (webView->_gestureController) {
1650 WebCore::Color color = webView->_gestureController->backgroundColorForCurrentSnapshot();
1651 if (color.isValid())
1655 return webView->_page->pageExtendedBackgroundColor();
1658 static WebCore::Color scrollViewBackgroundColor(WKWebView *webView)
1660 if (!webView.opaque)
1661 return WebCore::Color::transparent;
1663 WebCore::Color color = baseScrollViewBackgroundColor(webView);
1665 if (!color.isValid())
1666 color = WebCore::Color::white;
1668 CGFloat zoomScale = contentZoomScale(webView);
1669 CGFloat minimumZoomScale = [webView->_scrollView minimumZoomScale];
1670 if (zoomScale < minimumZoomScale) {
1672 CGFloat opacity = std::max<CGFloat>(1 - slope * (minimumZoomScale - zoomScale), 0);
1673 color = WebCore::colorWithOverrideAlpha(color.rgb(), opacity);
1679 - (void)_updateScrollViewBackground
1681 WebCore::Color color = scrollViewBackgroundColor(self);
1683 if (_scrollViewBackgroundColor == color)
1686 _scrollViewBackgroundColor = color;
1688 auto uiBackgroundColor = adoptNS([[UIColor alloc] initWithCGColor:cachedCGColor(color)]);
1689 [_scrollView setBackgroundColor:uiBackgroundColor.get()];
1691 // Update the indicator style based on the lightness/darkness of the background color.
1692 double hue, saturation, lightness;
1693 color.getHSL(hue, saturation, lightness);
1694 if (lightness <= .5 && color.isVisible())
1695 [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleWhite];
1697 [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleDefault];
1700 - (void)_videoControlsManagerDidChange
1702 #if ENABLE(FULLSCREEN_API)
1703 if (_fullScreenWindowController)
1704 [_fullScreenWindowController videoControlsManagerDidChange];
1708 - (CGPoint)_initialContentOffsetForScrollView
1710 auto combinedUnobscuredAndScrollViewInset = [self _computedContentInset];
1711 return CGPointMake(-combinedUnobscuredAndScrollViewInset.left, -combinedUnobscuredAndScrollViewInset.top);
1714 - (CGPoint)_contentOffsetAdjustedForObscuredInset:(CGPoint)point
1716 CGPoint result = point;
1717 UIEdgeInsets contentInset = [self _computedObscuredInset];
1719 result.x -= contentInset.left;
1720 result.y -= contentInset.top;
1725 - (UIRectEdge)_effectiveObscuredInsetEdgesAffectedBySafeArea
1727 if (![self usesStandardContentView])
1728 return UIRectEdgeAll;
1729 return _obscuredInsetEdgesAffectedBySafeArea;
1732 - (UIEdgeInsets)_computedObscuredInset
1734 if (!linkedOnOrAfter(WebKit::SDKVersion::FirstWhereScrollViewContentInsetsAreNotObscuringInsets)) {
1735 // For binary compability with third party apps, treat scroll view content insets as obscuring insets when the app is compiled
1736 // against a WebKit version without the fix in r229641.
1737 return [self _computedContentInset];
1740 if (_haveSetObscuredInsets)
1741 return _obscuredInsets;
1744 if (self._safeAreaShouldAffectObscuredInsets)
1745 return UIEdgeInsetsAdd(UIEdgeInsetsZero, self._scrollViewSystemContentInset, self._effectiveObscuredInsetEdgesAffectedBySafeArea);
1748 return UIEdgeInsetsZero;
1751 - (UIEdgeInsets)_computedContentInset
1753 if (_haveSetObscuredInsets)
1754 return _obscuredInsets;
1756 UIEdgeInsets insets = [_scrollView contentInset];
1759 if (self._safeAreaShouldAffectObscuredInsets)
1760 insets = UIEdgeInsetsAdd(insets, self._scrollViewSystemContentInset, self._effectiveObscuredInsetEdgesAffectedBySafeArea);
1766 - (UIEdgeInsets)_computedUnobscuredSafeAreaInset
1768 if (_haveSetUnobscuredSafeAreaInsets)
1769 return _unobscuredSafeAreaInsets;
1772 if (!self._safeAreaShouldAffectObscuredInsets)
1773 return self.safeAreaInsets;
1776 return UIEdgeInsetsZero;
1779 - (void)_processWillSwapOrDidExit
1781 // FIXME: Which ones of these need to be done in the process swap case and which ones in the exit case?
1782 [self _hidePasswordView];
1783 [self _cancelAnimatedResize];
1785 _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
1786 _initialScaleFactor = 1;
1787 _hasCommittedLoadForMainFrame = NO;
1788 _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1789 _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
1790 _waitingForEndAnimatedResize = NO;
1791 _waitingForCommitAfterAnimatedResize = NO;
1792 _animatedResizeOriginalContentWidth = 0;
1793 [_contentView setHidden:NO];
1794 _scrollOffsetToRestore = WTF::nullopt;
1795 _unobscuredCenterToRestore = WTF::nullopt;
1796 _scrollViewBackgroundColor = WebCore::Color();
1797 _delayUpdateVisibleContentRects = NO;
1798 _hadDelayedUpdateVisibleContentRects = NO;
1799 _currentlyAdjustingScrollViewInsetsForKeyboard = NO;
1800 _lastSentViewLayoutSize = WTF::nullopt;
1801 _lastSentMaximumUnobscuredSize = WTF::nullopt;
1802 _lastSentDeviceOrientation = WTF::nullopt;
1804 _frozenVisibleContentRect = WTF::nullopt;
1805 _frozenUnobscuredContentRect = WTF::nullopt;
1807 _firstPaintAfterCommitLoadTransactionID = 0;
1808 _firstTransactionIDAfterPageRestore = WTF::nullopt;
1810 _hasScheduledVisibleRectUpdate = NO;
1811 _commitDidRestoreScrollPosition = NO;
1813 _avoidsUnsafeArea = YES;
1816 - (void)_processWillSwap
1818 RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _processWillSwap]", self);
1819 [self _processWillSwapOrDidExit];
1822 - (void)_processDidExit
1824 RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _processDidExit]", self);
1826 [self _processWillSwapOrDidExit];
1828 [_contentView setFrame:self.bounds];
1829 [_scrollView setBackgroundColor:[UIColor whiteColor]];
1830 [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1831 [_scrollView setZoomScale:1];
1835 - (void)_didRelaunchProcess
1837 RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didRelaunchProcess]", self);
1838 _hasScheduledVisibleRectUpdate = NO;
1839 _visibleContentRectUpdateScheduledFromScrollViewInStableState = YES;
1842 - (void)_didCommitLoadForMainFrame
1844 _firstPaintAfterCommitLoadTransactionID = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1846 _hasCommittedLoadForMainFrame = YES;
1847 _needsResetViewStateAfterCommitLoadForMainFrame = YES;
1849 [_scrollView _stopScrollingAndZoomingAnimations];
1852 static CGPoint contentOffsetBoundedInValidRange(UIScrollView *scrollView, CGPoint contentOffset)
1854 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1855 UIEdgeInsets contentInsets = scrollView.adjustedContentInset;
1857 UIEdgeInsets contentInsets = scrollView.contentInset;
1860 CGSize contentSize = scrollView.contentSize;
1861 CGSize scrollViewSize = scrollView.bounds.size;
1863 CGPoint minimumContentOffset = CGPointMake(-contentInsets.left, -contentInsets.top);
1864 CGPoint maximumContentOffset = CGPointMake(std::max(minimumContentOffset.x, contentSize.width + contentInsets.right - scrollViewSize.width), std::max(minimumContentOffset.y, contentSize.height + contentInsets.bottom - scrollViewSize.height));
1866 return CGPointMake(std::max(std::min(contentOffset.x, maximumContentOffset.x), minimumContentOffset.x), std::max(std::min(contentOffset.y, maximumContentOffset.y), minimumContentOffset.y));
1869 static void changeContentOffsetBoundedInValidRange(UIScrollView *scrollView, WebCore::FloatPoint contentOffset)
1871 scrollView.contentOffset = contentOffsetBoundedInValidRange(scrollView, contentOffset);
1874 - (WebCore::FloatRect)visibleRectInViewCoordinates
1876 WebCore::FloatRect bounds = self.bounds;
1877 bounds.moveBy([_scrollView contentOffset]);
1878 WebCore::FloatRect contentViewBounds = [_contentView bounds];
1879 bounds.intersect(contentViewBounds);
1883 // WebCore stores the page scale factor as float instead of double. When we get a scale from WebCore,
1884 // we need to ignore differences that are within a small rounding error on floats.
1885 static inline bool areEssentiallyEqualAsFloat(float a, float b)
1887 return WTF::areEssentiallyEqual(a, b);
1890 - (void)_didCommitLayerTreeDuringAnimatedResize:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
1892 auto updateID = layerTreeTransaction.dynamicViewportSizeUpdateID();
1893 if (updateID && *updateID == _currentDynamicViewportSizeUpdateID) {
1894 double pageScale = layerTreeTransaction.pageScaleFactor();
1895 WebCore::IntPoint scrollPosition = layerTreeTransaction.scrollPosition();
1897 CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
1898 double currentTargetScale = animatingScaleTarget * [[_contentView layer] transform].m11;
1899 double scale = pageScale / currentTargetScale;
1900 _resizeAnimationTransformAdjustments = CATransform3DMakeScale(scale, scale, 1);
1902 CGPoint newContentOffset = [self _contentOffsetAdjustedForObscuredInset:CGPointMake(scrollPosition.x() * pageScale, scrollPosition.y() * pageScale)];
1903 CGPoint currentContentOffset = [_scrollView contentOffset];
1905 _resizeAnimationTransformAdjustments.m41 = (currentContentOffset.x - newContentOffset.x) / animatingScaleTarget;
1906 _resizeAnimationTransformAdjustments.m42 = (currentContentOffset.y - newContentOffset.y) / animatingScaleTarget;
1908 [_resizeAnimationView layer].sublayerTransform = _resizeAnimationTransformAdjustments;
1910 // If we've already passed endAnimatedResize, immediately complete
1911 // the resize when we have an up-to-date layer tree. Otherwise,
1912 // we will defer completion until endAnimatedResize.
1913 _waitingForCommitAfterAnimatedResize = NO;
1914 if (!_waitingForEndAnimatedResize)
1915 [self _didCompleteAnimatedResize];
1920 // If a commit arrives during the live part of a resize but before the
1921 // layer tree takes the current resize into account, it could change the
1922 // WKContentView's size. Update the resizeAnimationView's scale to ensure
1923 // we continue to fill the width of the resize target.
1925 if (_waitingForEndAnimatedResize)
1928 auto newViewLayoutSize = [self activeViewLayoutSize:self.bounds];
1929 CGFloat resizeAnimationViewScale = _animatedResizeOriginalContentWidth / newViewLayoutSize.width();
1930 [[_resizeAnimationView layer] setSublayerTransform:CATransform3DMakeScale(resizeAnimationViewScale, resizeAnimationViewScale, 1)];
1933 - (void)_didCommitLayerTree:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
1935 if (![self usesStandardContentView])
1938 LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _didCommitLayerTree:] transactionID " << layerTreeTransaction.transactionID() << " _dynamicViewportUpdateMode " << (int)_dynamicViewportUpdateMode);
1940 bool needUpdateVisibleContentRects = _page->updateLayoutViewportParameters(layerTreeTransaction);
1942 if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing) {
1943 [self _didCommitLayerTreeDuringAnimatedResize:layerTreeTransaction];
1947 if (_resizeAnimationView)
1948 RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didCommitLayerTree:] - dynamicViewportUpdateMode is NotResizing, but still have a live resizeAnimationView (unpaired begin/endAnimatedResize?)", self);
1950 CGSize newContentSize = roundScrollViewContentSize(*_page, [_contentView frame].size);
1951 [_scrollView _setContentSizePreservingContentOffsetDuringRubberband:newContentSize];
1953 [_scrollView setMinimumZoomScale:layerTreeTransaction.minimumScaleFactor()];
1954 [_scrollView setMaximumZoomScale:layerTreeTransaction.maximumScaleFactor()];
1955 [_scrollView setZoomEnabled:layerTreeTransaction.allowsUserScaling()];
1956 if (!layerTreeTransaction.scaleWasSetByUIProcess() && ![_scrollView isZooming] && ![_scrollView isZoomBouncing] && ![_scrollView _isAnimatingZoom] && [_scrollView zoomScale] != layerTreeTransaction.pageScaleFactor()) {
1957 LOG_WITH_STREAM(VisibleRects, stream << " updating scroll view with pageScaleFactor " << layerTreeTransaction.pageScaleFactor());
1958 [_scrollView setZoomScale:layerTreeTransaction.pageScaleFactor()];
1961 _viewportMetaTagWidth = layerTreeTransaction.viewportMetaTagWidth();
1962 _viewportMetaTagWidthWasExplicit = layerTreeTransaction.viewportMetaTagWidthWasExplicit();
1963 _viewportMetaTagCameFromImageDocument = layerTreeTransaction.viewportMetaTagCameFromImageDocument();
1964 _initialScaleFactor = layerTreeTransaction.initialScaleFactor();
1965 if (_page->inStableState() && layerTreeTransaction.isInStableState() && [_stableStatePresentationUpdateCallbacks count]) {
1966 for (dispatch_block_t action in _stableStatePresentationUpdateCallbacks.get())
1969 [_stableStatePresentationUpdateCallbacks removeAllObjects];
1970 _stableStatePresentationUpdateCallbacks = nil;
1973 if (![_contentView _mayDisableDoubleTapGesturesDuringSingleTap])
1974 [_contentView _setDoubleTapGesturesEnabled:self._allowsDoubleTapGestures];
1976 [self _updateScrollViewBackground];
1977 [self _setAvoidsUnsafeArea:layerTreeTransaction.avoidsUnsafeArea()];
1979 if (_gestureController)
1980 _gestureController->setRenderTreeSize(layerTreeTransaction.renderTreeSize());
1982 if (_needsResetViewStateAfterCommitLoadForMainFrame && layerTreeTransaction.transactionID() >= _firstPaintAfterCommitLoadTransactionID) {
1983 _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1984 [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1985 if (_observedRenderingProgressEvents & _WKRenderingProgressEventFirstPaint)
1986 _navigationState->didFirstPaint();
1988 needUpdateVisibleContentRects = true;
1991 if (_firstTransactionIDAfterPageRestore && layerTreeTransaction.transactionID() >= _firstTransactionIDAfterPageRestore.value()) {
1992 if (_scrollOffsetToRestore) {
1993 WebCore::FloatPoint scaledScrollOffset = _scrollOffsetToRestore.value();
1994 _scrollOffsetToRestore = WTF::nullopt;
1996 if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1997 scaledScrollOffset.scale(_scaleToRestore);
1998 WebCore::FloatPoint contentOffsetInScrollViewCoordinates = scaledScrollOffset - WebCore::FloatSize(_obscuredInsetsWhenSaved.left(), _obscuredInsetsWhenSaved.top());
2000 changeContentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
2001 _commitDidRestoreScrollPosition = YES;
2004 needUpdateVisibleContentRects = true;
2007 if (_unobscuredCenterToRestore) {
2008 WebCore::FloatPoint unobscuredCenterToRestore = _unobscuredCenterToRestore.value();
2009 _unobscuredCenterToRestore = WTF::nullopt;
2011 if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
2012 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, _obscuredInsets);
2013 WebCore::FloatSize unobscuredContentSizeAtNewScale = WebCore::FloatSize(unobscuredRect.size) / _scaleToRestore;
2014 WebCore::FloatPoint topLeftInDocumentCoordinates = unobscuredCenterToRestore - unobscuredContentSizeAtNewScale / 2;
2016 topLeftInDocumentCoordinates.scale(_scaleToRestore);
2017 topLeftInDocumentCoordinates.moveBy(WebCore::FloatPoint(-_obscuredInsets.left, -_obscuredInsets.top));
2019 changeContentOffsetBoundedInValidRange(_scrollView.get(), topLeftInDocumentCoordinates);
2022 needUpdateVisibleContentRects = true;
2025 if (_gestureController)
2026 _gestureController->didRestoreScrollPosition();
2028 _firstTransactionIDAfterPageRestore = WTF::nullopt;
2031 if (needUpdateVisibleContentRects)
2032 [self _scheduleVisibleContentRectUpdate];
2034 if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
2035 scrollPerfData->didCommitLayerTree([self visibleRectInViewCoordinates]);
2038 - (void)_layerTreeCommitComplete
2040 _commitDidRestoreScrollPosition = NO;
2043 - (void)_couldNotRestorePageState
2045 // The gestureController may be waiting for the scroll position to be restored
2046 // in order to remove the swipe snapshot. Since the scroll position could not be
2047 // restored, tell the gestureController it was restored so that it no longer waits
2049 if (_gestureController)
2050 _gestureController->didRestoreScrollPosition();
2053 - (void)_restorePageScrollPosition:(Optional<WebCore::FloatPoint>)scrollPosition scrollOrigin:(WebCore::FloatPoint)scrollOrigin previousObscuredInset:(WebCore::FloatBoxExtent)obscuredInsets scale:(double)scale
2055 if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing)
2058 if (![self usesStandardContentView])
2061 _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
2063 _scrollOffsetToRestore = WebCore::ScrollableArea::scrollOffsetFromPosition(WebCore::FloatPoint(scrollPosition.value()), WebCore::toFloatSize(scrollOrigin));
2065 _scrollOffsetToRestore = WTF::nullopt;
2067 _obscuredInsetsWhenSaved = obscuredInsets;
2068 _scaleToRestore = scale;
2071 - (void)_restorePageStateToUnobscuredCenter:(Optional<WebCore::FloatPoint>)center scale:(double)scale
2073 if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing)
2076 if (![self usesStandardContentView])
2079 _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
2080 _unobscuredCenterToRestore = center;
2082 _scaleToRestore = scale;
2085 - (RefPtr<WebKit::ViewSnapshot>)_takeViewSnapshot
2087 #if HAVE(CORE_ANIMATION_RENDER_SERVER)
2088 float deviceScale = WebCore::screenScaleFactor();
2089 WebCore::FloatSize snapshotSize(self.bounds.size);
2090 snapshotSize.scale(deviceScale);
2092 CATransform3D transform = CATransform3DMakeScale(deviceScale, deviceScale, 1);
2095 WebCore::IOSurface::Format snapshotFormat = WebCore::screenSupportsExtendedColor() ? WebCore::IOSurface::Format::RGB10 : WebCore::IOSurface::Format::RGBA;
2096 auto surface = WebCore::IOSurface::create(WebCore::expandedIntSize(snapshotSize), WebCore::sRGBColorSpaceRef(), snapshotFormat);
2099 CARenderServerRenderLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, reinterpret_cast<uint64_t>(self.layer), surface->surface(), 0, 0, &transform);
2101 #if HAVE(IOSURFACE_ACCELERATOR)
2102 WebCore::IOSurface::Format compressedFormat = WebCore::IOSurface::Format::YUV422;
2103 if (WebCore::IOSurface::allowConversionFromFormatToFormat(snapshotFormat, compressedFormat)) {
2104 auto viewSnapshot = WebKit::ViewSnapshot::create(nullptr);
2105 WebCore::IOSurface::convertToFormat(WTFMove(surface), WebCore::IOSurface::Format::YUV422, [viewSnapshot = viewSnapshot.copyRef()](std::unique_ptr<WebCore::IOSurface> convertedSurface) {
2106 if (convertedSurface)
2107 viewSnapshot->setSurface(WTFMove(convertedSurface));
2110 return viewSnapshot;
2112 #endif // HAVE(IOSURFACE_ACCELERATOR)
2114 return WebKit::ViewSnapshot::create(WTFMove(surface));
2115 #else // HAVE(IOSURFACE)
2116 uint32_t slotID = [WebKit::ViewSnapshotStore::snapshottingContext() createImageSlot:snapshotSize hasAlpha:YES];
2121 CARenderServerCaptureLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, (uint64_t)self.layer, slotID, 0, 0, &transform);
2122 WebCore::IntSize imageSize = WebCore::expandedIntSize(WebCore::FloatSize(snapshotSize));
2123 return WebKit::ViewSnapshot::create(slotID, imageSize, (imageSize.area() * 4).unsafeGet());
2124 #endif // HAVE(IOSURFACE)
2125 #else // HAVE(CORE_ANIMATION_RENDER_SERVER)
2130 - (void)_zoomToPoint:(WebCore::FloatPoint)point atScale:(double)scale animated:(BOOL)animated
2132 CFTimeInterval duration = 0;
2133 CGFloat zoomScale = contentZoomScale(self);
2136 const double maximumZoomDuration = 0.4;
2137 const double minimumZoomDuration = 0.1;
2138 const double zoomDurationFactor = 0.3;
2140 duration = std::min(fabs(log(zoomScale) - log(scale)) * zoomDurationFactor + minimumZoomDuration, maximumZoomDuration);
2143 if (scale != zoomScale)
2144 _page->willStartUserTriggeredZooming();
2146 LOG_WITH_STREAM(VisibleRects, stream << "_zoomToPoint:" << point << " scale: " << scale << " duration:" << duration);
2148 [_scrollView _zoomToCenter:point scale:scale duration:duration];
2151 - (void)_zoomToRect:(WebCore::FloatRect)targetRect atScale:(double)scale origin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2153 // FIXME: Some of this could be shared with _scrollToRect.
2154 const double visibleRectScaleChange = contentZoomScale(self) / scale;
2155 const WebCore::FloatRect visibleRect([self convertRect:self.bounds toView:self._currentContentView]);
2156 const WebCore::FloatRect unobscuredRect([self _contentRectForUserInteraction]);
2158 const WebCore::FloatSize topLeftObscuredInsetAfterZoom((unobscuredRect.minXMinYCorner() - visibleRect.minXMinYCorner()) * visibleRectScaleChange);
2159 const WebCore::FloatSize bottomRightObscuredInsetAfterZoom((visibleRect.maxXMaxYCorner() - unobscuredRect.maxXMaxYCorner()) * visibleRectScaleChange);
2161 const WebCore::FloatSize unobscuredRectSizeAfterZoom(unobscuredRect.size() * visibleRectScaleChange);
2163 // Center to the target rect.
2164 WebCore::FloatPoint unobscuredRectLocationAfterZoom = targetRect.location() - (unobscuredRectSizeAfterZoom - targetRect.size()) * 0.5;
2166 // Center to the tap point instead in case the target rect won't fit in a direction.
2167 if (targetRect.width() > unobscuredRectSizeAfterZoom.width())
2168 unobscuredRectLocationAfterZoom.setX(origin.x() - unobscuredRectSizeAfterZoom.width() / 2);
2169 if (targetRect.height() > unobscuredRectSizeAfterZoom.height())
2170 unobscuredRectLocationAfterZoom.setY(origin.y() - unobscuredRectSizeAfterZoom.height() / 2);
2172 // We have computed where we want the unobscured rect to be. Now adjust for the obscuring insets.
2173 WebCore::FloatRect visibleRectAfterZoom(unobscuredRectLocationAfterZoom, unobscuredRectSizeAfterZoom);
2174 visibleRectAfterZoom.move(-topLeftObscuredInsetAfterZoom);
2175 visibleRectAfterZoom.expand(topLeftObscuredInsetAfterZoom + bottomRightObscuredInsetAfterZoom);
2177 [self _zoomToPoint:visibleRectAfterZoom.center() atScale:scale animated:animated];
2180 static WebCore::FloatPoint constrainContentOffset(WebCore::FloatPoint contentOffset, WebCore::FloatSize contentSize, WebCore::FloatSize unobscuredContentSize)
2182 WebCore::FloatSize maximumContentOffset = contentSize - unobscuredContentSize;
2183 return contentOffset.constrainedBetween(WebCore::FloatPoint(), WebCore::FloatPoint(maximumContentOffset));
2186 - (void)_scrollToContentScrollPosition:(WebCore::FloatPoint)scrollPosition scrollOrigin:(WebCore::IntPoint)scrollOrigin
2188 if (_commitDidRestoreScrollPosition || _dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing)
2191 WebCore::FloatPoint contentOffset = WebCore::ScrollableArea::scrollOffsetFromPosition(scrollPosition, toFloatSize(scrollOrigin));
2193 WebCore::FloatPoint scaledOffset = contentOffset;
2194 CGFloat zoomScale = contentZoomScale(self);
2195 scaledOffset.scale(zoomScale);
2197 CGPoint contentOffsetInScrollViewCoordinates = [self _contentOffsetAdjustedForObscuredInset:scaledOffset];
2198 contentOffsetInScrollViewCoordinates = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
2200 [_scrollView _stopScrollingAndZoomingAnimations];
2202 if (!CGPointEqualToPoint(contentOffsetInScrollViewCoordinates, [_scrollView contentOffset]))
2203 [_scrollView setContentOffset:contentOffsetInScrollViewCoordinates];
2205 // If we haven't changed anything, there would not be any VisibleContentRect update sent to the content.
2206 // The WebProcess would keep the invalid contentOffset as its scroll position.
2207 // To synchronize the WebProcess with what is on screen, we send the VisibleContentRect again.
2208 _page->resendLastVisibleContentRects();
2212 - (BOOL)_scrollToRect:(WebCore::FloatRect)targetRect origin:(WebCore::FloatPoint)origin minimumScrollDistance:(float)minimumScrollDistance
2214 WebCore::FloatRect unobscuredContentRect([self _contentRectForUserInteraction]);
2215 WebCore::FloatPoint unobscuredContentOffset = unobscuredContentRect.location();
2216 WebCore::FloatSize contentSize([self._currentContentView bounds].size);
2218 // Center the target rect in the scroll view.
2219 // If the target doesn't fit in the scroll view, center on the gesture location instead.
2220 WebCore::FloatPoint newUnobscuredContentOffset;
2221 if (targetRect.width() <= unobscuredContentRect.width())
2222 newUnobscuredContentOffset.setX(targetRect.x() - (unobscuredContentRect.width() - targetRect.width()) / 2);
2224 newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
2225 if (targetRect.height() <= unobscuredContentRect.height())
2226 newUnobscuredContentOffset.setY(targetRect.y() - (unobscuredContentRect.height() - targetRect.height()) / 2);
2228 newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
2229 newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
2231 if (unobscuredContentOffset == newUnobscuredContentOffset) {
2232 if (targetRect.width() > unobscuredContentRect.width())
2233 newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
2234 if (targetRect.height() > unobscuredContentRect.height())
2235 newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
2236 newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
2239 WebCore::FloatSize scrollViewOffsetDelta = newUnobscuredContentOffset - unobscuredContentOffset;
2240 scrollViewOffsetDelta.scale(contentZoomScale(self));
2242 float scrollDistance = scrollViewOffsetDelta.diagonalLength();
2243 if (scrollDistance < minimumScrollDistance)
2246 [_contentView willStartZoomOrScroll];
2248 LOG_WITH_STREAM(VisibleRects, stream << "_scrollToRect: scrolling to " << [_scrollView contentOffset] + scrollViewOffsetDelta);
2250 [_scrollView setContentOffset:([_scrollView contentOffset] + scrollViewOffsetDelta) animated:YES];
2254 - (void)_zoomOutWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2256 [self _zoomToPoint:origin atScale:[_scrollView minimumZoomScale] animated:animated];
2259 - (void)_zoomToInitialScaleWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2261 ASSERT(_initialScaleFactor > 0);
2262 [self _zoomToPoint:origin atScale:_initialScaleFactor animated:animated];
2265 // focusedElementRect and selectionRect are both in document coordinates.
2266 - (void)_zoomToFocusRect:(const WebCore::FloatRect&)focusedElementRectInDocumentCoordinates selectionRect:(const WebCore::FloatRect&)selectionRectInDocumentCoordinates insideFixed:(BOOL)insideFixed
2267 fontSize:(float)fontSize minimumScale:(double)minimumScale maximumScale:(double)maximumScale allowScaling:(BOOL)allowScaling forceScroll:(BOOL)forceScroll
2269 LOG_WITH_STREAM(VisibleRects, stream << "_zoomToFocusRect:" << focusedElementRectInDocumentCoordinates << " selectionRect:" << selectionRectInDocumentCoordinates);
2270 UNUSED_PARAM(insideFixed);
2272 const double minimumHeightToShowContentAboveKeyboard = 106;
2273 const CFTimeInterval formControlZoomAnimationDuration = 0.25;
2274 const double caretOffsetFromWindowEdge = 8;
2276 UIWindow *window = [_scrollView window];
2278 // Find the portion of the view that is visible on the screen.
2279 UIViewController *topViewController = [[[_scrollView _viewControllerForAncestor] _rootAncestorViewController] _viewControllerForSupportedInterfaceOrientations];
2280 UIView *fullScreenView = topViewController.view;
2281 if (!fullScreenView)
2282 fullScreenView = window;
2284 CGRect unobscuredScrollViewRectInWebViewCoordinates = UIEdgeInsetsInsetRect([self bounds], _obscuredInsets);
2285 CGRect visibleScrollViewBoundsInWebViewCoordinates = CGRectIntersection(unobscuredScrollViewRectInWebViewCoordinates, [fullScreenView convertRect:[fullScreenView bounds] toView:self]);
2286 CGRect formAssistantFrameInWebViewCoordinates = [window convertRect:_inputViewBounds toView:self];
2287 CGRect intersectionBetweenScrollViewAndFormAssistant = CGRectIntersection(visibleScrollViewBoundsInWebViewCoordinates, formAssistantFrameInWebViewCoordinates);
2288 CGSize visibleSize = visibleScrollViewBoundsInWebViewCoordinates.size;
2290 CGFloat visibleOffsetFromTop = 0;
2291 if (!CGRectIsEmpty(intersectionBetweenScrollViewAndFormAssistant)) {
2292 CGFloat heightVisibleAboveFormAssistant = CGRectGetMinY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
2293 CGFloat heightVisibleBelowFormAssistant = CGRectGetMaxY(visibleScrollViewBoundsInWebViewCoordinates) - CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant);
2295 if (heightVisibleAboveFormAssistant >= minimumHeightToShowContentAboveKeyboard || heightVisibleBelowFormAssistant < heightVisibleAboveFormAssistant)
2296 visibleSize.height = heightVisibleAboveFormAssistant;
2298 visibleSize.height = heightVisibleBelowFormAssistant;
2299 visibleOffsetFromTop = CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
2303 // Zoom around the element's bounding frame. We use a "standard" size to determine the proper frame.
2304 double currentScale = contentZoomScale(self);
2305 double scale = currentScale;
2307 #if PLATFORM(WATCHOS)
2308 const CGFloat minimumMarginForZoomingToEntireFocusRectInWebViewCoordinates = 10;
2309 const CGFloat maximumMarginForZoomingToEntireFocusRectInWebViewCoordinates = 35;
2311 CGRect minimumTargetRectInDocumentCoordinates = UIRectInsetEdges(focusedElementRectInDocumentCoordinates, UIRectEdgeAll, -minimumMarginForZoomingToEntireFocusRectInWebViewCoordinates / currentScale);
2312 CGRect maximumTargetRectInDocumentCoordinates = UIRectInsetEdges(focusedElementRectInDocumentCoordinates, UIRectEdgeAll, -maximumMarginForZoomingToEntireFocusRectInWebViewCoordinates / currentScale);
2314 double clampedMaximumTargetScale = clampTo<double>(std::min(visibleSize.width / CGRectGetWidth(minimumTargetRectInDocumentCoordinates), visibleSize.height / CGRectGetHeight(minimumTargetRectInDocumentCoordinates)), minimumScale, maximumScale);
2315 double clampedMinimumTargetScale = clampTo<double>(std::min(visibleSize.width / CGRectGetWidth(maximumTargetRectInDocumentCoordinates), visibleSize.height / CGRectGetHeight(maximumTargetRectInDocumentCoordinates)), minimumScale, maximumScale);
2316 scale = clampTo<double>(currentScale, clampedMinimumTargetScale, clampedMaximumTargetScale);
2318 const double webViewStandardFontSize = 16;
2319 scale = clampTo<double>(webViewStandardFontSize / fontSize, minimumScale, maximumScale);
2323 CGFloat documentWidth = [_contentView bounds].size.width;
2324 scale = CGRound(documentWidth * scale) / documentWidth;
2326 WebCore::FloatRect focusedElementRectInNewScale = focusedElementRectInDocumentCoordinates;
2327 focusedElementRectInNewScale.scale(scale);
2328 focusedElementRectInNewScale.moveBy([_contentView frame].origin);
2330 BOOL selectionRectIsNotNull = !selectionRectInDocumentCoordinates.isZero();
2332 CGRect currentlyVisibleRegionInWebViewCoordinates;
2333 currentlyVisibleRegionInWebViewCoordinates.origin = unobscuredScrollViewRectInWebViewCoordinates.origin;
2334 currentlyVisibleRegionInWebViewCoordinates.origin.y += visibleOffsetFromTop;
2335 currentlyVisibleRegionInWebViewCoordinates.size = visibleSize;
2337 // Don't bother scrolling if the entire node is already visible, whether or not we got a selectionRect.
2338 if (CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:focusedElementRectInDocumentCoordinates fromView:_contentView.get()]))
2341 // Don't bother scrolling if we have a valid selectionRect and it is already visible.
2342 if (selectionRectIsNotNull && CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:selectionRectInDocumentCoordinates fromView:_contentView.get()]))
2346 // We want to center the focused element within the viewport, with as much spacing on all sides as
2347 // we can get based on the visible area after zooming. The spacing in either dimension is half the
2348 // difference between the size of the DOM node and the size of the visible frame.
2349 // If the element is too wide to be horizontally centered or too tall to be vertically centered, we
2350 // instead scroll such that the left edge or top edge of the element is within the left half or top
2351 // half of the viewport, respectively.
2352 CGFloat horizontalSpaceInWebViewCoordinates = (visibleSize.width - focusedElementRectInNewScale.width()) / 2.0;
2353 CGFloat verticalSpaceInWebViewCoordinates = (visibleSize.height - focusedElementRectInNewScale.height()) / 2.0;
2355 auto topLeft = CGPointZero;
2356 auto scrollViewInsets = [_scrollView _effectiveContentInset];
2357 auto currentTopLeft = [_scrollView contentOffset];
2359 if (_haveSetObscuredInsets) {
2360 currentTopLeft.x += _obscuredInsets.left;
2361 currentTopLeft.y += _obscuredInsets.top;
2364 if (horizontalSpaceInWebViewCoordinates > 0)
2365 topLeft.x = focusedElementRectInNewScale.x() - horizontalSpaceInWebViewCoordinates;
2367 auto minimumOffsetToRevealLeftEdge = std::max(-scrollViewInsets.left, focusedElementRectInNewScale.x() - visibleSize.width / 2);
2368 auto maximumOffsetToRevealLeftEdge = focusedElementRectInNewScale.x();
2369 topLeft.x = clampTo<double>(currentTopLeft.x, minimumOffsetToRevealLeftEdge, maximumOffsetToRevealLeftEdge);
2372 if (verticalSpaceInWebViewCoordinates > 0)
2373 topLeft.y = focusedElementRectInNewScale.y() - verticalSpaceInWebViewCoordinates;
2375 auto minimumOffsetToRevealTopEdge = std::max(-scrollViewInsets.top, focusedElementRectInNewScale.y() - visibleSize.height / 2);
2376 auto maximumOffsetToRevealTopEdge = focusedElementRectInNewScale.y();
2377 topLeft.y = clampTo<double>(currentTopLeft.y, minimumOffsetToRevealTopEdge, maximumOffsetToRevealTopEdge);
2380 topLeft.y -= visibleOffsetFromTop;
2382 WebCore::FloatRect documentBoundsInNewScale = [_contentView bounds];
2383 documentBoundsInNewScale.scale(scale);
2384 documentBoundsInNewScale.moveBy([_contentView frame].origin);
2386 CGFloat minimumAllowableHorizontalOffsetInWebViewCoordinates = -INFINITY;
2387 CGFloat minimumAllowableVerticalOffsetInWebViewCoordinates = -INFINITY;
2388 CGFloat maximumAllowableHorizontalOffsetInWebViewCoordinates = CGRectGetMaxX(documentBoundsInNewScale) - visibleSize.width;
2389 CGFloat maximumAllowableVerticalOffsetInWebViewCoordinates = CGRectGetMaxY(documentBoundsInNewScale) - visibleSize.height;
2391 if (selectionRectIsNotNull) {
2392 WebCore::FloatRect selectionRectInNewScale = selectionRectInDocumentCoordinates;
2393 selectionRectInNewScale.scale(scale);
2394 selectionRectInNewScale.moveBy([_contentView frame].origin);
2395 // Adjust the min and max allowable scroll offsets, such that the selection rect remains visible.
2396 minimumAllowableHorizontalOffsetInWebViewCoordinates = CGRectGetMaxX(selectionRectInNewScale) + caretOffsetFromWindowEdge - visibleSize.width;
2397 minimumAllowableVerticalOffsetInWebViewCoordinates = CGRectGetMaxY(selectionRectInNewScale) + caretOffsetFromWindowEdge - visibleSize.height - visibleOffsetFromTop;
2398 maximumAllowableHorizontalOffsetInWebViewCoordinates = std::min<CGFloat>(maximumAllowableHorizontalOffsetInWebViewCoordinates, CGRectGetMinX(selectionRectInNewScale) - caretOffsetFromWindowEdge);
2399 maximumAllowableVerticalOffsetInWebViewCoordinates = std::min<CGFloat>(maximumAllowableVerticalOffsetInWebViewCoordinates, CGRectGetMinY(selectionRectInNewScale) - caretOffsetFromWindowEdge - visibleOffsetFromTop);
2402 // Constrain the left edge in document coordinates so that:
2403 // - it isn't so small that the scrollVisibleRect isn't visible on the screen
2404 // - it isn't so great that the document's right edge is less than the right edge of the screen
2405 topLeft.x = clampTo<CGFloat>(topLeft.x, minimumAllowableHorizontalOffsetInWebViewCoordinates, maximumAllowableHorizontalOffsetInWebViewCoordinates);
2407 // Constrain the top edge in document coordinates so that:
2408 // - it isn't so small that the scrollVisibleRect isn't visible on the screen
2409 // - it isn't so great that the document's bottom edge is higher than the top of the form assistant
2410 topLeft.y = clampTo<CGFloat>(topLeft.y, minimumAllowableVerticalOffsetInWebViewCoordinates, maximumAllowableVerticalOffsetInWebViewCoordinates);
2412 if (_haveSetObscuredInsets) {
2413 // This looks unintuitive, but is necessary in order to precisely center the focused element in the visible area.
2414 // The top left position already accounts for top and left obscured insets - i.e., a topLeft of (0, 0) corresponds
2415 // to the top- and left-most point below (and to the right of) the top inset area and left inset areas, respectively.
2416 // However, when telling WKScrollView to scroll to a given center position, this center position is computed relative
2417 // to the coordinate space of the scroll view. Thus, to compute our center position from the top left position, we
2418 // need to first move the top left position up and to the left, and then add half the width and height of the content
2419 // area (including obscured insets).
2420 topLeft.x -= _obscuredInsets.left;
2421 topLeft.y -= _obscuredInsets.top;
2424 WebCore::FloatPoint newCenter = CGPointMake(topLeft.x + CGRectGetWidth(self.bounds) / 2, topLeft.y + CGRectGetHeight(self.bounds) / 2);
2426 if (scale != currentScale)
2427 _page->willStartUserTriggeredZooming();
2429 LOG_WITH_STREAM(VisibleRects, stream << "_zoomToFocusRect: zooming to " << newCenter << " scale:" << scale);
2431 // The newCenter has been computed in the new scale, but _zoomToCenter expected the center to be in the original scale.
2432 newCenter.scale(1 / scale);
2433 [_scrollView _zoomToCenter:newCenter scale:scale duration:formControlZoomAnimationDuration force:YES];
2436 - (CGFloat)_targetContentZoomScaleForRect:(const WebCore::FloatRect&)targetRect currentScale:(double)currentScale fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale
2438 WebCore::FloatSize unobscuredContentSize([self _contentRectForUserInteraction].size);
2439 double horizontalScale = unobscuredContentSize.width() * currentScale / targetRect.width();
2440 double verticalScale = unobscuredContentSize.height() * currentScale / targetRect.height();
2442 horizontalScale = std::min(std::max(horizontalScale, minimumScale), maximumScale);
2443 verticalScale = std::min(std::max(verticalScale, minimumScale), maximumScale);
2445 return fitEntireRect ? std::min(horizontalScale, verticalScale) : horizontalScale;
2448 - (BOOL)_zoomToRect:(WebCore::FloatRect)targetRect withOrigin:(WebCore::FloatPoint)origin fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale minimumScrollDistance:(float)minimumScrollDistance
2450 const float maximumScaleFactorDeltaForPanScroll = 0.02;
2452 double currentScale = contentZoomScale(self);
2453 double targetScale = [self _targetContentZoomScaleForRect:targetRect currentScale:currentScale fitEntireRect:fitEntireRect minimumScale:minimumScale maximumScale:maximumScale];
2455 if (fabs(targetScale - currentScale) < maximumScaleFactorDeltaForPanScroll) {
2456 if ([self _scrollToRect:targetRect origin:origin minimumScrollDistance:minimumScrollDistance])
2458 } else if (targetScale != currentScale) {
2459 [self _zoomToRect:targetRect atScale:targetScale origin:origin animated:YES];
2466 - (void)didMoveToWindow
2468 _page->activityStateDidChange(WebCore::ActivityState::allFlags());
2471 - (void)setOpaque:(BOOL)opaque
2473 BOOL oldOpaque = self.opaque;
2475 [super setOpaque:opaque];
2476 [_contentView setOpaque:opaque];
2478 if (oldOpaque == opaque)
2484 _page->setDrawsBackground(opaque);
2485 [self _updateScrollViewBackground];
2488 - (void)setBackgroundColor:(UIColor *)backgroundColor
2490 [super setBackgroundColor:backgroundColor];
2491 [_contentView setBackgroundColor:backgroundColor];
2494 - (BOOL)_allowsDoubleTapGestures
2496 if (_fastClickingIsDisabled)
2499 // If the page is not user scalable, we don't allow double tap gestures.
2500 if (![_scrollView isZoomEnabled] || [_scrollView minimumZoomScale] >= [_scrollView maximumZoomScale])
2503 // If the viewport width was not explicit, we allow double tap gestures.
2504 if (!_viewportMetaTagWidthWasExplicit || _viewportMetaTagCameFromImageDocument)
2507 // If the page set a viewport width that wasn't the device width, then it was
2508 // scaled and thus will probably need to zoom.
2509 if (_viewportMetaTagWidth != WebCore::ViewportArguments::ValueDeviceWidth)
2512 // At this point, we have a page that asked for width = device-width. However,
2513 // if the content's width and height were large, we might have had to shrink it.
2514 // We'll enable double tap zoom whenever we're not at the actual initial scale.
2515 return !areEssentiallyEqualAsFloat(contentZoomScale(self), _initialScaleFactor);
2518 - (BOOL)_stylusTapGestureShouldCreateEditableImage
2520 return [_configuration _editableImagesEnabled];
2523 #pragma mark - UIScrollViewDelegate
2525 - (BOOL)usesStandardContentView
2527 return !_customContentView && !_passwordView;
2530 - (CGSize)scrollView:(UIScrollView*)scrollView contentSizeForZoomScale:(CGFloat)scale withProposedSize:(CGSize)proposedSize
2532 return roundScrollViewContentSize(*_page, proposedSize);
2535 - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
2537 ASSERT(_scrollView == scrollView);
2538 return self._currentContentView;
2541 - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
2543 if (![self usesStandardContentView]) {
2544 if ([_customContentView respondsToSelector:@selector(web_scrollViewWillBeginZooming:withView:)])
2545 [_customContentView web_scrollViewWillBeginZooming:scrollView withView:view];
2549 if (scrollView.pinchGestureRecognizer.state == UIGestureRecognizerStateBegan) {
2550 _page->willStartUserTriggeredZooming();
2551 [_contentView scrollViewWillStartPanOrPinchGesture];
2553 [_contentView willStartZoomOrScroll];
2556 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
2558 if (![self usesStandardContentView])
2561 if (scrollView.panGestureRecognizer.state == UIGestureRecognizerStateBegan)
2562 [_contentView scrollViewWillStartPanOrPinchGesture];
2564 [_contentView willStartZoomOrScroll];
2565 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2566 // FIXME: We will want to detect whether snapping will occur before beginning to drag. See WebPageProxy::didCommitLayerTree.
2567 WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2568 ASSERT(scrollView == _scrollView.get());
2569 CGFloat scrollDecelerationFactor = (coordinator && coordinator->shouldSetScrollViewDecelerationRateFast()) ? UIScrollViewDecelerationRateFast : UIScrollViewDecelerationRateNormal;
2570 scrollView.horizontalScrollDecelerationFactor = scrollDecelerationFactor;
2571 scrollView.verticalScrollDecelerationFactor = scrollDecelerationFactor;
2575 - (void)_didFinishScrolling
2577 if (![self usesStandardContentView])
2580 [self _scheduleVisibleContentRectUpdate];
2581 [_contentView didFinishScrolling];
2584 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
2586 // Work around <rdar://problem/16374753> by avoiding deceleration while
2587 // zooming. We'll animate to the right place once the zoom finishes.
2588 if ([scrollView isZooming])
2589 *targetContentOffset = [scrollView contentOffset];
2590 #if ENABLE(POINTER_EVENTS)
2592 if ([_contentView preventsPanningInXAxis])
2593 targetContentOffset->x = scrollView.contentOffset.x;
2594 if ([_contentView preventsPanningInYAxis])
2595 targetContentOffset->y = scrollView.contentOffset.y;
2598 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2599 if (WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy()) {
2600 // FIXME: Here, I'm finding the maximum horizontal/vertical scroll offsets. There's probably a better way to do this.
2601 CGSize maxScrollOffsets = CGSizeMake(scrollView.contentSize.width - scrollView.bounds.size.width, scrollView.contentSize.height - scrollView.bounds.size.height);
2603 UIEdgeInsets obscuredInset;
2605 id<WKUIDelegatePrivate> uiDelegatePrivate = static_cast<id <WKUIDelegatePrivate>>([self UIDelegate]);
2606 if ([uiDelegatePrivate respondsToSelector:@selector(_webView:finalObscuredInsetsForScrollView:withVelocity:targetContentOffset:)])
2607 obscuredInset = [uiDelegatePrivate _webView:self finalObscuredInsetsForScrollView:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
2609 obscuredInset = [self _computedObscuredInset];
2611 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInset);
2613 coordinator->adjustTargetContentOffsetForSnapping(maxScrollOffsets, velocity, unobscuredRect.origin.y, targetContentOffset);
2618 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
2620 // If we're decelerating, scroll offset will be updated when scrollViewDidFinishDecelerating: is called.
2622 [self _didFinishScrolling];
2625 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
2627 [self _didFinishScrolling];
2630 - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
2632 [self _didFinishScrolling];
2635 #if ENABLE(POINTER_EVENTS)
2636 - (CGPoint)_scrollView:(UIScrollView *)scrollView adjustedOffsetForOffset:(CGPoint)offset translation:(CGPoint)translation startPoint:(CGPoint)start locationInView:(CGPoint)locationInView horizontalVelocity:(inout double *)hv verticalVelocity:(inout double *)vv
2638 if (![_contentView preventsPanningInXAxis] && ![_contentView preventsPanningInYAxis])
2641 CGPoint adjustedContentOffset = CGPointMake(offset.x, offset.y);
2642 if ([_contentView preventsPanningInXAxis])
2643 adjustedContentOffset.x = start.x;
2644 if ([_contentView preventsPanningInYAxis])
2645 adjustedContentOffset.y = start.y;
2647 return adjustedContentOffset;
2651 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
2653 if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidScroll:)])
2654 [_customContentView web_scrollViewDidScroll:(UIScrollView *)scrollView];
2656 [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2658 if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
2659 scrollPerfData->didScroll([self visibleRectInViewCoordinates]);
2662 - (void)scrollViewDidZoom:(UIScrollView *)scrollView
2664 if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidZoom:)])
2665 [_customContentView web_scrollViewDidZoom:scrollView];
2667 [self _updateScrollViewBackground];
2668 [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2671 - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
2673 if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidEndZooming:withView:atScale:)])
2674 [_customContentView web_scrollViewDidEndZooming:scrollView withView:view atScale:scale];
2676 ASSERT(scrollView == _scrollView);
2677 // FIXME: remove when rdar://problem/36065495 is fixed.
2678 // When rotating with two fingers down, UIScrollView can set a bogus content view position.
2679 // "Center" is top left because we set the anchorPoint to 0,0.
2680 [_contentView setCenter:self.bounds.origin];
2682 [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2683 [_contentView didZoomToScale:scale];
2686 - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
2688 [self _didFinishScrolling];
2691 - (void)_scrollViewDidInterruptDecelerating:(UIScrollView *)scrollView
2693 if (![self usesStandardContentView])
2696 [_contentView didInterruptScrolling];
2697 [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2700 - (UIView *)_enclosingViewForExposedRectComputation
2702 return [self _scroller];
2705 - (CGRect)_visibleRectInEnclosingView:(UIView *)enclosingView
2710 CGRect exposedRect = [enclosingView convertRect:enclosingView.bounds toView:self];
2711 return CGRectIntersectsRect(exposedRect, self.bounds) ? CGRectIntersection(exposedRect, self.bounds) : CGRectZero;
2714 - (CGRect)_visibleContentRect
2716 if (_frozenVisibleContentRect)
2717 return _frozenVisibleContentRect.value();
2719 CGRect visibleRectInContentCoordinates = [self convertRect:self.bounds toView:_contentView.get()];
2721 if (UIView *enclosingView = [self _enclosingViewForExposedRectComputation]) {
2722 CGRect viewVisibleRect = [self _visibleRectInEnclosingView:enclosingView];
2723 CGRect viewVisibleContentRect = [self convertRect:viewVisibleRect toView:_contentView.get()];
2724 visibleRectInContentCoordinates = CGRectIntersection(visibleRectInContentCoordinates, viewVisibleContentRect);
2727 return visibleRectInContentCoordinates;
2730 // Called when some ancestor UIScrollView scrolls.
2733 [self _scheduleVisibleContentRectUpdateAfterScrollInView:[self _scroller]];
2735 const NSTimeInterval ScrollingEndedTimerInterval = 0.032;
2736 if (!_enclosingScrollViewScrollTimer) {
2737 _enclosingScrollViewScrollTimer = adoptNS([[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:ScrollingEndedTimerInterval]
2738 interval:0 target:self selector:@selector(_enclosingScrollerScrollingEnded:) userInfo:nil repeats:YES]);
2739 [[NSRunLoop mainRunLoop] addTimer:_enclosingScrollViewScrollTimer.get() forMode:NSDefaultRunLoopMode];
2741 _didScrollSinceLastTimerFire = YES;
2744 - (void)_enclosingScrollerScrollingEnded:(NSTimer *)timer
2746 if (_didScrollSinceLastTimerFire) {
2747 _didScrollSinceLastTimerFire = NO;
2751 [self _scheduleVisibleContentRectUpdate];
2752 [_enclosingScrollViewScrollTimer invalidate];
2753 _enclosingScrollViewScrollTimer = nil;
2756 - (UIEdgeInsets)_scrollViewSystemContentInset
2758 // It's not safe to access the scroll view's safeAreaInsets or _systemContentInset from
2759 // inside our layoutSubviews implementation, because they aren't updated until afterwards.
2760 // Instead, depend on the fact that the UIScrollView and WKWebView are in the same coordinate
2761 // space, and map the WKWebView's own insets into the scroll view manually.
2762 return UIEdgeInsetsAdd([_scrollView _contentScrollInset], self.safeAreaInsets, [_scrollView _edgesApplyingSafeAreaInsetsToContentInset]);
2765 - (WebCore::FloatSize)activeViewLayoutSize:(const CGRect&)bounds
2767 if (_overridesViewLayoutSize)
2768 return WebCore::FloatSize(_viewLayoutSizeOverride);
2770 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2771 return WebCore::FloatSize(UIEdgeInsetsInsetRect(CGRectMake(0, 0, bounds.size.width, bounds.size.height), self._scrollViewSystemContentInset).size);
2773 return WebCore::FloatSize { bounds.size };
2777 - (void)_dispatchSetViewLayoutSize:(WebCore::FloatSize)viewLayoutSize
2779 if (_lastSentViewLayoutSize && CGSizeEqualToSize(_lastSentViewLayoutSize.value(), viewLayoutSize))
2782 LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _dispatchSetViewLayoutSize:] " << viewLayoutSize << " contentZoomScale " << contentZoomScale(self));
2783 _page->setViewportConfigurationViewLayoutSize(viewLayoutSize, _page->layoutSizeScaleFactor(), _minimumEffectiveDeviceWidth);
2784 _lastSentViewLayoutSize = viewLayoutSize;
2787 - (void)_dispatchSetMaximumUnobscuredSize:(WebCore::FloatSize)maximumUnobscuredSize
2789 if (_lastSentMaximumUnobscuredSize && CGSizeEqualToSize(_lastSentMaximumUnobscuredSize.value(), maximumUnobscuredSize))
2792 _page->setMaximumUnobscuredSize(maximumUnobscuredSize);
2793 _lastSentMaximumUnobscuredSize = maximumUnobscuredSize;
2796 - (void)_dispatchSetDeviceOrientation:(int32_t)deviceOrientation
2798 if (_lastSentDeviceOrientation && _lastSentDeviceOrientation.value() == deviceOrientation)
2801 _page->setDeviceOrientation(deviceOrientation);
2802 _lastSentDeviceOrientation = deviceOrientation;
2805 - (void)_frameOrBoundsChanged
2807 CGRect bounds = self.bounds;
2808 [_scrollView setFrame:bounds];
2810 if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing) {
2811 if (!_overridesViewLayoutSize)
2812 [self _dispatchSetViewLayoutSize:[self activeViewLayoutSize:self.bounds]];
2813 if (!_overridesMaximumUnobscuredSize)
2814 [self _dispatchSetMaximumUnobscuredSize:WebCore::FloatSize(bounds.size)];
2816 BOOL sizeChanged = NO;
2817 if (auto drawingArea = _page->drawingArea())
2818 sizeChanged = drawingArea->setSize(WebCore::IntSize(bounds.size));
2820 if (sizeChanged & [self usesStandardContentView])
2821 [_contentView setSizeChangedSinceLastVisibleContentRectUpdate:YES];
2824 [_customContentView web_setMinimumSize:bounds.size];
2825 [self _scheduleVisibleContentRectUpdate];
2828 // 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.
2829 - (CGRect)_contentRectForUserInteraction
2831 // FIXME: handle split keyboard.
2832 UIEdgeInsets obscuredInsets = _obscuredInsets;
2833 obscuredInsets.bottom = std::max(_obscuredInsets.bottom, _inputViewBounds.size.height);
2834 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInsets);
2835 return [self convertRect:unobscuredRect toView:self._currentContentView];
2838 // Ideally UIScrollView would expose this for us: <rdar://problem/21394567>.
2839 - (BOOL)_scrollViewIsRubberBanding
2841 float deviceScaleFactor = _page->deviceScaleFactor();
2843 CGPoint contentOffset = [_scrollView contentOffset];
2844 CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
2845 return !pointsEqualInDevicePixels(contentOffset, boundedOffset, deviceScaleFactor);
2848 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2849 - (void)safeAreaInsetsDidChange
2851 [super safeAreaInsetsDidChange];
2853 [self _scheduleVisibleContentRectUpdate];
2857 - (void)_scheduleVisibleContentRectUpdate
2859 // For visible rect updates not associated with a specific UIScrollView, just consider our own scroller.
2860 [self _scheduleVisibleContentRectUpdateAfterScrollInView:_scrollView.get()];
2863 - (BOOL)_scrollViewIsInStableState:(UIScrollView *)scrollView
2865 BOOL isStableState = !([scrollView isDragging] || [scrollView isDecelerating] || [scrollView isZooming] || [scrollView _isAnimatingZoom] || [scrollView _isScrollingToTop]);
2867 if (isStableState && scrollView == _scrollView.get())
2868 isStableState = !_isChangingObscuredInsetsInteractively;
2870 if (isStableState && scrollView == _scrollView.get())
2871 isStableState = ![self _scrollViewIsRubberBanding];
2874 isStableState = !scrollView._isInterruptingDeceleration;
2876 if (NSNumber *stableOverride = self._stableStateOverride)
2877 isStableState = stableOverride.boolValue;
2879 return isStableState;
2882 - (void)_addUpdateVisibleContentRectPreCommitHandler
2884 auto retainedSelf = retainPtr(self);
2885 [CATransaction addCommitHandler:[retainedSelf] {
2886 WKWebView *webView = retainedSelf.get();
2887 if (![webView _isValid]) {
2888 RELEASE_LOG_IF(webView._page && webView._page->isAlwaysOnLoggingAllowed(), ViewState, "In CATransaction preCommitHandler, WKWebView %p is invalid", webView);
2893 [webView _updateVisibleContentRects];
2894 } @catch (NSException *exception) {
2895 RELEASE_LOG_IF(webView._page && webView._page->isAlwaysOnLoggingAllowed(), ViewState, "In CATransaction preCommitHandler, -[WKWebView %p _updateVisibleContentRects] threw an exception", webView);
2897 webView->_hasScheduledVisibleRectUpdate = NO;
2898 } forPhase:kCATransactionPhasePreCommit];
2901 - (void)_scheduleVisibleContentRectUpdateAfterScrollInView:(UIScrollView *)scrollView
2903 _visibleContentRectUpdateScheduledFromScrollViewInStableState = [self _scrollViewIsInStableState:scrollView];
2905 if (_hasScheduledVisibleRectUpdate) {
2906 auto timeNow = MonotonicTime::now();
2907 if ((timeNow - _timeOfRequestForVisibleContentRectUpdate) > delayBeforeNoVisibleContentsRectsLogging) {
2908 RELEASE_LOG_IF_ALLOWED("-[WKWebView %p _scheduleVisibleContentRectUpdateAfterScrollInView]: _hasScheduledVisibleRectUpdate is true but haven't updated visible content rects for %.2fs (last update was %.2fs ago) - valid %d",
2909 self, (timeNow - _timeOfRequestForVisibleContentRectUpdate).value(), (timeNow - _timeOfLastVisibleContentRectUpdate).value(), [self _isValid]);
2914 _hasScheduledVisibleRectUpdate = YES;
2915 _timeOfRequestForVisibleContentRectUpdate = MonotonicTime::now();
2917 CATransactionPhase transactionPhase = [CATransaction currentPhase];
2918 if (transactionPhase == kCATransactionPhaseNull || transactionPhase == kCATransactionPhasePreLayout) {
2919 [self _addUpdateVisibleContentRectPreCommitHandler];
2923 dispatch_async(dispatch_get_main_queue(), [retainedSelf = retainPtr(self)] {
2924 WKWebView *webView = retainedSelf.get();
2925 if (![webView _isValid])
2927 [webView _addUpdateVisibleContentRectPreCommitHandler];
2931 static bool scrollViewCanScroll(UIScrollView *scrollView)
2936 UIEdgeInsets contentInset = scrollView.contentInset;
2937 CGSize contentSize = scrollView.contentSize;
2938 CGSize boundsSize = scrollView.bounds.size;
2940 return (contentSize.width + contentInset.left + contentInset.right) > boundsSize.width
2941 || (contentSize.height + contentInset.top + contentInset.bottom) > boundsSize.height;
2944 - (CGRect)_contentBoundsExtendedForRubberbandingWithScale:(CGFloat)scaleFactor
2946 CGPoint contentOffset = [_scrollView contentOffset];
2947 CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
2949 CGFloat horiontalRubberbandAmountInContentCoordinates = (contentOffset.x - boundedOffset.x) / scaleFactor;
2950 CGFloat verticalRubberbandAmountInContentCoordinates = (contentOffset.y - boundedOffset.y) / scaleFactor;
2952 CGRect extendedBounds = [_contentView bounds];
2954 if (horiontalRubberbandAmountInContentCoordinates < 0) {
2955 extendedBounds.origin.x += horiontalRubberbandAmountInContentCoordinates;
2956 extendedBounds.size.width -= horiontalRubberbandAmountInContentCoordinates;
2957 } else if (horiontalRubberbandAmountInContentCoordinates > 0)
2958 extendedBounds.size.width += horiontalRubberbandAmountInContentCoordinates;
2960 if (verticalRubberbandAmountInContentCoordinates < 0) {
2961 extendedBounds.origin.y += verticalRubberbandAmountInContentCoordinates;
2962 extendedBounds.size.height -= verticalRubberbandAmountInContentCoordinates;
2963 } else if (verticalRubberbandAmountInContentCoordinates > 0)
2964 extendedBounds.size.height += verticalRubberbandAmountInContentCoordinates;
2966 return extendedBounds;
2969 - (void)_updateVisibleContentRects
2971 BOOL inStableState = _visibleContentRectUpdateScheduledFromScrollViewInStableState;
2973 if (![self usesStandardContentView]) {
2974 [_passwordView setFrame:self.bounds];
2975 [_customContentView web_computedContentInsetDidChange];
2976 RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] - usesStandardContentView is NO, bailing", self);
2980 if (_delayUpdateVisibleContentRects) {
2981 _hadDelayedUpdateVisibleContentRects = YES;
2982 RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] - _delayUpdateVisibleContentRects is YES, bailing", self);
2986 if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing
2987 || (_needsResetViewStateAfterCommitLoadForMainFrame && ![_contentView sizeChangedSinceLastVisibleContentRectUpdate])
2988 || [_scrollView isZoomBouncing]
2989 || _currentlyAdjustingScrollViewInsetsForKeyboard) {
2990 RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] - scroll view state is non-stable, bailing (_dynamicViewportUpdateMode %d, _needsResetViewStateAfterCommitLoadForMainFrame %d, sizeChangedSinceLastVisibleContentRectUpdate %d, [_scrollView isZoomBouncing] %d, _currentlyAdjustingScrollViewInsetsForKeyboard %d)",
2991 self, _dynamicViewportUpdateMode, _needsResetViewStateAfterCommitLoadForMainFrame, [_contentView sizeChangedSinceLastVisibleContentRectUpdate], [_scrollView isZoomBouncing], _currentlyAdjustingScrollViewInsetsForKeyboard);
2995 CGRect visibleRectInContentCoordinates = [self _visibleContentRect];
2997 UIEdgeInsets computedContentInsetUnadjustedForKeyboard = [self _computedObscuredInset];
2998 if (!_haveSetObscuredInsets)
2999 computedContentInsetUnadjustedForKeyboard.bottom -= _totalScrollViewBottomInsetAdjustmentForKeyboard;
3001 CGFloat scaleFactor = contentZoomScale(self);
3003 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, computedContentInsetUnadjustedForKeyboard);
3004 CGRect unobscuredRectInContentCoordinates = _frozenUnobscuredContentRect ? _frozenUnobscuredContentRect.value() : [self convertRect:unobscuredRect toView:_contentView.get()];
3005 unobscuredRectInContentCoordinates = CGRectIntersection(unobscuredRectInContentCoordinates, [self _contentBoundsExtendedForRubberbandingWithScale:scaleFactor]);
3007 // The following logic computes the extent to which the bottom, top, left and right content insets are visible.
3008 auto scrollViewInsets = [_scrollView contentInset];
3009 auto scrollViewBounds = [_scrollView bounds];
3010 auto scrollViewContentSize = [_scrollView contentSize];
3011 auto scrollViewOriginIncludingInset = UIEdgeInsetsInsetRect(scrollViewBounds, computedContentInsetUnadjustedForKeyboard).origin;
3012 auto maximumVerticalScrollExtentWithoutRevealingBottomContentInset = scrollViewContentSize.height - CGRectGetHeight(scrollViewBounds);
3013 auto maximumHorizontalScrollExtentWithoutRevealingRightContentInset = scrollViewContentSize.width - CGRectGetWidth(scrollViewBounds);
3014 auto contentInsets = UIEdgeInsetsZero;
3015 if (scrollViewInsets.left > 0 && scrollViewOriginIncludingInset.x < 0)
3016 contentInsets.left = std::min(-scrollViewOriginIncludingInset.x, scrollViewInsets.left) / scaleFactor;
3018 if (scrollViewInsets.top > 0 && scrollViewOriginIncludingInset.y < 0)
3019 contentInsets.top = std::min(-scrollViewOriginIncludingInset.y, scrollViewInsets.top) / scaleFactor;
3021 if (scrollViewInsets.right > 0 && scrollViewOriginIncludingInset.x > maximumHorizontalScrollExtentWithoutRevealingRightContentInset)
3022 contentInsets.right = std::min(scrollViewOriginIncludingInset.x - maximumHorizontalScrollExtentWithoutRevealingRightContentInset, scrollViewInsets.right) / scaleFactor;
3024 if (scrollViewInsets.bottom > 0 && scrollViewOriginIncludingInset.y > maximumVerticalScrollExtentWithoutRevealingBottomContentInset)
3025 contentInsets.bottom = std::min(scrollViewOriginIncludingInset.y - maximumVerticalScrollExtentWithoutRevealingBottomContentInset, scrollViewInsets.bottom) / scaleFactor;
3027 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
3028 if (inStableState) {
3029 WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
3030 if (coordinator && coordinator->hasActiveSnapPoint()) {
3031 CGPoint currentPoint = [_scrollView contentOffset];
3032 CGPoint activePoint = coordinator->nearestActiveContentInsetAdjustedSnapPoint(unobscuredRect.origin.y, currentPoint);
3034 if (!CGPointEqualToPoint(activePoint, currentPoint)) {
3035 RetainPtr<WKScrollView> strongScrollView = _scrollView;
3036 dispatch_async(dispatch_get_main_queue(), [strongScrollView, activePoint] {
3037 [strongScrollView setContentOffset:activePoint animated:NO];
3044 [_contentView didUpdateVisibleRect:visibleRectInContentCoordinates
3045 unobscuredRect:unobscuredRectInContentCoordinates
3046 contentInsets:contentInsets
3047 unobscuredRectInScrollViewCoordinates:unobscuredRect
3048 obscuredInsets:_obscuredInsets
3049 unobscuredSafeAreaInsets:[self _computedUnobscuredSafeAreaInset]
3050 inputViewBounds:_inputViewBounds
3051 scale:scaleFactor minimumScale:[_scrollView minimumZoomScale]
3052 inStableState:inStableState
3053 isChangingObscuredInsetsInteractively:_isChangingObscuredInsetsInteractively
3054 enclosedInScrollableAncestorView:scrollViewCanScroll([self _scroller])];
3056 while (!_visibleContentRectUpdateCallbacks.isEmpty()) {
3057 auto callback = _visibleContentRectUpdateCallbacks.takeLast();
3061 auto timeNow = MonotonicTime::now();
3062 if ((timeNow - _timeOfRequestForVisibleContentRectUpdate) > delayBeforeNoVisibleContentsRectsLogging)
3063 RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] finally ran %.2fs after being scheduled", self, (timeNow - _timeOfRequestForVisibleContentRectUpdate).value());
3065 _timeOfLastVisibleContentRectUpdate = timeNow;
3068 - (void)_didStartProvisionalLoadForMainFrame
3070 if (_gestureController)
3071 _gestureController->didStartProvisionalLoadForMainFrame();
3074 static WebCore::FloatSize activeMaximumUnobscuredSize(WKWebView *webView, const CGRect& bounds)
3076 return WebCore::FloatSize(webView->_overridesMaximumUnobscuredSize ? webView->_maximumUnobscuredSizeOverride : bounds.size);
3079 static int32_t activeOrientation(WKWebView *webView)
3081 return webView->_overridesInterfaceOrientation ? deviceOrientationForUIInterfaceOrientation(webView->_interfaceOrientationOverride) : webView->_page->deviceOrientation();
3084 - (void)_cancelAnimatedResize
3086 LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _cancelAnimatedResize:] " << " _dynamicViewportUpdateMode " << (int)_dynamicViewportUpdateMode);
3087 if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing)
3090 if (!_customContentView) {
3091 if (_resizeAnimationView) {
3092 NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
3093 [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
3094 [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
3095 [_resizeAnimationView removeFromSuperview];
3096 _resizeAnimationView = nil;
3099 [_contentView setHidden:NO];
3100 _resizeAnimationTransformAdjustments = CATransform3DIdentity;
3103 _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
3104 [self _scheduleVisibleContentRectUpdate];
3107 - (void)_didCompleteAnimatedResize
3109 if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing)
3112 [_contentView setHidden:NO];
3114 if (!_resizeAnimationView) {
3115 // Paranoia. If _resizeAnimationView is null we'll end up setting a zero scale on the content view.
3116 RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didCompleteAnimatedResize:] - _resizeAnimationView is nil", self);
3117 [self _cancelAnimatedResize];
3121 NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
3122 [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
3123 [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
3125 CALayer *contentLayer = [_contentView layer];
3126 CGFloat adjustmentScale = _resizeAnimationTransformAdjustments.m11;
3127 contentLayer.sublayerTransform = CATransform3DIdentity;
3129 CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
3130 CATransform3D contentLayerTransform = contentLayer.transform;
3131 CGFloat currentScale = [[_resizeAnimationView layer] transform].m11 * contentLayerTransform.m11;
3133 // We cannot use [UIScrollView setZoomScale:] directly because the UIScrollView delegate would get a callback with
3134 // an invalid contentOffset. The real content offset is only set below.
3135 // Since there is no public API for setting both the zoomScale and the contentOffset, we set the zoomScale manually
3136 // on the zoom layer and then only change the contentOffset.
3137 CGFloat adjustedScale = adjustmentScale * currentScale;
3138 contentLayerTransform.m11 = adjustedScale;
3139 contentLayerTransform.m22 = adjustedScale;
3140 contentLayer.transform = contentLayerTransform;
3142 CGPoint currentScrollOffset = [_scrollView contentOffset];
3143 double horizontalScrollAdjustement = _resizeAnimationTransformAdjustments.m41 * animatingScaleTarget;
3144 double verticalScrollAdjustment = _resizeAnimationTransformAdjustments.m42 * animatingScaleTarget;
3146 [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
3147 [_scrollView setContentOffset:CGPointMake(currentScrollOffset.x - horizontalScrollAdjustement, currentScrollOffset.y - verticalScrollAdjustment)];
3149 [_resizeAnimationView removeFromSuperview];
3150 _resizeAnimationView = nil;
3151 _resizeAnimationTransformAdjustments = CATransform3DIdentity;
3153 _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
3154 [self _scheduleVisibleContentRectUpdate];
3156 CGRect newBounds = self.bounds;
3157 auto newViewLayoutSize = [self activeViewLayoutSize:newBounds];
3158 auto newMaximumUnobscuredSize = activeMaximumUnobscuredSize(self, newBounds);
3159 int32_t newOrientation = activeOrientation(self);
3161 if (!_lastSentViewLayoutSize || newViewLayoutSize != _lastSentViewLayoutSize.value())
3162 [self _dispatchSetViewLayoutSize:newViewLayoutSize];
3164 if (!_lastSentMaximumUnobscuredSize || newMaximumUnobscuredSize != _lastSentMaximumUnobscuredSize.value())
3165 [self _dispatchSetMaximumUnobscuredSize:WebCore::FloatSize(newMaximumUnobscuredSize)];
3167 if (!_lastSentDeviceOrientation || newOrientation != _lastSentDeviceOrientation.value())
3168 [self _dispatchSetDeviceOrientation:newOrientation];
3170 while (!_callbacksDeferredDuringResize.isEmpty())
3171 _callbacksDeferredDuringResize.takeLast()();
3174 - (void)_didFinishLoadForMainFrame
3176 if (_gestureController)
3177 _gestureController->didFinishLoadForMainFrame();
3180 - (void)_didFailLoadForMainFrame
3182 if (_gestureController)
3183 _gestureController->didFailLoadForMainFrame();
3186 - (void)_didSameDocumentNavigationForMainFrame:(WebKit::SameDocumentNavigationType)navigationType
3188 [_customContentView web_didSameDocumentNavigation:toAPI(navigationType)];
3190 if (_gestureController)
3191 _gestureController->didSameDocumentNavigationForMainFrame(navigationType);
3194 - (void)_keyboardChangedWithInfo:(NSDictionary *)keyboardInfo adjustScrollView:(BOOL)adjustScrollView
3196 NSValue *endFrameValue = [keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
3200 // The keyboard rect is always in screen coordinates. In the view services case the window does not
3201 // have the interface orientation rotation transformation; its host does. So, it makes no sense to
3202 // clip the keyboard rect against its screen.
3203 if ([[self window] _isHostedInAnotherProcess])
3204 _inputViewBounds = [self.window convertRect:[endFrameValue CGRectValue] fromWindow:nil];
3206 _inputViewBounds = [self.window convertRect:CGRectIntersection([endFrameValue CGRectValue], self.window.screen.bounds) fromWindow:nil];
3208 if ([[UIPeripheralHost sharedInstance] isUndocked])
3209 _inputViewBounds = CGRectZero;
3211 if (adjustScrollView) {
3212 CGFloat bottomInsetBeforeAdjustment = [_scrollView contentInset].bottom;
3213 SetForScope<BOOL> insetAdjustmentGuard(_currentlyAdjustingScrollViewInsetsForKeyboard, YES);
3214 [_scrollView _adjustForAutomaticKeyboardInfo:keyboardInfo animated:YES lastAdjustment:&_lastAdjustmentForScroller];
3215 CGFloat bottomInsetAfterAdjustment = [_scrollView contentInset].bottom;
3216 if (bottomInsetBeforeAdjustment != bottomInsetAfterAdjustment)
3217 _totalScrollViewBottomInsetAdjustmentForKeyboard += bottomInsetAfterAdjustment - bottomInsetBeforeAdjustment;
3220 [self _scheduleVisibleContentRectUpdate];
3223 - (BOOL)_shouldUpdateKeyboardWithInfo:(NSDictionary *)keyboardInfo
3225 if ([_contentView isFocusingElement])
3228 NSNumber *isLocalKeyboard = [keyboardInfo valueForKey:UIKeyboardIsLocalUserInfoKey];
3229 return isLocalKeyboard && !isLocalKeyboard.boolValue;
3232 - (void)_keyboardWillChangeFrame:(NSNotification *)notification
3234 if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
3235 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
3238 - (void)_keyboardDidChangeFrame:(NSNotification *)notification
3240 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:NO];
3243 - (void)_keyboardWillShow:(NSNotification *)notification
3245 if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
3246 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
3248 _page->setIsKeyboardAnimatingIn(true);
3251 - (void)_keyboardDidShow:(NSNotification *)notification
3253 _page->setIsKeyboardAnimatingIn(false);
3256 - (void)_keyboardWillHide:(NSNotification *)notification
3258 // Ignore keyboard will hide notifications sent during rotation. They're just there for
3259 // backwards compatibility reasons and processing the will hide notification would
3260 // temporarily screw up the unobscured view area.
3261 if ([[UIPeripheralHost sharedInstance] rotationState])
3264 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
3267 static void hardwareKeyboardAvailabilityChangedCallback(CFNotificationCenterRef, void* observer, CFStringRef, const void*, CFDictionaryRef)
3270 WKWebView *webView = (__bridge WKWebView *)observer;
3271 webView._page->hardwareKeyboardAvailabilityChanged();
3274 - (void)_windowDidRotate:(NSNotification *)notification
3276 if (!_overridesInterfaceOrientation)
3277 [self _dispatchSetDeviceOrientation:deviceOrientation()];
3280 - (void)_contentSizeCategoryDidChange:(NSNotification *)notification
3282 _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
3285 - (NSString *)_contentSizeCategory
3287 return [[UIApplication sharedApplication] preferredContentSizeCategory];
3290 - (void)_accessibilitySettingsDidChange:(NSNotification *)notification
3292 _page->accessibilitySettingsDidChange();
3295 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
3297 if (_allowsBackForwardNavigationGestures == allowsBackForwardNavigationGestures)
3300 _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
3302 if (allowsBackForwardNavigationGestures && !_gestureController) {
3303 _gestureController = std::make_unique<WebKit::ViewGestureController>(*_page);
3304 _gestureController->installSwipeHandler(self, [self scrollView]);
3305 if (WKWebView *alternateWebView = [_configuration _alternateWebViewForNavigationGestures])
3306 _gestureController->setAlternateBackForwardListSourcePage(alternateWebView->_page.get());
3309 if (_gestureController)
3310 _gestureController->setSwipeGestureEnabled(allowsBackForwardNavigationGestures);
3312 _page->setShouldRecordNavigationSnapshots(allowsBackForwardNavigationGestures);
3315 - (BOOL)allowsBackForwardNavigationGestures
3317 return _allowsBackForwardNavigationGestures;
3320 - (BOOL)_isNavigationSwipeGestureRecognizer:(UIGestureRecognizer *)recognizer
3322 if (!_gestureController)
3324 return _gestureController->isNavigationSwipeGestureRecognizer(recognizer);
3327 - (void)_navigationGestureDidBegin
3329 // During a back/forward swipe, there's a view interposed between this view and the content view that has
3330 // an offset and animation on it, which results in computing incorrect rectangles. Work around by using
3331 // frozen rects during swipes.
3332 CGRect fullViewRect = self.bounds;
3333 CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, [self _computedObscuredInset]);
3335 _frozenVisibleContentRect = [self convertRect:fullViewRect toView:_contentView.get()];
3336 _frozenUnobscuredContentRect = [self convertRect:unobscuredRect toView:_contentView.get()];
3338 LOG_WITH_STREAM(VisibleRects, stream << "_navigationGestureDidBegin: freezing visibleContentRect " << WebCore::FloatRect(_frozenVisibleContentRect.value()) << " UnobscuredContentRect " << WebCore::FloatRect(_frozenUnobscuredContentRect.value()));
3341 - (void)_navigationGestureDidEnd
3343 _frozenVisibleContentRect = WTF::nullopt;
3344 _frozenUnobscuredContentRect = WTF::nullopt;
3347 - (void)_showPasswordViewWithDocumentName:(NSString *)documentName passwordHandler:(void (^)(NSString *))passwordHandler
3349 ASSERT(!_passwordView);
3350 _passwordView = adoptNS([[WKPasswordView alloc] initWithFrame:self.bounds documentName:documentName]);
3351 [_passwordView setUserDidEnterPassword:passwordHandler];
3352 [_passwordView showInScrollView:_scrollView.get()];
3353 self._currentContentView.hidden = YES;
3356 - (void)_hidePasswordView
3361 self._currentContentView.hidden = NO;
3362 [_passwordView hide];
3363 _passwordView = nil;
3366 - (WKPasswordView *)_passwordView
3368 return _passwordView.get();
3371 - (void)_updateScrollViewInsetAdjustmentBehavior
3373 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
3374 if (![_scrollView _contentInsetAdjustmentBehaviorWasExternallyOverridden])
3375 [_scrollView _setContentInsetAdjustmentBehaviorInternal:self._safeAreaShouldAffectObscuredInsets ? UIScrollViewContentInsetAdjustmentAlways : UIScrollViewContentInsetAdjustmentNever];
3379 - (void)_setAvoidsUnsafeArea:(BOOL)avoidsUnsafeArea
3381 if (_avoidsUnsafeArea == avoidsUnsafeArea)
3384 _avoidsUnsafeArea = avoidsUnsafeArea;
3386 [self _updateScrollViewInsetAdjustmentBehavior];
3387 [self _scheduleVisibleContentRectUpdate];
3389 id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)[self UIDelegate];
3390 if ([uiDelegate respondsToSelector:@selector(_webView:didChangeSafeAreaShouldAffectObscuredInsets:)])
3391 [uiDelegate _webView:self didChangeSafeAreaShouldAffectObscuredInsets:avoidsUnsafeArea];
3394 - (BOOL)_haveSetObscuredInsets
3396 return _haveSetObscuredInsets;
3399 #endif // PLATFORM(IOS_FAMILY)
3401 #if ENABLE(ACCESSIBILITY_EVENTS)
3403 static void accessibilityEventsEnabledChangedCallback(CFNotificationCenterRef, void* observer, CFStringRef, const void*, CFDictionaryRef)
3406 WKWebView *webview = (__bridge WKWebView *)observer;
3407 [webview _updateAccessibilityEventsEnabled];
3410 - (void)_updateAccessibilityEventsEnabled
3412 if (!isNullFunctionPointer(_AXSWebAccessibilityEventsEnabled))
3413 _page->updateAccessibilityEventsEnabled(_AXSWebAccessibilityEventsEnabled());
3418 #pragma mark OS X-specific methods
3422 - (BOOL)acceptsFirstResponder
3424 return _impl->acceptsFirstResponder();
3427 - (BOOL)becomeFirstResponder
3429 return _impl->becomeFirstResponder();
3432 - (BOOL)resignFirstResponder
3434 return _impl->resignFirstResponder();
3437 - (void)viewWillStartLiveResize
3439 _impl->viewWillStartLiveResize();
3442 - (void)viewDidEndLiveResize
3444 _impl->viewDidEndLiveResize();
3452 - (NSSize)intrinsicContentSize
3454 return NSSizeFromCGSize(_impl->intrinsicContentSize());
3457 - (void)prepareContentInRect:(NSRect)rect
3459 _impl->prepareContentInRect(NSRectToCGRect(rect));
3462 - (void)setFrameSize:(NSSize)size
3464 [super setFrameSize:size];
3465 [_safeBrowsingWarning setFrame:self.bounds];
3466 _impl->setFrameSize(NSSizeToCGSize(size));
3469 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
3473 _impl->renewGState();
3474 [super renewGState];
3477 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _impl->executeEditCommandForSelector(_cmd); }
3479 WEBCORE_COMMAND(alignCenter)
3480 WEBCORE_COMMAND(alignJustified)
3481 WEBCORE_COMMAND(alignLeft)
3482 WEBCORE_COMMAND(alignRight)
3483 WEBCORE_COMMAND(copy)
3484 WEBCORE_COMMAND(cut)
3485 WEBCORE_COMMAND(delete)
3486 WEBCORE_COMMAND(deleteBackward)
3487 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
3488 WEBCORE_COMMAND(deleteForward)
3489 WEBCORE_COMMAND(deleteToBeginningOfLine)
3490 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
3491 WEBCORE_COMMAND(deleteToEndOfLine)
3492 WEBCORE_COMMAND(deleteToEndOfParagraph)
3493 WEBCORE_COMMAND(deleteToMark)
3494 WEBCORE_COMMAND(deleteWordBackward)
3495 WEBCORE_COMMAND(deleteWordForward)
3496 WEBCORE_COMMAND(ignoreSpelling)
3497 WEBCORE_COMMAND(indent)
3498 WEBCORE_COMMAND(insertBacktab)
3499 WEBCORE_COMMAND(insertLineBreak)
3500 WEBCORE_COMMAND(insertNewline)
3501 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
3502 WEBCORE_COMMAND(insertParagraphSeparator)
3503 WEBCORE_COMMAND(insertTab)
3504 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
3505 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
3506 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
3507 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
3508 WEBCORE_COMMAND(moveBackward)
3509 WEBCORE_COMMAND(moveBackwardAndModifySelection)
3510 WEBCORE_COMMAND(moveDown)
3511 WEBCORE_COMMAND(moveDownAndModifySelection)
3512 WEBCORE_COMMAND(moveForward)
3513 WEBCORE_COMMAND(moveForwardAndModifySelection)
3514 WEBCORE_COMMAND(moveLeft)
3515 WEBCORE_COMMAND(moveLeftAndModifySelection)
3516 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
3517 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
3518 WEBCORE_COMMAND(moveRight)
3519 WEBCORE_COMMAND(moveRightAndModifySelection)
3520 WEBCORE_COMMAND(moveToBeginningOfDocument)
3521 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
3522 WEBCORE_COMMAND(moveToBeginningOfLine)
3523 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
3524 WEBCORE_COMMAND(moveToBeginningOfParagraph)
3525 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
3526 WEBCORE_COMMAND(moveToBeginningOfSentence)
3527 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
3528 WEBCORE_COMMAND(moveToEndOfDocument)
3529 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
3530 WEBCORE_COMMAND(moveToEndOfLine)
3531 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
3532 WEBCORE_COMMAND(moveToEndOfParagraph)
3533 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
3534 WEBCORE_COMMAND(moveToEndOfSentence)
3535 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
3536 WEBCORE_COMMAND(moveToLeftEndOfLine)
3537 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
3538 WEBCORE_COMMAND(moveToRightEndOfLine)
3539 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
3540 WEBCORE_COMMAND(moveUp)
3541 WEBCORE_COMMAND(moveUpAndModifySelection)
3542 WEBCORE_COMMAND(moveWordBackward)
3543 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
3544 WEBCORE_COMMAND(moveWordForward)
3545 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
3546 WEBCORE_COMMAND(moveWordLeft)
3547 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
3548 WEBCORE_COMMAND(moveWordRight)
3549 WEBCORE_COMMAND(moveWordRightAndModifySelection)
3550 WEBCORE_COMMAND(outdent)
3551 WEBCORE_COMMAND(pageDown)
3552 WEBCORE_COMMAND(pageDownAndModifySelection)
3553 WEBCORE_COMMAND(pageUp)
3554 WEBCORE_COMMAND(pageUpAndModifySelection)
3555 WEBCORE_COMMAND(paste)
3556 WEBCORE_COMMAND(pasteAsPlainText)
3557 WEBCORE_COMMAND(scrollPageDown)
3558 WEBCORE_COMMAND(scrollPageUp)
3559 WEBCORE_COMMAND(scrollLineDown)
3560 WEBCORE_COMMAND(scrollLineUp)
3561 WEBCORE_COMMAND(scrollToBeginningOfDocument)
3562 WEBCORE_COMMAND(scrollToEndOfDocument)
3563 WEBCORE_COMMAND(selectAll)
3564 WEBCORE_COMMAND(selectLine)
3565 WEBCORE_COMMAND(selectParagraph)
3566 WEBCORE_COMMAND(selectSentence)
3567 WEBCORE_COMMAND(selectToMark)
3568 WEBCORE_COMMAND(selectWord)
3569 WEBCORE_COMMAND(setMark)
3570 WEBCORE_COMMAND(subscript)
3571 WEBCORE_COMMAND(superscript)
3572 WEBCORE_COMMAND(swapWithMark)
3573 WEBCORE_COMMAND(takeFindStringFromSelection)
3574 WEBCORE_COMMAND(transpose)
3575 WEBCORE_COMMAND(underline)
3576 WEBCORE_COMMAND(unscript)
3577 WEBCORE_COMMAND(yank)
3578 WEBCORE_COMMAND(yankAndSelect)
3580 #undef WEBCORE_COMMAND
3582 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
3584 return _impl->writeSelectionToPasteboard(pasteboard, types);
3587 - (void)centerSelectionInVisibleArea:(id)sender
3589 _impl->centerSelectionInVisibleArea();
3592 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
3594 return _impl->validRequestorForSendAndReturnTypes(sendType, returnType);
3597 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
3599 return _impl->readSelectionFromPasteboard(pasteboard);
3602 - (void)changeFont:(id)sender
3604 _impl->changeFontFromFontManager();
3607 - (void)changeColor:(id)sender
3609 _impl->changeFontColorFromSender(sender);
3612 - (void)changeAttributes:(id)sender
3614 _impl->changeFontAttributesFromSender(sender);
3617 - (IBAction)startSpeaking:(id)sender
3619 _impl->startSpeaking();
3622 - (IBAction)stopSpeaking:(id)sender
3624 _impl->stopSpeaking(sender);
3627 - (IBAction)showGuessPanel:(id)sender
3629 _impl->showGuessPanel(sender);
3632 - (IBAction)checkSpelling:(id)sender
3634 _impl->checkSpelling();
3637 - (void)changeSpelling:(id)sender
3639 _impl->changeSpelling(sender);
3642 - (IBAction)toggleContinuousSpellChecking:(id)sender
3644 _impl->toggleContinuousSpellChecking();
3647 - (BOOL)isGrammarCheckingEnabled
3649 return _impl->isGrammarCheckingEnabled();
3652 - (void)setGrammarCheckingEnabled:(BOOL)flag
3654 _impl->setGrammarCheckingEnabled(flag);
3657 - (IBAction)toggleGrammarChecking:(id)sender
3659 _impl->toggleGrammarChecking();
3662 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
3664 _impl->toggleAutomaticSpellingCorrection();
3667 - (void)orderFrontSubstitutionsPanel:(id)sender
3669 _impl->orderFrontSubstitutionsPanel(sender);
3672 - (IBAction)toggleSmartInsertDelete:(id)sender
3674 _impl->toggleSmartInsertDelete();
3677 - (BOOL)isAutomaticQuoteSubstitutionEnabled
3679 return _impl->isAutomaticQuoteSubstitutionEnabled();
3682 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
3684 _impl->setAutomaticQuoteSubstitutionEnabled(flag);
3687 - (void)toggleAutomaticQuoteSubstitution:(id)sender
3689 _impl->toggleAutomaticQuoteSubstitution();
3692 - (BOOL)isAutomaticDashSubstitutionEnabled
3694 return _impl->isAutomaticDashSubstitutionEnabled();
3697 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
3699 _impl->setAutomaticDashSubstitutionEnabled(flag);
3702 - (void)toggleAutomaticDashSubstitution:(id)sender
3704 _impl->toggleAutomaticDashSubstitution();
3707 - (BOOL)isAutomaticLinkDetectionEnabled
3709 return _impl->isAutomaticLinkDetectionEnabled();
3712 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
3714 _impl->setAutomaticLinkDetectionEnabled(flag);
3717 - (void)toggleAutomaticLinkDetection:(id)sender
3719 _impl->toggleAutomaticLinkDetection();
3722 - (BOOL)isAutomaticTextReplacementEnabled
3724 return _impl->isAutomaticTextReplacementEnabled();
3727 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
3729 _impl->setAutomaticTextReplacementEnabled(flag);
3732 - (void)toggleAutomaticTextReplacement:(id)sender
3734 _impl->toggleAutomaticTextReplacement();
3737 - (void)uppercaseWord:(id)sender
3739 _impl->uppercaseWord();
3742 - (void)lowercaseWord:(id)sender
3744 _impl->lowercaseWord();
3747 - (void)capitalizeWord:(id)sender
3749 _impl->capitalizeWord();
3752 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
3754 return _impl->wantsKeyDownForEvent(event);
3757 - (void)scrollWheel:(NSEvent *)event
3759 _impl->scrollWheel(event);
3762 - (void)swipeWithEvent:(NSEvent *)event
3764 _impl->swipeWithEvent(event);
3767 - (void)mouseMoved:(NSEvent *)event
3769 _impl->mouseMoved(event);
3772 - (void)mouseDown:(NSEvent *)event
3774 _impl->mouseDown(event);
3777 - (void)mouseUp:(NSEvent *)event
3779 _impl->mouseUp(event);
3782 - (void)mouseDragged:(NSEvent *)event
3784 _impl->mouseDragged(event);
3787 - (void)mouseEntered:(NSEvent *)event
3789 _impl->mouseEntered(event);
3792 - (void)mouseExited:(NSEvent *)event
3794 _impl->mouseExited(event);
3797 - (void)otherMouseDown:(NSEvent *)event
3799 _impl->otherMouseDown(event);
3802 - (void)otherMouseDragged:(NSEvent *)event
3804 _impl->otherMouseDragged(event);
3807 - (void)otherMouseUp:(NSEvent *)event
3809 _impl->otherMouseUp(event);
3812 - (void)rightMouseDown:(NSEvent *)event
3814 _impl->rightMouseDown(event);
3817 - (void)rightMouseDragged:(NSEvent *)event
3819 _impl->rightMouseDragged(event);
3822 - (void)rightMouseUp:(NSEvent *)event
3824 _impl->rightMouseUp(event);
3827 - (void)pressureChangeWithEvent:(NSEvent *)event
3829 _impl->pressureChangeWithEvent(event);
3832 - (BOOL)acceptsFirstMouse:(NSEvent *)event
3834 return _impl->acceptsFirstMouse(event);
3837 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
3839 return _impl->shouldDelayWindowOrderingForEvent(event);
3842 - (void)doCommandBySelector:(SEL)selector
3844 _impl->doCommandBySelector(selector);
3847 - (void)insertText:(id)string
3849 _impl->insertText(string);
3852 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
3854 _impl->insertText(string, replacementRange);
3857 - (NSTextInputContext *)inputContext
3861 return _impl->inputContext();
3864 - (BOOL)performKeyEquivalent:(NSEvent *)event
3866 return _impl->performKeyEquivalent(event);
3869 - (void)keyUp:(NSEvent *)theEvent
3871 _impl->keyUp(theEvent);
3874 - (void)keyDown:(NSEvent *)theEvent
3876 _impl->keyDown(theEvent);
3879 - (void)flagsChanged:(NSEvent *)theEvent
3881 _impl->flagsChanged(theEvent);
3884 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelectedRange replacementRange:(NSRange)replacementRange
3886 _impl->setMarkedText(string, newSelectedRange, replacementRange);
3891 _impl->unmarkText();
3894 - (NSRange)selectedRange
3896 return _impl->selectedRange();
3899 - (BOOL)hasMarkedText
3901 return _impl->hasMarkedText();
3904 - (NSRange)markedRange
3906 return _impl->markedRange();
3909 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange
3911 return _impl->attributedSubstringForProposedRange(nsRange, actualRange);
3914 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
3916 return _impl->characterIndexForPoint(thePoint);
3919 - (void)typingAttributesWithCompletionHandler:(void(^)(NSDictionary<NSString *, id> *))completion
3921 _impl->typingAttributesWithCompletionHandler(completion);
3924 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
3926 return _impl->firstRectForCharacterRange(theRange, actualRange);
3929 - (void)selectedRangeWithCompletionHandler:(void(^)(NSRange selectedRange))completionHandlerPtr
3931 _impl->selectedRangeWithCompletionHandler(completionHandlerPtr);
3934 - (void)markedRangeWithCompletionHandler:(void(^)(NSRange markedRange))completionHandlerPtr
3936 _impl->markedRangeWithCompletionHandler(completionHandlerPtr);
3939 - (void)hasMarkedTextWithCompletionHandler:(void(^)(BOOL hasMarkedText))completionHandlerPtr
3941 _impl->hasMarkedTextWithCompletionHandler(completionHandlerPtr);
3944 - (void)attributedSubstringForProposedRange:(NSRange)nsRange completionHandler:(void(^)(NSAttributedString *attrString, NSRange actualRange))completionHandlerPtr
3946 _impl->attributedSubstringForProposedRange(nsRange, completionHandlerPtr);
3949 - (void)firstRectForCharacterRange:(NSRange)theRange completionHandler:(void(^)(NSRect firstRect, NSRange actualRange))completionHandlerPtr
3951 _impl->firstRectForCharacterRange(theRange, completionHandlerPtr);
3954 - (void)characterIndexForPoint:(NSPoint)thePoint completionHandler:(void(^)(NSUInteger))completionHandlerPtr
3956 _impl->characterIndexForPoint(thePoint, completionHandlerPtr);
3959 - (NSArray *)validAttributesForMarkedText
3961 return _impl->validAttributesForMarkedText();
3964 #if ENABLE(DRAG_SUPPORT)
3965 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
3966 - (void)draggedImage:(NSImage *)image endedAt:(NSPoint)endPoint operation:(NSDragOperation)operation
3969 _impl->draggedImage(image, NSPointToCGPoint(endPoint), operation);
3972 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
3974 return _impl->draggingEntered(draggingInfo);
3977 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
3979 return _impl->draggingUpdated(draggingInfo);
3982 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
3984 _impl->draggingExited(draggingInfo);
3987 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
3989 return _impl->prepareForDragOperation(draggingInfo);
3992 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
3994 return _impl->performDragOperation(draggingInfo);
3997 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
3999 return _impl->hitTestForDragTypes(NSPointToCGPoint(*point), types);
4001 #endif // ENABLE(DRAG_SUPPORT)
4003 - (BOOL)_windowResizeMouseLocationIsInVisibleScrollerThumb:(NSPoint)point
4005 return _impl->windowResizeMouseLocationIsInVisibleScrollerThumb(NSPointToCGPoint(point));
4008 - (void)viewWillMoveToWindow:(NSWindow *)window
4010 _impl->viewWillMoveToWindow(window);
4013 - (void)viewDidMoveToWindow
4015 _impl->viewDidMoveToWindow();
4018 - (void)drawRect:(NSRect)rect
4020 _impl->drawRect(NSRectToCGRect(rect));
4025 return _impl->isOpaque();
4028 - (BOOL)mouseDownCanMoveWindow
4030 return WebKit::WebViewImpl::mouseDownCanMoveWindow();
4035 _impl->viewDidHide();
4038 - (void)viewDidUnhide
4040 _impl->viewDidUnhide();
4043 - (void)viewDidChangeBackingProperties
4045 _impl->viewDidChangeBackingProperties();
4048 - (void)_activeSpaceDidChange:(NSNotification *)notification
4050 _impl->activeSpaceDidChange();
4053 - (id)accessibilityFocusedUIElement
4055 return _impl->accessibilityFocusedUIElement();
4058 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
4059 - (BOOL)accessibilityIsIgnored
4062 return _impl->accessibilityIsIgnored();
4065 - (id)accessibilityHitTest:(NSPoint)point
4067 return _impl->accessibilityHitTest(NSPointToCGPoint(point));
4070 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
4071 - (id)accessibilityAttributeValue:(NSString *)attribute
4074 return _impl->accessibilityAttributeValue(attribute);
4077 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
4078 - (id)accessibilityAttributeValue:(NSString *)attribute forParameter:(id)parameter
4081 return _impl->accessibilityAttributeValue(attribute, parameter);
4084 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
4085 - (NSArray<NSString *> *)accessibilityParameterizedAttributeNames
4088 NSArray<NSString *> *names = [super accessibilityParameterizedAttributeNames];
<