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 "LegacySessionStateCoding.h"
39 #import "NavigationState.h"
40 #import "ObjCObjectGraph.h"
41 #import "RemoteLayerTreeScrollingPerformanceData.h"
42 #import "RemoteLayerTreeTransaction.h"
43 #import "RemoteObjectRegistry.h"
44 #import "RemoteObjectRegistryMessages.h"
45 #import "UIDelegate.h"
46 #import "ViewGestureController.h"
47 #import "ViewSnapshotStore.h"
48 #import "WKBackForwardListInternal.h"
49 #import "WKBackForwardListItemInternal.h"
50 #import "WKBrowsingContextHandleInternal.h"
51 #import "WKErrorInternal.h"
52 #import "WKHistoryDelegatePrivate.h"
53 #import "WKLayoutMode.h"
55 #import "WKNSURLExtras.h"
56 #import "WKNavigationDelegate.h"
57 #import "WKNavigationInternal.h"
58 #import "WKPreferencesInternal.h"
59 #import "WKProcessPoolInternal.h"
60 #import "WKSharedAPICast.h"
61 #import "WKUIDelegate.h"
62 #import "WKUIDelegatePrivate.h"
63 #import "WKUserContentControllerInternal.h"
64 #import "WKWebViewConfigurationInternal.h"
65 #import "WKWebViewContentProvider.h"
66 #import "WKWebsiteDataStoreInternal.h"
67 #import "WebBackForwardList.h"
68 #import "WebCertificateInfo.h"
69 #import "WebFormSubmissionListenerProxy.h"
70 #import "WebKitSystemInterface.h"
71 #import "WebPageGroup.h"
72 #import "WebPageProxy.h"
73 #import "WebPreferencesKeys.h"
74 #import "WebProcessPool.h"
75 #import "WebProcessProxy.h"
76 #import "WebViewImpl.h"
77 #import "_WKDiagnosticLoggingDelegate.h"
78 #import "_WKFindDelegate.h"
79 #import "_WKFrameHandleInternal.h"
80 #import "_WKHitTestResultInternal.h"
81 #import "_WKInputDelegate.h"
82 #import "_WKRemoteObjectRegistryInternal.h"
83 #import "_WKSessionStateInternal.h"
84 #import "_WKVisitedLinkStoreInternal.h"
85 #import <WebCore/GraphicsContextCG.h>
86 #import <WebCore/IOSurface.h>
87 #import <WebCore/JSDOMBinding.h>
88 #import <WebCore/NSTextFinderSPI.h>
89 #import <WebCore/PlatformScreen.h>
90 #import <WebCore/RuntimeApplicationChecks.h>
91 #import <WebCore/Settings.h>
92 #import <WebCore/TextStream.h>
93 #import <WebCore/WritingMode.h>
94 #import <wtf/HashMap.h>
95 #import <wtf/MathExtras.h>
96 #import <wtf/NeverDestroyed.h>
97 #import <wtf/Optional.h>
98 #import <wtf/RetainPtr.h>
99 #import <wtf/TemporaryChange.h>
100 #import <wtf/spi/darwin/dyldSPI.h>
103 #import "_WKWebViewPrintFormatter.h"
104 #import "ProcessThrottler.h"
105 #import "RemoteLayerTreeDrawingAreaProxy.h"
106 #import "RemoteScrollingCoordinatorProxy.h"
108 #import "WKContentViewInteraction.h"
109 #import "WKPDFView.h"
110 #import "WKScrollView.h"
111 #import "WKWebViewContentProviderRegistry.h"
112 #import "WebVideoFullscreenManagerProxy.h"
113 #import <UIKit/UIApplication.h>
114 #import <WebCore/CoreGraphicsSPI.h>
115 #import <WebCore/FrameLoaderTypes.h>
116 #import <WebCore/InspectorOverlay.h>
117 #import <WebCore/QuartzCoreSPI.h>
118 #import <WebCore/ScrollableArea.h>
120 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000
121 #if __has_include(<AccessibilitySupport.h>)
122 #include <AccessibilitySupport.h>
125 CFStringRef kAXSAllowForceWebScalingEnabledNotification;
130 @interface UIScrollView (UIScrollViewInternal)
131 - (void)_adjustForAutomaticKeyboardInfo:(NSDictionary*)info animated:(BOOL)animated lastAdjustment:(CGFloat*)lastAdjustment;
132 - (BOOL)_isScrollingToTop;
133 - (BOOL)_isInterruptingDeceleration;
134 - (CGPoint)_animatedTargetOffset;
137 @interface UIPeripheralHost(UIKitInternal)
138 - (CGFloat)getVerticalOverlapForView:(UIView *)view usingKeyboardInfo:(NSDictionary *)info;
141 @interface UIView (UIViewInternal)
142 - (UIViewController *)_viewControllerForAncestor;
145 @interface UIWindow (UIWindowInternal)
146 - (BOOL)_isHostedInAnotherProcess;
149 @interface UIViewController (UIViewControllerInternal)
150 - (UIViewController *)_rootAncestorViewController;
151 - (UIViewController *)_viewControllerForSupportedInterfaceOrientations;
154 enum class DynamicViewportUpdateMode {
156 ResizingWithAnimation,
157 ResizingWithDocumentHidden,
160 #endif // PLATFORM(IOS)
163 static const uint32_t firstSDKVersionWithLinkPreviewEnabledByDefault = 0xA0000;
167 #import "WKTextFinderClient.h"
168 #import "WKViewInternal.h"
169 #import <WebCore/ColorMac.h>
171 @interface WKWebView () <WebViewImplDelegate, NSTextInputClient>
175 static HashMap<WebKit::WebPageProxy*, WKWebView *>& pageToViewMap()
177 static NeverDestroyed<HashMap<WebKit::WebPageProxy*, WKWebView *>> map;
181 WKWebView* fromWebPageProxy(WebKit::WebPageProxy& page)
183 return pageToViewMap().get(&page);
186 @implementation WKWebView {
187 std::unique_ptr<WebKit::NavigationState> _navigationState;
188 std::unique_ptr<WebKit::UIDelegate> _uiDelegate;
190 _WKRenderingProgressEvents _observedRenderingProgressEvents;
192 WebKit::WeakObjCPtr<id <_WKInputDelegate>> _inputDelegate;
195 RetainPtr<_WKRemoteObjectRegistry> _remoteObjectRegistry;
197 RetainPtr<WKScrollView> _scrollView;
198 RetainPtr<WKContentView> _contentView;
200 BOOL _overridesMinimumLayoutSize;
201 CGSize _minimumLayoutSizeOverride;
202 BOOL _overridesMaximumUnobscuredSize;
203 CGSize _maximumUnobscuredSizeOverride;
204 CGRect _inputViewBounds;
205 CGFloat _viewportMetaTagWidth;
206 BOOL _viewportMetaTagWidthWasExplicit;
207 BOOL _viewportMetaTagCameFromImageDocument;
208 CGFloat _initialScaleFactor;
209 BOOL _fastClickingIsDisabled;
211 BOOL _allowsLinkPreview;
213 UIEdgeInsets _obscuredInsets;
214 BOOL _haveSetObscuredInsets;
215 BOOL _isChangingObscuredInsetsInteractively;
217 UIInterfaceOrientation _interfaceOrientationOverride;
218 BOOL _overridesInterfaceOrientation;
220 BOOL _allowsViewportShrinkToFit;
222 BOOL _hasCommittedLoadForMainFrame;
223 BOOL _needsResetViewStateAfterCommitLoadForMainFrame;
224 uint64_t _firstPaintAfterCommitLoadTransactionID;
225 DynamicViewportUpdateMode _dynamicViewportUpdateMode;
226 CATransform3D _resizeAnimationTransformAdjustments;
227 Optional<uint64_t> _resizeAnimationTransformTransactionID;
228 RetainPtr<UIView> _resizeAnimationView;
229 CGFloat _lastAdjustmentForScroller;
230 Optional<CGRect> _frozenVisibleContentRect;
231 Optional<CGRect> _frozenUnobscuredContentRect;
233 BOOL _needsToRestoreScrollPosition;
234 BOOL _commitDidRestoreScrollPosition;
235 WebCore::FloatPoint _scrollOffsetToRestore;
236 WebCore::FloatSize _obscuredInsetWhenSaved;
238 BOOL _needsToRestoreUnobscuredCenter;
239 WebCore::FloatPoint _unobscuredCenterToRestore;
240 uint64_t _firstTransactionIDAfterPageRestore;
241 double _scaleToRestore;
243 std::unique_ptr<WebKit::ViewGestureController> _gestureController;
244 BOOL _allowsBackForwardNavigationGestures;
246 RetainPtr<UIView <WKWebViewContentProvider>> _customContentView;
247 RetainPtr<UIView> _customContentFixedOverlayView;
249 RetainPtr<NSTimer> _enclosingScrollViewScrollTimer;
250 BOOL _didScrollSinceLastTimerFire;
252 WebCore::Color _scrollViewBackgroundColor;
254 // This value tracks the current adjustment added to the bottom inset due to the keyboard sliding out from the bottom
255 // when computing obscured content insets. This is used when updating the visible content rects where we should not
256 // include this adjustment.
257 CGFloat _totalScrollViewBottomInsetAdjustmentForKeyboard;
258 BOOL _currentlyAdjustingScrollViewInsetsForKeyboard;
260 BOOL _delayUpdateVisibleContentRects;
261 BOOL _hadDelayedUpdateVisibleContentRects;
263 Vector<std::function<void ()>> _snapshotsDeferredDuringResize;
266 std::unique_ptr<WebKit::WebViewImpl> _impl;
267 RetainPtr<WKTextFinderClient> _textFinderClient;
271 - (instancetype)initWithFrame:(CGRect)frame
273 return [self initWithFrame:frame configuration:adoptNS([[WKWebViewConfiguration alloc] init]).get()];
277 static int32_t deviceOrientationForUIInterfaceOrientation(UIInterfaceOrientation orientation)
279 switch (orientation) {
280 case UIInterfaceOrientationUnknown:
281 case UIInterfaceOrientationPortrait:
283 case UIInterfaceOrientationPortraitUpsideDown:
285 case UIInterfaceOrientationLandscapeLeft:
287 case UIInterfaceOrientationLandscapeRight:
292 static int32_t deviceOrientation()
294 return deviceOrientationForUIInterfaceOrientation([[UIApplication sharedApplication] statusBarOrientation]);
297 - (BOOL)_isShowingVideoPictureInPicture
302 if (!_page || !_page->videoFullscreenManager())
305 return _page->videoFullscreenManager()->hasMode(WebCore::HTMLMediaElementEnums::VideoFullscreenModePictureInPicture);
309 - (BOOL)_mayAutomaticallyShowVideoPictureInPicture
314 if (!_page || !_page->videoFullscreenManager())
317 return _page->videoFullscreenManager()->mayAutomaticallyShowVideoPictureInPicture();
321 static bool shouldAllowPictureInPictureMediaPlayback()
323 static bool shouldAllowPictureInPictureMediaPlayback = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_9_0;
324 return shouldAllowPictureInPictureMediaPlayback;
329 static bool shouldRequireUserGestureToLoadVideo()
332 static bool shouldRequireUserGestureToLoadVideo = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
333 return shouldRequireUserGestureToLoadVideo;
339 #if ENABLE(DATA_DETECTION) && PLATFORM(IOS)
340 static WebCore::DataDetectorTypes fromWKDataDetectorTypes(uint64_t types)
342 if (static_cast<WKDataDetectorTypes>(types) == WKDataDetectorTypeNone)
343 return WebCore::DataDetectorTypeNone;
344 if (static_cast<WKDataDetectorTypes>(types) == WKDataDetectorTypeAll)
345 return WebCore::DataDetectorTypeAll;
347 uint32_t value = WebCore::DataDetectorTypeNone;
348 if (types & WKDataDetectorTypePhoneNumber)
349 value |= WebCore::DataDetectorTypePhoneNumber;
350 if (types & WKDataDetectorTypeLink)
351 value |= WebCore::DataDetectorTypeLink;
352 if (types & WKDataDetectorTypeAddress)
353 value |= WebCore::DataDetectorTypeAddress;
354 if (types & WKDataDetectorTypeCalendarEvent)
355 value |= WebCore::DataDetectorTypeCalendarEvent;
356 if (types & WKDataDetectorTypeTrackingNumber)
357 value |= WebCore::DataDetectorTypeTrackingNumber;
358 if (types & WKDataDetectorTypeFlightNumber)
359 value |= WebCore::DataDetectorTypeFlightNumber;
360 if (types & WKDataDetectorTypeLookupSuggestion)
361 value |= WebCore::DataDetectorTypeLookupSuggestion;
363 return static_cast<WebCore::DataDetectorTypes>(value);
368 static uint32_t convertUserInterfaceDirectionPolicy(WKUserInterfaceDirectionPolicy policy)
371 case WKUserInterfaceDirectionPolicyContent:
372 return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content);
373 case WKUserInterfaceDirectionPolicySystem:
374 return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::System);
376 return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content);
379 static uint32_t convertSystemLayoutDirection(NSUserInterfaceLayoutDirection direction)
382 case NSUserInterfaceLayoutDirectionLeftToRight:
383 return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::LTR);
384 case NSUserInterfaceLayoutDirectionRightToLeft:
385 return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::RTL);
387 return static_cast<uint32_t>(WebCore::UserInterfaceLayoutDirection::LTR);
391 - (void)_initializeWithConfiguration:(WKWebViewConfiguration *)configuration
394 [NSException raise:NSInvalidArgumentException format:@"Configuration cannot be nil"];
396 _configuration = adoptNS([configuration copy]);
398 if (WKWebView *relatedWebView = [_configuration _relatedWebView]) {
399 WKProcessPool *processPool = [_configuration processPool];
400 WKProcessPool *relatedWebViewProcessPool = [relatedWebView->_configuration processPool];
401 if (processPool && processPool != relatedWebViewProcessPool)
402 [NSException raise:NSInvalidArgumentException format:@"Related web view %@ has process pool %@ but configuration specifies a different process pool %@", relatedWebView, relatedWebViewProcessPool, configuration.processPool];
404 [_configuration setProcessPool:relatedWebViewProcessPool];
407 [_configuration _validate];
409 WebKit::WebProcessPool& processPool = *[_configuration processPool]->_processPool;
410 processPool.setResourceLoadStatisticsEnabled(configuration.websiteDataStore._resourceLoadStatisticsEnabled);
412 auto pageConfiguration = API::PageConfiguration::create();
414 pageConfiguration->setProcessPool(&processPool);
415 pageConfiguration->setPreferences([_configuration preferences]->_preferences.get());
416 if (WKWebView *relatedWebView = [_configuration _relatedWebView])
417 pageConfiguration->setRelatedPage(relatedWebView->_page.get());
419 pageConfiguration->setUserContentController([_configuration userContentController]->_userContentControllerProxy.get());
420 pageConfiguration->setVisitedLinkStore([_configuration _visitedLinkStore]->_visitedLinkStore.get());
421 pageConfiguration->setWebsiteDataStore([_configuration websiteDataStore]->_websiteDataStore.get());
422 pageConfiguration->setTreatsSHA1SignedCertificatesAsInsecure([_configuration _treatsSHA1SignedCertificatesAsInsecure]);
424 RefPtr<WebKit::WebPageGroup> pageGroup;
425 NSString *groupIdentifier = configuration._groupIdentifier;
426 if (groupIdentifier.length) {
427 pageGroup = WebKit::WebPageGroup::create(configuration._groupIdentifier);
428 pageConfiguration->setPageGroup(pageGroup.get());
431 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::suppressesIncrementalRenderingKey(), WebKit::WebPreferencesStore::Value(!![_configuration suppressesIncrementalRendering]));
433 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldRespectImageOrientationKey(), WebKit::WebPreferencesStore::Value(!![_configuration _respectsImageOrientation]));
434 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldPrintBackgroundsKey(), WebKit::WebPreferencesStore::Value(!![_configuration _printsBackgrounds]));
435 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey(), WebKit::WebPreferencesStore::Value([_configuration _incrementalRenderingSuppressionTimeout]));
436 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::javaScriptMarkupEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsJavaScriptMarkup]));
437 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldConvertPositionStyleOnCopyKey(), WebKit::WebPreferencesStore::Value(!![_configuration _convertsPositionStyleOnCopy]));
438 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::httpEquivEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsMetaRefresh]));
439 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowUniversalAccessFromFileURLsKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowUniversalAccessFromFileURLs]));
440 pageConfiguration->setInitialCapitalizationEnabled([_configuration _initialCapitalizationEnabled]);
441 pageConfiguration->setWaitsForPaintAfterViewDidMoveToWindow([_configuration _waitsForPaintAfterViewDidMoveToWindow]);
444 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::showsURLsInToolTipsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _showsURLsInToolTips]));
445 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::serviceControlsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _serviceControlsEnabled]));
446 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::imageControlsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _imageControlsEnabled]));
448 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::userInterfaceDirectionPolicyKey(), WebKit::WebPreferencesStore::Value(convertUserInterfaceDirectionPolicy([_configuration userInterfaceDirectionPolicy])));
449 // We are in the View's initialization routine, so our client hasn't had time to set our user interface direction.
450 // Therefore, according to the docs[1], "this property contains the value reported by the app's userInterfaceLayoutDirection property."
451 // [1] http://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/index.html#//apple_ref/doc/uid/20000014-SW222
452 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::systemLayoutDirectionKey(), WebKit::WebPreferencesStore::Value(convertSystemLayoutDirection(self.userInterfaceLayoutDirection)));
456 pageConfiguration->setAlwaysRunsAtForegroundPriority([_configuration _alwaysRunsAtForegroundPriority]);
458 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsInlineMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsInlineMediaPlayback]));
459 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsInlineMediaPlaybackAfterFullscreenKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsInlineMediaPlaybackAfterFullscreen]));
460 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::inlineMediaPlaybackRequiresPlaysInlineAttributeKey(), WebKit::WebPreferencesStore::Value(!![_configuration _inlineMediaPlaybackRequiresPlaysInlineAttribute]));
461 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsPictureInPictureMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback()));
462 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::userInterfaceDirectionPolicyKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content)));
463 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::systemLayoutDirectionKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(WebCore::LTR)));
466 WKAudiovisualMediaTypes mediaTypesRequiringUserGesture = [_configuration mediaTypesRequiringUserActionForPlayback];
467 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureForVideoPlaybackKey(), WebKit::WebPreferencesStore::Value((mediaTypesRequiringUserGesture & WKAudiovisualMediaTypeVideo) == WKAudiovisualMediaTypeVideo));
468 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureForAudioPlaybackKey(), WebKit::WebPreferencesStore::Value(((mediaTypesRequiringUserGesture & WKAudiovisualMediaTypeAudio) == WKAudiovisualMediaTypeAudio)));
469 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureToLoadVideoKey(), WebKit::WebPreferencesStore::Value(shouldRequireUserGestureToLoadVideo()));
470 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mainContentUserGestureOverrideEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _mainContentUserGestureOverrideEnabled]));
471 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::invisibleAutoplayNotPermittedKey(), WebKit::WebPreferencesStore::Value(!![_configuration _invisibleAutoplayNotPermitted]));
472 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mediaDataLoadsAutomaticallyKey(), WebKit::WebPreferencesStore::Value(!![_configuration _mediaDataLoadsAutomatically]));
474 // FIXME: <rdar://problem/25135244> Remove bundle checks for attachmentElementEnabled
476 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::attachmentElementEnabledKey(), WebKit::WebPreferencesStore::Value(WebCore::IOSApplication::isMobileMail() ? true : !![_configuration _attachmentElementEnabled]));
478 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::attachmentElementEnabledKey(), WebKit::WebPreferencesStore::Value(WebCore::MacApplication::isAppleMail() ? true : !![_configuration _attachmentElementEnabled]));
481 #if ENABLE(DATA_DETECTION) && PLATFORM(IOS)
482 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::dataDetectorTypesKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(fromWKDataDetectorTypes([_configuration dataDetectorTypes]))));
484 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
485 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsAirPlayForMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsAirPlayForMediaPlayback]));
488 #if ENABLE(APPLE_PAY)
489 pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::applePayEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _applePayEnabled]));
493 CGRect bounds = self.bounds;
494 _scrollView = adoptNS([[WKScrollView alloc] initWithFrame:bounds]);
495 [_scrollView setInternalDelegate:self];
496 [_scrollView setBouncesZoom:YES];
498 [self addSubview:_scrollView.get()];
500 static uint32_t programSDKVersion = dyld_get_program_sdk_version();
501 _allowsLinkPreview = programSDKVersion >= firstSDKVersionWithLinkPreviewEnabledByDefault;
503 _contentView = adoptNS([[WKContentView alloc] initWithFrame:bounds processPool:processPool configuration:WTFMove(pageConfiguration) webView:self]);
505 _page = [_contentView page];
506 _page->setDeviceOrientation(deviceOrientation());
508 [_contentView layer].anchorPoint = CGPointZero;
509 [_contentView setFrame:bounds];
510 [_scrollView addSubview:_contentView.get()];
511 [_scrollView addSubview:[_contentView unscaledView]];
512 [self _updateScrollViewBackground];
514 _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
515 _initialScaleFactor = 1;
516 _fastClickingIsDisabled = [[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitFastClickingDisabled"];
518 [self _frameOrBoundsChanged];
520 NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
521 [center addObserver:self selector:@selector(_keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
522 [center addObserver:self selector:@selector(_keyboardDidChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
523 [center addObserver:self selector:@selector(_keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
524 [center addObserver:self selector:@selector(_keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
525 [center addObserver:self selector:@selector(_windowDidRotate:) name:UIWindowDidRotateNotification object:nil];
526 [center addObserver:self selector:@selector(_contentSizeCategoryDidChange:) name:UIContentSizeCategoryDidChangeNotification object:nil];
527 _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
529 [[_configuration _contentProviderRegistry] addPage:*_page];
530 _page->setForceAlwaysUserScalable([_configuration ignoresViewportScaleLimits]);
534 _impl = std::make_unique<WebKit::WebViewImpl>(self, self, processPool, WTFMove(pageConfiguration));
535 _page = &_impl->page();
537 _impl->setAutomaticallyAdjustsContentInsets(true);
538 _impl->setRequiresUserActionForEditingControlsManager([configuration _requiresUserActionForEditingControlsManager]);
541 _page->setBackgroundExtendsBeyondPage(true);
543 if (NSString *applicationNameForUserAgent = configuration.applicationNameForUserAgent)
544 _page->setApplicationNameForUserAgent(applicationNameForUserAgent);
546 _navigationState = std::make_unique<WebKit::NavigationState>(self);
547 _page->setNavigationClient(_navigationState->createNavigationClient());
549 _uiDelegate = std::make_unique<WebKit::UIDelegate>(self);
550 _page->setFindClient(std::make_unique<WebKit::FindClient>(self));
551 _page->setDiagnosticLoggingClient(std::make_unique<WebKit::DiagnosticLoggingClient>(self));
553 pageToViewMap().add(_page.get(), self);
556 - (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration
558 if (!(self = [super initWithFrame:frame]))
561 [self _initializeWithConfiguration:configuration];
566 - (instancetype)initWithCoder:(NSCoder *)coder
568 if (!(self = [super initWithCoder:coder]))
571 WKWebViewConfiguration *configuration = [coder decodeObjectForKey:@"configuration"];
572 [self _initializeWithConfiguration:configuration];
574 self.allowsBackForwardNavigationGestures = [coder decodeBoolForKey:@"allowsBackForwardNavigationGestures"];
575 self.customUserAgent = [coder decodeObjectForKey:@"customUserAgent"];
576 self.allowsLinkPreview = [coder decodeBoolForKey:@"allowsLinkPreview"];
579 self.allowsMagnification = [coder decodeBoolForKey:@"allowsMagnification"];
580 self.magnification = [coder decodeDoubleForKey:@"magnification"];
586 - (void)encodeWithCoder:(NSCoder *)coder
588 [coder encodeObject:_configuration.get() forKey:@"configuration"];
590 [coder encodeBool:self.allowsBackForwardNavigationGestures forKey:@"allowsBackForwardNavigationGestures"];
591 [coder encodeObject:self.customUserAgent forKey:@"customUserAgent"];
592 [coder encodeBool:self.allowsLinkPreview forKey:@"allowsLinkPreview"];
595 [coder encodeBool:self.allowsMagnification forKey:@"allowsMagnification"];
596 [coder encodeDouble:self.magnification forKey:@"magnification"];
603 [_textFinderClient willDestroyView:self];
607 [_contentView _webViewDestroyed];
609 if (_remoteObjectRegistry)
610 _page->process().processPool().removeMessageReceiver(Messages::RemoteObjectRegistry::messageReceiverName(), _page->pageID());
614 [_remoteObjectRegistry _invalidate];
615 [[_configuration _contentProviderRegistry] removePage:*_page];
616 #if PLATFORM(IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000
617 CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), nullptr, nullptr);
619 [[NSNotificationCenter defaultCenter] removeObserver:self];
620 [_scrollView setInternalDelegate:nil];
623 pageToViewMap().remove(_page.get());
628 - (WKWebViewConfiguration *)configuration
630 return [[_configuration copy] autorelease];
633 - (WKBackForwardList *)backForwardList
635 return wrapper(_page->backForwardList());
638 - (id <WKNavigationDelegate>)navigationDelegate
640 return _navigationState->navigationDelegate().autorelease();
643 - (void)setNavigationDelegate:(id <WKNavigationDelegate>)navigationDelegate
645 _page->setNavigationClient(_navigationState->createNavigationClient());
646 _navigationState->setNavigationDelegate(navigationDelegate);
649 - (id <WKUIDelegate>)UIDelegate
651 return _uiDelegate->delegate().autorelease();
654 - (void)setUIDelegate:(id<WKUIDelegate>)UIDelegate
656 #if ENABLE(CONTEXT_MENUS)
657 _page->setContextMenuClient(_uiDelegate->createContextMenuClient());
659 _page->setUIClient(_uiDelegate->createUIClient());
660 _uiDelegate->setDelegate(UIDelegate);
663 - (WKNavigation *)loadRequest:(NSURLRequest *)request
665 auto navigation = _page->loadRequest(request);
669 return [wrapper(*navigation.leakRef()) autorelease];
672 - (WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL
674 if (![URL isFileURL])
675 [NSException raise:NSInvalidArgumentException format:@"%@ is not a file URL", URL];
677 if (![readAccessURL isFileURL])
678 [NSException raise:NSInvalidArgumentException format:@"%@ is not a file URL", readAccessURL];
680 auto navigation = _page->loadFile([URL _web_originalDataAsWTFString], [readAccessURL _web_originalDataAsWTFString]);
684 return [wrapper(*navigation.leakRef()) autorelease];
687 - (WKNavigation *)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
689 NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
691 return [self loadData:data MIMEType:@"text/html" characterEncodingName:@"UTF-8" baseURL:baseURL];
694 - (WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL
696 auto navigation = _page->loadData(API::Data::createWithoutCopying(data).ptr(), MIMEType, characterEncodingName, baseURL.absoluteString);
700 return [wrapper(*navigation.leakRef()) autorelease];
703 - (WKNavigation *)goToBackForwardListItem:(WKBackForwardListItem *)item
705 auto navigation = _page->goToBackForwardItem(&item._item);
709 return [wrapper(*navigation.leakRef()) autorelease];
714 return _page->pageLoadState().title();
719 return [NSURL _web_URLWithWTFString:_page->pageLoadState().activeURL()];
724 return _page->pageLoadState().isLoading();
727 - (double)estimatedProgress
729 return _page->pageLoadState().estimatedProgress();
732 - (BOOL)hasOnlySecureContent
734 return _page->pageLoadState().hasOnlySecureContent();
737 - (SecTrustRef)serverTrust
739 #if HAVE(SEC_TRUST_SERIALIZATION)
740 auto certificateInfo = _page->pageLoadState().certificateInfo();
741 if (!certificateInfo)
744 return certificateInfo->certificateInfo().trust();
752 return _page->pageLoadState().canGoBack();
757 return _page->pageLoadState().canGoForward();
760 - (WKNavigation *)goBack
762 auto navigation = _page->goBack();
766 return [wrapper(*navigation.leakRef()) autorelease];
769 - (WKNavigation *)goForward
771 auto navigation = _page->goForward();
775 return [wrapper(*navigation.leakRef()) autorelease];
778 - (WKNavigation *)reload
780 const bool reloadFromOrigin = false;
781 const bool contentBlockersEnabled = true;
782 auto navigation = _page->reload(reloadFromOrigin, contentBlockersEnabled);
786 return [wrapper(*navigation.leakRef()) autorelease];
789 - (WKNavigation *)reloadFromOrigin
791 const bool reloadFromOrigin = true;
792 const bool contentBlockersEnabled = true;
793 auto navigation = _page->reload(reloadFromOrigin, contentBlockersEnabled);
797 return [wrapper(*navigation.leakRef()) autorelease];
802 _page->stopLoading();
805 static WKErrorCode callbackErrorCode(WebKit::CallbackBase::Error error)
808 case WebKit::CallbackBase::Error::None:
809 ASSERT_NOT_REACHED();
810 return WKErrorUnknown;
812 case WebKit::CallbackBase::Error::Unknown:
813 return WKErrorUnknown;
815 case WebKit::CallbackBase::Error::ProcessExited:
816 return WKErrorWebContentProcessTerminated;
818 case WebKit::CallbackBase::Error::OwnerWasInvalidated:
819 return WKErrorWebViewInvalidated;
823 - (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *))completionHandler
825 auto handler = adoptNS([completionHandler copy]);
827 _page->runJavaScriptInMainFrame(javaScriptString, [handler](API::SerializedScriptValue* serializedScriptValue, bool hadException, const WebCore::ExceptionDetails& details, WebKit::ScriptValueCallback::Error errorCode) {
831 if (errorCode != WebKit::ScriptValueCallback::Error::None) {
832 auto error = createNSError(callbackErrorCode(errorCode));
833 if (errorCode == WebKit::ScriptValueCallback::Error::OwnerWasInvalidated) {
834 // The OwnerWasInvalidated callback is synchronous. We don't want to call the block from within it
835 // because that can trigger re-entrancy bugs in WebKit.
836 // FIXME: It would be even better if GenericCallback did this for us.
837 dispatch_async(dispatch_get_main_queue(), [handler, error] {
838 auto rawHandler = (void (^)(id, NSError *))handler.get();
839 rawHandler(nil, error.get());
844 auto rawHandler = (void (^)(id, NSError *))handler.get();
845 rawHandler(nil, error.get());
849 auto rawHandler = (void (^)(id, NSError *))handler.get();
851 ASSERT(!serializedScriptValue);
853 RetainPtr<NSMutableDictionary> userInfo = adoptNS([[NSMutableDictionary alloc] init]);
855 [userInfo setObject:localizedDescriptionForErrorCode(WKErrorJavaScriptExceptionOccurred) forKey:NSLocalizedDescriptionKey];
856 [userInfo setObject:static_cast<NSString *>(details.message) forKey:_WKJavaScriptExceptionMessageErrorKey];
857 [userInfo setObject:@(details.lineNumber) forKey:_WKJavaScriptExceptionLineNumberErrorKey];
858 [userInfo setObject:@(details.columnNumber) forKey:_WKJavaScriptExceptionColumnNumberErrorKey];
860 if (!details.sourceURL.isEmpty())
861 [userInfo setObject:[NSURL _web_URLWithWTFString:details.sourceURL] forKey:_WKJavaScriptExceptionSourceURLErrorKey];
863 rawHandler(nil, adoptNS([[NSError alloc] initWithDomain:WKErrorDomain code:WKErrorJavaScriptExceptionOccurred userInfo:userInfo.get()]).get());
867 if (!serializedScriptValue) {
868 rawHandler(nil, createNSError(WKErrorJavaScriptResultTypeIsUnsupported).get());
872 id body = API::SerializedScriptValue::deserialize(*serializedScriptValue->internalRepresentation(), 0);
873 rawHandler(body, nil);
877 - (NSString *)customUserAgent
879 return _page->customUserAgent();
882 - (void)setCustomUserAgent:(NSString *)customUserAgent
884 _page->setCustomUserAgent(customUserAgent);
887 - (WKPageRef)_pageForTesting
889 return toAPI(_page.get());
892 - (BOOL)allowsLinkPreview
895 return _impl->allowsLinkPreview();
897 return _allowsLinkPreview;
901 - (void)setAllowsLinkPreview:(BOOL)allowsLinkPreview
904 _impl->setAllowsLinkPreview(allowsLinkPreview);
907 if (_allowsLinkPreview == allowsLinkPreview)
910 _allowsLinkPreview = allowsLinkPreview;
912 #if HAVE(LINK_PREVIEW)
913 if (_allowsLinkPreview)
914 [_contentView _registerPreview];
916 [_contentView _unregisterPreview];
917 #endif // HAVE(LINK_PREVIEW)
918 #endif // PLATFORM(IOS)
921 #pragma mark iOS-specific methods
925 - (BOOL)_isBackground
927 if ([self _isDisplayingPDF])
928 return [(WKPDFView *)_customContentView isBackground];
930 return [_contentView isBackground];
933 - (void)setFrame:(CGRect)frame
935 CGRect oldFrame = self.frame;
936 [super setFrame:frame];
938 if (!CGSizeEqualToSize(oldFrame.size, frame.size))
939 [self _frameOrBoundsChanged];
942 - (void)setBounds:(CGRect)bounds
944 CGRect oldBounds = self.bounds;
945 [super setBounds:bounds];
946 [_customContentFixedOverlayView setFrame:self.bounds];
948 if (!CGSizeEqualToSize(oldBounds.size, bounds.size))
949 [self _frameOrBoundsChanged];
952 - (void)layoutSubviews
954 [super layoutSubviews];
955 [self _frameOrBoundsChanged];
958 - (UIScrollView *)scrollView
960 return _scrollView.get();
963 - (WKBrowsingContextController *)browsingContextController
965 return [_contentView browsingContextController];
968 - (BOOL)becomeFirstResponder
970 return [self._currentContentView becomeFirstResponder] || [super becomeFirstResponder];
973 - (BOOL)canBecomeFirstResponder
975 if (self._currentContentView == _contentView && [_contentView isResigningFirstResponder])
980 static inline CGFloat floorToDevicePixel(CGFloat input, float deviceScaleFactor)
982 return CGFloor(input * deviceScaleFactor) / deviceScaleFactor;
985 static inline bool pointsEqualInDevicePixels(CGPoint a, CGPoint b, float deviceScaleFactor)
987 return fabs(a.x * deviceScaleFactor - b.x * deviceScaleFactor) < std::numeric_limits<float>::epsilon()
988 && fabs(a.y * deviceScaleFactor - b.y * deviceScaleFactor) < std::numeric_limits<float>::epsilon();
991 static CGSize roundScrollViewContentSize(const WebKit::WebPageProxy& page, CGSize contentSize)
993 float deviceScaleFactor = page.deviceScaleFactor();
994 return CGSizeMake(floorToDevicePixel(contentSize.width, deviceScaleFactor), floorToDevicePixel(contentSize.height, deviceScaleFactor));
997 - (UIView *)_currentContentView
999 return _customContentView ? _customContentView.get() : _contentView.get();
1002 - (WKWebViewContentProviderRegistry *)_contentProviderRegistry
1004 return [_configuration _contentProviderRegistry];
1007 - (WKSelectionGranularity)_selectionGranularity
1009 return [_configuration selectionGranularity];
1012 - (void)_setHasCustomContentView:(BOOL)pageHasCustomContentView loadedMIMEType:(const WTF::String&)mimeType
1014 if (pageHasCustomContentView) {
1015 [_customContentView removeFromSuperview];
1016 [_customContentFixedOverlayView removeFromSuperview];
1018 Class representationClass = [[_configuration _contentProviderRegistry] providerForMIMEType:mimeType];
1019 ASSERT(representationClass);
1020 _customContentView = adoptNS([[representationClass alloc] web_initWithFrame:self.bounds webView:self]);
1021 _customContentFixedOverlayView = adoptNS([[UIView alloc] initWithFrame:self.bounds]);
1022 [_customContentFixedOverlayView setUserInteractionEnabled:NO];
1024 [[_contentView unscaledView] removeFromSuperview];
1025 [_contentView removeFromSuperview];
1026 [_scrollView addSubview:_customContentView.get()];
1027 [self addSubview:_customContentFixedOverlayView.get()];
1029 [_customContentView web_setMinimumSize:self.bounds.size];
1030 [_customContentView web_setFixedOverlayView:_customContentFixedOverlayView.get()];
1031 } else if (_customContentView) {
1032 [_customContentView removeFromSuperview];
1033 _customContentView = nullptr;
1035 [_customContentFixedOverlayView removeFromSuperview];
1036 _customContentFixedOverlayView = nullptr;
1038 [_scrollView addSubview:_contentView.get()];
1039 [_scrollView addSubview:[_contentView unscaledView]];
1040 [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
1042 [_customContentFixedOverlayView setFrame:self.bounds];
1043 [self addSubview:_customContentFixedOverlayView.get()];
1046 if (self.isFirstResponder && self._currentContentView.canBecomeFirstResponder)
1047 [self._currentContentView becomeFirstResponder];
1050 - (void)_didFinishLoadingDataForCustomContentProviderWithSuggestedFilename:(const String&)suggestedFilename data:(NSData *)data
1052 ASSERT(_customContentView);
1053 [_customContentView web_setContentProviderData:data suggestedFilename:suggestedFilename];
1055 // FIXME: It may make more sense for custom content providers to invoke this when they're ready,
1056 // because there's no guarantee that all custom content providers will lay out synchronously.
1057 _page->didLayoutForCustomContentProvider();
1060 - (void)_willInvokeUIScrollViewDelegateCallback
1062 _delayUpdateVisibleContentRects = YES;
1065 - (void)_didInvokeUIScrollViewDelegateCallback
1067 _delayUpdateVisibleContentRects = NO;
1068 if (_hadDelayedUpdateVisibleContentRects) {
1069 _hadDelayedUpdateVisibleContentRects = NO;
1070 [self _updateVisibleContentRectAfterScrollInView:_scrollView.get()];
1074 static CGFloat contentZoomScale(WKWebView *webView)
1076 CGFloat scale = webView._currentContentView.layer.affineTransform.a;
1077 ASSERT(scale == [webView->_scrollView zoomScale]);
1081 static WebCore::Color baseScrollViewBackgroundColor(WKWebView *webView)
1083 if (webView->_customContentView)
1084 return [webView->_customContentView backgroundColor].CGColor;
1086 if (webView->_gestureController) {
1087 WebCore::Color color = webView->_gestureController->backgroundColorForCurrentSnapshot();
1088 if (color.isValid())
1092 return webView->_page->pageExtendedBackgroundColor();
1095 static WebCore::Color scrollViewBackgroundColor(WKWebView *webView)
1097 if (!webView.opaque)
1098 return WebCore::Color::transparent;
1100 WebCore::Color color = baseScrollViewBackgroundColor(webView);
1102 if (!color.isValid())
1103 color = WebCore::Color::white;
1105 CGFloat zoomScale = contentZoomScale(webView);
1106 CGFloat minimumZoomScale = [webView->_scrollView minimumZoomScale];
1107 if (zoomScale < minimumZoomScale) {
1109 CGFloat opacity = std::max<CGFloat>(1 - slope * (minimumZoomScale - zoomScale), 0);
1110 color = WebCore::colorWithOverrideAlpha(color.rgb(), opacity);
1116 - (void)_updateScrollViewBackground
1118 WebCore::Color color = scrollViewBackgroundColor(self);
1120 if (_scrollViewBackgroundColor == color)
1123 _scrollViewBackgroundColor = color;
1125 auto uiBackgroundColor = adoptNS([[UIColor alloc] initWithCGColor:cachedCGColor(color)]);
1126 [_scrollView setBackgroundColor:uiBackgroundColor.get()];
1128 // Update the indicator style based on the lightness/darkness of the background color.
1129 double hue, saturation, lightness;
1130 color.getHSL(hue, saturation, lightness);
1131 if (lightness <= .5 && color.alpha() > 0)
1132 [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleWhite];
1134 [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleDefault];
1137 - (CGPoint)_adjustedContentOffset:(CGPoint)point
1139 CGPoint result = point;
1140 UIEdgeInsets contentInset = [self _computedContentInset];
1142 result.x -= contentInset.left;
1143 result.y -= contentInset.top;
1148 - (UIEdgeInsets)_computedContentInset
1150 if (_haveSetObscuredInsets)
1151 return _obscuredInsets;
1153 return [_scrollView contentInset];
1156 - (void)_processDidExit
1158 if (!_customContentView && _dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
1159 NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
1160 [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
1161 [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
1162 [_resizeAnimationView removeFromSuperview];
1163 _resizeAnimationView = nil;
1165 _resizeAnimationTransformAdjustments = CATransform3DIdentity;
1167 [_contentView setFrame:self.bounds];
1168 [_scrollView setBackgroundColor:[UIColor whiteColor]];
1169 [_scrollView setContentOffset:[self _adjustedContentOffset:CGPointZero]];
1170 [_scrollView setZoomScale:1];
1172 _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
1173 _initialScaleFactor = 1;
1174 _hasCommittedLoadForMainFrame = NO;
1175 _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1176 _dynamicViewportUpdateMode = DynamicViewportUpdateMode::NotResizing;
1177 [_contentView setHidden:NO];
1178 _needsToRestoreScrollPosition = NO;
1179 _needsToRestoreUnobscuredCenter = NO;
1180 _scrollViewBackgroundColor = WebCore::Color();
1181 _delayUpdateVisibleContentRects = NO;
1182 _hadDelayedUpdateVisibleContentRects = NO;
1185 - (void)_didCommitLoadForMainFrame
1187 _firstPaintAfterCommitLoadTransactionID = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1189 _hasCommittedLoadForMainFrame = YES;
1190 _needsResetViewStateAfterCommitLoadForMainFrame = YES;
1193 static CGPoint contentOffsetBoundedInValidRange(UIScrollView *scrollView, CGPoint contentOffset)
1195 UIEdgeInsets contentInsets = scrollView.contentInset;
1196 CGSize contentSize = scrollView.contentSize;
1197 CGSize scrollViewSize = scrollView.bounds.size;
1199 CGFloat maxHorizontalOffset = contentSize.width + contentInsets.right - scrollViewSize.width;
1200 contentOffset.x = std::min(maxHorizontalOffset, contentOffset.x);
1201 contentOffset.x = std::max(-contentInsets.left, contentOffset.x);
1203 CGFloat maxVerticalOffset = contentSize.height + contentInsets.bottom - scrollViewSize.height;
1204 contentOffset.y = std::min(maxVerticalOffset, contentOffset.y);
1205 contentOffset.y = std::max(-contentInsets.top, contentOffset.y);
1206 return contentOffset;
1209 static void changeContentOffsetBoundedInValidRange(UIScrollView *scrollView, WebCore::FloatPoint contentOffset)
1211 scrollView.contentOffset = contentOffsetBoundedInValidRange(scrollView, contentOffset);
1214 - (WebCore::FloatRect)visibleRectInViewCoordinates
1216 WebCore::FloatRect bounds = self.bounds;
1217 bounds.moveBy([_scrollView contentOffset]);
1218 WebCore::FloatRect contentViewBounds = [_contentView bounds];
1219 bounds.intersect(contentViewBounds);
1223 // WebCore stores the page scale factor as float instead of double. When we get a scale from WebCore,
1224 // we need to ignore differences that are within a small rounding error on floats.
1225 static inline bool areEssentiallyEqualAsFloat(float a, float b)
1227 return WTF::areEssentiallyEqual(a, b);
1230 - (void)_didCommitLayerTree:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
1232 if (_customContentView)
1235 if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
1236 if (_resizeAnimationTransformTransactionID && layerTreeTransaction.transactionID() >= _resizeAnimationTransformTransactionID.value()) {
1237 _resizeAnimationTransformTransactionID = Nullopt;
1238 [_resizeAnimationView layer].sublayerTransform = _resizeAnimationTransformAdjustments;
1239 if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::ResizingWithDocumentHidden) {
1240 [_contentView setHidden:NO];
1241 [self _endAnimatedResize];
1247 CGSize newContentSize = roundScrollViewContentSize(*_page, [_contentView frame].size);
1248 [_scrollView _setContentSizePreservingContentOffsetDuringRubberband:newContentSize];
1250 [_scrollView setMinimumZoomScale:layerTreeTransaction.minimumScaleFactor()];
1251 [_scrollView setMaximumZoomScale:layerTreeTransaction.maximumScaleFactor()];
1252 [_scrollView setZoomEnabled:layerTreeTransaction.allowsUserScaling()];
1253 if (!layerTreeTransaction.scaleWasSetByUIProcess() && ![_scrollView isZooming] && ![_scrollView isZoomBouncing] && ![_scrollView _isAnimatingZoom])
1254 [_scrollView setZoomScale:layerTreeTransaction.pageScaleFactor()];
1256 _viewportMetaTagWidth = layerTreeTransaction.viewportMetaTagWidth();
1257 _viewportMetaTagWidthWasExplicit = layerTreeTransaction.viewportMetaTagWidthWasExplicit();
1258 _viewportMetaTagCameFromImageDocument = layerTreeTransaction.viewportMetaTagCameFromImageDocument();
1259 _initialScaleFactor = layerTreeTransaction.initialScaleFactor();
1260 if (![_contentView _mayDisableDoubleTapGesturesDuringSingleTap])
1261 [_contentView _setDoubleTapGesturesEnabled:self._allowsDoubleTapGestures];
1263 [self _updateScrollViewBackground];
1265 if (_gestureController)
1266 _gestureController->setRenderTreeSize(layerTreeTransaction.renderTreeSize());
1268 if (_needsResetViewStateAfterCommitLoadForMainFrame && layerTreeTransaction.transactionID() >= _firstPaintAfterCommitLoadTransactionID) {
1269 _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1270 [_scrollView setContentOffset:[self _adjustedContentOffset:CGPointZero]];
1271 [self _updateVisibleContentRects];
1272 if (_observedRenderingProgressEvents & _WKRenderingProgressEventFirstPaint)
1273 _navigationState->didFirstPaint();
1276 bool isTransactionAfterPageRestore = layerTreeTransaction.transactionID() >= _firstTransactionIDAfterPageRestore;
1278 if (_needsToRestoreScrollPosition && isTransactionAfterPageRestore) {
1279 _needsToRestoreScrollPosition = NO;
1281 if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1282 WebCore::FloatPoint scaledScrollOffset = _scrollOffsetToRestore;
1283 scaledScrollOffset.scale(_scaleToRestore, _scaleToRestore);
1284 WebCore::FloatPoint contentOffsetInScrollViewCoordinates = scaledScrollOffset - _obscuredInsetWhenSaved;
1286 changeContentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
1287 _commitDidRestoreScrollPosition = YES;
1289 if (_gestureController)
1290 _gestureController->didRestoreScrollPosition();
1292 [self _updateVisibleContentRects];
1295 if (_needsToRestoreUnobscuredCenter && isTransactionAfterPageRestore) {
1296 _needsToRestoreUnobscuredCenter = NO;
1298 if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1299 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, _obscuredInsets);
1300 WebCore::FloatSize unobscuredContentSizeAtNewScale(unobscuredRect.size.width / _scaleToRestore, unobscuredRect.size.height / _scaleToRestore);
1301 WebCore::FloatPoint topLeftInDocumentCoordinates(_unobscuredCenterToRestore.x() - unobscuredContentSizeAtNewScale.width() / 2, _unobscuredCenterToRestore.y() - unobscuredContentSizeAtNewScale.height() / 2);
1303 topLeftInDocumentCoordinates.scale(_scaleToRestore, _scaleToRestore);
1304 topLeftInDocumentCoordinates.moveBy(WebCore::FloatPoint(-_obscuredInsets.left, -_obscuredInsets.top));
1306 changeContentOffsetBoundedInValidRange(_scrollView.get(), topLeftInDocumentCoordinates);
1307 if (_gestureController)
1308 _gestureController->didRestoreScrollPosition();
1310 [self _updateVisibleContentRects];
1313 if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
1314 scrollPerfData->didCommitLayerTree([self visibleRectInViewCoordinates]);
1317 - (void)_layerTreeCommitComplete
1319 _commitDidRestoreScrollPosition = NO;
1322 - (void)_dynamicViewportUpdateChangedTargetToScale:(double)newScale position:(CGPoint)newScrollPosition nextValidLayerTreeTransactionID:(uint64_t)nextValidLayerTreeTransactionID
1324 if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
1325 CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
1326 double currentTargetScale = animatingScaleTarget * [[_contentView layer] transform].m11;
1327 double scale = newScale / currentTargetScale;
1328 _resizeAnimationTransformAdjustments = CATransform3DMakeScale(scale, scale, 1);
1330 CGPoint newContentOffset = [self _adjustedContentOffset:CGPointMake(newScrollPosition.x * newScale, newScrollPosition.y * newScale)];
1331 CGPoint currentContentOffset = [_scrollView contentOffset];
1333 _resizeAnimationTransformAdjustments.m41 = (currentContentOffset.x - newContentOffset.x) / animatingScaleTarget;
1334 _resizeAnimationTransformAdjustments.m42 = (currentContentOffset.y - newContentOffset.y) / animatingScaleTarget;
1335 _resizeAnimationTransformTransactionID = nextValidLayerTreeTransactionID;
1339 - (void)_couldNotRestorePageState
1341 // The gestureController may be waiting for the scroll position to be restored
1342 // in order to remove the swipe snapshot. Since the scroll position could not be
1343 // restored, tell the gestureController it was restored so that it no longer waits
1345 if (_gestureController)
1346 _gestureController->didRestoreScrollPosition();
1349 - (void)_restorePageScrollPosition:(WebCore::FloatPoint)scrollPosition scrollOrigin:(WebCore::FloatPoint)scrollOrigin previousObscuredInset:(WebCore::FloatSize)obscuredInset scale:(double)scale
1351 if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1354 if (_customContentView)
1357 _needsToRestoreUnobscuredCenter = NO;
1358 _needsToRestoreScrollPosition = YES;
1359 _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1361 _scrollOffsetToRestore = WebCore::ScrollableArea::scrollOffsetFromPosition(WebCore::FloatPoint(scrollPosition), WebCore::toFloatSize(scrollOrigin));
1362 _obscuredInsetWhenSaved = obscuredInset;
1363 _scaleToRestore = scale;
1366 - (void)_restorePageStateToUnobscuredCenter:(WebCore::FloatPoint)center scale:(double)scale
1368 if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1371 if (_customContentView)
1374 _needsToRestoreScrollPosition = NO;
1375 _needsToRestoreUnobscuredCenter = YES;
1376 _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1377 _unobscuredCenterToRestore = center;
1378 _scaleToRestore = scale;
1381 - (PassRefPtr<WebKit::ViewSnapshot>)_takeViewSnapshot
1383 float deviceScale = WebCore::screenScaleFactor();
1384 WebCore::FloatSize snapshotSize(self.bounds.size);
1385 snapshotSize.scale(deviceScale, deviceScale);
1387 CATransform3D transform = CATransform3DMakeScale(deviceScale, deviceScale, 1);
1390 WebCore::IOSurface::Format snapshotFormat = WebCore::screenSupportsExtendedColor() ? WebCore::IOSurface::Format::RGB10 : WebCore::IOSurface::Format::RGBA;
1391 auto surface = WebCore::IOSurface::create(WebCore::expandedIntSize(snapshotSize), WebCore::sRGBColorSpaceRef(), snapshotFormat);
1394 CARenderServerRenderLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, reinterpret_cast<uint64_t>(self.layer), surface->surface(), 0, 0, &transform);
1396 WebCore::IOSurface::Format compressedFormat = WebCore::IOSurface::Format::YUV422;
1397 if (WebCore::IOSurface::allowConversionFromFormatToFormat(snapshotFormat, compressedFormat)) {
1398 RefPtr<WebKit::ViewSnapshot> viewSnapshot = WebKit::ViewSnapshot::create(nullptr);
1399 WebCore::IOSurface::convertToFormat(WTFMove(surface), WebCore::IOSurface::Format::YUV422, [viewSnapshot](std::unique_ptr<WebCore::IOSurface> convertedSurface) {
1400 if (convertedSurface)
1401 viewSnapshot->setSurface(WTFMove(convertedSurface));
1404 return viewSnapshot;
1407 return WebKit::ViewSnapshot::create(WTFMove(surface));
1409 uint32_t slotID = [WebKit::ViewSnapshotStore::snapshottingContext() createImageSlot:snapshotSize hasAlpha:YES];
1414 CARenderServerCaptureLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, (uint64_t)self.layer, slotID, 0, 0, &transform);
1415 WebCore::IntSize imageSize = WebCore::expandedIntSize(WebCore::FloatSize(snapshotSize));
1416 return WebKit::ViewSnapshot::create(slotID, imageSize, imageSize.width() * imageSize.height() * 4);
1420 - (void)_zoomToPoint:(WebCore::FloatPoint)point atScale:(double)scale animated:(BOOL)animated
1422 CFTimeInterval duration = 0;
1423 CGFloat zoomScale = contentZoomScale(self);
1426 const double maximumZoomDuration = 0.4;
1427 const double minimumZoomDuration = 0.1;
1428 const double zoomDurationFactor = 0.3;
1430 duration = std::min(fabs(log(zoomScale) - log(scale)) * zoomDurationFactor + minimumZoomDuration, maximumZoomDuration);
1433 if (scale != zoomScale)
1434 _page->willStartUserTriggeredZooming();
1436 LOG_WITH_STREAM(VisibleRects, stream << "_zoomToPoint:" << point << " scale: " << scale << " duration:" << duration);
1438 [_scrollView _zoomToCenter:point scale:scale duration:duration];
1441 - (void)_zoomToRect:(WebCore::FloatRect)targetRect atScale:(double)scale origin:(WebCore::FloatPoint)origin animated:(BOOL)animated
1443 // FIXME: Some of this could be shared with _scrollToRect.
1444 const double visibleRectScaleChange = contentZoomScale(self) / scale;
1445 const WebCore::FloatRect visibleRect([self convertRect:self.bounds toView:self._currentContentView]);
1446 const WebCore::FloatRect unobscuredRect([self _contentRectForUserInteraction]);
1448 const WebCore::FloatSize topLeftObscuredInsetAfterZoom((unobscuredRect.minXMinYCorner() - visibleRect.minXMinYCorner()) * visibleRectScaleChange);
1449 const WebCore::FloatSize bottomRightObscuredInsetAfterZoom((visibleRect.maxXMaxYCorner() - unobscuredRect.maxXMaxYCorner()) * visibleRectScaleChange);
1451 const WebCore::FloatSize unobscuredRectSizeAfterZoom(unobscuredRect.size() * visibleRectScaleChange);
1453 // Center to the target rect.
1454 WebCore::FloatPoint unobscuredRectLocationAfterZoom = targetRect.location() - (unobscuredRectSizeAfterZoom - targetRect.size()) * 0.5;
1456 // Center to the tap point instead in case the target rect won't fit in a direction.
1457 if (targetRect.width() > unobscuredRectSizeAfterZoom.width())
1458 unobscuredRectLocationAfterZoom.setX(origin.x() - unobscuredRectSizeAfterZoom.width() / 2);
1459 if (targetRect.height() > unobscuredRectSizeAfterZoom.height())
1460 unobscuredRectLocationAfterZoom.setY(origin.y() - unobscuredRectSizeAfterZoom.height() / 2);
1462 // We have computed where we want the unobscured rect to be. Now adjust for the obscuring insets.
1463 WebCore::FloatRect visibleRectAfterZoom(unobscuredRectLocationAfterZoom, unobscuredRectSizeAfterZoom);
1464 visibleRectAfterZoom.move(-topLeftObscuredInsetAfterZoom);
1465 visibleRectAfterZoom.expand(topLeftObscuredInsetAfterZoom + bottomRightObscuredInsetAfterZoom);
1467 [self _zoomToPoint:visibleRectAfterZoom.center() atScale:scale animated:animated];
1470 static WebCore::FloatPoint constrainContentOffset(WebCore::FloatPoint contentOffset, WebCore::FloatSize contentSize, WebCore::FloatSize unobscuredContentSize)
1472 WebCore::FloatSize maximumContentOffset = contentSize - unobscuredContentSize;
1473 return contentOffset.constrainedBetween(WebCore::FloatPoint(), WebCore::FloatPoint(maximumContentOffset));
1476 - (void)_scrollToContentScrollPosition:(WebCore::FloatPoint)scrollPosition scrollOrigin:(WebCore::IntPoint)scrollOrigin
1478 if (_commitDidRestoreScrollPosition || _dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1481 WebCore::FloatPoint contentOffset = WebCore::ScrollableArea::scrollOffsetFromPosition(scrollPosition, toFloatSize(scrollOrigin));
1483 WebCore::FloatPoint scaledOffset = contentOffset;
1484 CGFloat zoomScale = contentZoomScale(self);
1485 scaledOffset.scale(zoomScale, zoomScale);
1487 CGPoint contentOffsetInScrollViewCoordinates = [self _adjustedContentOffset:scaledOffset];
1488 contentOffsetInScrollViewCoordinates = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
1490 [_scrollView _stopScrollingAndZoomingAnimations];
1492 if (!CGPointEqualToPoint(contentOffsetInScrollViewCoordinates, [_scrollView contentOffset]))
1493 [_scrollView setContentOffset:contentOffsetInScrollViewCoordinates];
1495 // If we haven't changed anything, there would not be any VisibleContentRect update sent to the content.
1496 // The WebProcess would keep the invalid contentOffset as its scroll position.
1497 // To synchronize the WebProcess with what is on screen, we send the VisibleContentRect again.
1498 _page->resendLastVisibleContentRects();
1502 - (BOOL)_scrollToRect:(WebCore::FloatRect)targetRect origin:(WebCore::FloatPoint)origin minimumScrollDistance:(float)minimumScrollDistance
1504 WebCore::FloatRect unobscuredContentRect([self _contentRectForUserInteraction]);
1505 WebCore::FloatPoint unobscuredContentOffset = unobscuredContentRect.location();
1506 WebCore::FloatSize contentSize([self._currentContentView bounds].size);
1508 // Center the target rect in the scroll view.
1509 // If the target doesn't fit in the scroll view, center on the gesture location instead.
1510 WebCore::FloatPoint newUnobscuredContentOffset;
1511 if (targetRect.width() <= unobscuredContentRect.width())
1512 newUnobscuredContentOffset.setX(targetRect.x() - (unobscuredContentRect.width() - targetRect.width()) / 2);
1514 newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
1515 if (targetRect.height() <= unobscuredContentRect.height())
1516 newUnobscuredContentOffset.setY(targetRect.y() - (unobscuredContentRect.height() - targetRect.height()) / 2);
1518 newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
1519 newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
1521 if (unobscuredContentOffset == newUnobscuredContentOffset) {
1522 if (targetRect.width() > unobscuredContentRect.width())
1523 newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
1524 if (targetRect.height() > unobscuredContentRect.height())
1525 newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
1526 newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
1529 WebCore::FloatSize scrollViewOffsetDelta = newUnobscuredContentOffset - unobscuredContentOffset;
1530 scrollViewOffsetDelta.scale(contentZoomScale(self));
1532 float scrollDistance = scrollViewOffsetDelta.diagonalLength();
1533 if (scrollDistance < minimumScrollDistance)
1536 [_contentView willStartZoomOrScroll];
1538 LOG_WITH_STREAM(VisibleRects, stream << "_scrollToRect: scrolling to " << [_scrollView contentOffset] + scrollViewOffsetDelta);
1540 [_scrollView setContentOffset:([_scrollView contentOffset] + scrollViewOffsetDelta) animated:YES];
1544 - (void)_scrollByContentOffset:(WebCore::FloatPoint)contentOffsetDelta
1546 WebCore::FloatPoint scaledOffsetDelta = contentOffsetDelta;
1547 CGFloat zoomScale = contentZoomScale(self);
1548 scaledOffsetDelta.scale(zoomScale, zoomScale);
1550 CGPoint currentOffset = [_scrollView _isAnimatingScroll] ? [_scrollView _animatedTargetOffset] : [_scrollView contentOffset];
1551 CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), currentOffset + scaledOffsetDelta);
1553 if (CGPointEqualToPoint(boundedOffset, currentOffset))
1555 [_contentView willStartZoomOrScroll];
1557 LOG_WITH_STREAM(VisibleRects, stream << "_scrollByContentOffset: scrolling to " << boundedOffset);
1559 [_scrollView setContentOffset:boundedOffset animated:YES];
1562 - (void)_zoomOutWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
1564 [self _zoomToPoint:origin atScale:[_scrollView minimumZoomScale] animated:animated];
1567 - (void)_zoomToInitialScaleWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
1569 ASSERT(_initialScaleFactor > 0);
1570 [self _zoomToPoint:origin atScale:_initialScaleFactor animated:animated];
1573 // focusedElementRect and selectionRect are both in document coordinates.
1574 - (void)_zoomToFocusRect:(WebCore::FloatRect)focusedElementRectInDocumentCoordinates selectionRect:(WebCore::FloatRect)selectionRectInDocumentCoordinates fontSize:(float)fontSize minimumScale:(double)minimumScale maximumScale:(double)maximumScale allowScaling:(BOOL)allowScaling forceScroll:(BOOL)forceScroll
1576 const double WKWebViewStandardFontSize = 16;
1577 const double kMinimumHeightToShowContentAboveKeyboard = 106;
1578 const CFTimeInterval UIWebFormAnimationDuration = 0.25;
1579 const double CaretOffsetFromWindowEdge = 20;
1581 // Zoom around the element's bounding frame. We use a "standard" size to determine the proper frame.
1582 double scale = allowScaling ? std::min(std::max(WKWebViewStandardFontSize / fontSize, minimumScale), maximumScale) : contentZoomScale(self);
1583 CGFloat documentWidth = [_contentView bounds].size.width;
1584 scale = CGRound(documentWidth * scale) / documentWidth;
1586 UIWindow *window = [_scrollView window];
1588 WebCore::FloatRect focusedElementRectInNewScale = focusedElementRectInDocumentCoordinates;
1589 focusedElementRectInNewScale.scale(scale);
1590 focusedElementRectInNewScale.moveBy([_contentView frame].origin);
1592 // Find the portion of the view that is visible on the screen.
1593 UIViewController *topViewController = [[[_scrollView _viewControllerForAncestor] _rootAncestorViewController] _viewControllerForSupportedInterfaceOrientations];
1594 UIView *fullScreenView = topViewController.view;
1595 if (!fullScreenView)
1596 fullScreenView = window;
1598 CGRect unobscuredScrollViewRectInWebViewCoordinates = UIEdgeInsetsInsetRect([self bounds], _obscuredInsets);
1599 CGRect visibleScrollViewBoundsInWebViewCoordinates = CGRectIntersection(unobscuredScrollViewRectInWebViewCoordinates, [fullScreenView convertRect:[fullScreenView bounds] toView:self]);
1600 CGRect formAssistantFrameInWebViewCoordinates = [window convertRect:_inputViewBounds toView:self];
1601 CGRect intersectionBetweenScrollViewAndFormAssistant = CGRectIntersection(visibleScrollViewBoundsInWebViewCoordinates, formAssistantFrameInWebViewCoordinates);
1602 CGSize visibleSize = visibleScrollViewBoundsInWebViewCoordinates.size;
1604 CGFloat visibleOffsetFromTop = 0;
1605 if (!CGRectIsEmpty(intersectionBetweenScrollViewAndFormAssistant)) {
1606 CGFloat heightVisibleAboveFormAssistant = CGRectGetMinY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
1607 CGFloat heightVisibleBelowFormAssistant = CGRectGetMaxY(visibleScrollViewBoundsInWebViewCoordinates) - CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant);
1609 if (heightVisibleAboveFormAssistant >= kMinimumHeightToShowContentAboveKeyboard || heightVisibleBelowFormAssistant < heightVisibleAboveFormAssistant)
1610 visibleSize.height = heightVisibleAboveFormAssistant;
1612 visibleSize.height = heightVisibleBelowFormAssistant;
1613 visibleOffsetFromTop = CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
1617 BOOL selectionRectIsNotNull = !selectionRectInDocumentCoordinates.isZero();
1619 CGRect currentlyVisibleRegionInWebViewCoordinates;
1620 currentlyVisibleRegionInWebViewCoordinates.origin = unobscuredScrollViewRectInWebViewCoordinates.origin;
1621 currentlyVisibleRegionInWebViewCoordinates.origin.y += visibleOffsetFromTop;
1622 currentlyVisibleRegionInWebViewCoordinates.size = visibleSize;
1624 // Don't bother scrolling if the entire node is already visible, whether or not we got a selectionRect.
1625 if (CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:focusedElementRectInDocumentCoordinates fromView:_contentView.get()]))
1628 // Don't bother scrolling if we have a valid selectionRect and it is already visible.
1629 if (selectionRectIsNotNull && CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:selectionRectInDocumentCoordinates fromView:_contentView.get()]))
1633 // We want to zoom to the left/top corner of the DOM node, with as much spacing on all sides as we
1634 // can get based on the visible area after zooming (workingFrame). The spacing in either dimension is half the
1635 // difference between the size of the DOM node and the size of the visible frame.
1636 CGFloat horizontalSpaceInWebViewCoordinates = std::max((visibleSize.width - focusedElementRectInNewScale.width()) / 2.0, 0.0);
1637 CGFloat verticalSpaceInWebViewCoordinates = std::max((visibleSize.height - focusedElementRectInNewScale.height()) / 2.0, 0.0);
1640 topLeft.x = focusedElementRectInNewScale.x() - horizontalSpaceInWebViewCoordinates;
1641 topLeft.y = focusedElementRectInNewScale.y() - verticalSpaceInWebViewCoordinates - visibleOffsetFromTop;
1643 CGFloat minimumAllowableHorizontalOffsetInWebViewCoordinates = -INFINITY;
1644 CGFloat minimumAllowableVerticalOffsetInWebViewCoordinates = -INFINITY;
1645 if (selectionRectIsNotNull) {
1646 WebCore::FloatRect selectionRectInNewScale = selectionRectInDocumentCoordinates;
1647 selectionRectInNewScale.scale(scale);
1648 selectionRectInNewScale.moveBy([_contentView frame].origin);
1649 minimumAllowableHorizontalOffsetInWebViewCoordinates = CGRectGetMaxX(selectionRectInNewScale) + CaretOffsetFromWindowEdge - visibleSize.width;
1650 minimumAllowableVerticalOffsetInWebViewCoordinates = CGRectGetMaxY(selectionRectInNewScale) + CaretOffsetFromWindowEdge - visibleSize.height - visibleOffsetFromTop;
1653 WebCore::FloatRect documentBoundsInNewScale = [_contentView bounds];
1654 documentBoundsInNewScale.scale(scale);
1655 documentBoundsInNewScale.moveBy([_contentView frame].origin);
1657 // Constrain the left edge in document coordinates so that:
1658 // - it isn't so small that the scrollVisibleRect isn't visible on the screen
1659 // - it isn't so great that the document's right edge is less than the right edge of the screen
1660 if (selectionRectIsNotNull && topLeft.x < minimumAllowableHorizontalOffsetInWebViewCoordinates)
1661 topLeft.x = minimumAllowableHorizontalOffsetInWebViewCoordinates;
1663 CGFloat maximumAllowableHorizontalOffset = CGRectGetMaxX(documentBoundsInNewScale) - visibleSize.width;
1664 if (topLeft.x > maximumAllowableHorizontalOffset)
1665 topLeft.x = maximumAllowableHorizontalOffset;
1668 // Constrain the top edge in document coordinates so that:
1669 // - it isn't so small that the scrollVisibleRect isn't visible on the screen
1670 // - it isn't so great that the document's bottom edge is higher than the top of the form assistant
1671 if (selectionRectIsNotNull && topLeft.y < minimumAllowableVerticalOffsetInWebViewCoordinates)
1672 topLeft.y = minimumAllowableVerticalOffsetInWebViewCoordinates;
1674 CGFloat maximumAllowableVerticalOffset = CGRectGetMaxY(documentBoundsInNewScale) - visibleSize.height;
1675 if (topLeft.y > maximumAllowableVerticalOffset)
1676 topLeft.y = maximumAllowableVerticalOffset;
1679 WebCore::FloatPoint newCenter = CGPointMake(topLeft.x + unobscuredScrollViewRectInWebViewCoordinates.size.width / 2.0, topLeft.y + unobscuredScrollViewRectInWebViewCoordinates.size.height / 2.0);
1681 if (scale != contentZoomScale(self))
1682 _page->willStartUserTriggeredZooming();
1684 LOG_WITH_STREAM(VisibleRects, stream << "_zoomToFocusRect: zooming to " << newCenter << " scale:" << scale);
1686 // The newCenter has been computed in the new scale, but _zoomToCenter expected the center to be in the original scale.
1687 newCenter.scale(1 / scale, 1 / scale);
1688 [_scrollView _zoomToCenter:newCenter
1690 duration:UIWebFormAnimationDuration
1694 - (CGFloat)_targetContentZoomScaleForRect:(const WebCore::FloatRect&)targetRect currentScale:(double)currentScale fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale
1696 WebCore::FloatSize unobscuredContentSize([self _contentRectForUserInteraction].size);
1697 double horizontalScale = unobscuredContentSize.width() * currentScale / targetRect.width();
1698 double verticalScale = unobscuredContentSize.height() * currentScale / targetRect.height();
1700 horizontalScale = std::min(std::max(horizontalScale, minimumScale), maximumScale);
1701 verticalScale = std::min(std::max(verticalScale, minimumScale), maximumScale);
1703 return fitEntireRect ? std::min(horizontalScale, verticalScale) : horizontalScale;
1706 - (BOOL)_zoomToRect:(WebCore::FloatRect)targetRect withOrigin:(WebCore::FloatPoint)origin fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale minimumScrollDistance:(float)minimumScrollDistance
1708 const float maximumScaleFactorDeltaForPanScroll = 0.02;
1710 double currentScale = contentZoomScale(self);
1711 double targetScale = [self _targetContentZoomScaleForRect:targetRect currentScale:currentScale fitEntireRect:fitEntireRect minimumScale:minimumScale maximumScale:maximumScale];
1713 if (fabs(targetScale - currentScale) < maximumScaleFactorDeltaForPanScroll) {
1714 if ([self _scrollToRect:targetRect origin:origin minimumScrollDistance:minimumScrollDistance])
1716 } else if (targetScale != currentScale) {
1717 [self _zoomToRect:targetRect atScale:targetScale origin:origin animated:YES];
1724 - (void)didMoveToWindow
1726 _page->viewStateDidChange(WebCore::ViewState::AllFlags);
1729 - (void)setOpaque:(BOOL)opaque
1731 BOOL oldOpaque = self.opaque;
1733 [super setOpaque:opaque];
1734 [_contentView setOpaque:opaque];
1736 if (oldOpaque == opaque)
1739 _page->setDrawsBackground(opaque);
1740 [self _updateScrollViewBackground];
1743 - (void)setBackgroundColor:(UIColor *)backgroundColor
1745 [super setBackgroundColor:backgroundColor];
1746 [_contentView setBackgroundColor:backgroundColor];
1749 - (BOOL)_allowsDoubleTapGestures
1751 if (_fastClickingIsDisabled)
1754 // If the page is not user scalable, we don't allow double tap gestures.
1755 if (![_scrollView isZoomEnabled] || [_scrollView minimumZoomScale] >= [_scrollView maximumZoomScale])
1758 // If the viewport width was not explicit, we allow double tap gestures.
1759 if (!_viewportMetaTagWidthWasExplicit || _viewportMetaTagCameFromImageDocument)
1762 // If the page set a viewport width that wasn't the device width, then it was
1763 // scaled and thus will probably need to zoom.
1764 if (_viewportMetaTagWidth != WebCore::ViewportArguments::ValueDeviceWidth)
1767 // At this point, we have a page that asked for width = device-width. However,
1768 // if the content's width and height were large, we might have had to shrink it.
1769 // Since we'll enable double tap zoom whenever we're not at the actual
1770 // initial scale, this simply becomes a test of the current scale against 1.
1771 return !areEssentiallyEqualAsFloat(contentZoomScale(self), 1);
1774 #pragma mark - UIScrollViewDelegate
1776 - (BOOL)usesStandardContentView
1778 return !_customContentView;
1781 - (CGSize)scrollView:(UIScrollView*)scrollView contentSizeForZoomScale:(CGFloat)scale withProposedSize:(CGSize)proposedSize
1783 return roundScrollViewContentSize(*_page, proposedSize);
1786 - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
1788 ASSERT(_scrollView == scrollView);
1790 if (_customContentView)
1791 return _customContentView.get();
1793 return _contentView.get();
1796 - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
1798 if (![self usesStandardContentView])
1801 if (scrollView.pinchGestureRecognizer.state == UIGestureRecognizerStateBegan) {
1802 _page->willStartUserTriggeredZooming();
1803 [_contentView scrollViewWillStartPanOrPinchGesture];
1805 [_contentView willStartZoomOrScroll];
1808 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
1810 if (![self usesStandardContentView])
1813 if (scrollView.panGestureRecognizer.state == UIGestureRecognizerStateBegan)
1814 [_contentView scrollViewWillStartPanOrPinchGesture];
1816 [_contentView willStartZoomOrScroll];
1817 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
1818 // FIXME: We will want to detect whether snapping will occur before beginning to drag. See WebPageProxy::didCommitLayerTree.
1819 WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
1820 ASSERT(scrollView == _scrollView.get());
1821 CGFloat scrollDecelerationFactor = (coordinator && coordinator->shouldSetScrollViewDecelerationRateFast()) ? UIScrollViewDecelerationRateFast : [_scrollView preferredScrollDecelerationFactor];
1822 scrollView.horizontalScrollDecelerationFactor = scrollDecelerationFactor;
1823 scrollView.verticalScrollDecelerationFactor = scrollDecelerationFactor;
1827 - (void)_didFinishScrolling
1829 if (![self usesStandardContentView])
1832 [self _updateVisibleContentRectAfterScrollInView:_scrollView.get()];
1833 [_contentView didFinishScrolling];
1836 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
1838 // Work around <rdar://problem/16374753> by avoiding deceleration while
1839 // zooming. We'll animate to the right place once the zoom finishes.
1840 if ([scrollView isZooming])
1841 *targetContentOffset = [scrollView contentOffset];
1842 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
1843 if (WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy()) {
1844 // FIXME: Here, I'm finding the maximum horizontal/vertical scroll offsets. There's probably a better way to do this.
1845 CGSize maxScrollOffsets = CGSizeMake(scrollView.contentSize.width - scrollView.bounds.size.width, scrollView.contentSize.height - scrollView.bounds.size.height);
1847 CGRect fullViewRect = self.bounds;
1849 UIEdgeInsets contentInset;
1851 id<WKUIDelegatePrivate> uiDelegatePrivate = static_cast<id <WKUIDelegatePrivate>>([self UIDelegate]);
1852 if ([uiDelegatePrivate respondsToSelector:@selector(_webView:finalObscuredInsetsForScrollView:withVelocity:targetContentOffset:)])
1853 contentInset = [uiDelegatePrivate _webView:self finalObscuredInsetsForScrollView:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
1855 contentInset = [self _computedContentInset];
1857 CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, contentInset);
1859 coordinator->adjustTargetContentOffsetForSnapping(maxScrollOffsets, velocity, unobscuredRect.origin.y, targetContentOffset);
1864 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
1866 // If we're decelerating, scroll offset will be updated when scrollViewDidFinishDecelerating: is called.
1868 [self _didFinishScrolling];
1871 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
1873 [self _didFinishScrolling];
1876 - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
1878 [self _didFinishScrolling];
1881 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
1883 if (![self usesStandardContentView])
1884 [_customContentView scrollViewDidScroll:(UIScrollView *)scrollView];
1886 [self _updateVisibleContentRectAfterScrollInView:scrollView];
1888 if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
1889 scrollPerfData->didScroll([self visibleRectInViewCoordinates]);
1892 - (void)scrollViewDidZoom:(UIScrollView *)scrollView
1894 [self _updateScrollViewBackground];
1895 [self _updateVisibleContentRectAfterScrollInView:scrollView];
1898 - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
1900 ASSERT(scrollView == _scrollView);
1901 [self _updateVisibleContentRectAfterScrollInView:scrollView];
1902 [_contentView didZoomToScale:scale];
1905 - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
1907 [self _didFinishScrolling];
1910 - (void)_scrollViewDidInterruptDecelerating:(UIScrollView *)scrollView
1912 if (![self usesStandardContentView])
1915 [_contentView didInterruptScrolling];
1916 [self _updateVisibleContentRectAfterScrollInView:scrollView];
1919 - (CGRect)_visibleRectInEnclosingScrollView:(UIScrollView *)enclosingScrollView
1921 if (!enclosingScrollView)
1924 CGRect exposedRect = [enclosingScrollView convertRect:enclosingScrollView.bounds toView:self];
1925 return CGRectIntersectsRect(exposedRect, self.bounds) ? CGRectIntersection(exposedRect, self.bounds) : CGRectZero;
1928 - (CGRect)_visibleContentRect
1930 if (_frozenVisibleContentRect)
1931 return _frozenVisibleContentRect.value();
1933 CGRect visibleRectInContentCoordinates = [self convertRect:self.bounds toView:_contentView.get()];
1935 if (UIScrollView *enclosingScroller = [self _scroller]) {
1936 CGRect viewVisibleRect = [self _visibleRectInEnclosingScrollView:enclosingScroller];
1937 CGRect viewVisibleContentRect = [self convertRect:viewVisibleRect toView:_contentView.get()];
1938 visibleRectInContentCoordinates = CGRectIntersection(visibleRectInContentCoordinates, viewVisibleContentRect);
1941 return visibleRectInContentCoordinates;
1944 // Called when some ancestor UIScrollView scrolls.
1947 [self _updateVisibleContentRectAfterScrollInView:[self _scroller]];
1949 const NSTimeInterval ScrollingEndedTimerInterval = 0.032;
1950 if (!_enclosingScrollViewScrollTimer) {
1951 _enclosingScrollViewScrollTimer = adoptNS([[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:ScrollingEndedTimerInterval]
1952 interval:0 target:self selector:@selector(_enclosingScrollerScrollingEnded:) userInfo:nil repeats:YES]);
1953 [[NSRunLoop mainRunLoop] addTimer:_enclosingScrollViewScrollTimer.get() forMode:NSDefaultRunLoopMode];
1955 _didScrollSinceLastTimerFire = YES;
1958 - (void)_enclosingScrollerScrollingEnded:(NSTimer *)timer
1960 if (_didScrollSinceLastTimerFire) {
1961 _didScrollSinceLastTimerFire = NO;
1965 [self _updateVisibleContentRects];
1966 [_enclosingScrollViewScrollTimer invalidate];
1967 _enclosingScrollViewScrollTimer = nil;
1970 - (void)_frameOrBoundsChanged
1972 CGRect bounds = self.bounds;
1973 [_scrollView setFrame:bounds];
1975 if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing) {
1976 if (!_overridesMinimumLayoutSize)
1977 _page->setViewportConfigurationMinimumLayoutSize(WebCore::FloatSize(bounds.size));
1978 if (!_overridesMaximumUnobscuredSize)
1979 _page->setMaximumUnobscuredSize(WebCore::FloatSize(bounds.size));
1980 if (auto drawingArea = _page->drawingArea())
1981 drawingArea->setSize(WebCore::IntSize(bounds.size), WebCore::IntSize(), WebCore::IntSize());
1984 [_customContentView web_setMinimumSize:bounds.size];
1985 [self _updateVisibleContentRects];
1988 // 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.
1989 - (CGRect)_contentRectForUserInteraction
1991 // FIXME: handle split keyboard.
1992 UIEdgeInsets obscuredInsets = _obscuredInsets;
1993 obscuredInsets.bottom = std::max(_obscuredInsets.bottom, _inputViewBounds.size.height);
1994 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInsets);
1995 return [self convertRect:unobscuredRect toView:self._currentContentView];
1998 // Ideally UIScrollView would expose this for us: <rdar://problem/21394567>.
1999 - (BOOL)_scrollViewIsRubberBanding
2001 float deviceScaleFactor = _page->deviceScaleFactor();
2003 CGPoint contentOffset = [_scrollView contentOffset];
2004 CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
2005 return !pointsEqualInDevicePixels(contentOffset, boundedOffset, deviceScaleFactor);
2008 - (void)_updateVisibleContentRects
2010 // For visible rect updates not associated with a spefic UIScrollView, just consider our own scroller.
2011 [self _updateVisibleContentRectAfterScrollInView:_scrollView.get()];
2014 - (void)_updateVisibleContentRectAfterScrollInView:(UIScrollView *)scrollView
2016 BOOL isStableState = !([scrollView isDragging] || [scrollView isDecelerating] || [scrollView isZooming] || [scrollView _isAnimatingZoom] || [scrollView _isScrollingToTop]);
2018 if (isStableState && scrollView == _scrollView.get())
2019 isStableState = !_isChangingObscuredInsetsInteractively;
2021 if (isStableState && scrollView == _scrollView.get())
2022 isStableState = ![self _scrollViewIsRubberBanding];
2024 // FIXME: this can be made static after we stop supporting iOS 8.x.
2025 if (isStableState && [scrollView respondsToSelector:@selector(_isInterruptingDeceleration)])
2026 isStableState = ![scrollView performSelector:@selector(_isInterruptingDeceleration)];
2028 [self _updateContentRectsWithState:isStableState];
2031 static bool scrollViewCanScroll(UIScrollView *scrollView)
2036 UIEdgeInsets contentInset = scrollView.contentInset;
2037 CGSize contentSize = scrollView.contentSize;
2038 CGSize boundsSize = scrollView.bounds.size;
2040 return (contentSize.width + contentInset.left + contentInset.right) > boundsSize.width
2041 || (contentSize.height + contentInset.top + contentInset.bottom) > boundsSize.height;
2044 - (void)_updateContentRectsWithState:(BOOL)inStableState
2046 if (![self usesStandardContentView]) {
2047 [_customContentView web_computedContentInsetDidChange];
2051 if (_delayUpdateVisibleContentRects) {
2052 _hadDelayedUpdateVisibleContentRects = YES;
2056 if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing
2057 || _needsResetViewStateAfterCommitLoadForMainFrame
2058 || [_scrollView isZoomBouncing]
2059 || _currentlyAdjustingScrollViewInsetsForKeyboard)
2062 CGRect fullViewRect = self.bounds;
2063 CGRect visibleRectInContentCoordinates = [self _visibleContentRect];
2065 UIEdgeInsets computedContentInsetUnadjustedForKeyboard = [self _computedContentInset];
2066 if (!_haveSetObscuredInsets)
2067 computedContentInsetUnadjustedForKeyboard.bottom -= _totalScrollViewBottomInsetAdjustmentForKeyboard;
2069 CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, computedContentInsetUnadjustedForKeyboard);
2070 CGRect unobscuredRectInContentCoordinates = _frozenUnobscuredContentRect ? _frozenUnobscuredContentRect.value() : [self convertRect:unobscuredRect toView:_contentView.get()];
2072 CGFloat scaleFactor = contentZoomScale(self);
2074 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2075 if (inStableState) {
2076 WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2077 if (coordinator && coordinator->hasActiveSnapPoint()) {
2078 CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, computedContentInsetUnadjustedForKeyboard);
2080 CGPoint currentPoint = [_scrollView contentOffset];
2081 CGPoint activePoint = coordinator->nearestActiveContentInsetAdjustedSnapPoint(unobscuredRect.origin.y, currentPoint);
2083 if (!CGPointEqualToPoint(activePoint, currentPoint)) {
2084 RetainPtr<WKScrollView> strongScrollView = _scrollView;
2085 dispatch_async(dispatch_get_main_queue(), [strongScrollView, activePoint] {
2086 [strongScrollView setContentOffset:activePoint animated:NO];
2093 [_contentView didUpdateVisibleRect:visibleRectInContentCoordinates
2094 unobscuredRect:unobscuredRectInContentCoordinates
2095 unobscuredRectInScrollViewCoordinates:unobscuredRect
2096 obscuredInset:CGSizeMake(_obscuredInsets.left, _obscuredInsets.top)
2097 scale:scaleFactor minimumScale:[_scrollView minimumZoomScale]
2098 inStableState:inStableState
2099 isChangingObscuredInsetsInteractively:_isChangingObscuredInsetsInteractively
2100 enclosedInScrollableAncestorView:scrollViewCanScroll([self _scroller])];
2103 - (void)_didFinishLoadForMainFrame
2105 if (_gestureController)
2106 _gestureController->didFinishLoadForMainFrame();
2109 - (void)_didFailLoadForMainFrame
2111 if (_gestureController)
2112 _gestureController->didFailLoadForMainFrame();
2115 - (void)_didSameDocumentNavigationForMainFrame:(WebKit::SameDocumentNavigationType)navigationType
2117 [_customContentView web_didSameDocumentNavigation:toAPI(navigationType)];
2119 if (_gestureController)
2120 _gestureController->didSameDocumentNavigationForMainFrame(navigationType);
2123 - (void)_keyboardChangedWithInfo:(NSDictionary *)keyboardInfo adjustScrollView:(BOOL)adjustScrollView
2125 NSValue *endFrameValue = [keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
2129 // The keyboard rect is always in screen coordinates. In the view services case the window does not
2130 // have the interface orientation rotation transformation; its host does. So, it makes no sense to
2131 // clip the keyboard rect against its screen.
2132 if ([[self window] _isHostedInAnotherProcess])
2133 _inputViewBounds = [self.window convertRect:[endFrameValue CGRectValue] fromWindow:nil];
2135 _inputViewBounds = [self.window convertRect:CGRectIntersection([endFrameValue CGRectValue], self.window.screen.bounds) fromWindow:nil];
2137 if (adjustScrollView) {
2138 CGFloat bottomInsetBeforeAdjustment = [_scrollView contentInset].bottom;
2139 TemporaryChange<BOOL> insetAdjustmentGuard(_currentlyAdjustingScrollViewInsetsForKeyboard, YES);
2140 [_scrollView _adjustForAutomaticKeyboardInfo:keyboardInfo animated:YES lastAdjustment:&_lastAdjustmentForScroller];
2141 CGFloat bottomInsetAfterAdjustment = [_scrollView contentInset].bottom;
2142 if (bottomInsetBeforeAdjustment != bottomInsetAfterAdjustment)
2143 _totalScrollViewBottomInsetAdjustmentForKeyboard += bottomInsetAfterAdjustment - bottomInsetBeforeAdjustment;
2146 [self _updateVisibleContentRects];
2149 - (BOOL)_shouldUpdateKeyboardWithInfo:(NSDictionary *)keyboardInfo
2151 if ([_contentView isAssistingNode])
2154 NSNumber *isLocalKeyboard = [keyboardInfo valueForKey:UIKeyboardIsLocalUserInfoKey];
2155 return isLocalKeyboard && !isLocalKeyboard.boolValue;
2158 - (void)_keyboardWillChangeFrame:(NSNotification *)notification
2160 if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
2161 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
2164 - (void)_keyboardDidChangeFrame:(NSNotification *)notification
2166 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:NO];
2169 - (void)_keyboardWillShow:(NSNotification *)notification
2171 if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
2172 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
2175 - (void)_keyboardWillHide:(NSNotification *)notification
2177 // Ignore keyboard will hide notifications sent during rotation. They're just there for
2178 // backwards compatibility reasons and processing the will hide notification would
2179 // temporarily screw up the the unobscured view area.
2180 if ([[UIPeripheralHost sharedInstance] rotationState])
2183 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
2186 - (void)_windowDidRotate:(NSNotification *)notification
2188 if (!_overridesInterfaceOrientation)
2189 _page->setDeviceOrientation(deviceOrientation());
2192 - (void)_contentSizeCategoryDidChange:(NSNotification *)notification
2194 _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
2197 - (NSString *)_contentSizeCategory
2199 return [[UIApplication sharedApplication] preferredContentSizeCategory];
2202 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
2204 if (_allowsBackForwardNavigationGestures == allowsBackForwardNavigationGestures)
2207 _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
2209 if (allowsBackForwardNavigationGestures) {
2210 if (!_gestureController) {
2211 _gestureController = std::make_unique<WebKit::ViewGestureController>(*_page);
2212 _gestureController->installSwipeHandler(self, [self scrollView]);
2213 if (WKWebView *alternateWebView = [_configuration _alternateWebViewForNavigationGestures])
2214 _gestureController->setAlternateBackForwardListSourcePage(alternateWebView->_page.get());
2217 _gestureController = nullptr;
2219 _page->setShouldRecordNavigationSnapshots(allowsBackForwardNavigationGestures);
2222 - (BOOL)allowsBackForwardNavigationGestures
2224 return _allowsBackForwardNavigationGestures;
2227 - (void)_navigationGestureDidBegin
2229 // During a back/forward swipe, there's a view interposed between this view and the content view that has
2230 // an offset and animation on it, which results in computing incorrect rectangles. Work around by using
2231 // frozen rects during swipes.
2232 CGRect fullViewRect = self.bounds;
2233 CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, [self _computedContentInset]);
2235 _frozenVisibleContentRect = [self convertRect:fullViewRect toView:_contentView.get()];
2236 _frozenUnobscuredContentRect = [self convertRect:unobscuredRect toView:_contentView.get()];
2238 LOG_WITH_STREAM(VisibleRects, stream << "_navigationGestureDidBegin: freezing visibleContentRect " << _frozenVisibleContentRect.value() << " UnobscuredContentRect " << _frozenUnobscuredContentRect.value());
2241 - (void)_navigationGestureDidEnd
2243 _frozenVisibleContentRect = Nullopt;
2244 _frozenUnobscuredContentRect = Nullopt;
2247 #endif // PLATFORM(IOS)
2249 #pragma mark OS X-specific methods
2253 - (BOOL)acceptsFirstResponder
2255 return _impl->acceptsFirstResponder();
2258 - (BOOL)becomeFirstResponder
2260 return _impl->becomeFirstResponder();
2263 - (BOOL)resignFirstResponder
2265 return _impl->resignFirstResponder();
2268 - (void)viewWillStartLiveResize
2270 _impl->viewWillStartLiveResize();
2273 - (void)viewDidEndLiveResize
2275 _impl->viewDidEndLiveResize();
2283 - (NSSize)intrinsicContentSize
2285 return NSSizeFromCGSize(_impl->intrinsicContentSize());
2288 - (void)prepareContentInRect:(NSRect)rect
2290 _impl->prepareContentInRect(NSRectToCGRect(rect));
2293 - (void)setFrameSize:(NSSize)size
2295 [super setFrameSize:size];
2296 _impl->setFrameSize(NSSizeToCGSize(size));
2301 _impl->renewGState();
2302 [super renewGState];
2305 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _impl->executeEditCommandForSelector(_cmd); }
2307 WEBCORE_COMMAND(alignCenter)
2308 WEBCORE_COMMAND(alignJustified)
2309 WEBCORE_COMMAND(alignLeft)
2310 WEBCORE_COMMAND(alignRight)
2311 WEBCORE_COMMAND(copy)
2312 WEBCORE_COMMAND(cut)
2313 WEBCORE_COMMAND(delete)
2314 WEBCORE_COMMAND(deleteBackward)
2315 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
2316 WEBCORE_COMMAND(deleteForward)
2317 WEBCORE_COMMAND(deleteToBeginningOfLine)
2318 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
2319 WEBCORE_COMMAND(deleteToEndOfLine)
2320 WEBCORE_COMMAND(deleteToEndOfParagraph)
2321 WEBCORE_COMMAND(deleteToMark)
2322 WEBCORE_COMMAND(deleteWordBackward)
2323 WEBCORE_COMMAND(deleteWordForward)
2324 WEBCORE_COMMAND(ignoreSpelling)
2325 WEBCORE_COMMAND(indent)
2326 WEBCORE_COMMAND(insertBacktab)
2327 WEBCORE_COMMAND(insertLineBreak)
2328 WEBCORE_COMMAND(insertNewline)
2329 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
2330 WEBCORE_COMMAND(insertParagraphSeparator)
2331 WEBCORE_COMMAND(insertTab)
2332 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
2333 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
2334 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
2335 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
2336 WEBCORE_COMMAND(moveBackward)
2337 WEBCORE_COMMAND(moveBackwardAndModifySelection)
2338 WEBCORE_COMMAND(moveDown)
2339 WEBCORE_COMMAND(moveDownAndModifySelection)
2340 WEBCORE_COMMAND(moveForward)
2341 WEBCORE_COMMAND(moveForwardAndModifySelection)
2342 WEBCORE_COMMAND(moveLeft)
2343 WEBCORE_COMMAND(moveLeftAndModifySelection)
2344 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
2345 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
2346 WEBCORE_COMMAND(moveRight)
2347 WEBCORE_COMMAND(moveRightAndModifySelection)
2348 WEBCORE_COMMAND(moveToBeginningOfDocument)
2349 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
2350 WEBCORE_COMMAND(moveToBeginningOfLine)
2351 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
2352 WEBCORE_COMMAND(moveToBeginningOfParagraph)
2353 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
2354 WEBCORE_COMMAND(moveToBeginningOfSentence)
2355 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
2356 WEBCORE_COMMAND(moveToEndOfDocument)
2357 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
2358 WEBCORE_COMMAND(moveToEndOfLine)
2359 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
2360 WEBCORE_COMMAND(moveToEndOfParagraph)
2361 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
2362 WEBCORE_COMMAND(moveToEndOfSentence)
2363 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
2364 WEBCORE_COMMAND(moveToLeftEndOfLine)
2365 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
2366 WEBCORE_COMMAND(moveToRightEndOfLine)
2367 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
2368 WEBCORE_COMMAND(moveUp)
2369 WEBCORE_COMMAND(moveUpAndModifySelection)
2370 WEBCORE_COMMAND(moveWordBackward)
2371 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
2372 WEBCORE_COMMAND(moveWordForward)
2373 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
2374 WEBCORE_COMMAND(moveWordLeft)
2375 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
2376 WEBCORE_COMMAND(moveWordRight)
2377 WEBCORE_COMMAND(moveWordRightAndModifySelection)
2378 WEBCORE_COMMAND(outdent)
2379 WEBCORE_COMMAND(pageDown)
2380 WEBCORE_COMMAND(pageDownAndModifySelection)
2381 WEBCORE_COMMAND(pageUp)
2382 WEBCORE_COMMAND(pageUpAndModifySelection)
2383 WEBCORE_COMMAND(paste)
2384 WEBCORE_COMMAND(pasteAsPlainText)
2385 WEBCORE_COMMAND(scrollPageDown)
2386 WEBCORE_COMMAND(scrollPageUp)
2387 WEBCORE_COMMAND(scrollLineDown)
2388 WEBCORE_COMMAND(scrollLineUp)
2389 WEBCORE_COMMAND(scrollToBeginningOfDocument)
2390 WEBCORE_COMMAND(scrollToEndOfDocument)
2391 WEBCORE_COMMAND(selectAll)
2392 WEBCORE_COMMAND(selectLine)
2393 WEBCORE_COMMAND(selectParagraph)
2394 WEBCORE_COMMAND(selectSentence)
2395 WEBCORE_COMMAND(selectToMark)
2396 WEBCORE_COMMAND(selectWord)
2397 WEBCORE_COMMAND(setMark)
2398 WEBCORE_COMMAND(subscript)
2399 WEBCORE_COMMAND(superscript)
2400 WEBCORE_COMMAND(swapWithMark)
2401 WEBCORE_COMMAND(takeFindStringFromSelection)
2402 WEBCORE_COMMAND(transpose)
2403 WEBCORE_COMMAND(underline)
2404 WEBCORE_COMMAND(unscript)
2405 WEBCORE_COMMAND(yank)
2406 WEBCORE_COMMAND(yankAndSelect)
2408 #undef WEBCORE_COMMAND
2410 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
2412 return _impl->writeSelectionToPasteboard(pasteboard, types);
2415 - (void)centerSelectionInVisibleArea:(id)sender
2417 _impl->centerSelectionInVisibleArea();
2420 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
2422 return _impl->validRequestorForSendAndReturnTypes(sendType, returnType);
2425 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
2427 return _impl->readSelectionFromPasteboard(pasteboard);
2430 - (void)changeFont:(id)sender
2432 _impl->changeFontFromFontPanel();
2435 - (IBAction)startSpeaking:(id)sender
2437 _impl->startSpeaking();
2440 - (IBAction)stopSpeaking:(id)sender
2442 _impl->stopSpeaking(sender);
2445 - (IBAction)showGuessPanel:(id)sender
2447 _impl->showGuessPanel(sender);
2450 - (IBAction)checkSpelling:(id)sender
2452 _impl->checkSpelling();
2455 - (void)changeSpelling:(id)sender
2457 _impl->changeSpelling(sender);
2460 - (IBAction)toggleContinuousSpellChecking:(id)sender
2462 _impl->toggleContinuousSpellChecking();
2465 - (BOOL)isGrammarCheckingEnabled
2467 return _impl->isGrammarCheckingEnabled();
2470 - (void)setGrammarCheckingEnabled:(BOOL)flag
2472 _impl->setGrammarCheckingEnabled(flag);
2475 - (IBAction)toggleGrammarChecking:(id)sender
2477 _impl->toggleGrammarChecking();
2480 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
2482 _impl->toggleAutomaticSpellingCorrection();
2485 - (void)orderFrontSubstitutionsPanel:(id)sender
2487 _impl->orderFrontSubstitutionsPanel(sender);
2490 - (IBAction)toggleSmartInsertDelete:(id)sender
2492 _impl->toggleSmartInsertDelete();
2495 - (BOOL)isAutomaticQuoteSubstitutionEnabled
2497 return _impl->isAutomaticQuoteSubstitutionEnabled();
2500 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
2502 _impl->setAutomaticQuoteSubstitutionEnabled(flag);
2505 - (void)toggleAutomaticQuoteSubstitution:(id)sender
2507 _impl->toggleAutomaticQuoteSubstitution();
2510 - (BOOL)isAutomaticDashSubstitutionEnabled
2512 return _impl->isAutomaticDashSubstitutionEnabled();
2515 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
2517 _impl->setAutomaticDashSubstitutionEnabled(flag);
2520 - (void)toggleAutomaticDashSubstitution:(id)sender
2522 _impl->toggleAutomaticDashSubstitution();
2525 - (BOOL)isAutomaticLinkDetectionEnabled
2527 return _impl->isAutomaticLinkDetectionEnabled();
2530 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
2532 _impl->setAutomaticLinkDetectionEnabled(flag);
2535 - (void)toggleAutomaticLinkDetection:(id)sender
2537 _impl->toggleAutomaticLinkDetection();
2540 - (BOOL)isAutomaticTextReplacementEnabled
2542 return _impl->isAutomaticTextReplacementEnabled();
2545 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
2547 _impl->setAutomaticTextReplacementEnabled(flag);
2550 - (void)toggleAutomaticTextReplacement:(id)sender
2552 _impl->toggleAutomaticTextReplacement();
2555 - (void)uppercaseWord:(id)sender
2557 _impl->uppercaseWord();
2560 - (void)lowercaseWord:(id)sender
2562 _impl->lowercaseWord();
2565 - (void)capitalizeWord:(id)sender
2567 _impl->capitalizeWord();
2570 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
2572 return _impl->wantsKeyDownForEvent(event);
2575 - (void)scrollWheel:(NSEvent *)event
2577 _impl->scrollWheel(event);
2580 - (void)swipeWithEvent:(NSEvent *)event
2582 _impl->swipeWithEvent(event);
2585 - (void)mouseMoved:(NSEvent *)event
2587 _impl->mouseMoved(event);
2590 - (void)mouseDown:(NSEvent *)event
2592 _impl->mouseDown(event);
2595 - (void)mouseUp:(NSEvent *)event
2597 _impl->mouseUp(event);
2600 - (void)mouseDragged:(NSEvent *)event
2602 _impl->mouseDragged(event);
2605 - (void)mouseEntered:(NSEvent *)event
2607 _impl->mouseEntered(event);
2610 - (void)mouseExited:(NSEvent *)event
2612 _impl->mouseExited(event);
2615 - (void)otherMouseDown:(NSEvent *)event
2617 _impl->otherMouseDown(event);
2620 - (void)otherMouseDragged:(NSEvent *)event
2622 _impl->otherMouseDragged(event);
2625 - (void)otherMouseUp:(NSEvent *)event
2627 _impl->otherMouseUp(event);
2630 - (void)rightMouseDown:(NSEvent *)event
2632 _impl->rightMouseDown(event);
2635 - (void)rightMouseDragged:(NSEvent *)event
2637 _impl->rightMouseDragged(event);
2640 - (void)rightMouseUp:(NSEvent *)event
2642 _impl->rightMouseUp(event);
2645 - (void)pressureChangeWithEvent:(NSEvent *)event
2647 _impl->pressureChangeWithEvent(event);
2650 - (BOOL)acceptsFirstMouse:(NSEvent *)event
2652 return _impl->acceptsFirstMouse(event);
2655 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
2657 return _impl->shouldDelayWindowOrderingForEvent(event);
2660 - (void)doCommandBySelector:(SEL)selector
2662 _impl->doCommandBySelector(selector);
2665 - (void)insertText:(id)string
2667 _impl->insertText(string);
2670 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
2672 _impl->insertText(string, replacementRange);
2675 - (NSTextInputContext *)inputContext
2679 return _impl->inputContext();
2682 - (BOOL)performKeyEquivalent:(NSEvent *)event
2684 return _impl->performKeyEquivalent(event);
2687 - (void)keyUp:(NSEvent *)theEvent
2689 _impl->keyUp(theEvent);
2692 - (void)keyDown:(NSEvent *)theEvent
2694 _impl->keyDown(theEvent);
2697 - (void)flagsChanged:(NSEvent *)theEvent
2699 _impl->flagsChanged(theEvent);
2702 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelectedRange replacementRange:(NSRange)replacementRange
2704 _impl->setMarkedText(string, newSelectedRange, replacementRange);
2709 _impl->unmarkText();
2712 - (NSRange)selectedRange
2714 return _impl->selectedRange();
2717 - (BOOL)hasMarkedText
2719 return _impl->hasMarkedText();
2722 - (NSRange)markedRange
2724 return _impl->markedRange();
2727 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange
2729 return _impl->attributedSubstringForProposedRange(nsRange, actualRange);
2732 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
2734 return _impl->characterIndexForPoint(thePoint);
2737 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
2739 return _impl->firstRectForCharacterRange(theRange, actualRange);
2742 - (void)selectedRangeWithCompletionHandler:(void(^)(NSRange selectedRange))completionHandlerPtr
2744 _impl->selectedRangeWithCompletionHandler(completionHandlerPtr);
2747 - (void)markedRangeWithCompletionHandler:(void(^)(NSRange markedRange))completionHandlerPtr
2749 _impl->markedRangeWithCompletionHandler(completionHandlerPtr);
2752 - (void)hasMarkedTextWithCompletionHandler:(void(^)(BOOL hasMarkedText))completionHandlerPtr
2754 _impl->hasMarkedTextWithCompletionHandler(completionHandlerPtr);
2757 - (void)attributedSubstringForProposedRange:(NSRange)nsRange completionHandler:(void(^)(NSAttributedString *attrString, NSRange actualRange))completionHandlerPtr
2759 _impl->attributedSubstringForProposedRange(nsRange, completionHandlerPtr);
2762 - (void)firstRectForCharacterRange:(NSRange)theRange completionHandler:(void(^)(NSRect firstRect, NSRange actualRange))completionHandlerPtr
2764 _impl->firstRectForCharacterRange(theRange, completionHandlerPtr);
2767 - (void)characterIndexForPoint:(NSPoint)thePoint completionHandler:(void(^)(NSUInteger))completionHandlerPtr
2769 _impl->characterIndexForPoint(thePoint, completionHandlerPtr);
2772 - (NSArray *)validAttributesForMarkedText
2774 return _impl->validAttributesForMarkedText();
2777 #if ENABLE(DRAG_SUPPORT)
2778 - (void)draggedImage:(NSImage *)image endedAt:(NSPoint)endPoint operation:(NSDragOperation)operation
2780 _impl->draggedImage(image, NSPointToCGPoint(endPoint), operation);
2783 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
2785 return _impl->draggingEntered(draggingInfo);
2788 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
2790 return _impl->draggingUpdated(draggingInfo);
2793 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
2795 _impl->draggingExited(draggingInfo);
2798 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
2800 return _impl->prepareForDragOperation(draggingInfo);
2803 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
2805 return _impl->performDragOperation(draggingInfo);
2808 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
2810 return _impl->hitTestForDragTypes(NSPointToCGPoint(*point), types);
2812 #endif // ENABLE(DRAG_SUPPORT)
2814 - (BOOL)_windowResizeMouseLocationIsInVisibleScrollerThumb:(NSPoint)point
2816 return _impl->windowResizeMouseLocationIsInVisibleScrollerThumb(NSPointToCGPoint(point));
2819 - (void)viewWillMoveToWindow:(NSWindow *)window
2821 _impl->viewWillMoveToWindow(window);
2824 - (void)viewDidMoveToWindow
2826 _impl->viewDidMoveToWindow();
2829 - (void)drawRect:(NSRect)rect
2831 _impl->drawRect(NSRectToCGRect(rect));
2836 return _impl->isOpaque();
2839 - (BOOL)mouseDownCanMoveWindow
2841 return WebKit::WebViewImpl::mouseDownCanMoveWindow();
2846 _impl->viewDidHide();
2849 - (void)viewDidUnhide
2851 _impl->viewDidUnhide();
2854 - (void)viewDidChangeBackingProperties
2856 _impl->viewDidChangeBackingProperties();
2859 - (void)_activeSpaceDidChange:(NSNotification *)notification
2861 _impl->activeSpaceDidChange();
2864 - (id)accessibilityFocusedUIElement
2866 return _impl->accessibilityFocusedUIElement();
2869 - (BOOL)accessibilityIsIgnored
2871 return _impl->accessibilityIsIgnored();
2874 - (id)accessibilityHitTest:(NSPoint)point
2876 return _impl->accessibilityHitTest(NSPointToCGPoint(point));
2879 - (id)accessibilityAttributeValue:(NSString *)attribute
2881 return _impl->accessibilityAttributeValue(attribute);
2884 - (NSView *)hitTest:(NSPoint)point
2887 return [super hitTest:point];
2888 return _impl->hitTest(NSPointToCGPoint(point));
2891 - (NSInteger)conversationIdentifier
2893 return (NSInteger)self;
2896 - (void)quickLookWithEvent:(NSEvent *)event
2898 _impl->quickLookWithEvent(event);
2901 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
2903 return _impl->addTrackingRect(NSRectToCGRect(rect), owner, data, assumeInside);
2906 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
2908 return _impl->addTrackingRectWithTrackingNum(NSRectToCGRect(rect), owner, data, assumeInside, tag);
2911 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
2913 CGRect *cgRects = (CGRect *)calloc(1, sizeof(CGRect));
2914 for (int i = 0; i < count; i++)
2915 cgRects[i] = NSRectToCGRect(rects[i]);
2916 _impl->addTrackingRectsWithTrackingNums(cgRects, owner, userDataList, assumeInsideList, trackingNums, count);
2920 - (void)removeTrackingRect:(NSTrackingRectTag)tag
2924 _impl->removeTrackingRect(tag);
2927 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
2931 _impl->removeTrackingRects(tags, count);
2934 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
2936 return _impl->stringForToolTip(tag);
2939 - (void)pasteboardChangedOwner:(NSPasteboard *)pasteboard
2941 _impl->pasteboardChangedOwner(pasteboard);
2944 - (void)pasteboard:(NSPasteboard *)pasteboard provideDataForType:(NSString *)type
2946 _impl->provideDataForPasteboard(pasteboard, type);
2949 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
2951 return _impl->namesOfPromisedFilesDroppedAtDestination(dropDestination);
2954 - (BOOL)wantsUpdateLayer
2956 return WebKit::WebViewImpl::wantsUpdateLayer();
2961 _impl->updateLayer();
2964 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
2966 _impl->setAllowsBackForwardNavigationGestures(allowsBackForwardNavigationGestures);
2969 - (BOOL)allowsBackForwardNavigationGestures
2971 return _impl->allowsBackForwardNavigationGestures();
2974 - (void)smartMagnifyWithEvent:(NSEvent *)event
2976 _impl->smartMagnifyWithEvent(event);
2979 - (void)setMagnification:(double)magnification centeredAtPoint:(NSPoint)point
2981 _impl->setMagnification(magnification, NSPointToCGPoint(point));
2984 - (void)setMagnification:(double)magnification
2986 _impl->setMagnification(magnification);
2989 - (double)magnification
2991 return _impl->magnification();
2994 - (void)setAllowsMagnification:(BOOL)allowsMagnification
2996 _impl->setAllowsMagnification(allowsMagnification);
2999 - (BOOL)allowsMagnification
3001 return _impl->allowsMagnification();
3004 - (void)magnifyWithEvent:(NSEvent *)event
3006 _impl->magnifyWithEvent(event);
3009 #if ENABLE(MAC_GESTURE_EVENTS)
3010 - (void)rotateWithEvent:(NSEvent *)event
3012 _impl->rotateWithEvent(event);
3016 - (WKTextFinderClient *)_ensureTextFinderClient
3018 if (!_textFinderClient)
3019 _textFinderClient = adoptNS([[WKTextFinderClient alloc] initWithPage:*_page view:self]);
3020 return _textFinderClient.get();
3023 - (void)findMatchesForString:(NSString *)targetString relativeToMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)relativeMatch findOptions:(NSTextFinderAsynchronousDocumentFindOptions)findOptions maxResults:(NSUInteger)maxResults resultCollector:(void (^)(NSArray *matches, BOOL didWrap))resultCollector
3025 [[self _ensureTextFinderClient] findMatchesForString:targetString relativeToMatch:relativeMatch findOptions:findOptions maxResults:maxResults resultCollector:resultCollector];
3028 - (NSView *)documentContainerView
3033 - (void)getSelectedText:(void (^)(NSString *selectedTextString))completionHandler
3035 [[self _ensureTextFinderClient] getSelectedText:completionHandler];
3038 - (void)selectFindMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)findMatch completionHandler:(void (^)(void))completionHandler
3040 [[self _ensureTextFinderClient] selectFindMatch:findMatch completionHandler:completionHandler];
3043 - (NSTextInputContext *)_web_superInputContext
3045 return [super inputContext];
3048 - (void)_web_superQuickLookWithEvent:(NSEvent *)event
3050 [super quickLookWithEvent:event];
3053 - (void)_web_superSwipeWithEvent:(NSEvent *)event
3055 [super swipeWithEvent:event];
3058 - (void)_web_superMagnifyWithEvent:(NSEvent *)event
3060 [super magnifyWithEvent:event];
3063 - (void)_web_superSmartMagnifyWithEvent:(NSEvent *)event
3065 [super smartMagnifyWithEvent:event];
3068 - (void)_web_superRemoveTrackingRect:(NSTrackingRectTag)tag
3070 [super removeTrackingRect:tag];
3073 - (id)_web_superAccessibilityAttributeValue:(NSString *)attribute
3075 #pragma clang diagnostic push
3076 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
3077 return [super accessibilityAttributeValue:attribute];
3078 #pragma clang diagnostic pop
3081 - (void)_web_superDoCommandBySelector:(SEL)selector
3083 [super doCommandBySelector:selector];
3086 - (BOOL)_web_superPerformKeyEquivalent:(NSEvent *)event
3088 return [super performKeyEquivalent:event];
3091 - (void)_web_superKeyDown:(NSEvent *)event
3093 [super keyDown:event];
3096 - (NSView *)_web_superHitTest:(NSPoint)point
3098 return [super hitTest:point];
3101 - (id)_web_immediateActionAnimationControllerForHitTestResultInternal:(API::HitTestResult*)hitTestResult withType:(uint32_t)type userData:(API::Object*)userData
3103 id<NSSecureCoding> data = userData ? static_cast<id<NSSecureCoding>>(userData->wrapper()) : nil;
3104 return [self _immediateActionAnimationControllerForHitTestResult:wrapper(*hitTestResult) withType:(_WKImmediateActionType)type userData:data];
3107 // We don't expose these various bits of SPI like WKView does,
3108 // so have these internal methods just do the work (or do nothing):
3109 - (void)_web_prepareForImmediateActionAnimation
3113 - (void)_web_cancelImmediateActionAnimation
3117 - (void)_web_completeImmediateActionAnimation
3121 - (void)_web_didChangeContentSize:(NSSize)newSize
3125 - (void)_web_dismissContentRelativeChildWindows
3127 _impl->dismissContentRelativeChildWindowsFromViewOnly();
3130 - (void)_web_dismissContentRelativeChildWindowsWithAnimation:(BOOL)withAnimation
3132 _impl->dismissContentRelativeChildWindowsWithAnimationFromViewOnly(withAnimation);
3135 - (void)_web_gestureEventWasNotHandledByWebCore:(NSEvent *)event
3137 _impl->gestureEventWasNotHandledByWebCoreFromViewOnly(event);
3140 #endif // PLATFORM(MAC)
3144 @implementation WKWebView (WKPrivate)
3148 return _page->isEditable();
3151 - (void)_setEditable:(BOOL)editable
3153 _page->setEditable(editable);
3155 _impl->startObservingFontPanel();
3159 - (_WKRemoteObjectRegistry *)_remoteObjectRegistry
3162 return _impl->remoteObjectRegistry();
3164 if (!_remoteObjectRegistry) {
3165 _remoteObjectRegistry = adoptNS([[_WKRemoteObjectRegistry alloc] _initWithMessageSender:*_page]);
3166 _page->process().processPool().addMessageReceiver(Messages::RemoteObjectRegistry::messageReceiverName(), _page->pageID(), [_remoteObjectRegistry remoteObjectRegistry]);
3169 return _remoteObjectRegistry.get();
3173 - (WKBrowsingContextHandle *)_handle
3175 return [[[WKBrowsingContextHandle alloc] _initWithPageID:_page->pageID()] autorelease];
3178 - (_WKRenderingProgressEvents)_observedRenderingProgressEvents
3180 return _observedRenderingProgressEvents;
3183 - (id <WKHistoryDelegatePrivate>)_historyDelegate
3185 return _navigationState->historyDelegate().autorelease();
3188 - (void)_setHistoryDelegate:(id <WKHistoryDelegatePrivate>)historyDelegate
3190 _page->setHistoryClient(_navigationState->createHistoryClient());
3191 _navigationState->setHistoryDelegate(historyDelegate);
3194 - (NSURL *)_unreachableURL
3196 return [NSURL _web_URLWithWTFString:_page->pageLoadState().unreachableURL()];
3199 - (void)_loadAlternateHTMLString:(NSString *)string baseURL:(NSURL *)baseURL forUnreachableURL:(NSURL *)unreachableURL
3201 _page->loadAlternateHTMLString(string, [baseURL _web_originalDataAsWTFString], [unreachableURL _web_originalDataAsWTFString]);
3204 - (WKNavigation *)_loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL userData:(id)userData
3206 auto navigation = _page->loadData(API::Data::createWithoutCopying(data).ptr(), MIMEType, characterEncodingName, baseURL.absoluteString, WebKit::ObjCObjectGraph::create(userData).ptr());
3210 return [wrapper(*navigation.leakRef()) autorelease];
3213 - (NSArray *)_certificateChain
3215 if (WebKit::WebFrameProxy* mainFrame = _page->mainFrame())
3216 return mainFrame->certificateInfo() ? (NSArray *)mainFrame->certificateInfo()->certificateInfo().certificateChain() : nil;
3221 - (NSURL *)_committedURL
3223 return [NSURL _web_URLWithWTFString:_page->pageLoadState().url()];
3226 - (NSString *)_MIMEType
3228 if (_page->mainFrame())
3229 return _page->mainFrame()->mimeType();
3234 - (NSString *)_userAgent
3236 return _page->userAgent();
3239 - (NSString *)_applicationNameForUserAgent
3241 return _page->applicationNameForUserAgent();
3244 - (void)_setApplicationNameForUserAgent:(NSString *)applicationNameForUserAgent
3246 _page->setApplicationNameForUserAgent(applicationNameForUserAgent);
3249 - (NSString *)_customUserAgent
3251 return self.customUserAgent;
3254 - (void)_setCustomUserAgent:(NSString *)customUserAgent
3256 self.customUserAgent = customUserAgent;
3259 - (void)_setUserContentExtensionsEnabled:(BOOL)userContentExtensionsEnabled
3261 // This is kept for binary compatibility with iOS 9.
3264 - (BOOL)_userContentExtensionsEnabled
3266 // This is kept for binary compatibility with iOS 9.
3270 - (pid_t)_webProcessIdentifier
3272 return _page->isValid() ? _page->processIdentifier() : 0;
3275 - (void)_killWebContentProcess
3277 if (!_page->isValid())
3280 _page->process().terminate();
3283 - (WKNavigation *)_reloadWithoutContentBlockers
3285 const bool reloadFromOrigin = false;
3286 const bool contentBlockersEnabled = false;
3287 auto navigation = _page->reload(reloadFromOrigin, contentBlockersEnabled);
3291 return [wrapper(*navigation.leakRef()) autorelease];
3294 - (void)_killWebContentProcessAndResetState
3296 _page->terminateProcess();
3300 static WebCore::FloatSize activeMinimumLayoutSize(WKWebView *webView, const CGRect& bounds)
3302 return WebCore::FloatSize(webView->_overridesMinimumLayoutSize ? webView->_minimumLayoutSizeOverride : bounds.size);
3305 static WebCore::FloatSize activeMaximumUnobscuredSize(WKWebView *webView, const CGRect& bounds)
3307 return WebCore::FloatSize(webView->_overridesMaximumUnobscuredSize ? webView->_maximumUnobscuredSizeOverride : bounds.size);
3310 static int32_t activeOrientation(WKWebView *webView)
3312 return webView->_overridesInterfaceOrientation ? deviceOrientationForUIInterfaceOrientation(webView->_interfaceOrientationOverride) : webView->_page->deviceOrientation();
3315 - (void (^)(void))_retainActiveFocusedState
3317 ++_activeFocusedStateRetainCount;
3319 // FIXME: Use something like CompletionHandlerCallChecker to ensure that the returned block is called before it's released.
3321 --_activeFocusedStateRetainCount;
3322 } copy] autorelease];
3325 - (void)_becomeFirstResponderWithSelectionMovingForward:(BOOL)selectingForward completionHandler:(void (^)(BOOL didBecomeFirstResponder))completionHandler
3327 typeof(completionHandler) completionHandlerCopy = nil;
3328 if (completionHandler)
3329 completionHandlerCopy = Block_copy(completionHandler);
3331 [_contentView _becomeFirstResponderWithSelectionMovingForward:selectingForward completionHandler:[completionHandlerCopy](BOOL didBecomeFirstResponder) {
3332 if (!completionHandlerCopy)
3335 completionHandlerCopy(didBecomeFirstResponder);
3336 Block_release(completionHandlerCopy);
3340 - (id)_snapshotLayerContentsForBackForwardListItem:(WKBackForwardListItem *)item
3342 if (_page->backForwardList().currentItem() == &item._item)
3343 _page->recordNavigationSnapshot(*_page->backForwardList().currentItem());
3345 if (auto* viewSnapshot = item._item.snapshot())
3346 return viewSnapshot->asLayerContents();
3351 - (NSArray *)_dataDetectionResults
3353 return [_contentView _dataDetectionResults];
3357 - (void)_didRelaunchProcess
3360 CGRect bounds = self.bounds;
3361 WebCore::FloatSize minimalLayoutSize = activeMinimumLayoutSize(self, bounds);
3362 _page->setViewportConfigurationMinimumLayoutSize(minimalLayoutSize);
3363 _page->setMaximumUnobscuredSize(activeMaximumUnobscuredSize(self, bounds));
3367 - (NSData *)_sessionStateData
3369 WebKit::SessionState sessionState = _page->sessionState();
3371 // FIXME: This should not use the legacy session state encoder.
3372 return [wrapper(*WebKit::encodeLegacySessionState(sessionState).leakRef()) autorelease];
3375 - (_WKSessionState *)_sessionState
3377 return adoptNS([[_WKSessionState alloc] _initWithSessionState:_page->sessionState()]).autorelease();
3380 - (_WKSessionState *)_sessionStateWithFilter:(BOOL (^)(WKBackForwardListItem *item))filter
3382 WebKit::SessionState sessionState = _page->sessionState([filter](WebKit::WebBackForwardListItem& item) {
3386 return (bool)filter(wrapper(item));
3389 return adoptNS([[_WKSessionState alloc] _initWithSessionState:sessionState]).autorelease();
3392 - (void)_restoreFromSessionStateData:(NSData *)sessionStateData
3394 // FIXME: This should not use the legacy session state decoder.
3395 WebKit::SessionState sessionState;
3396 if (!WebKit::decodeLegacySessionState(static_cast<const uint8_t*>(sessionStateData.bytes), sessionStateData.length, sessionState))
3399 _page->restoreFromSessionState(WTFMove(sessionState), true);
3402 - (WKNavigation *)_restoreSessionState:(_WKSessionState *)sessionState andNavigate:(BOOL)navigate
3404 auto navigation = _page->restoreFromSessionState(sessionState->_sessionState, navigate);
3408 return [wrapper(*navigation.leakRef()) autorelease];
3416 - (BOOL)_allowsRemoteInspection
3418 #if ENABLE(REMOTE_INSPECTOR)
3419 return _page->allowsRemoteInspection();
3425 - (void)_setAllowsRemoteInspection:(BOOL)allow
3427 #if ENABLE(REMOTE_INSPECTOR)
3428 _page->setAllowsRemoteInspection(allow);
3432 - (NSString *)_remoteInspectionNameOverride
3434 #if ENABLE(REMOTE_INSPECTOR)
3435 return _page->remoteInspectionNameOverride();
3441 - (void)_setRemoteInspectionNameOverride:(NSString *)name
3443 #if ENABLE(REMOTE_INSPECTOR)
3444 _page->setRemoteInspectionNameOverride(name);
3448 - (BOOL)_addsVisitedLinks
3450 return _page->addsVisitedLinks();
3453 - (void)_setAddsVisitedLinks:(BOOL)addsVisitedLinks
3455 _page->setAddsVisitedLinks(addsVisitedLinks);
3458 - (BOOL)_networkRequestsInProgress
3460 return _page->pageLoadState().networkRequestsInProgress();
3463 static inline WebCore::LayoutMilestones layoutMilestones(_WKRenderingProgressEvents events)
3465 WebCore::LayoutMilestones milestones = 0;
3467 if (events & _WKRenderingProgressEventFirstLayout)
3468 milestones |= WebCore::DidFirstLayout;
3470 if (events & _WKRenderingProgressEventFirstVisuallyNonEmptyLayout)
3471 milestones |= WebCore::DidFirstVisuallyNonEmptyLayout;
3473 if (events & _WKRenderingProgressEventFirstPaintWithSignificantArea)
3474 milestones |= WebCore::DidHitRelevantRepaintedObjectsAreaThreshold;
3476 if (events & _WKRenderingProgressEventReachedSessionRestorationRenderTreeSizeThreshold)
3477 milestones |= WebCore::ReachedSessionRestorationRenderTreeSizeThreshold;
3479 if (events & _WKRenderingProgressEventFirstLayoutAfterSuppressedIncrementalRendering)
3480 milestones |= WebCore::DidFirstLayoutAfterSuppressedIncrementalRendering;
3482 if (events & _WKRenderingProgressEventFirstPaintAfterSuppressedIncrementalRendering)
3483 milestones |= WebCore::DidFirstPaintAfterSuppressedIncrementalRendering;
3488 - (void)_setObservedRenderingProgressEvents:(_WKRenderingProgressEvents)observedRenderingProgressEvents
3490 _observedRenderingProgressEvents = observedRenderingProgressEvents;
3491 _page->listenForLayoutMilestones(layoutMilestones(observedRenderingProgressEvents));
3494 - (void)_getMainResourceDataWithCompletionHandler:(void (^)(NSData *, NSError *))completionHandler
3496 auto handler = adoptNS([completionHandler copy]);
3498 _page->getMainResourceDataOfFrame(_page->mainFrame(), [handler](API::Data* data, WebKit::CallbackBase::Error error) {
3499 void (^completionHandlerBlock)(NSData *, NSError *) = (void (^)(NSData *, NSError *))handler.get();
3500 if (error != WebKit::CallbackBase::Error::None) {
3501 // FIXME: Pipe a proper error in from the WebPageProxy.
3502 RetainPtr<NSError> error = adoptNS([[NSError alloc] init]);
3503 completionHandlerBlock(nil, error.get());
3505 completionHandlerBlock(wrapper(*data), nil);
3509 - (void)_getWebArchiveDataWithCompletionHandler:(void (^)(NSData *, NSError *))completionHandler
3511 auto handler = adoptNS([completionHandler copy]);
3513 _page->getWebArchiveOfFrame(_page->mainFrame(), [handler](API::Data* data, WebKit::CallbackBase::Error error) {
3514 void (^completionHandlerBlock)(NSData *, NSError *) = (void (^)(NSData *, NSError *))handler.get();
3515 if (error != WebKit::CallbackBase::Error::None) {
3516 // FIXME: Pipe a proper error in from the WebPageProxy.
3517 RetainPtr<NSError> error = adoptNS([[NSError alloc] init]);
3518 completionHandlerBlock(nil, error.get());
3520 completionHandlerBlock(wrapper(*data), nil);
3524 - (_WKPaginationMode)_paginationMode
3526 switch (_page->paginationMode()) {
3527 case WebCore::Pagination::Unpaginated:
3528 return _WKPaginationModeUnpaginated;
3529 case WebCore::Pagination::LeftToRightPaginated:
3530 return _WKPaginationModeLeftToRight;
3531 case WebCore::Pagination::RightToLeftPaginated:
3532 return _WKPaginationModeRightToLeft;
3533 case WebCore::Pagination::TopToBottomPaginated:
3534 return _WKPaginationModeTopToBottom;
3535 case WebCore::Pagination::BottomToTopPaginated:
3536 return _WKPaginationModeBottomToTop;
3539 ASSERT_NOT_REACHED();
3540 return _WKPaginationModeUnpaginated;
3543 - (void)_setPaginationMode:(_WKPaginationMode)paginationMode
3545 WebCore::Pagination::Mode mode;