[iOS WK2] Hit-testing fails when specifying a large top content inset
authorwenson_hsieh@apple.com <wenson_hsieh@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Thu, 15 Mar 2018 20:50:03 +0000 (20:50 +0000)
committerwenson_hsieh@apple.com <wenson_hsieh@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Thu, 15 Mar 2018 20:50:03 +0000 (20:50 +0000)
https://bugs.webkit.org/show_bug.cgi?id=183648
<rdar://problem/38421894>

Reviewed by Tim Horton.

Source/WebKit:

Currently, in the process of computing unobscured content rect in the UI process on iOS, we subtract away parts
of the view that are obscured by insets (e.g. MobileSafari's chrome). The helper method -[WKWebView
_computeContentInset] is intended to compute these obscuring insets around the view, but it takes scroll view
insets into account. This means that if WKWebView's inner scroll view has content insets, we'll end up shrinking
the unobscured content rect as if the insetted region obscures the viewport; this causes visible content on the
page to be uninteractible, since WKWebView erroneously thinks it's obscured.

To address this, we rename _computeContentInset to _computeObscuredInset, and make it _not_ affected by the
scroll view's content insets. From code inspection and testing, all but one of the former call sites of
_computeContentInset really need the obscured inset instead (see below). The one exception, -[WKWebView
_adjustedContentOffset:], takes a scroll position from the page and maps it to a content offset in the inner
UIScrollView (see below for more details).

Tests:  ScrollViewInsetTests.InnerHeightWithLargeTopContentInset
        ScrollViewInsetTests.InnerHeightWithLargeBottomContentInset
        ScrollViewInsetTests.RestoreInitialContentOffsetAfterCrash
        ScrollViewInsetTests.RestoreInitialContentOffsetAfterNavigation

* UIProcess/API/Cocoa/WKWebView.mm:
(-[WKWebView _setHasCustomContentView:loadedMIMEType:]):
(-[WKWebView _initialContentOffsetForScrollView]):

See -_contentOffsetAdjustedForObscuredInset: below.

(-[WKWebView _contentOffsetAdjustedForObscuredInset:]):

Formerly -_adjustedContentOffset:. -_contentOffsetAdjustedForObscuredInset: no longer takes scroll view content
inset into account, and only cares about insets that obscure the view. This means that the scroll position
(0, 0) in the document now maps to the content offset in the inner UIScrollView, such that the top of the page
is aligned with the top of the viewport.

However, many call sites of -_adjustedContentOffset: were intended to compute the initial, top-left-most content
offset in the scroll view to scroll to when resetting the web view (i.e., they pass in CGPointZero for the
scroll position). An example of this is the scroll position to jump to after web content process termination, or
the scroll position after main frame navigation. In these cases, we actually want to jump to the top of the
scroll view, so we do want to use the version of the computed content insets that accounts for scroll view
insets.

Since these cases are limited to finding the top-left-most scroll position, we pull this out into a separate
helper method (-_initialContentOffsetForScrollView) and replace calls to
`-[self _adjustedContentOffset:CGPointZero]` with this instead.

(-[WKWebView _computedObscuredInset]):

A version of -_computeContentInset that doesn't care about scroll view insets. Used whereever we need to account
for obscured insets rather than the combination of content insets and unobscured insets (e.g.
-_initialContentOffsetForScrollView).

(-[WKWebView _processDidExit]):
(-[WKWebView _didCommitLayerTree:]):
(-[WKWebView _dynamicViewportUpdateChangedTargetToScale:position:nextValidLayerTreeTransactionID:]):
(-[WKWebView _scrollToContentScrollPosition:scrollOrigin:]):
(-[WKWebView scrollViewWillEndDragging:withVelocity:targetContentOffset:]):
(-[WKWebView _updateVisibleContentRects]):
(-[WKWebView _navigationGestureDidBegin]):

In all these places where we inset the view bounds to compute the unobscured region of the viewport, it doesn't
make sense to additionally inset by the scroll view's content insets, since (1) the scroll view's content insets
don't obscure the viewport, and (2) it's perfectly valid for the inner scroll view to have arbitrarily large
content insets.

(-[WKWebView _adjustedContentOffset:]): Deleted.

Renamed to -_contentOffsetAdjustedForObscuredInset:.

* UIProcess/API/Cocoa/WKWebViewInternal.h:
* UIProcess/ios/WKPDFView.mm:
(-[WKPDFView _offsetForPageNumberIndicator]):

