2 * Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
3 * 1999 Lars Knoll <knoll@kde.org>
4 * 1999 Antti Koivisto <koivisto@kde.org>
5 * 2000 Dirk Mueller <mueller@kde.org>
6 * Copyright (C) 2004-2008, 2013-2015 Apple Inc. All rights reserved.
7 * (C) 2006 Graham Dennis (graham.dennis@gmail.com)
8 * (C) 2006 Alexey Proskuryakov (ap@nypop.com)
9 * Copyright (C) 2009 Google Inc. All rights reserved.
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Library General Public
13 * License as published by the Free Software Foundation; either
14 * version 2 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Library General Public License for more details.
21 * You should have received a copy of the GNU Library General Public License
22 * along with this library; see the file COPYING.LIB. If not, write to
23 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 * Boston, MA 02110-1301, USA.
28 #include "FrameView.h"
30 #include "AXObjectCache.h"
31 #include "AnimationController.h"
32 #include "BackForwardController.h"
33 #include "CachedImage.h"
34 #include "CachedResourceLoader.h"
36 #include "ChromeClient.h"
37 #include "DOMWindow.h"
38 #include "DebugPageOverlays.h"
39 #include "DocumentMarkerController.h"
40 #include "EventHandler.h"
41 #include "FloatRect.h"
42 #include "FocusController.h"
43 #include "FontLoader.h"
44 #include "FrameLoader.h"
45 #include "FrameLoaderClient.h"
46 #include "FrameSelection.h"
47 #include "FrameTree.h"
48 #include "GraphicsContext.h"
49 #include "HTMLBodyElement.h"
50 #include "HTMLDocument.h"
51 #include "HTMLFrameElement.h"
52 #include "HTMLFrameSetElement.h"
53 #include "HTMLNames.h"
54 #include "HTMLPlugInImageElement.h"
55 #include "ImageDocument.h"
56 #include "InspectorClient.h"
57 #include "InspectorController.h"
58 #include "InspectorInstrumentation.h"
60 #include "MainFrame.h"
61 #include "MemoryCache.h"
62 #include "MemoryPressureHandler.h"
63 #include "OverflowEvent.h"
64 #include "PageOverlayController.h"
65 #include "ProgressTracker.h"
66 #include "RenderEmbeddedObject.h"
67 #include "RenderFullScreen.h"
68 #include "RenderIFrame.h"
69 #include "RenderInline.h"
70 #include "RenderLayer.h"
71 #include "RenderLayerBacking.h"
72 #include "RenderLayerCompositor.h"
73 #include "RenderSVGRoot.h"
74 #include "RenderScrollbar.h"
75 #include "RenderScrollbarPart.h"
76 #include "RenderStyle.h"
77 #include "RenderText.h"
78 #include "RenderTheme.h"
79 #include "RenderView.h"
80 #include "RenderWidget.h"
81 #include "SVGDocument.h"
82 #include "SVGSVGElement.h"
83 #include "ScriptedAnimationController.h"
84 #include "ScrollAnimator.h"
85 #include "ScrollingCoordinator.h"
87 #include "StyleResolver.h"
88 #include "TextResourceDecoder.h"
89 #include "TextStream.h"
90 #include "TiledBacking.h"
91 #include "WheelEventTestTrigger.h"
93 #include <wtf/CurrentTime.h>
95 #include <wtf/TemporaryChange.h>
97 #if USE(COORDINATED_GRAPHICS)
98 #include "TiledBackingStore.h"
101 #if ENABLE(TEXT_AUTOSIZING)
102 #include "TextAutosizer.h"
105 #if ENABLE(CSS_SCROLL_SNAP)
106 #include "AxisScrollSnapOffsets.h"
110 #include "DocumentLoader.h"
111 #include "LegacyTileCache.h"
116 using namespace HTMLNames;
118 double FrameView::sCurrentPaintTimeStamp = 0.0;
120 // The maximum number of updateEmbeddedObjects iterations that should be done before returning.
121 static const unsigned maxUpdateEmbeddedObjectsIterations = 2;
123 static RenderLayer::UpdateLayerPositionsFlags updateLayerPositionFlags(RenderLayer* layer, bool isRelayoutingSubtree, bool didFullRepaint)
125 RenderLayer::UpdateLayerPositionsFlags flags = RenderLayer::defaultFlags;
126 if (didFullRepaint) {
127 flags &= ~RenderLayer::CheckForRepaint;
128 flags |= RenderLayer::NeedsFullRepaintInBacking;
130 if (isRelayoutingSubtree && layer->enclosingPaginationLayer(RenderLayer::IncludeCompositedPaginatedLayers))
131 flags |= RenderLayer::UpdatePagination;
135 Pagination::Mode paginationModeForRenderStyle(const RenderStyle& style)
137 EOverflow overflow = style.overflowY();
138 if (overflow != OPAGEDX && overflow != OPAGEDY)
139 return Pagination::Unpaginated;
141 bool isHorizontalWritingMode = style.isHorizontalWritingMode();
142 TextDirection textDirection = style.direction();
143 WritingMode writingMode = style.writingMode();
145 // paged-x always corresponds to LeftToRightPaginated or RightToLeftPaginated. If the WritingMode
146 // is horizontal, then we use TextDirection to choose between those options. If the WritingMode
147 // is vertical, then the direction of the verticality dictates the choice.
148 if (overflow == OPAGEDX) {
149 if ((isHorizontalWritingMode && textDirection == LTR) || writingMode == LeftToRightWritingMode)
150 return Pagination::LeftToRightPaginated;
151 return Pagination::RightToLeftPaginated;
154 // paged-y always corresponds to TopToBottomPaginated or BottomToTopPaginated. If the WritingMode
155 // is horizontal, then the direction of the horizontality dictates the choice. If the WritingMode
156 // is vertical, then we use TextDirection to choose between those options.
157 if (writingMode == TopToBottomWritingMode || (!isHorizontalWritingMode && textDirection == RTL))
158 return Pagination::TopToBottomPaginated;
159 return Pagination::BottomToTopPaginated;
162 FrameView::FrameView(Frame& frame)
164 , m_canHaveScrollbars(true)
165 , m_layoutTimer(*this, &FrameView::layoutTimerFired)
166 , m_layoutRoot(nullptr)
167 , m_layoutPhase(OutsideLayout)
168 , m_inSynchronousPostLayout(false)
169 , m_postLayoutTasksTimer(*this, &FrameView::postLayoutTimerFired)
170 , m_updateEmbeddedObjectsTimer(*this, &FrameView::updateEmbeddedObjectsTimerFired)
171 , m_isTransparent(false)
172 , m_baseBackgroundColor(Color::white)
173 , m_mediaType("screen")
174 , m_overflowStatusDirty(true)
175 , m_viewportRenderer(nullptr)
176 , m_wasScrolledByUser(false)
177 , m_inProgrammaticScroll(false)
178 , m_safeToPropagateScrollToParent(true)
179 , m_delayedScrollEventTimer(*this, &FrameView::delayedScrollEventTimerFired)
180 , m_isTrackingRepaints(false)
181 , m_shouldUpdateWhileOffscreen(true)
182 , m_exposedRect(FloatRect::infiniteRect())
183 , m_deferSetNeedsLayoutCount(0)
184 , m_setNeedsLayoutWasDeferred(false)
185 , m_speculativeTilingEnabled(false)
186 , m_speculativeTilingEnableTimer(*this, &FrameView::speculativeTilingEnableTimerFired)
188 , m_useCustomFixedPositionLayoutRect(false)
189 , m_useCustomSizeForResizeEvent(false)
190 , m_horizontalVelocity(0)
191 , m_verticalVelocity(0)
192 , m_scaleChangeRate(0)
193 , m_lastVelocityUpdateTime(0)
195 , m_hasOverrideViewportSize(false)
196 , m_shouldAutoSize(false)
197 , m_inAutoSize(false)
198 , m_didRunAutosize(false)
199 , m_autoSizeFixedMinimumHeight(0)
202 , m_milestonesPendingPaint(0)
203 , m_visualUpdatesAllowedByClient(true)
204 , m_hasFlippedBlockRenderers(false)
205 , m_scrollPinningBehavior(DoNotPin)
209 #if ENABLE(RUBBER_BANDING)
210 ScrollElasticity verticalElasticity = ScrollElasticityNone;
211 ScrollElasticity horizontalElasticity = ScrollElasticityNone;
212 if (m_frame->isMainFrame()) {
213 verticalElasticity = m_frame->page() ? m_frame->page()->verticalScrollElasticity() : ScrollElasticityAllowed;
214 horizontalElasticity = m_frame->page() ? m_frame->page()->horizontalScrollElasticity() : ScrollElasticityAllowed;
215 } else if (m_frame->settings().rubberBandingForSubScrollableRegionsEnabled()) {
216 verticalElasticity = ScrollElasticityAutomatic;
217 horizontalElasticity = ScrollElasticityAutomatic;
220 ScrollableArea::setVerticalScrollElasticity(verticalElasticity);
221 ScrollableArea::setHorizontalScrollElasticity(horizontalElasticity);
225 Ref<FrameView> FrameView::create(Frame& frame)
227 Ref<FrameView> view = adoptRef(*new FrameView(frame));
232 Ref<FrameView> FrameView::create(Frame& frame, const IntSize& initialSize)
234 Ref<FrameView> view = adoptRef(*new FrameView(frame));
235 view->Widget::setFrameRect(IntRect(view->location(), initialSize));
240 FrameView::~FrameView()
242 if (m_postLayoutTasksTimer.isActive())
243 m_postLayoutTasksTimer.stop();
245 removeFromAXObjectCache();
248 // Custom scrollbars should already be destroyed at this point
249 ASSERT(!horizontalScrollbar() || !horizontalScrollbar()->isCustomScrollbar());
250 ASSERT(!verticalScrollbar() || !verticalScrollbar()->isCustomScrollbar());
252 setHasHorizontalScrollbar(false); // Remove native scrollbars now before we lose the connection to the HostWindow.
253 setHasVerticalScrollbar(false);
255 ASSERT(!m_scrollCorner);
257 ASSERT(frame().view() != this || !frame().contentRenderer());
260 void FrameView::reset()
262 m_cannotBlitToWindow = false;
263 m_isOverlapped = false;
264 m_contentIsOpaque = false;
265 m_layoutTimer.stop();
266 m_layoutRoot = nullptr;
267 m_delayedLayout = false;
268 m_needsFullRepaint = true;
269 m_layoutSchedulingEnabled = true;
270 m_layoutPhase = OutsideLayout;
271 m_inSynchronousPostLayout = false;
273 m_nestedLayoutCount = 0;
274 m_postLayoutTasksTimer.stop();
275 m_updateEmbeddedObjectsTimer.stop();
276 m_firstLayout = true;
277 m_firstLayoutCallbackPending = false;
278 m_wasScrolledByUser = false;
279 m_safeToPropagateScrollToParent = true;
280 m_delayedScrollEventTimer.stop();
281 m_lastViewportSize = IntSize();
282 m_lastZoomFactor = 1.0f;
283 m_isTrackingRepaints = false;
284 m_trackedRepaintRects.clear();
286 m_paintBehavior = PaintBehaviorNormal;
287 m_isPainting = false;
288 m_visuallyNonEmptyCharacterCount = 0;
289 m_visuallyNonEmptyPixelCount = 0;
290 m_isVisuallyNonEmpty = false;
291 m_firstVisuallyNonEmptyLayoutCallbackPending = true;
292 m_maintainScrollPositionAnchor = nullptr;
293 m_throttledTimers.clear();
296 void FrameView::removeFromAXObjectCache()
298 if (AXObjectCache* cache = axObjectCache()) {
299 if (HTMLFrameOwnerElement* owner = frame().ownerElement())
300 cache->childrenChanged(owner->renderer());
305 void FrameView::resetScrollbars()
307 // Reset the document's scrollbars back to our defaults before we yield the floor.
308 m_firstLayout = true;
309 setScrollbarsSuppressed(true);
310 if (m_canHaveScrollbars)
311 setScrollbarModes(ScrollbarAuto, ScrollbarAuto);
313 setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff);
314 setScrollbarsSuppressed(false);
317 void FrameView::resetScrollbarsAndClearContentsSize()
321 setScrollbarsSuppressed(true);
322 setContentsSize(IntSize());
323 setScrollbarsSuppressed(false);
326 void FrameView::init()
330 m_margins = LayoutSize(-1, -1); // undefined
331 m_size = LayoutSize();
333 // Propagate the marginwidth/height and scrolling modes to the view.
334 Element* ownerElement = frame().ownerElement();
335 if (is<HTMLFrameElementBase>(ownerElement)) {
336 HTMLFrameElementBase& frameElement = downcast<HTMLFrameElementBase>(*ownerElement);
337 if (frameElement.scrollingMode() == ScrollbarAlwaysOff)
338 setCanHaveScrollbars(false);
339 LayoutUnit marginWidth = frameElement.marginWidth();
340 LayoutUnit marginHeight = frameElement.marginHeight();
341 if (marginWidth != -1)
342 setMarginWidth(marginWidth);
343 if (marginHeight != -1)
344 setMarginHeight(marginHeight);
347 Page* page = frame().page();
348 if (page && page->chrome().client().shouldPaintEntireContents())
349 setPaintsEntireContents(true);
352 void FrameView::prepareForDetach()
354 detachCustomScrollbars();
355 // When the view is no longer associated with a frame, it needs to be removed from the ax object cache
356 // right now, otherwise it won't be able to reach the topDocument()'s axObject cache later.
357 removeFromAXObjectCache();
359 if (frame().page()) {
360 if (ScrollingCoordinator* scrollingCoordinator = frame().page()->scrollingCoordinator())
361 scrollingCoordinator->willDestroyScrollableArea(*this);
365 void FrameView::detachCustomScrollbars()
367 Scrollbar* horizontalBar = horizontalScrollbar();
368 if (horizontalBar && horizontalBar->isCustomScrollbar())
369 setHasHorizontalScrollbar(false);
371 Scrollbar* verticalBar = verticalScrollbar();
372 if (verticalBar && verticalBar->isCustomScrollbar())
373 setHasVerticalScrollbar(false);
375 m_scrollCorner = nullptr;
378 void FrameView::recalculateScrollbarOverlayStyle()
380 ScrollbarOverlayStyle oldOverlayStyle = scrollbarOverlayStyle();
381 ScrollbarOverlayStyle overlayStyle = ScrollbarOverlayStyleDefault;
383 Color backgroundColor = documentBackgroundColor();
384 if (backgroundColor.isValid()) {
385 // Reduce the background color from RGB to a lightness value
386 // and determine which scrollbar style to use based on a lightness
388 double hue, saturation, lightness;
389 backgroundColor.getHSL(hue, saturation, lightness);
390 if (lightness <= .5 && backgroundColor.alpha() > 0)
391 overlayStyle = ScrollbarOverlayStyleLight;
394 if (oldOverlayStyle != overlayStyle)
395 setScrollbarOverlayStyle(overlayStyle);
398 void FrameView::clear()
400 setCanBlitOnScroll(true);
404 setScrollbarsSuppressed(true);
407 // To avoid flashes of white, disable tile updates immediately when view is cleared at the beginning of a page load.
408 // Tiling will be re-enabled from UIKit via [WAKWindow setTilingMode:] when we have content to draw.
409 if (LegacyTileCache* tileCache = legacyTileCache())
410 tileCache->setTilingMode(LegacyTileCache::Disabled);
414 bool FrameView::didFirstLayout() const
416 return !m_firstLayout;
419 void FrameView::invalidateRect(const IntRect& rect)
422 if (HostWindow* window = hostWindow())
423 window->invalidateContentsAndRootView(rect);
427 RenderWidget* renderer = frame().ownerRenderer();
431 IntRect repaintRect = rect;
432 repaintRect.move(renderer->borderLeft() + renderer->paddingLeft(),
433 renderer->borderTop() + renderer->paddingTop());
434 renderer->repaintRectangle(repaintRect);
437 void FrameView::setFrameRect(const IntRect& newRect)
439 IntRect oldRect = frameRect();
440 if (newRect == oldRect)
443 #if ENABLE(TEXT_AUTOSIZING)
444 // Autosized font sizes depend on the width of the viewing area.
445 if (newRect.width() != oldRect.width()) {
446 if (frame().isMainFrame() && page->settings().textAutosizingEnabled()) {
447 for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext())
448 frame().document()->textAutosizer()->recalculateMultipliers();
453 ScrollView::setFrameRect(newRect);
455 updateScrollableAreaSet();
457 if (RenderView* renderView = this->renderView()) {
458 if (renderView->usesCompositing())
459 renderView->compositor().frameViewDidChangeSize();
462 if (frame().isMainFrame())
463 frame().mainFrame().pageOverlayController().didChangeViewSize();
465 viewportContentsChanged();
468 #if ENABLE(REQUEST_ANIMATION_FRAME)
469 bool FrameView::scheduleAnimation()
471 if (HostWindow* window = hostWindow()) {
472 window->scheduleAnimation();
479 void FrameView::setMarginWidth(LayoutUnit w)
481 // make it update the rendering area when set
482 m_margins.setWidth(w);
485 void FrameView::setMarginHeight(LayoutUnit h)
487 // make it update the rendering area when set
488 m_margins.setHeight(h);
491 bool FrameView::frameFlatteningEnabled() const
493 return frame().settings().frameFlatteningEnabled();
496 bool FrameView::isFrameFlatteningValidForThisFrame() const
498 if (!frameFlatteningEnabled())
501 HTMLFrameOwnerElement* owner = frame().ownerElement();
505 // Frame flattening is valid only for <frame> and <iframe>.
506 return owner->hasTagName(frameTag) || owner->hasTagName(iframeTag);
509 bool FrameView::avoidScrollbarCreation() const
511 // with frame flattening no subframe can have scrollbars
512 // but we also cannot turn scrollbars off as we determine
513 // our flattening policy using that.
514 return isFrameFlatteningValidForThisFrame();
517 void FrameView::setCanHaveScrollbars(bool canHaveScrollbars)
519 m_canHaveScrollbars = canHaveScrollbars;
520 ScrollView::setCanHaveScrollbars(canHaveScrollbars);
523 void FrameView::updateCanHaveScrollbars()
527 scrollbarModes(hMode, vMode);
528 if (hMode == ScrollbarAlwaysOff && vMode == ScrollbarAlwaysOff)
529 setCanHaveScrollbars(false);
531 setCanHaveScrollbars(true);
534 PassRefPtr<Scrollbar> FrameView::createScrollbar(ScrollbarOrientation orientation)
536 if (!frame().settings().allowCustomScrollbarInMainFrame() && frame().isMainFrame())
537 return ScrollView::createScrollbar(orientation);
539 // FIXME: We need to update the scrollbar dynamically as documents change (or as doc elements and bodies get discovered that have custom styles).
540 Document* doc = frame().document();
542 // Try the <body> element first as a scrollbar source.
543 HTMLElement* body = doc ? doc->bodyOrFrameset() : nullptr;
544 if (body && body->renderer() && body->renderer()->style().hasPseudoStyle(SCROLLBAR))
545 return RenderScrollbar::createCustomScrollbar(*this, orientation, body);
547 // If the <body> didn't have a custom style, then the root element might.
548 Element* docElement = doc ? doc->documentElement() : nullptr;
549 if (docElement && docElement->renderer() && docElement->renderer()->style().hasPseudoStyle(SCROLLBAR))
550 return RenderScrollbar::createCustomScrollbar(*this, orientation, docElement);
552 // If we have an owning iframe/frame element, then it can set the custom scrollbar also.
553 RenderWidget* frameRenderer = frame().ownerRenderer();
554 if (frameRenderer && frameRenderer->style().hasPseudoStyle(SCROLLBAR))
555 return RenderScrollbar::createCustomScrollbar(*this, orientation, nullptr, &frame());
557 // Nobody set a custom style, so we just use a native scrollbar.
558 return ScrollView::createScrollbar(orientation);
561 void FrameView::setContentsSize(const IntSize& size)
563 if (size == contentsSize())
566 m_deferSetNeedsLayoutCount++;
568 ScrollView::setContentsSize(size);
571 Page* page = frame().page();
575 updateScrollableAreaSet();
577 page->chrome().contentsSizeChanged(&frame(), size); // Notify only.
579 if (frame().isMainFrame())
580 frame().mainFrame().pageOverlayController().didChangeDocumentSize();
582 ASSERT(m_deferSetNeedsLayoutCount);
583 m_deferSetNeedsLayoutCount--;
585 if (!m_deferSetNeedsLayoutCount)
586 m_setNeedsLayoutWasDeferred = false; // FIXME: Find a way to make the deferred layout actually happen.
589 void FrameView::adjustViewSize()
591 RenderView* renderView = this->renderView();
595 ASSERT(frame().view() == this);
597 const IntRect rect = renderView->documentRect();
598 const IntSize& size = rect.size();
599 ScrollView::setScrollOrigin(IntPoint(-rect.x(), -rect.y()), !frame().document()->printing(), size == contentsSize());
601 setContentsSize(size);
604 void FrameView::applyOverflowToViewport(RenderElement* renderer, ScrollbarMode& hMode, ScrollbarMode& vMode)
606 // Handle the overflow:hidden/scroll case for the body/html elements. WinIE treats
607 // overflow:hidden and overflow:scroll on <body> as applying to the document's
608 // scrollbars. The CSS2.1 draft states that HTML UAs should use the <html> or <body> element and XML/XHTML UAs should
609 // use the root element.
611 // To combat the inability to scroll on a page with overflow:hidden on the root when scaled, disregard hidden when
612 // there is a frameScaleFactor that is greater than one on the main frame. Also disregard hidden if there is a
615 bool overrideHidden = frame().isMainFrame() && ((frame().frameScaleFactor() > 1) || headerHeight() || footerHeight());
617 EOverflow overflowX = renderer->style().overflowX();
618 EOverflow overflowY = renderer->style().overflowY();
620 if (is<RenderSVGRoot>(*renderer)) {
621 // FIXME: evaluate if we can allow overflow for these cases too.
622 // Overflow is always hidden when stand-alone SVG documents are embedded.
623 if (downcast<RenderSVGRoot>(*renderer).isEmbeddedThroughFrameContainingSVGDocument()) {
632 hMode = ScrollbarAuto;
634 hMode = ScrollbarAlwaysOff;
637 hMode = ScrollbarAlwaysOn;
640 hMode = ScrollbarAuto;
643 // Don't set it at all.
650 vMode = ScrollbarAuto;
652 vMode = ScrollbarAlwaysOff;
655 vMode = ScrollbarAlwaysOn;
658 vMode = ScrollbarAuto;
661 // Don't set it at all. Values of OPAGEDX and OPAGEDY are handled by applyPaginationToViewPort().
665 m_viewportRenderer = renderer;
668 void FrameView::applyPaginationToViewport()
670 Document* document = frame().document();
671 auto documentElement = document->documentElement();
672 RenderElement* documentRenderer = documentElement ? documentElement->renderer() : nullptr;
673 RenderElement* documentOrBodyRenderer = documentRenderer;
674 auto* body = document->body();
675 if (body && body->renderer())
676 documentOrBodyRenderer = documentRenderer->style().overflowX() == OVISIBLE && is<HTMLHtmlElement>(*documentElement) ? body->renderer() : documentRenderer;
678 Pagination pagination;
680 if (!documentOrBodyRenderer) {
681 setPagination(pagination);
685 EOverflow overflowY = documentOrBodyRenderer->style().overflowY();
686 if (overflowY == OPAGEDX || overflowY == OPAGEDY) {
687 pagination.mode = WebCore::paginationModeForRenderStyle(documentOrBodyRenderer->style());
688 pagination.gap = static_cast<unsigned>(documentOrBodyRenderer->style().columnGap());
691 setPagination(pagination);
694 void FrameView::calculateScrollbarModesForLayout(ScrollbarMode& hMode, ScrollbarMode& vMode, ScrollbarModesCalculationStrategy strategy)
696 m_viewportRenderer = nullptr;
698 const HTMLFrameOwnerElement* owner = frame().ownerElement();
699 if (owner && (owner->scrollingMode() == ScrollbarAlwaysOff)) {
700 hMode = ScrollbarAlwaysOff;
701 vMode = ScrollbarAlwaysOff;
705 if (m_canHaveScrollbars || strategy == RulesFromWebContentOnly) {
706 hMode = ScrollbarAuto;
707 vMode = ScrollbarAuto;
709 hMode = ScrollbarAlwaysOff;
710 vMode = ScrollbarAlwaysOff;
714 Document* document = frame().document();
715 auto documentElement = document->documentElement();
716 RenderElement* rootRenderer = documentElement ? documentElement->renderer() : nullptr;
717 auto* body = document->bodyOrFrameset();
718 if (body && body->renderer()) {
719 if (is<HTMLFrameSetElement>(*body) && !frameFlatteningEnabled()) {
720 vMode = ScrollbarAlwaysOff;
721 hMode = ScrollbarAlwaysOff;
722 } else if (is<HTMLBodyElement>(*body)) {
723 // It's sufficient to just check the X overflow,
724 // since it's illegal to have visible in only one direction.
725 RenderElement* o = rootRenderer->style().overflowX() == OVISIBLE && is<HTMLHtmlElement>(*document->documentElement()) ? body->renderer() : rootRenderer;
726 applyOverflowToViewport(o, hMode, vMode);
728 } else if (rootRenderer)
729 applyOverflowToViewport(rootRenderer, hMode, vMode);
733 void FrameView::willRecalcStyle()
735 RenderView* renderView = this->renderView();
739 renderView->compositor().willRecalcStyle();
742 void FrameView::updateCompositingLayersAfterStyleChange()
744 RenderView* renderView = this->renderView();
748 // If we expect to update compositing after an incipient layout, don't do so here.
749 if (inPreLayoutStyleUpdate() || layoutPending() || renderView->needsLayout())
752 renderView->compositor().didRecalcStyleWithNoPendingLayout();
755 void FrameView::updateCompositingLayersAfterLayout()
757 RenderView* renderView = this->renderView();
761 // This call will make sure the cached hasAcceleratedCompositing is updated from the pref
762 renderView->compositor().cacheAcceleratedCompositingFlags();
763 renderView->compositor().updateCompositingLayers(CompositingUpdateAfterLayout);
766 void FrameView::clearBackingStores()
768 RenderView* renderView = this->renderView();
772 RenderLayerCompositor& compositor = renderView->compositor();
773 ASSERT(compositor.inCompositingMode());
774 compositor.enableCompositingMode(false);
775 compositor.clearBackingForAllLayers();
778 void FrameView::restoreBackingStores()
780 RenderView* renderView = this->renderView();
784 RenderLayerCompositor& compositor = renderView->compositor();
785 compositor.enableCompositingMode(true);
786 compositor.updateCompositingLayers(CompositingUpdateAfterLayout);
789 GraphicsLayer* FrameView::layerForScrolling() const
791 RenderView* renderView = this->renderView();
794 return renderView->compositor().scrollLayer();
797 GraphicsLayer* FrameView::layerForHorizontalScrollbar() const
799 RenderView* renderView = this->renderView();
802 return renderView->compositor().layerForHorizontalScrollbar();
805 GraphicsLayer* FrameView::layerForVerticalScrollbar() const
807 RenderView* renderView = this->renderView();
810 return renderView->compositor().layerForVerticalScrollbar();
813 GraphicsLayer* FrameView::layerForScrollCorner() const
815 RenderView* renderView = this->renderView();
818 return renderView->compositor().layerForScrollCorner();
821 TiledBacking* FrameView::tiledBacking() const
823 RenderView* renderView = this->renderView();
827 RenderLayerBacking* backing = renderView->layer()->backing();
831 return backing->graphicsLayer()->tiledBacking();
834 uint64_t FrameView::scrollLayerID() const
836 RenderView* renderView = this->renderView();
840 RenderLayerBacking* backing = renderView->layer()->backing();
844 return backing->scrollingNodeIDForRole(Scrolling);
847 ScrollableArea* FrameView::scrollableAreaForScrollLayerID(uint64_t nodeID) const
849 RenderView* renderView = this->renderView();
853 return renderView->compositor().scrollableAreaForScrollLayerID(nodeID);
856 #if ENABLE(RUBBER_BANDING)
857 GraphicsLayer* FrameView::layerForOverhangAreas() const
859 RenderView* renderView = this->renderView();
862 return renderView->compositor().layerForOverhangAreas();
865 GraphicsLayer* FrameView::setWantsLayerForTopOverHangArea(bool wantsLayer) const
867 RenderView* renderView = this->renderView();
871 return renderView->compositor().updateLayerForTopOverhangArea(wantsLayer);
874 GraphicsLayer* FrameView::setWantsLayerForBottomOverHangArea(bool wantsLayer) const
876 RenderView* renderView = this->renderView();
880 return renderView->compositor().updateLayerForBottomOverhangArea(wantsLayer);
883 #endif // ENABLE(RUBBER_BANDING)
885 #if ENABLE(CSS_SCROLL_SNAP)
886 void FrameView::updateSnapOffsets()
888 if (!frame().document())
891 // FIXME: Should we allow specifying snap points through <html> tags too?
892 HTMLElement* body = frame().document()->bodyOrFrameset();
893 if (!renderView() || !body || !body->renderer())
896 updateSnapOffsetsForScrollableArea(*this, *body, *renderView(), body->renderer()->style());
900 bool FrameView::flushCompositingStateForThisFrame(Frame* rootFrameForFlush)
902 RenderView* renderView = this->renderView();
904 return true; // We don't want to keep trying to update layers if we have no renderer.
906 ASSERT(frame().view() == this);
908 // If we sync compositing layers when a layout is pending, we may cause painting of compositing
909 // layer content to occur before layout has happened, which will cause paintContents() to bail.
914 if (LegacyTileCache* tileCache = legacyTileCache())
915 tileCache->doPendingRepaints();
918 renderView->compositor().flushPendingLayerChanges(rootFrameForFlush == m_frame.ptr());
923 void FrameView::setNeedsOneShotDrawingSynchronization()
925 if (Page* page = frame().page())
926 page->chrome().client().setNeedsOneShotDrawingSynchronization();
929 GraphicsLayer* FrameView::graphicsLayerForPlatformWidget(PlatformWidget platformWidget)
931 // To find the Widget that corresponds with platformWidget we have to do a linear
932 // search of our child widgets.
933 Widget* foundWidget = nullptr;
934 for (auto& widget : children()) {
935 if (widget->platformWidget() != platformWidget)
937 foundWidget = widget.get();
944 auto* renderWidget = RenderWidget::find(foundWidget);
948 RenderLayer* widgetLayer = renderWidget->layer();
949 if (!widgetLayer || !widgetLayer->isComposited())
952 return widgetLayer->backing()->parentForSublayers();
955 void FrameView::scheduleLayerFlushAllowingThrottling()
957 RenderView* view = this->renderView();
960 view->compositor().scheduleLayerFlush(true /* canThrottle */);
963 void FrameView::setHeaderHeight(int headerHeight)
966 ASSERT(frame().isMainFrame());
967 m_headerHeight = headerHeight;
969 if (RenderView* renderView = this->renderView())
970 renderView->setNeedsLayout();
973 void FrameView::setFooterHeight(int footerHeight)
976 ASSERT(frame().isMainFrame());
977 m_footerHeight = footerHeight;
979 if (RenderView* renderView = this->renderView())
980 renderView->setNeedsLayout();
983 float FrameView::topContentInset(TopContentInsetType contentInsetTypeToReturn) const
985 if (platformWidget() && contentInsetTypeToReturn == TopContentInsetType::WebCoreOrPlatformContentInset)
986 return platformTopContentInset();
988 if (!frame().isMainFrame())
991 Page* page = frame().page();
992 return page ? page->topContentInset() : 0;
995 void FrameView::topContentInsetDidChange(float newTopContentInset)
997 RenderView* renderView = this->renderView();
1001 if (platformWidget())
1002 platformSetTopContentInset(newTopContentInset);
1006 updateScrollbars(scrollOffset());
1007 if (renderView->usesCompositing())
1008 renderView->compositor().frameViewDidChangeSize();
1010 if (TiledBacking* tiledBacking = this->tiledBacking())
1011 tiledBacking->setTopContentInset(newTopContentInset);
1014 bool FrameView::hasCompositedContent() const
1016 if (RenderView* renderView = this->renderView())
1017 return renderView->compositor().inCompositingMode();
1021 // Sometimes (for plug-ins) we need to eagerly go into compositing mode.
1022 void FrameView::enterCompositingMode()
1024 if (RenderView* renderView = this->renderView()) {
1025 renderView->compositor().enableCompositingMode();
1027 renderView->compositor().scheduleCompositingLayerUpdate();
1031 bool FrameView::isEnclosedInCompositingLayer() const
1033 auto frameOwnerRenderer = frame().ownerRenderer();
1034 if (frameOwnerRenderer && frameOwnerRenderer->containerForRepaint())
1037 if (FrameView* parentView = parentFrameView())
1038 return parentView->isEnclosedInCompositingLayer();
1042 bool FrameView::flushCompositingStateIncludingSubframes()
1044 bool allFramesFlushed = flushCompositingStateForThisFrame(&frame());
1046 for (Frame* child = frame().tree().firstRenderedChild(); child; child = child->tree().traverseNextRendered(m_frame.ptr())) {
1049 bool flushed = child->view()->flushCompositingStateForThisFrame(&frame());
1050 allFramesFlushed &= flushed;
1052 return allFramesFlushed;
1055 bool FrameView::isSoftwareRenderable() const
1057 RenderView* renderView = this->renderView();
1058 return !renderView || !renderView->compositor().has3DContent();
1061 void FrameView::setIsInWindow(bool isInWindow)
1063 if (RenderView* renderView = this->renderView())
1064 renderView->setIsInWindow(isInWindow);
1067 RenderObject* FrameView::layoutRoot(bool onlyDuringLayout) const
1069 return onlyDuringLayout && layoutPending() ? nullptr : m_layoutRoot;
1072 inline void FrameView::forceLayoutParentViewIfNeeded()
1074 RenderWidget* ownerRenderer = frame().ownerRenderer();
1078 RenderBox* contentBox = embeddedContentBox();
1082 auto& svgRoot = downcast<RenderSVGRoot>(*contentBox);
1083 if (svgRoot.everHadLayout() && !svgRoot.needsLayout())
1086 // If the embedded SVG document appears the first time, the ownerRenderer has already finished
1087 // layout without knowing about the existence of the embedded SVG document, because RenderReplaced
1088 // embeddedContentBox() returns nullptr, as long as the embedded document isn't loaded yet. Before
1089 // bothering to lay out the SVG document, mark the ownerRenderer needing layout and ask its
1090 // FrameView for a layout. After that the RenderEmbeddedObject (ownerRenderer) carries the
1091 // correct size, which RenderSVGRoot::computeReplacedLogicalWidth/Height rely on, when laying
1092 // out for the first time, or when the RenderSVGRoot size has changed dynamically (eg. via <script>).
1093 Ref<FrameView> frameView(ownerRenderer->view().frameView());
1095 // Mark the owner renderer as needing layout.
1096 ownerRenderer->setNeedsLayoutAndPrefWidthsRecalc();
1098 // Synchronously enter layout, to layout the view containing the host object/embed/iframe.
1099 frameView->layout();
1102 void FrameView::layout(bool allowSubtree)
1107 // Protect the view from being deleted during layout (in recalcStyle).
1108 Ref<FrameView> protect(*this);
1110 // Many of the tasks performed during layout can cause this function to be re-entered,
1111 // so save the layout phase now and restore it on exit.
1112 TemporaryChange<LayoutPhase> layoutPhaseRestorer(m_layoutPhase, InPreLayout);
1114 // Every scroll that happens during layout is programmatic.
1115 TemporaryChange<bool> changeInProgrammaticScroll(m_inProgrammaticScroll, true);
1117 bool inChildFrameLayoutWithFrameFlattening = isInChildFrameWithFrameFlattening();
1119 if (inChildFrameLayoutWithFrameFlattening) {
1120 startLayoutAtMainFrameViewIfNeeded(allowSubtree);
1121 RenderElement* root = m_layoutRoot ? m_layoutRoot : frame().document()->renderView();
1122 if (!root || !root->needsLayout())
1127 if (updateFixedPositionLayoutRect())
1128 allowSubtree = false;
1131 m_layoutTimer.stop();
1132 m_delayedLayout = false;
1133 m_setNeedsLayoutWasDeferred = false;
1135 // we shouldn't enter layout() while painting
1136 ASSERT(!isPainting());
1140 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willLayout(frame());
1141 AnimationUpdateBlock animationUpdateBlock(&frame().animation());
1143 if (!allowSubtree && m_layoutRoot) {
1144 m_layoutRoot->markContainingBlocksForLayout(false);
1145 m_layoutRoot = nullptr;
1148 ASSERT(frame().view() == this);
1149 ASSERT(frame().document());
1151 Document& document = *frame().document();
1152 ASSERT(!document.inPageCache());
1155 RenderElement* root;
1158 TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
1160 if (!m_nestedLayoutCount && !m_inSynchronousPostLayout && m_postLayoutTasksTimer.isActive() && !inChildFrameLayoutWithFrameFlattening) {
1161 // This is a new top-level layout. If there are any remaining tasks from the previous
1162 // layout, finish them now.
1163 TemporaryChange<bool> inSynchronousPostLayoutChange(m_inSynchronousPostLayout, true);
1164 performPostLayoutTasks();
1167 m_layoutPhase = InPreLayoutStyleUpdate;
1169 // Viewport-dependent media queries may cause us to need completely different style information.
1170 StyleResolver* styleResolver = document.styleResolverIfExists();
1171 if (!styleResolver || styleResolver->hasMediaQueriesAffectedByViewportChange()) {
1172 document.styleResolverChanged(DeferRecalcStyle);
1173 // FIXME: This instrumentation event is not strictly accurate since cached media query results do not persist across StyleResolver rebuilds.
1174 InspectorInstrumentation::mediaQueryResultChanged(document);
1176 document.evaluateMediaQueryList();
1178 // If there is any pagination to apply, it will affect the RenderView's style, so we should
1179 // take care of that now.
1180 applyPaginationToViewport();
1182 // Always ensure our style info is up-to-date. This can happen in situations where
1183 // the layout beats any sort of style recalc update that needs to occur.
1184 document.updateStyleIfNeeded();
1185 m_layoutPhase = InPreLayout;
1187 subtree = m_layoutRoot;
1189 // If there is only one ref to this view left, then its going to be destroyed as soon as we exit,
1190 // so there's no point to continuing to layout
1194 root = subtree ? m_layoutRoot : document.renderView();
1196 // FIXME: Do we need to set m_size here?
1200 // Close block here so we can set up the font cache purge preventer, which we will still
1201 // want in scope even after we want m_layoutSchedulingEnabled to be restored again.
1202 // The next block sets m_layoutSchedulingEnabled back to false once again.
1207 ++m_nestedLayoutCount;
1210 TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
1212 if (!m_layoutRoot) {
1213 auto* body = document.bodyOrFrameset();
1214 if (body && body->renderer()) {
1215 if (is<HTMLFrameSetElement>(*body) && !frameFlatteningEnabled()) {
1216 body->renderer()->setChildNeedsLayout();
1217 } else if (is<HTMLBodyElement>(*body)) {
1218 if (!m_firstLayout && m_size.height() != layoutHeight() && body->renderer()->enclosingBox().stretchesToViewport())
1219 body->renderer()->setChildNeedsLayout();
1223 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1224 if (m_firstLayout && !frame().ownerElement())
1225 printf("Elapsed time before first layout: %lld\n", document.elapsedTime().count());
1229 autoSizeIfEnabled();
1231 m_needsFullRepaint = !subtree && (m_firstLayout || downcast<RenderView>(*root).printing());
1234 ScrollbarMode hMode;
1235 ScrollbarMode vMode;
1236 calculateScrollbarModesForLayout(hMode, vMode);
1238 if (m_firstLayout || (hMode != horizontalScrollbarMode() || vMode != verticalScrollbarMode())) {
1239 if (m_firstLayout) {
1240 setScrollbarsSuppressed(true);
1242 m_firstLayout = false;
1243 m_firstLayoutCallbackPending = true;
1244 m_lastViewportSize = sizeForResizeEvent();
1245 m_lastZoomFactor = root->style().zoom();
1247 // Set the initial vMode to AlwaysOn if we're auto.
1248 if (vMode == ScrollbarAuto)
1249 setVerticalScrollbarMode(ScrollbarAlwaysOn); // This causes a vertical scrollbar to appear.
1250 // Set the initial hMode to AlwaysOff if we're auto.
1251 if (hMode == ScrollbarAuto)
1252 setHorizontalScrollbarMode(ScrollbarAlwaysOff); // This causes a horizontal scrollbar to disappear.
1253 Page* page = frame().page();
1254 if (page && page->expectsWheelEventTriggers())
1255 scrollAnimator().setWheelEventTestTrigger(page->testTrigger());
1256 setScrollbarModes(hMode, vMode);
1257 setScrollbarsSuppressed(false, true);
1259 setScrollbarModes(hMode, vMode);
1262 LayoutSize oldSize = m_size;
1263 m_size = layoutSize();
1265 if (oldSize != m_size) {
1266 m_needsFullRepaint = true;
1267 if (!m_firstLayout) {
1268 RenderBox* rootRenderer = document.documentElement() ? document.documentElement()->renderBox() : nullptr;
1269 auto* body = document.bodyOrFrameset();
1270 RenderBox* bodyRenderer = rootRenderer && body ? body->renderBox() : nullptr;
1271 if (bodyRenderer && bodyRenderer->stretchesToViewport())
1272 bodyRenderer->setChildNeedsLayout();
1273 else if (rootRenderer && rootRenderer->stretchesToViewport())
1274 rootRenderer->setChildNeedsLayout();
1278 m_layoutPhase = InPreLayout;
1281 layer = root->enclosingLayer();
1283 bool disableLayoutState = false;
1285 disableLayoutState = root->view().shouldDisableLayoutStateForSubtree(root);
1286 root->view().pushLayoutState(*root);
1288 LayoutStateDisabler layoutStateDisabler(disableLayoutState ? &root->view() : nullptr);
1289 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(&root->view());
1291 ASSERT(m_layoutPhase == InPreLayout);
1292 m_layoutPhase = InLayout;
1294 forceLayoutParentViewIfNeeded();
1296 ASSERT(m_layoutPhase == InLayout);
1299 #if ENABLE(IOS_TEXT_AUTOSIZING)
1300 if (Page* page = frame().page()) {
1301 float minimumZoomFontSize = frame().settings().minimumZoomFontSize();
1302 float textAutosizingWidth = page->textAutosizingWidth();
1303 if (minimumZoomFontSize && textAutosizingWidth && !root->view().printing()) {
1304 root->adjustComputedFontSizesOnBlocks(minimumZoomFontSize, textAutosizingWidth);
1305 if (root->needsLayout())
1310 #if ENABLE(TEXT_AUTOSIZING)
1311 if (document.textAutosizer()->processSubtree(root) && root->needsLayout())
1315 ASSERT(m_layoutPhase == InLayout);
1318 root->view().popLayoutState(*root);
1320 m_layoutRoot = nullptr;
1322 // Close block here to end the scope of changeSchedulingEnabled and layoutStateDisabler.
1325 m_layoutPhase = InViewSizeAdjust;
1327 bool neededFullRepaint = m_needsFullRepaint;
1329 if (!subtree && !downcast<RenderView>(*root).printing())
1332 m_layoutPhase = InPostLayout;
1334 m_needsFullRepaint = neededFullRepaint;
1336 // Now update the positions of all layers.
1337 if (m_needsFullRepaint)
1338 root->view().repaintRootContents();
1340 root->view().releaseProtectedRenderWidgets();
1342 ASSERT(!root->needsLayout());
1344 layer->updateLayerPositionsAfterLayout(renderView()->layer(), updateLayerPositionFlags(layer, subtree, m_needsFullRepaint));
1346 updateCompositingLayersAfterLayout();
1348 m_layoutPhase = InPostLayerPositionsUpdatedAfterLayout;
1352 #if PLATFORM(COCOA) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(EFL)
1353 if (AXObjectCache* cache = root->document().existingAXObjectCache())
1354 cache->postNotification(root, AXObjectCache::AXLayoutComplete);
1357 #if ENABLE(DASHBOARD_SUPPORT)
1358 updateAnnotatedRegions();
1361 #if ENABLE(IOS_TOUCH_EVENTS)
1362 document.dirtyTouchEventRects();
1365 updateCanBlitOnScrollRecursively();
1367 handleDeferredScrollUpdateAfterContentSizeChange();
1369 if (document.hasListenerType(Document::OVERFLOWCHANGED_LISTENER))
1370 updateOverflowStatus(layoutWidth() < contentsWidth(), layoutHeight() < contentsHeight());
1372 if (!m_postLayoutTasksTimer.isActive()) {
1373 if (!m_inSynchronousPostLayout) {
1374 if (inChildFrameLayoutWithFrameFlattening)
1375 updateWidgetPositions();
1377 TemporaryChange<bool> inSynchronousPostLayoutChange(m_inSynchronousPostLayout, true);
1378 performPostLayoutTasks(); // Calls resumeScheduledEvents().
1382 if (!m_postLayoutTasksTimer.isActive() && (needsLayout() || m_inSynchronousPostLayout || inChildFrameLayoutWithFrameFlattening)) {
1383 // If we need layout or are already in a synchronous call to postLayoutTasks(),
1384 // defer widget updates and event dispatch until after we return. postLayoutTasks()
1385 // can make us need to update again, and we can get stuck in a nasty cycle unless
1386 // we call it through the timer here.
1387 m_postLayoutTasksTimer.startOneShot(0);
1393 InspectorInstrumentation::didLayout(cookie, root);
1394 DebugPageOverlays::didLayout(frame());
1396 --m_nestedLayoutCount;
1399 bool FrameView::shouldDeferScrollUpdateAfterContentSizeChange()
1401 return (m_layoutPhase < InPostLayout) && (m_layoutPhase != OutsideLayout);
1404 RenderBox* FrameView::embeddedContentBox() const
1406 RenderView* renderView = this->renderView();
1410 RenderObject* firstChild = renderView->firstChild();
1412 // Curently only embedded SVG documents participate in the size-negotiation logic.
1413 if (is<RenderSVGRoot>(firstChild))
1414 return downcast<RenderSVGRoot>(firstChild);
1419 void FrameView::addEmbeddedObjectToUpdate(RenderEmbeddedObject& embeddedObject)
1421 if (!m_embeddedObjectsToUpdate)
1422 m_embeddedObjectsToUpdate = std::make_unique<ListHashSet<RenderEmbeddedObject*>>();
1424 HTMLFrameOwnerElement& element = embeddedObject.frameOwnerElement();
1425 if (is<HTMLObjectElement>(element) || is<HTMLEmbedElement>(element)) {
1426 // Tell the DOM element that it needs a widget update.
1427 HTMLPlugInImageElement& pluginElement = downcast<HTMLPlugInImageElement>(element);
1428 if (!pluginElement.needsCheckForSizeChange())
1429 pluginElement.setNeedsWidgetUpdate(true);
1432 m_embeddedObjectsToUpdate->add(&embeddedObject);
1435 void FrameView::removeEmbeddedObjectToUpdate(RenderEmbeddedObject& embeddedObject)
1437 if (!m_embeddedObjectsToUpdate)
1440 m_embeddedObjectsToUpdate->remove(&embeddedObject);
1443 void FrameView::setMediaType(const String& mediaType)
1445 m_mediaType = mediaType;
1448 String FrameView::mediaType() const
1450 // See if we have an override type.
1451 String overrideType = frame().loader().client().overrideMediaType();
1452 InspectorInstrumentation::applyEmulatedMedia(frame(), overrideType);
1453 if (!overrideType.isNull())
1454 return overrideType;
1458 void FrameView::adjustMediaTypeForPrinting(bool printing)
1461 if (m_mediaTypeWhenNotPrinting.isNull())
1462 m_mediaTypeWhenNotPrinting = mediaType();
1463 setMediaType("print");
1465 if (!m_mediaTypeWhenNotPrinting.isNull())
1466 setMediaType(m_mediaTypeWhenNotPrinting);
1467 m_mediaTypeWhenNotPrinting = String();
1471 bool FrameView::useSlowRepaints(bool considerOverlap) const
1473 bool mustBeSlow = hasSlowRepaintObjects() || (platformWidget() && hasViewportConstrainedObjects());
1475 // FIXME: WidgetMac.mm makes the assumption that useSlowRepaints ==
1476 // m_contentIsOpaque, so don't take the fast path for composited layers
1477 // if they are a platform widget in order to get painting correctness
1478 // for transparent layers. See the comment in WidgetMac::paint.
1479 if (usesCompositedScrolling() && !platformWidget())
1482 bool isOverlapped = m_isOverlapped && considerOverlap;
1484 if (mustBeSlow || m_cannotBlitToWindow || isOverlapped || !m_contentIsOpaque)
1487 if (FrameView* parentView = parentFrameView())
1488 return parentView->useSlowRepaints(considerOverlap);
1493 bool FrameView::useSlowRepaintsIfNotOverlapped() const
1495 return useSlowRepaints(false);
1498 void FrameView::updateCanBlitOnScrollRecursively()
1500 for (auto* frame = m_frame.ptr(); frame; frame = frame->tree().traverseNext(m_frame.ptr())) {
1501 if (FrameView* view = frame->view())
1502 view->setCanBlitOnScroll(!view->useSlowRepaints());
1506 bool FrameView::usesCompositedScrolling() const
1508 RenderView* renderView = this->renderView();
1509 if (renderView && renderView->isComposited()) {
1510 GraphicsLayer* layer = renderView->layer()->backing()->graphicsLayer();
1511 if (layer && layer->drawsContent())
1518 bool FrameView::usesAsyncScrolling() const
1520 #if ENABLE(ASYNC_SCROLLING)
1521 if (Page* page = frame().page()) {
1522 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1523 return scrollingCoordinator->coordinatesScrollingForFrameView(*this);
1529 void FrameView::setCannotBlitToWindow()
1531 m_cannotBlitToWindow = true;
1532 updateCanBlitOnScrollRecursively();
1535 void FrameView::addSlowRepaintObject(RenderElement* o)
1537 bool hadSlowRepaintObjects = hasSlowRepaintObjects();
1539 if (!m_slowRepaintObjects)
1540 m_slowRepaintObjects = std::make_unique<HashSet<RenderElement*>>();
1542 m_slowRepaintObjects->add(o);
1544 if (!hadSlowRepaintObjects) {
1545 updateCanBlitOnScrollRecursively();
1547 if (Page* page = frame().page()) {
1548 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1549 scrollingCoordinator->frameViewHasSlowRepaintObjectsDidChange(*this);
1554 void FrameView::removeSlowRepaintObject(RenderElement* o)
1556 if (!m_slowRepaintObjects)
1559 m_slowRepaintObjects->remove(o);
1560 if (m_slowRepaintObjects->isEmpty()) {
1561 m_slowRepaintObjects = nullptr;
1562 updateCanBlitOnScrollRecursively();
1564 if (Page* page = frame().page()) {
1565 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1566 scrollingCoordinator->frameViewHasSlowRepaintObjectsDidChange(*this);
1571 void FrameView::addViewportConstrainedObject(RenderElement* object)
1573 if (!m_viewportConstrainedObjects)
1574 m_viewportConstrainedObjects = std::make_unique<ViewportConstrainedObjectSet>();
1576 if (!m_viewportConstrainedObjects->contains(object)) {
1577 m_viewportConstrainedObjects->add(object);
1578 if (platformWidget())
1579 updateCanBlitOnScrollRecursively();
1581 if (Page* page = frame().page()) {
1582 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1583 scrollingCoordinator->frameViewFixedObjectsDidChange(*this);
1588 void FrameView::removeViewportConstrainedObject(RenderElement* object)
1590 if (m_viewportConstrainedObjects && m_viewportConstrainedObjects->remove(object)) {
1591 if (Page* page = frame().page()) {
1592 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1593 scrollingCoordinator->frameViewFixedObjectsDidChange(*this);
1596 // FIXME: In addFixedObject() we only call this if there's a platform widget,
1597 // why isn't the same check being made here?
1598 updateCanBlitOnScrollRecursively();
1602 LayoutRect FrameView::viewportConstrainedVisibleContentRect() const
1605 if (useCustomFixedPositionLayoutRect())
1606 return customFixedPositionLayoutRect();
1608 LayoutRect viewportRect = visibleContentRect();
1610 viewportRect.setLocation(toLayoutPoint(scrollOffsetForFixedPosition()));
1611 return viewportRect;
1614 float FrameView::frameScaleFactor() const
1616 return frame().frameScaleFactor();
1619 LayoutSize FrameView::scrollOffsetForFixedPosition(const LayoutRect& visibleContentRect, const LayoutSize& totalContentsSize, const LayoutPoint& scrollPosition, const LayoutPoint& scrollOrigin, float frameScaleFactor, bool fixedElementsLayoutRelativeToFrame, ScrollBehaviorForFixedElements behaviorForFixed, int headerHeight, int footerHeight)
1621 LayoutPoint position;
1622 if (behaviorForFixed == StickToDocumentBounds)
1623 position = ScrollableArea::constrainScrollPositionForOverhang(visibleContentRect, totalContentsSize, scrollPosition, scrollOrigin, headerHeight, footerHeight);
1625 position = scrollPosition;
1626 position.setY(position.y() - headerHeight);
1629 LayoutSize maxSize = totalContentsSize - visibleContentRect.size();
1631 float dragFactorX = (fixedElementsLayoutRelativeToFrame || !maxSize.width()) ? 1 : (totalContentsSize.width() - visibleContentRect.width() * frameScaleFactor) / maxSize.width();
1632 float dragFactorY = (fixedElementsLayoutRelativeToFrame || !maxSize.height()) ? 1 : (totalContentsSize.height() - visibleContentRect.height() * frameScaleFactor) / maxSize.height();
1634 return LayoutSize(position.x() * dragFactorX / frameScaleFactor, position.y() * dragFactorY / frameScaleFactor);
1637 float FrameView::yPositionForInsetClipLayer(const FloatPoint& scrollPosition, float topContentInset)
1639 if (!topContentInset)
1642 // The insetClipLayer should not move for negative scroll values.
1643 float scrollY = std::max<float>(0, scrollPosition.y());
1645 if (scrollY >= topContentInset)
1648 return topContentInset - scrollY;
1651 float FrameView::yPositionForHeaderLayer(const FloatPoint& scrollPosition, float topContentInset)
1653 if (!topContentInset)
1656 float scrollY = std::max<float>(0, scrollPosition.y());
1658 if (scrollY >= topContentInset)
1659 return topContentInset;
1664 float FrameView::yPositionForRootContentLayer(const FloatPoint& scrollPosition, float topContentInset, float headerHeight)
1666 return yPositionForHeaderLayer(scrollPosition, topContentInset) + headerHeight;
1669 float FrameView::yPositionForFooterLayer(const FloatPoint& scrollPosition, float topContentInset, float totalContentsHeight, float footerHeight)
1671 return yPositionForHeaderLayer(scrollPosition, topContentInset) + totalContentsHeight - footerHeight;
1674 float FrameView::yPositionForRootContentLayer() const
1676 return yPositionForRootContentLayer(scrollPosition(), topContentInset(), headerHeight());
1680 LayoutRect FrameView::rectForViewportConstrainedObjects(const LayoutRect& visibleContentRect, const LayoutSize& totalContentsSize, float frameScaleFactor, bool fixedElementsLayoutRelativeToFrame, ScrollBehaviorForFixedElements scrollBehavior)
1682 if (fixedElementsLayoutRelativeToFrame)
1683 return visibleContentRect;
1685 if (totalContentsSize.isEmpty())
1686 return visibleContentRect;
1688 // We impose an lower limit on the size (so an upper limit on the scale) of
1689 // the rect used to position fixed objects so that they don't crowd into the
1690 // center of the screen at larger scales.
1691 const LayoutUnit maxContentWidthForZoomThreshold = LayoutUnit::fromPixel(1024);
1692 float zoomedOutScale = frameScaleFactor * visibleContentRect.width() / std::min(maxContentWidthForZoomThreshold, totalContentsSize.width());
1693 float constraintThresholdScale = 1.5 * zoomedOutScale;
1694 float maxPostionedObjectsRectScale = std::min(frameScaleFactor, constraintThresholdScale);
1696 LayoutRect viewportConstrainedObjectsRect = visibleContentRect;
1698 if (frameScaleFactor > constraintThresholdScale) {
1699 FloatRect contentRect(FloatPoint(), totalContentsSize);
1700 FloatRect viewportRect = visibleContentRect;
1702 // Scale the rect up from a point that is relative to its position in the viewport.
1703 FloatSize sizeDelta = contentRect.size() - viewportRect.size();
1705 FloatPoint scaleOrigin;
1706 scaleOrigin.setX(contentRect.x() + sizeDelta.width() > 0 ? contentRect.width() * (viewportRect.x() - contentRect.x()) / sizeDelta.width() : 0);
1707 scaleOrigin.setY(contentRect.y() + sizeDelta.height() > 0 ? contentRect.height() * (viewportRect.y() - contentRect.y()) / sizeDelta.height() : 0);
1709 AffineTransform rescaleTransform = AffineTransform::translation(scaleOrigin.x(), scaleOrigin.y());
1710 rescaleTransform.scale(frameScaleFactor / maxPostionedObjectsRectScale, frameScaleFactor / maxPostionedObjectsRectScale);
1711 rescaleTransform = CGAffineTransformTranslate(rescaleTransform, -scaleOrigin.x(), -scaleOrigin.y());
1713 viewportConstrainedObjectsRect = enclosingLayoutRect(rescaleTransform.mapRect(visibleContentRect));
1716 if (scrollBehavior == StickToDocumentBounds) {
1717 LayoutRect documentBounds(LayoutPoint(), totalContentsSize);
1718 viewportConstrainedObjectsRect.intersect(documentBounds);
1721 return viewportConstrainedObjectsRect;
1724 LayoutRect FrameView::viewportConstrainedObjectsRect() const
1726 return rectForViewportConstrainedObjects(visibleContentRect(), totalContentsSize(), frame().frameScaleFactor(), fixedElementsLayoutRelativeToFrame(), scrollBehaviorForFixedElements());
1730 IntPoint FrameView::minimumScrollPosition() const
1732 IntPoint minimumPosition(ScrollView::minimumScrollPosition());
1734 if (frame().isMainFrame() && m_scrollPinningBehavior == PinToBottom)
1735 minimumPosition.setY(maximumScrollPosition().y());
1737 return minimumPosition;
1740 IntPoint FrameView::maximumScrollPosition() const
1742 IntPoint maximumOffset(contentsWidth() - visibleWidth() - scrollOrigin().x(), totalContentsSize().height() - visibleHeight() - scrollOrigin().y());
1744 maximumOffset.clampNegativeToZero();
1746 if (frame().isMainFrame() && m_scrollPinningBehavior == PinToTop)
1747 maximumOffset.setY(minimumScrollPosition().y());
1749 return maximumOffset;
1752 void FrameView::delayedScrollEventTimerFired()
1757 void FrameView::viewportContentsChanged()
1759 if (!frame().view()) {
1760 // The frame is being destroyed.
1764 // When the viewport contents changes (scroll, resize, style recalc, layout, ...),
1765 // check if we should resume animated images or unthrottle DOM timers.
1766 applyRecursivelyWithVisibleRect([] (FrameView& frameView, const IntRect& visibleRect) {
1767 frameView.resumeVisibleImageAnimations(visibleRect);
1768 frameView.updateThrottledDOMTimersState(visibleRect);
1769 frameView.updateScriptedAnimationsThrottlingState(visibleRect);
1773 bool FrameView::fixedElementsLayoutRelativeToFrame() const
1775 return frame().settings().fixedElementsLayoutRelativeToFrame();
1778 IntPoint FrameView::lastKnownMousePosition() const
1780 return frame().eventHandler().lastKnownMousePosition();
1783 bool FrameView::isHandlingWheelEvent() const
1785 return frame().eventHandler().isHandlingWheelEvent();
1788 bool FrameView::shouldSetCursor() const
1790 Page* page = frame().page();
1791 return page && page->isVisible() && page->focusController().isActive();
1794 bool FrameView::scrollContentsFastPath(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect)
1796 if (!m_viewportConstrainedObjects || m_viewportConstrainedObjects->isEmpty()) {
1797 hostWindow()->scroll(scrollDelta, rectToScroll, clipRect);
1801 const bool isCompositedContentLayer = usesCompositedScrolling();
1803 // Get the rects of the fixed objects visible in the rectToScroll
1804 Region regionToUpdate;
1805 for (auto& renderer : *m_viewportConstrainedObjects) {
1806 if (!renderer->style().hasViewportConstrainedPosition())
1808 if (renderer->isComposited())
1811 // Fixed items should always have layers.
1812 ASSERT(renderer->hasLayer());
1813 RenderLayer* layer = downcast<RenderBoxModelObject>(*renderer).layer();
1815 if (layer->viewportConstrainedNotCompositedReason() == RenderLayer::NotCompositedForBoundsOutOfView
1816 || layer->viewportConstrainedNotCompositedReason() == RenderLayer::NotCompositedForNoVisibleContent) {
1817 // Don't invalidate for invisible fixed layers.
1821 if (layer->hasAncestorWithFilterOutsets()) {
1822 // If the fixed layer has a blur/drop-shadow filter applied on at least one of its parents, we cannot
1823 // scroll using the fast path, otherwise the outsets of the filter will be moved around the page.
1827 // FIXME: use pixel snapping instead of enclosing when ScrollView has finished transitioning from IntRect to Float/LayoutRect.
1828 IntRect updateRect = enclosingIntRect(layer->repaintRectIncludingNonCompositingDescendants());
1829 updateRect = contentsToRootView(updateRect);
1830 if (!isCompositedContentLayer && clipsRepaints())
1831 updateRect.intersect(rectToScroll);
1832 if (!updateRect.isEmpty())
1833 regionToUpdate.unite(updateRect);
1837 hostWindow()->scroll(scrollDelta, rectToScroll, clipRect);
1839 // 2) update the area of fixed objects that has been invalidated
1840 Vector<IntRect> subRectsToUpdate = regionToUpdate.rects();
1841 size_t viewportConstrainedObjectsCount = subRectsToUpdate.size();
1842 for (size_t i = 0; i < viewportConstrainedObjectsCount; ++i) {
1843 IntRect updateRect = subRectsToUpdate[i];
1844 IntRect scrolledRect = updateRect;
1845 scrolledRect.move(scrollDelta);
1846 updateRect.unite(scrolledRect);
1847 if (isCompositedContentLayer) {
1848 updateRect = rootViewToContents(updateRect);
1849 ASSERT(renderView());
1850 renderView()->layer()->setBackingNeedsRepaintInRect(updateRect);
1853 if (clipsRepaints())
1854 updateRect.intersect(rectToScroll);
1855 hostWindow()->invalidateContentsAndRootView(updateRect);
1861 void FrameView::scrollContentsSlowPath(const IntRect& updateRect)
1863 repaintSlowRepaintObjects();
1865 if (!usesCompositedScrolling() && isEnclosedInCompositingLayer()) {
1866 if (RenderWidget* frameRenderer = frame().ownerRenderer()) {
1867 LayoutRect rect(frameRenderer->borderLeft() + frameRenderer->paddingLeft(), frameRenderer->borderTop() + frameRenderer->paddingTop(),
1868 visibleWidth(), visibleHeight());
1869 frameRenderer->repaintRectangle(rect);
1874 ScrollView::scrollContentsSlowPath(updateRect);
1877 void FrameView::repaintSlowRepaintObjects()
1879 if (!m_slowRepaintObjects)
1882 // Renderers with fixed backgrounds may be in compositing layers, so we need to explicitly
1883 // repaint them after scrolling.
1884 for (auto& renderer : *m_slowRepaintObjects)
1885 renderer->repaintSlowRepaintObject();
1888 // Note that this gets called at painting time.
1889 void FrameView::setIsOverlapped(bool isOverlapped)
1891 if (isOverlapped == m_isOverlapped)
1894 m_isOverlapped = isOverlapped;
1895 updateCanBlitOnScrollRecursively();
1898 bool FrameView::isOverlappedIncludingAncestors() const
1903 if (FrameView* parentView = parentFrameView()) {
1904 if (parentView->isOverlapped())
1911 void FrameView::setContentIsOpaque(bool contentIsOpaque)
1913 if (contentIsOpaque == m_contentIsOpaque)
1916 m_contentIsOpaque = contentIsOpaque;
1917 updateCanBlitOnScrollRecursively();
1920 void FrameView::restoreScrollbar()
1922 setScrollbarsSuppressed(false);
1925 bool FrameView::scrollToFragment(const URL& url)
1927 // If our URL has no ref, then we have no place we need to jump to.
1928 // OTOH If CSS target was set previously, we want to set it to 0, recalc
1929 // and possibly repaint because :target pseudo class may have been
1930 // set (see bug 11321).
1931 if (!url.hasFragmentIdentifier() && !frame().document()->cssTarget())
1934 String fragmentIdentifier = url.fragmentIdentifier();
1935 if (scrollToAnchor(fragmentIdentifier))
1938 // Try again after decoding the ref, based on the document's encoding.
1939 if (TextResourceDecoder* decoder = frame().document()->decoder())
1940 return scrollToAnchor(decodeURLEscapeSequences(fragmentIdentifier, decoder->encoding()));
1945 bool FrameView::scrollToAnchor(const String& name)
1947 ASSERT(frame().document());
1948 auto& document = *frame().document();
1950 if (!document.haveStylesheetsLoaded()) {
1951 document.setGotoAnchorNeededAfterStylesheetsLoad(true);
1955 document.setGotoAnchorNeededAfterStylesheetsLoad(false);
1957 Element* anchorElement = document.findAnchor(name);
1959 // Setting to null will clear the current target.
1960 document.setCSSTarget(anchorElement);
1962 if (is<SVGDocument>(document)) {
1963 if (auto* rootElement = downcast<SVGDocument>(document).rootElement()) {
1964 rootElement->scrollToAnchor(name, anchorElement);
1970 // Implement the rule that "" and "top" both mean top of page as in other browsers.
1971 if (!anchorElement && !(name.isEmpty() || equalIgnoringCase(name, "top")))
1974 ContainerNode* scrollPositionAnchor = anchorElement;
1975 if (!scrollPositionAnchor)
1976 scrollPositionAnchor = frame().document();
1977 maintainScrollPositionAtAnchor(scrollPositionAnchor);
1979 // If the anchor accepts keyboard focus, move focus there to aid users relying on keyboard navigation.
1980 if (anchorElement && anchorElement->isFocusable())
1981 document.setFocusedElement(anchorElement);
1986 void FrameView::maintainScrollPositionAtAnchor(ContainerNode* anchorNode)
1988 m_maintainScrollPositionAnchor = anchorNode;
1989 if (!m_maintainScrollPositionAnchor)
1992 // We need to update the layout before scrolling, otherwise we could
1993 // really mess things up if an anchor scroll comes at a bad moment.
1994 frame().document()->updateStyleIfNeeded();
1995 // Only do a layout if changes have occurred that make it necessary.
1996 RenderView* renderView = this->renderView();
1997 if (renderView && renderView->needsLayout())
2003 void FrameView::scrollElementToRect(Element* element, const IntRect& rect)
2005 frame().document()->updateLayoutIgnorePendingStylesheets();
2008 if (RenderElement* renderer = element->renderer())
2009 bounds = renderer->anchorRect();
2010 int centeringOffsetX = (rect.width() - bounds.width()) / 2;
2011 int centeringOffsetY = (rect.height() - bounds.height()) / 2;
2012 setScrollPosition(IntPoint(bounds.x() - centeringOffsetX - rect.x(), bounds.y() - centeringOffsetY - rect.y()));
2015 void FrameView::setScrollPosition(const IntPoint& scrollPoint)
2017 TemporaryChange<bool> changeInProgrammaticScroll(m_inProgrammaticScroll, true);
2018 m_maintainScrollPositionAnchor = nullptr;
2019 Page* page = frame().page();
2020 if (page && page->expectsWheelEventTriggers())
2021 scrollAnimator().setWheelEventTestTrigger(page->testTrigger());
2022 ScrollView::setScrollPosition(scrollPoint);
2025 void FrameView::delegatesScrollingDidChange()
2027 // When we switch to delgatesScrolling mode, we should destroy the scrolling/clipping layers in RenderLayerCompositor.
2028 if (hasCompositedContent())
2029 clearBackingStores();
2032 #if USE(COORDINATED_GRAPHICS)
2033 void FrameView::setFixedVisibleContentRect(const IntRect& visibleContentRect)
2035 bool visibleContentSizeDidChange = false;
2036 if (visibleContentRect.size() != this->fixedVisibleContentRect().size()) {
2037 // When the viewport size changes or the content is scaled, we need to
2038 // reposition the fixed and sticky positioned elements.
2039 setViewportConstrainedObjectsNeedLayout();
2040 visibleContentSizeDidChange = true;
2043 IntSize offset = scrollOffset();
2044 IntPoint oldPosition = scrollPosition();
2045 ScrollView::setFixedVisibleContentRect(visibleContentRect);
2046 if (offset != scrollOffset()) {
2047 updateLayerPositionsAfterScrolling();
2048 if (frame().settings().acceleratedCompositingForFixedPositionEnabled())
2049 updateCompositingLayersAfterScrolling();
2050 IntPoint newPosition = scrollPosition();
2051 scrollAnimator().setCurrentPosition(scrollPosition());
2052 scrollPositionChanged(oldPosition, newPosition);
2054 if (visibleContentSizeDidChange) {
2055 // Update the scroll-bars to calculate new page-step size.
2056 updateScrollbars(scrollOffset());
2058 didChangeScrollOffset();
2062 void FrameView::setViewportConstrainedObjectsNeedLayout()
2064 if (!hasViewportConstrainedObjects())
2067 for (auto& renderer : *m_viewportConstrainedObjects)
2068 renderer->setNeedsLayout();
2071 void FrameView::didChangeScrollOffset()
2073 frame().mainFrame().pageOverlayController().didScrollFrame(frame());
2074 frame().loader().client().didChangeScrollOffset();
2077 void FrameView::scrollPositionChangedViaPlatformWidgetImpl(const IntPoint& oldPosition, const IntPoint& newPosition)
2079 updateLayerPositionsAfterScrolling();
2080 updateCompositingLayersAfterScrolling();
2081 repaintSlowRepaintObjects();
2082 scrollPositionChanged(oldPosition, newPosition);
2085 void FrameView::scrollPositionChanged(const IntPoint& oldPosition, const IntPoint& newPosition)
2087 Page* page = frame().page();
2088 auto throttlingDelay = page ? page->chrome().client().eventThrottlingDelay() : std::chrono::milliseconds::zero();
2090 if (throttlingDelay == std::chrono::milliseconds::zero()) {
2091 m_delayedScrollEventTimer.stop();
2093 } else if (!m_delayedScrollEventTimer.isActive())
2094 m_delayedScrollEventTimer.startOneShot(throttlingDelay);
2096 if (Document* document = frame().document())
2097 document->sendWillRevealEdgeEventsIfNeeded(oldPosition, newPosition, visibleContentRect(), contentsSize());
2099 if (RenderView* renderView = this->renderView()) {
2100 if (renderView->usesCompositing())
2101 renderView->compositor().frameViewDidScroll();
2104 viewportContentsChanged();
2107 void FrameView::applyRecursivelyWithVisibleRect(const std::function<void (FrameView& frameView, const IntRect& visibleRect)>& apply)
2109 IntRect windowClipRect = this->windowClipRect();
2110 auto visibleRect = windowToContents(windowClipRect);
2111 apply(*this, visibleRect);
2113 // Recursive call for subframes. We cache the current FrameView's windowClipRect to avoid recomputing it for every subframe.
2114 TemporaryChange<IntRect*> windowClipRectCache(m_cachedWindowClipRect, &windowClipRect);
2115 for (Frame* childFrame = frame().tree().firstChild(); childFrame; childFrame = childFrame->tree().nextSibling()) {
2116 if (auto* childView = childFrame->view())
2117 childView->applyRecursivelyWithVisibleRect(apply);
2121 void FrameView::resumeVisibleImageAnimations(const IntRect& visibleRect)
2123 if (visibleRect.isEmpty())
2126 if (auto* renderView = frame().contentRenderer())
2127 renderView->resumePausedImageAnimationsIfNeeded(visibleRect);
2130 void FrameView::updateScriptedAnimationsThrottlingState(const IntRect& visibleRect)
2132 #if ENABLE(REQUEST_ANIMATION_FRAME)
2133 if (frame().isMainFrame())
2136 auto* document = frame().document();
2140 auto* scriptedAnimationController = document->scriptedAnimationController();
2141 if (!scriptedAnimationController)
2144 // FIXME: This doesn't work for subframes of a "display: none" frame because
2145 // they have a non-null ownerRenderer.
2146 bool shouldThrottle = !frame().ownerRenderer() || visibleRect.isEmpty();
2147 scriptedAnimationController->setThrottled(shouldThrottle);
2149 UNUSED_PARAM(visibleRect);
2154 void FrameView::resumeVisibleImageAnimationsIncludingSubframes()
2156 applyRecursivelyWithVisibleRect([] (FrameView& frameView, const IntRect& visibleRect) {
2157 frameView.resumeVisibleImageAnimations(visibleRect);
2161 void FrameView::updateLayerPositionsAfterScrolling()
2163 // If we're scrolling as a result of updating the view size after layout, we'll update widgets and layer positions soon anyway.
2164 if (m_layoutPhase == InViewSizeAdjust)
2167 if (m_nestedLayoutCount <= 1 && hasViewportConstrainedObjects()) {
2168 if (RenderView* renderView = this->renderView()) {
2169 updateWidgetPositions();
2170 renderView->layer()->updateLayerPositionsAfterDocumentScroll();
2175 bool FrameView::shouldUpdateCompositingLayersAfterScrolling() const
2177 #if ENABLE(ASYNC_SCROLLING)
2178 // If the scrolling thread is updating the fixed elements, then the FrameView should not update them as well.
2180 Page* page = frame().page();
2184 if (&page->mainFrame() != m_frame.ptr())
2187 ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator();
2188 if (!scrollingCoordinator)
2191 if (!scrollingCoordinator->supportsFixedPositionLayers())
2194 if (scrollingCoordinator->shouldUpdateScrollLayerPositionSynchronously())
2197 if (inProgrammaticScroll())
2205 void FrameView::updateCompositingLayersAfterScrolling()
2207 ASSERT(m_layoutPhase >= InPostLayout || m_layoutPhase == OutsideLayout);
2209 if (!shouldUpdateCompositingLayersAfterScrolling())
2212 if (m_nestedLayoutCount <= 1 && hasViewportConstrainedObjects()) {
2213 if (RenderView* renderView = this->renderView())
2214 renderView->compositor().updateCompositingLayers(CompositingUpdateOnScroll);
2218 bool FrameView::isRubberBandInProgress() const
2220 if (scrollbarsSuppressed())
2223 // If the scrolling thread updates the scroll position for this FrameView, then we should return
2224 // ScrollingCoordinator::isRubberBandInProgress().
2225 if (Page* page = frame().page()) {
2226 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator()) {
2227 if (!scrollingCoordinator->shouldUpdateScrollLayerPositionSynchronously())
2228 return scrollingCoordinator->isRubberBandInProgress();
2232 // If the main thread updates the scroll position for this FrameView, we should return
2233 // ScrollAnimator::isRubberBandInProgress().
2234 if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
2235 return scrollAnimator->isRubberBandInProgress();
2240 bool FrameView::requestScrollPositionUpdate(const IntPoint& position)
2242 #if ENABLE(ASYNC_SCROLLING)
2243 if (TiledBacking* tiledBacking = this->tiledBacking())
2244 tiledBacking->prepopulateRect(FloatRect(position, visibleContentRect().size()));
2247 #if ENABLE(ASYNC_SCROLLING) || USE(COORDINATED_GRAPHICS)
2248 if (Page* page = frame().page()) {
2249 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
2250 return scrollingCoordinator->requestScrollPositionUpdate(*this, position);
2253 UNUSED_PARAM(position);
2259 HostWindow* FrameView::hostWindow() const
2261 if (Page* page = frame().page())
2262 return &page->chrome();
2266 void FrameView::addTrackedRepaintRect(const FloatRect& r)
2268 if (!m_isTrackingRepaints || r.isEmpty())
2271 FloatRect repaintRect = r;
2272 repaintRect.move(-scrollOffset());
2273 m_trackedRepaintRects.append(repaintRect);
2276 void FrameView::repaintContentRectangle(const IntRect& r)
2278 ASSERT(!frame().ownerElement());
2280 if (!shouldUpdate())
2283 ScrollView::repaintContentRectangle(r);
2286 static unsigned countRenderedCharactersInRenderObjectWithThreshold(const RenderElement& renderer, unsigned threshold)
2289 for (const RenderObject* descendant = &renderer; descendant; descendant = descendant->nextInPreOrder()) {
2290 if (is<RenderText>(*descendant)) {
2291 count += downcast<RenderText>(*descendant).text()->length();
2292 if (count >= threshold)
2299 bool FrameView::renderedCharactersExceed(unsigned threshold)
2301 if (!frame().contentRenderer())
2303 return countRenderedCharactersInRenderObjectWithThreshold(*frame().contentRenderer(), threshold) >= threshold;
2306 void FrameView::availableContentSizeChanged(AvailableSizeChangeReason reason)
2308 if (Document* document = frame().document())
2309 document->updateViewportUnitsOnResize();
2312 ScrollView::availableContentSizeChanged(reason);
2315 bool FrameView::shouldLayoutAfterContentsResized() const
2317 return !useFixedLayout() || useCustomFixedPositionLayoutRect();
2320 void FrameView::updateContentsSize()
2322 // We check to make sure the view is attached to a frame() as this method can
2323 // be triggered before the view is attached by Frame::createView(...) setting
2324 // various values such as setScrollBarModes(...) for example. An ASSERT is
2325 // triggered when a view is layout before being attached to a frame().
2326 if (!frame().view())
2330 if (RenderView* root = m_frame->contentRenderer()) {
2331 if (useCustomFixedPositionLayoutRect() && hasViewportConstrainedObjects()) {
2332 setViewportConstrainedObjectsNeedLayout();
2333 // We must eagerly enter compositing mode because fixed position elements
2334 // will not have been made compositing via a preceding style change before
2335 // m_useCustomFixedPositionLayoutRect was true.
2336 root->compositor().enableCompositingMode();
2341 if (shouldLayoutAfterContentsResized() && needsLayout())
2344 if (RenderView* renderView = this->renderView()) {
2345 if (renderView->usesCompositing())
2346 renderView->compositor().frameViewDidChangeSize();
2350 void FrameView::addedOrRemovedScrollbar()
2352 if (RenderView* renderView = this->renderView()) {
2353 if (renderView->usesCompositing())
2354 renderView->compositor().frameViewDidAddOrRemoveScrollbars();
2358 static LayerFlushThrottleState::Flags determineLayerFlushThrottleState(Page& page)
2360 // We only throttle when constantly receiving new data during the inital page load.
2361 if (!page.progress().isMainLoadProgressing())
2363 // Scrolling during page loading disables throttling.
2364 if (page.mainFrame().view()->wasScrolledByUser())
2366 // Disable for image documents so large GIF animations don't get throttled during loading.
2367 auto* document = page.mainFrame().document();
2368 if (!document || is<ImageDocument>(*document))
2370 return LayerFlushThrottleState::Enabled;
2373 void FrameView::disableLayerFlushThrottlingTemporarilyForInteraction()
2375 if (!frame().page())
2377 auto& page = *frame().page();
2379 LayerFlushThrottleState::Flags flags = LayerFlushThrottleState::UserIsInteracting | determineLayerFlushThrottleState(page);
2380 if (page.chrome().client().adjustLayerFlushThrottling(flags))
2383 if (RenderView* view = renderView())
2384 view->compositor().disableLayerFlushThrottlingTemporarilyForInteraction();
2387 void FrameView::loadProgressingStatusChanged()
2389 updateLayerFlushThrottling();
2390 adjustTiledBackingCoverage();
2393 void FrameView::updateLayerFlushThrottling()
2395 Page* page = frame().page();
2399 ASSERT(frame().isMainFrame());
2401 LayerFlushThrottleState::Flags flags = determineLayerFlushThrottleState(*page);
2403 // See if the client is handling throttling.
2404 if (page->chrome().client().adjustLayerFlushThrottling(flags))
2407 for (auto* frame = m_frame.ptr(); frame; frame = frame->tree().traverseNext(m_frame.ptr())) {
2408 if (RenderView* renderView = frame->contentRenderer())
2409 renderView->compositor().setLayerFlushThrottlingEnabled(flags & LayerFlushThrottleState::Enabled);
2413 void FrameView::adjustTiledBackingCoverage()
2415 if (!m_speculativeTilingEnabled)
2416 enableSpeculativeTilingIfNeeded();
2418 RenderView* renderView = this->renderView();
2419 if (renderView && renderView->layer()->backing())
2420 renderView->layer()->backing()->adjustTiledBackingCoverage();
2422 if (LegacyTileCache* tileCache = legacyTileCache())
2423 tileCache->setSpeculativeTileCreationEnabled(m_speculativeTilingEnabled);
2427 static bool shouldEnableSpeculativeTilingDuringLoading(const FrameView& view)
2429 Page* page = view.frame().page();
2430 return page && view.isVisuallyNonEmpty() && !page->progress().isMainLoadProgressing();
2433 void FrameView::enableSpeculativeTilingIfNeeded()
2435 ASSERT(!m_speculativeTilingEnabled);
2436 if (m_wasScrolledByUser) {
2437 m_speculativeTilingEnabled = true;
2440 if (!shouldEnableSpeculativeTilingDuringLoading(*this))
2442 if (m_speculativeTilingEnableTimer.isActive())
2444 // Delay enabling a bit as load completion may trigger further loading from scripts.
2445 static const double speculativeTilingEnableDelay = 0.5;
2446 m_speculativeTilingEnableTimer.startOneShot(speculativeTilingEnableDelay);
2449 void FrameView::speculativeTilingEnableTimerFired()
2451 if (m_speculativeTilingEnabled)
2453 m_speculativeTilingEnabled = shouldEnableSpeculativeTilingDuringLoading(*this);
2454 adjustTiledBackingCoverage();
2457 void FrameView::layoutTimerFired()
2459 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2460 if (!frame().document()->ownerElement())
2461 printf("Layout timer fired at %lld\n", frame().document()->elapsedTime().count());
2466 void FrameView::scheduleRelayout()
2468 // FIXME: We should assert the page is not in the page cache, but that is causing
2469 // too many false assertions. See <rdar://problem/7218118>.
2470 ASSERT(frame().view() == this);
2473 m_layoutRoot->markContainingBlocksForLayout(false);
2474 m_layoutRoot = nullptr;
2476 if (!m_layoutSchedulingEnabled)
2480 if (!frame().document()->shouldScheduleLayout())
2482 InspectorInstrumentation::didInvalidateLayout(frame());
2483 // When frame flattening is enabled, the contents of the frame could affect the layout of the parent frames.
2484 // Also invalidate parent frame starting from the owner element of this frame.
2485 if (frame().ownerRenderer() && isInChildFrameWithFrameFlattening())
2486 frame().ownerRenderer()->setNeedsLayout(MarkContainingBlockChain);
2488 std::chrono::milliseconds delay = frame().document()->minimumLayoutDelay();
2489 if (m_layoutTimer.isActive() && m_delayedLayout && !delay.count())
2490 unscheduleRelayout();
2491 if (m_layoutTimer.isActive())
2494 m_delayedLayout = delay.count();
2496 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2497 if (!frame().document()->ownerElement())
2498 printf("Scheduling layout for %d\n", delay);
2501 m_layoutTimer.startOneShot(delay);
2504 static bool isObjectAncestorContainerOf(RenderObject* ancestor, RenderObject* descendant)
2506 for (RenderObject* r = descendant; r; r = r->container()) {
2513 void FrameView::scheduleRelayoutOfSubtree(RenderElement& newRelayoutRoot)
2515 ASSERT(renderView());
2516 RenderView& renderView = *this->renderView();
2518 // Try to catch unnecessary work during render tree teardown.
2519 ASSERT(!renderView.documentBeingDestroyed());
2520 ASSERT(frame().view() == this);
2522 if (renderView.needsLayout()) {
2523 newRelayoutRoot.markContainingBlocksForLayout(false);
2527 if (!layoutPending() && m_layoutSchedulingEnabled) {
2528 std::chrono::milliseconds delay = renderView.document().minimumLayoutDelay();
2529 ASSERT(!newRelayoutRoot.container() || !newRelayoutRoot.container()->needsLayout());
2530 m_layoutRoot = &newRelayoutRoot;
2531 InspectorInstrumentation::didInvalidateLayout(frame());
2532 m_delayedLayout = delay.count();
2533 m_layoutTimer.startOneShot(delay);
2537 if (m_layoutRoot == &newRelayoutRoot)
2540 if (!m_layoutRoot) {
2541 // Just relayout the subtree.
2542 newRelayoutRoot.markContainingBlocksForLayout(false);
2543 InspectorInstrumentation::didInvalidateLayout(frame());
2547 if (isObjectAncestorContainerOf(m_layoutRoot, &newRelayoutRoot)) {
2548 // Keep the current root.
2549 newRelayoutRoot.markContainingBlocksForLayout(false, m_layoutRoot);
2550 ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
2554 if (isObjectAncestorContainerOf(&newRelayoutRoot, m_layoutRoot)) {
2555 // Re-root at newRelayoutRoot.
2556 m_layoutRoot->markContainingBlocksForLayout(false, &newRelayoutRoot);
2557 m_layoutRoot = &newRelayoutRoot;
2558 ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
2559 InspectorInstrumentation::didInvalidateLayout(frame());
2563 // Just do a full relayout.
2564 m_layoutRoot->markContainingBlocksForLayout(false);
2565 m_layoutRoot = nullptr;
2566 newRelayoutRoot.markContainingBlocksForLayout(false);
2567 InspectorInstrumentation::didInvalidateLayout(frame());
2570 bool FrameView::layoutPending() const
2572 return m_layoutTimer.isActive();
2575 bool FrameView::needsStyleRecalcOrLayout(bool includeSubframes) const
2577 if (frame().document() && frame().document()->childNeedsStyleRecalc())
2583 if (!includeSubframes)
2586 for (auto& frameView : renderedChildFrameViews()) {
2587 if (frameView->needsStyleRecalcOrLayout())
2594 bool FrameView::needsLayout() const
2596 // This can return true in cases where the document does not have a body yet.
2597 // Document::shouldScheduleLayout takes care of preventing us from scheduling
2598 // layout in that case.
2599 RenderView* renderView = this->renderView();
2600 return layoutPending()
2601 || (renderView && renderView->needsLayout())
2603 || (m_deferSetNeedsLayoutCount && m_setNeedsLayoutWasDeferred);
2606 void FrameView::setNeedsLayout()
2608 if (m_deferSetNeedsLayoutCount) {
2609 m_setNeedsLayoutWasDeferred = true;
2613 if (RenderView* renderView = this->renderView())
2614 renderView->setNeedsLayout();
2617 void FrameView::unscheduleRelayout()
2619 if (m_postLayoutTasksTimer.isActive())
2620 m_postLayoutTasksTimer.stop();
2622 if (!m_layoutTimer.isActive())
2625 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2626 if (!frame().document()->ownerElement())
2627 printf("Layout timer unscheduled at %d\n", frame().document()->elapsedTime());
2630 m_layoutTimer.stop();
2631 m_delayedLayout = false;
2634 #if ENABLE(REQUEST_ANIMATION_FRAME)
2635 void FrameView::serviceScriptedAnimations(double monotonicAnimationStartTime)
2637 for (auto* frame = m_frame.ptr(); frame; frame = frame->tree().traverseNext()) {
2638 frame->view()->serviceScrollAnimations();
2639 frame->animation().serviceAnimations();
2642 Vector<RefPtr<Document>> documents;
2643 for (auto* frame = m_frame.ptr(); frame; frame = frame->tree().traverseNext())
2644 documents.append(frame->document());
2646 for (size_t i = 0; i < documents.size(); ++i)
2647 documents[i]->serviceScriptedAnimations(monotonicAnimationStartTime);
2651 bool FrameView::isTransparent() const
2653 return m_isTransparent;
2656 void FrameView::setTransparent(bool isTransparent)
2658 if (m_isTransparent == isTransparent)
2661 m_isTransparent = isTransparent;
2663 // setTransparent can be called in the window between FrameView initialization
2664 // and switching in the new Document; this means that the RenderView that we
2665 // retrieve is actually attached to the previous Document, which is going away,
2666 // and must not update compositing layers.
2667 if (!isViewForDocumentInFrame())
2670 renderView()->compositor().rootBackgroundTransparencyChanged();
2673 bool FrameView::hasOpaqueBackground() const
2675 return !m_isTransparent && !m_baseBackgroundColor.hasAlpha();
2678 Color FrameView::baseBackgroundColor() const
2680 return m_baseBackgroundColor;
2683 void FrameView::setBaseBackgroundColor(const Color& backgroundColor)
2685 bool hadAlpha = m_baseBackgroundColor.hasAlpha();
2687 if (!backgroundColor.isValid())
2688 m_baseBackgroundColor = Color::white;
2690 m_baseBackgroundColor = backgroundColor;
2692 if (!isViewForDocumentInFrame())
2695 recalculateScrollbarOverlayStyle();
2697 if (m_baseBackgroundColor.hasAlpha() != hadAlpha)
2698 renderView()->compositor().rootBackgroundTransparencyChanged();
2701 void FrameView::updateBackgroundRecursively(const Color& backgroundColor, bool transparent)
2703 for (auto* frame = m_frame.ptr(); frame; frame = frame->tree().traverseNext(m_frame.ptr())) {
2704 if (FrameView* view = frame->view()) {
2705 view->setTransparent(transparent);
2706 view->setBaseBackgroundColor(backgroundColor);
2711 bool FrameView::hasExtendedBackgroundRectForPainting() const
2713 if (!frame().settings().backgroundShouldExtendBeyondPage())
2716 TiledBacking* tiledBacking = this->tiledBacking();
2720 return tiledBacking->hasMargins();
2723 void FrameView::updateExtendBackgroundIfNecessary()
2725 ExtendedBackgroundMode mode = calculateExtendedBackgroundMode();
2726 if (mode == ExtendedBackgroundModeNone)
2729 updateTilesForExtendedBackgroundMode(mode);
2732 FrameView::ExtendedBackgroundMode FrameView::calculateExtendedBackgroundMode() const
2734 // Just because Settings::backgroundShouldExtendBeyondPage() is true does not necessarily mean
2735 // that the background rect needs to be extended for painting. Simple backgrounds can be extended
2736 // just with RenderLayerCompositor::setRootExtendedBackgroundColor(). More complicated backgrounds,
2737 // such as images, require extending the background rect to continue painting into the extended
2738 // region. This function finds out if it is necessary to extend the background rect for painting.
2741 // <rdar://problem/16201373>
2742 return ExtendedBackgroundModeNone;
2745 if (!frame().settings().backgroundShouldExtendBeyondPage())
2746 return ExtendedBackgroundModeNone;
2748 if (!frame().isMainFrame())
2749 return ExtendedBackgroundModeNone;
2751 Document* document = frame().document();
2753 return ExtendedBackgroundModeNone;
2755 auto documentElement = document->documentElement();
2756 auto documentElementRenderer = documentElement ? documentElement->renderer() : nullptr;
2757 if (!documentElementRenderer)
2758 return ExtendedBackgroundModeNone;
2760 auto& renderer = documentElementRenderer->rendererForRootBackground();
2761 if (!renderer.style().hasBackgroundImage())
2762 return ExtendedBackgroundModeNone;
2764 ExtendedBackgroundMode mode = ExtendedBackgroundModeNone;
2766 if (renderer.style().backgroundRepeatX() == RepeatFill)
2767 mode |= ExtendedBackgroundModeHorizontal;
2768 if (renderer.style().backgroundRepeatY() == RepeatFill)
2769 mode |= ExtendedBackgroundModeVertical;
2774 void FrameView::updateTilesForExtendedBackgroundMode(ExtendedBackgroundMode mode)
2776 if (!frame().settings().backgroundShouldExtendBeyondPage())
2779 RenderView* renderView = this->renderView();
2783 RenderLayerBacking* backing = renderView->layer()->backing();
2787 TiledBacking* tiledBacking = backing->graphicsLayer()->tiledBacking();
2791 ExtendedBackgroundMode existingMode = ExtendedBackgroundModeNone;
2792 if (tiledBacking->hasVerticalMargins())
2793 existingMode |= ExtendedBackgroundModeVertical;
2794 if (tiledBacking->hasHorizontalMargins())
2795 existingMode |= ExtendedBackgroundModeHorizontal;
2797 if (existingMode == mode)
2800 renderView->compositor().setRootExtendedBackgroundColor(mode == ExtendedBackgroundModeAll ? Color() : documentBackgroundColor());
2801 backing->setTiledBackingHasMargins(mode & ExtendedBackgroundModeHorizontal, mode & ExtendedBackgroundModeVertical);
2804 IntRect FrameView::extendedBackgroundRectForPainting() const
2806 TiledBacking* tiledBacking = this->tiledBacking();
2810 RenderView* renderView = this->renderView();
2814 LayoutRect extendedRect = renderView->unextendedBackgroundRect(renderView);
2815 if (!tiledBacking->hasMargins())
2816 return snappedIntRect(extendedRect);
2818 extendedRect.moveBy(LayoutPoint(-tiledBacking->leftMarginWidth(), -tiledBacking->topMarginHeight()));
2819 extendedRect.expand(LayoutSize(tiledBacking->leftMarginWidth() + tiledBacking->rightMarginWidth(), tiledBacking->topMarginHeight() + tiledBacking->bottomMarginHeight()));
2820 return snappedIntRect(extendedRect);
2823 bool FrameView::shouldUpdateWhileOffscreen() const
2825 return m_shouldUpdateWhileOffscreen;
2828 void FrameView::setShouldUpdateWhileOffscreen(bool shouldUpdateWhileOffscreen)
2830 m_shouldUpdateWhileOffscreen = shouldUpdateWhileOffscreen;
2833 bool FrameView::shouldUpdate() const
2835 if (isOffscreen() && !shouldUpdateWhileOffscreen())
2840 void FrameView::scrollToAnchor()
2842 RefPtr<ContainerNode> anchorNode = m_maintainScrollPositionAnchor;
2846 if (!anchorNode->renderer())
2850 if (anchorNode != frame().document() && anchorNode->renderer())
2851 rect = anchorNode->renderer()->anchorRect();
2853 // Scroll nested layers and frames to reveal the anchor.
2854 // Align to the top and to the closest side (this matches other browsers).
2855 if (anchorNode->renderer()->style().isHorizontalWritingMode())
2856 anchorNode->renderer()->scrollRectToVisible(rect, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
2857 else if (anchorNode->renderer()->style().isFlippedBlocksWritingMode())
2858 anchorNode->renderer()->scrollRectToVisible(rect, ScrollAlignment::alignRightAlways, ScrollAlignment::alignToEdgeIfNeeded);
2860 anchorNode->renderer()->scrollRectToVisible(rect, ScrollAlignment::alignLeftAlways, ScrollAlignment::alignToEdgeIfNeeded);
2862 if (AXObjectCache* cache = frame().document()->existingAXObjectCache())
2863 cache->handleScrolledToAnchor(anchorNode.get());
2865 // scrollRectToVisible can call into setScrollPosition(), which resets m_maintainScrollPositionAnchor.
2866 m_maintainScrollPositionAnchor = anchorNode;
2869 void FrameView::updateEmbeddedObject(RenderEmbeddedObject& embeddedObject)
2871 // No need to update if it's already crashed or known to be missing.
2872 if (embeddedObject.isPluginUnavailable())
2875 HTMLFrameOwnerElement& element = embeddedObject.frameOwnerElement();
2877 if (embeddedObject.isSnapshottedPlugIn()) {
2878 if (is<HTMLObjectElement>(element) || is<HTMLEmbedElement>(element)) {
2879 HTMLPlugInImageElement& pluginElement = downcast<HTMLPlugInImageElement>(element);
2880 pluginElement.checkSnapshotStatus();
2885 auto weakRenderer = embeddedObject.createWeakPtr();
2887 // FIXME: This could turn into a real virtual dispatch if we defined
2888 // updateWidget(PluginCreationOption) on HTMLElement.
2889 if (is<HTMLPlugInImageElement>(element)) {
2890 HTMLPlugInImageElement& pluginElement = downcast<HTMLPlugInImageElement>(element);
2891 if (pluginElement.needsCheckForSizeChange()) {
2892 pluginElement.checkSnapshotStatus();
2895 if (pluginElement.needsWidgetUpdate())
2896 pluginElement.updateWidget(CreateAnyWidgetType);
2898 ASSERT_NOT_REACHED();
2900 // It's possible the renderer was destroyed below updateWidget() since loading a plugin may execute arbitrary JavaScript.
2904 embeddedObject.updateWidgetPosition();
2907 bool FrameView::updateEmbeddedObjects()
2909 if (m_nestedLayoutCount > 1 || !m_embeddedObjectsToUpdate || m_embeddedObjectsToUpdate->isEmpty())
2912 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
2914 // Insert a marker for where we should stop.
2915 ASSERT(!m_embeddedObjectsToUpdate->contains(nullptr));
2916 m_embeddedObjectsToUpdate->add(nullptr);
2918 while (!m_embeddedObjectsToUpdate->isEmpty()) {
2919 RenderEmbeddedObject* embeddedObject = m_embeddedObjectsToUpdate->takeFirst();
2920 if (!embeddedObject)
2922 updateEmbeddedObject(*embeddedObject);
2925 return m_embeddedObjectsToUpdate->isEmpty();
2928 void FrameView::updateEmbeddedObjectsTimerFired()
2930 RefPtr<FrameView> protect(this);
2931 m_updateEmbeddedObjectsTimer.stop();
2932 for (unsigned i = 0; i < maxUpdateEmbeddedObjectsIterations; i++) {
2933 if (updateEmbeddedObjects())
2938 void FrameView::flushAnyPendingPostLayoutTasks()
2940 if (m_postLayoutTasksTimer.isActive())
2941 performPostLayoutTasks();
2942 if (m_updateEmbeddedObjectsTimer.isActive())
2943 updateEmbeddedObjectsTimerFired();
2946 void FrameView::performPostLayoutTasks()
2948 // FIXME: We should not run any JavaScript code in this function.
2950 m_postLayoutTasksTimer.stop();
2952 frame().selection().didLayout();
2954 if (m_nestedLayoutCount <= 1 && frame().document()->documentElement())
2955 fireLayoutRelatedMilestonesIfNeeded();
2958 // Only send layout-related delegate callbacks synchronously for the main frame to
2959 // avoid re-entering layout for the main frame while delivering a layout-related delegate
2960 // callback for a subframe.
2961 if (frame().isMainFrame()) {
2962 if (Page* page = frame().page())
2963 page->chrome().client().didLayout();
2967 #if ENABLE(FONT_LOAD_EVENTS)
2968 if (RuntimeEnabledFeatures::sharedFeatures().fontLoadEventsEnabled())
2969 frame().document()->fonts()->didLayout();
2972 // FIXME: We should consider adding DidLayout as a LayoutMilestone. That would let us merge this
2973 // with didLayout(LayoutMilestones).
2974 frame().loader().client().dispatchDidLayout();
2976 updateWidgetPositions();
2978 // layout() protects FrameView, but it still can get destroyed when updateEmbeddedObjects()
2979 // is called through the post layout timer.
2980 Ref<FrameView> protect(*this);
2982 m_updateEmbeddedObjectsTimer.startOneShot(0);
2984 if (auto* page = frame().page()) {
2985 if (auto* scrollingCoordinator = page->scrollingCoordinator())
2986 scrollingCoordinator->frameViewLayoutUpdated(*this);
2989 if (RenderView* renderView = this->renderView()) {
2990 if (renderView->usesCompositing())
2991 renderView->compositor().frameViewDidLayout();
2996 sendResizeEventIfNeeded();
2997 viewportContentsChanged();
2999 #if ENABLE(CSS_SCROLL_SNAP)
3000 if (!frame().isMainFrame()) {
3001 updateSnapOffsets();
3003 if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
3004 return scrollAnimator->updateScrollAnimatorsAndTimers();
3010 IntSize FrameView::sizeForResizeEvent() const
3013 if (m_useCustomSizeForResizeEvent)
3014 return m_customSizeForResizeEvent;
3016 if (useFixedLayout() && !fixedLayoutSize().isEmpty() && delegatesScrolling())
3017 return fixedLayoutSize();
3018 return visibleContentRectIncludingScrollbars().size();
3021 void FrameView::sendResizeEventIfNeeded()
3023 if (isInLayout() || needsLayout())
3026 RenderView* renderView = this->renderView();
3027 if (!renderView || renderView->printing())
3030 if (frame().page() && frame().page()->chrome().client().isSVGImageChromeClient())
3033 IntSize currentSize = sizeForResizeEvent();
3034 float currentZoomFactor = renderView->style().zoom();
3036 if (currentSize == m_lastViewportSize && currentZoomFactor == m_lastZoomFactor)
3039 m_lastViewportSize = currentSize;
3040 m_lastZoomFactor = currentZoomFactor;
3046 // Don't send the resize event if the document is loading. Some pages automatically reload
3047 // when the window is resized; Safari on iOS often resizes the window while setting up its
3048 // viewport. This obviously can cause problems.
3049 if (DocumentLoader* documentLoader = frame().loader().documentLoader()) {
3050 if (documentLoader->isLoadingInAPISense())
3055 bool isMainFrame = frame().isMainFrame();
3056 bool canSendResizeEventSynchronously = isMainFrame && !m_shouldAutoSize;
3058 RefPtr<Event> resizeEvent = Event::create(eventNames().resizeEvent, false, false);
3059 if (canSendResizeEventSynchronously)
3060 frame().document()->dispatchWindowEvent(resizeEvent.release());
3062 // FIXME: Queueing this event for an unpredictable time in the future seems
3063 // intrinsically racy. By the time this resize event fires, the frame might
3064 // be resized again, so we could end up with two resize events for the same size.
3065 frame().document()->enqueueWindowEvent(resizeEvent.release());
3068 if (InspectorInstrumentation::hasFrontends() && isMainFrame) {
3069 if (Page* page = frame().page()) {
3070 if (InspectorClient* inspectorClient = page->inspectorController().inspectorClient())
3071 inspectorClient->didResizeMainFrame(&frame());
3076 void FrameView::willStartLiveResize()
3078 ScrollView::willStartLiveResize();
3079 adjustTiledBackingCoverage();
3082 void FrameView::willEndLiveResize()
3084 ScrollView::willEndLiveResize();
3085 adjustTiledBackingCoverage();
3088 void FrameView::postLayoutTimerFired()
3090 performPostLayoutTasks();
3093 void FrameView::registerThrottledDOMTimer(DOMTimer* timer)
3095 m_throttledTimers.add(timer);
3098 void FrameView::unregisterThrottledDOMTimer(DOMTimer* timer)
3100 m_throttledTimers.remove(timer);
3103 void FrameView::updateThrottledDOMTimersState(const IntRect& visibleRect)
3105 if (m_throttledTimers.isEmpty())
3108 // Do not iterate over the HashSet because calling DOMTimer::updateThrottlingStateAfterViewportChange()
3109 // may cause timers to remove themselves from it while we are iterating.
3110 Vector<DOMTimer*> timers;
3111 copyToVector(m_throttledTimers, timers);
3112 for (auto* timer : timers)
3113 timer->updateThrottlingStateAfterViewportChange(visibleRect);
3116 void FrameView::autoSizeIfEnabled()
3118 if (!m_shouldAutoSize)
3124 TemporaryChange<bool> changeInAutoSize(m_inAutoSize, true);
3126 Document* document = frame().document();
3130 RenderView* documentView = document->renderView();
3131 Element* documentElement = document->documentElement();
3132 if (!documentView || !documentElement)
3135 // Start from the minimum size and allow it to grow.
3136 resize(m_minAutoSize.width(), m_minAutoSize.height());
3138 IntSize size = frameRect().size();
3140 // Do the resizing twice. The first time is basically a rough calculation using the preferred width
3141 // which may result in a height change during the second iteration.
3142 for (int i = 0; i < 2; i++) {
3143 // Update various sizes including contentsSize, scrollHeight, etc.
3144 document->updateLayoutIgnorePendingStylesheets();
3145 int width = documentView->minPreferredLogicalWidth();
3146 int height = documentView->documentRect().height();
3147 IntSize newSize(width, height);
3149 // Check to see if a scrollbar is needed for a given dimension and
3150 // if so, increase the other dimension to account for the scrollbar.
3151 // Since the dimensions are only for the view rectangle, once a
3152 // dimension exceeds the maximum, there is no need to increase it further.
3153 if (newSize.width() > m_maxAutoSize.width()) {
3154 RefPtr<Scrollbar> localHorizontalScrollbar = horizontalScrollbar();
3155 if (!localHorizontalScrollbar)
3156 localHorizontalScrollbar = createScrollbar(HorizontalScrollbar);
3157 if (!localHorizontalScrollbar->isOverlayScrollbar())
3158 newSize.setHeight(newSize.height() + localHorizontalScrollbar->height());
3160 // Don't bother checking for a vertical scrollbar because the width is at
3161 // already greater the maximum.
3162 } else if (newSize.height() > m_maxAutoSize.height()) {
3163 RefPtr<Scrollbar> localVerticalScrollbar = verticalScrollbar();
3164 if (!localVerticalScrollbar)
3165 localVerticalScrollbar = createScrollbar(VerticalScrollbar);
3166 if (!localVerticalScrollbar->isOverlayScrollbar())
3167 newSize.setWidth(newSize.width() + localVerticalScrollbar->width());
3169 // Don't bother checking for a horizontal scrollbar because the height is
3170 // already greater the maximum.
3173 // Ensure the size is at least the min bounds.
3174 newSize = newSize.expandedTo(m_minAutoSize);
3176 // Bound the dimensions by the max bounds and determine what scrollbars to show.
3177 ScrollbarMode horizonalScrollbarMode = ScrollbarAlwaysOff;
3178 if (newSize.width() > m_maxAutoSize.width()) {
3179 newSize.setWidth(m_maxAutoSize.width());
3180 horizonalScrollbarMode = ScrollbarAlwaysOn;
3182 ScrollbarMode verticalScrollbarMode = ScrollbarAlwaysOff;
3183 if (newSize.height() > m_maxAutoSize.height()) {
3184 newSize.setHeight(m_maxAutoSize.height());
3185 verticalScrollbarMode = ScrollbarAlwaysOn;
3188 if (newSize == size)
3191 // While loading only allow the size to increase (to avoid twitching during intermediate smaller states)
3192 // unless autoresize has just been turned on or the maximum size is smaller than the current size.
3193 if (m_didRunAutosize && size.height() <= m_maxAutoSize.height() && size.width() <= m_maxAutoSize.width()
3194 && !frame().loader().isComplete() && (newSize.height() < size.height() || newSize.width() < size.width()))
3197 resize(newSize.width(), newSize.height());
3198 // Force the scrollbar state to avoid the scrollbar code adding them and causing them to be needed. For example,
3199 // a vertical scrollbar may cause text to wrap and thus increase the height (which is the only reason the scollbar is needed).
3200 setVerticalScrollbarLock(false);
3201 setHorizontalScrollbarLock(false);
3202 setScrollbarModes(horizonalScrollbarMode, verticalScrollbarMode, true, true);
3205 m_autoSizeContentSize = contentsSize();
3207 if (m_autoSizeFixedMinimumHeight) {
3208 resize(m_autoSizeContentSize.width(), std::max(m_autoSizeFixedMinimumHeight, m_autoSizeContentSize.height()));
3209 document->updateLayoutIgnorePendingStylesheets();
3212 m_didRunAutosize = true;
3215 void FrameView::setAutoSizeFixedMinimumHeight(int fixedMinimumHeight)
3217 if (m_autoSizeFixedMinimumHeight == fixedMinimumHeight)
3220 m_autoSizeFixedMinimumHeight = fixedMinimumHeight;
3225 void FrameView::updateOverflowStatus(bool horizontalOverflow, bool verticalOverflow)
3227 if (!m_viewportRenderer)
3230 if (m_overflowStatusDirty) {
3231 m_horizontalOverflow = horizontalOverflow;
3232 m_verticalOverflow = verticalOverflow;
3233 m_overflowStatusDirty = false;
3237 bool horizontalOverflowChanged = (m_horizontalOverflow != horizontalOverflow);
3238 bool verticalOverflowChanged = (m_verticalOverflow != verticalOverflow);
3240 if (horizontalOverflowChanged || verticalOverflowChanged) {
3241 m_horizontalOverflow = horizontalOverflow;
3242 m_verticalOverflow = verticalOverflow;
3244 RefPtr<OverflowEvent> overflowEvent = OverflowEvent::create(horizontalOverflowChanged, horizontalOverflow,
3245 verticalOverflowChanged, verticalOverflow);
3246 overflowEvent->setTarget(m_viewportRenderer->element());
3248 frame().document()->enqueueOverflowEvent(overflowEvent.release());
3252 const Pagination& FrameView::pagination() const
3254 if (m_pagination != Pagination())
3255 return m_pagination;
3257 if (frame().isMainFrame()) {
3258 if (Page* page = frame().page())
3259 return page->pagination();
3262 return m_pagination;
3265 void FrameView::setPagination(const Pagination& pagination)
3267 if (m_pagination == pagination)
3270 m_pagination = pagination;
3272 frame().document()->styleResolverChanged(DeferRecalcStyle);
3275 IntRect FrameView::windowClipRect() const
3277 ASSERT(frame().view() == this);
3279 if (m_cachedWindowClipRect)
3280 return *m_cachedWindowClipRect;
3282 if (paintsEntireContents())
3283 return contentsToWindow(IntRect(IntPoint(), totalContentsSize()));
3285 // Set our clip rect to be our contents.
3286 IntRect clipRect = contentsToWindow(visibleContentRect(LegacyIOSDocumentVisibleRect));
3288 if (!frame().ownerElement())
3291 // Take our owner element and get its clip rect.
3292 HTMLFrameOwnerElement* ownerElement = frame().ownerElement();
3293 if (FrameView* parentView = ownerElement->document().view())
3294 clipRect.intersect(parentView->windowClipRectForFrameOwner(ownerElement, true));
3298 IntRect FrameView::windowClipRectForFrameOwner(const HTMLFrameOwnerElement* ownerElement, bool clipToLayerContents) const
3300 // The renderer can sometimes be null when style="display:none" interacts
3301 // with external content and plugins.
3302 if (!ownerElement->renderer())
3303 return windowClipRect();
3305 // If we have no layer, just return our window clip rect.
3306 const RenderLayer* enclosingLayer = ownerElement->renderer()->enclosingLayer();
3307 if (!enclosingLayer)
3308 return windowClipRect();
3310 // Apply the clip from the layer.
3312 if (clipToLayerContents)
3313 clipRect = snappedIntRect(enclosingLayer->childrenClipRect());
3315 clipRect = snappedIntRect(enclosingLayer->selfClipRect());
3316 clipRect = contentsToWindow(clipRect);
3317 return intersection(clipRect, windowClipRect());
3320 bool FrameView::isActive() const
3322 Page* page = frame().page();
3323 return page && page->focusController().isActive();
3326 bool FrameView::updatesScrollLayerPositionOnMainThread() const
3328 if (Page* page = frame().page()) {
3329 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
3330 return scrollingCoordinator->shouldUpdateScrollLayerPositionSynchronously();
3336 bool FrameView::forceUpdateScrollbarsOnMainThreadForPerformanceTesting() const
3338 Page* page = frame().page();
3339 return page && page->settings().forceUpdateScrollbarsOnMainThreadForPerformanceTesting();
3342 void FrameView::scrollTo(const IntSize& newOffset)
3344 LayoutSize offset = scrollOffset();
3345 IntPoint oldPosition = scrollPosition();
3346 ScrollView::scrollTo(newOffset);
3347 if (offset != scrollOffset())
3348 scrollPositionChanged(oldPosition, scrollPosition());
3349 didChangeScrollOffset();
3352 float FrameView::adjustScrollStepForFixedContent(float step, ScrollbarOrientation orientation, ScrollGranularity granularity)
3354 if (granularity != ScrollByPage || orientation == HorizontalScrollbar)
3357 TrackedRendererListHashSet* positionedObjects = nullptr;
3358 if (RenderView* root = frame().contentRenderer()) {
3359 if (!root->hasPositionedObjects())
3361 positionedObjects = root->positionedObjects();
3364 FloatRect unobscuredContentRect = this->unobscuredContentRect();
3365 float topObscuredArea = 0;
3366 float bottomObscuredArea = 0;
3367 for (const auto& positionedObject : *positionedObjects) {
3368 const RenderStyle& style = positionedObject->style();
3369 if (style.position() != FixedPosition || style.visibility() == HIDDEN || !style.opacity())
3372 FloatQuad contentQuad = positionedObject->absoluteContentQuad();
3373 if (!contentQuad.isRectilinear())
3376 FloatRect contentBoundingBox = contentQuad.boundingBox();
3377 FloatRect fixedRectInView = intersection(unobscuredContentRect, contentBoundingBox);
3379 if (fixedRectInView.width() < unobscuredContentRect.width())
3382 if (fixedRectInView.y() == unobscuredContentRect.y())
3383 topObscuredArea = std::max(topObscuredArea, fixedRectInView.height());
3384 else if (fixedRectInView.maxY() == unobscuredContentRect.maxY())
3385 bottomObscuredArea = std::max(bottomObscuredArea, fixedRectInView.height());
3388 return Scrollbar::pageStep(unobscuredContentRect.height(), unobscuredContentRect.height() - topObscuredArea - bottomObscuredArea);
3391 void FrameView::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
3393 // Add in our offset within the FrameView.
3394 IntRect dirtyRect = rect;
3395 dirtyRect.moveBy(scrollbar->location());
3396 invalidateRect(dirtyRect);
3399 IntRect FrameView::windowResizerRect() const
3401 if (Page* page = frame().page())
3402 return page->chrome().windowResizerRect();
3406 float FrameView::visibleContentScaleFactor() const
3408 if (!frame().isMainFrame() || !frame().settings().delegatesPageScaling())
3411 Page* page = frame().page();
3415 return page->pageScaleFactor();
3418 void FrameView::setVisibleScrollerThumbRect(const IntRect& scrollerThumb)
3420 if (!frame().isMainFrame())
3423 Page* page = frame().page();
3427 page->chrome().client().notifyScrollerThumbIsVisibleInRect(scrollerThumb);
3430 ScrollableArea* FrameView::enclosingScrollableArea() const
3432 // FIXME: Walk up the frame tree and look for a scrollable parent frame or RenderLayer.
3436 IntRect FrameView::scrollableAreaBoundingBox() const
3438 RenderWidget* ownerRenderer = frame().ownerRenderer();
3442 return ownerRenderer->absoluteContentQuad().enclosingBoundingBox();
3445 bool FrameView::isScrollable(Scrollability definitionOfScrollable)
3448 // 1) If there an actual overflow.
3449 // 2) display:none or visibility:hidden set to self or inherited.
3450 // 3) overflow{-x,-y}: hidden;
3451 // 4) scrolling: no;
3453 bool requiresActualOverflowToBeConsideredScrollable = !frame().isMainFrame() || definitionOfScrollable != Scrollability::ScrollableOrRubberbandable;
3454 #if !ENABLE(RUBBER_BANDING)
3455 requiresActualOverflowToBeConsideredScrollable = true;
3459 if (requiresActualOverflowToBeConsideredScrollable) {
3460 IntSize totalContentsSize = this->totalContentsSize();
3461 IntSize visibleContentSize = visibleContentRect(LegacyIOSDocumentVisibleRect).size();
3462 if (totalContentsSize.height() <= visibleContentSize.height() && totalContentsSize.width() <= visibleContentSize.width())
3467 HTMLFrameOwnerElement* owner = frame().ownerElement();
3468 if (owner && (!owner->renderer() || !owner->renderer()->visibleToHitTesting()))
3472 ScrollbarMode horizontalMode;
3473 ScrollbarMode verticalMode;
3474 calculateScrollbarModesForLayout(horizontalMode, verticalMode, RulesFromWebContentOnly);
3475 if (horizontalMode == ScrollbarAlwaysOff && verticalMode == ScrollbarAlwaysOff)
3481 bool FrameView::isScrollableOrRubberbandable()
3483 return isScrollable(Scrollability::ScrollableOrRubberbandable);
3486 bool FrameView::hasScrollableOrRubberbandableAncestor()
3488 if (frame().isMainFrame())
3489 return isScrollableOrRubberbandable();
3491 for (FrameView* parent = this->parentFrameView(); parent; parent = parent->parentFrameView()) {
3492 Scrollability frameScrollability = parent->frame().isMainFrame() ? Scrollability::ScrollableOrRubberbandable : Scrollability::Scrollable;
3493 if (parent->isScrollable(frameScrollability))
3500 void FrameView::updateScrollableAreaSet()
3502 // That ensures that only inner frames are cached.
3503 FrameView* parentFrameView = this->parentFrameView();
3504 if (!parentFrameView)
3507 if (!isScrollable()) {
3508 parentFrameView->removeScrollableArea(this);
3512 parentFrameView->addScrollableArea(this);
3515 bool FrameView::shouldSuspendScrollAnimations() const
3517 return frame().loader().state() != FrameStateComplete;
3520 void FrameView::scrollbarStyleChanged(ScrollbarStyle newStyle, bool forceUpdate)
3522 if (!frame().isMainFrame())
3525 if (Page* page = frame().page())
3526 page->chrome().client().recommendedScrollbarStyleDidChange(newStyle);
3528 ScrollView::scrollbarStyleChanged(newStyle, forceUpdate);
3531 void FrameView::notifyPageThatContentAreaWillPaint() const
3533 Page* page = frame().page();
3537 contentAreaWillPaint();
3539 if (!m_scrollableAreas)
3542 for (auto& scrollableArea : *m_scrollableAreas)
3543 scrollableArea->contentAreaWillPaint();
3546 bool FrameView::scrollAnimatorEnabled() const
3548 #if ENABLE(SMOOTH_SCROLLING)
3549 if (Page* page = frame().page())
3550 return page->settings().scrollAnimatorEnabled();
3556 #if ENABLE(DASHBOARD_SUPPORT)
3557 void FrameView::updateAnnotatedRegions()
3559 Document* document = frame().document();
3560 if (!document->hasAnnotatedRegions())
3562 Vector<AnnotatedRegionValue> newRegions;
3563 document->renderBox()->collectAnnotatedRegions(newRegions);
3564 if (newRegions == document->annotatedRegions())
3566 document->setAnnotatedRegions(newRegions);
3567 Page* page = frame().page();
3570 page->chrome().client().annotatedRegionsChanged();
3574 void FrameView::updateScrollCorner()
3576 RenderElement* renderer = nullptr;
3577 RefPtr<RenderStyle> cornerStyle;
3578 IntRect cornerRect = scrollCornerRect();
3580 if (!cornerRect.isEmpty()) {
3581 // Try the <body> element first as a scroll corner source.
3582 Document* doc = frame().document();
3583 Element* body = doc ? doc->bodyOrFrameset() : nullptr;
3584 if (body && body->renderer()) {
3585 renderer = body->renderer();
3586 cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), &renderer->style());
3590 // If the <body> didn't have a custom style, then the root element might.
3591 Element* docElement = doc ? doc->documentElement() : nullptr;
3592 if (docElement && docElement->renderer()) {
3593 renderer = docElement->renderer();
3594 cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), &renderer->style());
3599 // If we have an owning iframe/frame element, then it can set the custom scrollbar also.
3600 if (RenderWidget* renderer = frame().ownerRenderer())
3601 cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), &renderer->style());
3606 m_scrollCorner = nullptr;
3608 if (!m_scrollCorner) {
3609 m_scrollCorner = createRenderer<RenderScrollbarPart>(renderer->document(), cornerStyle.releaseNonNull());
3610 m_scrollCorner->initializeStyle();
3612 m_scrollCorner->setStyle(cornerStyle.releaseNonNull());
3613 invalidateScrollCorner(cornerRect);
3616 ScrollView::updateScrollCorner();
3619 void FrameView::paintScrollCorner(GraphicsContext* context, const IntRect& cornerRect)
3621 if (context->updatingControlTints()) {
3622 updateScrollCorner();
3626 if (m_scrollCorner)