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];
2555 #if ENABLE(POINTER_EVENTS)
2556 [_contentView cancelPointersForGestureRecognizer:scrollView.pinchGestureRecognizer];
2560 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
2562 if (![self usesStandardContentView])
2565 if (scrollView.panGestureRecognizer.state == UIGestureRecognizerStateBegan)
2566 [_contentView scrollViewWillStartPanOrPinchGesture];
2568 [_contentView willStartZoomOrScroll];
2569 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2570 // FIXME: We will want to detect whether snapping will occur before beginning to drag. See WebPageProxy::didCommitLayerTree.
2571 WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2572 ASSERT(scrollView == _scrollView.get());
2573 CGFloat scrollDecelerationFactor = (coordinator && coordinator->shouldSetScrollViewDecelerationRateFast()) ? UIScrollViewDecelerationRateFast : UIScrollViewDecelerationRateNormal;
2574 scrollView.horizontalScrollDecelerationFactor = scrollDecelerationFactor;
2575 scrollView.verticalScrollDecelerationFactor = scrollDecelerationFactor;
2579 - (void)_didFinishScrolling
2581 if (![self usesStandardContentView])
2584 [self _scheduleVisibleContentRectUpdate];
2585 [_contentView didFinishScrolling];
2588 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
2590 // Work around <rdar://problem/16374753> by avoiding deceleration while
2591 // zooming. We'll animate to the right place once the zoom finishes.
2592 if ([scrollView isZooming])
2593 *targetContentOffset = [scrollView contentOffset];
2594 #if ENABLE(POINTER_EVENTS)
2596 if ([_contentView preventsPanningInXAxis])
2597 targetContentOffset->x = scrollView.contentOffset.x;
2598 if ([_contentView preventsPanningInYAxis])
2599 targetContentOffset->y = scrollView.contentOffset.y;
2602 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2603 if (WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy()) {
2604 // FIXME: Here, I'm finding the maximum horizontal/vertical scroll offsets. There's probably a better way to do this.
2605 CGSize maxScrollOffsets = CGSizeMake(scrollView.contentSize.width - scrollView.bounds.size.width, scrollView.contentSize.height - scrollView.bounds.size.height);
2607 UIEdgeInsets obscuredInset;
2609 id<WKUIDelegatePrivate> uiDelegatePrivate = static_cast<id <WKUIDelegatePrivate>>([self UIDelegate]);
2610 if ([uiDelegatePrivate respondsToSelector:@selector(_webView:finalObscuredInsetsForScrollView:withVelocity:targetContentOffset:)])
2611 obscuredInset = [uiDelegatePrivate _webView:self finalObscuredInsetsForScrollView:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
2613 obscuredInset = [self _computedObscuredInset];
2615 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInset);
2617 coordinator->adjustTargetContentOffsetForSnapping(maxScrollOffsets, velocity, unobscuredRect.origin.y, targetContentOffset);
2622 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
2624 // If we're decelerating, scroll offset will be updated when scrollViewDidFinishDecelerating: is called.
2626 [self _didFinishScrolling];
2629 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
2631 [self _didFinishScrolling];
2634 - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
2636 [self _didFinishScrolling];
2639 #if ENABLE(POINTER_EVENTS)
2640 - (CGPoint)_scrollView:(UIScrollView *)scrollView adjustedOffsetForOffset:(CGPoint)offset translation:(CGPoint)translation startPoint:(CGPoint)start locationInView:(CGPoint)locationInView horizontalVelocity:(inout double *)hv verticalVelocity:(inout double *)vv
2642 if (![_contentView preventsPanningInXAxis] && ![_contentView preventsPanningInYAxis]) {
2643 [_contentView cancelPointersForGestureRecognizer:scrollView.panGestureRecognizer];
2647 CGPoint adjustedContentOffset = CGPointMake(offset.x, offset.y);
2648 if ([_contentView preventsPanningInXAxis])
2649 adjustedContentOffset.x = start.x;
2650 if ([_contentView preventsPanningInYAxis])
2651 adjustedContentOffset.y = start.y;
2653 if ((![_contentView preventsPanningInXAxis] && adjustedContentOffset.x != start.x)
2654 || (![_contentView preventsPanningInYAxis] && adjustedContentOffset.y != start.y)) {
2655 [_contentView cancelPointersForGestureRecognizer:scrollView.panGestureRecognizer];
2658 return adjustedContentOffset;
2662 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
2664 if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidScroll:)])
2665 [_customContentView web_scrollViewDidScroll:(UIScrollView *)scrollView];
2667 [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2669 if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
2670 scrollPerfData->didScroll([self visibleRectInViewCoordinates]);
2673 - (void)scrollViewDidZoom:(UIScrollView *)scrollView
2675 if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidZoom:)])
2676 [_customContentView web_scrollViewDidZoom:scrollView];
2678 [self _updateScrollViewBackground];
2679 [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2682 - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
2684 if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidEndZooming:withView:atScale:)])
2685 [_customContentView web_scrollViewDidEndZooming:scrollView withView:view atScale:scale];
2687 ASSERT(scrollView == _scrollView);
2688 // FIXME: remove when rdar://problem/36065495 is fixed.
2689 // When rotating with two fingers down, UIScrollView can set a bogus content view position.
2690 // "Center" is top left because we set the anchorPoint to 0,0.
2691 [_contentView setCenter:self.bounds.origin];
2693 [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2694 [_contentView didZoomToScale:scale];
2697 - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
2699 [self _didFinishScrolling];
2702 - (void)_scrollViewDidInterruptDecelerating:(UIScrollView *)scrollView
2704 if (![self usesStandardContentView])
2707 [_contentView didInterruptScrolling];
2708 [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2711 - (UIView *)_enclosingViewForExposedRectComputation
2713 return [self _scroller];
2716 - (CGRect)_visibleRectInEnclosingView:(UIView *)enclosingView
2721 CGRect exposedRect = [enclosingView convertRect:enclosingView.bounds toView:self];
2722 return CGRectIntersectsRect(exposedRect, self.bounds) ? CGRectIntersection(exposedRect, self.bounds) : CGRectZero;
2725 - (CGRect)_visibleContentRect
2727 if (_frozenVisibleContentRect)
2728 return _frozenVisibleContentRect.value();
2730 CGRect visibleRectInContentCoordinates = [self convertRect:self.bounds toView:_contentView.get()];
2732 if (UIView *enclosingView = [self _enclosingViewForExposedRectComputation]) {
2733 CGRect viewVisibleRect = [self _visibleRectInEnclosingView:enclosingView];
2734 CGRect viewVisibleContentRect = [self convertRect:viewVisibleRect toView:_contentView.get()];
2735 visibleRectInContentCoordinates = CGRectIntersection(visibleRectInContentCoordinates, viewVisibleContentRect);
2738 return visibleRectInContentCoordinates;
2741 // Called when some ancestor UIScrollView scrolls.
2744 [self _scheduleVisibleContentRectUpdateAfterScrollInView:[self _scroller]];
2746 const NSTimeInterval ScrollingEndedTimerInterval = 0.032;
2747 if (!_enclosingScrollViewScrollTimer) {
2748 _enclosingScrollViewScrollTimer = adoptNS([[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:ScrollingEndedTimerInterval]
2749 interval:0 target:self selector:@selector(_enclosingScrollerScrollingEnded:) userInfo:nil repeats:YES]);
2750 [[NSRunLoop mainRunLoop] addTimer:_enclosingScrollViewScrollTimer.get() forMode:NSDefaultRunLoopMode];
2752 _didScrollSinceLastTimerFire = YES;
2755 - (void)_enclosingScrollerScrollingEnded:(NSTimer *)timer
2757 if (_didScrollSinceLastTimerFire) {
2758 _didScrollSinceLastTimerFire = NO;
2762 [self _scheduleVisibleContentRectUpdate];
2763 [_enclosingScrollViewScrollTimer invalidate];
2764 _enclosingScrollViewScrollTimer = nil;
2767 - (UIEdgeInsets)_scrollViewSystemContentInset
2769 // It's not safe to access the scroll view's safeAreaInsets or _systemContentInset from
2770 // inside our layoutSubviews implementation, because they aren't updated until afterwards.
2771 // Instead, depend on the fact that the UIScrollView and WKWebView are in the same coordinate
2772 // space, and map the WKWebView's own insets into the scroll view manually.
2773 return UIEdgeInsetsAdd([_scrollView _contentScrollInset], self.safeAreaInsets, [_scrollView _edgesApplyingSafeAreaInsetsToContentInset]);
2776 - (WebCore::FloatSize)activeViewLayoutSize:(const CGRect&)bounds
2778 if (_overridesViewLayoutSize)
2779 return WebCore::FloatSize(_viewLayoutSizeOverride);
2781 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2782 return WebCore::FloatSize(UIEdgeInsetsInsetRect(CGRectMake(0, 0, bounds.size.width, bounds.size.height), self._scrollViewSystemContentInset).size);
2784 return WebCore::FloatSize { bounds.size };
2788 - (void)_dispatchSetViewLayoutSize:(WebCore::FloatSize)viewLayoutSize
2790 if (_lastSentViewLayoutSize && CGSizeEqualToSize(_lastSentViewLayoutSize.value(), viewLayoutSize))
2793 LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _dispatchSetViewLayoutSize:] " << viewLayoutSize << " contentZoomScale " << contentZoomScale(self));
2794 _page->setViewportConfigurationViewLayoutSize(viewLayoutSize, _page->layoutSizeScaleFactor(), _minimumEffectiveDeviceWidth);
2795 _lastSentViewLayoutSize = viewLayoutSize;
2798 - (void)_dispatchSetMaximumUnobscuredSize:(WebCore::FloatSize)maximumUnobscuredSize
2800 if (_lastSentMaximumUnobscuredSize && CGSizeEqualToSize(_lastSentMaximumUnobscuredSize.value(), maximumUnobscuredSize))
2803 _page->setMaximumUnobscuredSize(maximumUnobscuredSize);
2804 _lastSentMaximumUnobscuredSize = maximumUnobscuredSize;
2807 - (void)_dispatchSetDeviceOrientation:(int32_t)deviceOrientation
2809 if (_lastSentDeviceOrientation && _lastSentDeviceOrientation.value() == deviceOrientation)
2812 _page->setDeviceOrientation(deviceOrientation);
2813 _lastSentDeviceOrientation = deviceOrientation;
2816 - (void)_frameOrBoundsChanged
2818 CGRect bounds = self.bounds;
2819 [_scrollView setFrame:bounds];
2821 if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing) {
2822 if (!_overridesViewLayoutSize)
2823 [self _dispatchSetViewLayoutSize:[self activeViewLayoutSize:self.bounds]];
2824 if (!_overridesMaximumUnobscuredSize)
2825 [self _dispatchSetMaximumUnobscuredSize:WebCore::FloatSize(bounds.size)];
2827 BOOL sizeChanged = NO;
2828 if (auto drawingArea = _page->drawingArea())
2829 sizeChanged = drawingArea->setSize(WebCore::IntSize(bounds.size));
2831 if (sizeChanged & [self usesStandardContentView])
2832 [_contentView setSizeChangedSinceLastVisibleContentRectUpdate:YES];
2835 [_customContentView web_setMinimumSize:bounds.size];
2836 [self _scheduleVisibleContentRectUpdate];
2839 // 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.
2840 - (CGRect)_contentRectForUserInteraction
2842 // FIXME: handle split keyboard.
2843 UIEdgeInsets obscuredInsets = _obscuredInsets;
2844 obscuredInsets.bottom = std::max(_obscuredInsets.bottom, _inputViewBounds.size.height);
2845 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInsets);
2846 return [self convertRect:unobscuredRect toView:self._currentContentView];
2849 // Ideally UIScrollView would expose this for us: <rdar://problem/21394567>.
2850 - (BOOL)_scrollViewIsRubberBanding
2852 float deviceScaleFactor = _page->deviceScaleFactor();
2854 CGPoint contentOffset = [_scrollView contentOffset];
2855 CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
2856 return !pointsEqualInDevicePixels(contentOffset, boundedOffset, deviceScaleFactor);
2859 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2860 - (void)safeAreaInsetsDidChange
2862 [super safeAreaInsetsDidChange];
2864 [self _scheduleVisibleContentRectUpdate];
2868 - (void)_scheduleVisibleContentRectUpdate
2870 // For visible rect updates not associated with a specific UIScrollView, just consider our own scroller.
2871 [self _scheduleVisibleContentRectUpdateAfterScrollInView:_scrollView.get()];
2874 - (BOOL)_scrollViewIsInStableState:(UIScrollView *)scrollView
2876 BOOL isStableState = !([scrollView isDragging] || [scrollView isDecelerating] || [scrollView isZooming] || [scrollView _isAnimatingZoom] || [scrollView _isScrollingToTop]);
2878 if (isStableState && scrollView == _scrollView.get())
2879 isStableState = !_isChangingObscuredInsetsInteractively;
2881 if (isStableState && scrollView == _scrollView.get())
2882 isStableState = ![self _scrollViewIsRubberBanding];
2885 isStableState = !scrollView._isInterruptingDeceleration;
2887 if (NSNumber *stableOverride = self._stableStateOverride)
2888 isStableState = stableOverride.boolValue;
2890 return isStableState;
2893 - (void)_addUpdateVisibleContentRectPreCommitHandler
2895 auto retainedSelf = retainPtr(self);
2896 [CATransaction addCommitHandler:[retainedSelf] {
2897 WKWebView *webView = retainedSelf.get();
2898 if (![webView _isValid]) {
2899 RELEASE_LOG_IF(webView._page && webView._page->isAlwaysOnLoggingAllowed(), ViewState, "In CATransaction preCommitHandler, WKWebView %p is invalid", webView);
2904 [webView _updateVisibleContentRects];
2905 } @catch (NSException *exception) {
2906 RELEASE_LOG_IF(webView._page && webView._page->isAlwaysOnLoggingAllowed(), ViewState, "In CATransaction preCommitHandler, -[WKWebView %p _updateVisibleContentRects] threw an exception", webView);
2908 webView->_hasScheduledVisibleRectUpdate = NO;
2909 } forPhase:kCATransactionPhasePreCommit];
2912 - (void)_scheduleVisibleContentRectUpdateAfterScrollInView:(UIScrollView *)scrollView
2914 _visibleContentRectUpdateScheduledFromScrollViewInStableState = [self _scrollViewIsInStableState:scrollView];
2916 if (_hasScheduledVisibleRectUpdate) {
2917 auto timeNow = MonotonicTime::now();
2918 if ((timeNow - _timeOfRequestForVisibleContentRectUpdate) > delayBeforeNoVisibleContentsRectsLogging) {
2919 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",
2920 self, (timeNow - _timeOfRequestForVisibleContentRectUpdate).value(), (timeNow - _timeOfLastVisibleContentRectUpdate).value(), [self _isValid]);
2925 _hasScheduledVisibleRectUpdate = YES;
2926 _timeOfRequestForVisibleContentRectUpdate = MonotonicTime::now();
2928 CATransactionPhase transactionPhase = [CATransaction currentPhase];
2929 if (transactionPhase == kCATransactionPhaseNull || transactionPhase == kCATransactionPhasePreLayout) {
2930 [self _addUpdateVisibleContentRectPreCommitHandler];
2934 dispatch_async(dispatch_get_main_queue(), [retainedSelf = retainPtr(self)] {
2935 WKWebView *webView = retainedSelf.get();
2936 if (![webView _isValid])
2938 [webView _addUpdateVisibleContentRectPreCommitHandler];
2942 static bool scrollViewCanScroll(UIScrollView *scrollView)
2947 UIEdgeInsets contentInset = scrollView.contentInset;
2948 CGSize contentSize = scrollView.contentSize;
2949 CGSize boundsSize = scrollView.bounds.size;
2951 return (contentSize.width + contentInset.left + contentInset.right) > boundsSize.width
2952 || (contentSize.height + contentInset.top + contentInset.bottom) > boundsSize.height;
2955 - (CGRect)_contentBoundsExtendedForRubberbandingWithScale:(CGFloat)scaleFactor
2957 CGPoint contentOffset = [_scrollView contentOffset];
2958 CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
2960 CGFloat horiontalRubberbandAmountInContentCoordinates = (contentOffset.x - boundedOffset.x) / scaleFactor;
2961 CGFloat verticalRubberbandAmountInContentCoordinates = (contentOffset.y - boundedOffset.y) / scaleFactor;
2963 CGRect extendedBounds = [_contentView bounds];
2965 if (horiontalRubberbandAmountInContentCoordinates < 0) {
2966 extendedBounds.origin.x += horiontalRubberbandAmountInContentCoordinates;
2967 extendedBounds.size.width -= horiontalRubberbandAmountInContentCoordinates;
2968 } else if (horiontalRubberbandAmountInContentCoordinates > 0)
2969 extendedBounds.size.width += horiontalRubberbandAmountInContentCoordinates;
2971 if (verticalRubberbandAmountInContentCoordinates < 0) {
2972 extendedBounds.origin.y += verticalRubberbandAmountInContentCoordinates;
2973 extendedBounds.size.height -= verticalRubberbandAmountInContentCoordinates;
2974 } else if (verticalRubberbandAmountInContentCoordinates > 0)
2975 extendedBounds.size.height += verticalRubberbandAmountInContentCoordinates;
2977 return extendedBounds;
2980 - (void)_updateVisibleContentRects
2982 BOOL inStableState = _visibleContentRectUpdateScheduledFromScrollViewInStableState;
2984 if (![self usesStandardContentView]) {
2985 [_passwordView setFrame:self.bounds];
2986 [_customContentView web_computedContentInsetDidChange];
2987 RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] - usesStandardContentView is NO, bailing", self);
2991 if (_delayUpdateVisibleContentRects) {
2992 _hadDelayedUpdateVisibleContentRects = YES;
2993 RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] - _delayUpdateVisibleContentRects is YES, bailing", self);
2997 if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing
2998 || (_needsResetViewStateAfterCommitLoadForMainFrame && ![_contentView sizeChangedSinceLastVisibleContentRectUpdate])
2999 || [_scrollView isZoomBouncing]
3000 || _currentlyAdjustingScrollViewInsetsForKeyboard) {
3001 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)",
3002 self, _dynamicViewportUpdateMode, _needsResetViewStateAfterCommitLoadForMainFrame, [_contentView sizeChangedSinceLastVisibleContentRectUpdate], [_scrollView isZoomBouncing], _currentlyAdjustingScrollViewInsetsForKeyboard);
3006 CGRect visibleRectInContentCoordinates = [self _visibleContentRect];
3008 UIEdgeInsets computedContentInsetUnadjustedForKeyboard = [self _computedObscuredInset];
3009 if (!_haveSetObscuredInsets)
3010 computedContentInsetUnadjustedForKeyboard.bottom -= _totalScrollViewBottomInsetAdjustmentForKeyboard;
3012 CGFloat scaleFactor = contentZoomScale(self);
3014 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, computedContentInsetUnadjustedForKeyboard);
3015 CGRect unobscuredRectInContentCoordinates = _frozenUnobscuredContentRect ? _frozenUnobscuredContentRect.value() : [self convertRect:unobscuredRect toView:_contentView.get()];
3016 unobscuredRectInContentCoordinates = CGRectIntersection(unobscuredRectInContentCoordinates, [self _contentBoundsExtendedForRubberbandingWithScale:scaleFactor]);
3018 // The following logic computes the extent to which the bottom, top, left and right content insets are visible.
3019 auto scrollViewInsets = [_scrollView contentInset];
3020 auto scrollViewBounds = [_scrollView bounds];
3021 auto scrollViewContentSize = [_scrollView contentSize];
3022 auto scrollViewOriginIncludingInset = UIEdgeInsetsInsetRect(scrollViewBounds, computedContentInsetUnadjustedForKeyboard).origin;
3023 auto maximumVerticalScrollExtentWithoutRevealingBottomContentInset = scrollViewContentSize.height - CGRectGetHeight(scrollViewBounds);
3024 auto maximumHorizontalScrollExtentWithoutRevealingRightContentInset = scrollViewContentSize.width - CGRectGetWidth(scrollViewBounds);
3025 auto contentInsets = UIEdgeInsetsZero;
3026 if (scrollViewInsets.left > 0 && scrollViewOriginIncludingInset.x < 0)
3027 contentInsets.left = std::min(-scrollViewOriginIncludingInset.x, scrollViewInsets.left) / scaleFactor;
3029 if (scrollViewInsets.top > 0 && scrollViewOriginIncludingInset.y < 0)
3030 contentInsets.top = std::min(-scrollViewOriginIncludingInset.y, scrollViewInsets.top) / scaleFactor;
3032 if (scrollViewInsets.right > 0 && scrollViewOriginIncludingInset.x > maximumHorizontalScrollExtentWithoutRevealingRightContentInset)
3033 contentInsets.right = std::min(scrollViewOriginIncludingInset.x - maximumHorizontalScrollExtentWithoutRevealingRightContentInset, scrollViewInsets.right) / scaleFactor;
3035 if (scrollViewInsets.bottom > 0 && scrollViewOriginIncludingInset.y > maximumVerticalScrollExtentWithoutRevealingBottomContentInset)
3036 contentInsets.bottom = std::min(scrollViewOriginIncludingInset.y - maximumVerticalScrollExtentWithoutRevealingBottomContentInset, scrollViewInsets.bottom) / scaleFactor;
3038 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
3039 if (inStableState) {
3040 WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
3041 if (coordinator && coordinator->hasActiveSnapPoint()) {
3042 CGPoint currentPoint = [_scrollView contentOffset];
3043 CGPoint activePoint = coordinator->nearestActiveContentInsetAdjustedSnapPoint(unobscuredRect.origin.y, currentPoint);
3045 if (!CGPointEqualToPoint(activePoint, currentPoint)) {
3046 RetainPtr<WKScrollView> strongScrollView = _scrollView;
3047 dispatch_async(dispatch_get_main_queue(), [strongScrollView, activePoint] {
3048 [strongScrollView setContentOffset:activePoint animated:NO];
3055 [_contentView didUpdateVisibleRect:visibleRectInContentCoordinates
3056 unobscuredRect:unobscuredRectInContentCoordinates
3057 contentInsets:contentInsets
3058 unobscuredRectInScrollViewCoordinates:unobscuredRect
3059 obscuredInsets:_obscuredInsets
3060 unobscuredSafeAreaInsets:[self _computedUnobscuredSafeAreaInset]
3061 inputViewBounds:_inputViewBounds
3062 scale:scaleFactor minimumScale:[_scrollView minimumZoomScale]
3063 inStableState:inStableState
3064 isChangingObscuredInsetsInteractively:_isChangingObscuredInsetsInteractively
3065 enclosedInScrollableAncestorView:scrollViewCanScroll([self _scroller])];
3067 while (!_visibleContentRectUpdateCallbacks.isEmpty()) {
3068 auto callback = _visibleContentRectUpdateCallbacks.takeLast();
3072 auto timeNow = MonotonicTime::now();
3073 if ((timeNow - _timeOfRequestForVisibleContentRectUpdate) > delayBeforeNoVisibleContentsRectsLogging)
3074 RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] finally ran %.2fs after being scheduled", self, (timeNow - _timeOfRequestForVisibleContentRectUpdate).value());
3076 _timeOfLastVisibleContentRectUpdate = timeNow;
3079 - (void)_didStartProvisionalLoadForMainFrame
3081 if (_gestureController)
3082 _gestureController->didStartProvisionalLoadForMainFrame();
3085 static WebCore::FloatSize activeMaximumUnobscuredSize(WKWebView *webView, const CGRect& bounds)
3087 return WebCore::FloatSize(webView->_overridesMaximumUnobscuredSize ? webView->_maximumUnobscuredSizeOverride : bounds.size);
3090 static int32_t activeOrientation(WKWebView *webView)
3092 return webView->_overridesInterfaceOrientation ? deviceOrientationForUIInterfaceOrientation(webView->_interfaceOrientationOverride) : webView->_page->deviceOrientation();
3095 - (void)_cancelAnimatedResize
3097 LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _cancelAnimatedResize:] " << " _dynamicViewportUpdateMode " << (int)_dynamicViewportUpdateMode);
3098 if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing)
3101 if (!_customContentView) {
3102 if (_resizeAnimationView) {
3103 NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
3104 [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
3105 [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
3106 [_resizeAnimationView removeFromSuperview];
3107 _resizeAnimationView = nil;
3110 [_contentView setHidden:NO];
3111 _resizeAnimationTransformAdjustments = CATransform3DIdentity;
3114 _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
3115 [self _scheduleVisibleContentRectUpdate];
3118 - (void)_didCompleteAnimatedResize
3120 if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing)
3123 [_contentView setHidden:NO];
3125 if (!_resizeAnimationView) {
3126 // Paranoia. If _resizeAnimationView is null we'll end up setting a zero scale on the content view.
3127 RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didCompleteAnimatedResize:] - _resizeAnimationView is nil", self);
3128 [self _cancelAnimatedResize];
3132 NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
3133 [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
3134 [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
3136 CALayer *contentLayer = [_contentView layer];
3137 CGFloat adjustmentScale = _resizeAnimationTransformAdjustments.m11;
3138 contentLayer.sublayerTransform = CATransform3DIdentity;
3140 CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
3141 CATransform3D contentLayerTransform = contentLayer.transform;
3142 CGFloat currentScale = [[_resizeAnimationView layer] transform].m11 * contentLayerTransform.m11;
3144 // We cannot use [UIScrollView setZoomScale:] directly because the UIScrollView delegate would get a callback with
3145 // an invalid contentOffset. The real content offset is only set below.
3146 // Since there is no public API for setting both the zoomScale and the contentOffset, we set the zoomScale manually
3147 // on the zoom layer and then only change the contentOffset.
3148 CGFloat adjustedScale = adjustmentScale * currentScale;
3149 contentLayerTransform.m11 = adjustedScale;
3150 contentLayerTransform.m22 = adjustedScale;
3151 contentLayer.transform = contentLayerTransform;
3153 CGPoint currentScrollOffset = [_scrollView contentOffset];
3154 double horizontalScrollAdjustement = _resizeAnimationTransformAdjustments.m41 * animatingScaleTarget;
3155 double verticalScrollAdjustment = _resizeAnimationTransformAdjustments.m42 * animatingScaleTarget;
3157 [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
3158 [_scrollView setContentOffset:CGPointMake(currentScrollOffset.x - horizontalScrollAdjustement, currentScrollOffset.y - verticalScrollAdjustment)];
3160 [_resizeAnimationView removeFromSuperview];
3161 _resizeAnimationView = nil;
3162 _resizeAnimationTransformAdjustments = CATransform3DIdentity;
3164 _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
3165 [self _scheduleVisibleContentRectUpdate];
3167 CGRect newBounds = self.bounds;
3168 auto newViewLayoutSize = [self activeViewLayoutSize:newBounds];
3169 auto newMaximumUnobscuredSize = activeMaximumUnobscuredSize(self, newBounds);
3170 int32_t newOrientation = activeOrientation(self);
3172 if (!_lastSentViewLayoutSize || newViewLayoutSize != _lastSentViewLayoutSize.value())
3173 [self _dispatchSetViewLayoutSize:newViewLayoutSize];
3175 if (!_lastSentMaximumUnobscuredSize || newMaximumUnobscuredSize != _lastSentMaximumUnobscuredSize.value())
3176 [self _dispatchSetMaximumUnobscuredSize:WebCore::FloatSize(newMaximumUnobscuredSize)];
3178 if (!_lastSentDeviceOrientation || newOrientation != _lastSentDeviceOrientation.value())
3179 [self _dispatchSetDeviceOrientation:newOrientation];
3181 while (!_callbacksDeferredDuringResize.isEmpty())
3182 _callbacksDeferredDuringResize.takeLast()();
3185 - (void)_didFinishLoadForMainFrame
3187 if (_gestureController)
3188 _gestureController->didFinishLoadForMainFrame();
3191 - (void)_didFailLoadForMainFrame
3193 if (_gestureController)
3194 _gestureController->didFailLoadForMainFrame();
3197 - (void)_didSameDocumentNavigationForMainFrame:(WebKit::SameDocumentNavigationType)navigationType
3199 [_customContentView web_didSameDocumentNavigation:toAPI(navigationType)];
3201 if (_gestureController)
3202 _gestureController->didSameDocumentNavigationForMainFrame(navigationType);
3205 - (void)_keyboardChangedWithInfo:(NSDictionary *)keyboardInfo adjustScrollView:(BOOL)adjustScrollView
3207 NSValue *endFrameValue = [keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
3211 // The keyboard rect is always in screen coordinates. In the view services case the window does not
3212 // have the interface orientation rotation transformation; its host does. So, it makes no sense to
3213 // clip the keyboard rect against its screen.
3214 if ([[self window] _isHostedInAnotherProcess])
3215 _inputViewBounds = [self.window convertRect:[endFrameValue CGRectValue] fromWindow:nil];
3217 _inputViewBounds = [self.window convertRect:CGRectIntersection([endFrameValue CGRectValue], self.window.screen.bounds) fromWindow:nil];
3219 if ([[UIPeripheralHost sharedInstance] isUndocked])
3220 _inputViewBounds = CGRectZero;
3222 if (adjustScrollView) {
3223 CGFloat bottomInsetBeforeAdjustment = [_scrollView contentInset].bottom;
3224 SetForScope<BOOL> insetAdjustmentGuard(_currentlyAdjustingScrollViewInsetsForKeyboard, YES);
3225 [_scrollView _adjustForAutomaticKeyboardInfo:keyboardInfo animated:YES lastAdjustment:&_lastAdjustmentForScroller];
3226 CGFloat bottomInsetAfterAdjustment = [_scrollView contentInset].bottom;
3227 if (bottomInsetBeforeAdjustment != bottomInsetAfterAdjustment)
3228 _totalScrollViewBottomInsetAdjustmentForKeyboard += bottomInsetAfterAdjustment - bottomInsetBeforeAdjustment;
3231 [self _scheduleVisibleContentRectUpdate];
3234 - (BOOL)_shouldUpdateKeyboardWithInfo:(NSDictionary *)keyboardInfo
3236 if ([_contentView isFocusingElement])
3239 NSNumber *isLocalKeyboard = [keyboardInfo valueForKey:UIKeyboardIsLocalUserInfoKey];
3240 return isLocalKeyboard && !isLocalKeyboard.boolValue;
3243 - (void)_keyboardWillChangeFrame:(NSNotification *)notification
3245 if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
3246 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
3249 - (void)_keyboardDidChangeFrame:(NSNotification *)notification
3251 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:NO];
3254 - (void)_keyboardWillShow:(NSNotification *)notification
3256 if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
3257 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
3259 _page->setIsKeyboardAnimatingIn(true);
3262 - (void)_keyboardDidShow:(NSNotification *)notification
3264 _page->setIsKeyboardAnimatingIn(false);
3267 - (void)_keyboardWillHide:(NSNotification *)notification
3269 // Ignore keyboard will hide notifications sent during rotation. They're just there for
3270 // backwards compatibility reasons and processing the will hide notification would
3271 // temporarily screw up the unobscured view area.
3272 if ([[UIPeripheralHost sharedInstance] rotationState])
3275 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
3278 static void hardwareKeyboardAvailabilityChangedCallback(CFNotificationCenterRef, void* observer, CFStringRef, const void*, CFDictionaryRef)
3281 WKWebView *webView = (__bridge WKWebView *)observer;
3282 webView._page->hardwareKeyboardAvailabilityChanged();
3285 - (void)_windowDidRotate:(NSNotification *)notification
3287 if (!_overridesInterfaceOrientation)
3288 [self _dispatchSetDeviceOrientation:deviceOrientation()];
3291 - (void)_contentSizeCategoryDidChange:(NSNotification *)notification
3293 _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
3296 - (NSString *)_contentSizeCategory
3298 return [[UIApplication sharedApplication] preferredContentSizeCategory];
3301 - (void)_accessibilitySettingsDidChange:(NSNotification *)notification
3303 _page->accessibilitySettingsDidChange();
3306 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
3308 if (_allowsBackForwardNavigationGestures == allowsBackForwardNavigationGestures)
3311 _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
3313 if (allowsBackForwardNavigationGestures && !_gestureController) {
3314 _gestureController = std::make_unique<WebKit::ViewGestureController>(*_page);
3315 _gestureController->installSwipeHandler(self, [self scrollView]);
3316 if (WKWebView *alternateWebView = [_configuration _alternateWebViewForNavigationGestures])
3317 _gestureController->setAlternateBackForwardListSourcePage(alternateWebView->_page.get());
3320 if (_gestureController)
3321 _gestureController->setSwipeGestureEnabled(allowsBackForwardNavigationGestures);
3323 _page->setShouldRecordNavigationSnapshots(allowsBackForwardNavigationGestures);
3326 - (BOOL)allowsBackForwardNavigationGestures
3328 return _allowsBackForwardNavigationGestures;
3331 - (BOOL)_isNavigationSwipeGestureRecognizer:(UIGestureRecognizer *)recognizer
3333 if (!_gestureController)
3335 return _gestureController->isNavigationSwipeGestureRecognizer(recognizer);
3338 - (void)_navigationGestureDidBegin
3340 // During a back/forward swipe, there's a view interposed between this view and the content view that has
3341 // an offset and animation on it, which results in computing incorrect rectangles. Work around by using
3342 // frozen rects during swipes.
3343 CGRect fullViewRect = self.bounds;
3344 CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, [self _computedObscuredInset]);
3346 _frozenVisibleContentRect = [self convertRect:fullViewRect toView:_contentView.get()];
3347 _frozenUnobscuredContentRect = [self convertRect:unobscuredRect toView:_contentView.get()];
3349 LOG_WITH_STREAM(VisibleRects, stream << "_navigationGestureDidBegin: freezing visibleContentRect " << WebCore::FloatRect(_frozenVisibleContentRect.value()) << " UnobscuredContentRect " << WebCore::FloatRect(_frozenUnobscuredContentRect.value()));
3352 - (void)_navigationGestureDidEnd
3354 _frozenVisibleContentRect = WTF::nullopt;
3355 _frozenUnobscuredContentRect = WTF::nullopt;
3358 - (void)_showPasswordViewWithDocumentName:(NSString *)documentName passwordHandler:(void (^)(NSString *))passwordHandler
3360 ASSERT(!_passwordView);
3361 _passwordView = adoptNS([[WKPasswordView alloc] initWithFrame:self.bounds documentName:documentName]);
3362 [_passwordView setUserDidEnterPassword:passwordHandler];
3363 [_passwordView showInScrollView:_scrollView.get()];
3364 self._currentContentView.hidden = YES;
3367 - (void)_hidePasswordView
3372 self._currentContentView.hidden = NO;
3373 [_passwordView hide];
3374 _passwordView = nil;
3377 - (WKPasswordView *)_passwordView
3379 return _passwordView.get();
3382 - (void)_updateScrollViewInsetAdjustmentBehavior
3384 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
3385 if (![_scrollView _contentInsetAdjustmentBehaviorWasExternallyOverridden])
3386 [_scrollView _setContentInsetAdjustmentBehaviorInternal:self._safeAreaShouldAffectObscuredInsets ? UIScrollViewContentInsetAdjustmentAlways : UIScrollViewContentInsetAdjustmentNever];
3390 - (void)_setAvoidsUnsafeArea:(BOOL)avoidsUnsafeArea
3392 if (_avoidsUnsafeArea == avoidsUnsafeArea)
3395 _avoidsUnsafeArea = avoidsUnsafeArea;
3397 [self _updateScrollViewInsetAdjustmentBehavior];
3398 [self _scheduleVisibleContentRectUpdate];
3400 id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)[self UIDelegate];
3401 if ([uiDelegate respondsToSelector:@selector(_webView:didChangeSafeAreaShouldAffectObscuredInsets:)])
3402 [uiDelegate _webView:self didChangeSafeAreaShouldAffectObscuredInsets:avoidsUnsafeArea];
3405 - (BOOL)_haveSetObscuredInsets
3407 return _haveSetObscuredInsets;