Similar to -_scrollToFragment: (see below).

(-[WKPDFView _scrollToFragment:]):

This helper figures out which content offset to scroll to, given the y-origin of a page in a PDF document. If
insets are added to the scroll view, we end up scrolling to the wrong content offset since we'll add the height
of the top content inset (imagine that the top content inset is enormous — then we'll scroll an amount equal to
the top content inset _past_ the point where the y-origin of the page is at the top of the viewport).

Tools:

Adds four new API tests to verify that adding top or bottom content insets to the WKWebView's scroll view does
not cause the DOMWindow's innerHeight to shrink. Currently, doing so would cause the innerHeight to be reported
as (viewHeight - inset.top) or (viewHeight - inset.bottom).

See WebKit ChangeLog for more details.

* TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
* TestWebKitAPI/Tests/ios/ScrollViewInsetTests.mm: Added.
(TestWebKitAPI::TEST):

git-svn-id: https://svn.webkit.org/repository/webkit/trunk@229641 268f45cc-cd09-0410-ab3c-d52691b4dbfc

Source/WebKit/ChangeLog
Source/WebKit/UIProcess/API/Cocoa/WKWebView.mm
Source/WebKit/UIProcess/API/Cocoa/WKWebViewInternal.h
Source/WebKit/UIProcess/ios/WKPDFView.mm
Tools/ChangeLog
Tools/TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj
Tools/TestWebKitAPI/Tests/ios/ScrollViewInsetTests.mm [new file with mode: 0644]

index 03cda2b..42dd920 100644 (file)
@@ -1,3 +1,89 @@
+2018-03-15  Wenson Hsieh  <wenson_hsieh@apple.com>
+
+        [iOS WK2] Hit-testing fails when specifying a large top content inset
+        https://bugs.webkit.org/show_bug.cgi?id=183648
+        <rdar://problem/38421894>
+
+        Reviewed by Tim Horton.
+
+        Currently, in the process of computing unobscured content rect in the UI process on iOS, we subtract away parts
+        of the view that are obscured by insets (e.g. MobileSafari's chrome). The helper method -[WKWebView
+        _computeContentInset] is intended to compute these obscuring insets around the view, but it takes scroll view
+        insets into account. This means that if WKWebView's inner scroll view has content insets, we'll end up shrinking
+        the unobscured content rect as if the insetted region obscures the viewport; this causes visible content on the
+        page to be uninteractible, since WKWebView erroneously thinks it's obscured.
+
+        To address this, we rename _computeContentInset to _computeObscuredInset, and make it _not_ affected by the
+        scroll view's content insets. From code inspection and testing, all but one of the former call sites of
+        _computeContentInset really need the obscured inset instead (see below). The one exception, -[WKWebView
+        _adjustedContentOffset:], takes a scroll position from the page and maps it to a content offset in the inner
+        UIScrollView (see below for more details).
+
+        Tests:  ScrollViewInsetTests.InnerHeightWithLargeTopContentInset
+                ScrollViewInsetTests.InnerHeightWithLargeBottomContentInset
+                ScrollViewInsetTests.RestoreInitialContentOffsetAfterCrash
+                ScrollViewInsetTests.RestoreInitialContentOffsetAfterNavigation
+
+        * UIProcess/API/Cocoa/WKWebView.mm:
+        (-[WKWebView _setHasCustomContentView:loadedMIMEType:]):
+        (-[WKWebView _initialContentOffsetForScrollView]):
+
+        See -_contentOffsetAdjustedForObscuredInset: below.
+
+        (-[WKWebView _contentOffsetAdjustedForObscuredInset:]):
+
+        Formerly -_adjustedContentOffset:. -_contentOffsetAdjustedForObscuredInset: no longer takes scroll view content
+        inset into account, and only cares about insets that obscure the view. This means that the scroll position
+        (0, 0) in the document now maps to the content offset in the inner UIScrollView, such that the top of the page
+        is aligned with the top of the viewport.
+
+        However, many call sites of -_adjustedContentOffset: were intended to compute the initial, top-left-most content
+        offset in the scroll view to scroll to when resetting the web view (i.e., they pass in CGPointZero for the
+        scroll position). An example of this is the scroll position to jump to after web content process termination, or
+        the scroll position after main frame navigation. In these cases, we actually want to jump to the top of the
+        scroll view, so we do want to use the version of the computed content insets that accounts for scroll view
+        insets.
+
+        Since these cases are limited to finding the top-left-most scroll position, we pull this out into a separate
+        helper method (-_initialContentOffsetForScrollView) and replace calls to
+        `-[self _adjustedContentOffset:CGPointZero]` with this instead.
+
+        (-[WKWebView _computedObscuredInset]):
+
+        A version of -_computeContentInset that doesn't care about scroll view insets. Used whereever we need to account
+        for obscured insets rather than the combination of content insets and unobscured insets (e.g.
+        -_initialContentOffsetForScrollView).
+
+        (-[WKWebView _processDidExit]):
+        (-[WKWebView _didCommitLayerTree:]):
+        (-[WKWebView _dynamicViewportUpdateChangedTargetToScale:position:nextValidLayerTreeTransactionID:]):
+        (-[WKWebView _scrollToContentScrollPosition:scrollOrigin:]):
+        (-[WKWebView scrollViewWillEndDragging:withVelocity:targetContentOffset:]):
+        (-[WKWebView _updateVisibleContentRects]):
+        (-[WKWebView _navigationGestureDidBegin]):
+
+        In all these places where we inset the view bounds to compute the unobscured region of the viewport, it doesn't
+        make sense to additionally inset by the scroll view's content insets, since (1) the scroll view's content insets
+        don't obscure the viewport, and (2) it's perfectly valid for the inner scroll view to have arbitrarily large
+        content insets.
+
+        (-[WKWebView _adjustedContentOffset:]): Deleted.
+
+        Renamed to -_contentOffsetAdjustedForObscuredInset:.
+
+        * UIProcess/API/Cocoa/WKWebViewInternal.h:
+        * UIProcess/ios/WKPDFView.mm:
+        (-[WKPDFView _offsetForPageNumberIndicator]):
+
+        Similar to -_scrollToFragment: (see below).
+
+        (-[WKPDFView _scrollToFragment:]):
+
+        This helper figures out which content offset to scroll to, given the y-origin of a page in a PDF document. If
+        insets are added to the scroll view, we end up scrolling to the wrong content offset since we'll add the height
+        of the top content inset (imagine that the top content inset is enormous — then we'll scroll an amount equal to
+        the top content inset _past_ the point where the y-origin of the page is at the top of the viewport).
+
 2018-03-15  Brent Fulgham  <bfulgham@apple.com>
 
         [macOS] Correct sandbox violations during Flash playback under ToT WebKit
