2 * Copyright (C) 2014-2016 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 "FindClient.h"
37 #import "FullscreenClient.h"
38 #import "IconLoadingDelegate.h"
39 #import "LegacySessionStateCoding.h"
41 #import "NavigationState.h"
42 #import "ObjCObjectGraph.h"
43 #import "RemoteLayerTreeScrollingPerformanceData.h"
44 #import "RemoteLayerTreeTransaction.h"
45 #import "RemoteObjectRegistry.h"
46 #import "RemoteObjectRegistryMessages.h"
47 #import "UIDelegate.h"
48 #import "ViewGestureController.h"
49 #import "ViewSnapshotStore.h"
50 #import "WKBackForwardListInternal.h"
51 #import "WKBackForwardListItemInternal.h"
52 #import "WKBrowsingContextHandleInternal.h"
53 #import "WKErrorInternal.h"
54 #import "WKHistoryDelegatePrivate.h"
55 #import "WKLayoutMode.h"
57 #import "WKNSURLExtras.h"
58 #import "WKNavigationDelegate.h"
59 #import "WKNavigationInternal.h"
60 #import "WKPreferencesInternal.h"
61 #import "WKProcessPoolInternal.h"
62 #import "WKSharedAPICast.h"
63 #import "WKUIDelegate.h"
64 #import "WKUIDelegatePrivate.h"
65 #import "WKUserContentControllerInternal.h"
66 #import "WKWebViewConfigurationInternal.h"
67 #import "WKWebViewContentProvider.h"
68 #import "WKWebsiteDataStoreInternal.h"
69 #import "WebBackForwardList.h"
70 #import "WebCertificateInfo.h"
71 #import "WebFormSubmissionListenerProxy.h"
72 #import "WebFullScreenManagerProxy.h"
73 #import "WebKitSystemInterface.h"
74 #import "WebPageGroup.h"
75 #import "WebPageProxy.h"
76 #import "WebPreferencesKeys.h"
77 #import "WebProcessPool.h"
78 #import "WebProcessProxy.h"
79 #import "WebViewImpl.h"
80 #import "_WKDiagnosticLoggingDelegate.h"
81 #import "_WKFindDelegate.h"
82 #import "_WKFrameHandleInternal.h"
83 #import "_WKFullscreenDelegate.h"
84 #import "_WKHitTestResultInternal.h"
85 #import "_WKInputDelegate.h"
86 #import "_WKRemoteObjectRegistryInternal.h"
87 #import "_WKSessionStateInternal.h"
88 #import "_WKVisitedLinkStoreInternal.h"
89 #import <WebCore/GraphicsContextCG.h>
90 #import <WebCore/IOSurface.h>
91 #import <WebCore/JSDOMBinding.h>
92 #import <WebCore/NSTextFinderSPI.h>
93 #import <WebCore/PlatformScreen.h>
94 #import <WebCore/RuntimeApplicationChecks.h>
95 #import <WebCore/Settings.h>
96 #import <WebCore/TextStream.h>
97 #import <WebCore/ValidationBubble.h>
98 #import <WebCore/WritingMode.h>
99 #import <wtf/HashMap.h>
100 #import <wtf/MathExtras.h>
101 #import <wtf/NeverDestroyed.h>
102 #import <wtf/Optional.h>
103 #import <wtf/RetainPtr.h>
104 #import <wtf/SetForScope.h>
105 #import <wtf/spi/darwin/dyldSPI.h>
108 #import "_WKWebViewPrintFormatter.h"
109 #import "ProcessThrottler.h"
110 #import "RemoteLayerTreeDrawingAreaProxy.h"
111 #import "RemoteScrollingCoordinatorProxy.h"
113 #import "WKContentViewInteraction.h"
114 #import "WKPDFView.h"
115 #import "WKScrollView.h"
116 #import "WKWebViewContentProviderRegistry.h"
117 #import "WebVideoFullscreenManagerProxy.h"
118 #import <UIKit/UIApplication.h>
119 #import <WebCore/CoreGraphicsSPI.h>
120 #import <WebCore/FrameLoaderTypes.h>
121 #import <WebCore/InspectorOverlay.h>
122 #import <WebCore/QuartzCoreSPI.h>
123 #import <WebCore/ScrollableArea.h>
125 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000
126 #if __has_include(<AccessibilitySupport.h>)
127 #include <AccessibilitySupport.h>
130 CFStringRef kAXSAllowForceWebScalingEnabledNotification;
135 @interface UIScrollView (UIScrollViewInternal)
136 - (void)_adjustForAutomaticKeyboardInfo:(NSDictionary*)info animated:(BOOL)animated lastAdjustment:(CGFloat*)lastAdjustment;
137 - (BOOL)_isScrollingToTop;
138 - (BOOL)_isInterruptingDeceleration;
139 - (CGPoint)_animatedTargetOffset;
142 @interface UIPeripheralHost(UIKitInternal)
143 - (CGFloat)getVerticalOverlapForView:(UIView *)view usingKeyboardInfo:(NSDictionary *)info;
146 @interface UIView (UIViewInternal)
147 - (UIViewController *)_viewControllerForAncestor;
150 @interface UIWindow (UIWindowInternal)
151 - (BOOL)_isHostedInAnotherProcess;
154 @interface UIViewController (UIViewControllerInternal)
155 - (UIViewController *)_rootAncestorViewController;
156 - (UIViewController *)_viewControllerForSupportedInterfaceOrientations;
159 enum class DynamicViewportUpdateMode {
161 ResizingWithAnimation,
162 ResizingWithDocumentHidden,
165 #endif // PLATFORM(IOS)
168 static const uint32_t firstSDKVersionWithLinkPreviewEnabledByDefault = 0xA0000;
172 #import "WKTextFinderClient.h"
173 #import "WKViewInternal.h"
174 #import <WebCore/ColorMac.h>
176 @interface WKWebView () <WebViewImplDelegate, NSTextInputClient>
180 @interface WKWebView () <NSTouchBarProvider>
182 #endif // HAVE(TOUCH_BAR)
183 #endif // PLATFORM(MAC)
185 static HashMap<WebKit::WebPageProxy*, WKWebView *>& pageToViewMap()
187 static NeverDestroyed<HashMap<WebKit::WebPageProxy*, WKWebView *>> map;
191 WKWebView* fromWebPageProxy(WebKit::WebPageProxy& page)
193 return pageToViewMap().get(&page);
196 @implementation WKWebView {
197 std::unique_ptr<WebKit::NavigationState> _navigationState;
198 std::unique_ptr<WebKit::UIDelegate> _uiDelegate;
199 std::unique_ptr<WebKit::IconLoadingDelegate> _iconLoadingDelegate;
201 _WKRenderingProgressEvents _observedRenderingProgressEvents;
203 WebKit::WeakObjCPtr<id <_WKInputDelegate>> _inputDelegate;
206 RetainPtr<_WKRemoteObjectRegistry> _remoteObjectRegistry;
208 RetainPtr<WKScrollView> _scrollView;
209 RetainPtr<WKContentView> _contentView;
211 BOOL _overridesMinimumLayoutSize;
212 CGSize _minimumLayoutSizeOverride;
213 BOOL _overridesMaximumUnobscuredSize;
214 CGSize _maximumUnobscuredSizeOverride;
215 CGRect _inputViewBounds;
216 CGFloat _viewportMetaTagWidth;
217 BOOL _viewportMetaTagWidthWasExplicit;
218 BOOL _viewportMetaTagCameFromImageDocument;
219 CGFloat _initialScaleFactor;
220 BOOL _fastClickingIsDisabled;
222 BOOL _allowsLinkPreview;
224 UIEdgeInsets _obscuredInsets;
225 BOOL _haveSetObscuredInsets;
226 BOOL _isChangingObscuredInsetsInteractively;
228 UIInterfaceOrientation _interfaceOrientationOverride;
229 BOOL _overridesInterfaceOrientation;
231 BOOL _allowsViewportShrinkToFit;
233 BOOL _hasCommittedLoadForMainFrame;
234 BOOL _needsResetViewStateAfterCommitLoadForMainFrame;
235 uint64_t _firstPaintAfterCommitLoadTransactionID;
236 DynamicViewportUpdateMode _dynamicViewportUpdateMode;
237 CATransform3D _resizeAnimationTransformAdjustments;
238 Optional<uint64_t> _resizeAnimationTransformTransactionID;
239 RetainPtr<UIView> _resizeAnimationView;
240 CGFloat _lastAdjustmentForScroller;
241 Optional<CGRect> _frozenVisibleContentRect;
242 Optional<CGRect> _frozenUnobscuredContentRect;
244 BOOL _needsToRestoreScrollPosition;
245 BOOL _commitDidRestoreScrollPosition;
246 WebCore::FloatPoint _scrollOffsetToRestore;
247 WebCore::FloatSize _obscuredInsetWhenSaved;
249 BOOL _needsToRestoreUnobscuredCenter;
250 WebCore::FloatPoint _unobscuredCenterToRestore;
251 uint64_t _firstTransactionIDAfterPageRestore;
252 double _scaleToRestore;
254 std::unique_ptr<WebKit::ViewGestureController> _gestureController;
255 BOOL _allowsBackForwardNavigationGestures;
257 RetainPtr<UIView <WKWebViewContentProvider>> _customContentView;
258 RetainPtr<UIView> _customContentFixedOverlayView;
260 RetainPtr<NSTimer> _enclosingScrollViewScrollTimer;
261 BOOL _didScrollSinceLastTimerFire;
263 WebCore::Color _scrollViewBackgroundColor;
265 // This value tracks the current adjustment added to the bottom inset due to the keyboard sliding out from the bottom
266 // when computing obscured content insets. This is used when updating the visible content rects where we should not
267 // include this adjustment.
268 CGFloat _totalScrollViewBottomInsetAdjustmentForKeyboard;
269 BOOL _currentlyAdjustingScrollViewInsetsForKeyboard;
271 BOOL _delayUpdateVisibleContentRects;
272 BOOL _hadDelayedUpdateVisibleContentRects;
274 Vector<std::function<void ()>> _snapshotsDeferredDuringResize;
277 std::unique_ptr<WebKit::WebViewImpl> _impl;
278 RetainPtr<WKTextFinderClient> _textFinderClient;
282 - (instancetype)initWithFrame:(CGRect)frame
284 return [self initWithFrame:frame configuration:adoptNS([[WKWebViewConfiguration alloc] init]).get()];
288 static int32_t deviceOrientationForUIInterfaceOrientation(UIInterfaceOrientation orientation)
290 switch (orientation) {
291 case UIInterfaceOrientationUnknown:
292 case UIInterfaceOrientationPortrait:
294 case UIInterfaceOrientationPortraitUpsideDown:
296 case UIInterfaceOrientationLandscapeLeft:
298 case UIInterfaceOrientationLandscapeRight:
303 static int32_t deviceOrientation()
305 return deviceOrientationForUIInterfaceOrientation([[UIApplication sharedApplication] statusBarOrientation]);
308 - (BOOL)_isShowingVideoPictureInPicture
313 if (!_page || !_page->videoFullscreenManager())
316 return _page->videoFullscreenManager()->hasMode(WebCore::HTMLMediaElementEnums::VideoFullscreenModePictureInPicture);
320 - (BOOL)_mayAutomaticallyShowVideoPictureInPicture
325 if (!_page || !_page->videoFullscreenManager())
328 return _page->videoFullscreenManager()->mayAutomaticallyShowVideoPictureInPicture();
332 static bool shouldAllowPictureInPictureMediaPlayback()
334 static bool shouldAllowPictureInPictureMediaPlayback = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_9_0;
335 return shouldAllowPictureInPictureMediaPlayback;
340 static bool shouldRequireUserGestureToLoadVideo()
343 static bool shouldRequireUserGestureToLoadVideo = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
344 return shouldRequireUserGestureToLoadVideo;
350 #if ENABLE(DATA_DETECTION) && PLATFORM(IOS)
351 static WebCore::DataDetectorTypes fromWKDataDetectorTypes(uint64_t types)
353 if (static_cast<WKDataDetectorTypes>(types) == WKDataDetectorTypeNone)
354 return WebCore::DataDetectorTypeNone;
355 if (static_cast<WKDataDetectorTypes>(types) == WKDataDetectorTypeAll)
356 return WebCore::DataDetectorTypeAll;
358 uint32_t value = WebCore::DataDetectorTypeNone;
359 if (types & WKDataDetectorTypePhoneNumber)
360 value |= WebCore::DataDetectorTypePhoneNumber;
361 if (types & WKDataDetectorTypeLink)
362 value |= WebCore::DataDetectorTypeLink;
363 if (types & WKDataDetectorTypeAddress)
364 value |= WebCore::DataDetectorTypeAddress;
365 if (types & WKDataDetectorTypeCalendarEvent)
366 value |= WebCore::DataDetectorTypeCalendarEvent;
367 if (types & WKDataDetectorTypeTrackingNumber)
368 value |= WebCore::DataDetectorTypeTrackingNumber;
369 if (types & WKDataDetectorTypeFlightNumber)
370 value |= WebCore::DataDetectorTypeFlightNumber;
371 if (types & WKDataDetectorTypeLookupSuggestion)
372 value |= WebCore::DataDetectorTypeLookupSuggestion;
374 return static_cast<WebCore::DataDetectorTypes>(value);
379 static uint32_t convertUserInterfaceDirectionPolicy(WKUserInterfaceDirectionPolicy policy)
382 case WKUserInterfaceDirectionPolicyContent:
383 return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content);
384 case WKUserInterfaceDirectionPolicySystem:
385 return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::System);
387 return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content);
390 static uint32_t convertSystemLayoutDirection(NSUserInterfaceLayoutDirection direction)
393 case NSUserInterfaceLayoutDirectionLeftToRight:
394 return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::LTR);
395 case NSUserInterfaceLayoutDirectionRightToLeft:
396 return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::RTL);
398 return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::LTR);
402 - (void)_initializeWithConfiguration:(WKWebViewConfiguration *)configuration
405 [NSException raise:NSInvalidArgumentException format:@"Configuration cannot be nil"];
407 _configuration = adoptNS([configuration copy]);
409 if (WKWebView *relatedWebView = [_configuration _relatedWebView]) {
410 WKProcessPool *processPool = [_configuration processPool];
411 WKProcessPool *relatedWebViewProcessPool = [relatedWebView->_configuration processPool];
412 if (processPool && processPool != relatedWebViewProcessPool)
413 [NSException raise:NSInvalidArgumentException format:@"Related web view %@ has process pool %@ but configuration specifies a different process pool %@", relatedWebView, relatedWebViewProcessPool, configuration.processPool];
415 [_configuration setProcessPool:relatedWebViewProcessPool];
418 [_configuration _validate];
420 WebKit::WebProcessPool& processPool = *[_configuration processPool]->_processPool;
421 processPool.setResourceLoadStatisticsEnabled(configuration.websiteDataStore._resourceLoadStatisticsEnabled);
423 auto pageConfiguration = API::PageConfiguration::create();
425 pageConfiguration->setProcessPool(&processPool);
426 pageConfiguration->setPreferences([_configuration preferences]->_preferences.get());
427 if (WKWebView *relatedWebView = [_configuration _relatedWebView])
428 pageConfiguration->setRelatedPage(relatedWebView->_page.get());
430 pageConfiguration->setUserContentController([_configuration userContentController]->_userContentControllerProxy.get());
431 pageConfiguration->setVisitedLinkStore([_configuration _visitedLinkStore]->_visitedLinkStore.get());
432 pageConfiguration->setWebsiteDataStore([_configuration websiteDataStore]->_websiteDataStore.get());
433 pageConfiguration->setTreatsSHA1SignedCertificatesAsInsecure([_configuration _treatsSHA1SignedCertificatesAsInsecure]);
435 RefPtr<WebKit::WebPageGroup> pageGroup;
436 NSString *groupIdentifier = configuration._groupIdentifier;
437 if (groupIdentifier.length) {
438 pageGroup = WebKit::WebPageGroup::create(configuration._groupIdentifier);
439 pageConfiguration->setPageGroup(pageGroup.get());
442 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::suppressesIncrementalRenderingKey(), WebKit::WebPreferencesStore::Value(!![_configuration suppressesIncrementalRendering]));
444 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldRespectImageOrientationKey(), WebKit::WebPreferencesStore::Value(!![_configuration _respectsImageOrientation]));
445 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldPrintBackgroundsKey(), WebKit::WebPreferencesStore::Value(!![_configuration _printsBackgrounds]));
446 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey(), WebKit::WebPreferencesStore::Value([_configuration _incrementalRenderingSuppressionTimeout]));
447 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::javaScriptMarkupEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsJavaScriptMarkup]));
448 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldConvertPositionStyleOnCopyKey(), WebKit::WebPreferencesStore::Value(!![_configuration _convertsPositionStyleOnCopy]));
449 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::httpEquivEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsMetaRefresh]));
450 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowUniversalAccessFromFileURLsKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowUniversalAccessFromFileURLs]));
451 pageConfiguration->setInitialCapitalizationEnabled([_configuration _initialCapitalizationEnabled]);
452 pageConfiguration->setWaitsForPaintAfterViewDidMoveToWindow([_configuration _waitsForPaintAfterViewDidMoveToWindow]);
455 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::showsURLsInToolTipsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _showsURLsInToolTips]));
456 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::serviceControlsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _serviceControlsEnabled]));
457 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::imageControlsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _imageControlsEnabled]));
459 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::userInterfaceDirectionPolicyKey(), WebKit::WebPreferencesStore::Value(convertUserInterfaceDirectionPolicy([_configuration userInterfaceDirectionPolicy])));
460 // We are in the View's initialization routine, so our client hasn't had time to set our user interface direction.
461 // Therefore, according to the docs[1], "this property contains the value reported by the app's userInterfaceLayoutDirection property."
462 // [1] http://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/index.html#//apple_ref/doc/uid/20000014-SW222
463 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::systemLayoutDirectionKey(), WebKit::WebPreferencesStore::Value(convertSystemLayoutDirection(self.userInterfaceLayoutDirection)));
467 pageConfiguration->setAlwaysRunsAtForegroundPriority([_configuration _alwaysRunsAtForegroundPriority]);
469 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsInlineMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsInlineMediaPlayback]));
470 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsInlineMediaPlaybackAfterFullscreenKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsInlineMediaPlaybackAfterFullscreen]));
471 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::inlineMediaPlaybackRequiresPlaysInlineAttributeKey(), WebKit::WebPreferencesStore::Value(!![_configuration _inlineMediaPlaybackRequiresPlaysInlineAttribute]));
472 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsPictureInPictureMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback()));
473 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::userInterfaceDirectionPolicyKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content)));
474 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::systemLayoutDirectionKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(WebCore::LTR)));
477 WKAudiovisualMediaTypes mediaTypesRequiringUserGesture = [_configuration mediaTypesRequiringUserActionForPlayback];
478 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureForVideoPlaybackKey(), WebKit::WebPreferencesStore::Value((mediaTypesRequiringUserGesture & WKAudiovisualMediaTypeVideo) == WKAudiovisualMediaTypeVideo));
479 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureForAudioPlaybackKey(), WebKit::WebPreferencesStore::Value(((mediaTypesRequiringUserGesture & WKAudiovisualMediaTypeAudio) == WKAudiovisualMediaTypeAudio)));
480 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureToLoadVideoKey(), WebKit::WebPreferencesStore::Value(shouldRequireUserGestureToLoadVideo()));
481 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mainContentUserGestureOverrideEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _mainContentUserGestureOverrideEnabled]));
482 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::invisibleAutoplayNotPermittedKey(), WebKit::WebPreferencesStore::Value(!![_configuration _invisibleAutoplayNotPermitted]));
483 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mediaDataLoadsAutomaticallyKey(), WebKit::WebPreferencesStore::Value(!![_configuration _mediaDataLoadsAutomatically]));
485 // FIXME: <rdar://problem/25135244> Remove bundle checks for attachmentElementEnabled
487 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::attachmentElementEnabledKey(), WebKit::WebPreferencesStore::Value(WebCore::IOSApplication::isMobileMail() ? true : !![_configuration _attachmentElementEnabled]));
489 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::attachmentElementEnabledKey(), WebKit::WebPreferencesStore::Value(WebCore::MacApplication::isAppleMail() ? true : !![_configuration _attachmentElementEnabled]));
492 #if ENABLE(DATA_DETECTION) && PLATFORM(IOS)
493 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::dataDetectorTypesKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(fromWKDataDetectorTypes([_configuration dataDetectorTypes]))));
495 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
496 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsAirPlayForMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsAirPlayForMediaPlayback]));
499 #if ENABLE(APPLE_PAY)
500 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::applePayEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _applePayEnabled]));
503 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::needsStorageAccessFromFileURLsQuirkKey(), WebKit::WebPreferencesStore::Value(!![_configuration _needsStorageAccessFromFileURLsQuirk]));
506 CGRect bounds = self.bounds;
507 _scrollView = adoptNS([[WKScrollView alloc] initWithFrame:bounds]);
508 [_scrollView setInternalDelegate:self];
509 [_scrollView setBouncesZoom:YES];
511 [self addSubview:_scrollView.get()];
513 static uint32_t programSDKVersion = dyld_get_program_sdk_version();
514 _allowsLinkPreview = programSDKVersion >= firstSDKVersionWithLinkPreviewEnabledByDefault;
516 _contentView = adoptNS([[WKContentView alloc] initWithFrame:bounds processPool:processPool configuration:WTFMove(pageConfiguration) webView:self]);
518 _page = [_contentView page];
519 _page->setDeviceOrientation(deviceOrientation());
521 [_contentView layer].anchorPoint = CGPointZero;
522 [_contentView setFrame:bounds];
523 [_scrollView addSubview:_contentView.get()];
524 [_scrollView addSubview:[_contentView unscaledView]];
525 [self _updateScrollViewBackground];
527 _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
528 _initialScaleFactor = 1;
529 _fastClickingIsDisabled = [[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitFastClickingDisabled"];
531 [self _frameOrBoundsChanged];
533 NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
534 [center addObserver:self selector:@selector(_keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
535 [center addObserver:self selector:@selector(_keyboardDidChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
536 [center addObserver:self selector:@selector(_keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
537 [center addObserver:self selector:@selector(_keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
538 [center addObserver:self selector:@selector(_keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
539 [center addObserver:self selector:@selector(_windowDidRotate:) name:UIWindowDidRotateNotification object:nil];
540 [center addObserver:self selector:@selector(_contentSizeCategoryDidChange:) name:UIContentSizeCategoryDidChangeNotification object:nil];
541 _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
543 [center addObserver:self selector:@selector(_accessibilitySettingsDidChange:) name:UIAccessibilityGrayscaleStatusDidChangeNotification object:nil];
544 [center addObserver:self selector:@selector(_accessibilitySettingsDidChange:) name:UIAccessibilityInvertColorsStatusDidChangeNotification object:nil];
545 [center addObserver:self selector:@selector(_accessibilitySettingsDidChange:) name:UIAccessibilityReduceMotionStatusDidChangeNotification object:nil];
547 [[_configuration _contentProviderRegistry] addPage:*_page];
548 _page->setForceAlwaysUserScalable([_configuration ignoresViewportScaleLimits]);
552 _impl = std::make_unique<WebKit::WebViewImpl>(self, self, processPool, WTFMove(pageConfiguration));
553 _page = &_impl->page();
555 _impl->setAutomaticallyAdjustsContentInsets(true);
556 _impl->setRequiresUserActionForEditingControlsManager([configuration _requiresUserActionForEditingControlsManager]);
559 _page->setBackgroundExtendsBeyondPage(true);
561 if (NSString *applicationNameForUserAgent = configuration.applicationNameForUserAgent)
562 _page->setApplicationNameForUserAgent(applicationNameForUserAgent);
564 _navigationState = std::make_unique<WebKit::NavigationState>(self);
565 _page->setNavigationClient(_navigationState->createNavigationClient());
567 _uiDelegate = std::make_unique<WebKit::UIDelegate>(self);
568 _page->setFindClient(std::make_unique<WebKit::FindClient>(self));
569 _page->setDiagnosticLoggingClient(std::make_unique<WebKit::DiagnosticLoggingClient>(self));
571 _iconLoadingDelegate = std::make_unique<WebKit::IconLoadingDelegate>(self);
573 #if ENABLE(FULLSCREEN_API)
574 _page->setFullscreenClient(std::make_unique<WebKit::FullscreenClient>(self));
577 pageToViewMap().add(_page.get(), self);
580 - (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration
582 if (!(self = [super initWithFrame:frame]))
585 [self _initializeWithConfiguration:configuration];
590 - (instancetype)initWithCoder:(NSCoder *)coder
592 if (!(self = [super initWithCoder:coder]))
595 WKWebViewConfiguration *configuration = [coder decodeObjectForKey:@"configuration"];
596 [self _initializeWithConfiguration:configuration];
598 self.allowsBackForwardNavigationGestures = [coder decodeBoolForKey:@"allowsBackForwardNavigationGestures"];
599 self.customUserAgent = [coder decodeObjectForKey:@"customUserAgent"];
600 self.allowsLinkPreview = [coder decodeBoolForKey:@"allowsLinkPreview"];
603 self.allowsMagnification = [coder decodeBoolForKey:@"allowsMagnification"];
604 self.magnification = [coder decodeDoubleForKey:@"magnification"];
610 - (void)encodeWithCoder:(NSCoder *)coder
612 [coder encodeObject:_configuration.get() forKey:@"configuration"];
614 [coder encodeBool:self.allowsBackForwardNavigationGestures forKey:@"allowsBackForwardNavigationGestures"];
615 [coder encodeObject:self.customUserAgent forKey:@"customUserAgent"];
616 [coder encodeBool:self.allowsLinkPreview forKey:@"allowsLinkPreview"];
619 [coder encodeBool:self.allowsMagnification forKey:@"allowsMagnification"];
620 [coder encodeDouble:self.magnification forKey:@"magnification"];
627 [_textFinderClient willDestroyView:self];
631 [_contentView _webViewDestroyed];
633 if (_remoteObjectRegistry)
634 _page->process().processPool().removeMessageReceiver(Messages::RemoteObjectRegistry::messageReceiverName(), _page->pageID());
638 [_remoteObjectRegistry _invalidate];
639 [[_configuration _contentProviderRegistry] removePage:*_page];
640 #if PLATFORM(IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000
641 CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), nullptr, nullptr);
643 [[NSNotificationCenter defaultCenter] removeObserver:self];
644 [_scrollView setInternalDelegate:nil];
647 pageToViewMap().remove(_page.get());
652 - (WKWebViewConfiguration *)configuration
654 return [[_configuration copy] autorelease];
657 - (WKBackForwardList *)backForwardList
659 return wrapper(_page->backForwardList());
662 - (id <WKNavigationDelegate>)navigationDelegate
664 return _navigationState->navigationDelegate().autorelease();
667 - (void)setNavigationDelegate:(id <WKNavigationDelegate>)navigationDelegate
669 _page->setNavigationClient(_navigationState->createNavigationClient());
670 _navigationState->setNavigationDelegate(navigationDelegate);
673 - (id <WKUIDelegate>)UIDelegate
675 return _uiDelegate->delegate().autorelease();
678 - (void)setUIDelegate:(id<WKUIDelegate>)UIDelegate
680 #if ENABLE(CONTEXT_MENUS)
681 _page->setContextMenuClient(_uiDelegate->createContextMenuClient());
683 _page->setUIClient(_uiDelegate->createUIClient());
684 _uiDelegate->setDelegate(UIDelegate);
687 - (id <_WKIconLoadingDelegate>)_iconLoadingDelegate
689 return _iconLoadingDelegate->delegate().autorelease();
692 - (void)_setIconLoadingDelegate:(id<_WKIconLoadingDelegate>)iconLoadingDelegate
694 _page->setIconLoadingClient(_iconLoadingDelegate->createIconLoadingClient());
695 _iconLoadingDelegate->setDelegate(iconLoadingDelegate);
698 - (WKNavigation *)loadRequest:(NSURLRequest *)request
700 auto navigation = _page->loadRequest(request);
704 return [wrapper(*navigation.leakRef()) autorelease];
707 - (WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL
709 if (![URL isFileURL])
710 [NSException raise:NSInvalidArgumentException format:@"%@ is not a file URL", URL];
712 if (![readAccessURL isFileURL])
713 [NSException raise:NSInvalidArgumentException format:@"%@ is not a file URL", readAccessURL];
715 auto navigation = _page->loadFile([URL _web_originalDataAsWTFString], [readAccessURL _web_originalDataAsWTFString]);
719 return [wrapper(*navigation.leakRef()) autorelease];
722 - (WKNavigation *)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
724 NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
726 return [self loadData:data MIMEType:@"text/html" characterEncodingName:@"UTF-8" baseURL:baseURL];
729 - (WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL
731 auto navigation = _page->loadData(API::Data::createWithoutCopying(data).ptr(), MIMEType, characterEncodingName, baseURL.absoluteString);
735 return [wrapper(*navigation.leakRef()) autorelease];
738 - (WKNavigation *)goToBackForwardListItem:(WKBackForwardListItem *)item
740 auto navigation = _page->goToBackForwardItem(&item._item);
744 return [wrapper(*navigation.leakRef()) autorelease];
749 return _page->pageLoadState().title();
754 return [NSURL _web_URLWithWTFString:_page->pageLoadState().activeURL()];
759 return _page->pageLoadState().isLoading();
762 - (double)estimatedProgress
764 return _page->pageLoadState().estimatedProgress();
767 - (BOOL)hasOnlySecureContent
769 return _page->pageLoadState().hasOnlySecureContent();
772 - (SecTrustRef)serverTrust
774 #if HAVE(SEC_TRUST_SERIALIZATION)
775 auto certificateInfo = _page->pageLoadState().certificateInfo();
776 if (!certificateInfo)
779 return certificateInfo->certificateInfo().trust();
787 return _page->pageLoadState().canGoBack();
792 return _page->pageLoadState().canGoForward();
795 - (WKNavigation *)goBack
797 auto navigation = _page->goBack();
801 return [wrapper(*navigation.leakRef()) autorelease];
804 - (WKNavigation *)goForward
806 auto navigation = _page->goForward();
810 return [wrapper(*navigation.leakRef()) autorelease];
813 - (WKNavigation *)reload
815 const bool reloadFromOrigin = false;
816 const bool contentBlockersEnabled = true;
817 auto navigation = _page->reload(reloadFromOrigin, contentBlockersEnabled);
821 return [wrapper(*navigation.leakRef()) autorelease];
824 - (WKNavigation *)reloadFromOrigin
826 const bool reloadFromOrigin = true;
827 const bool contentBlockersEnabled = true;
828 auto navigation = _page->reload(reloadFromOrigin, contentBlockersEnabled);
832 return [wrapper(*navigation.leakRef()) autorelease];
837 _page->stopLoading();
840 static WKErrorCode callbackErrorCode(WebKit::CallbackBase::Error error)
843 case WebKit::CallbackBase::Error::None:
844 ASSERT_NOT_REACHED();
845 return WKErrorUnknown;
847 case WebKit::CallbackBase::Error::Unknown:
848 return WKErrorUnknown;
850 case WebKit::CallbackBase::Error::ProcessExited:
851 return WKErrorWebContentProcessTerminated;
853 case WebKit::CallbackBase::Error::OwnerWasInvalidated:
854 return WKErrorWebViewInvalidated;
858 - (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *))completionHandler
860 auto handler = adoptNS([completionHandler copy]);
862 _page->runJavaScriptInMainFrame(javaScriptString, [handler](API::SerializedScriptValue* serializedScriptValue, bool hadException, const WebCore::ExceptionDetails& details, WebKit::ScriptValueCallback::Error errorCode) {
866 if (errorCode != WebKit::ScriptValueCallback::Error::None) {
867 auto error = createNSError(callbackErrorCode(errorCode));
868 if (errorCode == WebKit::ScriptValueCallback::Error::OwnerWasInvalidated) {
869 // The OwnerWasInvalidated callback is synchronous. We don't want to call the block from within it
870 // because that can trigger re-entrancy bugs in WebKit.
871 // FIXME: It would be even better if GenericCallback did this for us.
872 dispatch_async(dispatch_get_main_queue(), [handler, error] {
873 auto rawHandler = (void (^)(id, NSError *))handler.get();
874 rawHandler(nil, error.get());
879 auto rawHandler = (void (^)(id, NSError *))handler.get();
880 rawHandler(nil, error.get());
884 auto rawHandler = (void (^)(id, NSError *))handler.get();
886 ASSERT(!serializedScriptValue);
888 RetainPtr<NSMutableDictionary> userInfo = adoptNS([[NSMutableDictionary alloc] init]);
890 [userInfo setObject:localizedDescriptionForErrorCode(WKErrorJavaScriptExceptionOccurred) forKey:NSLocalizedDescriptionKey];
891 [userInfo setObject:static_cast<NSString *>(details.message) forKey:_WKJavaScriptExceptionMessageErrorKey];
892 [userInfo setObject:@(details.lineNumber) forKey:_WKJavaScriptExceptionLineNumberErrorKey];
893 [userInfo setObject:@(details.columnNumber) forKey:_WKJavaScriptExceptionColumnNumberErrorKey];
895 if (!details.sourceURL.isEmpty())
896 [userInfo setObject:[NSURL _web_URLWithWTFString:details.sourceURL] forKey:_WKJavaScriptExceptionSourceURLErrorKey];
898 rawHandler(nil, adoptNS([[NSError alloc] initWithDomain:WKErrorDomain code:WKErrorJavaScriptExceptionOccurred userInfo:userInfo.get()]).get());
902 if (!serializedScriptValue) {
903 rawHandler(nil, createNSError(WKErrorJavaScriptResultTypeIsUnsupported).get());
907 id body = API::SerializedScriptValue::deserialize(*serializedScriptValue->internalRepresentation(), 0);
908 rawHandler(body, nil);
912 - (NSString *)customUserAgent
914 return _page->customUserAgent();
917 - (void)setCustomUserAgent:(NSString *)customUserAgent
919 _page->setCustomUserAgent(customUserAgent);
922 - (WKPageRef)_pageForTesting
924 return toAPI(_page.get());
927 - (BOOL)allowsLinkPreview
930 return _impl->allowsLinkPreview();
932 return _allowsLinkPreview;
936 - (void)setAllowsLinkPreview:(BOOL)allowsLinkPreview
939 _impl->setAllowsLinkPreview(allowsLinkPreview);
942 if (_allowsLinkPreview == allowsLinkPreview)
945 _allowsLinkPreview = allowsLinkPreview;
947 #if HAVE(LINK_PREVIEW)
948 if (_allowsLinkPreview)
949 [_contentView _registerPreview];
951 [_contentView _unregisterPreview];
952 #endif // HAVE(LINK_PREVIEW)
953 #endif // PLATFORM(IOS)
956 #pragma mark iOS-specific methods
960 - (BOOL)_isBackground
962 if ([self _isDisplayingPDF])
963 return [(WKPDFView *)_customContentView isBackground];
965 return [_contentView isBackground];
968 - (void)setFrame:(CGRect)frame
970 CGRect oldFrame = self.frame;
971 [super setFrame:frame];
973 if (!CGSizeEqualToSize(oldFrame.size, frame.size))
974 [self _frameOrBoundsChanged];
977 - (void)setBounds:(CGRect)bounds
979 CGRect oldBounds = self.bounds;
980 [super setBounds:bounds];
981 [_customContentFixedOverlayView setFrame:self.bounds];
983 if (!CGSizeEqualToSize(oldBounds.size, bounds.size))
984 [self _frameOrBoundsChanged];
987 - (void)layoutSubviews
989 [super layoutSubviews];
990 [self _frameOrBoundsChanged];
993 - (UIScrollView *)scrollView
995 return _scrollView.get();
998 - (WKBrowsingContextController *)browsingContextController
1000 return [_contentView browsingContextController];
1003 - (BOOL)becomeFirstResponder
1005 return [self._currentContentView becomeFirstResponder] || [super becomeFirstResponder];
1008 - (BOOL)canBecomeFirstResponder
1010 if (self._currentContentView == _contentView && [_contentView isResigningFirstResponder])
1015 static inline CGFloat floorToDevicePixel(CGFloat input, float deviceScaleFactor)
1017 return CGFloor(input * deviceScaleFactor) / deviceScaleFactor;
1020 static inline bool pointsEqualInDevicePixels(CGPoint a, CGPoint b, float deviceScaleFactor)
1022 return fabs(a.x * deviceScaleFactor - b.x * deviceScaleFactor) < std::numeric_limits<float>::epsilon()
1023 && fabs(a.y * deviceScaleFactor - b.y * deviceScaleFactor) < std::numeric_limits<float>::epsilon();
1026 static CGSize roundScrollViewContentSize(const WebKit::WebPageProxy& page, CGSize contentSize)
1028 float deviceScaleFactor = page.deviceScaleFactor();
1029 return CGSizeMake(floorToDevicePixel(contentSize.width, deviceScaleFactor), floorToDevicePixel(contentSize.height, deviceScaleFactor));
1032 - (UIView *)_currentContentView
1034 return _customContentView ? _customContentView.get() : _contentView.get();
1037 - (WKWebViewContentProviderRegistry *)_contentProviderRegistry
1039 return [_configuration _contentProviderRegistry];
1042 - (WKSelectionGranularity)_selectionGranularity
1044 return [_configuration selectionGranularity];
1047 - (void)_setHasCustomContentView:(BOOL)pageHasCustomContentView loadedMIMEType:(const WTF::String&)mimeType
1049 if (pageHasCustomContentView) {
1050 [_customContentView removeFromSuperview];
1051 [_customContentFixedOverlayView removeFromSuperview];
1053 Class representationClass = [[_configuration _contentProviderRegistry] providerForMIMEType:mimeType];
1054 ASSERT(representationClass);
1055 _customContentView = adoptNS([[representationClass alloc] web_initWithFrame:self.bounds webView:self]);
1056 _customContentFixedOverlayView = adoptNS([[UIView alloc] initWithFrame:self.bounds]);
1057 [_customContentFixedOverlayView setUserInteractionEnabled:NO];
1059 [[_contentView unscaledView] removeFromSuperview];
1060 [_contentView removeFromSuperview];
1061 [_scrollView addSubview:_customContentView.get()];
1062 [self addSubview:_customContentFixedOverlayView.get()];
1064 [_customContentView web_setMinimumSize:self.bounds.size];
1065 [_customContentView web_setFixedOverlayView:_customContentFixedOverlayView.get()];
1066 } else if (_customContentView) {
1067 [_customContentView removeFromSuperview];
1068 _customContentView = nullptr;
1070 [_customContentFixedOverlayView removeFromSuperview];
1071 _customContentFixedOverlayView = nullptr;
1073 [_scrollView addSubview:_contentView.get()];
1074 [_scrollView addSubview:[_contentView unscaledView]];
1075 [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
1077 [_customContentFixedOverlayView setFrame:self.bounds];
1078 [self addSubview:_customContentFixedOverlayView.get()];
1081 if (self.isFirstResponder && self._currentContentView.canBecomeFirstResponder)
1082 [self._currentContentView becomeFirstResponder];
1085 - (void)_didFinishLoadingDataForCustomContentProviderWithSuggestedFilename:(const String&)suggestedFilename data:(NSData *)data
1087 ASSERT(_customContentView);
1088 [_customContentView web_setContentProviderData:data suggestedFilename:suggestedFilename];
1090 // FIXME: It may make more sense for custom content providers to invoke this when they're ready,
1091 // because there's no guarantee that all custom content providers will lay out synchronously.
1092 _page->didLayoutForCustomContentProvider();
1095 - (void)_willInvokeUIScrollViewDelegateCallback
1097 _delayUpdateVisibleContentRects = YES;
1100 - (void)_didInvokeUIScrollViewDelegateCallback
1102 _delayUpdateVisibleContentRects = NO;
1103 if (_hadDelayedUpdateVisibleContentRects) {
1104 _hadDelayedUpdateVisibleContentRects = NO;
1105 [self _updateVisibleContentRectAfterScrollInView:_scrollView.get()];
1109 static CGFloat contentZoomScale(WKWebView *webView)
1111 CGFloat scale = webView._currentContentView.layer.affineTransform.a;
1112 ASSERT(scale == [webView->_scrollView zoomScale]);
1116 static WebCore::Color baseScrollViewBackgroundColor(WKWebView *webView)
1118 if (webView->_customContentView)
1119 return [webView->_customContentView backgroundColor].CGColor;
1121 if (webView->_gestureController) {
1122 WebCore::Color color = webView->_gestureController->backgroundColorForCurrentSnapshot();
1123 if (color.isValid())
1127 return webView->_page->pageExtendedBackgroundColor();
1130 static WebCore::Color scrollViewBackgroundColor(WKWebView *webView)
1132 if (!webView.opaque)
1133 return WebCore::Color::transparent;
1135 WebCore::Color color = baseScrollViewBackgroundColor(webView);
1137 if (!color.isValid())
1138 color = WebCore::Color::white;
1140 CGFloat zoomScale = contentZoomScale(webView);
1141 CGFloat minimumZoomScale = [webView->_scrollView minimumZoomScale];
1142 if (zoomScale < minimumZoomScale) {
1144 CGFloat opacity = std::max<CGFloat>(1 - slope * (minimumZoomScale - zoomScale), 0);
1145 color = WebCore::colorWithOverrideAlpha(color.rgb(), opacity);
1151 - (void)_updateScrollViewBackground
1153 WebCore::Color color = scrollViewBackgroundColor(self);
1155 if (_scrollViewBackgroundColor == color)
1158 _scrollViewBackgroundColor = color;
1160 auto uiBackgroundColor = adoptNS([[UIColor alloc] initWithCGColor:cachedCGColor(color)]);
1161 [_scrollView setBackgroundColor:uiBackgroundColor.get()];
1163 // Update the indicator style based on the lightness/darkness of the background color.
1164 double hue, saturation, lightness;
1165 color.getHSL(hue, saturation, lightness);
1166 if (lightness <= .5 && color.isVisible())
1167 [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleWhite];
1169 [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleDefault];
1172 - (CGPoint)_adjustedContentOffset:(CGPoint)point
1174 CGPoint result = point;
1175 UIEdgeInsets contentInset = [self _computedContentInset];
1177 result.x -= contentInset.left;
1178 result.y -= contentInset.top;
1183 - (UIEdgeInsets)_computedContentInset
1185 if (_haveSetObscuredInsets)
1186 return _obscuredInsets;
1188 return [_scrollView contentInset];
1191 - (void)_processDidExit
1193 if (!_customContentView && _dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
1194 NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
1195 [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
1196 [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
1197 [_resizeAnimationView removeFromSuperview];
1198 _resizeAnimationView = nil;
1200 _resizeAnimationTransformAdjustments = CATransform3DIdentity;
1202 [_contentView setFrame:self.bounds];
1203 [_scrollView setBackgroundColor:[UIColor whiteColor]];
1204 [_scrollView setContentOffset:[self _adjustedContentOffset:CGPointZero]];
1205 [_scrollView setZoomScale:1];
1207 _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
1208 _initialScaleFactor = 1;
1209 _hasCommittedLoadForMainFrame = NO;
1210 _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1211 _dynamicViewportUpdateMode = DynamicViewportUpdateMode::NotResizing;
1212 [_contentView setHidden:NO];
1213 _needsToRestoreScrollPosition = NO;
1214 _needsToRestoreUnobscuredCenter = NO;
1215 _scrollViewBackgroundColor = WebCore::Color();
1216 _delayUpdateVisibleContentRects = NO;
1217 _hadDelayedUpdateVisibleContentRects = NO;
1220 - (void)_didCommitLoadForMainFrame
1222 _firstPaintAfterCommitLoadTransactionID = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1224 _hasCommittedLoadForMainFrame = YES;
1225 _needsResetViewStateAfterCommitLoadForMainFrame = YES;
1227 [_scrollView _stopScrollingAndZoomingAnimations];
1230 static CGPoint contentOffsetBoundedInValidRange(UIScrollView *scrollView, CGPoint contentOffset)
1232 UIEdgeInsets contentInsets = scrollView.contentInset;
1233 CGSize contentSize = scrollView.contentSize;
1234 CGSize scrollViewSize = scrollView.bounds.size;
1236 CGFloat maxHorizontalOffset = contentSize.width + contentInsets.right - scrollViewSize.width;
1237 contentOffset.x = std::min(maxHorizontalOffset, contentOffset.x);
1238 contentOffset.x = std::max(-contentInsets.left, contentOffset.x);
1240 CGFloat maxVerticalOffset = contentSize.height + contentInsets.bottom - scrollViewSize.height;
1241 contentOffset.y = std::min(maxVerticalOffset, contentOffset.y);
1242 contentOffset.y = std::max(-contentInsets.top, contentOffset.y);
1243 return contentOffset;
1246 static void changeContentOffsetBoundedInValidRange(UIScrollView *scrollView, WebCore::FloatPoint contentOffset)
1248 scrollView.contentOffset = contentOffsetBoundedInValidRange(scrollView, contentOffset);
1251 - (WebCore::FloatRect)visibleRectInViewCoordinates
1253 WebCore::FloatRect bounds = self.bounds;
1254 bounds.moveBy([_scrollView contentOffset]);
1255 WebCore::FloatRect contentViewBounds = [_contentView bounds];
1256 bounds.intersect(contentViewBounds);
1260 // WebCore stores the page scale factor as float instead of double. When we get a scale from WebCore,
1261 // we need to ignore differences that are within a small rounding error on floats.
1262 static inline bool areEssentiallyEqualAsFloat(float a, float b)
1264 return WTF::areEssentiallyEqual(a, b);
1267 - (void)_didCommitLayerTree:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
1269 if (_customContentView)
1272 if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
1273 if (_resizeAnimationTransformTransactionID && layerTreeTransaction.transactionID() >= _resizeAnimationTransformTransactionID.value()) {
1274 _resizeAnimationTransformTransactionID = Nullopt;
1275 [_resizeAnimationView layer].sublayerTransform = _resizeAnimationTransformAdjustments;
1276 if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::ResizingWithDocumentHidden) {
1277 [_contentView setHidden:NO];
1278 [self _endAnimatedResize];
1284 CGSize newContentSize = roundScrollViewContentSize(*_page, [_contentView frame].size);
1285 [_scrollView _setContentSizePreservingContentOffsetDuringRubberband:newContentSize];
1287 [_scrollView setMinimumZoomScale:layerTreeTransaction.minimumScaleFactor()];
1288 [_scrollView setMaximumZoomScale:layerTreeTransaction.maximumScaleFactor()];
1289 [_scrollView setZoomEnabled:layerTreeTransaction.allowsUserScaling()];
1290 if (!layerTreeTransaction.scaleWasSetByUIProcess() && ![_scrollView isZooming] && ![_scrollView isZoomBouncing] && ![_scrollView _isAnimatingZoom])
1291 [_scrollView setZoomScale:layerTreeTransaction.pageScaleFactor()];
1293 _viewportMetaTagWidth = layerTreeTransaction.viewportMetaTagWidth();
1294 _viewportMetaTagWidthWasExplicit = layerTreeTransaction.viewportMetaTagWidthWasExplicit();
1295 _viewportMetaTagCameFromImageDocument = layerTreeTransaction.viewportMetaTagCameFromImageDocument();
1296 _initialScaleFactor = layerTreeTransaction.initialScaleFactor();
1298 BOOL needUpdateVisbleContentRects = _page->updateLayoutViewportParameters(layerTreeTransaction);
1300 if (![_contentView _mayDisableDoubleTapGesturesDuringSingleTap])
1301 [_contentView _setDoubleTapGesturesEnabled:self._allowsDoubleTapGestures];
1303 [self _updateScrollViewBackground];
1305 if (_gestureController)
1306 _gestureController->setRenderTreeSize(layerTreeTransaction.renderTreeSize());
1308 if (_needsResetViewStateAfterCommitLoadForMainFrame && layerTreeTransaction.transactionID() >= _firstPaintAfterCommitLoadTransactionID) {
1309 _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1310 [_scrollView setContentOffset:[self _adjustedContentOffset:CGPointZero]];
1311 if (_observedRenderingProgressEvents & _WKRenderingProgressEventFirstPaint)
1312 _navigationState->didFirstPaint();
1314 needUpdateVisbleContentRects = YES;
1317 bool isTransactionAfterPageRestore = layerTreeTransaction.transactionID() >= _firstTransactionIDAfterPageRestore;
1319 if (_needsToRestoreScrollPosition && isTransactionAfterPageRestore) {
1320 _needsToRestoreScrollPosition = NO;
1322 if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1323 WebCore::FloatPoint scaledScrollOffset = _scrollOffsetToRestore;
1324 scaledScrollOffset.scale(_scaleToRestore);
1325 WebCore::FloatPoint contentOffsetInScrollViewCoordinates = scaledScrollOffset - _obscuredInsetWhenSaved;
1327 changeContentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
1328 _commitDidRestoreScrollPosition = YES;
1330 if (_gestureController)
1331 _gestureController->didRestoreScrollPosition();
1334 needUpdateVisbleContentRects = YES;
1337 if (_needsToRestoreUnobscuredCenter && isTransactionAfterPageRestore) {
1338 _needsToRestoreUnobscuredCenter = NO;
1340 if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1341 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, _obscuredInsets);
1342 WebCore::FloatSize unobscuredContentSizeAtNewScale(unobscuredRect.size.width / _scaleToRestore, unobscuredRect.size.height / _scaleToRestore);
1343 WebCore::FloatPoint topLeftInDocumentCoordinates(_unobscuredCenterToRestore.x() - unobscuredContentSizeAtNewScale.width() / 2, _unobscuredCenterToRestore.y() - unobscuredContentSizeAtNewScale.height() / 2);
1345 topLeftInDocumentCoordinates.scale(_scaleToRestore);
1346 topLeftInDocumentCoordinates.moveBy(WebCore::FloatPoint(-_obscuredInsets.left, -_obscuredInsets.top));
1348 changeContentOffsetBoundedInValidRange(_scrollView.get(), topLeftInDocumentCoordinates);
1349 if (_gestureController)
1350 _gestureController->didRestoreScrollPosition();
1353 needUpdateVisbleContentRects = YES;
1356 if (needUpdateVisbleContentRects)
1357 [self _updateVisibleContentRects];
1359 if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
1360 scrollPerfData->didCommitLayerTree([self visibleRectInViewCoordinates]);
1363 - (void)_layerTreeCommitComplete
1365 _commitDidRestoreScrollPosition = NO;
1368 - (void)_dynamicViewportUpdateChangedTargetToScale:(double)newScale position:(CGPoint)newScrollPosition nextValidLayerTreeTransactionID:(uint64_t)nextValidLayerTreeTransactionID
1370 if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
1371 CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
1372 double currentTargetScale = animatingScaleTarget * [[_contentView layer] transform].m11;
1373 double scale = newScale / currentTargetScale;
1374 _resizeAnimationTransformAdjustments = CATransform3DMakeScale(scale, scale, 1);
1376 CGPoint newContentOffset = [self _adjustedContentOffset:CGPointMake(newScrollPosition.x * newScale, newScrollPosition.y * newScale)];
1377 CGPoint currentContentOffset = [_scrollView contentOffset];
1379 _resizeAnimationTransformAdjustments.m41 = (currentContentOffset.x - newContentOffset.x) / animatingScaleTarget;
1380 _resizeAnimationTransformAdjustments.m42 = (currentContentOffset.y - newContentOffset.y) / animatingScaleTarget;
1381 _resizeAnimationTransformTransactionID = nextValidLayerTreeTransactionID;
1385 - (void)_couldNotRestorePageState
1387 // The gestureController may be waiting for the scroll position to be restored
1388 // in order to remove the swipe snapshot. Since the scroll position could not be
1389 // restored, tell the gestureController it was restored so that it no longer waits
1391 if (_gestureController)
1392 _gestureController->didRestoreScrollPosition();
1395 - (void)_restorePageScrollPosition:(WebCore::FloatPoint)scrollPosition scrollOrigin:(WebCore::FloatPoint)scrollOrigin previousObscuredInset:(WebCore::FloatSize)obscuredInset scale:(double)scale
1397 if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1400 if (_customContentView)
1403 _needsToRestoreUnobscuredCenter = NO;
1404 _needsToRestoreScrollPosition = YES;
1405 _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1407 _scrollOffsetToRestore = WebCore::ScrollableArea::scrollOffsetFromPosition(WebCore::FloatPoint(scrollPosition), WebCore::toFloatSize(scrollOrigin));
1408 _obscuredInsetWhenSaved = obscuredInset;
1409 _scaleToRestore = scale;
1412 - (void)_restorePageStateToUnobscuredCenter:(WebCore::FloatPoint)center scale:(double)scale
1414 if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1417 if (_customContentView)
1420 _needsToRestoreScrollPosition = NO;
1421 _needsToRestoreUnobscuredCenter = YES;
1422 _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1423 _unobscuredCenterToRestore = center;
1424 _scaleToRestore = scale;
1427 - (PassRefPtr<WebKit::ViewSnapshot>)_takeViewSnapshot
1429 float deviceScale = WebCore::screenScaleFactor();
1430 WebCore::FloatSize snapshotSize(self.bounds.size);
1431 snapshotSize.scale(deviceScale);
1433 CATransform3D transform = CATransform3DMakeScale(deviceScale, deviceScale, 1);
1436 WebCore::IOSurface::Format snapshotFormat = WebCore::screenSupportsExtendedColor() ? WebCore::IOSurface::Format::RGB10 : WebCore::IOSurface::Format::RGBA;
1437 auto surface = WebCore::IOSurface::create(WebCore::expandedIntSize(snapshotSize), WebCore::sRGBColorSpaceRef(), snapshotFormat);
1440 CARenderServerRenderLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, reinterpret_cast<uint64_t>(self.layer), surface->surface(), 0, 0, &transform);
1442 WebCore::IOSurface::Format compressedFormat = WebCore::IOSurface::Format::YUV422;
1443 if (WebCore::IOSurface::allowConversionFromFormatToFormat(snapshotFormat, compressedFormat)) {
1444 RefPtr<WebKit::ViewSnapshot> viewSnapshot = WebKit::ViewSnapshot::create(nullptr);
1445 WebCore::IOSurface::convertToFormat(WTFMove(surface), WebCore::IOSurface::Format::YUV422, [viewSnapshot](std::unique_ptr<WebCore::IOSurface> convertedSurface) {
1446 if (convertedSurface)
1447 viewSnapshot->setSurface(WTFMove(convertedSurface));
1450 return viewSnapshot;
1453 return WebKit::ViewSnapshot::create(WTFMove(surface));
1455 uint32_t slotID = [WebKit::ViewSnapshotStore::snapshottingContext() createImageSlot:snapshotSize hasAlpha:YES];
1460 CARenderServerCaptureLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, (uint64_t)self.layer, slotID, 0, 0, &transform);
1461 WebCore::IntSize imageSize = WebCore::expandedIntSize(WebCore::FloatSize(snapshotSize));
1462 return WebKit::ViewSnapshot::create(slotID, imageSize, (imageSize.area() * 4).unsafeGet());
1466 - (void)_zoomToPoint:(WebCore::FloatPoint)point atScale:(double)scale animated:(BOOL)animated
1468 CFTimeInterval duration = 0;
1469 CGFloat zoomScale = contentZoomScale(self);
1472 const double maximumZoomDuration = 0.4;
1473 const double minimumZoomDuration = 0.1;
1474 const double zoomDurationFactor = 0.3;
1476 duration = std::min(fabs(log(zoomScale) - log(scale)) * zoomDurationFactor + minimumZoomDuration, maximumZoomDuration);
1479 if (scale != zoomScale)
1480 _page->willStartUserTriggeredZooming();
1482 LOG_WITH_STREAM(VisibleRects, stream << "_zoomToPoint:" << point << " scale: " << scale << " duration:" << duration);
1484 [_scrollView _zoomToCenter:point scale:scale duration:duration];
1487 - (void)_zoomToRect:(WebCore::FloatRect)targetRect atScale:(double)scale origin:(WebCore::FloatPoint)origin animated:(BOOL)animated
1489 // FIXME: Some of this could be shared with _scrollToRect.
1490 const double visibleRectScaleChange = contentZoomScale(self) / scale;
1491 const WebCore::FloatRect visibleRect([self convertRect:self.bounds toView:self._currentContentView]);
1492 const WebCore::FloatRect unobscuredRect([self _contentRectForUserInteraction]);
1494 const WebCore::FloatSize topLeftObscuredInsetAfterZoom((unobscuredRect.minXMinYCorner() - visibleRect.minXMinYCorner()) * visibleRectScaleChange);
1495 const WebCore::FloatSize bottomRightObscuredInsetAfterZoom((visibleRect.maxXMaxYCorner() - unobscuredRect.maxXMaxYCorner()) * visibleRectScaleChange);
1497 const WebCore::FloatSize unobscuredRectSizeAfterZoom(unobscuredRect.size() * visibleRectScaleChange);
1499 // Center to the target rect.
1500 WebCore::FloatPoint unobscuredRectLocationAfterZoom = targetRect.location() - (unobscuredRectSizeAfterZoom - targetRect.size()) * 0.5;
1502 // Center to the tap point instead in case the target rect won't fit in a direction.
1503 if (targetRect.width() > unobscuredRectSizeAfterZoom.width())
1504 unobscuredRectLocationAfterZoom.setX(origin.x() - unobscuredRectSizeAfterZoom.width() / 2);
1505 if (targetRect.height() > unobscuredRectSizeAfterZoom.height())
1506 unobscuredRectLocationAfterZoom.setY(origin.y() - unobscuredRectSizeAfterZoom.height() / 2);
1508 // We have computed where we want the unobscured rect to be. Now adjust for the obscuring insets.
1509 WebCore::FloatRect visibleRectAfterZoom(unobscuredRectLocationAfterZoom, unobscuredRectSizeAfterZoom);
1510 visibleRectAfterZoom.move(-topLeftObscuredInsetAfterZoom);
1511 visibleRectAfterZoom.expand(topLeftObscuredInsetAfterZoom + bottomRightObscuredInsetAfterZoom);
1513 [self _zoomToPoint:visibleRectAfterZoom.center() atScale:scale animated:animated];
1516 static WebCore::FloatPoint constrainContentOffset(WebCore::FloatPoint contentOffset, WebCore::FloatSize contentSize, WebCore::FloatSize unobscuredContentSize)
1518 WebCore::FloatSize maximumContentOffset = contentSize - unobscuredContentSize;
1519 return contentOffset.constrainedBetween(WebCore::FloatPoint(), WebCore::FloatPoint(maximumContentOffset));
1522 - (void)_scrollToContentScrollPosition:(WebCore::FloatPoint)scrollPosition scrollOrigin:(WebCore::IntPoint)scrollOrigin
1524 if (_commitDidRestoreScrollPosition || _dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1527 WebCore::FloatPoint contentOffset = WebCore::ScrollableArea::scrollOffsetFromPosition(scrollPosition, toFloatSize(scrollOrigin));
1529 WebCore::FloatPoint scaledOffset = contentOffset;
1530 CGFloat zoomScale = contentZoomScale(self);
1531 scaledOffset.scale(zoomScale);
1533 CGPoint contentOffsetInScrollViewCoordinates = [self _adjustedContentOffset:scaledOffset];
1534 contentOffsetInScrollViewCoordinates = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
1536 [_scrollView _stopScrollingAndZoomingAnimations];
1538 if (!CGPointEqualToPoint(contentOffsetInScrollViewCoordinates, [_scrollView contentOffset]))
1539 [_scrollView setContentOffset:contentOffsetInScrollViewCoordinates];
1541 // If we haven't changed anything, there would not be any VisibleContentRect update sent to the content.
1542 // The WebProcess would keep the invalid contentOffset as its scroll position.
1543 // To synchronize the WebProcess with what is on screen, we send the VisibleContentRect again.
1544 _page->resendLastVisibleContentRects();
1548 - (BOOL)_scrollToRect:(WebCore::FloatRect)targetRect origin:(WebCore::FloatPoint)origin minimumScrollDistance:(float)minimumScrollDistance
1550 WebCore::FloatRect unobscuredContentRect([self _contentRectForUserInteraction]);
1551 WebCore::FloatPoint unobscuredContentOffset = unobscuredContentRect.location();
1552 WebCore::FloatSize contentSize([self._currentContentView bounds].size);
1554 // Center the target rect in the scroll view.
1555 // If the target doesn't fit in the scroll view, center on the gesture location instead.
1556 WebCore::FloatPoint newUnobscuredContentOffset;
1557 if (targetRect.width() <= unobscuredContentRect.width())
1558 newUnobscuredContentOffset.setX(targetRect.x() - (unobscuredContentRect.width() - targetRect.width()) / 2);
1560 newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
1561 if (targetRect.height() <= unobscuredContentRect.height())
1562 newUnobscuredContentOffset.setY(targetRect.y() - (unobscuredContentRect.height() - targetRect.height()) / 2);
1564 newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
1565 newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
1567 if (unobscuredContentOffset == newUnobscuredContentOffset) {
1568 if (targetRect.width() > unobscuredContentRect.width())
1569 newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
1570 if (targetRect.height() > unobscuredContentRect.height())
1571 newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
1572 newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
1575 WebCore::FloatSize scrollViewOffsetDelta = newUnobscuredContentOffset - unobscuredContentOffset;
1576 scrollViewOffsetDelta.scale(contentZoomScale(self));
1578 float scrollDistance = scrollViewOffsetDelta.diagonalLength();
1579 if (scrollDistance < minimumScrollDistance)
1582 [_contentView willStartZoomOrScroll];
1584 LOG_WITH_STREAM(VisibleRects, stream << "_scrollToRect: scrolling to " << [_scrollView contentOffset] + scrollViewOffsetDelta);
1586 [_scrollView setContentOffset:([_scrollView contentOffset] + scrollViewOffsetDelta) animated:YES];
1590 - (void)_scrollByContentOffset:(WebCore::FloatPoint)contentOffsetDelta
1592 WebCore::FloatPoint scaledOffsetDelta = contentOffsetDelta;
1593 CGFloat zoomScale = contentZoomScale(self);
1594 scaledOffsetDelta.scale(zoomScale);
1596 CGPoint currentOffset = [_scrollView _isAnimatingScroll] ? [_scrollView _animatedTargetOffset] : [_scrollView contentOffset];
1597 CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), currentOffset + scaledOffsetDelta);
1599 if (CGPointEqualToPoint(boundedOffset, currentOffset))
1601 [_contentView willStartZoomOrScroll];
1603 LOG_WITH_STREAM(VisibleRects, stream << "_scrollByContentOffset: scrolling to " << boundedOffset);
1605 [_scrollView setContentOffset:boundedOffset animated:YES];
1608 - (void)_zoomOutWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
1610 [self _zoomToPoint:origin atScale:[_scrollView minimumZoomScale] animated:animated];
1613 - (void)_zoomToInitialScaleWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
1615 ASSERT(_initialScaleFactor > 0);
1616 [self _zoomToPoint:origin atScale:_initialScaleFactor animated:animated];
1619 // focusedElementRect and selectionRect are both in document coordinates.
1620 - (void)_zoomToFocusRect:(WebCore::FloatRect)focusedElementRectInDocumentCoordinates selectionRect:(WebCore::FloatRect)selectionRectInDocumentCoordinates fontSize:(float)fontSize minimumScale:(double)minimumScale maximumScale:(double)maximumScale allowScaling:(BOOL)allowScaling forceScroll:(BOOL)forceScroll
1622 const double WKWebViewStandardFontSize = 16;
1623 const double kMinimumHeightToShowContentAboveKeyboard = 106;
1624 const CFTimeInterval UIWebFormAnimationDuration = 0.25;
1625 const double CaretOffsetFromWindowEdge = 20;
1627 // Zoom around the element's bounding frame. We use a "standard" size to determine the proper frame.
1628 double scale = allowScaling ? std::min(std::max(WKWebViewStandardFontSize / fontSize, minimumScale), maximumScale) : contentZoomScale(self);
1629 CGFloat documentWidth = [_contentView bounds].size.width;
1630 scale = CGRound(documentWidth * scale) / documentWidth;
1632 UIWindow *window = [_scrollView window];
1634 WebCore::FloatRect focusedElementRectInNewScale = focusedElementRectInDocumentCoordinates;
1635 focusedElementRectInNewScale.scale(scale);
1636 focusedElementRectInNewScale.moveBy([_contentView frame].origin);
1638 // Find the portion of the view that is visible on the screen.
1639 UIViewController *topViewController = [[[_scrollView _viewControllerForAncestor] _rootAncestorViewController] _viewControllerForSupportedInterfaceOrientations];
1640 UIView *fullScreenView = topViewController.view;
1641 if (!fullScreenView)
1642 fullScreenView = window;
1644 CGRect unobscuredScrollViewRectInWebViewCoordinates = UIEdgeInsetsInsetRect([self bounds], _obscuredInsets);
1645 CGRect visibleScrollViewBoundsInWebViewCoordinates = CGRectIntersection(unobscuredScrollViewRectInWebViewCoordinates, [fullScreenView convertRect:[fullScreenView bounds] toView:self]);
1646 CGRect formAssistantFrameInWebViewCoordinates = [window convertRect:_inputViewBounds toView:self];
1647 CGRect intersectionBetweenScrollViewAndFormAssistant = CGRectIntersection(visibleScrollViewBoundsInWebViewCoordinates, formAssistantFrameInWebViewCoordinates);
1648 CGSize visibleSize = visibleScrollViewBoundsInWebViewCoordinates.size;
1650 CGFloat visibleOffsetFromTop = 0;
1651 if (!CGRectIsEmpty(intersectionBetweenScrollViewAndFormAssistant)) {
1652 CGFloat heightVisibleAboveFormAssistant = CGRectGetMinY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
1653 CGFloat heightVisibleBelowFormAssistant = CGRectGetMaxY(visibleScrollViewBoundsInWebViewCoordinates) - CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant);
1655 if (heightVisibleAboveFormAssistant >= kMinimumHeightToShowContentAboveKeyboard || heightVisibleBelowFormAssistant < heightVisibleAboveFormAssistant)
1656 visibleSize.height = heightVisibleAboveFormAssistant;
1658 visibleSize.height = heightVisibleBelowFormAssistant;
1659 visibleOffsetFromTop = CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
1663 BOOL selectionRectIsNotNull = !selectionRectInDocumentCoordinates.isZero();
1665 CGRect currentlyVisibleRegionInWebViewCoordinates;
1666 currentlyVisibleRegionInWebViewCoordinates.origin = unobscuredScrollViewRectInWebViewCoordinates.origin;
1667 currentlyVisibleRegionInWebViewCoordinates.origin.y += visibleOffsetFromTop;
1668 currentlyVisibleRegionInWebViewCoordinates.size = visibleSize;
1670 // Don't bother scrolling if the entire node is already visible, whether or not we got a selectionRect.
1671 if (CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:focusedElementRectInDocumentCoordinates fromView:_contentView.get()]))
1674 // Don't bother scrolling if we have a valid selectionRect and it is already visible.
1675 if (selectionRectIsNotNull && CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:selectionRectInDocumentCoordinates fromView:_contentView.get()]))
1679 // We want to zoom to the left/top corner of the DOM node, with as much spacing on all sides as we
1680 // can get based on the visible area after zooming (workingFrame). The spacing in either dimension is half the
1681 // difference between the size of the DOM node and the size of the visible frame.
1682 CGFloat horizontalSpaceInWebViewCoordinates = std::max((visibleSize.width - focusedElementRectInNewScale.width()) / 2.0, 0.0);
1683 CGFloat verticalSpaceInWebViewCoordinates = std::max((visibleSize.height - focusedElementRectInNewScale.height()) / 2.0, 0.0);
1686 topLeft.x = focusedElementRectInNewScale.x() - horizontalSpaceInWebViewCoordinates;
1687 topLeft.y = focusedElementRectInNewScale.y() - verticalSpaceInWebViewCoordinates - visibleOffsetFromTop;
1689 CGFloat minimumAllowableHorizontalOffsetInWebViewCoordinates = -INFINITY;
1690 CGFloat minimumAllowableVerticalOffsetInWebViewCoordinates = -INFINITY;
1691 if (selectionRectIsNotNull) {
1692 WebCore::FloatRect selectionRectInNewScale = selectionRectInDocumentCoordinates;
1693 selectionRectInNewScale.scale(scale);
1694 selectionRectInNewScale.moveBy([_contentView frame].origin);
1695 minimumAllowableHorizontalOffsetInWebViewCoordinates = CGRectGetMaxX(selectionRectInNewScale) + CaretOffsetFromWindowEdge - visibleSize.width;
1696 minimumAllowableVerticalOffsetInWebViewCoordinates = CGRectGetMaxY(selectionRectInNewScale) + CaretOffsetFromWindowEdge - visibleSize.height - visibleOffsetFromTop;
1699 WebCore::FloatRect documentBoundsInNewScale = [_contentView bounds];
1700 documentBoundsInNewScale.scale(scale);
1701 documentBoundsInNewScale.moveBy([_contentView frame].origin);
1703 // Constrain the left edge in document coordinates so that:
1704 // - it isn't so small that the scrollVisibleRect isn't visible on the screen
1705 // - it isn't so great that the document's right edge is less than the right edge of the screen
1706 if (selectionRectIsNotNull && topLeft.x < minimumAllowableHorizontalOffsetInWebViewCoordinates)
1707 topLeft.x = minimumAllowableHorizontalOffsetInWebViewCoordinates;
1709 CGFloat maximumAllowableHorizontalOffset = CGRectGetMaxX(documentBoundsInNewScale) - visibleSize.width;
1710 if (topLeft.x > maximumAllowableHorizontalOffset)
1711 topLeft.x = maximumAllowableHorizontalOffset;
1714 // Constrain the top edge in document coordinates so that:
1715 // - it isn't so small that the scrollVisibleRect isn't visible on the screen
1716 // - it isn't so great that the document's bottom edge is higher than the top of the form assistant
1717 if (selectionRectIsNotNull && topLeft.y < minimumAllowableVerticalOffsetInWebViewCoordinates)
1718 topLeft.y = minimumAllowableVerticalOffsetInWebViewCoordinates;
1720 CGFloat maximumAllowableVerticalOffset = CGRectGetMaxY(documentBoundsInNewScale) - visibleSize.height;
1721 if (topLeft.y > maximumAllowableVerticalOffset)
1722 topLeft.y = maximumAllowableVerticalOffset;
1725 WebCore::FloatPoint newCenter = CGPointMake(topLeft.x + unobscuredScrollViewRectInWebViewCoordinates.size.width / 2.0, topLeft.y + unobscuredScrollViewRectInWebViewCoordinates.size.height / 2.0);
1727 if (scale != contentZoomScale(self))
1728 _page->willStartUserTriggeredZooming();
1730 LOG_WITH_STREAM(VisibleRects, stream << "_zoomToFocusRect: zooming to " << newCenter << " scale:" << scale);
1732 // The newCenter has been computed in the new scale, but _zoomToCenter expected the center to be in the original scale.
1733 newCenter.scale(1 / scale);
1734 [_scrollView _zoomToCenter:newCenter
1736 duration:UIWebFormAnimationDuration
1740 - (CGFloat)_targetContentZoomScaleForRect:(const WebCore::FloatRect&)targetRect currentScale:(double)currentScale fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale
1742 WebCore::FloatSize unobscuredContentSize([self _contentRectForUserInteraction].size);
1743 double horizontalScale = unobscuredContentSize.width() * currentScale / targetRect.width();
1744 double verticalScale = unobscuredContentSize.height() * currentScale / targetRect.height();
1746 horizontalScale = std::min(std::max(horizontalScale, minimumScale), maximumScale);
1747 verticalScale = std::min(std::max(verticalScale, minimumScale), maximumScale);
1749 return fitEntireRect ? std::min(horizontalScale, verticalScale) : horizontalScale;
1752 - (BOOL)_zoomToRect:(WebCore::FloatRect)targetRect withOrigin:(WebCore::FloatPoint)origin fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale minimumScrollDistance:(float)minimumScrollDistance
1754 const float maximumScaleFactorDeltaForPanScroll = 0.02;
1756 double currentScale = contentZoomScale(self);
1757 double targetScale = [self _targetContentZoomScaleForRect:targetRect currentScale:currentScale fitEntireRect:fitEntireRect minimumScale:minimumScale maximumScale:maximumScale];
1759 if (fabs(targetScale - currentScale) < maximumScaleFactorDeltaForPanScroll) {
1760 if ([self _scrollToRect:targetRect origin:origin minimumScrollDistance:minimumScrollDistance])
1762 } else if (targetScale != currentScale) {
1763 [self _zoomToRect:targetRect atScale:targetScale origin:origin animated:YES];
1770 - (void)didMoveToWindow
1772 _page->activityStateDidChange(WebCore::ActivityState::AllFlags);
1775 - (void)setOpaque:(BOOL)opaque
1777 BOOL oldOpaque = self.opaque;
1779 [super setOpaque:opaque];
1780 [_contentView setOpaque:opaque];
1782 if (oldOpaque == opaque)
1785 _page->setDrawsBackground(opaque);
1786 [self _updateScrollViewBackground];
1789 - (void)setBackgroundColor:(UIColor *)backgroundColor
1791 [super setBackgroundColor:backgroundColor];
1792 [_contentView setBackgroundColor:backgroundColor];
1795 - (BOOL)_allowsDoubleTapGestures
1797 if (_fastClickingIsDisabled)
1800 // If the page is not user scalable, we don't allow double tap gestures.
1801 if (![_scrollView isZoomEnabled] || [_scrollView minimumZoomScale] >= [_scrollView maximumZoomScale])
1804 // If the viewport width was not explicit, we allow double tap gestures.
1805 if (!_viewportMetaTagWidthWasExplicit || _viewportMetaTagCameFromImageDocument)
1808 // If the page set a viewport width that wasn't the device width, then it was
1809 // scaled and thus will probably need to zoom.
1810 if (_viewportMetaTagWidth != WebCore::ViewportArguments::ValueDeviceWidth)
1813 // At this point, we have a page that asked for width = device-width. However,
1814 // if the content's width and height were large, we might have had to shrink it.
1815 // Since we'll enable double tap zoom whenever we're not at the actual
1816 // initial scale, this simply becomes a test of the current scale against 1.
1817 return !areEssentiallyEqualAsFloat(contentZoomScale(self), 1);
1820 #pragma mark - UIScrollViewDelegate
1822 - (BOOL)usesStandardContentView
1824 return !_customContentView;
1827 - (CGSize)scrollView:(UIScrollView*)scrollView contentSizeForZoomScale:(CGFloat)scale withProposedSize:(CGSize)proposedSize
1829 return roundScrollViewContentSize(*_page, proposedSize);
1832 - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
1834 ASSERT(_scrollView == scrollView);
1836 if (_customContentView)
1837 return _customContentView.get();
1839 return _contentView.get();
1842 - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
1844 if (![self usesStandardContentView])
1847 if (scrollView.pinchGestureRecognizer.state == UIGestureRecognizerStateBegan) {
1848 _page->willStartUserTriggeredZooming();
1849 [_contentView scrollViewWillStartPanOrPinchGesture];
1851 [_contentView willStartZoomOrScroll];
1854 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
1856 if (![self usesStandardContentView])
1859 if (scrollView.panGestureRecognizer.state == UIGestureRecognizerStateBegan)
1860 [_contentView scrollViewWillStartPanOrPinchGesture];
1862 [_contentView willStartZoomOrScroll];
1863 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
1864 // FIXME: We will want to detect whether snapping will occur before beginning to drag. See WebPageProxy::didCommitLayerTree.
1865 WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
1866 ASSERT(scrollView == _scrollView.get());
1867 CGFloat scrollDecelerationFactor = (coordinator && coordinator->shouldSetScrollViewDecelerationRateFast()) ? UIScrollViewDecelerationRateFast : [_scrollView preferredScrollDecelerationFactor];
1868 scrollView.horizontalScrollDecelerationFactor = scrollDecelerationFactor;
1869 scrollView.verticalScrollDecelerationFactor = scrollDecelerationFactor;
1873 - (void)_didFinishScrolling
1875 if (![self usesStandardContentView])
1878 [self _updateVisibleContentRectAfterScrollInView:_scrollView.get()];
1879 [_contentView didFinishScrolling];
1882 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
1884 // Work around <rdar://problem/16374753> by avoiding deceleration while
1885 // zooming. We'll animate to the right place once the zoom finishes.
1886 if ([scrollView isZooming])
1887 *targetContentOffset = [scrollView contentOffset];
1888 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
1889 if (WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy()) {
1890 // FIXME: Here, I'm finding the maximum horizontal/vertical scroll offsets. There's probably a better way to do this.
1891 CGSize maxScrollOffsets = CGSizeMake(scrollView.contentSize.width - scrollView.bounds.size.width, scrollView.contentSize.height - scrollView.bounds.size.height);
1893 CGRect fullViewRect = self.bounds;
1895 UIEdgeInsets contentInset;
1897 id<WKUIDelegatePrivate> uiDelegatePrivate = static_cast<id <WKUIDelegatePrivate>>([self UIDelegate]);
1898 if ([uiDelegatePrivate respondsToSelector:@selector(_webView:finalObscuredInsetsForScrollView:withVelocity:targetContentOffset:)])
1899 contentInset = [uiDelegatePrivate _webView:self finalObscuredInsetsForScrollView:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
1901 contentInset = [self _computedContentInset];
1903 CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, contentInset);
1905 coordinator->adjustTargetContentOffsetForSnapping(maxScrollOffsets, velocity, unobscuredRect.origin.y, targetContentOffset);
1910 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
1912 // If we're decelerating, scroll offset will be updated when scrollViewDidFinishDecelerating: is called.
1914 [self _didFinishScrolling];
1917 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
1919 [self _didFinishScrolling];
1922 - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
1924 [self _didFinishScrolling];
1927 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
1929 if (![self usesStandardContentView])
1930 [_customContentView scrollViewDidScroll:(UIScrollView *)scrollView];
1932 [self _updateVisibleContentRectAfterScrollInView:scrollView];
1934 if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
1935 scrollPerfData->didScroll([self visibleRectInViewCoordinates]);
1938 - (void)scrollViewDidZoom:(UIScrollView *)scrollView
1940 [self _updateScrollViewBackground];
1941 [self _updateVisibleContentRectAfterScrollInView:scrollView];
1944 - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
1946 ASSERT(scrollView == _scrollView);
1947 [self _updateVisibleContentRectAfterScrollInView:scrollView];
1948 [_contentView didZoomToScale:scale];
1951 - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
1953 [self _didFinishScrolling];
1956 - (void)_scrollViewDidInterruptDecelerating:(UIScrollView *)scrollView
1958 if (![self usesStandardContentView])
1961 [_contentView didInterruptScrolling];
1962 [self _updateVisibleContentRectAfterScrollInView:scrollView];
1965 - (CGRect)_visibleRectInEnclosingScrollView:(UIScrollView *)enclosingScrollView
1967 if (!enclosingScrollView)
1970 CGRect exposedRect = [enclosingScrollView convertRect:enclosingScrollView.bounds toView:self];
1971 return CGRectIntersectsRect(exposedRect, self.bounds) ? CGRectIntersection(exposedRect, self.bounds) : CGRectZero;
1974 - (CGRect)_visibleContentRect
1976 if (_frozenVisibleContentRect)
1977 return _frozenVisibleContentRect.value();
1979 CGRect visibleRectInContentCoordinates = [self convertRect:self.bounds toView:_contentView.get()];
1981 if (UIScrollView *enclosingScroller = [self _scroller]) {
1982 CGRect viewVisibleRect = [self _visibleRectInEnclosingScrollView:enclosingScroller];
1983 CGRect viewVisibleContentRect = [self convertRect:viewVisibleRect toView:_contentView.get()];
1984 visibleRectInContentCoordinates = CGRectIntersection(visibleRectInContentCoordinates, viewVisibleContentRect);
1987 return visibleRectInContentCoordinates;
1990 // Called when some ancestor UIScrollView scrolls.
1993 [self _updateVisibleContentRectAfterScrollInView:[self _scroller]];
1995 const NSTimeInterval ScrollingEndedTimerInterval = 0.032;
1996 if (!_enclosingScrollViewScrollTimer) {
1997 _enclosingScrollViewScrollTimer = adoptNS([[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:ScrollingEndedTimerInterval]
1998 interval:0 target:self selector:@selector(_enclosingScrollerScrollingEnded:) userInfo:nil repeats:YES]);
1999 [[NSRunLoop mainRunLoop] addTimer:_enclosingScrollViewScrollTimer.get() forMode:NSDefaultRunLoopMode];
2001 _didScrollSinceLastTimerFire = YES;
2004 - (void)_enclosingScrollerScrollingEnded:(NSTimer *)timer
2006 if (_didScrollSinceLastTimerFire) {
2007 _didScrollSinceLastTimerFire = NO;
2011 [self _updateVisibleContentRects];
2012 [_enclosingScrollViewScrollTimer invalidate];
2013 _enclosingScrollViewScrollTimer = nil;
2016 - (void)_frameOrBoundsChanged
2018 CGRect bounds = self.bounds;
2019 [_scrollView setFrame:bounds];
2021 if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing) {
2022 if (!_overridesMinimumLayoutSize)
2023 _page->setViewportConfigurationMinimumLayoutSize(WebCore::FloatSize(bounds.size));
2024 if (!_overridesMaximumUnobscuredSize)
2025 _page->setMaximumUnobscuredSize(WebCore::FloatSize(bounds.size));
2026 if (auto drawingArea = _page->drawingArea())
2027 drawingArea->setSize(WebCore::IntSize(bounds.size), WebCore::IntSize(), WebCore::IntSize());
2030 [_customContentView web_setMinimumSize:bounds.size];
2031 [self _updateVisibleContentRects];
2034 // 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.
2035 - (CGRect)_contentRectForUserInteraction
2037 // FIXME: handle split keyboard.
2038 UIEdgeInsets obscuredInsets = _obscuredInsets;
2039 obscuredInsets.bottom = std::max(_obscuredInsets.bottom, _inputViewBounds.size.height);
2040 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInsets);
2041 return [self convertRect:unobscuredRect toView:self._currentContentView];
2044 // Ideally UIScrollView would expose this for us: <rdar://problem/21394567>.
2045 - (BOOL)_scrollViewIsRubberBanding
2047 float deviceScaleFactor = _page->deviceScaleFactor();
2049 CGPoint contentOffset = [_scrollView contentOffset];
2050 CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
2051 return !pointsEqualInDevicePixels(contentOffset, boundedOffset, deviceScaleFactor);
2054 - (void)_updateVisibleContentRects
2056 // For visible rect updates not associated with a spefic UIScrollView, just consider our own scroller.
2057 [self _updateVisibleContentRectAfterScrollInView:_scrollView.get()];
2060 - (void)_updateVisibleContentRectAfterScrollInView:(UIScrollView *)scrollView
2062 BOOL isStableState = !([scrollView isDragging] || [scrollView isDecelerating] || [scrollView isZooming] || [scrollView _isAnimatingZoom] || [scrollView _isScrollingToTop]);
2064 if (isStableState && scrollView == _scrollView.get())
2065 isStableState = !_isChangingObscuredInsetsInteractively;
2067 if (isStableState && scrollView == _scrollView.get())
2068 isStableState = ![self _scrollViewIsRubberBanding];
2070 // FIXME: this can be made static after we stop supporting iOS 8.x.
2071 if (isStableState && [scrollView respondsToSelector:@selector(_isInterruptingDeceleration)])
2072 isStableState = ![scrollView performSelector:@selector(_isInterruptingDeceleration)];
2074 if (NSNumber *stableOverride = self._stableStateOverride)
2075 isStableState = stableOverride.boolValue;
2077 [self _updateContentRectsWithState:isStableState];
2080 static bool scrollViewCanScroll(UIScrollView *scrollView)
2085 UIEdgeInsets contentInset = scrollView.contentInset;
2086 CGSize contentSize = scrollView.contentSize;
2087 CGSize boundsSize = scrollView.bounds.size;
2089 return (contentSize.width + contentInset.left + contentInset.right) > boundsSize.width
2090 || (contentSize.height + contentInset.top + contentInset.bottom) > boundsSize.height;
2093 - (void)_updateContentRectsWithState:(BOOL)inStableState
2095 if (![self usesStandardContentView]) {
2096 [_customContentView web_computedContentInsetDidChange];
2100 if (_delayUpdateVisibleContentRects) {
2101 _hadDelayedUpdateVisibleContentRects = YES;
2105 if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing
2106 || _needsResetViewStateAfterCommitLoadForMainFrame
2107 || [_scrollView isZoomBouncing]
2108 || _currentlyAdjustingScrollViewInsetsForKeyboard)
2111 CGRect fullViewRect = self.bounds;
2112 CGRect visibleRectInContentCoordinates = [self _visibleContentRect];
2114 UIEdgeInsets computedContentInsetUnadjustedForKeyboard = [self _computedContentInset];
2115 if (!_haveSetObscuredInsets)
2116 computedContentInsetUnadjustedForKeyboard.bottom -= _totalScrollViewBottomInsetAdjustmentForKeyboard;
2118 CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, computedContentInsetUnadjustedForKeyboard);
2119 CGRect unobscuredRectInContentCoordinates = _frozenUnobscuredContentRect ? _frozenUnobscuredContentRect.value() : [self convertRect:unobscuredRect toView:_contentView.get()];
2121 CGFloat scaleFactor = contentZoomScale(self);
2123 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2124 if (inStableState) {
2125 WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2126 if (coordinator && coordinator->hasActiveSnapPoint()) {
2127 CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, computedContentInsetUnadjustedForKeyboard);
2129 CGPoint currentPoint = [_scrollView contentOffset];
2130 CGPoint activePoint = coordinator->nearestActiveContentInsetAdjustedSnapPoint(unobscuredRect.origin.y, currentPoint);
2132 if (!CGPointEqualToPoint(activePoint, currentPoint)) {
2133 RetainPtr<WKScrollView> strongScrollView = _scrollView;
2134 dispatch_async(dispatch_get_main_queue(), [strongScrollView, activePoint] {
2135 [strongScrollView setContentOffset:activePoint animated:NO];
2142 [_contentView didUpdateVisibleRect:visibleRectInContentCoordinates
2143 unobscuredRect:unobscuredRectInContentCoordinates
2144 unobscuredRectInScrollViewCoordinates:unobscuredRect
2145 obscuredInset:CGSizeMake(_obscuredInsets.left, _obscuredInsets.top)
2146 scale:scaleFactor minimumScale:[_scrollView minimumZoomScale]
2147 inStableState:inStableState
2148 isChangingObscuredInsetsInteractively:_isChangingObscuredInsetsInteractively
2149 enclosedInScrollableAncestorView:scrollViewCanScroll([self _scroller])];
2152 - (void)_didFinishLoadForMainFrame
2154 if (_gestureController)
2155 _gestureController->didFinishLoadForMainFrame();
2158 - (void)_didFailLoadForMainFrame
2160 if (_gestureController)
2161 _gestureController->didFailLoadForMainFrame();
2164 - (void)_didSameDocumentNavigationForMainFrame:(WebKit::SameDocumentNavigationType)navigationType
2166 [_customContentView web_didSameDocumentNavigation:toAPI(navigationType)];
2168 if (_gestureController)
2169 _gestureController->didSameDocumentNavigationForMainFrame(navigationType);
2172 - (void)_keyboardChangedWithInfo:(NSDictionary *)keyboardInfo adjustScrollView:(BOOL)adjustScrollView
2174 NSValue *endFrameValue = [keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
2178 // The keyboard rect is always in screen coordinates. In the view services case the window does not
2179 // have the interface orientation rotation transformation; its host does. So, it makes no sense to
2180 // clip the keyboard rect against its screen.
2181 if ([[self window] _isHostedInAnotherProcess])
2182 _inputViewBounds = [self.window convertRect:[endFrameValue CGRectValue] fromWindow:nil];
2184 _inputViewBounds = [self.window convertRect:CGRectIntersection([endFrameValue CGRectValue], self.window.screen.bounds) fromWindow:nil];
2186 if (adjustScrollView) {
2187 CGFloat bottomInsetBeforeAdjustment = [_scrollView contentInset].bottom;
2188 SetForScope<BOOL> insetAdjustmentGuard(_currentlyAdjustingScrollViewInsetsForKeyboard, YES);
2189 [_scrollView _adjustForAutomaticKeyboardInfo:keyboardInfo animated:YES lastAdjustment:&_lastAdjustmentForScroller];
2190 CGFloat bottomInsetAfterAdjustment = [_scrollView contentInset].bottom;
2191 if (bottomInsetBeforeAdjustment != bottomInsetAfterAdjustment)
2192 _totalScrollViewBottomInsetAdjustmentForKeyboard += bottomInsetAfterAdjustment - bottomInsetBeforeAdjustment;
2195 [self _updateVisibleContentRects];
2198 - (BOOL)_shouldUpdateKeyboardWithInfo:(NSDictionary *)keyboardInfo
2200 if ([_contentView isAssistingNode])
2203 NSNumber *isLocalKeyboard = [keyboardInfo valueForKey:UIKeyboardIsLocalUserInfoKey];
2204 return isLocalKeyboard && !isLocalKeyboard.boolValue;
2207 - (void)_keyboardWillChangeFrame:(NSNotification *)notification
2209 if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
2210 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
2213 - (void)_keyboardDidChangeFrame:(NSNotification *)notification
2215 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:NO];
2218 - (void)_keyboardWillShow:(NSNotification *)notification
2220 if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
2221 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
2223 _page->setIsKeyboardAnimatingIn(true);
2226 - (void)_keyboardDidShow:(NSNotification *)notification
2228 _page->setIsKeyboardAnimatingIn(false);
2231 - (void)_keyboardWillHide:(NSNotification *)notification
2233 // Ignore keyboard will hide notifications sent during rotation. They're just there for
2234 // backwards compatibility reasons and processing the will hide notification would
2235 // temporarily screw up the the unobscured view area.
2236 if ([[UIPeripheralHost sharedInstance] rotationState])
2239 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
2242 - (void)_windowDidRotate:(NSNotification *)notification
2244 if (!_overridesInterfaceOrientation)
2245 _page->setDeviceOrientation(deviceOrientation());
2248 - (void)_contentSizeCategoryDidChange:(NSNotification *)notification
2250 _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
2253 - (NSString *)_contentSizeCategory
2255 return [[UIApplication sharedApplication] preferredContentSizeCategory];
2258 - (void)_accessibilitySettingsDidChange:(NSNotification *)notification
2260 _page->accessibilitySettingsDidChange();
2263 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
2265 if (_allowsBackForwardNavigationGestures == allowsBackForwardNavigationGestures)
2268 _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
2270 if (allowsBackForwardNavigationGestures) {
2271 if (!_gestureController) {
2272 _gestureController = std::make_unique<WebKit::ViewGestureController>(*_page);
2273 _gestureController->installSwipeHandler(self, [self scrollView]);
2274 if (WKWebView *alternateWebView = [_configuration _alternateWebViewForNavigationGestures])
2275 _gestureController->setAlternateBackForwardListSourcePage(alternateWebView->_page.get());
2278 _gestureController = nullptr;
2280 _page->setShouldRecordNavigationSnapshots(allowsBackForwardNavigationGestures);
2283 - (BOOL)allowsBackForwardNavigationGestures
2285 return _allowsBackForwardNavigationGestures;
2288 - (void)_navigationGestureDidBegin
2290 // During a back/forward swipe, there's a view interposed between this view and the content view that has
2291 // an offset and animation on it, which results in computing incorrect rectangles. Work around by using
2292 // frozen rects during swipes.
2293 CGRect fullViewRect = self.bounds;
2294 CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, [self _computedContentInset]);
2296 _frozenVisibleContentRect = [self convertRect:fullViewRect toView:_contentView.get()];
2297 _frozenUnobscuredContentRect = [self convertRect:unobscuredRect toView:_contentView.get()];
2299 LOG_WITH_STREAM(VisibleRects, stream << "_navigationGestureDidBegin: freezing visibleContentRect " << _frozenVisibleContentRect.value() << " UnobscuredContentRect " << _frozenUnobscuredContentRect.value());
2302 - (void)_navigationGestureDidEnd
2304 _frozenVisibleContentRect = Nullopt;
2305 _frozenUnobscuredContentRect = Nullopt;
2308 #endif // PLATFORM(IOS)
2310 #pragma mark OS X-specific methods
2314 - (BOOL)acceptsFirstResponder
2316 return _impl->acceptsFirstResponder();
2319 - (BOOL)becomeFirstResponder
2321 return _impl->becomeFirstResponder();
2324 - (BOOL)resignFirstResponder
2326 return _impl->resignFirstResponder();
2329 - (void)viewWillStartLiveResize
2331 _impl->viewWillStartLiveResize();
2334 - (void)viewDidEndLiveResize
2336 _impl->viewDidEndLiveResize();
2344 - (NSSize)intrinsicContentSize
2346 return NSSizeFromCGSize(_impl->intrinsicContentSize());
2349 - (void)prepareContentInRect:(NSRect)rect
2351 _impl->prepareContentInRect(NSRectToCGRect(rect));
2354 - (void)setFrameSize:(NSSize)size
2356 [super setFrameSize:size];
2357 _impl->setFrameSize(NSSizeToCGSize(size));
2362 _impl->renewGState();
2363 [super renewGState];
2366 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _impl->executeEditCommandForSelector(_cmd); }
2368 WEBCORE_COMMAND(alignCenter)
2369 WEBCORE_COMMAND(alignJustified)
2370 WEBCORE_COMMAND(alignLeft)
2371 WEBCORE_COMMAND(alignRight)
2372 WEBCORE_COMMAND(copy)
2373 WEBCORE_COMMAND(cut)
2374 WEBCORE_COMMAND(delete)
2375 WEBCORE_COMMAND(deleteBackward)
2376 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
2377 WEBCORE_COMMAND(deleteForward)
2378 WEBCORE_COMMAND(deleteToBeginningOfLine)
2379 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
2380 WEBCORE_COMMAND(deleteToEndOfLine)
2381 WEBCORE_COMMAND(deleteToEndOfParagraph)
2382 WEBCORE_COMMAND(deleteToMark)
2383 WEBCORE_COMMAND(deleteWordBackward)
2384 WEBCORE_COMMAND(deleteWordForward)
2385 WEBCORE_COMMAND(ignoreSpelling)
2386 WEBCORE_COMMAND(indent)
2387 WEBCORE_COMMAND(insertBacktab)
2388 WEBCORE_COMMAND(insertLineBreak)
2389 WEBCORE_COMMAND(insertNewline)
2390 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
2391 WEBCORE_COMMAND(insertParagraphSeparator)
2392 WEBCORE_COMMAND(insertTab)
2393 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
2394 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
2395 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
2396 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
2397 WEBCORE_COMMAND(moveBackward)
2398 WEBCORE_COMMAND(moveBackwardAndModifySelection)
2399 WEBCORE_COMMAND(moveDown)
2400 WEBCORE_COMMAND(moveDownAndModifySelection)
2401 WEBCORE_COMMAND(moveForward)
2402 WEBCORE_COMMAND(moveForwardAndModifySelection)
2403 WEBCORE_COMMAND(moveLeft)
2404 WEBCORE_COMMAND(moveLeftAndModifySelection)
2405 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
2406 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
2407 WEBCORE_COMMAND(moveRight)
2408 WEBCORE_COMMAND(moveRightAndModifySelection)
2409 WEBCORE_COMMAND(moveToBeginningOfDocument)
2410 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
2411 WEBCORE_COMMAND(moveToBeginningOfLine)
2412 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
2413 WEBCORE_COMMAND(moveToBeginningOfParagraph)
2414 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
2415 WEBCORE_COMMAND(moveToBeginningOfSentence)
2416 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
2417 WEBCORE_COMMAND(moveToEndOfDocument)
2418 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
2419 WEBCORE_COMMAND(moveToEndOfLine)
2420 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
2421 WEBCORE_COMMAND(moveToEndOfParagraph)
2422 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
2423 WEBCORE_COMMAND(moveToEndOfSentence)
2424 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
2425 WEBCORE_COMMAND(moveToLeftEndOfLine)
2426 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
2427 WEBCORE_COMMAND(moveToRightEndOfLine)
2428 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
2429 WEBCORE_COMMAND(moveUp)
2430 WEBCORE_COMMAND(moveUpAndModifySelection)
2431 WEBCORE_COMMAND(moveWordBackward)
2432 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
2433 WEBCORE_COMMAND(moveWordForward)
2434 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
2435 WEBCORE_COMMAND(moveWordLeft)
2436 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
2437 WEBCORE_COMMAND(moveWordRight)
2438 WEBCORE_COMMAND(moveWordRightAndModifySelection)
2439 WEBCORE_COMMAND(outdent)
2440 WEBCORE_COMMAND(pageDown)
2441 WEBCORE_COMMAND(pageDownAndModifySelection)
2442 WEBCORE_COMMAND(pageUp)
2443 WEBCORE_COMMAND(pageUpAndModifySelection)
2444 WEBCORE_COMMAND(paste)
2445 WEBCORE_COMMAND(pasteAsPlainText)
2446 WEBCORE_COMMAND(scrollPageDown)
2447 WEBCORE_COMMAND(scrollPageUp)
2448 WEBCORE_COMMAND(scrollLineDown)
2449 WEBCORE_COMMAND(scrollLineUp)
2450 WEBCORE_COMMAND(scrollToBeginningOfDocument)
2451 WEBCORE_COMMAND(scrollToEndOfDocument)
2452 WEBCORE_COMMAND(selectAll)
2453 WEBCORE_COMMAND(selectLine)
2454 WEBCORE_COMMAND(selectParagraph)
2455 WEBCORE_COMMAND(selectSentence)
2456 WEBCORE_COMMAND(selectToMark)
2457 WEBCORE_COMMAND(selectWord)
2458 WEBCORE_COMMAND(setMark)
2459 WEBCORE_COMMAND(subscript)
2460 WEBCORE_COMMAND(superscript)
2461 WEBCORE_COMMAND(swapWithMark)
2462 WEBCORE_COMMAND(takeFindStringFromSelection)
2463 WEBCORE_COMMAND(transpose)
2464 WEBCORE_COMMAND(underline)
2465 WEBCORE_COMMAND(unscript)
2466 WEBCORE_COMMAND(yank)
2467 WEBCORE_COMMAND(yankAndSelect)
2469 #undef WEBCORE_COMMAND
2471 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
2473 return _impl->writeSelectionToPasteboard(pasteboard, types);
2476 - (void)centerSelectionInVisibleArea:(id)sender
2478 _impl->centerSelectionInVisibleArea();
2481 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
2483 return _impl->validRequestorForSendAndReturnTypes(sendType, returnType);
2486 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
2488 return _impl->readSelectionFromPasteboard(pasteboard);
2491 - (void)changeFont:(id)sender
2493 _impl->changeFontFromFontPanel();
2496 - (IBAction)startSpeaking:(id)sender
2498 _impl->startSpeaking();
2501 - (IBAction)stopSpeaking:(id)sender
2503 _impl->stopSpeaking(sender);
2506 - (IBAction)showGuessPanel:(id)sender
2508 _impl->showGuessPanel(sender);
2511 - (IBAction)checkSpelling:(id)sender
2513 _impl->checkSpelling();
2516 - (void)changeSpelling:(id)sender
2518 _impl->changeSpelling(sender);
2521 - (IBAction)toggleContinuousSpellChecking:(id)sender
2523 _impl->toggleContinuousSpellChecking();
2526 - (BOOL)isGrammarCheckingEnabled
2528 return _impl->isGrammarCheckingEnabled();
2531 - (void)setGrammarCheckingEnabled:(BOOL)flag
2533 _impl->setGrammarCheckingEnabled(flag);
2536 - (IBAction)toggleGrammarChecking:(id)sender
2538 _impl->toggleGrammarChecking();
2541 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
2543 _impl->toggleAutomaticSpellingCorrection();
2546 - (void)orderFrontSubstitutionsPanel:(id)sender
2548 _impl->orderFrontSubstitutionsPanel(sender);
2551 - (IBAction)toggleSmartInsertDelete:(id)sender
2553 _impl->toggleSmartInsertDelete();
2556 - (BOOL)isAutomaticQuoteSubstitutionEnabled
2558 return _impl->isAutomaticQuoteSubstitutionEnabled();
2561 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
2563 _impl->setAutomaticQuoteSubstitutionEnabled(flag);
2566 - (void)toggleAutomaticQuoteSubstitution:(id)sender
2568 _impl->toggleAutomaticQuoteSubstitution();
2571 - (BOOL)isAutomaticDashSubstitutionEnabled
2573 return _impl->isAutomaticDashSubstitutionEnabled();
2576 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
2578 _impl->setAutomaticDashSubstitutionEnabled(flag);
2581 - (void)toggleAutomaticDashSubstitution:(id)sender
2583 _impl->toggleAutomaticDashSubstitution();
2586 - (BOOL)isAutomaticLinkDetectionEnabled
2588 return _impl->isAutomaticLinkDetectionEnabled();
2591 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
2593 _impl->setAutomaticLinkDetectionEnabled(flag);
2596 - (void)toggleAutomaticLinkDetection:(id)sender
2598 _impl->toggleAutomaticLinkDetection();
2601 - (BOOL)isAutomaticTextReplacementEnabled
2603 return _impl->isAutomaticTextReplacementEnabled();
2606 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
2608 _impl->setAutomaticTextReplacementEnabled(flag);
2611 - (void)toggleAutomaticTextReplacement:(id)sender
2613 _impl->toggleAutomaticTextReplacement();
2616 - (void)uppercaseWord:(id)sender
2618 _impl->uppercaseWord();
2621 - (void)lowercaseWord:(id)sender
2623 _impl->lowercaseWord();
2626 - (void)capitalizeWord:(id)sender
2628 _impl->capitalizeWord();
2631 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
2633 return _impl->wantsKeyDownForEvent(event);
2636 - (void)scrollWheel:(NSEvent *)event
2638 _impl->scrollWheel(event);
2641 - (void)swipeWithEvent:(NSEvent *)event
2643 _impl->swipeWithEvent(event);
2646 - (void)mouseMoved:(NSEvent *)event
2648 _impl->mouseMoved(event);
2651 - (void)mouseDown:(NSEvent *)event
2653 _impl->mouseDown(event);
2656 - (void)mouseUp:(NSEvent *)event
2658 _impl->mouseUp(event);
2661 - (void)mouseDragged:(NSEvent *)event
2663 _impl->mouseDragged(event);
2666 - (void)mouseEntered:(NSEvent *)event
2668 _impl->mouseEntered(event);
2671 - (void)mouseExited:(NSEvent *)event
2673 _impl->mouseExited(event);
2676 - (void)otherMouseDown:(NSEvent *)event
2678 _impl->otherMouseDown(event);
2681 - (void)otherMouseDragged:(NSEvent *)event
2683 _impl->otherMouseDragged(event);
2686 - (void)otherMouseUp:(NSEvent *)event
2688 _impl->otherMouseUp(event);
2691 - (void)rightMouseDown:(NSEvent *)event
2693 _impl->rightMouseDown(event);
2696 - (void)rightMouseDragged:(NSEvent *)event
2698 _impl->rightMouseDragged(event);
2701 - (void)rightMouseUp:(NSEvent *)event
2703 _impl->rightMouseUp(event);
2706 - (void)pressureChangeWithEvent:(NSEvent *)event
2708 _impl->pressureChangeWithEvent(event);
2711 - (BOOL)acceptsFirstMouse:(NSEvent *)event
2713 return _impl->acceptsFirstMouse(event);
2716 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
2718 return _impl->shouldDelayWindowOrderingForEvent(event);
2721 - (void)doCommandBySelector:(SEL)selector
2723 _impl->doCommandBySelector(selector);
2726 - (void)insertText:(id)string
2728 _impl->insertText(string);
2731 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
2733 _impl->insertText(string, replacementRange);
2736 - (NSTextInputContext *)inputContext
2740 return _impl->inputContext();
2743 - (BOOL)performKeyEquivalent:(NSEvent *)event
2745 return _impl->performKeyEquivalent(event);
2748 - (void)keyUp:(NSEvent *)theEvent
2750 _impl->keyUp(theEvent);
2753 - (void)keyDown:(NSEvent *)theEvent
2755 _impl->keyDown(theEvent);
2758 - (void)flagsChanged:(NSEvent *)theEvent
2760 _impl->flagsChanged(theEvent);
2763 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelectedRange replacementRange:(NSRange)replacementRange
2765 _impl->setMarkedText(string, newSelectedRange, replacementRange);
2770 _impl->unmarkText();
2773 - (NSRange)selectedRange
2775 return _impl->selectedRange();
2778 - (BOOL)hasMarkedText
2780 return _impl->hasMarkedText();
2783 - (NSRange)markedRange
2785 return _impl->markedRange();
2788 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange
2790 return _impl->attributedSubstringForProposedRange(nsRange, actualRange);
2793 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
2795 return _impl->characterIndexForPoint(thePoint);
2798 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
2800 return _impl->firstRectForCharacterRange(theRange, actualRange);
2803 - (void)selectedRangeWithCompletionHandler:(void(^)(NSRange selectedRange))completionHandlerPtr
2805 _impl->selectedRangeWithCompletionHandler(completionHandlerPtr);
2808 - (void)markedRangeWithCompletionHandler:(void(^)(NSRange markedRange))completionHandlerPtr
2810 _impl->markedRangeWithCompletionHandler(completionHandlerPtr);
2813 - (void)hasMarkedTextWithCompletionHandler:(void(^)(BOOL hasMarkedText))completionHandlerPtr
2815 _impl->hasMarkedTextWithCompletionHandler(completionHandlerPtr);
2818 - (void)attributedSubstringForProposedRange:(NSRange)nsRange completionHandler:(void(^)(NSAttributedString *attrString, NSRange actualRange))completionHandlerPtr
2820 _impl->attributedSubstringForProposedRange(nsRange, completionHandlerPtr);
2823 - (void)firstRectForCharacterRange:(NSRange)theRange completionHandler:(void(^)(NSRect firstRect, NSRange actualRange))completionHandlerPtr
2825 _impl->firstRectForCharacterRange(theRange, completionHandlerPtr);
2828 - (void)characterIndexForPoint:(NSPoint)thePoint completionHandler:(void(^)(NSUInteger))completionHandlerPtr
2830 _impl->characterIndexForPoint(thePoint, completionHandlerPtr);
2833 - (NSArray *)validAttributesForMarkedText
2835 return _impl->validAttributesForMarkedText();
2838 #if ENABLE(DRAG_SUPPORT)
2839 - (void)draggedImage:(NSImage *)image endedAt:(NSPoint)endPoint operation:(NSDragOperation)operation
2841 _impl->draggedImage(image, NSPointToCGPoint(endPoint), operation);
2844 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
2846 return _impl->draggingEntered(draggingInfo);
2849 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
2851 return _impl->draggingUpdated(draggingInfo);
2854 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
2856 _impl->draggingExited(draggingInfo);
2859 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
2861 return _impl->prepareForDragOperation(draggingInfo);
2864 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
2866 return _impl->performDragOperation(draggingInfo);
2869 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
2871 return _impl->hitTestForDragTypes(NSPointToCGPoint(*point), types);
2873 #endif // ENABLE(DRAG_SUPPORT)
2875 - (BOOL)_windowResizeMouseLocationIsInVisibleScrollerThumb:(NSPoint)point
2877 return _impl->windowResizeMouseLocationIsInVisibleScrollerThumb(NSPointToCGPoint(point));
2880 - (void)viewWillMoveToWindow:(NSWindow *)window
2882 _impl->viewWillMoveToWindow(window);
2885 - (void)viewDidMoveToWindow
2887 _impl->viewDidMoveToWindow();
2890 - (void)drawRect:(NSRect)rect
2892 _impl->drawRect(NSRectToCGRect(rect));
2897 return _impl->isOpaque();
2900 - (BOOL)mouseDownCanMoveWindow
2902 return WebKit::WebViewImpl::mouseDownCanMoveWindow();
2907 _impl->viewDidHide();
2910 - (void)viewDidUnhide
2912 _impl->viewDidUnhide();
2915 - (void)viewDidChangeBackingProperties
2917 _impl->viewDidChangeBackingProperties();
2920 - (void)_activeSpaceDidChange:(NSNotification *)notification
2922 _impl->activeSpaceDidChange();
2925 - (id)accessibilityFocusedUIElement
2927 return _impl->accessibilityFocusedUIElement();
2930 - (BOOL)accessibilityIsIgnored
2932 return _impl->accessibilityIsIgnored();
2935 - (id)accessibilityHitTest:(NSPoint)point
2937 return _impl->accessibilityHitTest(NSPointToCGPoint(point));
2940 - (id)accessibilityAttributeValue:(NSString *)attribute
2942 return _impl->accessibilityAttributeValue(attribute);
2945 - (NSView *)hitTest:(NSPoint)point
2948 return [super hitTest:point];
2949 return _impl->hitTest(NSPointToCGPoint(point));
2952 - (NSInteger)conversationIdentifier
2954 return (NSInteger)self;
2957 - (void)quickLookWithEvent:(NSEvent *)event
2959 _impl->quickLookWithEvent(event);
2962 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
2964 return _impl->addTrackingRect(NSRectToCGRect(rect), owner, data, assumeInside);
2967 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
2969 return _impl->addTrackingRectWithTrackingNum(NSRectToCGRect(rect), owner, data, assumeInside, tag);
2972 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
2974 CGRect *cgRects = (CGRect *)calloc(1, sizeof(CGRect));
2975 for (int i = 0; i < count; i++)
2976 cgRects[i] = NSRectToCGRect(rects[i]);
2977 _impl->addTrackingRectsWithTrackingNums(cgRects, owner, userDataList, assumeInsideList, trackingNums, count);
2981 - (void)removeTrackingRect:(NSTrackingRectTag)tag
2985 _impl->removeTrackingRect(tag);
2988 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
2992 _impl->removeTrackingRects(tags, count);
2995 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
2997 return _impl->stringForToolTip(tag);
3000 - (void)pasteboardChangedOwner:(NSPasteboard *)pasteboard
3002 _impl->pasteboardChangedOwner(pasteboard);
3005 - (void)pasteboard:(NSPasteboard *)pasteboard provideDataForType:(NSString *)type
3007 _impl->provideDataForPasteboard(pasteboard, type);
3010 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
3012 return _impl->namesOfPromisedFilesDroppedAtDestination(dropDestination);
3015 - (BOOL)wantsUpdateLayer
3017 return WebKit::WebViewImpl::wantsUpdateLayer();
3022 _impl->updateLayer();
3025 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
3027 _impl->setAllowsBackForwardNavigationGestures(allowsBackForwardNavigationGestures);
3030 - (BOOL)allowsBackForwardNavigationGestures
3032 return _impl->allowsBackForwardNavigationGestures();
3035 - (void)smartMagnifyWithEvent:(NSEvent *)event
3037 _impl->smartMagnifyWithEvent(event);
3040 - (void)setMagnification:(double)magnification centeredAtPoint:(NSPoint)point
3042 _impl->setMagnification(magnification, NSPointToCGPoint(point));
3045 - (void)setMagnification:(double)magnification
3047 _impl->setMagnification(magnification);
3050 - (double)magnification
3052 return _impl->magnification();
3055 - (void)setAllowsMagnification:(BOOL)allowsMagnification
3057 _impl->setAllowsMagnification(allowsMagnification);
3060 - (BOOL)allowsMagnification
3062 return _impl->allowsMagnification();
3065 - (void)magnifyWithEvent:(NSEvent *)event
3067 _impl->magnifyWithEvent(event);
3070 #if ENABLE(MAC_GESTURE_EVENTS)
3071 - (void)rotateWithEvent:(NSEvent *)event
3073 _impl->rotateWithEvent(event);
3077 - (WKTextFinderClient *)_ensureTextFinderClient
3079 if (!_textFinderClient)
3080 _textFinderClient = adoptNS([[WKTextFinderClient alloc] initWithPage:*_page view:self]);
3081 return _textFinderClient.get();
3084 - (void)findMatchesForString:(NSString *)targetString relativeToMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)relativeMatch findOptions:(NSTextFinderAsynchronousDocumentFindOptions)findOptions maxResults:(NSUInteger)maxResults resultCollector:(void (^)(NSArray *matches, BOOL didWrap))resultCollector
3086 [[self _ensureTextFinderClient] findMatchesForString:targetString relativeToMatch:relativeMatch findOptions:findOptions maxResults:maxResults resultCollector:resultCollector];
3089 - (NSView *)documentContainerView
3094 - (void)getSelectedText:(void (^)(NSString *selectedTextString))completionHandler
3096 [[self _ensureTextFinderClient] getSelectedText:completionHandler];
3099 - (void)selectFindMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)findMatch completionHandler:(void (^)(void))completionHandler
3101 [[self _ensureTextFinderClient] selectFindMatch:findMatch completionHandler:completionHandler];
3104 - (NSTextInputContext *)_web_superInputContext
3106 return [super inputContext];
3109 - (void)_web_superQuickLookWithEvent:(NSEvent *)event
3111 [super quickLookWithEvent:event];
3114 - (void)_web_superSwipeWithEvent:(NSEvent *)event
3116 [super swipeWithEvent:event];
3119 - (void)_web_superMagnifyWithEvent:(NSEvent *)event
3121 [super magnifyWithEvent:event];
3124 - (void)_web_superSmartMagnifyWithEvent:(NSEvent *)event
3126 [super smartMagnifyWithEvent:event];
3129 - (void)_web_superRemoveTrackingRect:(NSTrackingRectTag)tag
3131 [super removeTrackingRect:tag];
3134 - (id)_web_superAccessibilityAttributeValue:(NSString *)attribute
3136 #pragma clang diagnostic push
3137 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
3138 return [super accessibilityAttributeValue:attribute];
3139 #pragma clang diagnostic pop
3142 - (void)_web_superDoCommandBySelector:(SEL)selector
3144 [super doCommandBySelector:selector];
3147 - (BOOL)_web_superPerformKeyEquivalent:(NSEvent *)event
3149 return [super performKeyEquivalent:event];
3152 - (void)_web_superKeyDown:(NSEvent *)event
3154 [super keyDown:event];
3157 - (NSView *)_web_superHitTest:(NSPoint)point
3159 return [super hitTest:point];
3162 - (id)_web_immediateActionAnimationControllerForHitTestResultInternal:(API::HitTestResult*)hitTestResult withType:(uint32_t)type userData:(API::Object*)userData
3164 id<NSSecureCoding> data = userData ? static_cast<id<NSSecureCoding>>(userData->wrapper()) : nil;
3165 return [self _immediateActionAnimationControllerForHitTestResult:wrapper(*hitTestResult) withType:(_WKImmediateActionType)type userData:data];
3168 // We don't expose these various bits of SPI like WKView does,
3169 // so have these internal methods just do the work (or do nothing):
3170 - (void)_web_prepareForImmediateActionAnimation
3174 - (void)_web_cancelImmediateActionAnimation
3178 - (void)_web_completeImmediateActionAnimation
3182 - (void)_web_didChangeContentSize:(NSSize)newSize
3186 - (void)_web_dismissContentRelativeChildWindows
3188 _impl->dismissContentRelativeChildWindowsFromViewOnly();
3191 - (void)_web_dismissContentRelativeChildWindowsWithAnimation:(BOOL)withAnimation
3193 _impl->dismissContentRelativeChildWindowsWithAnimationFromViewOnly(withAnimation);
3196 - (void)_web_gestureEventWasNotHandledByWebCore:(NSEvent *)event
3198 _impl->gestureEventWasNotHandledByWebCoreFromViewOnly(event);
3201 #endif // PLATFORM(MAC)
3207 - (NSTouchBar *)makeTouchBar
3209 return _impl->makeTouchBar();
3212 - (NSCandidateListTouchBarItem *)candidateListTouchBarItem
3214 return _impl->candidateListTouchBarItem();
3217 - (void)_web_didAddMediaControlsManager:(id)controlsManager
3219 [self _addMediaPlaybackControlsView:controlsManager];
3222 - (void)_web_didRemoveMediaControlsManager
3224 [self _removeMediaPlaybackControlsView];
3227 - (void)_interactWithMediaControlsForTesting
3229 [self _setWantsMediaPlaybackControlsView:YES];
3230 [self makeTouchBar];
3233 #endif // HAVE(TOUCH_BAR)
3237 @implementation WKWebView (WKPrivate)
3241 return _page->isEditable();
3244 - (void)_setEditable:(BOOL)editable
3246 _page->setEditable(editable);
3248 _impl->startObservingFontPanel();
3252 - (_WKRemoteObjectRegistry *)_remoteObjectRegistry
3255 return _impl->remoteObjectRegistry();
3257 if (!_remoteObjectRegistry) {
3258 _remoteObjectRegistry = adoptNS([[_WKRemoteObjectRegistry alloc] _initWithMessageSender:*_page]);
3259 _page->process().processPool().addMessageReceiver(Messages::RemoteObjectRegistry::messageReceiverName(), _page->pageID(), [_remoteObjectRegistry remoteObjectRegistry]);
3262 return _remoteObjectRegistry.get();
3266 - (WKBrowsingContextHandle *)_handle
3268 return [[[WKBrowsingContextHandle alloc] _initWithPageID:_page->pageID()] autorelease];
3271 - (_WKRenderingProgressEvents)_observedRenderingProgressEvents
3273 return _observedRenderingProgressEvents;
3276 - (id <WKHistoryDelegatePrivate>)_historyDelegate
3278 return _navigationState->historyDelegate().autorelease();
3281 - (void)_setHistoryDelegate:(id <WKHistoryDelegatePrivate>)historyDelegate
3283 _page->setHistoryClient(_navigationState->createHistoryClient());
3284 _navigationState->setHistoryDelegate(historyDelegate);
3287 - (NSURL *)_unreachableURL
3289 return [NSURL _web_URLWithWTFString:_page->pageLoadState().unreachableURL()];
3292 - (void)_loadAlternateHTMLString:(NSString *)string baseURL:(NSURL *)baseURL forUnreachableURL:(NSURL *)unreachableURL
3294 _page->loadAlternateHTMLString(string, [baseURL _web_originalDataAsWTFString], [unreachableURL _web_originalDataAsWTFString]);
3297 - (WKNavigation *)_loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL userData:(id)userData
3299 auto navigation = _page->loadData(API::Data::createWithoutCopying(data).ptr(), MIMEType, characterEncodingName, baseURL.absoluteString, WebKit::ObjCObjectGraph::create(userData).ptr());
3303 return [wrapper(*navigation.leakRef()) autorelease];
3306 - (NSArray *)_certificateChain
3308 if (WebKit::WebFrameProxy* mainFrame = _page->mainFrame())
3309 return mainFrame->certificateInfo() ? (NSArray *)mainFrame->certificateInfo()->certificateInfo().certificateChain() : nil;
3314 - (NSURL *)_committedURL
3316 return [NSURL _web_URLWithWTFString:_page->pageLoadState().url()];
3319 - (NSString *)_MIMEType
3321 if (_page->mainFrame())
3322 return _page->mainFrame()->mimeType();
3327 - (NSString *)_userAgent
3329 return _page->userAgent();
3332 - (NSString *)_applicationNameForUserAgent
3334 return _page->applicationNameForUserAgent();
3337 - (void)_setApplicationNameForUserAgent:(NSString *)applicationNameForUserAgent
3339 _page->setApplicationNameForUserAgent(applicationNameForUserAgent);
3342 - (NSString *)_customUserAgent
3344 return self.customUserAgent;
3347 - (void)_setCustomUserAgent:(NSString *)customUserAgent
3349 self.customUserAgent = customUserAgent;
3352 - (void)_setUserContentExtensionsEnabled:(BOOL)userContentExtensionsEnabled
3354 // This is kept for binary compatibility with iOS 9.
3357 - (BOOL)_userContentExtensionsEnabled
3359 // This is kept for binary compatibility with iOS 9.
3363 - (pid_t)_webProcessIdentifier
3365 return _page->isValid() ? _page->processIdentifier() : 0;
3368 - (void)_killWebContentProcess
3370 if (!_page->isValid())
3373 _page->process().terminate();
3376 - (WKNavigation *)_reloadWithoutContentBlockers
3378 const bool reloadFromOrigin = false;
3379 const bool contentBlockersEnabled = false;
3380 auto navigation = _page->reload(reloadFromOrigin, contentBlockersEnabled);
3384 return [wrapper(*navigation.leakRef()) autorelease];
3387 - (void)_killWebContentProcessAndResetState
3389 _page->terminateProcess();
3393 static WebCore::FloatSize activeMinimumLayoutSize(WKWebView *webView, const CGRect& bounds)
3395 return WebCore::FloatSize(webView->_overridesMinimumLayoutSize ? webView->_minimumLayoutSizeOverride : bounds.size);
3398 static WebCore::FloatSize activeMaximumUnobscuredSize(WKWebView *webView, const CGRect& bounds)
3400 return WebCore::FloatSize(webView->_overridesMaximumUnobscuredSize ? webView->_maximumUnobscuredSizeOverride : bounds.size);
3403 static int32_t activeOrientation(WKWebView *webView)
3405 return webView->_overridesInterfaceOrientation ? deviceOrientationForUIInterfaceOrientation(webView->_interfaceOrientationOverride) : webView->_page->deviceOrientation();
3408 - (void (^)(void))_retainActiveFocusedState
3410 ++_activeFocusedStateRetainCount;
3412 // FIXME: Use something like CompletionHandlerCallChecker to ensure that the returned block is called before it's released.
3414 --_activeFocusedStateRetainCount;
3415 } copy] autorelease];
3418 - (void)_becomeFirstResponderWithSelectionMovingForward:(BOOL)selectingForward completionHandler:(void (^)(BOOL didBecomeFirstResponder))completionHandler
3420 typeof(completionHandler) completionHandlerCopy = nil;
3421 if (completionHandler)
3422 completionHandlerCopy = Block_copy(completionHandler);
3424 [_contentView _becomeFirstResponderWithSelectionMovingForward:selectingForward completionHandler:[completionHandlerCopy](BOOL didBecomeFirstResponder) {
3425 if (!completionHandlerCopy)
3428 completionHandlerCopy(didBecomeFirstResponder);
3429 Block_release(completionHandlerCopy);
3433 - (id)_snapshotLayerContentsForBackForwardListItem:(WKBackForwardListItem *)item
3435 if (_page->backForwardList().currentItem() == &item._item)
3436 _page->recordNavigationSnapshot(*_page->backForwardList().currentItem());
3438 if (auto* viewSnapshot = item._item.snapshot())
3439 return viewSnapshot->asLayerContents();
3444 - (NSArray *)_dataDetectionResults
3446 return [_contentView _dataDetectionResults];
3450 - (void)_didRelaunchProcess
3453 CGRect bounds = self.bounds;
3454 WebCore::FloatSize minimalLayoutSize = activeMinimumLayoutSize(self, bounds);
3455 _page->setViewportConfigurationMinimumLayoutSize(minimalLayoutSize);
3456 _page->setMaximumUnobscuredSize(activeMaximumUnobscuredSize(self, bounds));
3460 - (NSData *)_sessionStateData
3462 WebKit::SessionState sessionState = _page->sessionState();
3464 // FIXME: This should not use the legacy session state encoder.
3465 return [wrapper(*WebKit::encodeLegacySessionState(sessionState).leakRef()) autorelease];
3468 - (_WKSessionState *)_sessionState
3470 return adoptNS([[_WKSessionState alloc] _initWithSessionState:_page->sessionState()]).autorelease();
3473 - (_WKSessionState *)_sessionStateWithFilter:(BOOL (^)(WKBackForwardListItem *item))filter
3475 WebKit::SessionState sessionState = _page->sessionState([filter](WebKit::WebBackForwardListItem& item) {
3479 return (bool)filter(wrapper(item));
3482 return adoptNS([[_WKSessionState alloc] _initWithSessionState:sessionState]).autorelease();
3485 - (void)_restoreFromSessionStateData:(NSData *)sessionStateData
3487 // FIXME: This should not use the legacy session state decoder.
3488 WebKit::SessionState sessionState;
3489 if (!WebKit::decodeLegacySessionState(static_cast<const uint8_t*>(sessionStateData.bytes), sessionStateData.length, sessionState))
3492 _page->restoreFromSessionState(WTFMove(sessionState), true);
3495 - (WKNavigation *)_restoreSessionState:(_WKSessionState *)sessionState andNavigate:(BOOL)navigate
3497 auto navigation = _page->restoreFromSessionState(sessionState->_sessionState, navigate);
3501 return [wrapper(*navigation.leakRef()) autorelease];
3509 - (BOOL)_allowsRemoteInspection
3511 #if ENABLE(REMOTE_INSPECTOR)
3512 return _page->allowsRemoteInspection();
3518 - (void)_setAllowsRemoteInspection:(BOOL)allow
3520 #if ENABLE(REMOTE_INSPECTOR)
3521 _page->setAllowsRemoteInspection(allow);
3525 - (NSString *)_remoteInspectionNameOverride
3527 #if ENABLE(REMOTE_INSPECTOR)
3528 return _page->remoteInspectionNameOverride();
3534 - (void)_setRemoteInspectionNameOverride:(NSString *)name
3536 #if ENABLE(REMOTE_INSPECTOR)
3537 _page->setRemoteInspectionNameOverride(name);
3541 - (BOOL)_addsVisitedLinks
3543 return _page->addsVisitedLinks();
3546 - (void)_setAddsVisitedLinks:(BOOL)addsVisitedLinks
3548 _page->setAddsVisitedLinks(addsVisitedLinks);
3551 - (BOOL)_networkRequestsInProgress
3553 return _page->pageLoadState().networkRequestsInProgress();