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 [self _updateContentRectsWithState:isStableState];
2077 static bool scrollViewCanScroll(UIScrollView *scrollView)
2082 UIEdgeInsets contentInset = scrollView.contentInset;
2083 CGSize contentSize = scrollView.contentSize;
2084 CGSize boundsSize = scrollView.bounds.size;
2086 return (contentSize.width + contentInset.left + contentInset.right) > boundsSize.width
2087 || (contentSize.height + contentInset.top + contentInset.bottom) > boundsSize.height;
2090 - (void)_updateContentRectsWithState:(BOOL)inStableState
2092 if (![self usesStandardContentView]) {
2093 [_customContentView web_computedContentInsetDidChange];
2097 if (_delayUpdateVisibleContentRects) {
2098 _hadDelayedUpdateVisibleContentRects = YES;
2102 if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing
2103 || _needsResetViewStateAfterCommitLoadForMainFrame
2104 || [_scrollView isZoomBouncing]
2105 || _currentlyAdjustingScrollViewInsetsForKeyboard)
2108 CGRect fullViewRect = self.bounds;
2109 CGRect visibleRectInContentCoordinates = [self _visibleContentRect];
2111 UIEdgeInsets computedContentInsetUnadjustedForKeyboard = [self _computedContentInset];
2112 if (!_haveSetObscuredInsets)
2113 computedContentInsetUnadjustedForKeyboard.bottom -= _totalScrollViewBottomInsetAdjustmentForKeyboard;
2115 CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, computedContentInsetUnadjustedForKeyboard);
2116 CGRect unobscuredRectInContentCoordinates = _frozenUnobscuredContentRect ? _frozenUnobscuredContentRect.value() : [self convertRect:unobscuredRect toView:_contentView.get()];
2118 CGFloat scaleFactor = contentZoomScale(self);
2120 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2121 if (inStableState) {
2122 WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2123 if (coordinator && coordinator->hasActiveSnapPoint()) {
2124 CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, computedContentInsetUnadjustedForKeyboard);
2126 CGPoint currentPoint = [_scrollView contentOffset];
2127 CGPoint activePoint = coordinator->nearestActiveContentInsetAdjustedSnapPoint(unobscuredRect.origin.y, currentPoint);
2129 if (!CGPointEqualToPoint(activePoint, currentPoint)) {
2130 RetainPtr<WKScrollView> strongScrollView = _scrollView;
2131 dispatch_async(dispatch_get_main_queue(), [strongScrollView, activePoint] {
2132 [strongScrollView setContentOffset:activePoint animated:NO];
2139 [_contentView didUpdateVisibleRect:visibleRectInContentCoordinates
2140 unobscuredRect:unobscuredRectInContentCoordinates
2141 unobscuredRectInScrollViewCoordinates:unobscuredRect
2142 obscuredInset:CGSizeMake(_obscuredInsets.left, _obscuredInsets.top)
2143 scale:scaleFactor minimumScale:[_scrollView minimumZoomScale]
2144 inStableState:inStableState
2145 isChangingObscuredInsetsInteractively:_isChangingObscuredInsetsInteractively
2146 enclosedInScrollableAncestorView:scrollViewCanScroll([self _scroller])];
2149 - (void)_didFinishLoadForMainFrame
2151 if (_gestureController)
2152 _gestureController->didFinishLoadForMainFrame();
2155 - (void)_didFailLoadForMainFrame
2157 if (_gestureController)
2158 _gestureController->didFailLoadForMainFrame();
2161 - (void)_didSameDocumentNavigationForMainFrame:(WebKit::SameDocumentNavigationType)navigationType
2163 [_customContentView web_didSameDocumentNavigation:toAPI(navigationType)];
2165 if (_gestureController)
2166 _gestureController->didSameDocumentNavigationForMainFrame(navigationType);
2169 - (void)_keyboardChangedWithInfo:(NSDictionary *)keyboardInfo adjustScrollView:(BOOL)adjustScrollView
2171 NSValue *endFrameValue = [keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
2175 // The keyboard rect is always in screen coordinates. In the view services case the window does not
2176 // have the interface orientation rotation transformation; its host does. So, it makes no sense to
2177 // clip the keyboard rect against its screen.
2178 if ([[self window] _isHostedInAnotherProcess])
2179 _inputViewBounds = [self.window convertRect:[endFrameValue CGRectValue] fromWindow:nil];
2181 _inputViewBounds = [self.window convertRect:CGRectIntersection([endFrameValue CGRectValue], self.window.screen.bounds) fromWindow:nil];
2183 if (adjustScrollView) {
2184 CGFloat bottomInsetBeforeAdjustment = [_scrollView contentInset].bottom;
2185 SetForScope<BOOL> insetAdjustmentGuard(_currentlyAdjustingScrollViewInsetsForKeyboard, YES);
2186 [_scrollView _adjustForAutomaticKeyboardInfo:keyboardInfo animated:YES lastAdjustment:&_lastAdjustmentForScroller];
2187 CGFloat bottomInsetAfterAdjustment = [_scrollView contentInset].bottom;
2188 if (bottomInsetBeforeAdjustment != bottomInsetAfterAdjustment)
2189 _totalScrollViewBottomInsetAdjustmentForKeyboard += bottomInsetAfterAdjustment - bottomInsetBeforeAdjustment;
2192 [self _updateVisibleContentRects];
2195 - (BOOL)_shouldUpdateKeyboardWithInfo:(NSDictionary *)keyboardInfo
2197 if ([_contentView isAssistingNode])
2200 NSNumber *isLocalKeyboard = [keyboardInfo valueForKey:UIKeyboardIsLocalUserInfoKey];
2201 return isLocalKeyboard && !isLocalKeyboard.boolValue;
2204 - (void)_keyboardWillChangeFrame:(NSNotification *)notification
2206 if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
2207 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
2210 - (void)_keyboardDidChangeFrame:(NSNotification *)notification
2212 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:NO];
2215 - (void)_keyboardWillShow:(NSNotification *)notification
2217 if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
2218 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
2220 _page->setIsKeyboardAnimatingIn(true);
2223 - (void)_keyboardDidShow:(NSNotification *)notification
2225 _page->setIsKeyboardAnimatingIn(false);
2228 - (void)_keyboardWillHide:(NSNotification *)notification
2230 // Ignore keyboard will hide notifications sent during rotation. They're just there for
2231 // backwards compatibility reasons and processing the will hide notification would
2232 // temporarily screw up the the unobscured view area.
2233 if ([[UIPeripheralHost sharedInstance] rotationState])
2236 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
2239 - (void)_windowDidRotate:(NSNotification *)notification
2241 if (!_overridesInterfaceOrientation)
2242 _page->setDeviceOrientation(deviceOrientation());
2245 - (void)_contentSizeCategoryDidChange:(NSNotification *)notification
2247 _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
2250 - (NSString *)_contentSizeCategory
2252 return [[UIApplication sharedApplication] preferredContentSizeCategory];
2255 - (void)_accessibilitySettingsDidChange:(NSNotification *)notification
2257 _page->accessibilitySettingsDidChange();
2260 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
2262 if (_allowsBackForwardNavigationGestures == allowsBackForwardNavigationGestures)
2265 _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
2267 if (allowsBackForwardNavigationGestures) {
2268 if (!_gestureController) {
2269 _gestureController = std::make_unique<WebKit::ViewGestureController>(*_page);
2270 _gestureController->installSwipeHandler(self, [self scrollView]);
2271 if (WKWebView *alternateWebView = [_configuration _alternateWebViewForNavigationGestures])
2272 _gestureController->setAlternateBackForwardListSourcePage(alternateWebView->_page.get());
2275 _gestureController = nullptr;
2277 _page->setShouldRecordNavigationSnapshots(allowsBackForwardNavigationGestures);
2280 - (BOOL)allowsBackForwardNavigationGestures
2282 return _allowsBackForwardNavigationGestures;
2285 - (void)_navigationGestureDidBegin
2287 // During a back/forward swipe, there's a view interposed between this view and the content view that has
2288 // an offset and animation on it, which results in computing incorrect rectangles. Work around by using
2289 // frozen rects during swipes.
2290 CGRect fullViewRect = self.bounds;
2291 CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, [self _computedContentInset]);
2293 _frozenVisibleContentRect = [self convertRect:fullViewRect toView:_contentView.get()];
2294 _frozenUnobscuredContentRect = [self convertRect:unobscuredRect toView:_contentView.get()];
2296 LOG_WITH_STREAM(VisibleRects, stream << "_navigationGestureDidBegin: freezing visibleContentRect " << _frozenVisibleContentRect.value() << " UnobscuredContentRect " << _frozenUnobscuredContentRect.value());
2299 - (void)_navigationGestureDidEnd
2301 _frozenVisibleContentRect = Nullopt;
2302 _frozenUnobscuredContentRect = Nullopt;
2305 #endif // PLATFORM(IOS)
2307 #pragma mark OS X-specific methods
2311 - (BOOL)acceptsFirstResponder
2313 return _impl->acceptsFirstResponder();
2316 - (BOOL)becomeFirstResponder
2318 return _impl->becomeFirstResponder();
2321 - (BOOL)resignFirstResponder
2323 return _impl->resignFirstResponder();
2326 - (void)viewWillStartLiveResize
2328 _impl->viewWillStartLiveResize();
2331 - (void)viewDidEndLiveResize
2333 _impl->viewDidEndLiveResize();
2341 - (NSSize)intrinsicContentSize
2343 return NSSizeFromCGSize(_impl->intrinsicContentSize());
2346 - (void)prepareContentInRect:(NSRect)rect
2348 _impl->prepareContentInRect(NSRectToCGRect(rect));
2351 - (void)setFrameSize:(NSSize)size
2353 [super setFrameSize:size];
2354 _impl->setFrameSize(NSSizeToCGSize(size));
2359 _impl->renewGState();
2360 [super renewGState];
2363 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _impl->executeEditCommandForSelector(_cmd); }
2365 WEBCORE_COMMAND(alignCenter)
2366 WEBCORE_COMMAND(alignJustified)
2367 WEBCORE_COMMAND(alignLeft)
2368 WEBCORE_COMMAND(alignRight)
2369 WEBCORE_COMMAND(copy)
2370 WEBCORE_COMMAND(cut)
2371 WEBCORE_COMMAND(delete)
2372 WEBCORE_COMMAND(deleteBackward)
2373 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
2374 WEBCORE_COMMAND(deleteForward)
2375 WEBCORE_COMMAND(deleteToBeginningOfLine)
2376 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
2377 WEBCORE_COMMAND(deleteToEndOfLine)
2378 WEBCORE_COMMAND(deleteToEndOfParagraph)
2379 WEBCORE_COMMAND(deleteToMark)
2380 WEBCORE_COMMAND(deleteWordBackward)
2381 WEBCORE_COMMAND(deleteWordForward)
2382 WEBCORE_COMMAND(ignoreSpelling)
2383 WEBCORE_COMMAND(indent)
2384 WEBCORE_COMMAND(insertBacktab)
2385 WEBCORE_COMMAND(insertLineBreak)
2386 WEBCORE_COMMAND(insertNewline)
2387 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
2388 WEBCORE_COMMAND(insertParagraphSeparator)
2389 WEBCORE_COMMAND(insertTab)
2390 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
2391 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
2392 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
2393 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
2394 WEBCORE_COMMAND(moveBackward)
2395 WEBCORE_COMMAND(moveBackwardAndModifySelection)
2396 WEBCORE_COMMAND(moveDown)
2397 WEBCORE_COMMAND(moveDownAndModifySelection)
2398 WEBCORE_COMMAND(moveForward)
2399 WEBCORE_COMMAND(moveForwardAndModifySelection)
2400 WEBCORE_COMMAND(moveLeft)
2401 WEBCORE_COMMAND(moveLeftAndModifySelection)
2402 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
2403 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
2404 WEBCORE_COMMAND(moveRight)
2405 WEBCORE_COMMAND(moveRightAndModifySelection)
2406 WEBCORE_COMMAND(moveToBeginningOfDocument)
2407 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
2408 WEBCORE_COMMAND(moveToBeginningOfLine)
2409 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
2410 WEBCORE_COMMAND(moveToBeginningOfParagraph)
2411 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
2412 WEBCORE_COMMAND(moveToBeginningOfSentence)
2413 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
2414 WEBCORE_COMMAND(moveToEndOfDocument)
2415 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
2416 WEBCORE_COMMAND(moveToEndOfLine)
2417 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
2418 WEBCORE_COMMAND(moveToEndOfParagraph)
2419 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
2420 WEBCORE_COMMAND(moveToEndOfSentence)
2421 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
2422 WEBCORE_COMMAND(moveToLeftEndOfLine)
2423 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
2424 WEBCORE_COMMAND(moveToRightEndOfLine)
2425 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
2426 WEBCORE_COMMAND(moveUp)
2427 WEBCORE_COMMAND(moveUpAndModifySelection)
2428 WEBCORE_COMMAND(moveWordBackward)
2429 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
2430 WEBCORE_COMMAND(moveWordForward)
2431 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
2432 WEBCORE_COMMAND(moveWordLeft)
2433 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
2434 WEBCORE_COMMAND(moveWordRight)
2435 WEBCORE_COMMAND(moveWordRightAndModifySelection)
2436 WEBCORE_COMMAND(outdent)
2437 WEBCORE_COMMAND(pageDown)
2438 WEBCORE_COMMAND(pageDownAndModifySelection)
2439 WEBCORE_COMMAND(pageUp)
2440 WEBCORE_COMMAND(pageUpAndModifySelection)
2441 WEBCORE_COMMAND(paste)
2442 WEBCORE_COMMAND(pasteAsPlainText)
2443 WEBCORE_COMMAND(scrollPageDown)
2444 WEBCORE_COMMAND(scrollPageUp)
2445 WEBCORE_COMMAND(scrollLineDown)
2446 WEBCORE_COMMAND(scrollLineUp)
2447 WEBCORE_COMMAND(scrollToBeginningOfDocument)
2448 WEBCORE_COMMAND(scrollToEndOfDocument)
2449 WEBCORE_COMMAND(selectAll)
2450 WEBCORE_COMMAND(selectLine)
2451 WEBCORE_COMMAND(selectParagraph)
2452 WEBCORE_COMMAND(selectSentence)
2453 WEBCORE_COMMAND(selectToMark)
2454 WEBCORE_COMMAND(selectWord)
2455 WEBCORE_COMMAND(setMark)
2456 WEBCORE_COMMAND(subscript)
2457 WEBCORE_COMMAND(superscript)
2458 WEBCORE_COMMAND(swapWithMark)
2459 WEBCORE_COMMAND(takeFindStringFromSelection)
2460 WEBCORE_COMMAND(transpose)
2461 WEBCORE_COMMAND(underline)
2462 WEBCORE_COMMAND(unscript)
2463 WEBCORE_COMMAND(yank)
2464 WEBCORE_COMMAND(yankAndSelect)
2466 #undef WEBCORE_COMMAND
2468 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
2470 return _impl->writeSelectionToPasteboard(pasteboard, types);
2473 - (void)centerSelectionInVisibleArea:(id)sender
2475 _impl->centerSelectionInVisibleArea();
2478 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
2480 return _impl->validRequestorForSendAndReturnTypes(sendType, returnType);
2483 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
2485 return _impl->readSelectionFromPasteboard(pasteboard);
2488 - (void)changeFont:(id)sender
2490 _impl->changeFontFromFontPanel();
2493 - (IBAction)startSpeaking:(id)sender
2495 _impl->startSpeaking();
2498 - (IBAction)stopSpeaking:(id)sender
2500 _impl->stopSpeaking(sender);
2503 - (IBAction)showGuessPanel:(id)sender
2505 _impl->showGuessPanel(sender);
2508 - (IBAction)checkSpelling:(id)sender
2510 _impl->checkSpelling();
2513 - (void)changeSpelling:(id)sender
2515 _impl->changeSpelling(sender);
2518 - (IBAction)toggleContinuousSpellChecking:(id)sender
2520 _impl->toggleContinuousSpellChecking();
2523 - (BOOL)isGrammarCheckingEnabled
2525 return _impl->isGrammarCheckingEnabled();
2528 - (void)setGrammarCheckingEnabled:(BOOL)flag
2530 _impl->setGrammarCheckingEnabled(flag);
2533 - (IBAction)toggleGrammarChecking:(id)sender
2535 _impl->toggleGrammarChecking();
2538 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
2540 _impl->toggleAutomaticSpellingCorrection();
2543 - (void)orderFrontSubstitutionsPanel:(id)sender
2545 _impl->orderFrontSubstitutionsPanel(sender);
2548 - (IBAction)toggleSmartInsertDelete:(id)sender
2550 _impl->toggleSmartInsertDelete();
2553 - (BOOL)isAutomaticQuoteSubstitutionEnabled
2555 return _impl->isAutomaticQuoteSubstitutionEnabled();
2558 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
2560 _impl->setAutomaticQuoteSubstitutionEnabled(flag);
2563 - (void)toggleAutomaticQuoteSubstitution:(id)sender
2565 _impl->toggleAutomaticQuoteSubstitution();
2568 - (BOOL)isAutomaticDashSubstitutionEnabled
2570 return _impl->isAutomaticDashSubstitutionEnabled();
2573 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
2575 _impl->setAutomaticDashSubstitutionEnabled(flag);
2578 - (void)toggleAutomaticDashSubstitution:(id)sender
2580 _impl->toggleAutomaticDashSubstitution();
2583 - (BOOL)isAutomaticLinkDetectionEnabled
2585 return _impl->isAutomaticLinkDetectionEnabled();
2588 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
2590 _impl->setAutomaticLinkDetectionEnabled(flag);
2593 - (void)toggleAutomaticLinkDetection:(id)sender
2595 _impl->toggleAutomaticLinkDetection();
2598 - (BOOL)isAutomaticTextReplacementEnabled
2600 return _impl->isAutomaticTextReplacementEnabled();
2603 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
2605 _impl->setAutomaticTextReplacementEnabled(flag);
2608 - (void)toggleAutomaticTextReplacement:(id)sender
2610 _impl->toggleAutomaticTextReplacement();
2613 - (void)uppercaseWord:(id)sender
2615 _impl->uppercaseWord();
2618 - (void)lowercaseWord:(id)sender
2620 _impl->lowercaseWord();
2623 - (void)capitalizeWord:(id)sender
2625 _impl->capitalizeWord();
2628 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
2630 return _impl->wantsKeyDownForEvent(event);
2633 - (void)scrollWheel:(NSEvent *)event
2635 _impl->scrollWheel(event);
2638 - (void)swipeWithEvent:(NSEvent *)event
2640 _impl->swipeWithEvent(event);
2643 - (void)mouseMoved:(NSEvent *)event
2645 _impl->mouseMoved(event);
2648 - (void)mouseDown:(NSEvent *)event
2650 _impl->mouseDown(event);
2653 - (void)mouseUp:(NSEvent *)event
2655 _impl->mouseUp(event);
2658 - (void)mouseDragged:(NSEvent *)event
2660 _impl->mouseDragged(event);
2663 - (void)mouseEntered:(NSEvent *)event
2665 _impl->mouseEntered(event);
2668 - (void)mouseExited:(NSEvent *)event
2670 _impl->mouseExited(event);
2673 - (void)otherMouseDown:(NSEvent *)event
2675 _impl->otherMouseDown(event);
2678 - (void)otherMouseDragged:(NSEvent *)event
2680 _impl->otherMouseDragged(event);
2683 - (void)otherMouseUp:(NSEvent *)event
2685 _impl->otherMouseUp(event);
2688 - (void)rightMouseDown:(NSEvent *)event
2690 _impl->rightMouseDown(event);
2693 - (void)rightMouseDragged:(NSEvent *)event
2695 _impl->rightMouseDragged(event);
2698 - (void)rightMouseUp:(NSEvent *)event
2700 _impl->rightMouseUp(event);
2703 - (void)pressureChangeWithEvent:(NSEvent *)event
2705 _impl->pressureChangeWithEvent(event);
2708 - (BOOL)acceptsFirstMouse:(NSEvent *)event
2710 return _impl->acceptsFirstMouse(event);
2713 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
2715 return _impl->shouldDelayWindowOrderingForEvent(event);
2718 - (void)doCommandBySelector:(SEL)selector
2720 _impl->doCommandBySelector(selector);
2723 - (void)insertText:(id)string
2725 _impl->insertText(string);
2728 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
2730 _impl->insertText(string, replacementRange);
2733 - (NSTextInputContext *)inputContext
2737 return _impl->inputContext();
2740 - (BOOL)performKeyEquivalent:(NSEvent *)event
2742 return _impl->performKeyEquivalent(event);
2745 - (void)keyUp:(NSEvent *)theEvent
2747 _impl->keyUp(theEvent);
2750 - (void)keyDown:(NSEvent *)theEvent
2752 _impl->keyDown(theEvent);
2755 - (void)flagsChanged:(NSEvent *)theEvent
2757 _impl->flagsChanged(theEvent);
2760 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelectedRange replacementRange:(NSRange)replacementRange
2762 _impl->setMarkedText(string, newSelectedRange, replacementRange);
2767 _impl->unmarkText();
2770 - (NSRange)selectedRange
2772 return _impl->selectedRange();
2775 - (BOOL)hasMarkedText
2777 return _impl->hasMarkedText();
2780 - (NSRange)markedRange
2782 return _impl->markedRange();
2785 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange
2787 return _impl->attributedSubstringForProposedRange(nsRange, actualRange);
2790 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
2792 return _impl->characterIndexForPoint(thePoint);
2795 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
2797 return _impl->firstRectForCharacterRange(theRange, actualRange);
2800 - (void)selectedRangeWithCompletionHandler:(void(^)(NSRange selectedRange))completionHandlerPtr
2802 _impl->selectedRangeWithCompletionHandler(completionHandlerPtr);
2805 - (void)markedRangeWithCompletionHandler:(void(^)(NSRange markedRange))completionHandlerPtr
2807 _impl->markedRangeWithCompletionHandler(completionHandlerPtr);
2810 - (void)hasMarkedTextWithCompletionHandler:(void(^)(BOOL hasMarkedText))completionHandlerPtr
2812 _impl->hasMarkedTextWithCompletionHandler(completionHandlerPtr);
2815 - (void)attributedSubstringForProposedRange:(NSRange)nsRange completionHandler:(void(^)(NSAttributedString *attrString, NSRange actualRange))completionHandlerPtr
2817 _impl->attributedSubstringForProposedRange(nsRange, completionHandlerPtr);
2820 - (void)firstRectForCharacterRange:(NSRange)theRange completionHandler:(void(^)(NSRect firstRect, NSRange actualRange))completionHandlerPtr
2822 _impl->firstRectForCharacterRange(theRange, completionHandlerPtr);
2825 - (void)characterIndexForPoint:(NSPoint)thePoint completionHandler:(void(^)(NSUInteger))completionHandlerPtr
2827 _impl->characterIndexForPoint(thePoint, completionHandlerPtr);
2830 - (NSArray *)validAttributesForMarkedText
2832 return _impl->validAttributesForMarkedText();
2835 #if ENABLE(DRAG_SUPPORT)
2836 - (void)draggedImage:(NSImage *)image endedAt:(NSPoint)endPoint operation:(NSDragOperation)operation
2838 _impl->draggedImage(image, NSPointToCGPoint(endPoint), operation);
2841 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
2843 return _impl->draggingEntered(draggingInfo);
2846 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
2848 return _impl->draggingUpdated(draggingInfo);
2851 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
2853 _impl->draggingExited(draggingInfo);
2856 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
2858 return _impl->prepareForDragOperation(draggingInfo);
2861 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
2863 return _impl->performDragOperation(draggingInfo);
2866 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
2868 return _impl->hitTestForDragTypes(NSPointToCGPoint(*point), types);
2870 #endif // ENABLE(DRAG_SUPPORT)
2872 - (BOOL)_windowResizeMouseLocationIsInVisibleScrollerThumb:(NSPoint)point
2874 return _impl->windowResizeMouseLocationIsInVisibleScrollerThumb(NSPointToCGPoint(point));
2877 - (void)viewWillMoveToWindow:(NSWindow *)window
2879 _impl->viewWillMoveToWindow(window);
2882 - (void)viewDidMoveToWindow
2884 _impl->viewDidMoveToWindow();
2887 - (void)drawRect:(NSRect)rect
2889 _impl->drawRect(NSRectToCGRect(rect));
2894 return _impl->isOpaque();
2897 - (BOOL)mouseDownCanMoveWindow
2899 return WebKit::WebViewImpl::mouseDownCanMoveWindow();
2904 _impl->viewDidHide();
2907 - (void)viewDidUnhide
2909 _impl->viewDidUnhide();
2912 - (void)viewDidChangeBackingProperties
2914 _impl->viewDidChangeBackingProperties();
2917 - (void)_activeSpaceDidChange:(NSNotification *)notification
2919 _impl->activeSpaceDidChange();
2922 - (id)accessibilityFocusedUIElement
2924 return _impl->accessibilityFocusedUIElement();
2927 - (BOOL)accessibilityIsIgnored
2929 return _impl->accessibilityIsIgnored();
2932 - (id)accessibilityHitTest:(NSPoint)point
2934 return _impl->accessibilityHitTest(NSPointToCGPoint(point));
2937 - (id)accessibilityAttributeValue:(NSString *)attribute
2939 return _impl->accessibilityAttributeValue(attribute);
2942 - (NSView *)hitTest:(NSPoint)point
2945 return [super hitTest:point];
2946 return _impl->hitTest(NSPointToCGPoint(point));
2949 - (NSInteger)conversationIdentifier
2951 return (NSInteger)self;
2954 - (void)quickLookWithEvent:(NSEvent *)event
2956 _impl->quickLookWithEvent(event);
2959 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
2961 return _impl->addTrackingRect(NSRectToCGRect(rect), owner, data, assumeInside);
2964 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
2966 return _impl->addTrackingRectWithTrackingNum(NSRectToCGRect(rect), owner, data, assumeInside, tag);
2969 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
2971 CGRect *cgRects = (CGRect *)calloc(1, sizeof(CGRect));
2972 for (int i = 0; i < count; i++)
2973 cgRects[i] = NSRectToCGRect(rects[i]);
2974 _impl->addTrackingRectsWithTrackingNums(cgRects, owner, userDataList, assumeInsideList, trackingNums, count);
2978 - (void)removeTrackingRect:(NSTrackingRectTag)tag
2982 _impl->removeTrackingRect(tag);
2985 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
2989 _impl->removeTrackingRects(tags, count);
2992 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
2994 return _impl->stringForToolTip(tag);
2997 - (void)pasteboardChangedOwner:(NSPasteboard *)pasteboard
2999 _impl->pasteboardChangedOwner(pasteboard);
3002 - (void)pasteboard:(NSPasteboard *)pasteboard provideDataForType:(NSString *)type
3004 _impl->provideDataForPasteboard(pasteboard, type);
3007 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
3009 return _impl->namesOfPromisedFilesDroppedAtDestination(dropDestination);
3012 - (BOOL)wantsUpdateLayer
3014 return WebKit::WebViewImpl::wantsUpdateLayer();
3019 _impl->updateLayer();
3022 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
3024 _impl->setAllowsBackForwardNavigationGestures(allowsBackForwardNavigationGestures);
3027 - (BOOL)allowsBackForwardNavigationGestures
3029 return _impl->allowsBackForwardNavigationGestures();
3032 - (void)smartMagnifyWithEvent:(NSEvent *)event
3034 _impl->smartMagnifyWithEvent(event);
3037 - (void)setMagnification:(double)magnification centeredAtPoint:(NSPoint)point
3039 _impl->setMagnification(magnification, NSPointToCGPoint(point));
3042 - (void)setMagnification:(double)magnification
3044 _impl->setMagnification(magnification);
3047 - (double)magnification
3049 return _impl->magnification();
3052 - (void)setAllowsMagnification:(BOOL)allowsMagnification
3054 _impl->setAllowsMagnification(allowsMagnification);
3057 - (BOOL)allowsMagnification
3059 return _impl->allowsMagnification();
3062 - (void)magnifyWithEvent:(NSEvent *)event
3064 _impl->magnifyWithEvent(event);
3067 #if ENABLE(MAC_GESTURE_EVENTS)
3068 - (void)rotateWithEvent:(NSEvent *)event
3070 _impl->rotateWithEvent(event);
3074 - (WKTextFinderClient *)_ensureTextFinderClient
3076 if (!_textFinderClient)
3077 _textFinderClient = adoptNS([[WKTextFinderClient alloc] initWithPage:*_page view:self]);
3078 return _textFinderClient.get();
3081 - (void)findMatchesForString:(NSString *)targetString relativeToMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)relativeMatch findOptions:(NSTextFinderAsynchronousDocumentFindOptions)findOptions maxResults:(NSUInteger)maxResults resultCollector:(void (^)(NSArray *matches, BOOL didWrap))resultCollector
3083 [[self _ensureTextFinderClient] findMatchesForString:targetString relativeToMatch:relativeMatch findOptions:findOptions maxResults:maxResults resultCollector:resultCollector];
3086 - (NSView *)documentContainerView
3091 - (void)getSelectedText:(void (^)(NSString *selectedTextString))completionHandler
3093 [[self _ensureTextFinderClient] getSelectedText:completionHandler];
3096 - (void)selectFindMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)findMatch completionHandler:(void (^)(void))completionHandler
3098 [[self _ensureTextFinderClient] selectFindMatch:findMatch completionHandler:completionHandler];
3101 - (NSTextInputContext *)_web_superInputContext
3103 return [super inputContext];
3106 - (void)_web_superQuickLookWithEvent:(NSEvent *)event
3108 [super quickLookWithEvent:event];
3111 - (void)_web_superSwipeWithEvent:(NSEvent *)event
3113 [super swipeWithEvent:event];
3116 - (void)_web_superMagnifyWithEvent:(NSEvent *)event
3118 [super magnifyWithEvent:event];
3121 - (void)_web_superSmartMagnifyWithEvent:(NSEvent *)event
3123 [super smartMagnifyWithEvent:event];
3126 - (void)_web_superRemoveTrackingRect:(NSTrackingRectTag)tag
3128 [super removeTrackingRect:tag];
3131 - (id)_web_superAccessibilityAttributeValue:(NSString *)attribute
3133 #pragma clang diagnostic push
3134 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
3135 return [super accessibilityAttributeValue:attribute];
3136 #pragma clang diagnostic pop
3139 - (void)_web_superDoCommandBySelector:(SEL)selector
3141 [super doCommandBySelector:selector];
3144 - (BOOL)_web_superPerformKeyEquivalent:(NSEvent *)event
3146 return [super performKeyEquivalent:event];
3149 - (void)_web_superKeyDown:(NSEvent *)event
3151 [super keyDown:event];
3154 - (NSView *)_web_superHitTest:(NSPoint)point
3156 return [super hitTest:point];
3159 - (id)_web_immediateActionAnimationControllerForHitTestResultInternal:(API::HitTestResult*)hitTestResult withType:(uint32_t)type userData:(API::Object*)userData
3161 id<NSSecureCoding> data = userData ? static_cast<id<NSSecureCoding>>(userData->wrapper()) : nil;
3162 return [self _immediateActionAnimationControllerForHitTestResult:wrapper(*hitTestResult) withType:(_WKImmediateActionType)type userData:data];
3165 // We don't expose these various bits of SPI like WKView does,
3166 // so have these internal methods just do the work (or do nothing):
3167 - (void)_web_prepareForImmediateActionAnimation
3171 - (void)_web_cancelImmediateActionAnimation
3175 - (void)_web_completeImmediateActionAnimation
3179 - (void)_web_didChangeContentSize:(NSSize)newSize
3183 - (void)_web_dismissContentRelativeChildWindows
3185 _impl->dismissContentRelativeChildWindowsFromViewOnly();
3188 - (void)_web_dismissContentRelativeChildWindowsWithAnimation:(BOOL)withAnimation
3190 _impl->dismissContentRelativeChildWindowsWithAnimationFromViewOnly(withAnimation);
3193 - (void)_web_gestureEventWasNotHandledByWebCore:(NSEvent *)event
3195 _impl->gestureEventWasNotHandledByWebCoreFromViewOnly(event);
3198 #endif // PLATFORM(MAC)
3204 - (NSTouchBar *)makeTouchBar
3206 return _impl->makeTouchBar();
3209 - (NSCandidateListTouchBarItem *)candidateListTouchBarItem
3211 return _impl->candidateListTouchBarItem();
3214 - (void)_web_didAddMediaControlsManager:(id)controlsManager
3216 [self _addMediaPlaybackControlsView:controlsManager];
3219 - (void)_web_didRemoveMediaControlsManager
3221 [self _removeMediaPlaybackControlsView];
3224 - (void)_interactWithMediaControlsForTesting
3226 [self _setWantsMediaPlaybackControlsView:YES];
3227 [self makeTouchBar];
3230 #endif // HAVE(TOUCH_BAR)
3234 @implementation WKWebView (WKPrivate)
3238 return _page->isEditable();
3241 - (void)_setEditable:(BOOL)editable
3243 _page->setEditable(editable);
3245 _impl->startObservingFontPanel();
3249 - (_WKRemoteObjectRegistry *)_remoteObjectRegistry
3252 return _impl->remoteObjectRegistry();
3254 if (!_remoteObjectRegistry) {
3255 _remoteObjectRegistry = adoptNS([[_WKRemoteObjectRegistry alloc] _initWithMessageSender:*_page]);
3256 _page->process().processPool().addMessageReceiver(Messages::RemoteObjectRegistry::messageReceiverName(), _page->pageID(), [_remoteObjectRegistry remoteObjectRegistry]);
3259 return _remoteObjectRegistry.get();
3263 - (WKBrowsingContextHandle *)_handle
3265 return [[[WKBrowsingContextHandle alloc] _initWithPageID:_page->pageID()] autorelease];
3268 - (_WKRenderingProgressEvents)_observedRenderingProgressEvents
3270 return _observedRenderingProgressEvents;
3273 - (id <WKHistoryDelegatePrivate>)_historyDelegate
3275 return _navigationState->historyDelegate().autorelease();
3278 - (void)_setHistoryDelegate:(id <WKHistoryDelegatePrivate>)historyDelegate
3280 _page->setHistoryClient(_navigationState->createHistoryClient());
3281 _navigationState->setHistoryDelegate(historyDelegate);
3284 - (NSURL *)_unreachableURL
3286 return [NSURL _web_URLWithWTFString:_page->pageLoadState().unreachableURL()];
3289 - (void)_loadAlternateHTMLString:(NSString *)string baseURL:(NSURL *)baseURL forUnreachableURL:(NSURL *)unreachableURL
3291 _page->loadAlternateHTMLString(string, [baseURL _web_originalDataAsWTFString], [unreachableURL _web_originalDataAsWTFString]);
3294 - (WKNavigation *)_loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL userData:(id)userData
3296 auto navigation = _page->loadData(API::Data::createWithoutCopying(data).ptr(), MIMEType, characterEncodingName, baseURL.absoluteString, WebKit::ObjCObjectGraph::create(userData).ptr());
3300 return [wrapper(*navigation.leakRef()) autorelease];
3303 - (NSArray *)_certificateChain
3305 if (WebKit::WebFrameProxy* mainFrame = _page->mainFrame())
3306 return mainFrame->certificateInfo() ? (NSArray *)mainFrame->certificateInfo()->certificateInfo().certificateChain() : nil;
3311 - (NSURL *)_committedURL
3313 return [NSURL _web_URLWithWTFString:_page->pageLoadState().url()];
3316 - (NSString *)_MIMEType
3318 if (_page->mainFrame())
3319 return _page->mainFrame()->mimeType();
3324 - (NSString *)_userAgent
3326 return _page->userAgent();
3329 - (NSString *)_applicationNameForUserAgent
3331 return _page->applicationNameForUserAgent();
3334 - (void)_setApplicationNameForUserAgent:(NSString *)applicationNameForUserAgent
3336 _page->setApplicationNameForUserAgent(applicationNameForUserAgent);
3339 - (NSString *)_customUserAgent
3341 return self.customUserAgent;
3344 - (void)_setCustomUserAgent:(NSString *)customUserAgent
3346 self.customUserAgent = customUserAgent;
3349 - (void)_setUserContentExtensionsEnabled:(BOOL)userContentExtensionsEnabled
3351 // This is kept for binary compatibility with iOS 9.
3354 - (BOOL)_userContentExtensionsEnabled
3356 // This is kept for binary compatibility with iOS 9.
3360 - (pid_t)_webProcessIdentifier
3362 return _page->isValid() ? _page->processIdentifier() : 0;
3365 - (void)_killWebContentProcess
3367 if (!_page->isValid())
3370 _page->process().terminate();
3373 - (WKNavigation *)_reloadWithoutContentBlockers
3375 const bool reloadFromOrigin = false;
3376 const bool contentBlockersEnabled = false;
3377 auto navigation = _page->reload(reloadFromOrigin, contentBlockersEnabled);
3381 return [wrapper(*navigation.leakRef()) autorelease];
3384 - (void)_killWebContentProcessAndResetState
3386 _page->terminateProcess();
3390 static WebCore::FloatSize activeMinimumLayoutSize(WKWebView *webView, const CGRect& bounds)
3392 return WebCore::FloatSize(webView->_overridesMinimumLayoutSize ? webView->_minimumLayoutSizeOverride : bounds.size);
3395 static WebCore::FloatSize activeMaximumUnobscuredSize(WKWebView *webView, const CGRect& bounds)
3397 return WebCore::FloatSize(webView->_overridesMaximumUnobscuredSize ? webView->_maximumUnobscuredSizeOverride : bounds.size);
3400 static int32_t activeOrientation(WKWebView *webView)
3402 return webView->_overridesInterfaceOrientation ? deviceOrientationForUIInterfaceOrientation(webView->_interfaceOrientationOverride) : webView->_page->deviceOrientation();
3405 - (void (^)(void))_retainActiveFocusedState
3407 ++_activeFocusedStateRetainCount;
3409 // FIXME: Use something like CompletionHandlerCallChecker to ensure that the returned block is called before it's released.
3411 --_activeFocusedStateRetainCount;
3412 } copy] autorelease];
3415 - (void)_becomeFirstResponderWithSelectionMovingForward:(BOOL)selectingForward completionHandler:(void (^)(BOOL didBecomeFirstResponder))completionHandler
3417 typeof(completionHandler) completionHandlerCopy = nil;
3418 if (completionHandler)
3419 completionHandlerCopy = Block_copy(completionHandler);
3421 [_contentView _becomeFirstResponderWithSelectionMovingForward:selectingForward completionHandler:[completionHandlerCopy](BOOL didBecomeFirstResponder) {
3422 if (!completionHandlerCopy)
3425 completionHandlerCopy(didBecomeFirstResponder);
3426 Block_release(completionHandlerCopy);
3430 - (id)_snapshotLayerContentsForBackForwardListItem:(WKBackForwardListItem *)item
3432 if (_page->backForwardList().currentItem() == &item._item)
3433 _page->recordNavigationSnapshot(*_page->backForwardList().currentItem());
3435 if (auto* viewSnapshot = item._item.snapshot())
3436 return viewSnapshot->asLayerContents();
3441 - (NSArray *)_dataDetectionResults
3443 return [_contentView _dataDetectionResults];
3447 - (void)_didRelaunchProcess
3450 CGRect bounds = self.bounds;
3451 WebCore::FloatSize minimalLayoutSize = activeMinimumLayoutSize(self, bounds);
3452 _page->setViewportConfigurationMinimumLayoutSize(minimalLayoutSize);
3453 _page->setMaximumUnobscuredSize(activeMaximumUnobscuredSize(self, bounds));
3457 - (NSData *)_sessionStateData
3459 WebKit::SessionState sessionState = _page->sessionState();
3461 // FIXME: This should not use the legacy session state encoder.
3462 return [wrapper(*WebKit::encodeLegacySessionState(sessionState).leakRef()) autorelease];
3465 - (_WKSessionState *)_sessionState
3467 return adoptNS([[_WKSessionState alloc] _initWithSessionState:_page->sessionState()]).autorelease();
3470 - (_WKSessionState *)_sessionStateWithFilter:(BOOL (^)(WKBackForwardListItem *item))filter
3472 WebKit::SessionState sessionState = _page->sessionState([filter](WebKit::WebBackForwardListItem& item) {
3476 return (bool)filter(wrapper(item));
3479 return adoptNS([[_WKSessionState alloc] _initWithSessionState:sessionState]).autorelease();
3482 - (void)_restoreFromSessionStateData:(NSData *)sessionStateData
3484 // FIXME: This should not use the legacy session state decoder.
3485 WebKit::SessionState sessionState;
3486 if (!WebKit::decodeLegacySessionState(static_cast<const uint8_t*>(sessionStateData.bytes), sessionStateData.length, sessionState))
3489 _page->restoreFromSessionState(WTFMove(sessionState), true);
3492 - (WKNavigation *)_restoreSessionState:(_WKSessionState *)sessionState andNavigate:(BOOL)navigate
3494 auto navigation = _page->restoreFromSessionState(sessionState->_sessionState, navigate);
3498 return [wrapper(*navigation.leakRef()) autorelease];
3506 - (BOOL)_allowsRemoteInspection
3508 #if ENABLE(REMOTE_INSPECTOR)
3509 return _page->allowsRemoteInspection();
3515 - (void)_setAllowsRemoteInspection:(BOOL)allow
3517 #if ENABLE(REMOTE_INSPECTOR)
3518 _page->setAllowsRemoteInspection(allow);
3522 - (NSString *)_remoteInspectionNameOverride
3524 #if ENABLE(REMOTE_INSPECTOR)
3525 return _page->remoteInspectionNameOverride();
3531 - (void)_setRemoteInspectionNameOverride:(NSString *)name
3533 #if ENABLE(REMOTE_INSPECTOR)
3534 _page->setRemoteInspectionNameOverride(name);
3538 - (BOOL)_addsVisitedLinks
3540 return _page->addsVisitedLinks();
3543 - (void)_setAddsVisitedLinks:(BOOL)addsVisitedLinks
3545 _page->setAddsVisitedLinks(addsVisitedLinks);
3548 - (BOOL)_networkRequestsInProgress
3550 return _page->pageLoadState().networkRequestsInProgress();
3553 static inline WebCore::LayoutMilestones layoutMilestones(_WKRenderingProgressEvents events)
3555 WebCore::LayoutMilestones milestones = 0;
3557 if (events & _WKRenderingProgressEventFirstLayout)
3558 milestones |= WebCore::DidFirstLayout;
3560 if (events & _WKRenderingProgressEventFirstVisuallyNonEmptyLayout)
3561 milestones |= WebCore::DidFirstVisuallyNonEmptyLayout;
3563 if (events & _WKRenderingProgressEventFirstPaintWithSignificantArea)
3564 milestones |= WebCore::DidHitRelevantRepaintedObjectsAreaThreshold;
3566 if (events & _WKRenderingProgressEventReachedSessionRestorationRenderTreeSizeThreshold)
3567 milestones |= WebCore::ReachedSessionRestorationRenderTreeSizeThreshold;
3569 if (events & _WKRenderingProgressEventFirstLayoutAfterSuppressedIncrementalRendering)
3570 milestones |= WebCore::DidFirstLayoutAfterSuppressedIncrementalRendering;
3572 if (events & _WKRenderingProgressEventFirstPaintAfterSuppressedIncrementalRendering)
3573 milestones |= WebCore::DidFirstPaintAfterSuppressedIncrementalRendering;
3578 - (void)_setObservedRenderingProgressEvents:(_WKRenderingProgressEvents)observedRenderingProgressEvents
3580 _observedRenderingProgressEvents = observedRenderingProgressEvents;
3581 _page->listenForLayoutMilestones(layoutMilestones(observedRenderingProgressEvents));
3584 - (void)_getMainResourceDataWithCompletionHandler:(void (^)(NSData *, NSError *))completionHandler
3586 auto handler = adoptNS([completionHandler copy]);
3588 _page->getMainResourceDataOfFrame(_page->mainFrame(), [handler](API::Data* data, WebKit::CallbackBase::Error error) {
3589 void (^completionHandlerBlock)(NSData *, NSError *) = (void (^)(NSData *, NSError *))handler.get();
3590 if (error != WebKit::CallbackBase::Error::None) {
3591 // FIXME: Pipe a proper error in from the WebPageProxy.
3592 RetainPtr<NSError> error = adoptNS([[NSError alloc] init]);
3593 completionHandlerBlock(nil, error.get());
3595 completionHandlerBlock(wrapper(*data), nil);
3599 - (void)_getWebArchiveDataWithCompletionHandler:(void (^)(NSData *, NSError *))completionHandler
3601 auto handler = adoptNS([completionHandler copy]);
3603 _page->getWebArchiveOfFrame(_page->mainFrame(), [handler](API::Data* data, WebKit::CallbackBase::Error error) {
3604 void (^completionHandlerBlock)(NSData *, NSError *) = (void (^)(NSData *, NSError *))handler.get();
3605 if (error != WebKit::CallbackBase::Error::None) {
3606 // FIXME: Pipe a proper error in from the WebPageProxy.
3607 RetainPtr<NSError> error = adoptNS([[NSError alloc] init]);
3608 completionHandlerBlock(nil, error.get());
3610 completionHandlerBlock(wrapper(*data), nil);
3614 - (_WKPaginationMode)_paginationMode
3616 switch (_page->paginationMode()) {
3617 case WebCore::Pagination::Unpaginated:
3618 return _WKPaginationModeUnpaginated;
3619 case WebCore::Pagination::LeftToRightPaginated:
3620 return _WKPaginationModeLeftToRight;
3621 case WebCore::Pagination::RightToLeftPaginated:
3622 return _WKPaginationModeRightToLeft;
3623 case WebCore::Pagination::TopToBottomPaginated:
3624 return _WKPaginationModeTopToBottom;
3625 case WebCore::Pagination::BottomToTopPaginated:
3626 return _WKPaginationModeBottomToTop;
3629 ASSERT_NOT_REACHED();
3630 return _WKPaginationModeUnpaginated;
3633 - (void)_setPaginationMode:(_WKPaginationMode)paginationMode
3635 WebCore::Pagination::Mode mode;
3636 switch (paginationMode) {
3637 case _WKPaginationModeUnpaginated:
3638 mode = WebCore::Pagination::Unpaginated;
3640 case _WKPaginationModeLeftToRight:
3641 mode = WebCore::Pagination::LeftToRightPaginated;
3643 case _WKPaginationModeRightToLeft:
3644 mode = WebCore::Pagination::RightToLeftPaginated;
3646 case _WKPaginationModeTopToBottom:
3647 mode = WebCore::Pagination::TopToBottomPaginated;
3649 case _WKPaginationModeBottomToTop:
3650 mode = WebCore::Pagination::BottomToTopPaginated;
3656 _page->setPaginationMode(mode);
3659 - (BOOL)_paginationBehavesLikeColumns
3661 return _page->paginationBehavesLikeColumns();
3664 - (void)_setPaginationBehavesLikeColumns:(BOOL)behavesLikeColumns
3666 _page->setPaginationBehavesLikeColumns(behavesLikeColumns);
3669 - (CGFloat)_pageLength
3671 return _page->pageLength();
3674 - (void)_setPageLength:(CGFloat)pageLength
3676 _page->setPageLength(pageLength);
3679 - (CGFloat)_gapBetweenPages
3681 return _page->gapBetweenPages();
3684 - (void)_setGapBetweenPages:(CGFloat)gapBetweenPages
3686 _page->setGapBetweenPages(gapBetweenPages);
3689 - (BOOL)_paginationLineGridEnabled
3691 return _page->paginationLineGridEnabled();
3694 - (void)_setPaginationLineGridEnabled:(BOOL)lineGridEnabled
3696 _page->setPaginationLineGridEnabled(lineGridEnabled);
3699 - (NSUInteger)_pageCount
3701 return _page->pageCount();
3704 - (BOOL)_supportsTextZoom
3706 return _page->supportsTextZoom();
3709 - (double)_textZoomFactor
3711 return _page->textZoomFactor();
3714 - (void)_setTextZoomFactor:(double)zoomFactor
3716 _page->setTextZoomFactor(zoomFactor);
3719 - (double)_pageZoomFactor
3721 return _page->pageZoomFactor();
3724 - (void)_setPageZoomFactor:(double)zoomFactor
3726 _page->setPageZoomFactor(zoomFactor);
3729 - (id <_WKDiagnosticLoggingDelegate>)_diagnosticLoggingDelegate
3731 return [static_cast<WebKit::DiagnosticLoggingClient&>(_page->diagnosticLoggingClient()).delegate().leakRef() autorelease];
3734 - (void)_setDiagnosticLoggingDelegate:(id<_WKDiagnosticLoggingDelegate>)diagnosticLoggingDelegate
3736 static_cast<WebKit::DiagnosticLoggingClient&>(_page->diagnosticLoggingClient()).setDelegate(diagnosticLoggingDelegate);
3739 - (id <_WKFindDelegate>)_findDelegate
3741 return [static_cast<WebKit::FindClient&>(_page->findClient()).delegate().leakRef() autorelease];
3744 - (void)_setFindDelegate:(id<_WKFindDelegate>)findDelegate
3746 static_cast<WebKit::FindClient&>(_page->findClient()).setDelegate(findDelegate);
3749 static inline WebKit::FindOptions toFindOptions(_WKFindOptions wkFindOptions)
3751 unsigned findOptions = 0;
3753 if (wkFindOptions & _WKFindOptionsCaseInsensitive)
3754 findOptions |= WebKit::FindOptionsCaseInsensitive;
3755 if (wkFindOptions & _WKFindOptionsAtWordStarts)
3756 findOptions |= WebKit::FindOptionsAtWordStarts;
3757 if (wkFindOptions & _WKFindOptionsTreatMedialCapitalAsWordStart)
3758 findOptions |= WebKit::FindOptionsTreatMedialCapitalAsWordStart;
3759 if (wkFindOptions & _WKFindOptionsBackwards)
3760 findOptions |= WebKit::FindOptionsBackwards;
3761 if (wkFindOptions & _WKFindOptionsWrapAround)
3762 findOptions |= WebKit::FindOptionsWrapAround;
3763 if (wkFindOptions & _WKFindOptionsShowOverlay)
3764 findOptions |= WebKit::FindOptionsShowOverlay;
3765 if (wkFindOptions & _WKFindOptionsShowFindIndicator)
3766 findOptions |= WebKit::FindOptionsShowFindIndicator;
3767 if (wkFindOptions & _WKFindOptionsShowHighlight)
3768 findOptions |= WebKit::FindOptionsShowHighlight;
3769 if (wkFindOptions & _WKFindOptionsDetermineMatchIndex)
3770 findOptions |= WebKit::FindOptionsDetermineMatchIndex;
3772 return static_cast<WebKit::FindOptions>(findOptions);
3775 - (void)_countStringMatches:(NSString *)string options:(_WKFindOptions)options maxCount:(NSUInteger)maxCount
3778 if (_customContentView) {
3779 [_customContentView web_countStringMatches:string options:options maxCount:maxCount];
3783 _page->countStringMatches(string, toFindOptions(options), maxCount);
3786 - (void)_findString:(NSString *)string options:(_WKFindOptions)options maxCount:(NSUInteger)maxCount
3789 if (_customContentView) {
3790 [_customContentView web_findString:string options:options maxCount:maxCount];
3794 _page->findString(string, toFindOptions(options), maxCount);
3800 if (_customContentView) {
3801 [_customContentView web_hideFindUI];
3805 _page->hideFindUI();
3808 - (void)_saveBackForwardSnapshotForItem:(WKBackForwardListItem *)item
3810 _page->recordNavigationSnapshot(item._item);
3813 - (id <_WKInputDelegate>)_inputDelegate
3815 return _inputDelegate.getAutoreleased();
3818 - (void)_setInputDelegate:(id <_WKInputDelegate>)inputDelegate
3820 _inputDelegate = inputDelegate;
3822 class FormClient : public API::FormClient {
3824 explicit FormClient(WKWebView *webView)
3825 : m_webView(webView)
3829 virtual ~FormClient() { }
3831 void willSubmitForm(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, WebKit::WebFrameProxy& sourceFrame, const Vector<std::pair<WTF::String, WTF::String>>& textFieldValues, API::Object* userData, Ref<WebKit::WebFormSubmissionListenerProxy>&& listener) override
3833 if (userData && userData->type() != API::Object::Type::Data) {
3834 ASSERT(!userData || userData->type() == API::Object::Type::Data);
3835 m_webView->_page->process().connection()->markCurrentlyDispatchedMessageAsInvalid();
3836 listener->continueSubmission();
3840 auto inputDelegate = m_webView->_inputDelegate.get();
3842 if (![inputDelegate respondsToSelector:@selector(_webView:willSubmitFormValues:userObject:submissionHandler:)]) {
3843 listener->continueSubmission();
3847 auto valueMap = adoptNS([[NSMutableDictionary alloc] initWithCapacity:textFieldValues.size()]);
3848 for (const auto& pair : textFieldValues)
3849 [valueMap setObject:pair.second forKey:pair.first];
3851 NSObject <NSSecureCoding> *userObject = nil;
3852 if (API::Data* data = static_cast<API::Data*>(userData)) {
3853 auto nsData = adoptNS([[NSData alloc] initWithBytesNoCopy:const_cast<void*>(static_cast<const void*>(data->bytes())) length:data->size() freeWhenDone:NO]);
3854 auto unarchiver = adoptNS([[NSKeyedUnarchiver alloc] initForReadingWithData:nsData.get()]);
3855 [unarchiver setRequiresSecureCoding:YES];
3857 userObject = [unarchiver decodeObjectOfClass:[NSObject class] forKey:@"userObject"];
3858 } @catch (NSException *exception) {
3859 LOG_ERROR("Failed to decode user data: %@", exception);
3863 RefPtr<WebKit::WebFormSubmissionListenerProxy> localListener = WTFMove(listener);
3864 RefPtr<WebKit::CompletionHandlerCallChecker> checker = WebKit::CompletionHandlerCallChecker::create(inputDelegate.get(), @selector(_webView:willSubmitFormValues:userObject:submissionHandler:));
3865 [inputDelegate _webView:m_webView willSubmitFormValues:valueMap.get() userObject:userObject submissionHandler:[localListener, checker] {
3866 checker->didCallCompletionHandler();
3867 localListener->continueSubmission();
3872 WKWebView *m_webView;
3876 _page->setFormClient(std::make_unique<FormClient>(self));
3878 _page->setFormClient(nullptr);
3881 - (BOOL)_isDisplayingStandaloneImageDocument
3883 if (auto* mainFrame = _page->mainFrame())
3884 return mainFrame->isDisplayingStandaloneImageDocument();
3888 - (BOOL)_isDisplayingStandaloneMediaDocument
3890 if (auto* mainFrame = _page->mainFrame())
3891 return mainFrame->isDisplayingStandaloneMediaDocument();
3895 - (BOOL)_isShowingNavigationGestureSnapshot
3897 return _page->isShowingNavigationGestureSnapshot();
3900 - (_WKLayoutMode)_layoutMode
3903 switch (_impl->layoutMode()) {
3904 case kWKLayoutModeFixedSize:
3905 return _WKLayoutModeFixedSize;
3906 case kWKLayoutModeDynamicSizeComputedFromViewScale:
3907 return _WKLayoutModeDynamicSizeComputedFromViewScale;
3908 case kWKLayoutModeDynamicSizeComputedFromMinimumDocumentSize:
3909 return _WKLayoutModeDynamicSizeComputedFromMinimumDocumentSize;
3910 case kWKLayoutModeViewSize:
3912 return _WKLayoutModeViewSize;
3915 return _page->useFixedLayout() ? _WKLayoutModeFixedSize : _WKLayoutModeViewSize;
3919 - (void)_setLayoutMode:(_WKLayoutMode)layoutMode
3922 WKLayoutMode wkViewLayoutMode;
3923 switch (layoutMode) {
3924 case _WKLayoutModeFixedSize:
3925 wkViewLayoutMode = kWKLayoutModeFixedSize;
3927 case _WKLayoutModeDynamicSizeComputedFromViewScale:
3928 wkViewLayoutMode = kWKLayoutModeDynamicSizeComputedFromViewScale;
3930 case _WKLayoutModeDynamicSizeComputedFromMinimumDocumentSize:
3931 wkViewLayoutMode = kWKLayoutModeDynamicSizeComputedFromMinimumDocumentSize;
3933 case _WKLayoutModeViewSize:
3935 wkViewLayoutMode = kWKLayoutModeViewSize;
3938 _impl->setLayoutMode(wkViewLayoutMode);
3940 _page->setUseFixedLayout(layoutMode == _WKLayoutModeFixedSize || layoutMode == _WKLayoutModeDynamicSizeComputedFromViewScale);
3944 - (CGSize)_fixedLayoutSize
3946 return _page->fixedLayoutSize();
3949 - (void)_setFixedLayoutSize:(CGSize)fixedLayoutSize
3951 _page->setFixedLayoutSize(WebCore::expandedIntSize(WebCore::FloatSize(fixedLayoutSize)));
3954 - (CGFloat)_viewScale
3956 return _page->viewScaleFactor();
3959 - (void)_setViewScale:(CGFloat)viewScale
3962 _impl->setViewScale(viewScale);
3964 if (viewScale <= 0 || isnan(viewScale) || isinf(viewScale))
3965 [NSException raise:NSInvalidArgumentException format:@"View scale should be a positive number"];
3967 _page->scaleView(viewScale);
3971 #pragma mark scrollperf methods
3973 - (void)_setScrollPerformanceDataCollectionEnabled:(BOOL)enabled
3975 _page->setScrollPerformanceDataCollectionEnabled(enabled);
3978 - (BOOL)_scrollPerformanceDataCollectionEnabled
3980 return _page->scrollPerformanceDataCollectionEnabled();
3983 - (NSArray *)_scrollPerformanceData
3986 if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
3987 return scrollPerfData->data();
3992 #pragma mark media playback restrictions
3994 - (BOOL)_allowsMediaDocumentInlinePlayback
3997 return _page->allowsMediaDocumentInlinePlayback();
4003 - (void)_setAllowsMediaDocumentInlinePlayback:(BOOL)flag
4006 _page->setAllowsMediaDocumentInlinePlayback(flag);
4010 - (BOOL)_webProcessIsResponsive
4012 return _page->process().responsivenessTimer().isResponsive();
4015 - (void)_setFullscreenDelegate:(id<_WKFullscreenDelegate>)delegate
4017 #if ENABLE(FULLSCREEN_API)
4018 static_cast<WebKit::FullscreenClient&>(_page->fullscreenClient()).setDelegate(delegate);
4022 - (id<_WKFullscreenDelegate>)_fullscreenDelegate
4024 #if ENABLE(FULLSCREEN_API)
4025 return static_cast<WebKit::FullscreenClient&>(_page->fullscreenClient()).delegate().autorelease();
4031 - (BOOL)_isInFullscreen
4033 #if ENABLE(FULLSCREEN_API)
4034 return _page->fullScreenManager() && _page->fullScreenManager()->isFullScreen();
4040 #pragma mark iOS-specific methods
4044 - (CGSize)_minimumLayoutSizeOverride
4046 ASSERT(_overridesMinimumLayoutSize);
4047 return _minimumLayoutSizeOverride;
4050 - (void)_setMinimumLayoutSizeOverride:(CGSize)minimumLayoutSizeOverride
4052 _overridesMinimumLayoutSize = YES;
4053 if (CGSizeEqualToSize(_minimumLayoutSizeOverride, minimumLayoutSizeOverride))
4056 _minimumLayoutSizeOverride = minimumLayoutSizeOverride;
4057 if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing)
4058 _page->setViewportConfigurationMinimumLayoutSize(WebCore::FloatSize(minimumLayoutSizeOverride));
4061 - (UIEdgeInsets)_obscuredInsets
4063 return _obscuredInsets;
4066 - (void)_setObscuredInsets:(UIEdgeInsets)obscuredInsets
4068 ASSERT(obscuredInsets.top >= 0);
4069 ASSERT(obscuredInsets.left >= 0);
4070 ASSERT(obscuredInsets.bottom >= 0);
4071 ASSERT(obscuredInsets.right >= 0);
4073 _haveSetObscuredInsets = YES;
4075 if (UIEdgeInsetsEqualToEdgeInsets(_obscuredInsets, obscuredInsets))
4078 _obscuredInsets = obscuredInsets;
4080 [self _updateVisibleContentRects];
4083 - (void)_setInterfaceOrientationOverride:(UIInterfaceOrientation)interfaceOrientation
4085 if (!_overridesInterfaceOrientation)
4086 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIWindowDidRotateNotification object:nil];
4088 _overridesInterfaceOrientation = YES;
4090 if (interfaceOrientation == _interfaceOrientationOverride)
4093 _interfaceOrientationOverride = interfaceOrientation;
4095 if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing)
4096 _page->setDeviceOrientation(deviceOrientationForUIInterfaceOrientation(_interfaceOrientationOverride));
4099 - (UIInterfaceOrientation)_interfaceOrientationOverride
4101 ASSERT(_overridesInterfaceOrientation);
4102 return _interfaceOrientationOverride;
4105 - (CGSize)_maximumUnobscuredSizeOverride
4107 ASSERT(_overridesMaximumUnobscuredSize);
4108 return _maximumUnobscuredSizeOverride;
4111 - (void)_setMaximumUnobscuredSizeOverride:(CGSize)size
4113 ASSERT(size.width <= self.bounds.size.width && size.height <= self.bounds.size.height);
4114 _overridesMaximumUnobscuredSize = YES;
4115 if (CGSizeEqualToSize(_maximumUnobscuredSizeOverride, size))
4118 _maximumUnobscuredSizeOverride = size;
4119 if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing)
4120 _page->setMaximumUnobscuredSize(WebCore::FloatSize(size));
4123 - (void)_setBackgroundExtendsBeyondPage:(BOOL)backgroundExtends
4125 _page->setBackgroundExtendsBeyondPage(backgroundExtends);
4128 - (BOOL)_backgroundExtendsBeyondPage
4130 return _page->backgroundExtendsBeyondPage();
4133 - (void)_setAllowsViewportShrinkToFit:(BOOL)allowShrinkToFit
4135 _allowsViewportShrinkToFit = allowShrinkToFit;
4138 - (BOOL)_allowsViewportShrinkToFit
4140 return _allowsViewportShrinkToFit;
4143 - (void)_beginInteractiveObscuredInsetsChange
4145 ASSERT(!_isChangingObscuredInsetsInteractively);
4146 _isChangingObscuredInsetsInteractively = YES;
4149 - (void)_endInteractiveObscuredInsetsChange
4151 ASSERT(_isChangingObscuredInsetsInteractively);
4152 _isChangingObscuredInsetsInteractively = NO;
4153 [self _updateVisibleContentRects];
4156 - (void)_hideContentUntilNextUpdate
4158 if (auto* area = _page->drawingArea())
4159 area->hideContentUntilAnyUpdate();
4162 - (void)_beginAnimatedResizeWithUpdates:(void (^)(void))updateBlock
4164 CGRect oldBounds = self.bounds;
4165 WebCore::FloatRect oldUnobscuredContentRect = _page->unobscuredContentRect();
4167 if (_customContentView || !_hasCommittedLoadForMainFrame || CGRectIsEmpty(oldBounds) || oldUnobscuredContentRect.isEmpty()) {
4172 _dynamicViewportUpdateMode = DynamicViewportUpdateMode::ResizingWithAnimation;
4174 WebCore::FloatSize oldMinimumLayoutSize = activeMinimumLayoutSize(self, oldBounds);
4175 WebCore::FloatSize oldMaximumUnobscuredSize = activeMaximumUnobscuredSize(self, oldBounds);
4176 int32_t oldOrientation = activeOrientation(self);
4177 UIEdgeInsets oldObscuredInsets = _obscuredInsets;
4181 CGRect newBounds = self.bounds;
4182 WebCore::FloatSize newMinimumLayoutSize = activeMinimumLayoutSize(self, newBounds);
4183 WebCore::FloatSize newMaximumUnobscuredSize = activeMaximumUnobscuredSize(self, newBounds);
4184 int32_t newOrientation = activeOrientation(self);
4185 UIEdgeInsets newObscuredInsets = _obscuredInsets;
4186 CGRect futureUnobscuredRectInSelfCoordinates = UIEdgeInsetsInsetRect(newBounds, _obscuredInsets);
4187 CGRect contentViewBounds = [_contentView bounds];
4189 ASSERT_WITH_MESSAGE(!(_overridesMinimumLayoutSize && newMinimumLayoutSize.isEmpty()), "Clients controlling the layout size should maintain a valid layout size to minimize layouts.");
4190 if (CGRectIsEmpty(newBounds) || newMinimumLayoutSize.isEmpty() || CGRectIsEmpty(futureUnobscuredRectInSelfCoordinates) || CGRectIsEmpty(contentViewBounds)) {