index 2ade614..8c1148b 100644 (file)
@@ -1461,7 +1461,7 @@ static CGSize roundScrollViewContentSize(const WebKit::WebPageProxy& page, CGSiz
         [_customContentView web_setFixedOverlayView:_customContentFixedOverlayView.get()];
 
         _scrollViewBackgroundColor = WebCore::Color();
-        [_scrollView setContentOffset:[self _adjustedContentOffset:CGPointZero]];
+        [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
 
         [self _setAvoidsUnsafeArea:NO];
     } else if (_customContentView) {
@@ -1581,10 +1581,16 @@ static WebCore::Color scrollViewBackgroundColor(WKWebView *webView)
 #endif
 }
 
-- (CGPoint)_adjustedContentOffset:(CGPoint)point
+- (CGPoint)_initialContentOffsetForScrollView
+{
+    auto combinedUnobscuredAndScrollViewInset = [self _computedContentInset];
+    return CGPointMake(-combinedUnobscuredAndScrollViewInset.left, -combinedUnobscuredAndScrollViewInset.top);
+}
+
+- (CGPoint)_contentOffsetAdjustedForObscuredInset:(CGPoint)point
 {
     CGPoint result = point;
-    UIEdgeInsets contentInset = [self _computedContentInset];
+    UIEdgeInsets contentInset = [self _computedObscuredInset];
 
     result.x -= contentInset.left;
     result.y -= contentInset.top;
@@ -1599,6 +1605,19 @@ static WebCore::Color scrollViewBackgroundColor(WKWebView *webView)
     return _obscuredInsetEdgesAffectedBySafeArea;
 }
 
+- (UIEdgeInsets)_computedObscuredInset
+{
+    if (_haveSetObscuredInsets)
+        return _obscuredInsets;
+
+#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
+    if (self._safeAreaShouldAffectObscuredInsets)
+        return UIEdgeInsetsAdd(UIEdgeInsetsZero, self._scrollViewSystemContentInset, self._effectiveObscuredInsetEdgesAffectedBySafeArea);
+#endif
+
+    return UIEdgeInsetsZero;
+}
+
 - (UIEdgeInsets)_computedContentInset
 {
     if (_haveSetObscuredInsets)
@@ -1641,7 +1660,7 @@ static WebCore::Color scrollViewBackgroundColor(WKWebView *webView)
     }
     [_contentView setFrame:self.bounds];
     [_scrollView setBackgroundColor:[UIColor whiteColor]];
-    [_scrollView setContentOffset:[self _adjustedContentOffset:CGPointZero]];
+    [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
     [_scrollView setZoomScale:1];
 
     _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
@@ -1778,7 +1797,7 @@ static inline bool areEssentiallyEqualAsFloat(float a, float b)
 
     if (_needsResetViewStateAfterCommitLoadForMainFrame && layerTreeTransaction.transactionID() >= _firstPaintAfterCommitLoadTransactionID) {
         _needsResetViewStateAfterCommitLoadForMainFrame = NO;
-        [_scrollView setContentOffset:[self _adjustedContentOffset:CGPointZero]];
+        [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
         if (_observedRenderingProgressEvents & _WKRenderingProgressEventFirstPaint)
             _navigationState->didFirstPaint();
 
@@ -1847,7 +1866,7 @@ static inline bool areEssentiallyEqualAsFloat(float a, float b)
         double scale = newScale / currentTargetScale;
         _resizeAnimationTransformAdjustments = CATransform3DMakeScale(scale, scale, 1);
 
-        CGPoint newContentOffset = [self _adjustedContentOffset:CGPointMake(newScrollPosition.x * newScale, newScrollPosition.y * newScale)];
+        CGPoint newContentOffset = [self _contentOffsetAdjustedForObscuredInset:CGPointMake(newScrollPosition.x * newScale, newScrollPosition.y * newScale)];
         CGPoint currentContentOffset = [_scrollView contentOffset];
 
         _resizeAnimationTransformAdjustments.m41 = (currentContentOffset.x - newContentOffset.x) / animatingScaleTarget;
@@ -2006,7 +2025,7 @@ static WebCore::FloatPoint constrainContentOffset(WebCore::FloatPoint contentOff
     CGFloat zoomScale = contentZoomScale(self);
     scaledOffset.scale(zoomScale);
 
-    CGPoint contentOffsetInScrollViewCoordinates = [self _adjustedContentOffset:scaledOffset];
+    CGPoint contentOffsetInScrollViewCoordinates = [self _contentOffsetAdjustedForObscuredInset:scaledOffset];
     contentOffsetInScrollViewCoordinates = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
 
     [_scrollView _stopScrollingAndZoomingAnimations];
@@ -2373,17 +2392,15 @@ static WebCore::FloatPoint constrainContentOffset(WebCore::FloatPoint contentOff
         // FIXME: Here, I'm finding the maximum horizontal/vertical scroll offsets. There's probably a better way to do this.
         CGSize maxScrollOffsets = CGSizeMake(scrollView.contentSize.width - scrollView.bounds.size.width, scrollView.contentSize.height - scrollView.bounds.size.height);
 
-        CGRect fullViewRect = self.bounds;
-
-        UIEdgeInsets contentInset;
+        UIEdgeInsets obscuredInset;
 
         id<WKUIDelegatePrivate> uiDelegatePrivate = static_cast<id <WKUIDelegatePrivate>>([self UIDelegate]);
         if ([uiDelegatePrivate respondsToSelector:@selector(_webView:finalObscuredInsetsForScrollView:withVelocity:targetContentOffset:)])
-            contentInset = [uiDelegatePrivate _webView:self finalObscuredInsetsForScrollView:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
+            obscuredInset = [uiDelegatePrivate _webView:self finalObscuredInsetsForScrollView:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
         else
-            contentInset = [self _computedContentInset];
+            obscuredInset = [self _computedObscuredInset];
 
-        CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, contentInset);
+        CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInset);
 
         coordinator->adjustTargetContentOffsetForSnapping(maxScrollOffsets, velocity, unobscuredRect.origin.y, targetContentOffset);
     }
@@ -2750,16 +2767,15 @@ static bool scrollViewCanScroll(UIScrollView *scrollView)
         || _currentlyAdjustingScrollViewInsetsForKeyboard)
         return;
 
-    CGRect fullViewRect = self.bounds;
     CGRect visibleRectInContentCoordinates = [self _visibleContentRect];
 
-    UIEdgeInsets computedContentInsetUnadjustedForKeyboard = [self _computedContentInset];
+    UIEdgeInsets computedContentInsetUnadjustedForKeyboard = [self _computedObscuredInset];
     if (!_haveSetObscuredInsets)
         computedContentInsetUnadjustedForKeyboard.bottom -= _totalScrollViewBottomInsetAdjustmentForKeyboard;
 
     CGFloat scaleFactor = contentZoomScale(self);
 
-    CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, computedContentInsetUnadjustedForKeyboard);
+    CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, computedContentInsetUnadjustedForKeyboard);
     CGRect unobscuredRectInContentCoordinates = _frozenUnobscuredContentRect ? _frozenUnobscuredContentRect.value() : [self convertRect:unobscuredRect toView:_contentView.get()];
     unobscuredRectInContentCoordinates = CGRectIntersection(unobscuredRectInContentCoordinates, [self _contentBoundsExtendedForRubberbandingWithScale:scaleFactor]);
 
@@ -2767,8 +2783,6 @@ static bool scrollViewCanScroll(UIScrollView *scrollView)
     if (inStableState) {
         WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
         if (coordinator && coordinator->hasActiveSnapPoint()) {
-            CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, computedContentInsetUnadjustedForKeyboard);
-
             CGPoint currentPoint = [_scrollView contentOffset];
             CGPoint activePoint = coordinator->nearestActiveContentInsetAdjustedSnapPoint(unobscuredRect.origin.y, currentPoint);
 
@@ -2948,7 +2962,7 @@ static bool scrollViewCanScroll(UIScrollView *scrollView)
     // an offset and animation on it, which results in computing incorrect rectangles. Work around by using
     // frozen rects during swipes.
     CGRect fullViewRect = self.bounds;
-    CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, [self _computedContentInset]);
+    CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, [self _computedObscuredInset]);
 
     _frozenVisibleContentRect = [self convertRect:fullViewRect toView:_contentView.get()];
     _frozenUnobscuredContentRect = [self convertRect:unobscuredRect toView:_contentView.get()];
index 05d462b..035f3f0 100644 (file)
@@ -145,7 +145,7 @@ struct PrintInfo;
 @property (nonatomic, readonly) WKSelectionGranularity _selectionGranularity;
 
 @property (nonatomic, readonly) BOOL _allowsDoubleTapGestures;
-@property (nonatomic, readonly) UIEdgeInsets _computedContentInset;
+@property (nonatomic, readonly) UIEdgeInsets _computedObscuredInset;
 @property (nonatomic, readonly) UIEdgeInsets _computedUnobscuredSafeAreaInset;
 #endif
 
index f689877..df2132f 100644 (file)
@@ -308,7 +308,7 @@ static void detachViewForPage(PDFPageInfo& page)
 
 - (CGPoint)_offsetForPageNumberIndicator
 {
-    UIEdgeInsets insets = UIEdgeInsetsAdd(_webView._computedUnobscuredSafeAreaInset, _webView._computedContentInset, UIRectEdgeAll);
+    UIEdgeInsets insets = UIEdgeInsetsAdd(_webView._computedUnobscuredSafeAreaInset, _webView._computedObscuredInset, UIRectEdgeAll);
     return CGPointMake(insets.left, insets.top + _overlaidAccessoryViewsInset.height);
 }
 
@@ -366,7 +366,7 @@ static void detachViewForPage(PDFPageInfo& page)
     [self _resetZoomAnimated:NO];
 
     // Ensure that the page margin is visible below the content inset.
-    const CGFloat verticalOffset = _pages[pageIndex].frame.origin.y - _webView._computedContentInset.top - pdfPageMargin;
+    const CGFloat verticalOffset = _pages[pageIndex].frame.origin.y - _webView._computedObscuredInset.top - pdfPageMargin;
     [_scrollView setContentOffset:CGPointMake(_scrollView.contentOffset.x, verticalOffset) animated:NO];
 
     _isPerformingSameDocumentNavigation = NO;
index 4feed11..ef3f234 100644 (file)
@@ -1,3 +1,21 @@
+2018-03-15  Wenson Hsieh  <wenson_hsieh@apple.com>
+
+        [iOS WK2] Hit-testing fails when specifying a large top content inset
+        https://bugs.webkit.org/show_bug.cgi?id=183648
+        <rdar://problem/38421894>
+
+        Reviewed by Tim Horton.
+
+        Adds four new API tests to verify that adding top or bottom content insets to the WKWebView's scroll view does
+        not cause the DOMWindow's innerHeight to shrink. Currently, doing so would cause the innerHeight to be reported
+        as (viewHeight - inset.top) or (viewHeight - inset.bottom).
+
+        See WebKit ChangeLog for more details.
+
+        * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
+        * TestWebKitAPI/Tests/ios/ScrollViewInsetTests.mm: Added.
+        (TestWebKitAPI::TEST):
+
 2018-03-15  Aakash Jain  <aakash_jain@apple.com>
 
         Add unit-test for NetworkTransaction URLError handling
index 36c6db1..b394885 100644 (file)
                F4B825D81EF4DBFB006E417F /* compressed-files.zip in Copy Resources */ = {isa = PBXBuildFile; fileRef = F4B825D61EF4DBD4006E417F /* compressed-files.zip */; };
                F4BFA68E1E4AD08000154298 /* DragAndDropPasteboardTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = F4BFA68C1E4AD08000154298 /* DragAndDropPasteboardTests.mm */; };
                F4C2AB221DD6D95E00E06D5B /* enormous-video-with-sound.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = F4C2AB211DD6D94100E06D5B /* enormous-video-with-sound.html */; };
