2 * Copyright (C) 2014 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 "CompletionHandlerCallChecker.h"
33 #import "FindClient.h"
34 #import "LegacySessionStateCoding.h"
35 #import "NavigationState.h"
36 #import "RemoteLayerTreeTransaction.h"
37 #import "RemoteObjectRegistry.h"
38 #import "RemoteObjectRegistryMessages.h"
39 #import "UIDelegate.h"
40 #import "ViewGestureController.h"
41 #import "ViewSnapshotStore.h"
42 #import "WKBackForwardListInternal.h"
43 #import "WKBackForwardListItemInternal.h"
44 #import "WKBrowsingContextHandleInternal.h"
45 #import "WKErrorInternal.h"
46 #import "WKHistoryDelegatePrivate.h"
48 #import "WKNSURLExtras.h"
49 #import "WKNavigationDelegate.h"
50 #import "WKNavigationInternal.h"
51 #import "WKPreferencesInternal.h"
52 #import "WKProcessPoolInternal.h"
53 #import "WKUIDelegate.h"
54 #import "WKUIDelegatePrivate.h"
55 #import "WKUserContentControllerInternal.h"
56 #import "WKWebViewConfigurationInternal.h"
57 #import "WKWebViewContentProvider.h"
58 #import "WebBackForwardList.h"
59 #import "WebCertificateInfo.h"
60 #import "WebContext.h"
61 #import "WebFormSubmissionListenerProxy.h"
62 #import "WebKitSystemInterface.h"
63 #import "WebPageGroup.h"
64 #import "WebPageProxy.h"
65 #import "WebPreferencesKeys.h"
66 #import "WebProcessProxy.h"
67 #import "WebSerializedScriptValue.h"
68 #import "_WKFindDelegate.h"
69 #import "_WKFormDelegate.h"
70 #import "_WKRemoteObjectRegistryInternal.h"
71 #import "_WKSessionStateInternal.h"
72 #import "_WKVisitedLinkProviderInternal.h"
73 #import "_WKWebsiteDataStoreInternal.h"
74 #import <JavaScriptCore/JSContext.h>
75 #import <JavaScriptCore/JSValue.h>
76 #import <wtf/HashMap.h>
77 #import <wtf/NeverDestroyed.h>
78 #import <wtf/RetainPtr.h>
81 #import "_WKFrameHandleInternal.h"
82 #import "_WKWebViewPrintFormatter.h"
84 #import "ProcessThrottler.h"
85 #import "RemoteLayerTreeDrawingAreaProxy.h"
87 #import "WKScrollView.h"
88 #import "WKWebViewContentProviderRegistry.h"
89 #import "WebPageMessages.h"
90 #import <CoreGraphics/CGFloat.h>
91 #import <CoreGraphics/CGPDFDocumentPrivate.h>
92 #import <UIKit/UIApplication.h>
93 #import <UIKit/UIDevice_Private.h>
94 #import <UIKit/UIPeripheralHost_Private.h>
95 #import <UIKit/UIWindow_Private.h>
96 #import <QuartzCore/CARenderServer.h>
97 #import <QuartzCore/QuartzCorePrivate.h>
98 #import <WebCore/InspectorOverlay.h>
100 @interface UIScrollView (UIScrollViewInternal)
101 - (void)_adjustForAutomaticKeyboardInfo:(NSDictionary*)info animated:(BOOL)animated lastAdjustment:(CGFloat*)lastAdjustment;
102 - (BOOL)_isScrollingToTop;
105 @interface UIPeripheralHost(UIKitInternal)
106 - (CGFloat)getVerticalOverlapForView:(UIView *)view usingKeyboardInfo:(NSDictionary *)info;
109 @interface UIView (UIViewInternal)
110 - (UIViewController *)_viewControllerForAncestor;
113 @interface UIWindow (UIWindowInternal)
114 - (BOOL)_isHostedInAnotherProcess;
117 @interface UIViewController (UIViewControllerInternal)
118 - (UIViewController *)_rootAncestorViewController;
119 - (UIViewController *)_viewControllerForSupportedInterfaceOrientations;
122 enum class DynamicViewportUpdateMode {
124 ResizingWithAnimation,
125 ResizingWithDocumentHidden,
131 #import "WKViewInternal.h"
132 #import <WebCore/ColorMac.h>
136 static HashMap<WebKit::WebPageProxy*, WKWebView *>& pageToViewMap()
138 static NeverDestroyed<HashMap<WebKit::WebPageProxy*, WKWebView *>> map;
142 WKWebView* fromWebPageProxy(WebKit::WebPageProxy& page)
144 return pageToViewMap().get(&page);
147 @implementation WKWebView {
148 std::unique_ptr<WebKit::NavigationState> _navigationState;
149 std::unique_ptr<WebKit::UIDelegate> _uiDelegate;
151 RetainPtr<_WKRemoteObjectRegistry> _remoteObjectRegistry;
152 _WKRenderingProgressEvents _observedRenderingProgressEvents;
154 WebKit::WeakObjCPtr<id <_WKFormDelegate>> _formDelegate;
156 RetainPtr<WKScrollView> _scrollView;
157 RetainPtr<WKContentView> _contentView;
159 BOOL _overridesMinimumLayoutSize;
160 CGSize _minimumLayoutSizeOverride;
161 BOOL _overridesMinimumLayoutSizeForMinimalUI;
162 CGSize _minimumLayoutSizeOverrideForMinimalUI;
163 BOOL _overridesMaximumUnobscuredSize;
164 CGSize _maximumUnobscuredSizeOverride;
166 BOOL _needsToNotifyDelegateAboutMinimalUI;
167 CGRect _inputViewBounds;
168 CGFloat _viewportMetaTagWidth;
170 UIEdgeInsets _obscuredInsets;
171 bool _isChangingObscuredInsetsInteractively;
173 UIInterfaceOrientation _interfaceOrientationOverride;
174 BOOL _overridesInterfaceOrientation;
176 BOOL _hasCommittedLoadForMainFrame;
177 BOOL _needsResetViewStateAfterCommitLoadForMainFrame;
178 uint64_t _firstPaintAfterCommitLoadTransactionID;
179 DynamicViewportUpdateMode _dynamicViewportUpdateMode;
180 CATransform3D _resizeAnimationTransformAdjustments;
181 uint64_t _resizeAnimationTransformTransactionID;
182 RetainPtr<UIView> _resizeAnimationView;
183 CGFloat _lastAdjustmentForScroller;
185 BOOL _needsToRestoreExposedRect;
186 WebCore::FloatRect _exposedRectToRestore;
187 BOOL _needsToRestoreUnobscuredCenter;
188 WebCore::FloatPoint _unobscuredCenterToRestore;
189 uint64_t _firstTransactionIDAfterPageRestore;
190 double _scaleToRestore;
192 std::unique_ptr<WebKit::ViewGestureController> _gestureController;
193 BOOL _allowsBackForwardNavigationGestures;
195 RetainPtr<UIView <WKWebViewContentProvider>> _customContentView;
196 RetainPtr<UIView> _customContentFixedOverlayView;
198 WebCore::Color _scrollViewBackgroundColor;
200 BOOL _delayUpdateVisibleContentRects;
201 BOOL _hadDelayedUpdateVisibleContentRects;
203 BOOL _pageIsPrintingToPDF;
204 RetainPtr<CGPDFDocumentRef> _printedDocument;
207 RetainPtr<WKView> _wkView;
211 - (instancetype)initWithFrame:(CGRect)frame
213 return [self initWithFrame:frame configuration:adoptNS([[WKWebViewConfiguration alloc] init]).get()];
217 static int32_t deviceOrientationForUIInterfaceOrientation(UIInterfaceOrientation orientation)
219 switch (orientation) {
220 case UIInterfaceOrientationUnknown:
221 case UIInterfaceOrientationPortrait:
223 case UIInterfaceOrientationPortraitUpsideDown:
225 case UIInterfaceOrientationLandscapeLeft:
227 case UIInterfaceOrientationLandscapeRight:
232 static int32_t deviceOrientation()
234 return deviceOrientationForUIInterfaceOrientation([[UIApplication sharedApplication] statusBarOrientation]);
238 - (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration
240 if (!(self = [super initWithFrame:frame]))
243 _configuration = adoptNS([configuration copy]);
245 if (WKWebView *relatedWebView = [_configuration _relatedWebView]) {
246 WKProcessPool *processPool = [_configuration processPool];
247 WKProcessPool *relatedWebViewProcessPool = [relatedWebView->_configuration processPool];
248 if (processPool && processPool != relatedWebViewProcessPool)
249 [NSException raise:NSInvalidArgumentException format:@"Related web view %@ has process pool %@ but configuration specifies a different process pool %@", relatedWebView, relatedWebViewProcessPool, configuration.processPool];
251 [_configuration setProcessPool:relatedWebViewProcessPool];
254 [_configuration _validate];
256 CGRect bounds = self.bounds;
258 WebKit::WebContext& context = *[_configuration processPool]->_context;
260 WebKit::WebPageConfiguration webPageConfiguration;
261 webPageConfiguration.preferences = [_configuration preferences]->_preferences.get();
262 if (WKWebView *relatedWebView = [_configuration _relatedWebView])
263 webPageConfiguration.relatedPage = relatedWebView->_page.get();
265 webPageConfiguration.userContentController = [_configuration userContentController]->_userContentControllerProxy.get();
266 webPageConfiguration.visitedLinkProvider = [_configuration _visitedLinkProvider]->_visitedLinkProvider.get();
267 webPageConfiguration.session = [_configuration _websiteDataStore]->_session.get();
269 RefPtr<WebKit::WebPageGroup> pageGroup;
270 NSString *groupIdentifier = configuration._groupIdentifier;
271 if (groupIdentifier.length) {
272 pageGroup = WebKit::WebPageGroup::create(configuration._groupIdentifier);
273 webPageConfiguration.pageGroup = pageGroup.get();
276 webPageConfiguration.preferenceValues.set(WebKit::WebPreferencesKey::suppressesIncrementalRenderingKey(), WebKit::WebPreferencesStore::Value(!![_configuration suppressesIncrementalRendering]));
279 webPageConfiguration.preferenceValues.set(WebKit::WebPreferencesKey::mediaPlaybackAllowsInlineKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsInlineMediaPlayback]));
280 webPageConfiguration.preferenceValues.set(WebKit::WebPreferencesKey::mediaPlaybackRequiresUserGestureKey(), WebKit::WebPreferencesStore::Value(!![_configuration mediaPlaybackRequiresUserAction]));
281 webPageConfiguration.preferenceValues.set(WebKit::WebPreferencesKey::mediaPlaybackAllowsAirPlayKey(), WebKit::WebPreferencesStore::Value(!![_configuration mediaPlaybackAllowsAirPlay]));
285 _scrollView = adoptNS([[WKScrollView alloc] initWithFrame:bounds]);
286 [_scrollView setInternalDelegate:self];
287 [_scrollView setBouncesZoom:YES];
289 [self addSubview:_scrollView.get()];
291 _contentView = adoptNS([[WKContentView alloc] initWithFrame:bounds context:context configuration:WTF::move(webPageConfiguration) webView:self]);
293 _page = [_contentView page];
294 _page->setApplicationNameForUserAgent([@"Mobile/" stringByAppendingString:[UIDevice currentDevice].buildVersion]);
295 _page->setDeviceOrientation(deviceOrientation());
297 [_contentView layer].anchorPoint = CGPointZero;
298 [_contentView setFrame:bounds];
299 [_scrollView addSubview:_contentView.get()];
300 [_scrollView addSubview:[_contentView unscaledView]];
301 [self _updateScrollViewBackground];
303 _viewportMetaTagWidth = -1;
305 [self _frameOrBoundsChanged];
307 NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
308 [center addObserver:self selector:@selector(_keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
309 [center addObserver:self selector:@selector(_keyboardDidChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
310 [center addObserver:self selector:@selector(_keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
311 [center addObserver:self selector:@selector(_keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
312 [center addObserver:self selector:@selector(_windowDidRotate:) name:UIWindowDidRotateNotification object:nil];
313 [center addObserver:self selector:@selector(_contentSizeCategoryDidChange:) name:UIContentSizeCategoryDidChangeNotification object:nil];
314 _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
316 [[_configuration _contentProviderRegistry] addPage:*_page];
320 _wkView = adoptNS([[WKView alloc] initWithFrame:bounds context:context configuration:WTF::move(webPageConfiguration) webView:self]);
321 [self addSubview:_wkView.get()];
322 _page = WebKit::toImpl([_wkView pageRef]);
324 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
325 [_wkView _setAutomaticallyAdjustsContentInsets:YES];
329 _page->setBackgroundExtendsBeyondPage(true);
331 _navigationState = std::make_unique<WebKit::NavigationState>(self);
332 _page->setPolicyClient(_navigationState->createPolicyClient());
333 _page->setLoaderClient(_navigationState->createLoaderClient());
335 _uiDelegate = std::make_unique<WebKit::UIDelegate>(self);
336 _page->setUIClient(_uiDelegate->createUIClient());
338 _page->setFindClient(std::make_unique<WebKit::FindClient>(self));
340 pageToViewMap().add(_page.get(), self);
345 - (instancetype)initWithCoder:(NSCoder *)coder
355 [_remoteObjectRegistry _invalidate];
357 [[_configuration _contentProviderRegistry] removePage:*_page];
358 [[NSNotificationCenter defaultCenter] removeObserver:self];
361 pageToViewMap().remove(_page.get());
366 - (WKWebViewConfiguration *)configuration
368 return [[_configuration copy] autorelease];
371 - (WKBackForwardList *)backForwardList
373 return wrapper(_page->backForwardList());
376 - (id <WKNavigationDelegate>)navigationDelegate
378 return _navigationState->navigationDelegate().autorelease();
381 - (void)setNavigationDelegate:(id <WKNavigationDelegate>)navigationDelegate
383 _navigationState->setNavigationDelegate(navigationDelegate);
386 - (id <WKUIDelegate>)UIDelegate
388 return _uiDelegate->delegate().autorelease();
391 - (void)setUIDelegate:(id<WKUIDelegate>)UIDelegate
393 _uiDelegate->setDelegate(UIDelegate);
396 - (WKNavigation *)loadRequest:(NSURLRequest *)request
398 uint64_t navigationID = _page->loadRequest(request);
399 auto navigation = _navigationState->createLoadRequestNavigation(navigationID, request);
401 return navigation.autorelease();
404 - (WKNavigation *)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
406 uint64_t navigationID = _page->loadHTMLString(string, baseURL.absoluteString);
410 auto navigation = _navigationState->createLoadDataNavigation(navigationID);
412 return navigation.autorelease();
415 - (WKNavigation *)goToBackForwardListItem:(WKBackForwardListItem *)item
417 uint64_t navigationID = _page->goToBackForwardItem(&item._item);
419 auto navigation = _navigationState->createBackForwardNavigation(navigationID, item._item);
421 return navigation.autorelease();
426 return _page->pageLoadState().title();
431 return [NSURL _web_URLWithWTFString:_page->pageLoadState().activeURL()];
436 return _page->pageLoadState().isLoading();
439 - (double)estimatedProgress
441 return _page->pageLoadState().estimatedProgress();
444 - (BOOL)hasOnlySecureContent
446 return _page->pageLoadState().hasOnlySecureContent();
451 return _page->pageLoadState().canGoBack();
456 return _page->pageLoadState().canGoForward();
459 - (WKNavigation *)goBack
461 uint64_t navigationID = _page->goBack();
465 ASSERT(_page->backForwardList().currentItem());
466 auto navigation = _navigationState->createBackForwardNavigation(navigationID, *_page->backForwardList().currentItem());
468 return navigation.autorelease();
471 - (WKNavigation *)goForward
473 uint64_t navigationID = _page->goForward();
477 ASSERT(_page->backForwardList().currentItem());
478 auto navigation = _navigationState->createBackForwardNavigation(navigationID, *_page->backForwardList().currentItem());
480 return navigation.autorelease();
483 - (WKNavigation *)reload
485 uint64_t navigationID = _page->reload(false);
489 auto navigation = _navigationState->createReloadNavigation(navigationID);
490 return navigation.autorelease();
493 - (WKNavigation *)reloadFromOrigin
495 uint64_t navigationID = _page->reload(true);
499 auto navigation = _navigationState->createReloadNavigation(navigationID);
500 return navigation.autorelease();
505 _page->stopLoading();
508 static WKErrorCode callbackErrorCode(WebKit::CallbackBase::Error error)
511 case WebKit::CallbackBase::Error::None:
512 ASSERT_NOT_REACHED();
513 return WKErrorUnknown;
515 case WebKit::CallbackBase::Error::Unknown:
516 return WKErrorUnknown;
518 case WebKit::CallbackBase::Error::ProcessExited:
519 return WKErrorWebContentProcessTerminated;
521 case WebKit::CallbackBase::Error::OwnerWasInvalidated:
522 return WKErrorWebViewInvalidated;
526 - (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *))completionHandler
528 auto handler = adoptNS([completionHandler copy]);
530 _page->runJavaScriptInMainFrame(javaScriptString, [handler](WebKit::WebSerializedScriptValue* serializedScriptValue, WebKit::ScriptValueCallback::Error errorCode) {
534 auto completionHandler = (void (^)(id, NSError *))handler.get();
536 if (errorCode != WebKit::ScriptValueCallback::Error::None) {
537 auto error = createNSError(callbackErrorCode(errorCode));
538 if (errorCode == WebKit::ScriptValueCallback::Error::OwnerWasInvalidated) {
539 // The OwnerWasInvalidated callback is synchronous. We don't want to call the block from within it
540 // because that can trigger re-entrancy bugs in WebKit.
541 // FIXME: It would be even better if GenericCallback did this for us.
542 dispatch_async(dispatch_get_main_queue(), [completionHandler, error] {
543 completionHandler(nil, error.get());
548 completionHandler(nil, error.get());
552 if (!serializedScriptValue) {
553 completionHandler(nil, createNSError(WKErrorJavaScriptExceptionOccurred).get());
557 auto context = adoptNS([[JSContext alloc] init]);
558 JSValueRef valueRef = serializedScriptValue->deserialize([context JSGlobalContextRef], 0);
559 JSValue *value = [JSValue valueWithJSValueRef:valueRef inContext:context.get()];
561 completionHandler([value toObject], nil);
565 #pragma mark iOS-specific methods
568 - (void)setFrame:(CGRect)frame
570 CGRect oldFrame = self.frame;
571 [super setFrame:frame];
573 if (!CGSizeEqualToSize(oldFrame.size, frame.size))
574 [self _frameOrBoundsChanged];
577 - (void)setBounds:(CGRect)bounds
579 CGRect oldBounds = self.bounds;
580 [super setBounds:bounds];
581 [_customContentFixedOverlayView setFrame:self.bounds];
583 if (!CGSizeEqualToSize(oldBounds.size, bounds.size))
584 [self _frameOrBoundsChanged];
587 - (UIScrollView *)scrollView
589 return _scrollView.get();
592 - (WKBrowsingContextController *)browsingContextController
594 return [_contentView browsingContextController];
597 static inline CGFloat floorToDevicePixel(CGFloat input, float deviceScaleFactor)
599 return CGFloor(input * deviceScaleFactor) / deviceScaleFactor;
602 static CGSize roundScrollViewContentSize(const WebKit::WebPageProxy& page, CGSize contentSize)
604 float deviceScaleFactor = page.deviceScaleFactor();
605 return CGSizeMake(floorToDevicePixel(contentSize.width, deviceScaleFactor), floorToDevicePixel(contentSize.height, deviceScaleFactor));
608 - (UIView *)_currentContentView
610 return _customContentView ? _customContentView.get() : _contentView.get();
613 - (void)_setHasCustomContentView:(BOOL)pageHasCustomContentView loadedMIMEType:(const WTF::String&)mimeType
615 if (pageHasCustomContentView) {
616 [_customContentView removeFromSuperview];
617 [_customContentFixedOverlayView removeFromSuperview];
619 Class representationClass = [[_configuration _contentProviderRegistry] providerForMIMEType:mimeType];
620 ASSERT(representationClass);
621 _customContentView = adoptNS([[representationClass alloc] web_initWithFrame:self.bounds webView:self]);
622 _customContentFixedOverlayView = adoptNS([[UIView alloc] initWithFrame:self.bounds]);
623 [_customContentFixedOverlayView setUserInteractionEnabled:NO];
625 [[_contentView unscaledView] removeFromSuperview];
626 [_contentView removeFromSuperview];
627 [_scrollView addSubview:_customContentView.get()];
628 [self addSubview:_customContentFixedOverlayView.get()];
630 [_customContentView web_setMinimumSize:self.bounds.size];
631 [_customContentView web_setFixedOverlayView:_customContentFixedOverlayView.get()];
632 } else if (_customContentView) {
633 [_customContentView removeFromSuperview];
634 _customContentView = nullptr;
636 [_customContentFixedOverlayView removeFromSuperview];
637 _customContentFixedOverlayView = nullptr;
639 [_scrollView addSubview:_contentView.get()];
640 [_scrollView addSubview:[_contentView unscaledView]];
641 [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
643 [_customContentFixedOverlayView setFrame:self.bounds];
644 [self addSubview:_customContentFixedOverlayView.get()];
648 - (void)_didFinishLoadingDataForCustomContentProviderWithSuggestedFilename:(const String&)suggestedFilename data:(NSData *)data
650 ASSERT(_customContentView);
651 [_customContentView web_setContentProviderData:data suggestedFilename:suggestedFilename];
654 - (void)_setViewportMetaTagWidth:(float)newWidth
656 _viewportMetaTagWidth = newWidth;
659 - (void)_willInvokeUIScrollViewDelegateCallback
661 _delayUpdateVisibleContentRects = YES;
664 - (void)_didInvokeUIScrollViewDelegateCallback
666 _delayUpdateVisibleContentRects = NO;
667 if (_hadDelayedUpdateVisibleContentRects) {
668 _hadDelayedUpdateVisibleContentRects = NO;
669 [self _updateVisibleContentRects];
673 static CGFloat contentZoomScale(WKWebView *webView)
675 CGFloat scale = webView._currentContentView.layer.affineTransform.a;
676 ASSERT(scale == [webView->_scrollView zoomScale]);
680 static WebCore::Color scrollViewBackgroundColor(WKWebView *webView)
683 return WebCore::Color::transparent;
685 WebCore::Color color;
687 if (webView->_customContentView)
688 color = [webView->_customContentView backgroundColor].CGColor;
690 color = webView->_page->pageExtendedBackgroundColor();
692 if (!color.isValid())
693 color = WebCore::Color::white;
695 CGFloat zoomScale = contentZoomScale(webView);
696 CGFloat minimumZoomScale = [webView->_scrollView minimumZoomScale];
697 if (zoomScale < minimumZoomScale) {
699 CGFloat opacity = std::max<CGFloat>(1 - slope * (minimumZoomScale - zoomScale), 0);
700 color = WebCore::colorWithOverrideAlpha(color.rgb(), opacity);
706 - (void)_updateScrollViewBackground
708 WebCore::Color color = scrollViewBackgroundColor(self);
710 if (_scrollViewBackgroundColor == color)
713 _scrollViewBackgroundColor = color;
715 auto uiBackgroundColor = adoptNS([[UIColor alloc] initWithCGColor:cachedCGColor(color, WebCore::ColorSpaceDeviceRGB)]);
716 [_scrollView setBackgroundColor:uiBackgroundColor.get()];
719 - (void)_setUsesMinimalUI:(BOOL)usesMinimalUI
721 _usesMinimalUI = usesMinimalUI;
722 _needsToNotifyDelegateAboutMinimalUI = YES;
725 - (BOOL)_usesMinimalUI
727 return _usesMinimalUI;
730 - (CGPoint)_adjustedContentOffset:(CGPoint)point
732 CGPoint result = point;
733 UIEdgeInsets contentInset = [self _computedContentInset];
735 result.x -= contentInset.left;
736 result.y -= contentInset.top;
741 - (UIEdgeInsets)_computedContentInset
743 if (!UIEdgeInsetsEqualToEdgeInsets(_obscuredInsets, UIEdgeInsetsZero))
744 return _obscuredInsets;
746 return [_scrollView contentInset];
749 - (void)_processDidExit
751 if (!_customContentView && _dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
752 NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
753 [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
754 [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
755 [_resizeAnimationView removeFromSuperview];
756 _resizeAnimationView = nil;
758 _resizeAnimationTransformAdjustments = CATransform3DIdentity;
760 [_contentView setFrame:self.bounds];
761 [_scrollView setBackgroundColor:[UIColor whiteColor]];
762 [_scrollView setContentOffset:[self _adjustedContentOffset:CGPointZero]];
763 [_scrollView setZoomScale:1];
765 _viewportMetaTagWidth = -1;
766 _hasCommittedLoadForMainFrame = NO;
767 _needsResetViewStateAfterCommitLoadForMainFrame = NO;
768 _dynamicViewportUpdateMode = DynamicViewportUpdateMode::NotResizing;
769 [_contentView setHidden:NO];
770 _needsToRestoreExposedRect = NO;
771 _needsToRestoreUnobscuredCenter = NO;
772 _scrollViewBackgroundColor = WebCore::Color();
773 _delayUpdateVisibleContentRects = NO;
774 _hadDelayedUpdateVisibleContentRects = NO;
777 - (void)_didCommitLoadForMainFrame
779 _firstPaintAfterCommitLoadTransactionID = toRemoteLayerTreeDrawingAreaProxy(_page->drawingArea())->nextLayerTreeTransactionID();
781 _hasCommittedLoadForMainFrame = YES;
782 _needsResetViewStateAfterCommitLoadForMainFrame = YES;
786 static void changeContentOffsetBoundedInValidRange(UIScrollView *scrollView, WebCore::FloatPoint contentOffset)
788 UIEdgeInsets contentInsets = scrollView.contentInset;
789 CGSize contentSize = scrollView.contentSize;
790 CGSize scrollViewSize = scrollView.bounds.size;
792 float maxHorizontalOffset = contentSize.width + contentInsets.right - scrollViewSize.width;
793 if (contentOffset.x() > maxHorizontalOffset)
794 contentOffset.setX(maxHorizontalOffset);
795 float maxVerticalOffset = contentSize.height + contentInsets.bottom - scrollViewSize.height;
796 if (contentOffset.y() > maxVerticalOffset)
797 contentOffset.setY(maxVerticalOffset);
798 if (contentOffset.x() < -contentInsets.left)
799 contentOffset.setX(-contentInsets.left);
800 if (contentOffset.y() < -contentInsets.top)
801 contentOffset.setY(-contentInsets.top);
802 scrollView.contentOffset = contentOffset;
805 // WebCore stores the page scale factor as float instead of double. When we get a scale from WebCore,
806 // we need to ignore differences that are within a small rounding error on floats.
807 template <typename TypeA, typename TypeB>
808 static inline bool withinEpsilon(TypeA a, TypeB b)
810 return std::abs(a - b) < std::numeric_limits<float>::epsilon();
813 - (void)_didCommitLayerTree:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
815 if (_customContentView)
818 if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
819 if (layerTreeTransaction.transactionID() >= _resizeAnimationTransformTransactionID) {
820 [_resizeAnimationView layer].sublayerTransform = _resizeAnimationTransformAdjustments;
821 if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::ResizingWithDocumentHidden) {
822 [_contentView setHidden:NO];
823 [self _endAnimatedResize];
829 CGSize newContentSize = roundScrollViewContentSize(*_page, [_contentView frame].size);
830 [_scrollView _setContentSizePreservingContentOffsetDuringRubberband:newContentSize];
832 [_scrollView setMinimumZoomScale:layerTreeTransaction.minimumScaleFactor()];
833 [_scrollView setMaximumZoomScale:layerTreeTransaction.maximumScaleFactor()];
834 [_scrollView setZoomEnabled:layerTreeTransaction.allowsUserScaling()];
835 if (!layerTreeTransaction.scaleWasSetByUIProcess() && ![_scrollView isZooming] && ![_scrollView isZoomBouncing] && ![_scrollView _isAnimatingZoom])
836 [_scrollView setZoomScale:layerTreeTransaction.pageScaleFactor()];
838 [self _updateScrollViewBackground];
840 if (_gestureController)
841 _gestureController->setRenderTreeSize(layerTreeTransaction.renderTreeSize());
843 if (_needsToNotifyDelegateAboutMinimalUI || _needsResetViewStateAfterCommitLoadForMainFrame) {
844 _needsToNotifyDelegateAboutMinimalUI = NO;
846 auto delegate = _uiDelegate->delegate();
847 if ([delegate respondsToSelector:@selector(_webView:usesMinimalUI:)])
848 [static_cast<id <WKUIDelegatePrivate>>(delegate.get()) _webView:self usesMinimalUI:_usesMinimalUI];
851 if (_needsResetViewStateAfterCommitLoadForMainFrame && layerTreeTransaction.transactionID() >= _firstPaintAfterCommitLoadTransactionID) {
852 _needsResetViewStateAfterCommitLoadForMainFrame = NO;
853 [_scrollView setContentOffset:[self _adjustedContentOffset:CGPointZero]];
854 [self _updateVisibleContentRects];
857 if (_needsToRestoreExposedRect && layerTreeTransaction.transactionID() >= _firstTransactionIDAfterPageRestore) {
858 _needsToRestoreExposedRect = NO;
860 if (withinEpsilon(contentZoomScale(self), _scaleToRestore)) {
861 WebCore::FloatPoint exposedPosition = _exposedRectToRestore.location();
862 exposedPosition.scale(_scaleToRestore, _scaleToRestore);
864 changeContentOffsetBoundedInValidRange(_scrollView.get(), exposedPosition);
866 [self _updateVisibleContentRects];
869 if (_needsToRestoreUnobscuredCenter && layerTreeTransaction.transactionID() >= _firstTransactionIDAfterPageRestore) {
870 _needsToRestoreUnobscuredCenter = NO;
872 if (withinEpsilon(contentZoomScale(self), _scaleToRestore)) {
873 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, _obscuredInsets);
874 WebCore::FloatSize unobscuredContentSizeAtNewScale(unobscuredRect.size.width / _scaleToRestore, unobscuredRect.size.height / _scaleToRestore);
875 WebCore::FloatPoint topLeftInDocumentCoordinate(_unobscuredCenterToRestore.x() - unobscuredContentSizeAtNewScale.width() / 2, _unobscuredCenterToRestore.y() - unobscuredContentSizeAtNewScale.height() / 2);
877 topLeftInDocumentCoordinate.scale(_scaleToRestore, _scaleToRestore);
878 topLeftInDocumentCoordinate.moveBy(WebCore::FloatPoint(-_obscuredInsets.left, -_obscuredInsets.top));
880 changeContentOffsetBoundedInValidRange(_scrollView.get(), topLeftInDocumentCoordinate);
882 [self _updateVisibleContentRects];
886 - (void)_dynamicViewportUpdateChangedTargetToScale:(double)newScale position:(CGPoint)newScrollPosition nextValidLayerTreeTransactionID:(uint64_t)nextValidLayerTreeTransactionID
888 if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
889 CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
890 double currentTargetScale = animatingScaleTarget * [[_contentView layer] transform].m11;
891 double scale = newScale / currentTargetScale;
892 _resizeAnimationTransformAdjustments = CATransform3DMakeScale(scale, scale, 1);
894 CGPoint newContentOffset = [self _adjustedContentOffset:CGPointMake(newScrollPosition.x * newScale, newScrollPosition.y * newScale)];
895 CGPoint currentContentOffset = [_scrollView contentOffset];
897 _resizeAnimationTransformAdjustments.m41 = (currentContentOffset.x - newContentOffset.x) / animatingScaleTarget;
898 _resizeAnimationTransformAdjustments.m42 = (currentContentOffset.y - newContentOffset.y) / animatingScaleTarget;
899 _resizeAnimationTransformTransactionID = nextValidLayerTreeTransactionID;
903 - (void)_restorePageStateToExposedRect:(WebCore::FloatRect)exposedRect scale:(double)scale
905 if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
908 if (_customContentView)
911 _needsToRestoreUnobscuredCenter = NO;
912 _needsToRestoreExposedRect = YES;
913 _firstTransactionIDAfterPageRestore = toRemoteLayerTreeDrawingAreaProxy(_page->drawingArea())->nextLayerTreeTransactionID();
914 _exposedRectToRestore = exposedRect;
915 _scaleToRestore = scale;
918 - (void)_restorePageStateToUnobscuredCenter:(WebCore::FloatPoint)center scale:(double)scale
920 if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
923 if (_customContentView)
926 _needsToRestoreExposedRect = NO;
927 _needsToRestoreUnobscuredCenter = YES;
928 _firstTransactionIDAfterPageRestore = toRemoteLayerTreeDrawingAreaProxy(_page->drawingArea())->nextLayerTreeTransactionID();
929 _unobscuredCenterToRestore = center;
930 _scaleToRestore = scale;
933 - (PassRefPtr<WebKit::ViewSnapshot>)_takeViewSnapshot
935 float deviceScale = WKGetScreenScaleFactor();
936 CGSize snapshotSize = self.bounds.size;
937 snapshotSize.width *= deviceScale;
938 snapshotSize.height *= deviceScale;
940 uint32_t slotID = [WebKit::ViewSnapshotStore::snapshottingContext() createImageSlot:snapshotSize hasAlpha:YES];
945 CATransform3D transform = CATransform3DMakeScale(deviceScale, deviceScale, 1);
946 CARenderServerCaptureLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, (uint64_t)self.layer, slotID, 0, 0, &transform);
948 WebCore::IntSize imageSize = WebCore::expandedIntSize(WebCore::FloatSize(snapshotSize));
949 return WebKit::ViewSnapshot::create(slotID, imageSize, imageSize.width() * imageSize.height() * 4);
952 - (void)_zoomToPoint:(WebCore::FloatPoint)point atScale:(double)scale
954 double maximumZoomDuration = 0.4;
955 double minimumZoomDuration = 0.1;
956 double zoomDurationFactor = 0.3;
958 CGFloat zoomScale = contentZoomScale(self);
959 CFTimeInterval duration = std::min(fabs(log(zoomScale) - log(scale)) * zoomDurationFactor + minimumZoomDuration, maximumZoomDuration);
961 if (scale != zoomScale)
962 _page->willStartUserTriggeredZooming();
964 [_scrollView _zoomToCenter:point scale:scale duration:duration];
967 - (void)_zoomToRect:(WebCore::FloatRect)targetRect atScale:(double)scale origin:(WebCore::FloatPoint)origin
969 // FIMXE: Some of this could be shared with _scrollToRect.
970 const double visibleRectScaleChange = contentZoomScale(self) / scale;
971 const WebCore::FloatRect visibleRect([self convertRect:self.bounds toView:self._currentContentView]);
972 const WebCore::FloatRect unobscuredRect([self _contentRectForUserInteraction]);
974 const WebCore::FloatSize topLeftObscuredInsetAfterZoom((unobscuredRect.minXMinYCorner() - visibleRect.minXMinYCorner()) * visibleRectScaleChange);
975 const WebCore::FloatSize bottomRightObscuredInsetAfterZoom((visibleRect.maxXMaxYCorner() - unobscuredRect.maxXMaxYCorner()) * visibleRectScaleChange);
977 const WebCore::FloatSize unobscuredRectSizeAfterZoom(unobscuredRect.size() * visibleRectScaleChange);
979 // Center to the target rect.
980 WebCore::FloatPoint unobscuredRectLocationAfterZoom = targetRect.location() - (unobscuredRectSizeAfterZoom - targetRect.size()) * 0.5;
982 // Center to the tap point instead in case the target rect won't fit in a direction.
983 if (targetRect.width() > unobscuredRectSizeAfterZoom.width())
984 unobscuredRectLocationAfterZoom.setX(origin.x() - unobscuredRectSizeAfterZoom.width() / 2);
985 if (targetRect.height() > unobscuredRectSizeAfterZoom.height())
986 unobscuredRectLocationAfterZoom.setY(origin.y() - unobscuredRectSizeAfterZoom.height() / 2);
988 // We have computed where we want the unobscured rect to be. Now adjust for the obscuring insets.
989 WebCore::FloatRect visibleRectAfterZoom(unobscuredRectLocationAfterZoom, unobscuredRectSizeAfterZoom);
990 visibleRectAfterZoom.move(-topLeftObscuredInsetAfterZoom);
991 visibleRectAfterZoom.expand(topLeftObscuredInsetAfterZoom + bottomRightObscuredInsetAfterZoom);
993 [self _zoomToPoint:visibleRectAfterZoom.center() atScale:scale];
996 static WebCore::FloatPoint constrainContentOffset(WebCore::FloatPoint contentOffset, WebCore::FloatSize contentSize, WebCore::FloatSize unobscuredContentSize)
998 WebCore::FloatSize maximumContentOffset = contentSize - unobscuredContentSize;
999 contentOffset = contentOffset.shrunkTo(WebCore::FloatPoint(maximumContentOffset.width(), maximumContentOffset.height()));
1000 contentOffset = contentOffset.expandedTo(WebCore::FloatPoint());
1001 return contentOffset;
1004 - (void)_scrollToContentOffset:(WebCore::FloatPoint)contentOffset
1006 if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1009 WebCore::FloatPoint scaledOffset = contentOffset;
1010 CGFloat zoomScale = contentZoomScale(self);
1011 scaledOffset.scale(zoomScale, zoomScale);
1013 WebCore::FloatPoint contentOffsetInDocument = scaledOffset;
1014 WebCore::FloatSize documentSizeInSelfCoordinates([_contentView frame].size);
1015 WebCore::FloatSize unobscuredRectSize(UIEdgeInsetsInsetRect(self.bounds, [self _computedContentInset]).size);
1017 float maximumHorizontalOffset = documentSizeInSelfCoordinates.width() - unobscuredRectSize.width();
1018 float maximumVerticalOffset = documentSizeInSelfCoordinates.height() - unobscuredRectSize.height();
1019 contentOffsetInDocument = contentOffsetInDocument.shrunkTo(WebCore::FloatPoint(maximumHorizontalOffset, maximumVerticalOffset));
1020 contentOffsetInDocument = contentOffsetInDocument.expandedTo(WebCore::FloatPoint(0, 0));
1022 [_scrollView _stopScrollingAndZoomingAnimations];
1024 CGPoint adjustedContentOffset = [self _adjustedContentOffset:contentOffsetInDocument];
1025 if (!CGPointEqualToPoint(adjustedContentOffset, [_scrollView contentOffset]))
1026 [_scrollView setContentOffset:adjustedContentOffset];
1028 // If we haven't changed anything, there would not be any VisibleContentRect update sent to the content.
1029 // The WebProcess would keep the invalid contentOffset as its scroll position.
1030 // To synchronize the WebProcess with what is on screen, we send the VisibleContentRect again.
1031 _page->resendLastVisibleContentRects();
1035 - (BOOL)_scrollToRect:(WebCore::FloatRect)targetRect origin:(WebCore::FloatPoint)origin minimumScrollDistance:(float)minimumScrollDistance
1037 WebCore::FloatRect unobscuredContentRect([self _contentRectForUserInteraction]);
1038 WebCore::FloatPoint unobscuredContentOffset = unobscuredContentRect.location();
1039 WebCore::FloatSize contentSize([self._currentContentView bounds].size);
1041 // Center the target rect in the scroll view.
1042 // If the target doesn't fit in the scroll view, center on the gesture location instead.
1043 WebCore::FloatPoint newUnobscuredContentOffset;
1044 if (targetRect.width() <= unobscuredContentRect.width())
1045 newUnobscuredContentOffset.setX(targetRect.x() - (unobscuredContentRect.width() - targetRect.width()) / 2);
1047 newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
1048 if (targetRect.height() <= unobscuredContentRect.height())
1049 newUnobscuredContentOffset.setY(targetRect.y() - (unobscuredContentRect.height() - targetRect.height()) / 2);
1051 newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
1052 newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
1054 if (unobscuredContentOffset == newUnobscuredContentOffset) {
1055 if (targetRect.width() > unobscuredContentRect.width())
1056 newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
1057 if (targetRect.height() > unobscuredContentRect.height())
1058 newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
1059 newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
1062 WebCore::FloatSize scrollViewOffsetDelta = newUnobscuredContentOffset - unobscuredContentOffset;
1063 scrollViewOffsetDelta.scale(contentZoomScale(self));
1065 float scrollDistance = scrollViewOffsetDelta.diagonalLength();
1066 if (scrollDistance < minimumScrollDistance)
1069 [_scrollView setContentOffset:([_scrollView contentOffset] + scrollViewOffsetDelta) animated:YES];
1073 - (void)_zoomOutWithOrigin:(WebCore::FloatPoint)origin
1075 [self _zoomToPoint:origin atScale:[_scrollView minimumZoomScale]];
1078 // focusedElementRect and selectionRect are both in document coordinates.
1079 - (void)_zoomToFocusRect:(WebCore::FloatRect)focusedElementRectInDocumentCoordinates selectionRect:(WebCore::FloatRect)selectionRectInDocumentCoordinates fontSize:(float)fontSize minimumScale:(double)minimumScale maximumScale:(double)maximumScale allowScaling:(BOOL)allowScaling forceScroll:(BOOL)forceScroll
1081 const double WKWebViewStandardFontSize = 16;
1082 const double kMinimumHeightToShowContentAboveKeyboard = 106;
1083 const CFTimeInterval UIWebFormAnimationDuration = 0.25;
1084 const double CaretOffsetFromWindowEdge = 20;
1086 // Zoom around the element's bounding frame. We use a "standard" size to determine the proper frame.
1087 double scale = allowScaling ? std::min(std::max(WKWebViewStandardFontSize / fontSize, minimumScale), maximumScale) : contentZoomScale(self);
1088 CGFloat documentWidth = [_contentView bounds].size.width;
1089 scale = CGRound(documentWidth * scale) / documentWidth;
1091 UIWindow *window = [_scrollView window];
1093 WebCore::FloatRect focusedElementRectInNewScale = focusedElementRectInDocumentCoordinates;
1094 focusedElementRectInNewScale.scale(scale);
1095 focusedElementRectInNewScale.moveBy([_contentView frame].origin);
1097 // Find the portion of the view that is visible on the screen.
1098 UIViewController *topViewController = [[[_scrollView _viewControllerForAncestor] _rootAncestorViewController] _viewControllerForSupportedInterfaceOrientations];
1099 UIView *fullScreenView = topViewController.view;
1100 if (!fullScreenView)
1101 fullScreenView = window;
1103 CGRect unobscuredScrollViewRectInWebViewCoordinates = UIEdgeInsetsInsetRect([self bounds], _obscuredInsets);
1104 CGRect visibleScrollViewBoundsInWebViewCoordinates = CGRectIntersection(unobscuredScrollViewRectInWebViewCoordinates, [fullScreenView convertRect:[fullScreenView bounds] toView:self]);
1105 CGRect formAssistantFrameInWebViewCoordinates = [window convertRect:_inputViewBounds toView:self];
1106 CGRect intersectionBetweenScrollViewAndFormAssistant = CGRectIntersection(visibleScrollViewBoundsInWebViewCoordinates, formAssistantFrameInWebViewCoordinates);
1107 CGSize visibleSize = visibleScrollViewBoundsInWebViewCoordinates.size;
1109 CGFloat visibleOffsetFromTop = 0;
1110 if (!CGRectIsEmpty(intersectionBetweenScrollViewAndFormAssistant)) {
1111 CGFloat heightVisibleAboveFormAssistant = CGRectGetMinY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
1112 CGFloat heightVisibleBelowFormAssistant = CGRectGetMaxY(visibleScrollViewBoundsInWebViewCoordinates) - CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant);
1114 if (heightVisibleAboveFormAssistant >= kMinimumHeightToShowContentAboveKeyboard || heightVisibleBelowFormAssistant < heightVisibleAboveFormAssistant)
1115 visibleSize.height = heightVisibleAboveFormAssistant;
1117 visibleSize.height = heightVisibleBelowFormAssistant;
1118 visibleOffsetFromTop = CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
1122 BOOL selectionRectIsNotNull = !selectionRectInDocumentCoordinates.isZero();
1124 CGRect currentlyVisibleRegionInWebViewCoordinates;
1125 currentlyVisibleRegionInWebViewCoordinates.origin = unobscuredScrollViewRectInWebViewCoordinates.origin;
1126 currentlyVisibleRegionInWebViewCoordinates.origin.y += visibleOffsetFromTop;
1127 currentlyVisibleRegionInWebViewCoordinates.size = visibleSize;
1129 // Don't bother scrolling if the entire node is already visible, whether or not we got a selectionRect.
1130 if (CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:focusedElementRectInDocumentCoordinates fromView:_contentView.get()]))
1133 // Don't bother scrolling if we have a valid selectionRect and it is already visible.
1134 if (selectionRectIsNotNull && CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:selectionRectInDocumentCoordinates fromView:_contentView.get()]))
1138 // We want to zoom to the left/top corner of the DOM node, with as much spacing on all sides as we
1139 // can get based on the visible area after zooming (workingFrame). The spacing in either dimension is half the
1140 // difference between the size of the DOM node and the size of the visible frame.
1141 CGFloat horizontalSpaceInWebViewCoordinates = std::max((visibleSize.width - focusedElementRectInNewScale.width()) / 2.0, 0.0);
1142 CGFloat verticalSpaceInWebViewCoordinates = std::max((visibleSize.height - focusedElementRectInNewScale.height()) / 2.0, 0.0);
1145 topLeft.x = focusedElementRectInNewScale.x() - horizontalSpaceInWebViewCoordinates;
1146 topLeft.y = focusedElementRectInNewScale.y() - verticalSpaceInWebViewCoordinates - visibleOffsetFromTop;
1148 CGFloat minimumAllowableHorizontalOffsetInWebViewCoordinates = -INFINITY;
1149 CGFloat minimumAllowableVerticalOffsetInWebViewCoordinates = -INFINITY;
1150 if (selectionRectIsNotNull) {
1151 WebCore::FloatRect selectionRectInNewScale = selectionRectInDocumentCoordinates;
1152 selectionRectInNewScale.scale(scale);
1153 selectionRectInNewScale.moveBy([_contentView frame].origin);
1154 minimumAllowableHorizontalOffsetInWebViewCoordinates = CGRectGetMaxX(selectionRectInNewScale) + CaretOffsetFromWindowEdge - visibleSize.width;
1155 minimumAllowableVerticalOffsetInWebViewCoordinates = CGRectGetMaxY(selectionRectInNewScale) + CaretOffsetFromWindowEdge - visibleSize.height - visibleOffsetFromTop;
1158 WebCore::FloatRect documentBoundsInNewScale = [_contentView bounds];
1159 documentBoundsInNewScale.scale(scale);
1160 documentBoundsInNewScale.moveBy([_contentView frame].origin);
1162 // Constrain the left edge in document coordinates so that:
1163 // - it isn't so small that the scrollVisibleRect isn't visible on the screen
1164 // - it isn't so great that the document's right edge is less than the right edge of the screen
1165 if (selectionRectIsNotNull && topLeft.x < minimumAllowableHorizontalOffsetInWebViewCoordinates)
1166 topLeft.x = minimumAllowableHorizontalOffsetInWebViewCoordinates;
1168 CGFloat maximumAllowableHorizontalOffset = CGRectGetMaxX(documentBoundsInNewScale) - visibleSize.width;
1169 if (topLeft.x > maximumAllowableHorizontalOffset)
1170 topLeft.x = maximumAllowableHorizontalOffset;
1173 // Constrain the top edge in document coordinates so that:
1174 // - it isn't so small that the scrollVisibleRect isn't visible on the screen
1175 // - it isn't so great that the document's bottom edge is higher than the top of the form assistant
1176 if (selectionRectIsNotNull && topLeft.y < minimumAllowableVerticalOffsetInWebViewCoordinates)
1177 topLeft.y = minimumAllowableVerticalOffsetInWebViewCoordinates;
1179 CGFloat maximumAllowableVerticalOffset = CGRectGetMaxY(documentBoundsInNewScale) - visibleSize.height;
1180 if (topLeft.y > maximumAllowableVerticalOffset)
1181 topLeft.y = maximumAllowableVerticalOffset;
1184 WebCore::FloatPoint newCenter = CGPointMake(topLeft.x + unobscuredScrollViewRectInWebViewCoordinates.size.width / 2.0, topLeft.y + unobscuredScrollViewRectInWebViewCoordinates.size.height / 2.0);
1186 if (scale != contentZoomScale(self))
1187 _page->willStartUserTriggeredZooming();
1189 // The newCenter has been computed in the new scale, but _zoomToCenter expected the center to be in the original scale.
1190 newCenter.scale(1 / scale, 1 / scale);
1191 [_scrollView _zoomToCenter:newCenter
1193 duration:UIWebFormAnimationDuration
1197 - (BOOL)_zoomToRect:(WebCore::FloatRect)targetRect withOrigin:(WebCore::FloatPoint)origin fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale minimumScrollDistance:(float)minimumScrollDistance
1199 const float maximumScaleFactorDeltaForPanScroll = 0.02;
1201 double currentScale = contentZoomScale(self);
1203 WebCore::FloatSize unobscuredContentSize([self _contentRectForUserInteraction].size);
1204 double horizontalScale = unobscuredContentSize.width() * currentScale / targetRect.width();
1205 double verticalScale = unobscuredContentSize.height() * currentScale / targetRect.height();
1207 horizontalScale = std::min(std::max(horizontalScale, minimumScale), maximumScale);
1208 verticalScale = std::min(std::max(verticalScale, minimumScale), maximumScale);
1210 double targetScale = fitEntireRect ? std::min(horizontalScale, verticalScale) : horizontalScale;
1211 if (fabs(targetScale - currentScale) < maximumScaleFactorDeltaForPanScroll) {
1212 if ([self _scrollToRect:targetRect origin:origin minimumScrollDistance:minimumScrollDistance])
1214 } else if (targetScale != currentScale) {
1215 [self _zoomToRect:targetRect atScale:targetScale origin:origin];
1222 - (void)didMoveToWindow
1224 _page->viewStateDidChange(WebCore::ViewState::IsInWindow);
1227 - (void)setOpaque:(BOOL)opaque
1229 BOOL oldOpaque = self.opaque;
1231 [super setOpaque:opaque];
1232 [_contentView setOpaque:opaque];
1234 if (oldOpaque == opaque)
1237 _page->setDrawsBackground(opaque);
1238 [self _updateScrollViewBackground];
1241 - (void)setBackgroundColor:(UIColor *)backgroundColor
1243 [super setBackgroundColor:backgroundColor];
1244 [_contentView setBackgroundColor:backgroundColor];
1247 #pragma mark - UIScrollViewDelegate
1249 - (BOOL)usesStandardContentView
1251 return !_customContentView;
1254 - (CGSize)scrollView:(UIScrollView*)scrollView contentSizeForZoomScale:(CGFloat)scale withProposedSize:(CGSize)proposedSize
1256 return roundScrollViewContentSize(*_page, proposedSize);
1259 - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
1261 ASSERT(_scrollView == scrollView);
1263 if (_customContentView)
1264 return _customContentView.get();
1266 return _contentView.get();
1269 - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
1271 if (![self usesStandardContentView])
1274 if (scrollView.pinchGestureRecognizer.state == UIGestureRecognizerStateBegan) {
1275 _page->willStartUserTriggeredZooming();
1276 [_contentView scrollViewWillStartPanOrPinchGesture];
1278 [_contentView willStartZoomOrScroll];
1281 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
1283 if (![self usesStandardContentView])
1286 if (scrollView.panGestureRecognizer.state == UIGestureRecognizerStateBegan)
1287 [_contentView scrollViewWillStartPanOrPinchGesture];
1288 [_contentView willStartZoomOrScroll];
1291 - (void)_didFinishScrolling
1293 if (![self usesStandardContentView])
1296 [self _updateVisibleContentRects];
1297 [_contentView didFinishScrolling];
1300 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
1302 // Work around <rdar://problem/16374753> by avoiding deceleration while
1303 // zooming. We'll animate to the right place once the zoom finishes.
1304 if ([scrollView isZooming])
1305 *targetContentOffset = [scrollView contentOffset];
1308 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
1310 // If we're decelerating, scroll offset will be updated when scrollViewDidFinishDecelerating: is called.
1312 [self _didFinishScrolling];
1315 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
1317 [self _didFinishScrolling];
1320 - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
1322 [self _didFinishScrolling];
1325 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
1327 if (![self usesStandardContentView])
1328 [_customContentView scrollViewDidScroll:(UIScrollView *)scrollView];
1330 [self _updateVisibleContentRects];
1333 - (void)scrollViewDidZoom:(UIScrollView *)scrollView
1335 [self _updateScrollViewBackground];
1336 [self _updateVisibleContentRects];
1339 - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
1341 ASSERT(scrollView == _scrollView);
1342 [self _updateVisibleContentRects];
1343 [_contentView didZoomToScale:scale];
1346 - (void)_frameOrBoundsChanged
1348 CGRect bounds = self.bounds;
1349 [_scrollView setFrame:bounds];
1351 if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing) {
1352 if (!_overridesMinimumLayoutSize)
1353 _page->setViewportConfigurationMinimumLayoutSize(WebCore::FloatSize(bounds.size));
1354 if (!_overridesMinimumLayoutSizeForMinimalUI)
1355 _page->setViewportConfigurationMinimumLayoutSizeForMinimalUI(WebCore::FloatSize(bounds.size));
1356 if (!_overridesMaximumUnobscuredSize)
1357 _page->setMaximumUnobscuredSize(WebCore::FloatSize(bounds.size));
1358 _page->drawingArea()->setSize(WebCore::IntSize(bounds.size), WebCore::IntSize(), WebCore::IntSize());
1361 [_customContentView web_setMinimumSize:bounds.size];
1362 [self _updateVisibleContentRects];
1365 // Unobscured content rect where the user can interact. When the keyboard is up, this should be the area above or bellow the keyboard, wherever there is enough space.
1366 - (CGRect)_contentRectForUserInteraction
1368 // FIXME: handle split keyboard.
1369 UIEdgeInsets obscuredInsets = _obscuredInsets;
1370 obscuredInsets.bottom = std::max(_obscuredInsets.bottom, _inputViewBounds.size.height);
1371 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInsets);
1372 return [self convertRect:unobscuredRect toView:self._currentContentView];
1375 - (void)_updateVisibleContentRects
1377 if (![self usesStandardContentView]) {
1378 [_customContentView web_computedContentInsetDidChange];
1382 if (_delayUpdateVisibleContentRects) {
1383 _hadDelayedUpdateVisibleContentRects = YES;
1387 if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1390 if (_needsResetViewStateAfterCommitLoadForMainFrame)
1393 CGRect fullViewRect = self.bounds;
1394 CGRect visibleRectInContentCoordinates = [self convertRect:fullViewRect toView:_contentView.get()];
1396 CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, [self _computedContentInset]);
1397 CGRect unobscuredRectInContentCoordinates = [self convertRect:unobscuredRect toView:_contentView.get()];
1399 CGFloat scaleFactor = contentZoomScale(self);
1401 BOOL isStableState = !(_isChangingObscuredInsetsInteractively || [_scrollView isDragging] || [_scrollView isDecelerating] || [_scrollView isZooming] || [_scrollView isZoomBouncing] || [_scrollView _isAnimatingZoom] || [_scrollView _isScrollingToTop]);
1402 [_contentView didUpdateVisibleRect:visibleRectInContentCoordinates
1403 unobscuredRect:unobscuredRectInContentCoordinates
1404 unobscuredRectInScrollViewCoordinates:unobscuredRect
1405 scale:scaleFactor minimumScale:[_scrollView minimumZoomScale]
1406 inStableState:isStableState isChangingObscuredInsetsInteractively:_isChangingObscuredInsetsInteractively];
1409 - (void)_keyboardChangedWithInfo:(NSDictionary *)keyboardInfo adjustScrollView:(BOOL)adjustScrollView
1411 NSValue *endFrameValue = [keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
1415 // The keyboard rect is always in screen coordinates. In the view services case the window does not
1416 // have the interface orientation rotation transformation; its host does. So, it makes no sense to
1417 // clip the keyboard rect against its screen.
1418 if ([[self window] _isHostedInAnotherProcess])
1419 _inputViewBounds = [self.window convertRect:[endFrameValue CGRectValue] fromWindow:nil];
1421 _inputViewBounds = [self.window convertRect:CGRectIntersection([endFrameValue CGRectValue], self.window.screen.bounds) fromWindow:nil];
1423 [self _updateVisibleContentRects];
1425 if (adjustScrollView)
1426 [_scrollView _adjustForAutomaticKeyboardInfo:keyboardInfo animated:YES lastAdjustment:&_lastAdjustmentForScroller];
1429 - (void)_keyboardWillChangeFrame:(NSNotification *)notification
1431 if ([_contentView isAssistingNode])
1432 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
1435 - (void)_keyboardDidChangeFrame:(NSNotification *)notification
1437 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:NO];
1440 - (void)_keyboardWillShow:(NSNotification *)notification
1442 if ([_contentView isAssistingNode])
1443 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
1446 - (void)_keyboardWillHide:(NSNotification *)notification
1448 // Ignore keyboard will hide notifications sent during rotation. They're just there for
1449 // backwards compatibility reasons and processing the will hide notification would
1450 // temporarily screw up the the unobscured view area.
1451 if ([[UIPeripheralHost sharedInstance] rotationState])
1454 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
1457 - (void)_windowDidRotate:(NSNotification *)notification
1459 if (!_overridesInterfaceOrientation)
1460 _page->setDeviceOrientation(deviceOrientation());
1463 - (void)_contentSizeCategoryDidChange:(NSNotification *)notification
1465 _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
1468 - (NSString *)_contentSizeCategory
1470 return [[UIApplication sharedApplication] preferredContentSizeCategory];
1473 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
1475 if (_allowsBackForwardNavigationGestures == allowsBackForwardNavigationGestures)
1478 _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
1480 if (allowsBackForwardNavigationGestures) {
1481 if (!_gestureController) {
1482 _gestureController = std::make_unique<WebKit::ViewGestureController>(*_page);
1483 _gestureController->installSwipeHandler(self, [self scrollView]);
1484 _gestureController->setAlternateBackForwardListSourceView([_configuration _alternateWebViewForNavigationGestures]);
1487 _gestureController = nullptr;
1489 _page->setShouldRecordNavigationSnapshots(allowsBackForwardNavigationGestures);
1492 - (BOOL)allowsBackForwardNavigationGestures
1494 return _allowsBackForwardNavigationGestures;
1499 #pragma mark OS X-specific methods
1503 - (void)resizeSubviewsWithOldSize:(NSSize)oldSize
1505 [_wkView setFrame:self.bounds];
1508 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
1510 [_wkView setAllowsBackForwardNavigationGestures:allowsBackForwardNavigationGestures];
1513 - (BOOL)allowsBackForwardNavigationGestures
1515 return [_wkView allowsBackForwardNavigationGestures];
1518 - (void)setAllowsMagnification:(BOOL)allowsMagnification
1520 [_wkView setAllowsMagnification:allowsMagnification];
1523 - (BOOL)allowsMagnification
1525 return [_wkView allowsMagnification];
1528 - (void)setMagnification:(CGFloat)magnification
1530 [_wkView setMagnification:magnification];
1533 - (CGFloat)magnification
1535 return [_wkView magnification];
1538 - (void)setMagnification:(CGFloat)magnification centeredAtPoint:(CGPoint)point
1540 [_wkView setMagnification:magnification centeredAtPoint:NSPointFromCGPoint(point)];
1547 @implementation WKWebView (WKPrivate)
1549 - (_WKRemoteObjectRegistry *)_remoteObjectRegistry
1551 if (!_remoteObjectRegistry) {
1552 _remoteObjectRegistry = adoptNS([[_WKRemoteObjectRegistry alloc] _initWithMessageSender:*_page]);
1553 _page->process().context().addMessageReceiver(Messages::RemoteObjectRegistry::messageReceiverName(), _page->pageID(), [_remoteObjectRegistry remoteObjectRegistry]);
1556 return _remoteObjectRegistry.get();
1559 - (WKBrowsingContextHandle *)_handle
1561 return [[[WKBrowsingContextHandle alloc] _initWithPageID:_page->pageID()] autorelease];
1564 - (_WKRenderingProgressEvents)_observedRenderingProgressEvents
1566 return _observedRenderingProgressEvents;
1569 - (id <WKHistoryDelegatePrivate>)_historyDelegate
1571 return _navigationState->historyDelegate().autorelease();
1574 - (void)_setHistoryDelegate:(id <WKHistoryDelegatePrivate>)historyDelegate
1576 _navigationState->setHistoryDelegate(historyDelegate);
1579 - (NSURL *)_unreachableURL
1581 return [NSURL _web_URLWithWTFString:_page->pageLoadState().unreachableURL()];
1584 - (void)_loadAlternateHTMLString:(NSString *)string baseURL:(NSURL *)baseURL forUnreachableURL:(NSURL *)unreachableURL
1586 _page->loadAlternateHTMLString(string, [baseURL _web_originalDataAsWTFString], [unreachableURL _web_originalDataAsWTFString]);
1589 - (NSArray *)_certificateChain
1591 if (WebKit::WebFrameProxy* mainFrame = _page->mainFrame())
1592 return mainFrame->certificateInfo() ? (NSArray *)mainFrame->certificateInfo()->certificateInfo().certificateChain() : nil;
1597 - (NSURL *)_committedURL
1599 return [NSURL _web_URLWithWTFString:_page->pageLoadState().url()];
1602 - (NSString *)_MIMEType
1604 if (_page->mainFrame())
1605 return _page->mainFrame()->mimeType();
1610 - (NSString *)_applicationNameForUserAgent
1612 return _page->applicationNameForUserAgent();
1615 - (void)_setApplicationNameForUserAgent:(NSString *)applicationNameForUserAgent
1617 _page->setApplicationNameForUserAgent(applicationNameForUserAgent);
1620 - (NSString *)_customUserAgent
1622 return _page->customUserAgent();
1625 - (void)_setCustomUserAgent:(NSString *)_customUserAgent
1627 _page->setCustomUserAgent(_customUserAgent);
1630 - (pid_t)_webProcessIdentifier
1632 return _page->isValid() ? _page->processIdentifier() : 0;
1635 - (void)_killWebContentProcess
1637 if (!_page->isValid())
1640 _page->process().terminate();
1644 static WebCore::FloatSize activeMinimumLayoutSize(WKWebView *webView, const CGRect& bounds)
1646 return WebCore::FloatSize(webView->_overridesMinimumLayoutSize ? webView->_minimumLayoutSizeOverride : bounds.size);
1649 static WebCore::FloatSize activeMinimumLayoutSizeForMinimalUI(WKWebView *webView, WebCore::FloatSize minimumLayoutSize)
1651 return webView->_overridesMinimumLayoutSizeForMinimalUI ? WebCore::FloatSize(webView->_minimumLayoutSizeOverrideForMinimalUI) : minimumLayoutSize;
1654 static WebCore::FloatSize activeMaximumUnobscuredSize(WKWebView *webView, const CGRect& bounds)
1656 return WebCore::FloatSize(webView->_overridesMaximumUnobscuredSize ? webView->_maximumUnobscuredSizeOverride : bounds.size);
1659 static int32_t activeOrientation(WKWebView *webView)
1661 return webView->_overridesInterfaceOrientation ? deviceOrientationForUIInterfaceOrientation(webView->_interfaceOrientationOverride) : webView->_page->deviceOrientation();
1665 - (void)_didRelaunchProcess
1668 CGRect bounds = self.bounds;
1669 WebCore::FloatSize minimalLayoutSize = activeMinimumLayoutSize(self, bounds);
1670 _page->setViewportConfigurationMinimumLayoutSize(minimalLayoutSize);
1671 _page->setViewportConfigurationMinimumLayoutSizeForMinimalUI(activeMinimumLayoutSizeForMinimalUI(self, minimalLayoutSize));
1672 _page->setMaximumUnobscuredSize(activeMaximumUnobscuredSize(self, bounds));
1676 - (NSData *)_sessionStateData
1678 WebKit::SessionState sessionState = _page->sessionState();
1680 // FIXME: This should not use the legacy session state encoder.
1681 return [wrapper(*WebKit::encodeLegacySessionState(sessionState).release().leakRef()) autorelease];
1684 - (_WKSessionState *)_sessionState
1686 return adoptNS([[_WKSessionState alloc] _initWithSessionState:_page->sessionState()]).autorelease();
1689 - (void)_restoreFromSessionStateData:(NSData *)sessionStateData
1691 // FIXME: This should not use the legacy session state decoder.
1692 WebKit::SessionState sessionState;
1693 if (!WebKit::decodeLegacySessionState(static_cast<const uint8_t*>(sessionStateData.bytes), sessionStateData.length, sessionState))
1696 if (uint64_t navigationID = _page->restoreFromSessionState(WTF::move(sessionState), true)) {
1697 // FIXME: This is not necessarily always a reload navigation.
1698 _navigationState->createReloadNavigation(navigationID);
1702 - (WKNavigation *)_restoreSessionState:(_WKSessionState *)sessionState andNavigate:(BOOL)navigate
1704 if (uint64_t navigationID = _page->restoreFromSessionState(sessionState->_sessionState, navigate)) {
1705 // FIXME: This is not necessarily always a reload navigation.
1706 return _navigationState->createReloadNavigation(navigationID).autorelease();
1717 - (BOOL)_allowsRemoteInspection
1719 #if ENABLE(REMOTE_INSPECTOR)
1720 return _page->allowsRemoteInspection();
1726 - (void)_setAllowsRemoteInspection:(BOOL)allow
1728 #if ENABLE(REMOTE_INSPECTOR)
1729 _page->setAllowsRemoteInspection(allow);
1733 - (BOOL)_addsVisitedLinks
1735 return _page->addsVisitedLinks();
1738 - (void)_setAddsVisitedLinks:(BOOL)addsVisitedLinks
1740 _page->setAddsVisitedLinks(addsVisitedLinks);
1743 - (BOOL)_networkRequestsInProgress
1745 return _page->pageLoadState().networkRequestsInProgress();
1748 static inline WebCore::LayoutMilestones layoutMilestones(_WKRenderingProgressEvents events)
1750 WebCore::LayoutMilestones milestones = 0;
1752 if (events & _WKRenderingProgressEventFirstLayout)
1753 milestones |= WebCore::DidFirstLayout;
1755 if (events & _WKRenderingProgressEventFirstPaintWithSignificantArea)
1756 milestones |= WebCore::DidHitRelevantRepaintedObjectsAreaThreshold;
1761 - (void)_setObservedRenderingProgressEvents:(_WKRenderingProgressEvents)observedRenderingProgressEvents
1763 _observedRenderingProgressEvents = observedRenderingProgressEvents;
1764 _page->listenForLayoutMilestones(layoutMilestones(observedRenderingProgressEvents));
1767 - (void)_getMainResourceDataWithCompletionHandler:(void (^)(NSData *, NSError *))completionHandler
1769 auto handler = adoptNS([completionHandler copy]);
1771 _page->getMainResourceDataOfFrame(_page->mainFrame(), [handler](API::Data* data, WebKit::CallbackBase::Error error) {
1772 void (^completionHandlerBlock)(NSData *, NSError *) = (void (^)(NSData *, NSError *))handler.get();
1773 if (error != WebKit::CallbackBase::Error::None) {
1774 // FIXME: Pipe a proper error in from the WebPageProxy.
1775 RetainPtr<NSError> error = adoptNS([[NSError alloc] init]);
1776 completionHandlerBlock(nil, error.get());
1778 completionHandlerBlock(wrapper(*data), nil);
1782 - (void)_getWebArchiveDataWithCompletionHandler:(void (^)(NSData *, NSError *))completionHandler
1784 auto handler = adoptNS([completionHandler copy]);
1786 _page->getWebArchiveOfFrame(_page->mainFrame(), [handler](API::Data* data, WebKit::CallbackBase::Error error) {
1787 void (^completionHandlerBlock)(NSData *, NSError *) = (void (^)(NSData *, NSError *))handler.get();
1788 if (error != WebKit::CallbackBase::Error::None) {
1789 // FIXME: Pipe a proper error in from the WebPageProxy.
1790 RetainPtr<NSError> error = adoptNS([[NSError alloc] init]);
1791 completionHandlerBlock(nil, error.get());
1793 completionHandlerBlock(wrapper(*data), nil);
1797 - (_WKPaginationMode)_paginationMode
1799 switch (_page->paginationMode()) {
1800 case WebCore::Pagination::Unpaginated:
1801 return _WKPaginationModeUnpaginated;
1802 case WebCore::Pagination::LeftToRightPaginated:
1803 return _WKPaginationModeLeftToRight;
1804 case WebCore::Pagination::RightToLeftPaginated:
1805 return _WKPaginationModeRightToLeft;
1806 case WebCore::Pagination::TopToBottomPaginated:
1807 return _WKPaginationModeTopToBottom;
1808 case WebCore::Pagination::BottomToTopPaginated:
1809 return _WKPaginationModeBottomToTop;
1812 ASSERT_NOT_REACHED();
1813 return _WKPaginationModeUnpaginated;
1816 - (void)_setPaginationMode:(_WKPaginationMode)paginationMode
1818 WebCore::Pagination::Mode mode;
1819 switch (paginationMode) {
1820 case _WKPaginationModeUnpaginated:
1821 mode = WebCore::Pagination::Unpaginated;
1823 case _WKPaginationModeLeftToRight:
1824 mode = WebCore::Pagination::LeftToRightPaginated;
1826 case _WKPaginationModeRightToLeft:
1827 mode = WebCore::Pagination::RightToLeftPaginated;
1829 case _WKPaginationModeTopToBottom:
1830 mode = WebCore::Pagination::TopToBottomPaginated;
1832 case _WKPaginationModeBottomToTop:
1833 mode = WebCore::Pagination::BottomToTopPaginated;
1839 _page->setPaginationMode(mode);
1842 - (BOOL)_paginationBehavesLikeColumns
1844 return _page->paginationBehavesLikeColumns();
1847 - (void)_setPaginationBehavesLikeColumns:(BOOL)behavesLikeColumns
1849 _page->setPaginationBehavesLikeColumns(behavesLikeColumns);
1852 - (CGFloat)_pageLength
1854 return _page->pageLength();
1857 - (void)_setPageLength:(CGFloat)pageLength
1859 _page->setPageLength(pageLength);
1862 - (CGFloat)_gapBetweenPages
1864 return _page->gapBetweenPages();
1867 - (void)_setGapBetweenPages:(CGFloat)gapBetweenPages
1869 _page->setGapBetweenPages(gapBetweenPages);
1872 - (NSUInteger)_pageCount
1874 return _page->pageCount();
1877 - (BOOL)_supportsTextZoom
1879 return _page->supportsTextZoom();
1882 - (double)_textZoomFactor
1884 return _page->textZoomFactor();
1887 - (void)_setTextZoomFactor:(double)zoomFactor
1889 _page->setTextZoomFactor(zoomFactor);
1892 - (double)_pageZoomFactor
1894 return _page->pageZoomFactor();
1897 - (void)_setPageZoomFactor:(double)zoomFactor
1899 _page->setPageZoomFactor(zoomFactor);
1902 - (id <_WKFindDelegate>)_findDelegate
1904 return [static_cast<WebKit::FindClient&>(_page->findClient()).delegate().leakRef() autorelease];
1907 - (void)_setFindDelegate:(id<_WKFindDelegate>)findDelegate
1909 static_cast<WebKit::FindClient&>(_page->findClient()).setDelegate(findDelegate);
1912 static inline WebKit::FindOptions toFindOptions(_WKFindOptions wkFindOptions)
1914 unsigned findOptions = 0;
1916 if (wkFindOptions & _WKFindOptionsCaseInsensitive)
1917 findOptions |= WebKit::FindOptionsCaseInsensitive;
1918 if (wkFindOptions & _WKFindOptionsAtWordStarts)
1919 findOptions |= WebKit::FindOptionsAtWordStarts;
1920 if (wkFindOptions & _WKFindOptionsTreatMedialCapitalAsWordStart)
1921 findOptions |= WebKit::FindOptionsTreatMedialCapitalAsWordStart;
1922 if (wkFindOptions & _WKFindOptionsBackwards)
1923 findOptions |= WebKit::FindOptionsBackwards;
1924 if (wkFindOptions & _WKFindOptionsWrapAround)
1925 findOptions |= WebKit::FindOptionsWrapAround;
1926 if (wkFindOptions & _WKFindOptionsShowOverlay)
1927 findOptions |= WebKit::FindOptionsShowOverlay;
1928 if (wkFindOptions & _WKFindOptionsShowFindIndicator)
1929 findOptions |= WebKit::FindOptionsShowFindIndicator;
1930 if (wkFindOptions & _WKFindOptionsShowHighlight)
1931 findOptions |= WebKit::FindOptionsShowHighlight;
1932 if (wkFindOptions & _WKFindOptionsDetermineMatchIndex)
1933 findOptions |= WebKit::FindOptionsDetermineMatchIndex;
1935 return static_cast<WebKit::FindOptions>(findOptions);
1938 - (void)_countStringMatches:(NSString *)string options:(_WKFindOptions)options maxCount:(NSUInteger)maxCount
1940 _page->countStringMatches(string, toFindOptions(options), maxCount);
1943 - (void)_findString:(NSString *)string options:(_WKFindOptions)options maxCount:(NSUInteger)maxCount
1945 _page->findString(string, toFindOptions(options), maxCount);
1950 _page->hideFindUI();
1953 - (id <_WKFormDelegate>)_formDelegate
1955 return _formDelegate.getAutoreleased();
1958 - (void)_setFormDelegate:(id <_WKFormDelegate>)formDelegate
1960 _formDelegate = formDelegate;
1962 class FormClient : public API::FormClient {
1964 explicit FormClient(WKWebView *webView)
1965 : m_webView(webView)
1969 virtual ~FormClient() { }
1971 virtual bool willSubmitForm(WebKit::WebPageProxy*, WebKit::WebFrameProxy*, WebKit::WebFrameProxy* sourceFrame, const Vector<std::pair<WTF::String, WTF::String>>& textFieldValues, API::Object* userData, WebKit::WebFormSubmissionListenerProxy* listener) override
1973 if (userData && userData->type() != API::Object::Type::Data) {
1974 ASSERT(!userData || userData->type() == API::Object::Type::Data);
1975 m_webView->_page->process().connection()->markCurrentlyDispatchedMessageAsInvalid();
1979 auto formDelegate = m_webView->_formDelegate.get();
1981 if (![formDelegate respondsToSelector:@selector(_webView:willSubmitFormValues:userObject:submissionHandler:)])
1984 auto valueMap = adoptNS([[NSMutableDictionary alloc] initWithCapacity:textFieldValues.size()]);
1985 for (const auto& pair : textFieldValues)
1986 [valueMap setObject:pair.second forKey:pair.first];
1988 NSObject <NSSecureCoding> *userObject = nil;
1989 if (API::Data* data = static_cast<API::Data*>(userData)) {
1990 auto nsData = adoptNS([[NSData alloc] initWithBytesNoCopy:const_cast<void*>(static_cast<const void*>(data->bytes())) length:data->size() freeWhenDone:NO]);
1991 auto unarchiver = adoptNS([[NSKeyedUnarchiver alloc] initForReadingWithData:nsData.get()]);
1992 [unarchiver setRequiresSecureCoding:YES];
1994 userObject = [unarchiver decodeObjectOfClass:[NSObject class] forKey:@"userObject"];
1995 } @catch (NSException *exception) {
1996 LOG_ERROR("Failed to decode user data: %@", exception);
2000 RefPtr<WebKit::CompletionHandlerCallChecker> checker = WebKit::CompletionHandlerCallChecker::create(formDelegate.get(), @selector(_webView:willSubmitFormValues:userObject:submissionHandler:));
2001 [formDelegate _webView:m_webView willSubmitFormValues:valueMap.get() userObject:userObject submissionHandler:[listener, checker] {
2002 checker->didCallCompletionHandler();
2003 listener->continueSubmission();
2009 WKWebView *m_webView;
2013 _page->setFormClient(std::make_unique<FormClient>(self));
2015 _page->setFormClient(nullptr);
2018 - (BOOL)_isDisplayingStandaloneImageDocument
2020 if (auto* mainFrame = _page->mainFrame())
2021 return mainFrame->isDisplayingStandaloneImageDocument();
2025 - (BOOL)_isShowingNavigationGestureSnapshot
2027 return _page->isShowingNavigationGestureSnapshot();
2030 #pragma mark iOS-specific methods
2034 - (CGSize)_minimumLayoutSizeOverride
2036 ASSERT(_overridesMinimumLayoutSize);
2037 return _minimumLayoutSizeOverride;
2040 - (void)_setMinimumLayoutSizeOverride:(CGSize)minimumLayoutSizeOverride
2042 _overridesMinimumLayoutSize = YES;
2043 if (CGSizeEqualToSize(_minimumLayoutSizeOverride, minimumLayoutSizeOverride))
2046 _minimumLayoutSizeOverride = minimumLayoutSizeOverride;
2047 if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing)
2048 _page->setViewportConfigurationMinimumLayoutSize(WebCore::FloatSize(minimumLayoutSizeOverride));
2051 - (CGSize)_minimumLayoutSizeOverrideForMinimalUI
2053 ASSERT(_overridesMinimumLayoutSizeForMinimalUI);
2054 return _minimumLayoutSizeOverrideForMinimalUI;
2057 - (void)_setMinimumLayoutSizeOverrideForMinimalUI:(CGSize)size
2059 _overridesMinimumLayoutSizeForMinimalUI = YES;
2060 if (CGSizeEqualToSize(_minimumLayoutSizeOverrideForMinimalUI, size))
2063 _minimumLayoutSizeOverrideForMinimalUI = size;
2064 if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing)
2065 _page->setViewportConfigurationMinimumLayoutSizeForMinimalUI(WebCore::FloatSize(size));
2068 - (UIEdgeInsets)_obscuredInsets
2070 return _obscuredInsets;
2073 - (void)_setObscuredInsets:(UIEdgeInsets)obscuredInsets
2075 ASSERT(obscuredInsets.top >= 0);
2076 ASSERT(obscuredInsets.left >= 0);
2077 ASSERT(obscuredInsets.bottom >= 0);
2078 ASSERT(obscuredInsets.right >= 0);
2080 if (UIEdgeInsetsEqualToEdgeInsets(_obscuredInsets, obscuredInsets))
2083 _obscuredInsets = obscuredInsets;
2085 [self _updateVisibleContentRects];
2088 - (void)_setInterfaceOrientationOverride:(UIInterfaceOrientation)interfaceOrientation
2090 if (!_overridesInterfaceOrientation)
2091 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIWindowDidRotateNotification object:nil];
2093 _overridesInterfaceOrientation = YES;
2095 if (interfaceOrientation == _interfaceOrientationOverride)
2098 _interfaceOrientationOverride = interfaceOrientation;
2100 if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing)
2101 _page->setDeviceOrientation(deviceOrientationForUIInterfaceOrientation(_interfaceOrientationOverride));
2104 - (UIInterfaceOrientation)_interfaceOrientationOverride
2106 ASSERT(_overridesInterfaceOrientation);
2107 return _interfaceOrientationOverride;
2110 - (CGSize)_maximumUnobscuredSizeOverride
2112 ASSERT(_overridesMaximumUnobscuredSize);
2113 return _maximumUnobscuredSizeOverride;
2116 - (void)_setMaximumUnobscuredSizeOverride:(CGSize)size
2118 ASSERT(size.width <= self.bounds.size.width && size.height <= self.bounds.size.height);
2119 _overridesMaximumUnobscuredSize = YES;
2120 if (CGSizeEqualToSize(_maximumUnobscuredSizeOverride, size))
2123 _maximumUnobscuredSizeOverride = size;
2124 if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing)
2125 _page->setMaximumUnobscuredSize(WebCore::FloatSize(size));
2128 - (void)_setBackgroundExtendsBeyondPage:(BOOL)backgroundExtends
2130 _page->setBackgroundExtendsBeyondPage(backgroundExtends);
2133 - (BOOL)_backgroundExtendsBeyondPage
2135 return _page->backgroundExtendsBeyondPage();
2138 - (void)_beginInteractiveObscuredInsetsChange
2140 ASSERT(!_isChangingObscuredInsetsInteractively);
2141 _isChangingObscuredInsetsInteractively = YES;
2144 - (void)_endInteractiveObscuredInsetsChange
2146 ASSERT(_isChangingObscuredInsetsInteractively);
2147 _isChangingObscuredInsetsInteractively = NO;
2148 [self _updateVisibleContentRects];
2151 - (void)_beginAnimatedResizeWithUpdates:(void (^)(void))updateBlock
2153 if (_customContentView || !_hasCommittedLoadForMainFrame) {
2158 _dynamicViewportUpdateMode = DynamicViewportUpdateMode::ResizingWithAnimation;
2160 CGRect oldBounds = self.bounds;
2161 WebCore::FloatSize oldMinimumLayoutSize = activeMinimumLayoutSize(self, oldBounds);
2162 WebCore::FloatSize oldMinimumLayoutSizeForMinimalUI = activeMinimumLayoutSizeForMinimalUI(self, oldMinimumLayoutSize);
2163 WebCore::FloatSize oldMaximumUnobscuredSize = activeMaximumUnobscuredSize(self, oldBounds);
2164 int32_t oldOrientation = activeOrientation(self);
2165 UIEdgeInsets oldObscuredInsets = _obscuredInsets;
2166 WebCore::FloatRect oldUnobscuredContentRect = _page->unobscuredContentRect();
2170 CGRect newBounds = self.bounds;
2171 WebCore::FloatSize newMinimumLayoutSize = activeMinimumLayoutSize(self, newBounds);
2172 WebCore::FloatSize newMinimumLayoutSizeForMinimalUI = activeMinimumLayoutSizeForMinimalUI(self, newMinimumLayoutSize);
2173 WebCore::FloatSize newMaximumUnobscuredSize = activeMaximumUnobscuredSize(self, newBounds);
2174 int32_t newOrientation = activeOrientation(self);
2175 UIEdgeInsets newObscuredInsets = _obscuredInsets;
2177 if (CGRectEqualToRect(oldBounds, newBounds)
2178 && oldMinimumLayoutSize == newMinimumLayoutSize
2179 && oldMinimumLayoutSizeForMinimalUI == newMinimumLayoutSizeForMinimalUI
2180 && oldMaximumUnobscuredSize == newMaximumUnobscuredSize
2181 && oldOrientation == newOrientation
2182 && UIEdgeInsetsEqualToEdgeInsets(oldObscuredInsets, newObscuredInsets)) {
2183 _dynamicViewportUpdateMode = DynamicViewportUpdateMode::NotResizing;
2184 [self _updateVisibleContentRects];
2188 _resizeAnimationTransformAdjustments = CATransform3DIdentity;
2190 NSUInteger indexOfContentView = [[_scrollView subviews] indexOfObject:_contentView.get()];
2191 _resizeAnimationView = adoptNS([[UIView alloc] init]);
2192 [_scrollView insertSubview:_resizeAnimationView.get() atIndex:indexOfContentView];
2193 [_resizeAnimationView addSubview:_contentView.get()];
2194 [_resizeAnimationView addSubview:[_contentView unscaledView]];
2196 CGSize contentSizeInContentViewCoordinates = [_contentView bounds].size;
2197 [_scrollView setMinimumZoomScale:std::min(newMinimumLayoutSize.width() / contentSizeInContentViewCoordinates.width, [_scrollView minimumZoomScale])];
2198 [_scrollView setMaximumZoomScale:std::max(newMinimumLayoutSize.width() / contentSizeInContentViewCoordinates.width, [_scrollView maximumZoomScale])];
2200 // Compute the new scale to keep the current content width in the scrollview.
2201 CGFloat oldWebViewWidthInContentViewCoordinates = oldUnobscuredContentRect.width();
2202 CGFloat visibleContentViewWidthInContentCoordinates = std::min(contentSizeInContentViewCoordinates.width, oldWebViewWidthInContentViewCoordinates);
2203 CGFloat targetScale = newMinimumLayoutSize.width() / visibleContentViewWidthInContentCoordinates;
2204 CGFloat resizeAnimationViewAnimationScale = targetScale / contentZoomScale(self);
2205 [_resizeAnimationView setTransform:CGAffineTransformMakeScale(resizeAnimationViewAnimationScale, resizeAnimationViewAnimationScale)];
2207 // Compute a new position to keep the content centered.
2208 CGPoint originalContentCenter = oldUnobscuredContentRect.center();
2209 CGPoint originalContentCenterInSelfCoordinates = [self convertPoint:originalContentCenter fromView:_contentView.get()];
2210 CGRect futureUnobscuredRectInSelfCoordinates = UIEdgeInsetsInsetRect(newBounds, _obscuredInsets);
2211 CGPoint futureUnobscuredRectCenterInSelfCoordinates = CGPointMake(futureUnobscuredRectInSelfCoordinates.origin.x + futureUnobscuredRectInSelfCoordinates.size.width / 2, futureUnobscuredRectInSelfCoordinates.origin.y + futureUnobscuredRectInSelfCoordinates.size.height / 2);
2213 CGPoint originalContentOffset = [_scrollView contentOffset];
2214 CGPoint contentOffset = originalContentOffset;
2215 contentOffset.x += (originalContentCenterInSelfCoordinates.x - futureUnobscuredRectCenterInSelfCoordinates.x);
2216 contentOffset.y += (originalContentCenterInSelfCoordinates.y - futureUnobscuredRectCenterInSelfCoordinates.y);
2218 // Limit the new offset within the scrollview, we do not want to rubber band programmatically.
2219 CGSize futureContentSizeInSelfCoordinates = CGSizeMake(contentSizeInContentViewCoordinates.width * targetScale, contentSizeInContentViewCoordinates.height * targetScale);
2220 CGFloat maxHorizontalOffset = futureContentSizeInSelfCoordinates.width - newBounds.size.width + _obscuredInsets.right;
2221 contentOffset.x = std::min(contentOffset.x, maxHorizontalOffset);
2222 CGFloat maxVerticalOffset = futureContentSizeInSelfCoordinates.height - newBounds.size.height + _obscuredInsets.bottom;
2223 contentOffset.y = std::min(contentOffset.y, maxVerticalOffset);
2225 contentOffset.x = std::max(contentOffset.x, -_obscuredInsets.left);
2226 contentOffset.y = std::max(contentOffset.y, -_obscuredInsets.top);
2228 // Make the top/bottom edges "sticky" within 1 pixel.
2229 if (oldUnobscuredContentRect.maxY() > contentSizeInContentViewCoordinates.height - 1)
2230 contentOffset.y = maxVerticalOffset;
2231 if (oldUnobscuredContentRect.y() < 1)
2232 contentOffset.y = -_obscuredInsets.top;
2234 // FIXME: if we have content centered after double tap to zoom, we should also try to keep that rect in view.
2235 [_scrollView setContentSize:roundScrollViewContentSize(*_page, futureContentSizeInSelfCoordinates)];
2236 [_scrollView setContentOffset:contentOffset];
2238 CGRect visibleRectInContentCoordinates = [self convertRect:newBounds toView:_contentView.get()];
2239 CGRect unobscuredRectInContentCoordinates = [self convertRect:futureUnobscuredRectInSelfCoordinates toView:_contentView.get()];
2241 _page->dynamicViewportSizeUpdate(newMinimumLayoutSize, newMinimumLayoutSizeForMinimalUI, newMaximumUnobscuredSize, visibleRectInContentCoordinates, unobscuredRectInContentCoordinates, futureUnobscuredRectInSelfCoordinates, targetScale, newOrientation);
2242 _page->drawingArea()->setSize(WebCore::IntSize(newBounds.size), WebCore::IntSize(), WebCore::IntSize());
2245 - (void)_endAnimatedResize
2247 if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing)
2250 _page->synchronizeDynamicViewportUpdate();
2252 NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
2253 [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
2254 [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
2256 CALayer *contentViewLayer = [_contentView layer];
2257 CGFloat adjustmentScale = _resizeAnimationTransformAdjustments.m11;
2258 contentViewLayer.sublayerTransform = CATransform3DIdentity;
2260 CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
2261 CALayer *contentLayer = [_contentView layer];
2262 CATransform3D contentLayerTransform = contentLayer.transform;
2263 CGFloat currentScale = [[_resizeAnimationView layer] transform].m11 * contentLayerTransform.m11;
2265 // We cannot use [UIScrollView setZoomScale:] directly because the UIScrollView delegate would get a callback with
2266 // an invalid contentOffset. The real content offset is only set below.
2267 // Since there is no public API for setting both the zoomScale and the contentOffset, we set the zoomScale manually
2268 // on the zoom layer and then only change the contentOffset.
2269 CGFloat adjustedScale = adjustmentScale * currentScale;
2270 contentLayerTransform.m11 = adjustedScale;
2271 contentLayerTransform.m22 = adjustedScale;
2272 contentLayer.transform = contentLayerTransform;
2274 CGPoint currentScrollOffset = [_scrollView contentOffset];
2275 double horizontalScrollAdjustement = _resizeAnimationTransformAdjustments.m41 * animatingScaleTarget;
2276 double verticalScrollAdjustment = _resizeAnimationTransformAdjustments.m42 * animatingScaleTarget;
2278 [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
2279 [_scrollView setContentOffset:CGPointMake(currentScrollOffset.x - horizontalScrollAdjustement, currentScrollOffset.y - verticalScrollAdjustment)];
2281 [_resizeAnimationView removeFromSuperview];
2282 _resizeAnimationView = nil;
2283 _resizeAnimationTransformAdjustments = CATransform3DIdentity;
2285 _dynamicViewportUpdateMode = DynamicViewportUpdateMode::NotResizing;
2286 [_contentView setHidden:NO];
2287 [self _updateVisibleContentRects];
2290 - (void)_resizeWhileHidingContentWithUpdates:(void (^)(void))updateBlock
2292 [self _beginAnimatedResizeWithUpdates:updateBlock];
2293 if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::ResizingWithAnimation) {
2294 [_contentView setHidden:YES];
2295 _dynamicViewportUpdateMode = DynamicViewportUpdateMode::ResizingWithDocumentHidden;
2299 - (void)_setOverlaidAccessoryViewsInset:(CGSize)inset
2301 [_customContentView web_setOverlaidAccessoryViewsInset:inset];
2304 - (void)_snapshotRect:(CGRect)rectInViewCoordinates intoImageOfWidth:(CGFloat)imageWidth completionHandler:(void(^)(CGImageRef))completionHandler
2306 CGRect snapshotRectInContentCoordinates = [self convertRect:rectInViewCoordinates toView:_contentView.get()];
2307 CGFloat imageHeight = imageWidth / snapshotRectInContentCoordinates.size.width * snapshotRectInContentCoordinates.size.height;
2308 CGSize imageSize = CGSizeMake(imageWidth, imageHeight);
2310 void(^copiedCompletionHandler)(CGImageRef) = [completionHandler copy];
2311 _page->takeSnapshot(WebCore::enclosingIntRect(snapshotRectInContentCoordinates), WebCore::expandedIntSize(WebCore::FloatSize(imageSize)), WebKit::SnapshotOptionsExcludeDeviceScaleFactor, [=](const WebKit::ShareableBitmap::Handle& imageHandle, WebKit::CallbackBase::Error) {
2312 if (imageHandle.isNull()) {
2313 copiedCompletionHandler(nullptr);
2314 [copiedCompletionHandler release];
2318 RefPtr<WebKit::ShareableBitmap> bitmap = WebKit::ShareableBitmap::create(imageHandle, WebKit::SharedMemory::ReadOnly);
2321 copiedCompletionHandler(nullptr);
2322 [copiedCompletionHandler release];
2326 RetainPtr<CGImageRef> cgImage;
2327 cgImage = bitmap->makeCGImage();
2328 copiedCompletionHandler(cgImage.get());
2329 [copiedCompletionHandler release];
2333 - (void)_overrideLayoutParametersWithMinimumLayoutSize:(CGSize)minimumLayoutSize minimumLayoutSizeForMinimalUI:(CGSize)minimumLayoutSizeForMinimalUI maximumUnobscuredSizeOverride:(CGSize)maximumUnobscuredSizeOverride
2335 // FIXME: After Safari is updated to use this function instead of setting the parameters separately, we should remove
2336 // the individual setters and send a single message to send everything at once to the WebProcess.
2337 self._minimumLayoutSizeOverride = minimumLayoutSize;
2338 self._minimumLayoutSizeOverrideForMinimalUI = minimumLayoutSizeForMinimalUI;
2339 self._maximumUnobscuredSizeOverride = maximumUnobscuredSizeOverride;
2342 - (UIView *)_viewForFindUI
2344 return [self viewForZoomingInScrollView:[self scrollView]];
2347 - (BOOL)_isDisplayingPDF
2349 return [_customContentView isKindOfClass:[WKPDFView class]];
2352 - (NSData *)_dataForDisplayedPDF
2354 if (![self _isDisplayingPDF])
2356 CGPDFDocumentRef pdfDocument = [(WKPDFView *)_customContentView pdfDocument];
2357 return [(NSData *)CGDataProviderCopyData(CGPDFDocumentGetDataProvider(pdfDocument)) autorelease];
2360 - (NSString *)_suggestedFilenameForDisplayedPDF
2362 if (![self _isDisplayingPDF])
2364 return [(WKPDFView *)_customContentView.get() suggestedFilename];
2367 - (CGFloat)_viewportMetaTagWidth
2369 return _viewportMetaTagWidth;
2372 - (_WKWebViewPrintFormatter *)_webViewPrintFormatter
2374 UIViewPrintFormatter *viewPrintFormatter = self.viewPrintFormatter;
2375 ASSERT([viewPrintFormatter isKindOfClass:[_WKWebViewPrintFormatter class]]);
2376 return (_WKWebViewPrintFormatter *)viewPrintFormatter;
2381 #pragma mark - OS X-specific methods
2383 - (NSColor *)_pageExtendedBackgroundColor
2385 WebCore::Color color = _page->pageExtendedBackgroundColor();
2386 if (!color.isValid())
2389 return nsColor(color);
2392 - (BOOL)_drawsTransparentBackground
2394 return _page->drawsTransparentBackground();
2397 - (void)_setDrawsTransparentBackground:(BOOL)drawsTransparentBackground
2399 _page->setDrawsTransparentBackground(drawsTransparentBackground);
2402 - (void)_setTopContentInset:(CGFloat)contentInset
2404 [_wkView _setTopContentInset:contentInset];
2407 - (CGFloat)_topContentInset
2409 return [_wkView _topContentInset];
2412 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
2414 - (void)_setAutomaticallyAdjustsContentInsets:(BOOL)automaticallyAdjustsContentInsets
2416 [_wkView _setAutomaticallyAdjustsContentInsets:automaticallyAdjustsContentInsets];
2419 - (BOOL)_automaticallyAdjustsContentInsets
2421 return [_wkView _automaticallyAdjustsContentInsets];
2430 #if !TARGET_OS_IPHONE
2432 @implementation WKWebView (WKIBActions)
2434 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
2436 SEL action = item.action;
2438 if (action == @selector(goBack:))
2439 return !!_page->backForwardList().backItem();
2441 if (action == @selector(goForward:))
2442 return !!_page->backForwardList().forwardItem();
2444 if (action == @selector(stopLoading:)) {
2445 // FIXME: Return no if we're stopped.
2449 if (action == @selector(reload:) || action == @selector(reloadFromOrigin:)) {
2450 // FIXME: Return no if we're loading.
2457 - (IBAction)goBack:(id)sender
2462 - (IBAction)goForward:(id)sender
2467 - (IBAction)reload:(id)sender
2472 - (IBAction)reloadFromOrigin:(id)sender
2474 [self reloadFromOrigin];
2477 - (IBAction)stopLoading:(id)sender
2479 _page->stopLoading();
2487 @implementation WKWebView (_WKWebViewPrintFormatter)
2489 - (Class)_printFormatterClass
2491 return [_WKWebViewPrintFormatter class];
2494 - (NSInteger)_computePageCountAndStartDrawingToPDFForFrame:(_WKFrameHandle *)frame printInfo:(const WebKit::PrintInfo&)printInfo firstPage:(uint32_t)firstPage computedTotalScaleFactor:(double&)totalScaleFactor
2496 if ([self _isDisplayingPDF])
2497 return CGPDFDocumentGetNumberOfPages([(WKPDFView *)_customContentView pdfDocument]);
2499 _pageIsPrintingToPDF = YES;
2500 Vector<WebCore::IntRect> pageRects;
2501 uint64_t frameID = frame ? frame._frameID : _page->mainFrame()->frameID();
2502 if (!_page->sendSync(Messages::WebPage::ComputePagesForPrintingAndStartDrawingToPDF(frameID, printInfo, firstPage), Messages::WebPage::ComputePagesForPrintingAndStartDrawingToPDF::Reply(pageRects, totalScaleFactor)))
2504 return pageRects.size();
2507 - (void)_endPrinting
2509 _pageIsPrintingToPDF = NO;
2510 _printedDocument = nullptr;
2511 _page->send(Messages::WebPage::EndPrinting());
2514 // FIXME: milliseconds::max() overflows when converted to nanoseconds, causing condition_variable::wait_for() to believe
2515 // a timeout occurred on any spurious wakeup. Use nanoseconds::max() (converted to ms) to avoid this. We should perhaps
2516 // change waitForAndDispatchImmediately() to take nanoseconds to avoid this issue.
2517 static constexpr std::chrono::milliseconds didFinishLoadingTimeout = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::nanoseconds::max());
2519 - (CGPDFDocumentRef)_printedDocument
2521 if ([self _isDisplayingPDF]) {
2522 ASSERT(!_pageIsPrintingToPDF);
2523 return [(WKPDFView *)_customContentView pdfDocument];
2526 if (_pageIsPrintingToPDF) {
2527 if (!_page->process().connection()->waitForAndDispatchImmediately<Messages::WebPageProxy::DidFinishDrawingPagesToPDF>(_page->pageID(), didFinishLoadingTimeout)) {
2528 ASSERT_NOT_REACHED();
2531 ASSERT(!_pageIsPrintingToPDF);
2533 return _printedDocument.get();
2536 - (void)_setPrintedDocument:(CGPDFDocumentRef)printedDocument
2538 if (!_pageIsPrintingToPDF)
2540 ASSERT(![self _isDisplayingPDF]);
2541 _printedDocument = printedDocument;
2542 _pageIsPrintingToPDF = NO;
2548 #endif // WK_API_ENABLED