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 "FindClient.h"
33 #import "NavigationState.h"
34 #import "RemoteLayerTreeTransaction.h"
35 #import "RemoteObjectRegistry.h"
36 #import "RemoteObjectRegistryMessages.h"
37 #import "UIDelegate.h"
38 #import "ViewGestureController.h"
39 #import "ViewSnapshotStore.h"
40 #import "WKBackForwardListInternal.h"
41 #import "WKBackForwardListItemInternal.h"
42 #import "WKBrowsingContextHandleInternal.h"
43 #import "WKErrorInternal.h"
44 #import "WKHistoryDelegatePrivate.h"
46 #import "WKNSURLExtras.h"
47 #import "WKNavigationDelegate.h"
48 #import "WKNavigationInternal.h"
49 #import "WKPreferencesInternal.h"
50 #import "WKProcessPoolInternal.h"
51 #import "WKUIDelegate.h"
52 #import "WKUIDelegatePrivate.h"
53 #import "WKUserContentControllerInternal.h"
54 #import "WKWebViewConfigurationInternal.h"
55 #import "WKWebViewContentProvider.h"
56 #import "WebBackForwardList.h"
57 #import "WebCertificateInfo.h"
58 #import "WebContext.h"
59 #import "WebFormSubmissionListenerProxy.h"
60 #import "WebKitSystemInterface.h"
61 #import "WebPageGroup.h"
62 #import "WebPageProxy.h"
63 #import "WebPreferencesKeys.h"
64 #import "WebProcessProxy.h"
65 #import "WebSerializedScriptValue.h"
66 #import "_WKFindDelegate.h"
67 #import "_WKFormDelegate.h"
68 #import "_WKRemoteObjectRegistryInternal.h"
69 #import "_WKVisitedLinkProviderInternal.h"
70 #import "_WKWebsiteDataStoreInternal.h"
71 #import <JavaScriptCore/JSContext.h>
72 #import <JavaScriptCore/JSValue.h>
73 #import <wtf/HashMap.h>
74 #import <wtf/NeverDestroyed.h>
75 #import <wtf/RetainPtr.h>
78 #import "_WKFrameHandleInternal.h"
79 #import "_WKWebViewPrintFormatter.h"
81 #import "ProcessThrottler.h"
83 #import "WKScrollView.h"
84 #import "WKWebViewContentProviderRegistry.h"
85 #import "WebPageMessages.h"
86 #import <CoreGraphics/CGFloat.h>
87 #import <CoreGraphics/CGPDFDocumentPrivate.h>
88 #import <UIKit/UIApplication.h>
89 #import <UIKit/UIPeripheralHost_Private.h>
90 #import <UIKit/UIWindow_Private.h>
91 #import <QuartzCore/CARenderServer.h>
92 #import <QuartzCore/QuartzCorePrivate.h>
94 @interface UIScrollView (UIScrollViewInternal)
95 - (void)_adjustForAutomaticKeyboardInfo:(NSDictionary*)info animated:(BOOL)animated lastAdjustment:(CGFloat*)lastAdjustment;
96 - (BOOL)_isScrollingToTop;
99 @interface UIPeripheralHost(UIKitInternal)
100 - (CGFloat)getVerticalOverlapForView:(UIView *)view usingKeyboardInfo:(NSDictionary *)info;
103 @interface UIView (UIViewInternal)
104 - (UIViewController *)_viewControllerForAncestor;
107 @interface UIWindow (UIWindowInternal)
108 - (BOOL)_isHostedInAnotherProcess;
111 @interface UIViewController (UIViewControllerInternal)
112 - (UIViewController *)_rootAncestorViewController;
113 - (UIViewController *)_viewControllerForSupportedInterfaceOrientations;
118 #import "WKViewInternal.h"
119 #import <WebCore/ColorMac.h>
123 static HashMap<WebKit::WebPageProxy*, WKWebView *>& pageToViewMap()
125 static NeverDestroyed<HashMap<WebKit::WebPageProxy*, WKWebView *>> map;
129 WKWebView* fromWebPageProxy(WebKit::WebPageProxy& page)
131 return pageToViewMap().get(&page);
134 @implementation WKWebView {
135 std::unique_ptr<WebKit::NavigationState> _navigationState;
136 std::unique_ptr<WebKit::UIDelegate> _uiDelegate;
138 RetainPtr<_WKRemoteObjectRegistry> _remoteObjectRegistry;
139 _WKRenderingProgressEvents _observedRenderingProgressEvents;
141 WebKit::WeakObjCPtr<id <_WKFormDelegate>> _formDelegate;
143 RetainPtr<WKScrollView> _scrollView;
144 RetainPtr<WKContentView> _contentView;
146 BOOL _overridesMinimumLayoutSize;
147 CGSize _minimumLayoutSizeOverride;
148 BOOL _overridesMinimumLayoutSizeForMinimalUI;
149 CGSize _minimumLayoutSizeOverrideForMinimalUI;
150 BOOL _overridesMaximumUnobscuredSize;
151 CGSize _maximumUnobscuredSizeOverride;
153 BOOL _needsToNotifyDelegateAboutMinimalUI;
154 CGRect _inputViewBounds;
155 CGFloat _viewportMetaTagWidth;
157 UIEdgeInsets _obscuredInsets;
158 bool _isChangingObscuredInsetsInteractively;
160 UIInterfaceOrientation _interfaceOrientationOverride;
161 BOOL _overridesInterfaceOrientation;
163 BOOL _needsResetViewStateAfterCommitLoadForMainFrame;
164 BOOL _isAnimatingResize;
165 CATransform3D _resizeAnimationTransformAdjustments;
166 RetainPtr<UIView> _resizeAnimationView;
167 CGFloat _lastAdjustmentForScroller;
169 std::unique_ptr<WebKit::ViewGestureController> _gestureController;
170 BOOL _allowsBackForwardNavigationGestures;
172 RetainPtr<UIView <WKWebViewContentProvider>> _customContentView;
173 RetainPtr<UIView> _customContentFixedOverlayView;
175 WebCore::Color _scrollViewBackgroundColor;
177 BOOL _delayUpdateVisibleContentRects;
178 BOOL _hadDelayedUpdateVisibleContentRects;
180 BOOL _pageIsPrintingToPDF;
181 RetainPtr<CGPDFDocumentRef> _printedDocument;
184 RetainPtr<WKView> _wkView;
188 - (instancetype)initWithFrame:(CGRect)frame
190 return [self initWithFrame:frame configuration:adoptNS([[WKWebViewConfiguration alloc] init]).get()];
194 static int32_t deviceOrientationForUIInterfaceOrientation(UIInterfaceOrientation orientation)
196 switch (orientation) {
197 case UIInterfaceOrientationUnknown:
198 case UIInterfaceOrientationPortrait:
200 case UIInterfaceOrientationPortraitUpsideDown:
202 case UIInterfaceOrientationLandscapeLeft:
204 case UIInterfaceOrientationLandscapeRight:
209 static int32_t deviceOrientation()
211 return deviceOrientationForUIInterfaceOrientation([[UIApplication sharedApplication] statusBarOrientation]);
215 - (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration
217 if (!(self = [super initWithFrame:frame]))
220 _configuration = adoptNS([configuration copy]);
222 if (WKWebView *relatedWebView = [_configuration _relatedWebView]) {
223 WKProcessPool *processPool = [_configuration processPool];
224 WKProcessPool *relatedWebViewProcessPool = [relatedWebView->_configuration processPool];
225 if (processPool && processPool != relatedWebViewProcessPool)
226 [NSException raise:NSInvalidArgumentException format:@"Related web view %@ has process pool %@ but configuration specifies a different process pool %@", relatedWebView, relatedWebViewProcessPool, configuration.processPool];
228 [_configuration setProcessPool:relatedWebViewProcessPool];
231 [_configuration _validate];
233 CGRect bounds = self.bounds;
235 WebKit::WebContext& context = *[_configuration processPool]->_context;
237 WebKit::WebPageConfiguration webPageConfiguration;
238 webPageConfiguration.preferences = [_configuration preferences]->_preferences.get();
239 if (WKWebView *relatedWebView = [_configuration _relatedWebView])
240 webPageConfiguration.relatedPage = relatedWebView->_page.get();
242 webPageConfiguration.userContentController = [_configuration userContentController]->_userContentControllerProxy.get();
243 webPageConfiguration.visitedLinkProvider = [_configuration _visitedLinkProvider]->_visitedLinkProvider.get();
244 webPageConfiguration.session = [_configuration _websiteDataStore]->_session.get();
246 RefPtr<WebKit::WebPageGroup> pageGroup;
247 NSString *groupIdentifier = configuration._groupIdentifier;
248 if (groupIdentifier.length) {
249 pageGroup = WebKit::WebPageGroup::create(configuration._groupIdentifier);
250 webPageConfiguration.pageGroup = pageGroup.get();
253 webPageConfiguration.preferenceValues.set(WebKit::WebPreferencesKey::suppressesIncrementalRenderingKey(), WebKit::WebPreferencesStore::Value(!![_configuration suppressesIncrementalRendering]));
256 _scrollView = adoptNS([[WKScrollView alloc] initWithFrame:bounds]);
257 [_scrollView setInternalDelegate:self];
258 [_scrollView setBouncesZoom:YES];
260 [self addSubview:_scrollView.get()];
261 [_scrollView setBackgroundColor:[UIColor whiteColor]];
263 _contentView = adoptNS([[WKContentView alloc] initWithFrame:bounds context:context configuration:std::move(webPageConfiguration) webView:self]);
264 _page = [_contentView page];
266 _page->setDeviceOrientation(deviceOrientation());
268 [_contentView layer].anchorPoint = CGPointZero;
269 [_contentView setFrame:bounds];
270 [_scrollView addSubview:_contentView.get()];
271 _viewportMetaTagWidth = -1;
273 [self _frameOrBoundsChanged];
275 NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
276 [center addObserver:self selector:@selector(_keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
277 [center addObserver:self selector:@selector(_keyboardDidChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
278 [center addObserver:self selector:@selector(_keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
279 [center addObserver:self selector:@selector(_keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
280 [center addObserver:self selector:@selector(_windowDidRotate:) name:UIWindowDidRotateNotification object:nil];
281 [center addObserver:self selector:@selector(_contentSizeCategoryDidChange:) name:UIContentSizeCategoryDidChangeNotification object:nil];
282 _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
284 [[_configuration _contentProviderRegistry] addPage:*_page];
288 _wkView = [[WKView alloc] initWithFrame:bounds context:context configuration:std::move(webPageConfiguration) webView:self];
289 [self addSubview:_wkView.get()];
290 _page = WebKit::toImpl([_wkView pageRef]);
293 _page->setBackgroundExtendsBeyondPage(true);
295 _navigationState = std::make_unique<WebKit::NavigationState>(self);
296 _page->setPolicyClient(_navigationState->createPolicyClient());
297 _page->setLoaderClient(_navigationState->createLoaderClient());
299 _uiDelegate = std::make_unique<WebKit::UIDelegate>(self);
300 _page->setUIClient(_uiDelegate->createUIClient());
302 _page->setFindClient(std::make_unique<WebKit::FindClient>(self));
304 pageToViewMap().add(_page.get(), self);
309 - (instancetype)initWithCoder:(NSCoder *)coder
319 [_remoteObjectRegistry _invalidate];
321 [[_configuration _contentProviderRegistry] removePage:*_page];
322 [[NSNotificationCenter defaultCenter] removeObserver:self];
325 pageToViewMap().remove(_page.get());
330 - (WKWebViewConfiguration *)configuration
332 return [[_configuration copy] autorelease];
335 - (WKBackForwardList *)backForwardList
337 return wrapper(_page->backForwardList());
340 - (id <WKNavigationDelegate>)navigationDelegate
342 return [_navigationState->navigationDelegate().leakRef() autorelease];
345 - (void)setNavigationDelegate:(id <WKNavigationDelegate>)navigationDelegate
347 _navigationState->setNavigationDelegate(navigationDelegate);
350 - (id <WKUIDelegate>)UIDelegate
352 return [_uiDelegate->delegate().leakRef() autorelease];
355 - (void)setUIDelegate:(id<WKUIDelegate>)UIDelegate
357 _uiDelegate->setDelegate(UIDelegate);
360 - (WKNavigation *)loadRequest:(NSURLRequest *)request
362 uint64_t navigationID = _page->loadRequest(request);
363 auto navigation = _navigationState->createLoadRequestNavigation(navigationID, request);
365 return [navigation.leakRef() autorelease];
368 - (WKNavigation *)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
370 uint64_t navigationID = _page->loadHTMLString(string, baseURL.absoluteString);
371 auto navigation = _navigationState->createLoadDataNavigation(navigationID);
373 return [navigation.leakRef() autorelease];
376 - (WKNavigation *)goToBackForwardListItem:(WKBackForwardListItem *)item
378 uint64_t navigationID = _page->goToBackForwardItem(&item._item);
380 auto navigation = _navigationState->createBackForwardNavigation(navigationID, item._item);
382 return [navigation.leakRef() autorelease];
387 return _page->pageLoadState().title();
392 return [NSURL _web_URLWithWTFString:_page->pageLoadState().activeURL()];
397 return _page->pageLoadState().isLoading();
400 - (double)estimatedProgress
402 return _page->pageLoadState().estimatedProgress();
405 - (BOOL)hasOnlySecureContent
407 return _page->pageLoadState().hasOnlySecureContent();
412 return _page->pageLoadState().canGoBack();
417 return _page->pageLoadState().canGoForward();
420 - (WKNavigation *)goBack
422 uint64_t navigationID = _page->goBack();
426 ASSERT(_page->backForwardList().currentItem());
427 auto navigation = _navigationState->createBackForwardNavigation(navigationID, *_page->backForwardList().currentItem());
429 return [navigation.leakRef() autorelease];
432 - (WKNavigation *)goForward
434 uint64_t navigationID = _page->goForward();
438 ASSERT(_page->backForwardList().currentItem());
439 auto navigation = _navigationState->createBackForwardNavigation(navigationID, *_page->backForwardList().currentItem());
441 return [navigation.leakRef() autorelease];
444 - (WKNavigation *)reload
446 uint64_t navigationID = _page->reload(false);
447 ASSERT(navigationID);
449 auto navigation = _navigationState->createReloadNavigation(navigationID);
450 return [navigation.leakRef() autorelease];
453 - (WKNavigation *)reloadFromOrigin
455 uint64_t navigationID = _page->reload(true);
456 ASSERT(navigationID);
458 auto navigation = _navigationState->createReloadNavigation(navigationID);
459 return [navigation.leakRef() autorelease];
464 _page->stopLoading();
467 static WKErrorCode callbackErrorCode(WebKit::CallbackBase::Error error)
470 case WebKit::CallbackBase::Error::None:
471 ASSERT_NOT_REACHED();
472 return WKErrorUnknown;
474 case WebKit::CallbackBase::Error::Unknown:
475 return WKErrorUnknown;
477 case WebKit::CallbackBase::Error::ProcessExited:
478 return WKErrorWebContentProcessTerminated;
480 case WebKit::CallbackBase::Error::OwnerWasInvalidated:
481 return WKErrorWebViewInvalidated;
485 - (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *))completionHandler
487 auto handler = adoptNS([completionHandler copy]);
489 _page->runJavaScriptInMainFrame(javaScriptString, WebKit::ScriptValueCallback::create([handler](WebKit::WebSerializedScriptValue* serializedScriptValue, WebKit::ScriptValueCallback::Error errorCode) {
493 auto completionHandler = (void (^)(id, NSError *))handler.get();
495 if (errorCode != WebKit::ScriptValueCallback::Error::None) {
496 auto error = createNSError(callbackErrorCode(errorCode));
497 if (errorCode == WebKit::ScriptValueCallback::Error::OwnerWasInvalidated) {
498 // The OwnerWasInvalidated callback is synchronous. We don't want to call the block from within it
499 // because that can trigger re-entrancy bugs in WebKit.
500 // FIXME: It would be even better if GenericCallback did this for us.
501 dispatch_async(dispatch_get_main_queue(), [completionHandler, error] {
502 completionHandler(nil, error.get());
507 completionHandler(nil, error.get());
511 if (!serializedScriptValue) {
512 completionHandler(nil, createNSError(WKErrorJavaScriptExceptionOccurred).get());
516 auto context = adoptNS([[JSContext alloc] init]);
517 JSValueRef valueRef = serializedScriptValue->deserialize([context JSGlobalContextRef], 0);
518 JSValue *value = [JSValue valueWithJSValueRef:valueRef inContext:context.get()];
520 completionHandler([value toObject], nil);
524 #pragma mark iOS-specific methods
527 - (void)setFrame:(CGRect)frame
529 CGRect oldFrame = self.frame;
530 [super setFrame:frame];
532 if (!CGSizeEqualToSize(oldFrame.size, frame.size))
533 [self _frameOrBoundsChanged];
536 - (void)setBounds:(CGRect)bounds
538 CGRect oldBounds = self.bounds;
539 [super setBounds:bounds];
540 [_customContentFixedOverlayView setFrame:self.bounds];
542 if (!CGSizeEqualToSize(oldBounds.size, bounds.size))
543 [self _frameOrBoundsChanged];
546 - (UIScrollView *)scrollView
548 return _scrollView.get();
551 - (WKBrowsingContextController *)browsingContextController
553 return [_contentView browsingContextController];
556 static inline CGFloat floorToDevicePixel(CGFloat input, float deviceScaleFactor)
558 return CGFloor(input * deviceScaleFactor) / deviceScaleFactor;
561 static CGSize roundScrollViewContentSize(const WebKit::WebPageProxy& page, CGSize contentSize)
563 float deviceScaleFactor = page.deviceScaleFactor();
564 return CGSizeMake(floorToDevicePixel(contentSize.width, deviceScaleFactor), floorToDevicePixel(contentSize.height, deviceScaleFactor));
567 - (void)_setHasCustomContentView:(BOOL)pageHasCustomContentView loadedMIMEType:(const WTF::String&)mimeType
569 if (pageHasCustomContentView) {
570 [_customContentView removeFromSuperview];
571 [_customContentFixedOverlayView removeFromSuperview];
573 Class representationClass = [[_configuration _contentProviderRegistry] providerForMIMEType:mimeType];
574 ASSERT(representationClass);
575 _customContentView = adoptNS([[representationClass alloc] init]);
576 _customContentFixedOverlayView = adoptNS([[UIView alloc] initWithFrame:self.bounds]);
577 [_customContentFixedOverlayView setUserInteractionEnabled:NO];
579 [_contentView removeFromSuperview];
580 [_scrollView addSubview:_customContentView.get()];
581 [self addSubview:_customContentFixedOverlayView.get()];
583 [_customContentView web_setMinimumSize:self.bounds.size];
584 [_customContentView web_setScrollView:_scrollView.get()];
585 [_customContentView web_setObscuredInsets:_obscuredInsets];
586 [_customContentView web_setFixedOverlayView:_customContentFixedOverlayView.get()];
587 } else if (_customContentView) {
588 [_customContentView removeFromSuperview];
589 _customContentView = nullptr;
591 [_customContentFixedOverlayView removeFromSuperview];
592 _customContentFixedOverlayView = nullptr;
594 [_scrollView addSubview:_contentView.get()];
595 [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
597 [_customContentFixedOverlayView setFrame:self.bounds];
598 [self addSubview:_customContentFixedOverlayView.get()];
602 - (void)_didFinishLoadingDataForCustomContentProviderWithSuggestedFilename:(const String&)suggestedFilename data:(NSData *)data
604 ASSERT(_customContentView);
605 [_customContentView web_setContentProviderData:data suggestedFilename:suggestedFilename];
608 - (void)_setViewportMetaTagWidth:(float)newWidth
610 _viewportMetaTagWidth = newWidth;
613 - (void)_willInvokeUIScrollViewDelegateCallback
615 _delayUpdateVisibleContentRects = YES;
618 - (void)_didInvokeUIScrollViewDelegateCallback
620 _delayUpdateVisibleContentRects = NO;
621 if (_hadDelayedUpdateVisibleContentRects) {
622 _hadDelayedUpdateVisibleContentRects = NO;
623 [self _updateVisibleContentRects];
627 static CGFloat contentZoomScale(WKWebView* webView)
630 if (webView->_customContentView)
631 zoomView = webView->_customContentView.get();
633 zoomView = webView->_contentView.get();
635 CGFloat scale = [[zoomView layer] affineTransform].a;
636 ASSERT(scale == [webView->_scrollView zoomScale]);
640 - (void)_updateScrollViewBackground
642 WebCore::Color color;
643 if (_customContentView)
644 color = [_customContentView backgroundColor].CGColor;
646 color = _page->pageExtendedBackgroundColor();
647 CGFloat zoomScale = contentZoomScale(self);
648 CGFloat minimumZoomScale = [_scrollView minimumZoomScale];
649 if (zoomScale < minimumZoomScale) {
651 CGFloat opacity = std::max<CGFloat>(1 - slope * (minimumZoomScale - zoomScale), 0);
652 color = WebCore::colorWithOverrideAlpha(color.rgb(), opacity);
655 if (_scrollViewBackgroundColor == color)
658 _scrollViewBackgroundColor = color;
660 RetainPtr<UIColor*> uiBackgroundColor = adoptNS([[UIColor alloc] initWithCGColor:cachedCGColor(color, WebCore::ColorSpaceDeviceRGB)]);
661 [_scrollView setBackgroundColor:uiBackgroundColor.get()];
664 - (void)_setUsesMinimalUI:(BOOL)usesMinimalUI
666 _usesMinimalUI = usesMinimalUI;
667 _needsToNotifyDelegateAboutMinimalUI = YES;
670 - (BOOL)_usesMinimalUI
672 return _usesMinimalUI;
675 - (void)_processDidExit
677 if (!_customContentView && _isAnimatingResize) {
678 NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
679 [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
680 [_resizeAnimationView removeFromSuperview];
681 _resizeAnimationView = nil;
683 _isAnimatingResize = NO;
684 _resizeAnimationTransformAdjustments = CATransform3DIdentity;
686 [_contentView setFrame:self.bounds];
687 [_scrollView setBackgroundColor:[UIColor whiteColor]];
688 [_scrollView setContentOffset:CGPointMake(-_obscuredInsets.left, -_obscuredInsets.top)];
689 [_scrollView setZoomScale:1];
691 _viewportMetaTagWidth = -1;
692 _needsResetViewStateAfterCommitLoadForMainFrame = NO;
693 _scrollViewBackgroundColor = WebCore::Color();
694 _delayUpdateVisibleContentRects = NO;
695 _hadDelayedUpdateVisibleContentRects = NO;
698 - (void)_didCommitLoadForMainFrame
700 _needsResetViewStateAfterCommitLoadForMainFrame = YES;
704 - (void)_didCommitLayerTree:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
706 if (_customContentView)
709 if (_isAnimatingResize) {
710 [_resizeAnimationView layer].sublayerTransform = _resizeAnimationTransformAdjustments;
714 [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
715 [_scrollView setMinimumZoomScale:layerTreeTransaction.minimumScaleFactor()];
716 [_scrollView setMaximumZoomScale:layerTreeTransaction.maximumScaleFactor()];
717 [_scrollView setZoomEnabled:layerTreeTransaction.allowsUserScaling()];
718 if (!layerTreeTransaction.scaleWasSetByUIProcess() && ![_scrollView isZooming] && ![_scrollView isZoomBouncing] && ![_scrollView _isAnimatingZoom])
719 [_scrollView setZoomScale:layerTreeTransaction.pageScaleFactor()];
721 [self _updateScrollViewBackground];
723 if (_gestureController)
724 _gestureController->setRenderTreeSize(layerTreeTransaction.renderTreeSize());
726 if (_needsToNotifyDelegateAboutMinimalUI || _needsResetViewStateAfterCommitLoadForMainFrame) {
727 _needsToNotifyDelegateAboutMinimalUI = NO;
729 auto delegate = _uiDelegate->delegate();
730 if ([delegate respondsToSelector:@selector(_webView:usesMinimalUI:)])
731 [static_cast<id <WKUIDelegatePrivate>>(delegate.get()) _webView:self usesMinimalUI:_usesMinimalUI];
734 if (_needsResetViewStateAfterCommitLoadForMainFrame) {
735 _needsResetViewStateAfterCommitLoadForMainFrame = NO;
736 [_scrollView setContentOffset:CGPointMake(-_obscuredInsets.left, -_obscuredInsets.top)];
740 - (void)_dynamicViewportUpdateChangedTargetToScale:(double)newScale position:(CGPoint)newScrollPosition
742 if (_isAnimatingResize) {
743 CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
744 double currentTargetScale = animatingScaleTarget * [[_contentView layer] transform].m11;
745 double scale = newScale / currentTargetScale;
746 _resizeAnimationTransformAdjustments = CATransform3DMakeScale(scale, scale, 0);
748 CGPoint newContentOffset = CGPointMake(newScrollPosition.x * newScale, newScrollPosition.y * newScale);
749 newContentOffset.x -= _obscuredInsets.left;
750 newContentOffset.y -= _obscuredInsets.top;
751 CGPoint currentContentOffset = [_scrollView contentOffset];
753 _resizeAnimationTransformAdjustments.m41 = (currentContentOffset.x - newContentOffset.x) / animatingScaleTarget;
754 _resizeAnimationTransformAdjustments.m42 = (currentContentOffset.y - newContentOffset.y) / animatingScaleTarget;
758 - (WebKit::ViewSnapshot)_takeViewSnapshot
760 float deviceScale = WKGetScreenScaleFactor();
761 CGSize snapshotSize = self.bounds.size;
762 snapshotSize.width *= deviceScale;
763 snapshotSize.height *= deviceScale;
765 WebKit::ViewSnapshot snapshot;
766 snapshot.slotID = [WebKit::ViewSnapshotStore::snapshottingContext() createImageSlot:snapshotSize hasAlpha:YES];
768 CATransform3D transform = CATransform3DMakeScale(deviceScale, deviceScale, 1);
769 CARenderServerCaptureLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, (uint64_t)self.layer, snapshot.slotID, 0, 0, &transform);
771 snapshot.size = WebCore::expandedIntSize(WebCore::FloatSize(snapshotSize));
772 snapshot.imageSizeInBytes = snapshotSize.width * snapshotSize.height * 4;
777 - (void)_zoomToPoint:(WebCore::FloatPoint)point atScale:(double)scale
779 double maximumZoomDuration = 0.4;
780 double minimumZoomDuration = 0.1;
781 double zoomDurationFactor = 0.3;
783 CGFloat zoomScale = contentZoomScale(self);
784 CFTimeInterval duration = std::min(fabs(log(zoomScale) - log(scale)) * zoomDurationFactor + minimumZoomDuration, maximumZoomDuration);
786 if (scale != zoomScale)
787 _page->willStartUserTriggeredZooming();
789 [_scrollView _zoomToCenter:point scale:scale duration:duration];
792 - (void)_zoomToRect:(WebCore::FloatRect)targetRect atScale:(double)scale origin:(WebCore::FloatPoint)origin
794 // FIMXE: Some of this could be shared with _scrollToRect.
795 const double visibleRectScaleChange = contentZoomScale(self) / scale;
796 const WebCore::FloatRect visibleRect([self convertRect:self.bounds toView:_contentView.get()]);
797 const WebCore::FloatRect unobscuredRect([self _contentRectForUserInteraction]);
799 const WebCore::FloatSize topLeftObscuredInsetAfterZoom((unobscuredRect.minXMinYCorner() - visibleRect.minXMinYCorner()) * visibleRectScaleChange);
800 const WebCore::FloatSize bottomRightObscuredInsetAfterZoom((visibleRect.maxXMaxYCorner() - unobscuredRect.maxXMaxYCorner()) * visibleRectScaleChange);
802 const WebCore::FloatSize unobscuredRectSizeAfterZoom(unobscuredRect.size() * visibleRectScaleChange);
804 // Center to the target rect.
805 WebCore::FloatPoint unobscuredRectLocationAfterZoom = targetRect.location() - (unobscuredRectSizeAfterZoom - targetRect.size()) * 0.5;
807 // Center to the tap point instead in case the target rect won't fit in a direction.
808 if (targetRect.width() > unobscuredRectSizeAfterZoom.width())
809 unobscuredRectLocationAfterZoom.setX(origin.x() - unobscuredRectSizeAfterZoom.width() / 2);
810 if (targetRect.height() > unobscuredRectSizeAfterZoom.height())
811 unobscuredRectLocationAfterZoom.setY(origin.y() - unobscuredRectSizeAfterZoom.height() / 2);
813 // We have computed where we want the unobscured rect to be. Now adjust for the obscuring insets.
814 WebCore::FloatRect visibleRectAfterZoom(unobscuredRectLocationAfterZoom, unobscuredRectSizeAfterZoom);
815 visibleRectAfterZoom.move(-topLeftObscuredInsetAfterZoom);
816 visibleRectAfterZoom.expand(topLeftObscuredInsetAfterZoom + bottomRightObscuredInsetAfterZoom);
818 [self _zoomToPoint:visibleRectAfterZoom.center() atScale:scale];
821 static WebCore::FloatPoint constrainContentOffset(WebCore::FloatPoint contentOffset, WebCore::FloatSize contentSize, WebCore::FloatSize unobscuredContentSize)
823 WebCore::FloatSize maximumContentOffset = contentSize - unobscuredContentSize;
824 contentOffset = contentOffset.shrunkTo(WebCore::FloatPoint(maximumContentOffset.width(), maximumContentOffset.height()));
825 contentOffset = contentOffset.expandedTo(WebCore::FloatPoint());
826 return contentOffset;
829 - (void)_scrollToContentOffset:(WebCore::FloatPoint)contentOffset
831 if (_isAnimatingResize)
834 [_scrollView _stopScrollingAndZoomingAnimations];
836 WebCore::FloatPoint scaledOffset = contentOffset;
837 CGFloat zoomScale = contentZoomScale(self);
838 scaledOffset.scale(zoomScale, zoomScale);
840 scaledOffset -= WebCore::FloatSize(_obscuredInsets.left, _obscuredInsets.top);
841 [_scrollView setContentOffset:scaledOffset];
844 - (BOOL)_scrollToRect:(WebCore::FloatRect)targetRect origin:(WebCore::FloatPoint)origin minimumScrollDistance:(float)minimumScrollDistance
846 WebCore::FloatRect unobscuredContentRect([self _contentRectForUserInteraction]);
847 WebCore::FloatPoint unobscuredContentOffset = unobscuredContentRect.location();
848 WebCore::FloatSize contentSize([_contentView bounds].size);
850 // Center the target rect in the scroll view.
851 // If the target doesn't fit in the scroll view, center on the gesture location instead.
852 WebCore::FloatPoint newUnobscuredContentOffset;
853 if (targetRect.width() <= unobscuredContentRect.width())
854 newUnobscuredContentOffset.setX(targetRect.x() - (unobscuredContentRect.width() - targetRect.width()) / 2);
856 newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
857 if (targetRect.height() <= unobscuredContentRect.height())
858 newUnobscuredContentOffset.setY(targetRect.y() - (unobscuredContentRect.height() - targetRect.height()) / 2);
860 newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
861 newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
863 if (unobscuredContentOffset == newUnobscuredContentOffset) {
864 if (targetRect.width() > unobscuredContentRect.width())
865 newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
866 if (targetRect.height() > unobscuredContentRect.height())
867 newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
868 newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
871 WebCore::FloatSize scrollViewOffsetDelta = newUnobscuredContentOffset - unobscuredContentOffset;
872 scrollViewOffsetDelta.scale(contentZoomScale(self));
874 float scrollDistance = scrollViewOffsetDelta.diagonalLength();
875 if (scrollDistance < minimumScrollDistance)
878 [_scrollView setContentOffset:([_scrollView contentOffset] + scrollViewOffsetDelta) animated:YES];
882 - (void)_zoomOutWithOrigin:(WebCore::FloatPoint)origin
884 [self _zoomToPoint:origin atScale:[_scrollView minimumZoomScale]];
887 // focusedElementRect and selectionRect are both in document coordinates.
888 - (void)_zoomToFocusRect:(WebCore::FloatRect)focusedElementRectInDocumentCoordinates selectionRect:(WebCore::FloatRect)selectionRectInDocumentCoordinates fontSize:(float)fontSize minimumScale:(double)minimumScale maximumScale:(double)maximumScale allowScaling:(BOOL)allowScaling forceScroll:(BOOL)forceScroll
890 const double WKWebViewStandardFontSize = 16;
891 const double kMinimumHeightToShowContentAboveKeyboard = 106;
892 const CFTimeInterval UIWebFormAnimationDuration = 0.25;
893 const double CaretOffsetFromWindowEdge = 20;
895 // Zoom around the element's bounding frame. We use a "standard" size to determine the proper frame.
896 double scale = allowScaling ? std::min(std::max(WKWebViewStandardFontSize / fontSize, minimumScale), maximumScale) : contentZoomScale(self);
897 CGFloat documentWidth = [_contentView bounds].size.width;
898 scale = CGRound(documentWidth * scale) / documentWidth;
900 UIWindow *window = [_scrollView window];
902 WebCore::FloatRect focusedElementRectInNewScale = focusedElementRectInDocumentCoordinates;
903 focusedElementRectInNewScale.scale(scale);
904 focusedElementRectInNewScale.moveBy([_contentView frame].origin);
906 // Find the portion of the view that is visible on the screen.
907 UIViewController *topViewController = [[[_scrollView _viewControllerForAncestor] _rootAncestorViewController] _viewControllerForSupportedInterfaceOrientations];
908 UIView *fullScreenView = topViewController.view;
910 fullScreenView = window;
912 CGRect unobscuredScrollViewRectInWebViewCoordinates = UIEdgeInsetsInsetRect([self bounds], _obscuredInsets);
913 CGRect visibleScrollViewBoundsInWebViewCoordinates = CGRectIntersection(unobscuredScrollViewRectInWebViewCoordinates, [fullScreenView convertRect:[fullScreenView bounds] toView:self]);
914 CGRect formAssistantFrameInWebViewCoordinates = [window convertRect:_inputViewBounds toView:self];
915 CGRect intersectionBetweenScrollViewAndFormAssistant = CGRectIntersection(visibleScrollViewBoundsInWebViewCoordinates, formAssistantFrameInWebViewCoordinates);
916 CGSize visibleSize = visibleScrollViewBoundsInWebViewCoordinates.size;
918 CGFloat visibleOffsetFromTop = 0;
919 if (!CGRectIsEmpty(intersectionBetweenScrollViewAndFormAssistant)) {
920 CGFloat heightVisibleAboveFormAssistant = CGRectGetMinY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
921 CGFloat heightVisibleBelowFormAssistant = CGRectGetMaxY(visibleScrollViewBoundsInWebViewCoordinates) - CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant);
923 if (heightVisibleAboveFormAssistant >= kMinimumHeightToShowContentAboveKeyboard || heightVisibleBelowFormAssistant < heightVisibleAboveFormAssistant)
924 visibleSize.height = heightVisibleAboveFormAssistant;
926 visibleSize.height = heightVisibleBelowFormAssistant;
927 visibleOffsetFromTop = CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
931 BOOL selectionRectIsNotNull = !selectionRectInDocumentCoordinates.isZero();
933 CGRect currentlyVisibleRegionInWebViewCoordinates;
934 currentlyVisibleRegionInWebViewCoordinates.origin = unobscuredScrollViewRectInWebViewCoordinates.origin;
935 currentlyVisibleRegionInWebViewCoordinates.origin.y += visibleOffsetFromTop;
936 currentlyVisibleRegionInWebViewCoordinates.size = visibleSize;
938 // Don't bother scrolling if the entire node is already visible, whether or not we got a selectionRect.
939 if (CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:focusedElementRectInDocumentCoordinates fromView:_contentView.get()]))
942 // Don't bother scrolling if we have a valid selectionRect and it is already visible.
943 if (selectionRectIsNotNull && CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:selectionRectInDocumentCoordinates fromView:_contentView.get()]))
947 // We want to zoom to the left/top corner of the DOM node, with as much spacing on all sides as we
948 // can get based on the visible area after zooming (workingFrame). The spacing in either dimension is half the
949 // difference between the size of the DOM node and the size of the visible frame.
950 CGFloat horizontalSpaceInWebViewCoordinates = std::max((visibleSize.width - focusedElementRectInNewScale.width()) / 2.0, 0.0);
951 CGFloat verticalSpaceInWebViewCoordinates = std::max((visibleSize.height - focusedElementRectInNewScale.height()) / 2.0, 0.0);
954 topLeft.x = focusedElementRectInNewScale.x() - horizontalSpaceInWebViewCoordinates;
955 topLeft.y = focusedElementRectInNewScale.y() - verticalSpaceInWebViewCoordinates - visibleOffsetFromTop;
957 CGFloat minimumAllowableHorizontalOffsetInWebViewCoordinates = -INFINITY;
958 CGFloat minimumAllowableVerticalOffsetInWebViewCoordinates = -INFINITY;
959 if (selectionRectIsNotNull) {
960 WebCore::FloatRect selectionRectInNewScale = selectionRectInDocumentCoordinates;
961 selectionRectInNewScale.scale(scale);
962 selectionRectInNewScale.moveBy([_contentView frame].origin);
963 minimumAllowableHorizontalOffsetInWebViewCoordinates = CGRectGetMaxX(selectionRectInNewScale) + CaretOffsetFromWindowEdge - visibleSize.width;
964 minimumAllowableVerticalOffsetInWebViewCoordinates = CGRectGetMaxY(selectionRectInNewScale) + CaretOffsetFromWindowEdge - visibleSize.height - visibleOffsetFromTop;
967 WebCore::FloatRect documentBoundsInNewScale = [_contentView bounds];
968 documentBoundsInNewScale.scale(scale);
969 documentBoundsInNewScale.moveBy([_contentView frame].origin);
971 // Constrain the left edge in document coordinates so that:
972 // - it isn't so small that the scrollVisibleRect isn't visible on the screen
973 // - it isn't so great that the document's right edge is less than the right edge of the screen
974 if (selectionRectIsNotNull && topLeft.x < minimumAllowableHorizontalOffsetInWebViewCoordinates)
975 topLeft.x = minimumAllowableHorizontalOffsetInWebViewCoordinates;
977 CGFloat maximumAllowableHorizontalOffset = CGRectGetMaxX(documentBoundsInNewScale) - visibleSize.width;
978 if (topLeft.x > maximumAllowableHorizontalOffset)
979 topLeft.x = maximumAllowableHorizontalOffset;
982 // Constrain the top edge in document coordinates so that:
983 // - it isn't so small that the scrollVisibleRect isn't visible on the screen
984 // - it isn't so great that the document's bottom edge is higher than the top of the form assistant
985 if (selectionRectIsNotNull && topLeft.y < minimumAllowableVerticalOffsetInWebViewCoordinates)
986 topLeft.y = minimumAllowableVerticalOffsetInWebViewCoordinates;
988 CGFloat maximumAllowableVerticalOffset = CGRectGetMaxY(documentBoundsInNewScale) - visibleSize.height;
989 if (topLeft.y > maximumAllowableVerticalOffset)
990 topLeft.y = maximumAllowableVerticalOffset;
993 WebCore::FloatPoint newCenter = CGPointMake(topLeft.x + unobscuredScrollViewRectInWebViewCoordinates.size.width / 2.0, topLeft.y + unobscuredScrollViewRectInWebViewCoordinates.size.height / 2.0);
995 if (scale != contentZoomScale(self))
996 _page->willStartUserTriggeredZooming();
998 // The newCenter has been computed in the new scale, but _zoomToCenter expected the center to be in the original scale.
999 newCenter.scale(1 / scale, 1 / scale);
1000 [_scrollView _zoomToCenter:newCenter
1002 duration:UIWebFormAnimationDuration
1006 - (BOOL)_zoomToRect:(WebCore::FloatRect)targetRect withOrigin:(WebCore::FloatPoint)origin fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale minimumScrollDistance:(float)minimumScrollDistance
1008 const float maximumScaleFactorDeltaForPanScroll = 0.02;
1010 double currentScale = contentZoomScale(self);
1012 WebCore::FloatSize unobscuredContentSize([self _contentRectForUserInteraction].size);
1013 double horizontalScale = unobscuredContentSize.width() * currentScale / targetRect.width();
1014 double verticalScale = unobscuredContentSize.height() * currentScale / targetRect.height();
1016 horizontalScale = std::min(std::max(horizontalScale, minimumScale), maximumScale);
1017 verticalScale = std::min(std::max(verticalScale, minimumScale), maximumScale);
1019 double targetScale = fitEntireRect ? std::min(horizontalScale, verticalScale) : horizontalScale;
1020 if (fabs(targetScale - currentScale) < maximumScaleFactorDeltaForPanScroll) {
1021 if ([self _scrollToRect:targetRect origin:origin minimumScrollDistance:minimumScrollDistance])
1023 } else if (targetScale != currentScale) {
1024 [self _zoomToRect:targetRect atScale:targetScale origin:origin];
1031 - (void)didMoveToWindow
1033 _page->viewStateDidChange(WebCore::ViewState::IsInWindow);
1036 #pragma mark - UIScrollViewDelegate
1038 - (BOOL)usesStandardContentView
1040 return !_customContentView;
1043 - (CGSize)scrollView:(UIScrollView*)scrollView contentSizeForZoomScale:(CGFloat)scale withProposedSize:(CGSize)proposedSize
1045 return roundScrollViewContentSize(*_page, proposedSize);
1048 - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
1050 ASSERT(_scrollView == scrollView);
1052 if (_customContentView)
1053 return _customContentView.get();
1055 return _contentView.get();
1058 - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
1060 if (![self usesStandardContentView])
1063 if (scrollView.pinchGestureRecognizer.state == UIGestureRecognizerStateBegan) {
1064 _page->willStartUserTriggeredZooming();
1065 [_contentView scrollViewWillStartPanOrPinchGesture];
1067 [_contentView willStartZoomOrScroll];
1070 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
1072 if (![self usesStandardContentView])
1075 if (scrollView.panGestureRecognizer.state == UIGestureRecognizerStateBegan)
1076 [_contentView scrollViewWillStartPanOrPinchGesture];
1077 [_contentView willStartZoomOrScroll];
1080 - (void)_didFinishScrolling
1082 if (![self usesStandardContentView])
1085 [self _updateVisibleContentRects];
1086 [_contentView didFinishScrolling];
1089 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
1091 // Work around <rdar://problem/16374753> by avoiding deceleration while
1092 // zooming. We'll animate to the right place once the zoom finishes.
1093 if ([scrollView isZooming])
1094 *targetContentOffset = [scrollView contentOffset];
1097 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
1099 // If we're decelerating, scroll offset will be updated when scrollViewDidFinishDecelerating: is called.
1101 [self _didFinishScrolling];
1104 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
1106 [self _didFinishScrolling];
1109 - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
1111 [self _didFinishScrolling];
1114 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
1116 if (![self usesStandardContentView])
1117 [_customContentView scrollViewDidScroll:(UIScrollView *)scrollView];
1119 [self _updateVisibleContentRects];
1122 - (void)scrollViewDidZoom:(UIScrollView *)scrollView
1124 [self _updateScrollViewBackground];
1125 [self _updateVisibleContentRects];
1128 - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
1130 ASSERT(scrollView == _scrollView);
1131 [self _updateVisibleContentRects];
1132 [_contentView didZoomToScale:scale];
1135 - (void)_frameOrBoundsChanged
1137 CGRect bounds = self.bounds;
1138 if (!_isAnimatingResize) {
1139 if (!_overridesMinimumLayoutSize)
1140 _page->setViewportConfigurationMinimumLayoutSize(WebCore::FloatSize(bounds.size));
1141 if (!_overridesMinimumLayoutSizeForMinimalUI)
1142 _page->setViewportConfigurationMinimumLayoutSizeForMinimalUI(WebCore::FloatSize(bounds.size));
1143 if (!_overridesMaximumUnobscuredSize)
1144 _page->setMaximumUnobscuredSize(WebCore::FloatSize(bounds.size));
1147 [_scrollView setFrame:bounds];
1148 [_contentView setMinimumSize:bounds.size];
1149 [_customContentView web_setMinimumSize:bounds.size];
1150 [self _updateVisibleContentRects];
1153 // 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.
1154 - (CGRect)_contentRectForUserInteraction
1156 // FIXME: handle split keyboard.
1157 UIEdgeInsets obscuredInsets = _obscuredInsets;
1158 obscuredInsets.bottom = std::max(_obscuredInsets.bottom, _inputViewBounds.size.height);
1159 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInsets);
1160 return [self convertRect:unobscuredRect toView:_contentView.get()];
1163 - (void)_updateVisibleContentRects
1165 if (![self usesStandardContentView])
1168 if (_delayUpdateVisibleContentRects) {
1169 _hadDelayedUpdateVisibleContentRects = YES;
1173 if (_isAnimatingResize)
1176 CGRect fullViewRect = self.bounds;
1177 CGRect visibleRectInContentCoordinates = [self convertRect:fullViewRect toView:_contentView.get()];
1179 CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, _obscuredInsets);
1180 CGRect unobscuredRectInContentCoordinates = [self convertRect:unobscuredRect toView:_contentView.get()];
1182 CGFloat scaleFactor = contentZoomScale(self);
1184 BOOL isStableState = !(_isChangingObscuredInsetsInteractively || [_scrollView isDragging] || [_scrollView isDecelerating] || [_scrollView isZooming] || [_scrollView isZoomBouncing] || [_scrollView _isAnimatingZoom] || [_scrollView _isScrollingToTop]);
1185 [_contentView didUpdateVisibleRect:visibleRectInContentCoordinates
1186 unobscuredRect:unobscuredRectInContentCoordinates
1187 unobscuredRectInScrollViewCoordinates:unobscuredRect
1188 scale:scaleFactor minimumScale:[_scrollView minimumZoomScale]
1189 inStableState:isStableState isChangingObscuredInsetsInteractively:_isChangingObscuredInsetsInteractively];
1192 - (void)_keyboardChangedWithInfo:(NSDictionary *)keyboardInfo adjustScrollView:(BOOL)adjustScrollView
1194 NSValue *endFrameValue = [keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
1198 // The keyboard rect is always in screen coordinates. In the view services case the window does not
1199 // have the interface orientation rotation transformation; its host does. So, it makes no sense to
1200 // clip the keyboard rect against its screen.
1201 if ([[self window] _isHostedInAnotherProcess])
1202 _inputViewBounds = [self.window convertRect:[endFrameValue CGRectValue] fromWindow:nil];
1204 _inputViewBounds = [self.window convertRect:CGRectIntersection([endFrameValue CGRectValue], self.window.screen.bounds) fromWindow:nil];
1206 [self _updateVisibleContentRects];
1208 if (adjustScrollView)
1209 [_scrollView _adjustForAutomaticKeyboardInfo:keyboardInfo animated:YES lastAdjustment:&_lastAdjustmentForScroller];
1212 - (void)_keyboardWillChangeFrame:(NSNotification *)notification
1214 if ([_contentView isAssistingNode])
1215 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
1218 - (void)_keyboardDidChangeFrame:(NSNotification *)notification
1220 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:NO];
1223 - (void)_keyboardWillShow:(NSNotification *)notification
1225 if ([_contentView isAssistingNode])
1226 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
1229 - (void)_keyboardWillHide:(NSNotification *)notification
1231 // Ignore keyboard will hide notifications sent during rotation. They're just there for
1232 // backwards compatibility reasons and processing the will hide notification would
1233 // temporarily screw up the the unobscured view area.
1234 if ([[UIPeripheralHost sharedInstance] rotationState])
1237 [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
1240 - (void)_windowDidRotate:(NSNotification *)notification
1242 if (!_overridesInterfaceOrientation)
1243 _page->setDeviceOrientation(deviceOrientation());
1246 - (void)_contentSizeCategoryDidChange:(NSNotification *)notification
1248 _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
1251 - (NSString *)_contentSizeCategory
1253 return [[UIApplication sharedApplication] preferredContentSizeCategory];
1256 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
1258 if (_allowsBackForwardNavigationGestures == allowsBackForwardNavigationGestures)
1261 _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
1263 if (allowsBackForwardNavigationGestures) {
1264 if (!_gestureController) {
1265 _gestureController = std::make_unique<WebKit::ViewGestureController>(*_page);
1266 _gestureController->installSwipeHandler(self, [self scrollView]);
1269 _gestureController = nullptr;
1271 _page->setShouldRecordNavigationSnapshots(allowsBackForwardNavigationGestures);
1274 - (BOOL)allowsBackForwardNavigationGestures
1276 return _allowsBackForwardNavigationGestures;
1281 #pragma mark OS X-specific methods
1285 - (void)resizeSubviewsWithOldSize:(NSSize)oldSize
1287 [_wkView setFrame:self.bounds];
1290 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
1292 [_wkView setAllowsBackForwardNavigationGestures:allowsBackForwardNavigationGestures];
1295 - (BOOL)allowsBackForwardNavigationGestures
1297 return [_wkView allowsBackForwardNavigationGestures];
1300 - (void)setAllowsMagnification:(BOOL)allowsMagnification
1302 [_wkView setAllowsMagnification:allowsMagnification];
1305 - (BOOL)allowsMagnification
1307 return [_wkView allowsMagnification];
1310 - (void)setMagnification:(CGFloat)magnification
1312 [_wkView setMagnification:magnification];
1315 - (CGFloat)magnification
1317 return [_wkView magnification];
1320 - (void)setMagnification:(CGFloat)magnification centeredAtPoint:(CGPoint)point
1322 [_wkView setMagnification:magnification centeredAtPoint:NSPointFromCGPoint(point)];
1329 @implementation WKWebView (WKPrivate)
1331 - (_WKRemoteObjectRegistry *)_remoteObjectRegistry
1333 if (!_remoteObjectRegistry) {
1334 _remoteObjectRegistry = adoptNS([[_WKRemoteObjectRegistry alloc] _initWithMessageSender:*_page]);
1335 _page->process().context().addMessageReceiver(Messages::RemoteObjectRegistry::messageReceiverName(), _page->pageID(), [_remoteObjectRegistry remoteObjectRegistry]);
1338 return _remoteObjectRegistry.get();
1341 - (WKBrowsingContextHandle *)_handle
1343 return [[[WKBrowsingContextHandle alloc] _initWithPageID:_page->pageID()] autorelease];
1346 - (_WKRenderingProgressEvents)_observedRenderingProgressEvents
1348 return _observedRenderingProgressEvents;
1351 - (id <WKHistoryDelegatePrivate>)_historyDelegate
1353 return [_navigationState->historyDelegate().leakRef() autorelease];
1356 - (void)_setHistoryDelegate:(id <WKHistoryDelegatePrivate>)historyDelegate
1358 _navigationState->setHistoryDelegate(historyDelegate);
1361 - (NSURL *)_unreachableURL
1363 return [NSURL _web_URLWithWTFString:_page->pageLoadState().unreachableURL()];
1366 - (void)_loadAlternateHTMLString:(NSString *)string baseURL:(NSURL *)baseURL forUnreachableURL:(NSURL *)unreachableURL
1368 _page->loadAlternateHTMLString(string, [baseURL _web_originalDataAsWTFString], [unreachableURL _web_originalDataAsWTFString]);
1371 - (WKNavigation *)_reload
1373 return [self reload];
1376 - (NSArray *)_certificateChain
1378 if (WebKit::WebFrameProxy* mainFrame = _page->mainFrame())
1379 return mainFrame->certificateInfo() ? (NSArray *)mainFrame->certificateInfo()->certificateInfo().certificateChain() : nil;
1384 - (NSURL *)_committedURL
1386 return [NSURL _web_URLWithWTFString:_page->pageLoadState().url()];
1389 - (NSString *)_applicationNameForUserAgent
1391 return _page->applicationNameForUserAgent();
1394 - (void)_setApplicationNameForUserAgent:(NSString *)applicationNameForUserAgent
1396 _page->setApplicationNameForUserAgent(applicationNameForUserAgent);
1399 - (NSString *)_customUserAgent
1401 return _page->customUserAgent();
1404 - (void)_setCustomUserAgent:(NSString *)_customUserAgent
1406 _page->setCustomUserAgent(_customUserAgent);
1409 - (pid_t)_webProcessIdentifier
1411 return _page->isValid() ? _page->processIdentifier() : 0;
1414 - (void)_killWebContentProcess
1416 if (!_page->isValid())
1419 _page->process().terminate();
1422 - (NSData *)_sessionState
1424 return [wrapper(*_page->sessionStateData(nullptr, nullptr).leakRef()) autorelease];
1427 static void releaseNSData(unsigned char*, const void* data)
1429 [(NSData *)data release];
1432 - (void)_restoreFromSessionState:(NSData *)sessionState
1434 [sessionState retain];
1435 _page->restoreFromSessionStateData(API::Data::createWithoutCopying((const unsigned char*)sessionState.bytes, sessionState.length, releaseNSData, sessionState).get());
1443 - (BOOL)_privateBrowsingEnabled
1445 return [_configuration preferences]->_preferences->privateBrowsingEnabled();
1448 - (void)_setPrivateBrowsingEnabled:(BOOL)privateBrowsingEnabled
1450 [_configuration preferences]->_preferences->setPrivateBrowsingEnabled(privateBrowsingEnabled);
1453 - (BOOL)_allowsRemoteInspection
1455 #if ENABLE(REMOTE_INSPECTOR)
1456 return _page->allowsRemoteInspection();
1462 - (void)_setAllowsRemoteInspection:(BOOL)allow
1464 #if ENABLE(REMOTE_INSPECTOR)
1465 _page->setAllowsRemoteInspection(allow);
1469 - (BOOL)_addsVisitedLinks
1471 return _page->addsVisitedLinks();
1474 - (void)_setAddsVisitedLinks:(BOOL)addsVisitedLinks
1476 _page->setAddsVisitedLinks(addsVisitedLinks);
1479 static inline WebCore::LayoutMilestones layoutMilestones(_WKRenderingProgressEvents events)
1481 WebCore::LayoutMilestones milestones = 0;
1483 if (events & _WKRenderingProgressEventFirstLayout)
1484 milestones |= WebCore::DidFirstLayout;
1486 if (events & _WKRenderingProgressEventFirstPaintWithSignificantArea)
1487 milestones |= WebCore::DidHitRelevantRepaintedObjectsAreaThreshold;
1492 - (void)_setObservedRenderingProgressEvents:(_WKRenderingProgressEvents)observedRenderingProgressEvents
1494 _observedRenderingProgressEvents = observedRenderingProgressEvents;
1495 _page->listenForLayoutMilestones(layoutMilestones(observedRenderingProgressEvents));
1498 - (void)_runJavaScriptInMainFrame:(NSString *)scriptString
1500 [self evaluateJavaScript:scriptString completionHandler:^(id, NSError *) { }];
1503 - (void)_getWebArchiveDataWithCompletionHandler:(void (^)(NSData *, NSError *))completionHandler
1505 auto handler = adoptNS([completionHandler copy]);
1507 _page->getWebArchiveOfFrame(_page->mainFrame(), WebKit::DataCallback::create([handler](bool isError, API::Data* data) {
1508 void (^completionHandlerBlock)(NSData *, NSError *) = (void (^)(NSData *, NSError *))handler.get();
1510 // FIXME: Pipe a proper error in from the WebPageProxy.
1511 RetainPtr<NSError> error = adoptNS([[NSError alloc] init]);
1512 completionHandlerBlock(nil, error.get());
1514 completionHandlerBlock(wrapper(*data), nil);
1518 - (_WKPaginationMode)_paginationMode
1520 switch (_page->paginationMode()) {
1521 case WebCore::Pagination::Unpaginated:
1522 return _WKPaginationModeUnpaginated;
1523 case WebCore::Pagination::LeftToRightPaginated:
1524 return _WKPaginationModeLeftToRight;
1525 case WebCore::Pagination::RightToLeftPaginated:
1526 return _WKPaginationModeRightToLeft;
1527 case WebCore::Pagination::TopToBottomPaginated:
1528 return _WKPaginationModeTopToBottom;
1529 case WebCore::Pagination::BottomToTopPaginated:
1530 return _WKPaginationModeBottomToTop;
1533 ASSERT_NOT_REACHED();
1534 return _WKPaginationModeUnpaginated;
1537 - (void)_setPaginationMode:(_WKPaginationMode)paginationMode
1539 WebCore::Pagination::Mode mode;
1540 switch (paginationMode) {
1541 case _WKPaginationModeUnpaginated:
1542 mode = WebCore::Pagination::Unpaginated;
1544 case _WKPaginationModeLeftToRight:
1545 mode = WebCore::Pagination::LeftToRightPaginated;
1547 case _WKPaginationModeRightToLeft:
1548 mode = WebCore::Pagination::RightToLeftPaginated;
1550 case _WKPaginationModeTopToBottom:
1551 mode = WebCore::Pagination::TopToBottomPaginated;
1553 case _WKPaginationModeBottomToTop:
1554 mode = WebCore::Pagination::BottomToTopPaginated;
1560 _page->setPaginationMode(mode);
1563 - (BOOL)_paginationBehavesLikeColumns
1565 return _page->paginationBehavesLikeColumns();
1568 - (void)_setPaginationBehavesLikeColumns:(BOOL)behavesLikeColumns
1570 _page->setPaginationBehavesLikeColumns(behavesLikeColumns);
1573 - (CGFloat)_pageLength
1575 return _page->pageLength();
1578 - (void)_setPageLength:(CGFloat)pageLength
1580 _page->setPageLength(pageLength);
1583 - (CGFloat)_gapBetweenPages
1585 return _page->gapBetweenPages();
1588 - (void)_setGapBetweenPages:(CGFloat)gapBetweenPages
1590 _page->setGapBetweenPages(gapBetweenPages);
1593 - (NSUInteger)_pageCount
1595 return _page->pageCount();
1598 - (BOOL)_supportsTextZoom
1600 return _page->supportsTextZoom();
1603 - (double)_textZoomFactor
1605 return _page->textZoomFactor();
1608 - (void)_setTextZoomFactor:(double)zoomFactor
1610 _page->setTextZoomFactor(zoomFactor);
1613 - (double)_pageZoomFactor
1615 return _page->pageZoomFactor();
1618 - (void)_setPageZoomFactor:(double)zoomFactor
1620 _page->setPageZoomFactor(zoomFactor);
1623 - (id <_WKFindDelegate>)_findDelegate
1625 return [static_cast<WebKit::FindClient&>(_page->findClient()).delegate().leakRef() autorelease];
1628 - (void)_setFindDelegate:(id<_WKFindDelegate>)findDelegate
1630 static_cast<WebKit::FindClient&>(_page->findClient()).setDelegate(findDelegate);
1633 static inline WebKit::FindOptions toFindOptions(_WKFindOptions wkFindOptions)
1635 unsigned findOptions = 0;
1637 if (wkFindOptions & _WKFindOptionsCaseInsensitive)
1638 findOptions |= WebKit::FindOptionsCaseInsensitive;
1639 if (wkFindOptions & _WKFindOptionsAtWordStarts)
1640 findOptions |= WebKit::FindOptionsAtWordStarts;
1641 if (wkFindOptions & _WKFindOptionsTreatMedialCapitalAsWordStart)
1642 findOptions |= WebKit::FindOptionsTreatMedialCapitalAsWordStart;
1643 if (wkFindOptions & _WKFindOptionsBackwards)
1644 findOptions |= WebKit::FindOptionsBackwards;
1645 if (wkFindOptions & _WKFindOptionsWrapAround)
1646 findOptions |= WebKit::FindOptionsWrapAround;
1647 if (wkFindOptions & _WKFindOptionsShowOverlay)
1648 findOptions |= WebKit::FindOptionsShowOverlay;
1649 if (wkFindOptions & _WKFindOptionsShowFindIndicator)
1650 findOptions |= WebKit::FindOptionsShowFindIndicator;
1651 if (wkFindOptions & _WKFindOptionsShowHighlight)
1652 findOptions |= WebKit::FindOptionsShowHighlight;
1653 if (wkFindOptions & _WKFindOptionsDetermineMatchIndex)
1654 findOptions |= WebKit::FindOptionsDetermineMatchIndex;
1656 return static_cast<WebKit::FindOptions>(findOptions);
1659 - (void)_countStringMatches:(NSString *)string options:(_WKFindOptions)options maxCount:(NSUInteger)maxCount
1661 _page->countStringMatches(string, toFindOptions(options), maxCount);
1664 - (void)_findString:(NSString *)string options:(_WKFindOptions)options maxCount:(NSUInteger)maxCount
1666 _page->findString(string, toFindOptions(options), maxCount);
1671 _page->hideFindUI();
1674 - (id <_WKFormDelegate>)_formDelegate
1676 return _formDelegate.getAutoreleased();
1679 - (void)_setFormDelegate:(id <_WKFormDelegate>)formDelegate
1681 _formDelegate = formDelegate;
1683 class FormClient : public API::FormClient {
1685 explicit FormClient(WKWebView *webView)
1686 : m_webView(webView)
1690 virtual ~FormClient() { }
1692 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
1694 if (userData && userData->type() != API::Object::Type::Data) {
1695 ASSERT(!userData || userData->type() == API::Object::Type::Data);
1696 m_webView->_page->process().connection()->markCurrentlyDispatchedMessageAsInvalid();
1700 auto formDelegate = m_webView->_formDelegate.get();
1702 if (![formDelegate respondsToSelector:@selector(_webView:willSubmitFormValues:userObject:submissionHandler:)])
1705 auto valueMap = adoptNS([[NSMutableDictionary alloc] initWithCapacity:textFieldValues.size()]);
1706 for (const auto& pair : textFieldValues)
1707 [valueMap setObject:pair.second forKey:pair.first];
1709 NSObject <NSSecureCoding> *userObject = nil;
1710 if (API::Data* data = static_cast<API::Data*>(userData)) {
1711 auto nsData = adoptNS([[NSData alloc] initWithBytesNoCopy:const_cast<void*>(static_cast<const void*>(data->bytes())) length:data->size() freeWhenDone:NO]);
1712 auto unarchiver = adoptNS([[NSKeyedUnarchiver alloc] initForReadingWithData:nsData.get()]);
1713 [unarchiver setRequiresSecureCoding:YES];
1715 userObject = [unarchiver decodeObjectOfClass:[NSObject class] forKey:@"userObject"];
1716 } @catch (NSException *exception) {
1717 LOG_ERROR("Failed to decode user data: %@", exception);
1721 [formDelegate _webView:m_webView willSubmitFormValues:valueMap.get() userObject:userObject submissionHandler:^{
1722 listener->continueSubmission();
1728 WKWebView *m_webView;
1732 _page->setFormClient(std::make_unique<FormClient>(self));
1734 _page->setFormClient(nullptr);
1737 #pragma mark iOS-specific methods
1741 - (CGSize)_minimumLayoutSizeOverride
1743 ASSERT(_overridesMinimumLayoutSize);
1744 return _minimumLayoutSizeOverride;
1747 - (void)_setMinimumLayoutSizeOverride:(CGSize)minimumLayoutSizeOverride
1749 _overridesMinimumLayoutSize = YES;
1750 if (CGSizeEqualToSize(_minimumLayoutSizeOverride, minimumLayoutSizeOverride))
1753 _minimumLayoutSizeOverride = minimumLayoutSizeOverride;
1754 if (!_isAnimatingResize)
1755 _page->setViewportConfigurationMinimumLayoutSize(WebCore::FloatSize(minimumLayoutSizeOverride));
1758 - (CGSize)_minimumLayoutSizeOverrideForMinimalUI
1760 ASSERT(_overridesMinimumLayoutSizeForMinimalUI);
1761 return _minimumLayoutSizeOverrideForMinimalUI;
1764 - (void)_setMinimumLayoutSizeOverrideForMinimalUI:(CGSize)size
1766 _overridesMinimumLayoutSizeForMinimalUI = YES;
1767 if (CGSizeEqualToSize(_minimumLayoutSizeOverrideForMinimalUI, size))
1770 _minimumLayoutSizeOverrideForMinimalUI = size;
1771 if (!_isAnimatingResize)
1772 _page->setViewportConfigurationMinimumLayoutSizeForMinimalUI(WebCore::FloatSize(size));
1775 - (UIEdgeInsets)_obscuredInsets
1777 return _obscuredInsets;
1780 - (void)_setObscuredInsets:(UIEdgeInsets)obscuredInsets
1782 ASSERT(obscuredInsets.top >= 0);
1783 ASSERT(obscuredInsets.left >= 0);
1784 ASSERT(obscuredInsets.bottom >= 0);
1785 ASSERT(obscuredInsets.right >= 0);
1787 if (UIEdgeInsetsEqualToEdgeInsets(_obscuredInsets, obscuredInsets))
1790 _obscuredInsets = obscuredInsets;
1792 [self _updateVisibleContentRects];
1793 [_customContentView web_setObscuredInsets:obscuredInsets];
1796 - (void)_setInterfaceOrientationOverride:(UIInterfaceOrientation)interfaceOrientation
1798 if (!_overridesInterfaceOrientation)
1799 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIWindowDidRotateNotification object:nil];
1801 _overridesInterfaceOrientation = YES;
1803 if (interfaceOrientation == _interfaceOrientationOverride)
1806 _interfaceOrientationOverride = interfaceOrientation;
1808 if (!_isAnimatingResize)
1809 _page->setDeviceOrientation(deviceOrientationForUIInterfaceOrientation(_interfaceOrientationOverride));
1812 - (UIInterfaceOrientation)_interfaceOrientationOverride
1814 ASSERT(_overridesInterfaceOrientation);
1815 return _interfaceOrientationOverride;
1818 - (CGSize)_maximumUnobscuredSizeOverride
1820 ASSERT(_overridesMaximumUnobscuredSize);
1821 return _maximumUnobscuredSizeOverride;
1824 - (void)_setMaximumUnobscuredSizeOverride:(CGSize)size
1826 ASSERT(size.width <= self.bounds.size.width && size.height <= self.bounds.size.height);
1827 _overridesMaximumUnobscuredSize = YES;
1828 if (CGSizeEqualToSize(_maximumUnobscuredSizeOverride, size))
1831 _maximumUnobscuredSizeOverride = size;
1832 if (!_isAnimatingResize)
1833 _page->setMaximumUnobscuredSize(WebCore::FloatSize(size));
1836 - (void)_setBackgroundExtendsBeyondPage:(BOOL)backgroundExtends
1838 _page->setBackgroundExtendsBeyondPage(backgroundExtends);
1841 - (BOOL)_backgroundExtendsBeyondPage
1843 return _page->backgroundExtendsBeyondPage();
1846 - (void)_beginInteractiveObscuredInsetsChange
1848 ASSERT(!_isChangingObscuredInsetsInteractively);
1849 _isChangingObscuredInsetsInteractively = YES;
1852 - (void)_endInteractiveObscuredInsetsChange
1854 ASSERT(_isChangingObscuredInsetsInteractively);
1855 _isChangingObscuredInsetsInteractively = NO;
1856 [self _updateVisibleContentRects];
1859 - (void)_beginAnimatedResizeWithUpdates:(void (^)(void))updateBlock
1861 _isAnimatingResize = YES;
1863 if (_customContentView) {
1868 _resizeAnimationTransformAdjustments = CATransform3DIdentity;
1870 NSUInteger indexOfContentView = [[_scrollView subviews] indexOfObject:_contentView.get()];
1871 _resizeAnimationView = adoptNS([[UIView alloc] init]);
1872 [_scrollView insertSubview:_resizeAnimationView.get() atIndex:indexOfContentView];
1873 [_resizeAnimationView addSubview:_contentView.get()];
1874 WebCore::FloatRect oldUnobscuredContentRect = _page->unobscuredContentRect();
1878 CGRect newBounds = self.bounds;
1879 CGSize newMinimumLayoutSize = newBounds.size;
1881 CGSize contentSizeInContentViewCoordinates = [_contentView bounds].size;
1882 [_scrollView setMinimumZoomScale:std::min(newMinimumLayoutSize.width / contentSizeInContentViewCoordinates.width, [_scrollView minimumZoomScale])];
1883 [_scrollView setMaximumZoomScale:std::max(newMinimumLayoutSize.width / contentSizeInContentViewCoordinates.width, [_scrollView maximumZoomScale])];
1885 // Compute the new scale to keep the current content width in the scrollview.
1886 CGFloat oldWebViewWidthInContentViewCoordinates = oldUnobscuredContentRect.width();
1887 CGFloat visibleContentViewWidthInContentCoordinates = std::min(contentSizeInContentViewCoordinates.width, oldWebViewWidthInContentViewCoordinates);
1888 CGFloat targetScale = newMinimumLayoutSize.width / visibleContentViewWidthInContentCoordinates;
1889 CGFloat resizeAnimationViewAnimationScale = targetScale / contentZoomScale(self);
1890 [_resizeAnimationView setTransform:CGAffineTransformMakeScale(resizeAnimationViewAnimationScale, resizeAnimationViewAnimationScale)];
1892 // Compute a new position to keep the content centered.
1893 CGPoint originalContentCenter = oldUnobscuredContentRect.center();
1894 CGPoint originalContentCenterInSelfCoordinates = [self convertPoint:originalContentCenter fromView:_contentView.get()];
1895 CGRect futureUnobscuredRectInSelfCoordinates = UIEdgeInsetsInsetRect(newBounds, _obscuredInsets);
1896 CGPoint futureUnobscuredRectCenterInSelfCoordinates = CGPointMake(futureUnobscuredRectInSelfCoordinates.origin.x + futureUnobscuredRectInSelfCoordinates.size.width / 2, futureUnobscuredRectInSelfCoordinates.origin.y + futureUnobscuredRectInSelfCoordinates.size.height / 2);
1898 CGPoint originalContentOffset = [_scrollView contentOffset];
1899 CGPoint contentOffset = originalContentOffset;
1900 contentOffset.x += (originalContentCenterInSelfCoordinates.x - futureUnobscuredRectCenterInSelfCoordinates.x);
1901 contentOffset.y += (originalContentCenterInSelfCoordinates.y - futureUnobscuredRectCenterInSelfCoordinates.y);
1903 // Limit the new offset within the scrollview, we do not want to rubber band programmatically.
1904 CGSize futureContentSizeInSelfCoordinates = CGSizeMake(contentSizeInContentViewCoordinates.width * targetScale, contentSizeInContentViewCoordinates.height * targetScale);
1905 CGFloat maxHorizontalOffset = futureContentSizeInSelfCoordinates.width - newBounds.size.width + _obscuredInsets.right;
1906 contentOffset.x = std::min(contentOffset.x, maxHorizontalOffset);
1907 CGFloat maxVerticalOffset = futureContentSizeInSelfCoordinates.height - newBounds.size.height + _obscuredInsets.bottom;
1908 contentOffset.y = std::min(contentOffset.y, maxVerticalOffset);
1910 contentOffset.x = std::max(contentOffset.x, -_obscuredInsets.left);
1911 contentOffset.y = std::max(contentOffset.y, -_obscuredInsets.top);
1913 // Make the top/bottom edges "sticky" within 1 pixel.
1914 if (oldUnobscuredContentRect.maxY() > contentSizeInContentViewCoordinates.height - 1)
1915 contentOffset.y = maxVerticalOffset;
1916 if (oldUnobscuredContentRect.y() < 1)
1917 contentOffset.y = -_obscuredInsets.top;
1919 // FIXME: if we have content centered after double tap to zoom, we should also try to keep that rect in view.
1920 [_scrollView setContentSize:roundScrollViewContentSize(*_page, futureContentSizeInSelfCoordinates)];
1921 [_scrollView setContentOffset:contentOffset];
1923 CGRect visibleRectInContentCoordinates = [self convertRect:newBounds toView:_contentView.get()];
1924 CGRect unobscuredRectInContentCoordinates = [self convertRect:futureUnobscuredRectInSelfCoordinates toView:_contentView.get()];
1926 CGSize minimumLayoutSize = newBounds.size;
1927 if (_overridesMinimumLayoutSize)
1928 minimumLayoutSize = _minimumLayoutSizeOverride;
1930 CGSize minimumLayoutSizeForMinimalUI = minimumLayoutSize;
1931 if (_overridesMinimumLayoutSizeForMinimalUI)
1932 minimumLayoutSizeForMinimalUI = _minimumLayoutSizeOverrideForMinimalUI;
1934 CGSize maximumUnobscuredSize = newBounds.size;
1935 if (_overridesMaximumUnobscuredSize)
1936 maximumUnobscuredSize = _maximumUnobscuredSizeOverride;
1938 int32_t orientation;
1939 if (_overridesInterfaceOrientation)
1940 orientation = deviceOrientationForUIInterfaceOrientation(_interfaceOrientationOverride);
1942 orientation = _page->deviceOrientation();
1944 _page->dynamicViewportSizeUpdate(WebCore::FloatSize(minimumLayoutSize), WebCore::FloatSize(minimumLayoutSizeForMinimalUI), WebCore::FloatSize(maximumUnobscuredSize), visibleRectInContentCoordinates, unobscuredRectInContentCoordinates, futureUnobscuredRectInSelfCoordinates, targetScale, orientation);
1947 - (void)_endAnimatedResize
1949 _page->synchronizeDynamicViewportUpdate();
1951 if (!_customContentView && _isAnimatingResize) {
1952 NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
1953 [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
1955 CALayer *contentViewLayer = [_contentView layer];
1956 CATransform3D resizeAnimationTransformAdjustements = _resizeAnimationTransformAdjustments;
1957 CGFloat adjustmentScale = resizeAnimationTransformAdjustements.m11;
1958 contentViewLayer.sublayerTransform = CATransform3DIdentity;
1960 CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
1961 CALayer *contentLayer = [_contentView layer];
1962 CATransform3D contentLayerTransform = contentLayer.transform;
1963 CGFloat currentScale = [[_resizeAnimationView layer] transform].m11 * contentLayerTransform.m11;
1965 // We cannot use [UIScrollView setZoomScale:] directly because the UIScrollView delegate would get a callback with
1966 // an invalid contentOffset. The real content offset is only set below.
1967 // Since there is no public API for setting both the zoomScale and the contentOffset, we set the zoomScale manually
1968 // on the zoom layer and then only change the contentOffset.
1969 CGFloat adjustedScale = adjustmentScale * currentScale;
1970 contentLayerTransform.m11 = adjustedScale;
1971 contentLayerTransform.m22 = adjustedScale;
1972 contentLayer.transform = contentLayerTransform;
1974 CGPoint currentScrollOffset = [_scrollView contentOffset];
1975 double horizontalScrollAdjustement = _resizeAnimationTransformAdjustments.m41 * animatingScaleTarget;
1976 double verticalScrollAdjustment = _resizeAnimationTransformAdjustments.m42 * animatingScaleTarget;
1978 [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
1979 [_scrollView setContentOffset:CGPointMake(currentScrollOffset.x - horizontalScrollAdjustement, currentScrollOffset.y - verticalScrollAdjustment)];
1981 [_resizeAnimationView removeFromSuperview];
1982 _resizeAnimationView = nil;
1985 _isAnimatingResize = NO;
1986 _resizeAnimationTransformAdjustments = CATransform3DIdentity;
1988 [self _updateVisibleContentRects];
1991 - (void)_showInspectorIndication
1993 [_contentView setShowingInspectorIndication:YES];
1996 - (void)_hideInspectorIndication
1998 [_contentView setShowingInspectorIndication:NO];
2001 - (void)_setOverlaidAccessoryViewsInset:(CGSize)inset
2003 [_customContentView web_setOverlaidAccessoryViewsInset:inset];
2006 - (void)_snapshotRect:(CGRect)rectInViewCoordinates intoImageOfWidth:(CGFloat)imageWidth completionHandler:(void(^)(CGImageRef))completionHandler
2008 CGRect snapshotRectInContentCoordinates = [self convertRect:rectInViewCoordinates toView:_contentView.get()];
2009 CGFloat imageHeight = imageWidth / snapshotRectInContentCoordinates.size.width * snapshotRectInContentCoordinates.size.height;
2010 CGSize imageSize = CGSizeMake(imageWidth, imageHeight);
2013 WebKit::ProcessThrottler::BackgroundActivityToken* activityToken = new WebKit::ProcessThrottler::BackgroundActivityToken(_page->process().throttler());
2016 void(^copiedCompletionHandler)(CGImageRef) = [completionHandler copy];
2017 _page->takeSnapshot(WebCore::enclosingIntRect(snapshotRectInContentCoordinates), WebCore::expandedIntSize(WebCore::FloatSize(imageSize)), WebKit::SnapshotOptionsExcludeDeviceScaleFactor, [=](bool, const WebKit::ShareableBitmap::Handle& imageHandle) {
2019 // Automatically delete when this goes out of scope.
2020 auto uniqueActivityToken = std::unique_ptr<WebKit::ProcessThrottler::BackgroundActivityToken>(activityToken);
2023 if (imageHandle.isNull()) {
2024 copiedCompletionHandler(nullptr);
2025 [copiedCompletionHandler release];
2029 RefPtr<WebKit::ShareableBitmap> bitmap = WebKit::ShareableBitmap::create(imageHandle, WebKit::SharedMemory::ReadOnly);
2032 copiedCompletionHandler(nullptr);
2033 [copiedCompletionHandler release];
2037 RetainPtr<CGImageRef> cgImage;
2038 cgImage = bitmap->makeCGImage();
2039 copiedCompletionHandler(cgImage.get());
2040 [copiedCompletionHandler release];
2044 - (void)_overrideLayoutParametersWithMinimumLayoutSize:(CGSize)minimumLayoutSize minimumLayoutSizeForMinimalUI:(CGSize)minimumLayoutSizeForMinimalUI maximumUnobscuredSizeOverride:(CGSize)maximumUnobscuredSizeOverride
2046 // FIXME: After Safari is updated to use this function instead of setting the parameters separately, we should remove
2047 // the individual setters and send a single message to send everything at once to the WebProcess.
2048 self._minimumLayoutSizeOverride = minimumLayoutSize;
2049 self._minimumLayoutSizeOverrideForMinimalUI = minimumLayoutSizeForMinimalUI;
2050 self._maximumUnobscuredSizeOverride = maximumUnobscuredSizeOverride;
2053 - (UIView *)_viewForFindUI
2055 return [self viewForZoomingInScrollView:[self scrollView]];
2058 - (BOOL)_isDisplayingPDF
2060 return [_customContentView isKindOfClass:[WKPDFView class]];
2063 - (NSData *)_dataForDisplayedPDF
2065 if (![self _isDisplayingPDF])
2067 CGPDFDocumentRef pdfDocument = [(WKPDFView *)_customContentView pdfDocument];
2068 return [(NSData *)CGDataProviderCopyData(CGPDFDocumentGetDataProvider(pdfDocument)) autorelease];
2071 - (NSString *)_suggestedFilenameForDisplayedPDF
2073 if (![self _isDisplayingPDF])
2075 return [(WKPDFView *)_customContentView.get() suggestedFilename];
2078 - (CGFloat)_viewportMetaTagWidth
2080 return _viewportMetaTagWidth;
2083 - (_WKWebViewPrintFormatter *)_webViewPrintFormatter
2085 UIViewPrintFormatter *viewPrintFormatter = self.viewPrintFormatter;
2086 ASSERT([viewPrintFormatter isKindOfClass:[_WKWebViewPrintFormatter class]]);
2087 return (_WKWebViewPrintFormatter *)viewPrintFormatter;
2092 #pragma mark - OS X-specific methods
2094 - (NSColor *)_pageExtendedBackgroundColor
2096 WebCore::Color color = _page->pageExtendedBackgroundColor();
2097 if (!color.isValid())
2100 return nsColor(color);
2103 - (BOOL)_drawsTransparentBackground
2105 return _page->drawsTransparentBackground();
2108 - (void)_setDrawsTransparentBackground:(BOOL)drawsTransparentBackground
2110 _page->setDrawsTransparentBackground(drawsTransparentBackground);
2113 - (void)_setTopContentInset:(CGFloat)contentInset
2115 _page->setTopContentInset(contentInset);
2118 - (CGFloat)_topContentInset
2120 return _page->topContentInset();
2127 #if !TARGET_OS_IPHONE
2129 @implementation WKWebView (WKIBActions)
2131 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
2133 SEL action = item.action;
2135 if (action == @selector(goBack:))
2136 return !!_page->backForwardList().backItem();
2138 if (action == @selector(goForward:))
2139 return !!_page->backForwardList().forwardItem();
2141 if (action == @selector(stopLoading:)) {
2142 // FIXME: Return no if we're stopped.
2146 if (action == @selector(reload:) || action == @selector(reloadFromOrigin:)) {
2147 // FIXME: Return no if we're loading.
2154 - (IBAction)goBack:(id)sender
2159 - (IBAction)goForward:(id)sender
2164 - (IBAction)reload:(id)sender
2169 - (IBAction)reloadFromOrigin:(id)sender
2171 [self reloadFromOrigin];
2174 - (IBAction)stopLoading:(id)sender
2176 _page->stopLoading();
2184 @implementation WKWebView (_WKWebViewPrintFormatter)
2186 - (Class)_printFormatterClass
2188 return [_WKWebViewPrintFormatter class];
2191 - (NSInteger)_computePageCountAndStartDrawingToPDFForFrame:(_WKFrameHandle *)frame printInfo:(const WebKit::PrintInfo&)printInfo firstPage:(uint32_t)firstPage computedTotalScaleFactor:(double&)totalScaleFactor
2193 if ([self _isDisplayingPDF])
2194 return CGPDFDocumentGetNumberOfPages([(WKPDFView *)_customContentView pdfDocument]);
2196 _pageIsPrintingToPDF = YES;
2197 Vector<WebCore::IntRect> pageRects;
2198 uint64_t frameID = frame ? frame._frameID : _page->mainFrame()->frameID();
2199 if (!_page->sendSync(Messages::WebPage::ComputePagesForPrintingAndStartDrawingToPDF(frameID, printInfo, firstPage), Messages::WebPage::ComputePagesForPrintingAndStartDrawingToPDF::Reply(pageRects, totalScaleFactor)))
2201 return pageRects.size();
2204 - (void)_endPrinting
2206 _pageIsPrintingToPDF = NO;
2207 _printedDocument = nullptr;
2208 _page->send(Messages::WebPage::EndPrinting());
2211 // FIXME: milliseconds::max() overflows when converted to nanoseconds, causing condition_variable::wait_for() to believe
2212 // a timeout occurred on any spurious wakeup. Use nanoseconds::max() (converted to ms) to avoid this. We should perhaps
2213 // change waitForAndDispatchImmediately() to take nanoseconds to avoid this issue.
2214 static constexpr std::chrono::milliseconds didFinishLoadingTimeout = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::nanoseconds::max());
2216 - (CGPDFDocumentRef)_printedDocument
2218 if ([self _isDisplayingPDF]) {
2219 ASSERT(!_pageIsPrintingToPDF);
2220 return [(WKPDFView *)_customContentView pdfDocument];
2223 if (_pageIsPrintingToPDF) {
2224 if (!_page->process().connection()->waitForAndDispatchImmediately<Messages::WebPageProxy::DidFinishDrawingPagesToPDF>(_page->pageID(), didFinishLoadingTimeout)) {
2225 ASSERT_NOT_REACHED();
2228 ASSERT(!_pageIsPrintingToPDF);
2230 return _printedDocument.get();
2233 - (void)_setPrintedDocument:(CGPDFDocumentRef)printedDocument
2235 if (!_pageIsPrintingToPDF)
2237 ASSERT(![self _isDisplayingPDF]);
2238 _printedDocument = printedDocument;
2239 _pageIsPrintingToPDF = NO;
2245 #endif // WK_API_ENABLED