+               F4C8797F2059D8D3009CD00B /* ScrollViewInsetTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = F4C8797E2059D8D3009CD00B /* ScrollViewInsetTests.mm */; };
                F4D4F3B61E4E2BCB00BB2767 /* DataInteractionSimulator.mm in Sources */ = {isa = PBXBuildFile; fileRef = F4D4F3B41E4E2BCB00BB2767 /* DataInteractionSimulator.mm */; };
                F4D4F3B91E4E36E400BB2767 /* DataInteractionTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = F4D4F3B71E4E36E400BB2767 /* DataInteractionTests.mm */; };
                F4D5E4E81F0C5D38008C1A49 /* dragstart-clear-selection.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = F4D5E4E71F0C5D27008C1A49 /* dragstart-clear-selection.html */; };
                        dstPath = TestWebKitAPI.resources;
                        dstSubfolderSpec = 7;
                        files = (
-                               CD758A6F20572EA00071834A /* video-with-paused-audio-and-playing-muted.html in Copy Resources */,
                                1A9E52C913E65EF4006917F5 /* 18-characters.html in Copy Resources */,
                                379028B914FAC24C007E6B43 /* acceptsFirstMouse.html in Copy Resources */,
                                1C2B81871C8925A000A5529F /* Ahem.ttf in Copy Resources */,
                                CDC8E4951BC6F10800594FEC /* video-with-audio.mp4 in Copy Resources */,
                                CD321B041E3A85FA00EB21C8 /* video-with-muted-audio-and-webaudio.html in Copy Resources */,
                                CDB4115A1E0B00DB00EAD352 /* video-with-muted-audio.html in Copy Resources */,
+                               CD758A6F20572EA00071834A /* video-with-paused-audio-and-playing-muted.html in Copy Resources */,
                                CDC8E4961BC6F10800594FEC /* video-without-audio.html in Copy Resources */,
                                CDC8E4971BC6F10800594FEC /* video-without-audio.mp4 in Copy Resources */,
                                1C2B81861C89259D00A5529F /* webfont.html in Copy Resources */,
                F4B825D61EF4DBD4006E417F /* compressed-files.zip */ = {isa = PBXFileReference; lastKnownFileType = archive.zip; path = "compressed-files.zip"; sourceTree = "<group>"; };
                F4BFA68C1E4AD08000154298 /* DragAndDropPasteboardTests.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = DragAndDropPasteboardTests.mm; sourceTree = "<group>"; };
                F4C2AB211DD6D94100E06D5B /* enormous-video-with-sound.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = "enormous-video-with-sound.html"; sourceTree = "<group>"; };
+               F4C8797E2059D8D3009CD00B /* ScrollViewInsetTests.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = ScrollViewInsetTests.mm; sourceTree = "<group>"; };
                F4D4F3B41E4E2BCB00BB2767 /* DataInteractionSimulator.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = DataInteractionSimulator.mm; sourceTree = "<group>"; };
                F4D4F3B51E4E2BCB00BB2767 /* DataInteractionSimulator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DataInteractionSimulator.h; sourceTree = "<group>"; };
                F4D4F3B71E4E36E400BB2767 /* DataInteractionTests.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = DataInteractionTests.mm; sourceTree = "<group>"; };
                                F45B63FC1F19D410009D38B9 /* ActionSheetTests.mm */,
                                F4D4F3B71E4E36E400BB2767 /* DataInteractionTests.mm */,
                                7560917719259C59009EF06E /* MemoryCacheAddImageToCacheIOS.mm */,
+                               F4C8797E2059D8D3009CD00B /* ScrollViewInsetTests.mm */,
                                F46849BD1EEF58E400B937FE /* UIPasteboardTests.mm */,
                                2E1B881E2040EE5300FFF6A9 /* ViewportSizingTests.mm */,
                                514958BD1F7427AC00E87BAD /* WKWebViewAutofillTests.mm */,
                                CDC8E4891BC5C96200594FEC /* video-with-audio.html */,
                                CDC8E48A1BC5C96200594FEC /* video-with-audio.mp4 */,
                                CD321B031E3A84B700EB21C8 /* video-with-muted-audio-and-webaudio.html */,
-                               CD758A6E20572D540071834A /* video-with-paused-audio-and-playing-muted.html */,
                                CDB411591E09DA8E00EAD352 /* video-with-muted-audio.html */,
+                               CD758A6E20572D540071834A /* video-with-paused-audio-and-playing-muted.html */,
                                CDC8E48B1BC5C96200594FEC /* video-without-audio.html */,
                                CDC8E48C1BC5C96200594FEC /* video-without-audio.mp4 */,
                        );
                                A180C0FA1EE67DF000468F47 /* RunOpenPanel.mm in Sources */,
                                CDCFA7AA1E45183200C2433D /* SampleMap.cpp in Sources */,
                                7CCE7F121A411AE600447C4C /* ScrollPinningBehaviors.cpp in Sources */,
+                               F4C8797F2059D8D3009CD00B /* ScrollViewInsetTests.mm in Sources */,
                                CE06DF9B1E1851F200E570C9 /* SecurityOrigin.cpp in Sources */,
                                5769C50B1D9B0002000847FB /* SerializedCryptoKeyWrap.mm in Sources */,
                                51EB12941FDF052500A5A1BD /* ServiceWorkerBasic.mm in Sources */,
diff --git a/Tools/TestWebKitAPI/Tests/ios/ScrollViewInsetTests.mm b/Tools/TestWebKitAPI/Tests/ios/ScrollViewInsetTests.mm
new file mode 100644 (file)
index 0000000..cba21bb
--- /dev/null
@@ -0,0 +1,130 @@
+/*
+ * Copyright (C) 2018 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#if WK_API_ENABLED && PLATFORM(IOS)
+
+#import "PlatformUtilities.h"
+#import "TestNavigationDelegate.h"
+#import "TestWKWebView.h"
+#import "UIKitSPI.h"
+#import <WebKit/WKWebViewPrivate.h>
+
+namespace TestWebKitAPI {
+
+static const CGFloat viewHeight = 500;
+static NSString *veryTallDocumentMarkup = @"<meta name='viewport' content='width=device-width, initial-scale=1'><body style='width: 100%; height: 5000px'>";
+
+TEST(ScrollViewInsetTests, InnerHeightWithLargeTopContentInset)
+{
+    auto webView = adoptNS([[TestWKWebView alloc] initWithFrame:CGRectMake(0, 0, 320, viewHeight)]);
+    [webView scrollView].contentInset = UIEdgeInsetsMake(400, 0, 0, 0);
+    [webView synchronouslyLoadHTMLString:veryTallDocumentMarkup];
+    [webView stringByEvaluatingJavaScript:@"scrollTo(0, 10)"];
+    [webView waitForNextPresentationUpdate];
+    EXPECT_EQ(viewHeight, [[webView objectByEvaluatingJavaScript:@"innerHeight"] floatValue]);
+    EXPECT_EQ(10, [[webView objectByEvaluatingJavaScript:@"pageYOffset"] floatValue]);
+
+    [webView stringByEvaluatingJavaScript:@"scrollBy(0, -10)"];
+    [webView waitForNextPresentationUpdate];
+    EXPECT_EQ(viewHeight, [[webView objectByEvaluatingJavaScript:@"innerHeight"] floatValue]);
+    EXPECT_EQ(0, [[webView objectByEvaluatingJavaScript:@"pageYOffset"] floatValue]);
+
+    [webView stringByEvaluatingJavaScript:@"scrollBy(0, 20)"];
+    [webView waitForNextPresentationUpdate];
+    EXPECT_EQ(viewHeight, [[webView objectByEvaluatingJavaScript:@"innerHeight"] floatValue]);
+    EXPECT_EQ(20, [[webView objectByEvaluatingJavaScript:@"pageYOffset"] floatValue]);
+}
+
+TEST(ScrollViewInsetTests, InnerHeightWithLargeBottomContentInset)
+{
+    auto webView = adoptNS([[TestWKWebView alloc] initWithFrame:CGRectMake(0, 0, 320, viewHeight)]);
+    [webView scrollView].contentInset = UIEdgeInsetsMake(0, 0, 400, 0);
+    [webView synchronouslyLoadHTMLString:veryTallDocumentMarkup];
+    [webView stringByEvaluatingJavaScript:@"scrollTo(0, 10)"];
+    [webView waitForNextPresentationUpdate];
+    EXPECT_EQ(viewHeight, [[webView objectByEvaluatingJavaScript:@"innerHeight"] floatValue]);
+    EXPECT_EQ(10, [[webView objectByEvaluatingJavaScript:@"pageYOffset"] floatValue]);
+
+    [webView stringByEvaluatingJavaScript:@"scrollBy(0, -10)"];
+    [webView waitForNextPresentationUpdate];
+    EXPECT_EQ(viewHeight, [[webView objectByEvaluatingJavaScript:@"innerHeight"] floatValue]);
+    EXPECT_EQ(0, [[webView objectByEvaluatingJavaScript:@"pageYOffset"] floatValue]);
+
+    [webView stringByEvaluatingJavaScript:@"scrollBy(0, 20)"];
+    [webView waitForNextPresentationUpdate];
+    EXPECT_EQ(viewHeight, [[webView objectByEvaluatingJavaScript:@"innerHeight"] floatValue]);
+    EXPECT_EQ(20, [[webView objectByEvaluatingJavaScript:@"pageYOffset"] floatValue]);
+}
+
+TEST(ScrollViewInsetTests, RestoreInitialContentOffsetAfterNavigation)
+{
+    auto webView = adoptNS([[TestWKWebView alloc] initWithFrame:CGRectMake(0, 0, 320, viewHeight)]);
+    [webView scrollView].contentInset = UIEdgeInsetsMake(400, 0, 0, 0);
+    [webView synchronouslyLoadHTMLString:veryTallDocumentMarkup];
+    [webView stringByEvaluatingJavaScript:@"scrollTo(0, 1000)"];
+    [webView waitForNextPresentationUpdate];
+
+    CGPoint contentOffsetAfterScrolling = [webView scrollView].contentOffset;
+    EXPECT_EQ(0, contentOffsetAfterScrolling.x);
+    EXPECT_EQ(1000, contentOffsetAfterScrolling.y);
+
+    [webView synchronouslyLoadHTMLString:@"<body bgcolor='red'>"];
+    [webView waitForNextPresentationUpdate];
+
+    CGPoint contentOffsetAfterNavigation = [webView scrollView].contentOffset;
+    EXPECT_EQ(0, contentOffsetAfterNavigation.x);
+    EXPECT_EQ(-400, contentOffsetAfterNavigation.y);
+}
+
+TEST(ScrollViewInsetTests, RestoreInitialContentOffsetAfterCrash)
+{
+    auto delegate = adoptNS([[TestNavigationDelegate alloc] init]);
+    auto webView = adoptNS([[TestWKWebView alloc] initWithFrame:CGRectMake(0, 0, 320, viewHeight)]);
+    [webView scrollView].contentInset = UIEdgeInsetsMake(400, 0, 0, 0);
+    [webView synchronouslyLoadHTMLString:veryTallDocumentMarkup];
+    [webView setNavigationDelegate:delegate.get()];
+
+    CGPoint initialContentOffset = [webView scrollView].contentOffset;
+    __block CGPoint contentOffsetAfterCrash = CGPointZero;
+    __block bool done = false;
+    [delegate setWebContentProcessDidTerminate:^(WKWebView *webView) {
+        contentOffsetAfterCrash = webView.scrollView.contentOffset;
+        done = true;
+    }];
+
+    [webView _killWebContentProcessAndResetState];
+    Util::run(&done);
+
+    EXPECT_EQ(initialContentOffset.x, contentOffsetAfterCrash.x);
+    EXPECT_EQ(initialContentOffset.y, contentOffsetAfterCrash.y);
+    EXPECT_EQ(0, initialContentOffset.x);
+    EXPECT_EQ(-400, initialContentOffset.y);
+}
+
+} // namespace TestWebKitAPI
+
+#endif // WK_API_ENABLED && PLATFORM(IOS)