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, 2005, 2006, 2007, 2008, 2013 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 "DocumentMarkerController.h"
39 #include "EventHandler.h"
40 #include "FloatRect.h"
41 #include "FocusController.h"
42 #include "FontCache.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 "HTMLDocument.h"
50 #include "HTMLFrameElement.h"
51 #include "HTMLFrameSetElement.h"
52 #include "HTMLNames.h"
53 #include "HTMLPlugInImageElement.h"
54 #include "InspectorClient.h"
55 #include "InspectorController.h"
56 #include "InspectorInstrumentation.h"
58 #include "MainFrame.h"
59 #include "MemoryCache.h"
60 #include "MemoryPressureHandler.h"
61 #include "OverflowEvent.h"
62 #include "ProgressTracker.h"
63 #include "RenderEmbeddedObject.h"
64 #include "RenderFullScreen.h"
65 #include "RenderIFrame.h"
66 #include "RenderLayer.h"
67 #include "RenderLayerBacking.h"
68 #include "RenderLayerCompositor.h"
69 #include "RenderSVGRoot.h"
70 #include "RenderScrollbar.h"
71 #include "RenderScrollbarPart.h"
72 #include "RenderStyle.h"
73 #include "RenderText.h"
74 #include "RenderTheme.h"
75 #include "RenderView.h"
76 #include "RenderWidget.h"
77 #include "SVGDocument.h"
78 #include "SVGSVGElement.h"
79 #include "ScrollAnimator.h"
80 #include "ScrollingCoordinator.h"
82 #include "StyleResolver.h"
83 #include "TextResourceDecoder.h"
84 #include "TextStream.h"
85 #include "TiledBacking.h"
87 #include <wtf/CurrentTime.h>
89 #include <wtf/TemporaryChange.h>
91 #if USE(TILED_BACKING_STORE)
92 #include "TiledBackingStore.h"
95 #if ENABLE(TEXT_AUTOSIZING)
96 #include "TextAutosizer.h"
100 #include "DocumentLoader.h"
101 #include "LegacyTileCache.h"
102 #include "MemoryCache.h"
103 #include "MemoryPressureHandler.h"
104 #include "SystemMemory.h"
107 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
108 #include "HTMLMediaElement.h"
113 using namespace HTMLNames;
115 double FrameView::sCurrentPaintTimeStamp = 0.0;
117 // The maximum number of updateEmbeddedObjects iterations that should be done before returning.
118 static const unsigned maxUpdateEmbeddedObjectsIterations = 2;
120 static RenderLayer::UpdateLayerPositionsFlags updateLayerPositionFlags(RenderLayer* layer, bool isRelayoutingSubtree, bool didFullRepaint)
122 RenderLayer::UpdateLayerPositionsFlags flags = RenderLayer::defaultFlags;
123 if (didFullRepaint) {
124 flags &= ~RenderLayer::CheckForRepaint;
125 flags |= RenderLayer::NeedsFullRepaintInBacking;
127 if (isRelayoutingSubtree && (layer->isPaginated() || layer->enclosingPaginationLayer()))
128 flags |= RenderLayer::UpdatePagination;
132 Pagination::Mode paginationModeForRenderStyle(const RenderStyle& style)
134 EOverflow overflow = style.overflowY();
135 if (overflow != OPAGEDX && overflow != OPAGEDY)
136 return Pagination::Unpaginated;
138 bool isHorizontalWritingMode = style.isHorizontalWritingMode();
139 TextDirection textDirection = style.direction();
140 WritingMode writingMode = style.writingMode();
142 // paged-x always corresponds to LeftToRightPaginated or RightToLeftPaginated. If the WritingMode
143 // is horizontal, then we use TextDirection to choose between those options. If the WritingMode
144 // is vertical, then the direction of the verticality dictates the choice.
145 if (overflow == OPAGEDX) {
146 if ((isHorizontalWritingMode && textDirection == LTR) || writingMode == LeftToRightWritingMode)
147 return Pagination::LeftToRightPaginated;
148 return Pagination::RightToLeftPaginated;
151 // paged-y always corresponds to TopToBottomPaginated or BottomToTopPaginated. If the WritingMode
152 // is horizontal, then the direction of the horizontality dictates the choice. If the WritingMode
153 // is vertical, then we use TextDirection to choose between those options.
154 if (writingMode == TopToBottomWritingMode || (!isHorizontalWritingMode && textDirection == RTL))
155 return Pagination::TopToBottomPaginated;
156 return Pagination::BottomToTopPaginated;
159 FrameView::FrameView(Frame& frame)
161 , m_canHaveScrollbars(true)
162 , m_layoutTimer(this, &FrameView::layoutTimerFired)
164 , m_layoutPhase(OutsideLayout)
165 , m_inSynchronousPostLayout(false)
166 , m_postLayoutTasksTimer(this, &FrameView::postLayoutTimerFired)
167 , m_isTransparent(false)
168 , m_baseBackgroundColor(Color::white)
169 , m_mediaType("screen")
170 , m_overflowStatusDirty(true)
171 , m_viewportRenderer(0)
172 , m_wasScrolledByUser(false)
173 , m_inProgrammaticScroll(false)
174 , m_safeToPropagateScrollToParent(true)
175 , m_isTrackingRepaints(false)
176 , m_shouldUpdateWhileOffscreen(true)
177 , m_exposedRect(FloatRect::infiniteRect())
178 , m_deferSetNeedsLayouts(0)
179 , m_setNeedsLayoutWasDeferred(false)
180 , m_speculativeTilingEnabled(false)
181 , m_speculativeTilingEnableTimer(this, &FrameView::speculativeTilingEnableTimerFired)
183 , m_useCustomFixedPositionLayoutRect(false)
185 , m_hasOverrideViewportSize(false)
186 , m_shouldAutoSize(false)
187 , m_inAutoSize(false)
188 , m_didRunAutosize(false)
189 , m_autoSizeFixedMinimumHeight(0)
192 , m_milestonesPendingPaint(0)
193 , m_visualUpdatesAllowedByClient(true)
194 , m_scrollPinningBehavior(DoNotPin)
198 if (frame.isMainFrame()) {
199 ScrollableArea::setVerticalScrollElasticity(m_frame->page() ? m_frame->page()->verticalScrollElasticity() : ScrollElasticityAllowed);
200 ScrollableArea::setHorizontalScrollElasticity(m_frame->page() ? m_frame->page()->horizontalScrollElasticity() : ScrollElasticityAllowed);
204 PassRefPtr<FrameView> FrameView::create(Frame& frame)
206 RefPtr<FrameView> view = adoptRef(new FrameView(frame));
208 return view.release();
211 PassRefPtr<FrameView> FrameView::create(Frame& frame, const IntSize& initialSize)
213 RefPtr<FrameView> view = adoptRef(new FrameView(frame));
214 view->Widget::setFrameRect(IntRect(view->location(), initialSize));
216 return view.release();
219 FrameView::~FrameView()
221 if (m_postLayoutTasksTimer.isActive())
222 m_postLayoutTasksTimer.stop();
224 removeFromAXObjectCache();
227 // Custom scrollbars should already be destroyed at this point
228 ASSERT(!horizontalScrollbar() || !horizontalScrollbar()->isCustomScrollbar());
229 ASSERT(!verticalScrollbar() || !verticalScrollbar()->isCustomScrollbar());
231 setHasHorizontalScrollbar(false); // Remove native scrollbars now before we lose the connection to the HostWindow.
232 setHasVerticalScrollbar(false);
234 ASSERT(!m_scrollCorner);
236 ASSERT(frame().view() != this || !frame().contentRenderer());
239 void FrameView::reset()
241 m_cannotBlitToWindow = false;
242 m_isOverlapped = false;
243 m_contentIsOpaque = false;
246 m_layoutTimer.stop();
248 m_delayedLayout = false;
249 m_needsFullRepaint = true;
250 m_layoutSchedulingEnabled = true;
251 m_layoutPhase = OutsideLayout;
252 m_inSynchronousPostLayout = false;
254 m_nestedLayoutCount = 0;
255 m_postLayoutTasksTimer.stop();
256 m_firstLayout = true;
257 m_firstLayoutCallbackPending = false;
258 m_wasScrolledByUser = false;
259 m_safeToPropagateScrollToParent = true;
260 m_lastViewportSize = IntSize();
261 m_lastZoomFactor = 1.0f;
262 m_isTrackingRepaints = false;
263 m_trackedRepaintRects.clear();
265 m_paintBehavior = PaintBehaviorNormal;
266 m_isPainting = false;
267 m_visuallyNonEmptyCharacterCount = 0;
268 m_visuallyNonEmptyPixelCount = 0;
269 m_isVisuallyNonEmpty = false;
270 m_firstVisuallyNonEmptyLayoutCallbackPending = true;
271 m_maintainScrollPositionAnchor = 0;
274 void FrameView::removeFromAXObjectCache()
276 if (AXObjectCache* cache = axObjectCache())
280 void FrameView::resetScrollbars()
282 // Reset the document's scrollbars back to our defaults before we yield the floor.
283 m_firstLayout = true;
284 setScrollbarsSuppressed(true);
285 if (m_canHaveScrollbars)
286 setScrollbarModes(ScrollbarAuto, ScrollbarAuto);
288 setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff);
289 setScrollbarsSuppressed(false);
292 void FrameView::resetScrollbarsAndClearContentsSize()
296 setScrollbarsSuppressed(true);
297 setContentsSize(IntSize());
298 setScrollbarsSuppressed(false);
301 void FrameView::init()
305 m_margins = LayoutSize(-1, -1); // undefined
306 m_size = LayoutSize();
308 // Propagate the marginwidth/height and scrolling modes to the view.
309 Element* ownerElement = frame().ownerElement();
310 if (ownerElement && (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag))) {
311 HTMLFrameElementBase* frameElt = toHTMLFrameElementBase(ownerElement);
312 if (frameElt->scrollingMode() == ScrollbarAlwaysOff)
313 setCanHaveScrollbars(false);
314 LayoutUnit marginWidth = frameElt->marginWidth();
315 LayoutUnit marginHeight = frameElt->marginHeight();
316 if (marginWidth != -1)
317 setMarginWidth(marginWidth);
318 if (marginHeight != -1)
319 setMarginHeight(marginHeight);
322 Page* page = frame().page();
323 if (page && page->chrome().client().shouldPaintEntireContents())
324 setPaintsEntireContents(true);
327 void FrameView::prepareForDetach()
329 detachCustomScrollbars();
330 // When the view is no longer associated with a frame, it needs to be removed from the ax object cache
331 // right now, otherwise it won't be able to reach the topDocument()'s axObject cache later.
332 removeFromAXObjectCache();
334 if (frame().page()) {
335 if (ScrollingCoordinator* scrollingCoordinator = frame().page()->scrollingCoordinator())
336 scrollingCoordinator->willDestroyScrollableArea(this);
340 void FrameView::detachCustomScrollbars()
342 Scrollbar* horizontalBar = horizontalScrollbar();
343 if (horizontalBar && horizontalBar->isCustomScrollbar())
344 setHasHorizontalScrollbar(false);
346 Scrollbar* verticalBar = verticalScrollbar();
347 if (verticalBar && verticalBar->isCustomScrollbar())
348 setHasVerticalScrollbar(false);
350 m_scrollCorner = nullptr;
353 void FrameView::recalculateScrollbarOverlayStyle()
355 ScrollbarOverlayStyle oldOverlayStyle = scrollbarOverlayStyle();
356 ScrollbarOverlayStyle overlayStyle = ScrollbarOverlayStyleDefault;
358 Color backgroundColor = documentBackgroundColor();
359 if (backgroundColor.isValid()) {
360 // Reduce the background color from RGB to a lightness value
361 // and determine which scrollbar style to use based on a lightness
363 double hue, saturation, lightness;
364 backgroundColor.getHSL(hue, saturation, lightness);
365 if (lightness <= .5 && backgroundColor.alpha() > 0)
366 overlayStyle = ScrollbarOverlayStyleLight;
369 if (oldOverlayStyle != overlayStyle)
370 setScrollbarOverlayStyle(overlayStyle);
373 void FrameView::clear()
375 setCanBlitOnScroll(true);
379 setScrollbarsSuppressed(true);
382 // To avoid flashes of white, disable tile updates immediately when view is cleared at the beginning of a page load.
383 // Tiling will be re-enabled from UIKit via [WAKWindow setTilingMode:] when we have content to draw.
384 if (LegacyTileCache* tileCache = legacyTileCache())
385 tileCache->setTilingMode(LegacyTileCache::Disabled);
389 bool FrameView::didFirstLayout() const
391 return !m_firstLayout;
394 void FrameView::invalidateRect(const IntRect& rect)
397 if (HostWindow* window = hostWindow())
398 window->invalidateContentsAndRootView(rect);
402 RenderWidget* renderer = frame().ownerRenderer();
406 IntRect repaintRect = rect;
407 repaintRect.move(renderer->borderLeft() + renderer->paddingLeft(),
408 renderer->borderTop() + renderer->paddingTop());
409 renderer->repaintRectangle(repaintRect);
412 void FrameView::setFrameRect(const IntRect& newRect)
414 IntRect oldRect = frameRect();
415 if (newRect == oldRect)
418 #if ENABLE(TEXT_AUTOSIZING)
419 // Autosized font sizes depend on the width of the viewing area.
420 if (newRect.width() != oldRect.width()) {
421 Page* page = frame().page();
422 if (frame().isMainFrame() && page->settings().textAutosizingEnabled()) {
423 for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext())
424 frame().document()->textAutosizer()->recalculateMultipliers();
429 ScrollView::setFrameRect(newRect);
431 updateScrollableAreaSet();
433 if (RenderView* renderView = this->renderView()) {
434 if (renderView->usesCompositing())
435 renderView->compositor().frameViewDidChangeSize();
438 if (!frameFlatteningEnabled())
439 sendResizeEventIfNeeded();
442 #if ENABLE(REQUEST_ANIMATION_FRAME)
443 bool FrameView::scheduleAnimation()
445 if (HostWindow* window = hostWindow()) {
446 window->scheduleAnimation();
453 void FrameView::setMarginWidth(LayoutUnit w)
455 // make it update the rendering area when set
456 m_margins.setWidth(w);
459 void FrameView::setMarginHeight(LayoutUnit h)
461 // make it update the rendering area when set
462 m_margins.setHeight(h);
465 bool FrameView::frameFlatteningEnabled() const
467 return frame().settings().frameFlatteningEnabled();
470 bool FrameView::isFrameFlatteningValidForThisFrame() const
472 if (!frameFlatteningEnabled())
475 HTMLFrameOwnerElement* owner = frame().ownerElement();
479 // Frame flattening is valid only for <frame> and <iframe>.
480 return owner->hasTagName(frameTag) || owner->hasTagName(iframeTag);
483 bool FrameView::avoidScrollbarCreation() const
485 // with frame flattening no subframe can have scrollbars
486 // but we also cannot turn scrollbars off as we determine
487 // our flattening policy using that.
488 return isFrameFlatteningValidForThisFrame();
491 void FrameView::setCanHaveScrollbars(bool canHaveScrollbars)
493 m_canHaveScrollbars = canHaveScrollbars;
494 ScrollView::setCanHaveScrollbars(canHaveScrollbars);
497 void FrameView::updateCanHaveScrollbars()
501 scrollbarModes(hMode, vMode);
502 if (hMode == ScrollbarAlwaysOff && vMode == ScrollbarAlwaysOff)
503 setCanHaveScrollbars(false);
505 setCanHaveScrollbars(true);
508 PassRefPtr<Scrollbar> FrameView::createScrollbar(ScrollbarOrientation orientation)
510 if (!frame().settings().allowCustomScrollbarInMainFrame() && frame().isMainFrame())
511 return ScrollView::createScrollbar(orientation);
513 // FIXME: We need to update the scrollbar dynamically as documents change (or as doc elements and bodies get discovered that have custom styles).
514 Document* doc = frame().document();
516 // Try the <body> element first as a scrollbar source.
517 Element* body = doc ? doc->body() : 0;
518 if (body && body->renderer() && body->renderer()->style().hasPseudoStyle(SCROLLBAR))
519 return RenderScrollbar::createCustomScrollbar(this, orientation, body);
521 // If the <body> didn't have a custom style, then the root element might.
522 Element* docElement = doc ? doc->documentElement() : 0;
523 if (docElement && docElement->renderer() && docElement->renderer()->style().hasPseudoStyle(SCROLLBAR))
524 return RenderScrollbar::createCustomScrollbar(this, orientation, docElement);
526 // If we have an owning iframe/frame element, then it can set the custom scrollbar also.
527 RenderWidget* frameRenderer = frame().ownerRenderer();
528 if (frameRenderer && frameRenderer->style().hasPseudoStyle(SCROLLBAR))
529 return RenderScrollbar::createCustomScrollbar(this, orientation, 0, &frame());
531 // Nobody set a custom style, so we just use a native scrollbar.
532 return ScrollView::createScrollbar(orientation);
535 void FrameView::setContentsSize(const IntSize& size)
537 if (size == contentsSize())
540 m_deferSetNeedsLayouts++;
542 ScrollView::setContentsSize(size);
543 ScrollView::contentsResized();
545 Page* page = frame().page();
549 updateScrollableAreaSet();
551 page->chrome().contentsSizeChanged(&frame(), size); // Notify only.
553 ASSERT(m_deferSetNeedsLayouts);
554 m_deferSetNeedsLayouts--;
556 if (!m_deferSetNeedsLayouts)
557 m_setNeedsLayoutWasDeferred = false; // FIXME: Find a way to make the deferred layout actually happen.
560 void FrameView::adjustViewSize()
562 RenderView* renderView = this->renderView();
566 ASSERT(frame().view() == this);
568 const IntRect rect = renderView->documentRect();
569 const IntSize& size = rect.size();
570 ScrollView::setScrollOrigin(IntPoint(-rect.x(), -rect.y()), !frame().document()->printing(), size == contentsSize());
572 setContentsSize(size);
575 void FrameView::applyOverflowToViewport(RenderElement* o, ScrollbarMode& hMode, ScrollbarMode& vMode)
577 // Handle the overflow:hidden/scroll case for the body/html elements. WinIE treats
578 // overflow:hidden and overflow:scroll on <body> as applying to the document's
579 // scrollbars. The CSS2.1 draft states that HTML UAs should use the <html> or <body> element and XML/XHTML UAs should
580 // use the root element.
582 // To combat the inability to scroll on a page with overflow:hidden on the root when scaled, disregard hidden when
583 // there is a frameScaleFactor that is greater than one on the main frame. Also disregard hidden if there is a
586 bool overrideHidden = frame().isMainFrame() && ((frame().frameScaleFactor() > 1) || headerHeight() || footerHeight());
588 EOverflow overflowX = o->style().overflowX();
589 EOverflow overflowY = o->style().overflowY();
591 if (o->isSVGRoot()) {
592 // overflow is ignored in stand-alone SVG documents.
593 if (!toRenderSVGRoot(o)->isEmbeddedThroughFrameContainingSVGDocument())
602 hMode = ScrollbarAuto;
604 hMode = ScrollbarAlwaysOff;
607 hMode = ScrollbarAlwaysOn;
610 hMode = ScrollbarAuto;
613 // Don't set it at all.
620 vMode = ScrollbarAuto;
622 vMode = ScrollbarAlwaysOff;
625 vMode = ScrollbarAlwaysOn;
628 vMode = ScrollbarAuto;
631 // Don't set it at all. Values of OPAGEDX and OPAGEDY are handled by applyPaginationToViewPort().
635 m_viewportRenderer = o;
638 void FrameView::applyPaginationToViewport()
640 Document* document = frame().document();
641 auto documentElement = document->documentElement();
642 RenderElement* documentRenderer = documentElement ? documentElement->renderer() : nullptr;
643 RenderElement* documentOrBodyRenderer = documentRenderer;
644 auto body = document->body();
645 if (body && body->renderer()) {
646 if (body->hasTagName(bodyTag))
647 documentOrBodyRenderer = documentRenderer->style().overflowX() == OVISIBLE && documentElement->hasTagName(htmlTag) ? body->renderer() : documentRenderer;
650 Pagination pagination;
652 if (!documentOrBodyRenderer) {
653 setPagination(pagination);
657 EOverflow overflowY = documentOrBodyRenderer->style().overflowY();
658 if (overflowY == OPAGEDX || overflowY == OPAGEDY) {
659 pagination.mode = WebCore::paginationModeForRenderStyle(documentOrBodyRenderer->style());
660 pagination.gap = static_cast<unsigned>(documentOrBodyRenderer->style().columnGap());
663 setPagination(pagination);
666 void FrameView::calculateScrollbarModesForLayout(ScrollbarMode& hMode, ScrollbarMode& vMode, ScrollbarModesCalculationStrategy strategy)
668 m_viewportRenderer = 0;
670 const HTMLFrameOwnerElement* owner = frame().ownerElement();
671 if (owner && (owner->scrollingMode() == ScrollbarAlwaysOff)) {
672 hMode = ScrollbarAlwaysOff;
673 vMode = ScrollbarAlwaysOff;
677 if (m_canHaveScrollbars || strategy == RulesFromWebContentOnly) {
678 hMode = ScrollbarAuto;
679 vMode = ScrollbarAuto;
681 hMode = ScrollbarAlwaysOff;
682 vMode = ScrollbarAlwaysOff;
686 Document* document = frame().document();
687 auto documentElement = document->documentElement();
688 RenderElement* rootRenderer = documentElement ? documentElement->renderer() : nullptr;
689 auto body = document->body();
690 if (body && body->renderer()) {
691 if (body->hasTagName(framesetTag) && !frameFlatteningEnabled()) {
692 vMode = ScrollbarAlwaysOff;
693 hMode = ScrollbarAlwaysOff;
694 } else if (body->hasTagName(bodyTag)) {
695 // It's sufficient to just check the X overflow,
696 // since it's illegal to have visible in only one direction.
697 RenderElement* o = rootRenderer->style().overflowX() == OVISIBLE && document->documentElement()->hasTagName(htmlTag) ? body->renderer() : rootRenderer;
698 applyOverflowToViewport(o, hMode, vMode);
700 } else if (rootRenderer)
701 applyOverflowToViewport(rootRenderer, hMode, vMode);
705 void FrameView::updateCompositingLayersAfterStyleChange()
707 RenderView* renderView = this->renderView();
711 // If we expect to update compositing after an incipient layout, don't do so here.
712 if (inPreLayoutStyleUpdate() || layoutPending() || renderView->needsLayout())
715 RenderLayerCompositor& compositor = renderView->compositor();
716 // This call will make sure the cached hasAcceleratedCompositing is updated from the pref
717 compositor.cacheAcceleratedCompositingFlags();
718 compositor.updateCompositingLayers(CompositingUpdateAfterStyleChange);
721 void FrameView::updateCompositingLayersAfterLayout()
723 RenderView* renderView = this->renderView();
727 // This call will make sure the cached hasAcceleratedCompositing is updated from the pref
728 renderView->compositor().cacheAcceleratedCompositingFlags();
729 renderView->compositor().updateCompositingLayers(CompositingUpdateAfterLayout);
732 void FrameView::clearBackingStores()
734 RenderView* renderView = this->renderView();
738 RenderLayerCompositor& compositor = renderView->compositor();
739 ASSERT(compositor.inCompositingMode());
740 compositor.enableCompositingMode(false);
741 compositor.clearBackingForAllLayers();
744 void FrameView::restoreBackingStores()
746 RenderView* renderView = this->renderView();
750 RenderLayerCompositor& compositor = renderView->compositor();
751 compositor.enableCompositingMode(true);
752 compositor.updateCompositingLayers(CompositingUpdateAfterLayout);
755 GraphicsLayer* FrameView::layerForScrolling() const
757 RenderView* renderView = this->renderView();
760 return renderView->compositor().scrollLayer();
763 GraphicsLayer* FrameView::layerForHorizontalScrollbar() const
765 RenderView* renderView = this->renderView();
768 return renderView->compositor().layerForHorizontalScrollbar();
771 GraphicsLayer* FrameView::layerForVerticalScrollbar() const
773 RenderView* renderView = this->renderView();
776 return renderView->compositor().layerForVerticalScrollbar();
779 GraphicsLayer* FrameView::layerForScrollCorner() const
781 RenderView* renderView = this->renderView();
784 return renderView->compositor().layerForScrollCorner();
787 TiledBacking* FrameView::tiledBacking() const
789 RenderView* renderView = this->renderView();
793 RenderLayerBacking* backing = renderView->layer()->backing();
797 return backing->graphicsLayer()->tiledBacking();
800 uint64_t FrameView::scrollLayerID() const
802 RenderView* renderView = this->renderView();
806 RenderLayerBacking* backing = renderView->layer()->backing();
810 return backing->scrollingNodeID();
813 ScrollableArea* FrameView::scrollableAreaForScrollLayerID(uint64_t nodeID) const
815 RenderView* renderView = this->renderView();
819 return renderView->compositor().scrollableAreaForScrollLayerID(nodeID);
822 #if ENABLE(RUBBER_BANDING)
823 GraphicsLayer* FrameView::layerForOverhangAreas() const
825 RenderView* renderView = this->renderView();
828 return renderView->compositor().layerForOverhangAreas();
831 GraphicsLayer* FrameView::setWantsLayerForTopOverHangArea(bool wantsLayer) const
833 RenderView* renderView = this->renderView();
837 return renderView->compositor().updateLayerForTopOverhangArea(wantsLayer);
840 GraphicsLayer* FrameView::setWantsLayerForBottomOverHangArea(bool wantsLayer) const
842 RenderView* renderView = this->renderView();
846 return renderView->compositor().updateLayerForBottomOverhangArea(wantsLayer);
849 #endif // ENABLE(RUBBER_BANDING)
851 bool FrameView::flushCompositingStateForThisFrame(Frame* rootFrameForFlush)
853 RenderView* renderView = this->renderView();
855 return true; // We don't want to keep trying to update layers if we have no renderer.
857 ASSERT(frame().view() == this);
859 // If we sync compositing layers when a layout is pending, we may cause painting of compositing
860 // layer content to occur before layout has happened, which will cause paintContents() to bail.
865 if (LegacyTileCache* tileCache = legacyTileCache())
866 tileCache->doPendingRepaints();
869 renderView->compositor().flushPendingLayerChanges(rootFrameForFlush == &frame());
874 void FrameView::setNeedsOneShotDrawingSynchronization()
876 if (Page* page = frame().page())
877 page->chrome().client().setNeedsOneShotDrawingSynchronization();
880 GraphicsLayer* FrameView::graphicsLayerForPlatformWidget(PlatformWidget platformWidget)
882 // To find the Widget that corresponds with platformWidget we have to do a linear
883 // search of our child widgets.
884 Widget* foundWidget = nullptr;
885 for (auto& widget : children()) {
886 if (widget->platformWidget() != platformWidget)
888 foundWidget = widget.get();
895 auto* renderWidget = RenderWidget::find(foundWidget);
899 RenderLayer* widgetLayer = renderWidget->layer();
900 if (!widgetLayer || !widgetLayer->isComposited())
903 return widgetLayer->backing()->parentForSublayers();
906 void FrameView::scheduleLayerFlushAllowingThrottling()
908 RenderView* view = this->renderView();
911 view->compositor().scheduleLayerFlush(true /* canThrottle */);
914 void FrameView::setHeaderHeight(int headerHeight)
917 ASSERT(frame().isMainFrame());
918 m_headerHeight = headerHeight;
920 if (RenderView* renderView = this->renderView())
921 renderView->setNeedsLayout();
924 void FrameView::setFooterHeight(int footerHeight)
927 ASSERT(frame().isMainFrame());
928 m_footerHeight = footerHeight;
930 if (RenderView* renderView = this->renderView())
931 renderView->setNeedsLayout();
934 float FrameView::topContentInset() const
936 if (!frame().isMainFrame())
939 Page* page = frame().page();
940 return page ? page->topContentInset() : 0;
943 void FrameView::topContentInsetDidChange()
945 RenderView* renderView = this->renderView();
951 updateScrollbars(scrollOffset());
952 if (renderView->usesCompositing())
953 renderView->compositor().frameViewDidChangeSize();
956 bool FrameView::hasCompositedContent() const
958 if (RenderView* renderView = this->renderView())
959 return renderView->compositor().inCompositingMode();
963 bool FrameView::hasCompositedContentIncludingDescendants() const
965 for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) {
966 RenderView* renderView = frame->contentRenderer();
967 if (RenderLayerCompositor* compositor = renderView ? &renderView->compositor() : 0) {
968 if (compositor->inCompositingMode())
971 if (!RenderLayerCompositor::allowsIndependentlyCompositedFrames(this))
978 bool FrameView::hasCompositingAncestor() const
980 for (Frame* frame = this->frame().tree().parent(); frame; frame = frame->tree().parent()) {
981 if (FrameView* view = frame->view()) {
982 if (view->hasCompositedContent())
989 // Sometimes (for plug-ins) we need to eagerly go into compositing mode.
990 void FrameView::enterCompositingMode()
992 if (RenderView* renderView = this->renderView()) {
993 renderView->compositor().enableCompositingMode();
995 renderView->compositor().scheduleCompositingLayerUpdate();
999 bool FrameView::isEnclosedInCompositingLayer() const
1001 auto frameOwnerRenderer = frame().ownerRenderer();
1002 if (frameOwnerRenderer && frameOwnerRenderer->containerForRepaint())
1005 if (FrameView* parentView = parentFrameView())
1006 return parentView->isEnclosedInCompositingLayer();
1010 bool FrameView::flushCompositingStateIncludingSubframes()
1012 bool allFramesFlushed = flushCompositingStateForThisFrame(&frame());
1014 for (Frame* child = frame().tree().firstChild(); child; child = child->tree().traverseNext(&frame())) {
1015 bool flushed = child->view()->flushCompositingStateForThisFrame(&frame());
1016 allFramesFlushed &= flushed;
1018 return allFramesFlushed;
1021 bool FrameView::isSoftwareRenderable() const
1023 RenderView* renderView = this->renderView();
1024 return !renderView || !renderView->compositor().has3DContent();
1027 void FrameView::didMoveOnscreen()
1029 contentAreaDidShow();
1032 void FrameView::willMoveOffscreen()
1034 contentAreaDidHide();
1037 void FrameView::setIsInWindow(bool isInWindow)
1039 if (RenderView* renderView = this->renderView())
1040 renderView->setIsInWindow(isInWindow);
1043 RenderObject* FrameView::layoutRoot(bool onlyDuringLayout) const
1045 return onlyDuringLayout && layoutPending() ? 0 : m_layoutRoot;
1048 inline void FrameView::forceLayoutParentViewIfNeeded()
1050 RenderWidget* ownerRenderer = frame().ownerRenderer();
1054 RenderBox* contentBox = embeddedContentBox();
1058 RenderSVGRoot* svgRoot = toRenderSVGRoot(contentBox);
1059 if (svgRoot->everHadLayout() && !svgRoot->needsLayout())
1062 // If the embedded SVG document appears the first time, the ownerRenderer has already finished
1063 // layout without knowing about the existence of the embedded SVG document, because RenderReplaced
1064 // embeddedContentBox() returns 0, as long as the embedded document isn't loaded yet. Before
1065 // bothering to lay out the SVG document, mark the ownerRenderer needing layout and ask its
1066 // FrameView for a layout. After that the RenderEmbeddedObject (ownerRenderer) carries the
1067 // correct size, which RenderSVGRoot::computeReplacedLogicalWidth/Height rely on, when laying
1068 // out for the first time, or when the RenderSVGRoot size has changed dynamically (eg. via <script>).
1069 Ref<FrameView> frameView(ownerRenderer->view().frameView());
1071 // Mark the owner renderer as needing layout.
1072 ownerRenderer->setNeedsLayoutAndPrefWidthsRecalc();
1074 // Synchronously enter layout, to layout the view containing the host object/embed/iframe.
1075 frameView->layout();
1078 void FrameView::layout(bool allowSubtree)
1083 // Protect the view from being deleted during layout (in recalcStyle).
1084 Ref<FrameView> protect(*this);
1086 // Many of the tasks performed during layout can cause this function to be re-entered,
1087 // so save the layout phase now and restore it on exit.
1088 TemporaryChange<LayoutPhase> layoutPhaseRestorer(m_layoutPhase, InPreLayout);
1090 // Every scroll that happens during layout is programmatic.
1091 TemporaryChange<bool> changeInProgrammaticScroll(m_inProgrammaticScroll, true);
1093 bool inChildFrameLayoutWithFrameFlattening = isInChildFrameWithFrameFlattening();
1095 if (inChildFrameLayoutWithFrameFlattening) {
1096 startLayoutAtMainFrameViewIfNeeded(allowSubtree);
1097 RenderElement* root = m_layoutRoot ? m_layoutRoot : frame().document()->renderView();
1098 if (!root || !root->needsLayout())
1103 if (updateFixedPositionLayoutRect())
1104 allowSubtree = false;
1107 m_layoutTimer.stop();
1108 m_delayedLayout = false;
1109 m_setNeedsLayoutWasDeferred = false;
1111 // we shouldn't enter layout() while painting
1112 ASSERT(!isPainting());
1116 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willLayout(&frame());
1118 if (!allowSubtree && m_layoutRoot) {
1119 m_layoutRoot->markContainingBlocksForLayout(false);
1123 ASSERT(frame().view() == this);
1124 ASSERT(frame().document());
1126 Document& document = *frame().document();
1127 ASSERT(!document.inPageCache());
1130 RenderElement* root;
1133 TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
1135 if (!m_nestedLayoutCount && !m_inSynchronousPostLayout && m_postLayoutTasksTimer.isActive() && !inChildFrameLayoutWithFrameFlattening) {
1136 // This is a new top-level layout. If there are any remaining tasks from the previous
1137 // layout, finish them now.
1138 TemporaryChange<bool> inSynchronousPostLayoutChange(m_inSynchronousPostLayout, true);
1139 performPostLayoutTasks();
1142 m_layoutPhase = InPreLayoutStyleUpdate;
1144 // Viewport-dependent media queries may cause us to need completely different style information.
1145 StyleResolver* styleResolver = document.styleResolverIfExists();
1146 if (!styleResolver || styleResolver->affectedByViewportChange()) {
1147 document.styleResolverChanged(DeferRecalcStyle);
1148 // FIXME: This instrumentation event is not strictly accurate since cached media query results do not persist across StyleResolver rebuilds.
1149 InspectorInstrumentation::mediaQueryResultChanged(&document);
1151 document.evaluateMediaQueryList();
1153 // If there is any pagination to apply, it will affect the RenderView's style, so we should
1154 // take care of that now.
1155 applyPaginationToViewport();
1157 // Always ensure our style info is up-to-date. This can happen in situations where
1158 // the layout beats any sort of style recalc update that needs to occur.
1159 document.updateStyleIfNeeded();
1160 m_layoutPhase = InPreLayout;
1162 subtree = m_layoutRoot;
1164 // If there is only one ref to this view left, then its going to be destroyed as soon as we exit,
1165 // so there's no point to continuing to layout
1169 root = subtree ? m_layoutRoot : document.renderView();
1171 // FIXME: Do we need to set m_size here?
1175 // Close block here so we can set up the font cache purge preventer, which we will still
1176 // want in scope even after we want m_layoutSchedulingEnabled to be restored again.
1177 // The next block sets m_layoutSchedulingEnabled back to false once again.
1180 FontCachePurgePreventer fontCachePurgePreventer;
1183 ++m_nestedLayoutCount;
1186 TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
1188 if (!m_layoutRoot) {
1189 HTMLElement* body = document.body();
1190 if (body && body->renderer()) {
1191 if (body->hasTagName(framesetTag) && !frameFlatteningEnabled()) {
1192 body->renderer()->setChildNeedsLayout();
1193 } else if (body->hasTagName(bodyTag)) {
1194 if (!m_firstLayout && m_size.height() != layoutHeight() && body->renderer()->enclosingBox()->stretchesToViewport())
1195 body->renderer()->setChildNeedsLayout();
1199 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1200 if (m_firstLayout && !frame().ownerElement())
1201 printf("Elapsed time before first layout: %lld\n", document.elapsedTime().count());
1205 autoSizeIfEnabled();
1207 m_needsFullRepaint = !subtree && (m_firstLayout || toRenderView(*root).printing());
1210 ScrollbarMode hMode;
1211 ScrollbarMode vMode;
1212 calculateScrollbarModesForLayout(hMode, vMode);
1214 if (m_firstLayout || (hMode != horizontalScrollbarMode() || vMode != verticalScrollbarMode())) {
1215 if (m_firstLayout) {
1216 setScrollbarsSuppressed(true);
1218 m_firstLayout = false;
1219 m_firstLayoutCallbackPending = true;
1220 if (useFixedLayout() && !fixedLayoutSize().isEmpty() && delegatesScrolling())
1221 m_lastViewportSize = fixedLayoutSize();
1223 m_lastViewportSize = visibleContentRectIncludingScrollbars().size();
1225 m_lastZoomFactor = root->style().zoom();
1227 // Set the initial vMode to AlwaysOn if we're auto.
1228 if (vMode == ScrollbarAuto)
1229 setVerticalScrollbarMode(ScrollbarAlwaysOn); // This causes a vertical scrollbar to appear.
1230 // Set the initial hMode to AlwaysOff if we're auto.
1231 if (hMode == ScrollbarAuto)
1232 setHorizontalScrollbarMode(ScrollbarAlwaysOff); // This causes a horizontal scrollbar to disappear.
1234 setScrollbarModes(hMode, vMode);
1235 setScrollbarsSuppressed(false, true);
1237 setScrollbarModes(hMode, vMode);
1240 LayoutSize oldSize = m_size;
1242 m_size = layoutSize();
1244 if (oldSize != m_size) {
1245 m_needsFullRepaint = true;
1246 if (!m_firstLayout) {
1247 RenderBox* rootRenderer = document.documentElement() ? document.documentElement()->renderBox() : 0;
1248 RenderBox* bodyRenderer = rootRenderer && document.body() ? document.body()->renderBox() : 0;
1249 if (bodyRenderer && bodyRenderer->stretchesToViewport())
1250 bodyRenderer->setChildNeedsLayout();
1251 else if (rootRenderer && rootRenderer->stretchesToViewport())
1252 rootRenderer->setChildNeedsLayout();
1256 m_layoutPhase = InPreLayout;
1259 layer = root->enclosingLayer();
1261 bool disableLayoutState = false;
1263 disableLayoutState = root->view().shouldDisableLayoutStateForSubtree(root);
1264 root->view().pushLayoutState(*root);
1266 LayoutStateDisabler layoutStateDisabler(disableLayoutState ? &root->view() : 0);
1267 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(&root->view());
1269 ASSERT(m_layoutPhase == InPreLayout);
1270 m_layoutPhase = InLayout;
1272 forceLayoutParentViewIfNeeded();
1274 ASSERT(m_layoutPhase == InLayout);
1277 #if ENABLE(IOS_TEXT_AUTOSIZING)
1278 float minZoomFontSize = frame().settings().minimumZoomFontSize();
1279 float visWidth = frame().page()->textAutosizingWidth();
1280 if (minZoomFontSize && visWidth && !root->view().printing()) {
1281 root->adjustComputedFontSizesOnBlocks(minZoomFontSize, visWidth);
1282 bool needsLayout = root->needsLayout();
1287 #if ENABLE(TEXT_AUTOSIZING)
1288 if (document.textAutosizer()->processSubtree(root) && root->needsLayout())
1292 ASSERT(m_layoutPhase == InLayout);
1295 root->view().popLayoutState(*root);
1299 // Close block here to end the scope of changeSchedulingEnabled and layoutStateDisabler.
1302 m_layoutPhase = InViewSizeAdjust;
1304 bool neededFullRepaint = m_needsFullRepaint;
1306 if (!subtree && !toRenderView(*root).printing())
1309 m_layoutPhase = InPostLayout;
1311 m_needsFullRepaint = neededFullRepaint;
1313 // Now update the positions of all layers.
1314 if (m_needsFullRepaint)
1315 root->view().repaintRootContents();
1317 layer->updateLayerPositionsAfterLayout(renderView()->layer(), updateLayerPositionFlags(layer, subtree, m_needsFullRepaint));
1319 updateCompositingLayersAfterLayout();
1323 #if PLATFORM(COCOA) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(EFL)
1324 if (AXObjectCache* cache = root->document().existingAXObjectCache())
1325 cache->postNotification(root, AXObjectCache::AXLayoutComplete);
1328 #if ENABLE(DASHBOARD_SUPPORT)
1329 updateAnnotatedRegions();
1332 #if ENABLE(IOS_TOUCH_EVENTS)
1333 document.dirtyTouchEventRects();
1336 ASSERT(!root->needsLayout());
1338 updateCanBlitOnScrollRecursively();
1340 if (document.hasListenerType(Document::OVERFLOWCHANGED_LISTENER))
1341 updateOverflowStatus(layoutWidth() < contentsWidth(), layoutHeight() < contentsHeight());
1343 if (!m_postLayoutTasksTimer.isActive()) {
1344 if (!m_inSynchronousPostLayout) {
1345 if (inChildFrameLayoutWithFrameFlattening)
1346 updateWidgetPositions();
1348 TemporaryChange<bool> inSynchronousPostLayoutChange(m_inSynchronousPostLayout, true);
1349 performPostLayoutTasks(); // Calls resumeScheduledEvents().
1353 if (!m_postLayoutTasksTimer.isActive() && (needsLayout() || m_inSynchronousPostLayout || inChildFrameLayoutWithFrameFlattening)) {
1354 // If we need layout or are already in a synchronous call to postLayoutTasks(),
1355 // defer widget updates and event dispatch until after we return. postLayoutTasks()
1356 // can make us need to update again, and we can get stuck in a nasty cycle unless
1357 // we call it through the timer here.
1358 m_postLayoutTasksTimer.startOneShot(0);
1364 InspectorInstrumentation::didLayout(cookie, root);
1366 --m_nestedLayoutCount;
1369 RenderBox* FrameView::embeddedContentBox() const
1371 RenderView* renderView = this->renderView();
1375 RenderObject* firstChild = renderView->firstChild();
1376 if (!firstChild || !firstChild->isBox())
1379 // Curently only embedded SVG documents participate in the size-negotiation logic.
1380 if (toRenderBox(firstChild)->isSVGRoot())
1381 return toRenderBox(firstChild);
1386 void FrameView::addEmbeddedObjectToUpdate(RenderEmbeddedObject& embeddedObject)
1388 if (!m_embeddedObjectsToUpdate)
1389 m_embeddedObjectsToUpdate = std::make_unique<ListHashSet<RenderEmbeddedObject*>>();
1391 HTMLFrameOwnerElement& element = embeddedObject.frameOwnerElement();
1392 if (isHTMLObjectElement(element) || isHTMLEmbedElement(element)) {
1393 // Tell the DOM element that it needs a widget update.
1394 HTMLPlugInImageElement& pluginElement = toHTMLPlugInImageElement(element);
1395 if (!pluginElement.needsCheckForSizeChange())
1396 pluginElement.setNeedsWidgetUpdate(true);
1399 m_embeddedObjectsToUpdate->add(&embeddedObject);
1402 void FrameView::removeEmbeddedObjectToUpdate(RenderEmbeddedObject& embeddedObject)
1404 if (!m_embeddedObjectsToUpdate)
1407 m_embeddedObjectsToUpdate->remove(&embeddedObject);
1410 void FrameView::setMediaType(const String& mediaType)
1412 m_mediaType = mediaType;
1415 String FrameView::mediaType() const
1417 // See if we have an override type.
1418 String overrideType = frame().loader().client().overrideMediaType();
1419 InspectorInstrumentation::applyEmulatedMedia(&frame(), &overrideType);
1420 if (!overrideType.isNull())
1421 return overrideType;
1425 void FrameView::adjustMediaTypeForPrinting(bool printing)
1428 if (m_mediaTypeWhenNotPrinting.isNull())
1429 m_mediaTypeWhenNotPrinting = mediaType();
1430 setMediaType("print");
1432 if (!m_mediaTypeWhenNotPrinting.isNull())
1433 setMediaType(m_mediaTypeWhenNotPrinting);
1434 m_mediaTypeWhenNotPrinting = String();
1438 bool FrameView::useSlowRepaints(bool considerOverlap) const
1440 bool mustBeSlow = hasSlowRepaintObjects() || (platformWidget() && hasViewportConstrainedObjects());
1442 // FIXME: WidgetMac.mm makes the assumption that useSlowRepaints ==
1443 // m_contentIsOpaque, so don't take the fast path for composited layers
1444 // if they are a platform widget in order to get painting correctness
1445 // for transparent layers. See the comment in WidgetMac::paint.
1446 if (contentsInCompositedLayer() && !platformWidget())
1449 bool isOverlapped = m_isOverlapped && considerOverlap;
1451 if (mustBeSlow || m_cannotBlitToWindow || isOverlapped || !m_contentIsOpaque)
1454 if (FrameView* parentView = parentFrameView())
1455 return parentView->useSlowRepaints(considerOverlap);
1460 bool FrameView::useSlowRepaintsIfNotOverlapped() const
1462 return useSlowRepaints(false);
1465 void FrameView::updateCanBlitOnScrollRecursively()
1467 for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) {
1468 if (FrameView* view = frame->view())
1469 view->setCanBlitOnScroll(!view->useSlowRepaints());
1473 bool FrameView::contentsInCompositedLayer() const
1475 RenderView* renderView = this->renderView();
1476 if (renderView && renderView->isComposited()) {
1477 GraphicsLayer* layer = renderView->layer()->backing()->graphicsLayer();
1478 if (layer && layer->drawsContent())
1485 void FrameView::setCannotBlitToWindow()
1487 m_cannotBlitToWindow = true;
1488 updateCanBlitOnScrollRecursively();
1491 void FrameView::addSlowRepaintObject(RenderElement* o)
1493 bool hadSlowRepaintObjects = hasSlowRepaintObjects();
1495 if (!m_slowRepaintObjects)
1496 m_slowRepaintObjects = std::make_unique<HashSet<RenderElement*>>();
1498 m_slowRepaintObjects->add(o);
1500 if (!hadSlowRepaintObjects) {
1501 updateCanBlitOnScrollRecursively();
1503 if (Page* page = frame().page()) {
1504 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1505 scrollingCoordinator->frameViewHasSlowRepaintObjectsDidChange(this);
1510 void FrameView::removeSlowRepaintObject(RenderElement* o)
1512 if (!m_slowRepaintObjects)
1515 m_slowRepaintObjects->remove(o);
1516 if (m_slowRepaintObjects->isEmpty()) {
1517 m_slowRepaintObjects = nullptr;
1518 updateCanBlitOnScrollRecursively();
1520 if (Page* page = frame().page()) {
1521 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1522 scrollingCoordinator->frameViewHasSlowRepaintObjectsDidChange(this);
1527 void FrameView::addViewportConstrainedObject(RenderElement* object)
1529 if (!m_viewportConstrainedObjects)
1530 m_viewportConstrainedObjects = std::make_unique<ViewportConstrainedObjectSet>();
1532 if (!m_viewportConstrainedObjects->contains(object)) {
1533 m_viewportConstrainedObjects->add(object);
1534 if (platformWidget())
1535 updateCanBlitOnScrollRecursively();
1537 if (Page* page = frame().page()) {
1538 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1539 scrollingCoordinator->frameViewFixedObjectsDidChange(this);
1544 void FrameView::removeViewportConstrainedObject(RenderElement* object)
1546 if (m_viewportConstrainedObjects && m_viewportConstrainedObjects->remove(object)) {
1547 if (Page* page = frame().page()) {
1548 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1549 scrollingCoordinator->frameViewFixedObjectsDidChange(this);
1552 // FIXME: In addFixedObject() we only call this if there's a platform widget,
1553 // why isn't the same check being made here?
1554 updateCanBlitOnScrollRecursively();
1558 LayoutRect FrameView::viewportConstrainedVisibleContentRect() const
1561 if (useCustomFixedPositionLayoutRect())
1562 return customFixedPositionLayoutRect();
1564 LayoutRect viewportRect = visibleContentRect();
1566 viewportRect.setLocation(toLayoutPoint(scrollOffsetForFixedPosition()));
1567 return viewportRect;
1570 LayoutRect FrameView::viewportConstrainedExtentRect() const
1573 if (platformWidget())
1574 return visibleContentRect(ScrollableArea::LegacyIOSDocumentVisibleRect);
1576 return renderView()->unscaledDocumentRect();
1578 return viewportConstrainedVisibleContentRect();
1582 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)
1584 LayoutPoint position;
1585 if (behaviorForFixed == StickToDocumentBounds)
1586 position = ScrollableArea::constrainScrollPositionForOverhang(visibleContentRect, totalContentsSize, scrollPosition, scrollOrigin, headerHeight, footerHeight);
1588 position = scrollPosition;
1589 position.setY(position.y() - headerHeight);
1592 LayoutSize maxSize = totalContentsSize - visibleContentRect.size();
1594 float dragFactorX = (fixedElementsLayoutRelativeToFrame || !maxSize.width()) ? 1 : (totalContentsSize.width() - visibleContentRect.width() * frameScaleFactor) / maxSize.width();
1595 float dragFactorY = (fixedElementsLayoutRelativeToFrame || !maxSize.height()) ? 1 : (totalContentsSize.height() - visibleContentRect.height() * frameScaleFactor) / maxSize.height();
1597 return LayoutSize(position.x() * dragFactorX / frameScaleFactor, position.y() * dragFactorY / frameScaleFactor);
1600 LayoutSize FrameView::scrollOffsetForFixedPosition() const
1602 IntRect visibleContentRect = this->visibleContentRect();
1603 IntSize totalContentsSize = this->totalContentsSize();
1604 IntPoint scrollPosition = this->scrollPosition();
1605 IntPoint scrollOrigin = this->scrollOrigin();
1606 float frameScaleFactor = frame().frameScaleFactor();
1607 ScrollBehaviorForFixedElements behaviorForFixed = scrollBehaviorForFixedElements();
1608 return scrollOffsetForFixedPosition(visibleContentRect, totalContentsSize, scrollPosition, scrollOrigin, frameScaleFactor, fixedElementsLayoutRelativeToFrame(), behaviorForFixed, headerHeight(), footerHeight());
1612 LayoutRect FrameView::rectForViewportConstrainedObjects(const LayoutRect& visibleContentRect, const LayoutSize& totalContentsSize, float frameScaleFactor, bool fixedElementsLayoutRelativeToFrame, ScrollBehaviorForFixedElements scrollBehavior)
1614 if (fixedElementsLayoutRelativeToFrame)
1615 return visibleContentRect;
1617 // We impose an lower limit on the size (so an upper limit on the scale) of
1618 // the rect used to position fixed objects so that they don't crowd into the
1619 // center of the screen at larger scales.
1620 const float constraintThresholdScale = 1.2;
1622 float maxPostionedObjectsRectScale = std::min(frameScaleFactor, constraintThresholdScale);
1624 LayoutRect viewportConstrainedObjectsRect = visibleContentRect;
1626 if (frameScaleFactor > constraintThresholdScale) {
1627 FloatRect contentRect(FloatPoint(), totalContentsSize);
1628 FloatRect viewportRect = visibleContentRect;
1630 // Scale the rect up from a point that is relative to its position in the viewport.
1631 FloatSize sizeDelta = contentRect.size() - viewportRect.size();
1633 FloatPoint scaleOrigin;
1634 scaleOrigin.setX(contentRect.x() + sizeDelta.width() > 0 ? contentRect.width() * (viewportRect.x() - contentRect.x()) / sizeDelta.width() : 0);
1635 scaleOrigin.setY(contentRect.y() + sizeDelta.height() > 0 ? contentRect.height() * (viewportRect.y() - contentRect.y()) / sizeDelta.height() : 0);
1637 AffineTransform rescaleTransform = AffineTransform::translation(scaleOrigin.x(), scaleOrigin.y());
1638 rescaleTransform.scale(frameScaleFactor / maxPostionedObjectsRectScale, frameScaleFactor / maxPostionedObjectsRectScale);
1639 rescaleTransform = CGAffineTransformTranslate(rescaleTransform, -scaleOrigin.x(), -scaleOrigin.y());
1641 viewportConstrainedObjectsRect = enclosingLayoutRect(rescaleTransform.mapRect(visibleContentRect));
1644 if (scrollBehavior == StickToDocumentBounds) {
1645 LayoutRect documentBounds(LayoutPoint(), totalContentsSize);
1646 viewportConstrainedObjectsRect.intersect(documentBounds);
1649 return viewportConstrainedObjectsRect;
1652 LayoutRect FrameView::viewportConstrainedObjectsRect() const
1654 return rectForViewportConstrainedObjects(visibleContentRect(), totalContentsSize(), frame().frameScaleFactor(), fixedElementsLayoutRelativeToFrame(), scrollBehaviorForFixedElements());
1658 IntPoint FrameView::minimumScrollPosition() const
1660 IntPoint minimumPosition(ScrollView::minimumScrollPosition());
1662 if (frame().isMainFrame() && m_scrollPinningBehavior == PinToBottom)
1663 minimumPosition.setY(maximumScrollPosition().y());
1665 return minimumPosition;
1668 IntPoint FrameView::maximumScrollPosition() const
1670 IntPoint maximumOffset(contentsWidth() - visibleWidth() - scrollOrigin().x(), totalContentsSize().height() - visibleHeight() - scrollOrigin().y());
1672 maximumOffset.clampNegativeToZero();
1674 if (frame().isMainFrame() && m_scrollPinningBehavior == PinToTop)
1675 maximumOffset.setY(minimumScrollPosition().y());
1677 return maximumOffset;
1680 bool FrameView::fixedElementsLayoutRelativeToFrame() const
1682 return frame().settings().fixedElementsLayoutRelativeToFrame();
1685 IntPoint FrameView::lastKnownMousePosition() const
1687 return frame().eventHandler().lastKnownMousePosition();
1690 bool FrameView::isHandlingWheelEvent() const
1692 return frame().eventHandler().isHandlingWheelEvent();
1695 bool FrameView::shouldSetCursor() const
1697 Page* page = frame().page();
1698 return page && page->isVisible() && page->focusController().isActive();
1701 bool FrameView::scrollContentsFastPath(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect)
1703 if (!m_viewportConstrainedObjects || m_viewportConstrainedObjects->isEmpty()) {
1704 hostWindow()->scroll(scrollDelta, rectToScroll, clipRect);
1708 const bool isCompositedContentLayer = contentsInCompositedLayer();
1710 // Get the rects of the fixed objects visible in the rectToScroll
1711 Region regionToUpdate;
1712 for (auto& renderer : *m_viewportConstrainedObjects) {
1713 if (!renderer->style().hasViewportConstrainedPosition())
1715 if (renderer->isComposited())
1718 // Fixed items should always have layers.
1719 ASSERT(renderer->hasLayer());
1720 RenderLayer* layer = toRenderBoxModelObject(renderer)->layer();
1722 if (layer->viewportConstrainedNotCompositedReason() == RenderLayer::NotCompositedForBoundsOutOfView
1723 || layer->viewportConstrainedNotCompositedReason() == RenderLayer::NotCompositedForNoVisibleContent) {
1724 // Don't invalidate for invisible fixed layers.
1728 #if ENABLE(CSS_FILTERS)
1729 if (layer->hasAncestorWithFilterOutsets()) {
1730 // If the fixed layer has a blur/drop-shadow filter applied on at least one of its parents, we cannot
1731 // scroll using the fast path, otherwise the outsets of the filter will be moved around the page.
1735 IntRect updateRect = pixelSnappedIntRect(layer->repaintRectIncludingNonCompositingDescendants());
1736 updateRect = contentsToRootView(updateRect);
1737 if (!isCompositedContentLayer && clipsRepaints())
1738 updateRect.intersect(rectToScroll);
1739 if (!updateRect.isEmpty())
1740 regionToUpdate.unite(updateRect);
1744 hostWindow()->scroll(scrollDelta, rectToScroll, clipRect);
1746 // 2) update the area of fixed objects that has been invalidated
1747 Vector<IntRect> subRectsToUpdate = regionToUpdate.rects();
1748 size_t viewportConstrainedObjectsCount = subRectsToUpdate.size();
1749 for (size_t i = 0; i < viewportConstrainedObjectsCount; ++i) {
1750 IntRect updateRect = subRectsToUpdate[i];
1751 IntRect scrolledRect = updateRect;
1752 scrolledRect.move(scrollDelta);
1753 updateRect.unite(scrolledRect);
1754 if (isCompositedContentLayer) {
1755 updateRect = rootViewToContents(updateRect);
1756 ASSERT(renderView());
1757 renderView()->layer()->setBackingNeedsRepaintInRect(updateRect);
1760 if (clipsRepaints())
1761 updateRect.intersect(rectToScroll);
1762 hostWindow()->invalidateContentsAndRootView(updateRect);
1768 void FrameView::scrollContentsSlowPath(const IntRect& updateRect)
1770 if (contentsInCompositedLayer()) {
1771 // FIXME: respect paintsEntireContents()?
1772 IntRect updateRect = visibleContentRect(LegacyIOSDocumentVisibleRect);
1774 // Make sure to "apply" the scale factor here since we're converting from frame view
1775 // coordinates to layer backing coordinates.
1776 updateRect.scale(1 / frame().frameScaleFactor());
1778 ASSERT(renderView());
1779 renderView()->layer()->setBackingNeedsRepaintInRect(updateRect, GraphicsLayer::DoNotClipToLayer);
1782 repaintSlowRepaintObjects();
1784 if (RenderWidget* frameRenderer = frame().ownerRenderer()) {
1785 if (isEnclosedInCompositingLayer()) {
1786 LayoutRect rect(frameRenderer->borderLeft() + frameRenderer->paddingLeft(),
1787 frameRenderer->borderTop() + frameRenderer->paddingTop(),
1788 visibleWidth(), visibleHeight());
1789 frameRenderer->repaintRectangle(rect);
1794 ScrollView::scrollContentsSlowPath(updateRect);
1797 void FrameView::repaintSlowRepaintObjects()
1799 if (!m_slowRepaintObjects)
1802 // Renderers with fixed backgrounds may be in compositing layers, so we need to explicitly
1803 // repaint them after scrolling.
1804 for (auto& renderer : *m_slowRepaintObjects)
1805 renderer->repaintSlowRepaintObject();
1808 // Note that this gets called at painting time.
1809 void FrameView::setIsOverlapped(bool isOverlapped)
1811 if (isOverlapped == m_isOverlapped)
1814 m_isOverlapped = isOverlapped;
1815 updateCanBlitOnScrollRecursively();
1817 if (hasCompositedContentIncludingDescendants()) {
1818 // Overlap can affect compositing tests, so if it changes, we need to trigger
1819 // a layer update in the parent document.
1820 if (Frame* parentFrame = frame().tree().parent()) {
1821 if (RenderView* parentView = parentFrame->contentRenderer()) {
1822 RenderLayerCompositor& compositor = parentView->compositor();
1823 compositor.setCompositingLayersNeedRebuild();
1824 compositor.scheduleCompositingLayerUpdate();
1828 if (RenderLayerCompositor::allowsIndependentlyCompositedFrames(this)) {
1829 // We also need to trigger reevaluation for this and all descendant frames,
1830 // since a frame uses compositing if any ancestor is compositing.
1831 for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) {
1832 if (RenderView* view = frame->contentRenderer()) {
1833 RenderLayerCompositor& compositor = view->compositor();
1834 compositor.setCompositingLayersNeedRebuild();
1835 compositor.scheduleCompositingLayerUpdate();
1842 bool FrameView::isOverlappedIncludingAncestors() const
1847 if (FrameView* parentView = parentFrameView()) {
1848 if (parentView->isOverlapped())
1855 void FrameView::setContentIsOpaque(bool contentIsOpaque)
1857 if (contentIsOpaque == m_contentIsOpaque)
1860 m_contentIsOpaque = contentIsOpaque;
1861 updateCanBlitOnScrollRecursively();
1864 void FrameView::restoreScrollbar()
1866 setScrollbarsSuppressed(false);
1869 bool FrameView::scrollToFragment(const URL& url)
1871 // If our URL has no ref, then we have no place we need to jump to.
1872 // OTOH If CSS target was set previously, we want to set it to 0, recalc
1873 // and possibly repaint because :target pseudo class may have been
1874 // set (see bug 11321).
1875 if (!url.hasFragmentIdentifier() && !frame().document()->cssTarget())
1878 String fragmentIdentifier = url.fragmentIdentifier();
1879 if (scrollToAnchor(fragmentIdentifier))
1882 // Try again after decoding the ref, based on the document's encoding.
1883 if (TextResourceDecoder* decoder = frame().document()->decoder())
1884 return scrollToAnchor(decodeURLEscapeSequences(fragmentIdentifier, decoder->encoding()));
1889 bool FrameView::scrollToAnchor(const String& name)
1891 ASSERT(frame().document());
1893 if (!frame().document()->haveStylesheetsLoaded()) {
1894 frame().document()->setGotoAnchorNeededAfterStylesheetsLoad(true);
1898 frame().document()->setGotoAnchorNeededAfterStylesheetsLoad(false);
1900 Element* anchorElement = frame().document()->findAnchor(name);
1902 // Setting to null will clear the current target.
1903 frame().document()->setCSSTarget(anchorElement);
1905 if (frame().document()->isSVGDocument()) {
1906 if (SVGSVGElement* svg = toSVGDocument(frame().document())->rootElement()) {
1907 svg->setupInitialView(name, anchorElement);
1913 // Implement the rule that "" and "top" both mean top of page as in other browsers.
1914 if (!anchorElement && !(name.isEmpty() || equalIgnoringCase(name, "top")))
1917 maintainScrollPositionAtAnchor(anchorElement ? static_cast<Node*>(anchorElement) : frame().document());
1919 // If the anchor accepts keyboard focus, move focus there to aid users relying on keyboard navigation.
1920 if (anchorElement && anchorElement->isFocusable())
1921 frame().document()->setFocusedElement(anchorElement);
1926 void FrameView::maintainScrollPositionAtAnchor(Node* anchorNode)
1928 m_maintainScrollPositionAnchor = anchorNode;
1929 if (!m_maintainScrollPositionAnchor)
1932 // We need to update the layout before scrolling, otherwise we could
1933 // really mess things up if an anchor scroll comes at a bad moment.
1934 frame().document()->updateStyleIfNeeded();
1935 // Only do a layout if changes have occurred that make it necessary.
1936 RenderView* renderView = this->renderView();
1937 if (renderView && renderView->needsLayout())
1943 void FrameView::scrollElementToRect(Element* element, const IntRect& rect)
1945 frame().document()->updateLayoutIgnorePendingStylesheets();
1947 LayoutRect bounds = element->boundingBox();
1948 int centeringOffsetX = (rect.width() - bounds.width()) / 2;
1949 int centeringOffsetY = (rect.height() - bounds.height()) / 2;
1950 setScrollPosition(IntPoint(bounds.x() - centeringOffsetX - rect.x(), bounds.y() - centeringOffsetY - rect.y()));
1953 void FrameView::setScrollPosition(const IntPoint& scrollPoint)
1955 TemporaryChange<bool> changeInProgrammaticScroll(m_inProgrammaticScroll, true);
1956 m_maintainScrollPositionAnchor = 0;
1957 ScrollView::setScrollPosition(scrollPoint);
1960 void FrameView::delegatesScrollingDidChange()
1962 // When we switch to delgatesScrolling mode, we should destroy the scrolling/clipping layers in RenderLayerCompositor.
1963 if (hasCompositedContent())
1964 clearBackingStores();
1967 #if USE(TILED_BACKING_STORE)
1968 void FrameView::setFixedVisibleContentRect(const IntRect& visibleContentRect)
1970 bool visibleContentSizeDidChange = false;
1971 if (visibleContentRect.size() != this->fixedVisibleContentRect().size()) {
1972 // When the viewport size changes or the content is scaled, we need to
1973 // reposition the fixed and sticky positioned elements.
1974 setViewportConstrainedObjectsNeedLayout();
1975 visibleContentSizeDidChange = true;
1978 IntSize offset = scrollOffset();
1979 IntPoint oldPosition = scrollPosition();
1980 ScrollView::setFixedVisibleContentRect(visibleContentRect);
1981 if (offset != scrollOffset()) {
1982 updateLayerPositionsAfterScrolling();
1983 if (frame().page()->settings().acceleratedCompositingForFixedPositionEnabled())
1984 updateCompositingLayersAfterScrolling();
1985 IntPoint newPosition = scrollPosition();
1986 scrollAnimator()->setCurrentPosition(scrollPosition());
1987 scrollPositionChanged(oldPosition, newPosition);
1989 if (visibleContentSizeDidChange) {
1990 // Update the scroll-bars to calculate new page-step size.
1991 updateScrollbars(scrollOffset());
1993 frame().loader().client().didChangeScrollOffset();
1997 void FrameView::setViewportConstrainedObjectsNeedLayout()
1999 if (!hasViewportConstrainedObjects())
2002 for (auto& renderer : *m_viewportConstrainedObjects)
2003 renderer->setNeedsLayout();
2006 void FrameView::scrollPositionChangedViaPlatformWidget(const IntPoint& oldPosition, const IntPoint& newPosition)
2008 updateLayerPositionsAfterScrolling();
2009 updateCompositingLayersAfterScrolling();
2010 repaintSlowRepaintObjects();
2011 scrollPositionChanged(oldPosition, newPosition);
2014 void FrameView::scrollPositionChanged(const IntPoint& oldPosition, const IntPoint& newPosition)
2016 frame().eventHandler().sendScrollEvent();
2017 frame().eventHandler().dispatchFakeMouseMoveEventSoon();
2019 if (Document* document = frame().document())
2020 document->sendWillRevealEdgeEventsIfNeeded(oldPosition, newPosition, visibleContentRect(), contentsSize());
2022 if (RenderView* renderView = this->renderView()) {
2023 renderView->resumePausedImageAnimationsIfNeeded();
2024 if (renderView->usesCompositing())
2025 renderView->compositor().frameViewDidScroll();
2029 void FrameView::updateLayerPositionsAfterScrolling()
2031 // If we're scrolling as a result of updating the view size after layout, we'll update widgets and layer positions soon anyway.
2032 if (m_layoutPhase == InViewSizeAdjust)
2035 if (m_nestedLayoutCount <= 1 && hasViewportConstrainedObjects()) {
2036 if (RenderView* renderView = this->renderView()) {
2037 updateWidgetPositions();
2038 renderView->layer()->updateLayerPositionsAfterDocumentScroll();
2043 bool FrameView::shouldUpdateCompositingLayersAfterScrolling() const
2045 #if ENABLE(ASYNC_SCROLLING)
2046 // If the scrolling thread is updating the fixed elements, then the FrameView should not update them as well.
2048 Page* page = frame().page();
2052 if (&page->mainFrame() != &frame())
2055 ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator();
2056 if (!scrollingCoordinator)
2059 if (!scrollingCoordinator->supportsFixedPositionLayers())
2062 if (scrollingCoordinator->shouldUpdateScrollLayerPositionSynchronously())
2065 if (inProgrammaticScroll())
2073 void FrameView::updateCompositingLayersAfterScrolling()
2075 if (!shouldUpdateCompositingLayersAfterScrolling())
2078 if (m_nestedLayoutCount <= 1 && hasViewportConstrainedObjects()) {
2079 if (RenderView* renderView = this->renderView())
2080 renderView->compositor().updateCompositingLayers(CompositingUpdateOnScroll);
2084 bool FrameView::isRubberBandInProgress() const
2086 if (scrollbarsSuppressed())
2089 // If the scrolling thread updates the scroll position for this FrameView, then we should return
2090 // ScrollingCoordinator::isRubberBandInProgress().
2091 if (Page* page = frame().page()) {
2092 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator()) {
2093 if (!scrollingCoordinator->shouldUpdateScrollLayerPositionSynchronously())
2094 return scrollingCoordinator->isRubberBandInProgress();
2098 // If the main thread updates the scroll position for this FrameView, we should return
2099 // ScrollAnimator::isRubberBandInProgress().
2100 if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
2101 return scrollAnimator->isRubberBandInProgress();
2106 bool FrameView::requestScrollPositionUpdate(const IntPoint& position)
2108 #if ENABLE(ASYNC_SCROLLING)
2109 if (TiledBacking* tiledBacking = this->tiledBacking()) {
2110 IntRect visibleRect = visibleContentRect();
2111 visibleRect.setLocation(position);
2112 tiledBacking->prepopulateRect(visibleRect);
2115 if (Page* page = frame().page()) {
2116 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
2117 return scrollingCoordinator->requestScrollPositionUpdate(this, position);
2120 UNUSED_PARAM(position);
2126 HostWindow* FrameView::hostWindow() const
2128 if (Page* page = frame().page())
2129 return &page->chrome();
2133 void FrameView::addTrackedRepaintRect(const FloatRect& r)
2135 if (!m_isTrackingRepaints || r.isEmpty())
2138 FloatRect repaintRect = r;
2139 repaintRect.move(-scrollOffset());
2140 m_trackedRepaintRects.append(repaintRect);
2143 void FrameView::repaintContentRectangle(const IntRect& r)
2145 ASSERT(!frame().ownerElement());
2147 if (!shouldUpdate())
2150 #if USE(TILED_BACKING_STORE)
2151 if (frame().tiledBackingStore()) {
2152 frame().tiledBackingStore()->invalidate(r);
2156 ScrollView::repaintContentRectangle(r);
2159 static unsigned countRenderedCharactersInRenderObjectWithThreshold(const RenderObject& renderer, unsigned countSoFar, unsigned threshold)
2161 // FIXME: Consider writing this using RenderObject::nextInPreOrder() instead of using recursion.
2162 if (renderer.isText())
2163 countSoFar += toRenderText(renderer).text()->length();
2165 for (RenderObject* child = renderer.firstChildSlow(); child; child = child->nextSibling()) {
2166 if (countSoFar >= threshold)
2168 countSoFar = countRenderedCharactersInRenderObjectWithThreshold(*child, countSoFar, threshold);
2173 bool FrameView::renderedCharactersExceed(unsigned threshold)
2175 if (!m_frame->contentRenderer())
2177 return countRenderedCharactersInRenderObjectWithThreshold(*m_frame->contentRenderer(), 0, threshold) >= threshold;
2180 void FrameView::contentsResized()
2182 ScrollView::contentsResized();
2186 void FrameView::fixedLayoutSizeChanged()
2188 // Can be triggered before the view is set, see comment in FrameView::visibleContentsResized().
2189 // An ASSERT is triggered when a view schedules a layout before being attached to a frame.
2190 if (!frame().view())
2192 ScrollView::fixedLayoutSizeChanged();
2195 bool FrameView::shouldLayoutAfterContentsResized() const
2197 return !useFixedLayout() || useCustomFixedPositionLayoutRect();
2200 void FrameView::visibleContentsResized()
2202 // We check to make sure the view is attached to a frame() as this method can
2203 // be triggered before the view is attached by Frame::createView(...) setting
2204 // various values such as setScrollBarModes(...) for example. An ASSERT is
2205 // triggered when a view is layout before being attached to a frame().
2206 if (!frame().view())
2210 if (RenderView* root = m_frame->contentRenderer()) {
2211 if (useCustomFixedPositionLayoutRect() && hasViewportConstrainedObjects()) {
2212 setViewportConstrainedObjectsNeedLayout();
2213 // We must eagerly enter compositing mode because fixed position elements
2214 // will not have been made compositing via a preceding style change before
2215 // m_useCustomFixedPositionLayoutRect was true.
2216 root->compositor().enableCompositingMode();
2221 if (shouldLayoutAfterContentsResized() && needsLayout())
2224 if (RenderView* renderView = this->renderView()) {
2225 if (renderView->usesCompositing())
2226 renderView->compositor().frameViewDidChangeSize();
2230 void FrameView::addedOrRemovedScrollbar()
2232 if (RenderView* renderView = this->renderView()) {
2233 if (renderView->usesCompositing())
2234 renderView->compositor().frameViewDidAddOrRemoveScrollbars();
2238 void FrameView::disableLayerFlushThrottlingTemporarilyForInteraction()
2240 if (RenderView* view = renderView())
2241 view->compositor().disableLayerFlushThrottlingTemporarilyForInteraction();
2244 void FrameView::updateLayerFlushThrottlingInAllFrames()
2246 bool isMainLoadProgressing = frame().page()->progress().isMainLoadProgressing();
2247 for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) {
2248 if (RenderView* renderView = frame->contentRenderer())
2249 renderView->compositor().setLayerFlushThrottlingEnabled(isMainLoadProgressing);
2253 void FrameView::adjustTiledBackingCoverage()
2255 if (!m_speculativeTilingEnabled)
2256 enableSpeculativeTilingIfNeeded();
2258 RenderView* renderView = this->renderView();
2259 if (renderView && renderView->layer()->backing())
2260 renderView->layer()->backing()->adjustTiledBackingCoverage();
2262 if (LegacyTileCache* tileCache = legacyTileCache())
2263 tileCache->setSpeculativeTileCreationEnabled(m_speculativeTilingEnabled);
2267 static bool shouldEnableSpeculativeTilingDuringLoading(const FrameView& view)
2269 return view.isVisuallyNonEmpty() && !view.frame().page()->progress().isMainLoadProgressing();
2272 void FrameView::enableSpeculativeTilingIfNeeded()
2274 ASSERT(!m_speculativeTilingEnabled);
2275 if (m_wasScrolledByUser) {
2276 m_speculativeTilingEnabled = true;
2279 if (!shouldEnableSpeculativeTilingDuringLoading(*this))
2281 if (m_speculativeTilingEnableTimer.isActive())
2283 // Delay enabling a bit as load completion may trigger further loading from scripts.
2284 static const double speculativeTilingEnableDelay = 0.5;
2285 m_speculativeTilingEnableTimer.startOneShot(speculativeTilingEnableDelay);
2288 void FrameView::speculativeTilingEnableTimerFired(Timer<FrameView>&)
2290 if (m_speculativeTilingEnabled)
2292 m_speculativeTilingEnabled = shouldEnableSpeculativeTilingDuringLoading(*this);
2293 adjustTiledBackingCoverage();
2296 void FrameView::layoutTimerFired(Timer<FrameView>&)
2298 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2299 if (!frame().document()->ownerElement())
2300 printf("Layout timer fired at %lld\n", frame().document()->elapsedTime().count());
2305 void FrameView::scheduleRelayout()
2307 // FIXME: We should assert the page is not in the page cache, but that is causing
2308 // too many false assertions. See <rdar://problem/7218118>.
2309 ASSERT(frame().view() == this);
2312 m_layoutRoot->markContainingBlocksForLayout(false);
2315 if (!m_layoutSchedulingEnabled)
2319 if (!frame().document()->shouldScheduleLayout())
2321 InspectorInstrumentation::didInvalidateLayout(&frame());
2322 // When frame flattening is enabled, the contents of the frame could affect the layout of the parent frames.
2323 // Also invalidate parent frame starting from the owner element of this frame.
2324 if (frame().ownerRenderer() && isInChildFrameWithFrameFlattening())
2325 frame().ownerRenderer()->setNeedsLayout(MarkContainingBlockChain);
2327 std::chrono::milliseconds delay = frame().document()->minimumLayoutDelay();
2328 if (m_layoutTimer.isActive() && m_delayedLayout && !delay.count())
2329 unscheduleRelayout();
2330 if (m_layoutTimer.isActive())
2333 m_delayedLayout = delay.count();
2335 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2336 if (!frame().document()->ownerElement())
2337 printf("Scheduling layout for %d\n", delay);
2340 m_layoutTimer.startOneShot(delay);
2343 static bool isObjectAncestorContainerOf(RenderObject* ancestor, RenderObject* descendant)
2345 for (RenderObject* r = descendant; r; r = r->container()) {
2352 void FrameView::scheduleRelayoutOfSubtree(RenderElement& newRelayoutRoot)
2354 ASSERT(renderView());
2355 RenderView& renderView = *this->renderView();
2357 // Try to catch unnecessary work during render tree teardown.
2358 ASSERT(!renderView.documentBeingDestroyed());
2359 ASSERT(frame().view() == this);
2361 if (renderView.needsLayout()) {
2362 newRelayoutRoot.markContainingBlocksForLayout(false);
2366 if (!layoutPending() && m_layoutSchedulingEnabled) {
2367 std::chrono::milliseconds delay = renderView.document().minimumLayoutDelay();
2368 ASSERT(!newRelayoutRoot.container() || !newRelayoutRoot.container()->needsLayout());
2369 m_layoutRoot = &newRelayoutRoot;
2370 InspectorInstrumentation::didInvalidateLayout(&frame());
2371 m_delayedLayout = delay.count();
2372 m_layoutTimer.startOneShot(delay);
2376 if (m_layoutRoot == &newRelayoutRoot)
2379 if (!m_layoutRoot) {
2380 // Just relayout the subtree.
2381 newRelayoutRoot.markContainingBlocksForLayout(false);
2382 InspectorInstrumentation::didInvalidateLayout(&frame());
2386 if (isObjectAncestorContainerOf(m_layoutRoot, &newRelayoutRoot)) {
2387 // Keep the current root.
2388 newRelayoutRoot.markContainingBlocksForLayout(false, m_layoutRoot);
2389 ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
2393 if (isObjectAncestorContainerOf(&newRelayoutRoot, m_layoutRoot)) {
2394 // Re-root at newRelayoutRoot.
2395 m_layoutRoot->markContainingBlocksForLayout(false, &newRelayoutRoot);
2396 m_layoutRoot = &newRelayoutRoot;
2397 ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
2398 InspectorInstrumentation::didInvalidateLayout(&frame());
2402 // Just do a full relayout.
2403 m_layoutRoot->markContainingBlocksForLayout(false);
2405 newRelayoutRoot.markContainingBlocksForLayout(false);
2406 InspectorInstrumentation::didInvalidateLayout(&frame());
2409 bool FrameView::layoutPending() const
2411 return m_layoutTimer.isActive();
2414 bool FrameView::needsLayout() const
2416 // This can return true in cases where the document does not have a body yet.
2417 // Document::shouldScheduleLayout takes care of preventing us from scheduling
2418 // layout in that case.
2419 RenderView* renderView = this->renderView();
2420 return layoutPending()
2421 || (renderView && renderView->needsLayout())
2423 || (m_deferSetNeedsLayouts && m_setNeedsLayoutWasDeferred);
2426 void FrameView::setNeedsLayout()
2428 if (m_deferSetNeedsLayouts) {
2429 m_setNeedsLayoutWasDeferred = true;
2433 if (RenderView* renderView = this->renderView())
2434 renderView->setNeedsLayout();
2437 void FrameView::unscheduleRelayout()
2439 if (!m_layoutTimer.isActive())
2442 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2443 if (!frame().document()->ownerElement())
2444 printf("Layout timer unscheduled at %d\n", frame().document()->elapsedTime());
2447 m_layoutTimer.stop();
2448 m_delayedLayout = false;
2451 #if ENABLE(REQUEST_ANIMATION_FRAME)
2452 void FrameView::serviceScriptedAnimations(double monotonicAnimationStartTime)
2454 for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext()) {
2455 frame->view()->serviceScrollAnimations();
2456 frame->animation().serviceAnimations();
2459 Vector<RefPtr<Document>> documents;
2460 for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext())
2461 documents.append(frame->document());
2463 for (size_t i = 0; i < documents.size(); ++i)
2464 documents[i]->serviceScriptedAnimations(monotonicAnimationStartTime);
2468 bool FrameView::isTransparent() const
2470 return m_isTransparent;
2473 void FrameView::setTransparent(bool isTransparent)
2475 m_isTransparent = isTransparent;
2478 bool FrameView::hasOpaqueBackground() const
2480 return !m_isTransparent && !m_baseBackgroundColor.hasAlpha();
2483 Color FrameView::baseBackgroundColor() const
2485 return m_baseBackgroundColor;
2488 void FrameView::setBaseBackgroundColor(const Color& backgroundColor)
2490 if (!backgroundColor.isValid())
2491 m_baseBackgroundColor = Color::white;
2493 m_baseBackgroundColor = backgroundColor;
2495 recalculateScrollbarOverlayStyle();
2498 void FrameView::updateBackgroundRecursively(const Color& backgroundColor, bool transparent)
2500 for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) {
2501 if (FrameView* view = frame->view()) {
2502 view->setTransparent(transparent);
2503 view->setBaseBackgroundColor(backgroundColor);
2508 void FrameView::setBackgroundExtendsBeyondPage(bool extendBackground)
2510 RenderView* renderView = this->renderView();
2514 renderView->compositor().setRootExtendedBackgroundColor(extendBackground ? documentBackgroundColor() : Color());
2515 setHasExtendedBackgroundRectForPainting(needsExtendedBackgroundRectForPainting());
2518 bool FrameView::hasExtendedBackgroundRectForPainting() const
2520 if (!frame().settings().backgroundShouldExtendBeyondPage())
2523 TiledBacking* tiledBacking = this->tiledBacking();
2527 return tiledBacking->hasMargins();
2530 bool FrameView::needsExtendedBackgroundRectForPainting() const
2532 // Just because Settings::backgroundShouldExtendBeyondPage() is true does not necessarily mean
2533 // that the background rect needs to be extended for painting. Simple backgrounds can be extended
2534 // just with RenderLayerCompositor::setRootExtendedBackgroundColor(). More complicated backgrounds,
2535 // such as images, require extending the background rect to continue painting into the extended
2536 // region. This function finds out if it is necessary to extend the background rect for painting.
2539 // <rdar://problem/16201373>
2543 if (!frame().settings().backgroundShouldExtendBeyondPage())
2546 if (!frame().isMainFrame())
2549 Document* document = frame().document();
2553 auto documentElement = document->documentElement();
2554 auto bodyElement = document->body();
2555 auto documentElementRenderer = documentElement ? documentElement->renderer() : nullptr;
2556 auto bodyRenderer = bodyElement ? bodyElement->renderer() : nullptr;
2557 bool rootBackgroundHasImage = (documentElementRenderer && documentElementRenderer->style().hasBackgroundImage())
2558 || (bodyRenderer && bodyRenderer->style().hasBackgroundImage());
2560 return rootBackgroundHasImage;
2563 void FrameView::setHasExtendedBackgroundRectForPainting(bool shouldHaveExtendedBackgroundRect)
2565 if (shouldHaveExtendedBackgroundRect == hasExtendedBackgroundRectForPainting())
2568 RenderView* renderView = this->renderView();
2572 RenderLayerBacking* backing = renderView->layer()->backing();
2576 backing->setTiledBackingHasMargins(frame().settings().backgroundShouldExtendBeyondPage() && shouldHaveExtendedBackgroundRect);
2579 IntRect FrameView::extendedBackgroundRectForPainting() const
2581 TiledBacking* tiledBacking = this->tiledBacking();
2585 RenderView* renderView = this->renderView();
2589 LayoutRect extendedRect = renderView->unextendedBackgroundRect(renderView);
2590 if (!tiledBacking->hasMargins())
2591 return pixelSnappedIntRect(extendedRect);
2593 extendedRect.moveBy(LayoutPoint(-tiledBacking->leftMarginWidth(), -tiledBacking->topMarginHeight()));
2594 extendedRect.expand(LayoutSize(tiledBacking->leftMarginWidth() + tiledBacking->rightMarginWidth(), tiledBacking->topMarginHeight() + tiledBacking->bottomMarginHeight()));
2595 return pixelSnappedIntRect(extendedRect);
2598 bool FrameView::shouldUpdateWhileOffscreen() const
2600 return m_shouldUpdateWhileOffscreen;
2603 void FrameView::setShouldUpdateWhileOffscreen(bool shouldUpdateWhileOffscreen)
2605 m_shouldUpdateWhileOffscreen = shouldUpdateWhileOffscreen;
2608 bool FrameView::shouldUpdate() const
2610 if (isOffscreen() && !shouldUpdateWhileOffscreen())
2615 void FrameView::scrollToAnchor()
2617 RefPtr<Node> anchorNode = m_maintainScrollPositionAnchor;
2621 if (!anchorNode->renderer())
2625 if (anchorNode != frame().document())
2626 rect = anchorNode->boundingBox();
2628 // Scroll nested layers and frames to reveal the anchor.
2629 // Align to the top and to the closest side (this matches other browsers).
2630 anchorNode->renderer()->scrollRectToVisible(rect, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
2632 if (AXObjectCache* cache = frame().document()->existingAXObjectCache())
2633 cache->handleScrolledToAnchor(anchorNode.get());
2635 // scrollRectToVisible can call into setScrollPosition(), which resets m_maintainScrollPositionAnchor.
2636 m_maintainScrollPositionAnchor = anchorNode;
2639 void FrameView::updateEmbeddedObject(RenderEmbeddedObject& embeddedObject)
2641 // No need to update if it's already crashed or known to be missing.
2642 if (embeddedObject.isPluginUnavailable())
2645 HTMLFrameOwnerElement& element = embeddedObject.frameOwnerElement();
2647 if (embeddedObject.isSnapshottedPlugIn()) {
2648 if (isHTMLObjectElement(element) || isHTMLEmbedElement(element)) {
2649 HTMLPlugInImageElement& pluginElement = toHTMLPlugInImageElement(element);
2650 pluginElement.checkSnapshotStatus();
2655 auto weakRenderer = embeddedObject.createWeakPtr();
2657 // FIXME: This could turn into a real virtual dispatch if we defined
2658 // updateWidget(PluginCreationOption) on HTMLElement.
2659 if (isHTMLObjectElement(element) || isHTMLEmbedElement(element) || isHTMLAppletElement(element)) {
2660 HTMLPlugInImageElement& pluginElement = toHTMLPlugInImageElement(element);
2661 if (pluginElement.needsCheckForSizeChange()) {
2662 pluginElement.checkSnapshotStatus();
2665 if (pluginElement.needsWidgetUpdate())
2666 pluginElement.updateWidget(CreateAnyWidgetType);
2669 // FIXME: It is not clear that Media elements need or want this updateWidget() call.
2670 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
2671 else if (element.isMediaElement())
2672 toHTMLMediaElement(element).updateWidget(CreateAnyWidgetType);
2675 ASSERT_NOT_REACHED();
2677 // It's possible the renderer was destroyed below updateWidget() since loading a plugin may execute arbitrary JavaScript.
2681 embeddedObject.updateWidgetPosition();
2684 bool FrameView::updateEmbeddedObjects()
2686 if (m_nestedLayoutCount > 1 || !m_embeddedObjectsToUpdate || m_embeddedObjectsToUpdate->isEmpty())
2689 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
2691 // Insert a marker for where we should stop.
2692 ASSERT(!m_embeddedObjectsToUpdate->contains(nullptr));
2693 m_embeddedObjectsToUpdate->add(nullptr);
2695 while (!m_embeddedObjectsToUpdate->isEmpty()) {
2696 RenderEmbeddedObject* embeddedObject = m_embeddedObjectsToUpdate->takeFirst();
2697 if (!embeddedObject)
2699 updateEmbeddedObject(*embeddedObject);
2702 return m_embeddedObjectsToUpdate->isEmpty();
2705 void FrameView::flushAnyPendingPostLayoutTasks()
2707 if (!m_postLayoutTasksTimer.isActive())
2710 performPostLayoutTasks();
2713 void FrameView::performPostLayoutTasks()
2715 m_postLayoutTasksTimer.stop();
2717 frame().selection().setCaretRectNeedsUpdate();
2718 frame().selection().updateAndRevealSelection();
2720 if (m_nestedLayoutCount <= 1 && frame().document()->documentElement())
2721 fireLayoutRelatedMilestonesIfNeeded();
2724 // Only send layout-related delegate callbacks synchronously for the main frame to
2725 // avoid re-entering layout for the main frame while delivering a layout-related delegate
2726 // callback for a subframe.
2727 if (frame().isMainFrame())
2728 frame().page()->chrome().client().didLayout();
2731 #if ENABLE(FONT_LOAD_EVENTS)
2732 if (RuntimeEnabledFeatures::sharedFeatures().fontLoadEventsEnabled())
2733 frame().document()->fontloader()->didLayout();
2736 // FIXME: We should consider adding DidLayout as a LayoutMilestone. That would let us merge this
2737 // with didLayout(LayoutMilestones).
2738 frame().loader().client().dispatchDidLayout();
2740 updateWidgetPositions();
2742 // layout() protects FrameView, but it still can get destroyed when updateEmbeddedObjects()
2743 // is called through the post layout timer.
2744 Ref<FrameView> protect(*this);
2746 for (unsigned i = 0; i < maxUpdateEmbeddedObjectsIterations; i++) {
2747 if (updateEmbeddedObjects())
2751 if (auto* page = frame().page()) {
2752 if (auto* scrollingCoordinator = page->scrollingCoordinator())
2753 scrollingCoordinator->frameViewLayoutUpdated(this);
2756 if (RenderView* renderView = this->renderView()) {
2757 if (renderView->usesCompositing())
2758 renderView->compositor().frameViewDidLayout();
2763 sendResizeEventIfNeeded();
2766 void FrameView::sendResizeEventIfNeeded()
2768 RenderView* renderView = this->renderView();
2769 if (!renderView || renderView->printing())
2771 if (frame().page() && frame().page()->chrome().client().isSVGImageChromeClient())
2774 IntSize currentSize;
2775 if (useFixedLayout() && !fixedLayoutSize().isEmpty() && delegatesScrolling())
2776 currentSize = fixedLayoutSize();
2778 currentSize = visibleContentRectIncludingScrollbars().size();
2780 float currentZoomFactor = renderView->style().zoom();
2781 bool shouldSendResizeEvent = !m_firstLayout && (currentSize != m_lastViewportSize || currentZoomFactor != m_lastZoomFactor);
2783 m_lastViewportSize = currentSize;
2784 m_lastZoomFactor = currentZoomFactor;
2786 if (!shouldSendResizeEvent)
2790 // Don't send the resize event if the document is loading. Some pages automatically reload
2791 // when the window is resized; Safari on iOS often resizes the window while setting up its
2792 // viewport. This obviously can cause problems.
2793 if (DocumentLoader* documentLoader = frame().loader().documentLoader()) {
2794 if (documentLoader->isLoadingInAPISense())
2799 bool isMainFrame = frame().isMainFrame();
2800 bool canSendResizeEventSynchronously = !m_shouldAutoSize && isMainFrame && !isInLayout();
2802 // If we resized during layout, queue up a resize event for later, otherwise fire it right away.
2803 RefPtr<Event> resizeEvent = Event::create(eventNames().resizeEvent, false, false);
2804 if (canSendResizeEventSynchronously)
2805 frame().document()->dispatchWindowEvent(resizeEvent.release(), frame().document()->domWindow());
2807 frame().document()->enqueueWindowEvent(resizeEvent.release());
2809 #if ENABLE(INSPECTOR)
2810 Page* page = frame().page();
2811 if (InspectorInstrumentation::hasFrontends() && isMainFrame) {
2812 if (InspectorClient* inspectorClient = page ? page->inspectorController().inspectorClient() : nullptr)
2813 inspectorClient->didResizeMainFrame(&frame());
2818 void FrameView::willStartLiveResize()
2820 ScrollView::willStartLiveResize();
2821 adjustTiledBackingCoverage();
2824 void FrameView::willEndLiveResize()
2826 ScrollView::willEndLiveResize();
2827 adjustTiledBackingCoverage();
2830 void FrameView::postLayoutTimerFired(Timer<FrameView>&)
2832 performPostLayoutTasks();
2835 void FrameView::autoSizeIfEnabled()
2837 if (!m_shouldAutoSize)
2843 TemporaryChange<bool> changeInAutoSize(m_inAutoSize, true);
2845 Document* document = frame().document();
2849 RenderView* documentView = document->renderView();
2850 Element* documentElement = document->documentElement();
2851 if (!documentView || !documentElement)
2854 // Start from the minimum size and allow it to grow.
2855 resize(m_minAutoSize.width(), m_minAutoSize.height());
2857 IntSize size = frameRect().size();
2859 // Do the resizing twice. The first time is basically a rough calculation using the preferred width
2860 // which may result in a height change during the second iteration.
2861 for (int i = 0; i < 2; i++) {
2862 // Update various sizes including contentsSize, scrollHeight, etc.
2863 document->updateLayoutIgnorePendingStylesheets();
2864 int width = documentView->minPreferredLogicalWidth();
2865 int height = documentView->documentRect().height();
2866 IntSize newSize(width, height);
2868 // Check to see if a scrollbar is needed for a given dimension and
2869 // if so, increase the other dimension to account for the scrollbar.
2870 // Since the dimensions are only for the view rectangle, once a
2871 // dimension exceeds the maximum, there is no need to increase it further.
2872 if (newSize.width() > m_maxAutoSize.width()) {
2873 RefPtr<Scrollbar> localHorizontalScrollbar = horizontalScrollbar();
2874 if (!localHorizontalScrollbar)
2875 localHorizontalScrollbar = createScrollbar(HorizontalScrollbar);
2876 if (!localHorizontalScrollbar->isOverlayScrollbar())
2877 newSize.setHeight(newSize.height() + localHorizontalScrollbar->height());
2879 // Don't bother checking for a vertical scrollbar because the width is at
2880 // already greater the maximum.
2881 } else if (newSize.height() > m_maxAutoSize.height()) {
2882 RefPtr<Scrollbar> localVerticalScrollbar = verticalScrollbar();
2883 if (!localVerticalScrollbar)
2884 localVerticalScrollbar = createScrollbar(VerticalScrollbar);
2885 if (!localVerticalScrollbar->isOverlayScrollbar())
2886 newSize.setWidth(newSize.width() + localVerticalScrollbar->width());
2888 // Don't bother checking for a horizontal scrollbar because the height is
2889 // already greater the maximum.
2892 // Ensure the size is at least the min bounds.
2893 newSize = newSize.expandedTo(m_minAutoSize);
2895 // Bound the dimensions by the max bounds and determine what scrollbars to show.
2896 ScrollbarMode horizonalScrollbarMode = ScrollbarAlwaysOff;
2897 if (newSize.width() > m_maxAutoSize.width()) {
2898 newSize.setWidth(m_maxAutoSize.width());
2899 horizonalScrollbarMode = ScrollbarAlwaysOn;
2901 ScrollbarMode verticalScrollbarMode = ScrollbarAlwaysOff;
2902 if (newSize.height() > m_maxAutoSize.height()) {
2903 newSize.setHeight(m_maxAutoSize.height());
2904 verticalScrollbarMode = ScrollbarAlwaysOn;
2907 if (newSize == size)
2910 // While loading only allow the size to increase (to avoid twitching during intermediate smaller states)
2911 // unless autoresize has just been turned on or the maximum size is smaller than the current size.
2912 if (m_didRunAutosize && size.height() <= m_maxAutoSize.height() && size.width() <= m_maxAutoSize.width()
2913 && !frame().loader().isComplete() && (newSize.height() < size.height() || newSize.width() < size.width()))
2916 resize(newSize.width(), newSize.height());
2917 // Force the scrollbar state to avoid the scrollbar code adding them and causing them to be needed. For example,
2918 // a vertical scrollbar may cause text to wrap and thus increase the height (which is the only reason the scollbar is needed).
2919 setVerticalScrollbarLock(false);
2920 setHorizontalScrollbarLock(false);
2921 setScrollbarModes(horizonalScrollbarMode, verticalScrollbarMode, true, true);
2924 m_autoSizeContentSize = contentsSize();
2926 if (m_autoSizeFixedMinimumHeight) {
2927 resize(m_autoSizeContentSize.width(), std::max(m_autoSizeFixedMinimumHeight, m_autoSizeContentSize.height()));
2928 document->updateLayoutIgnorePendingStylesheets();
2931 m_didRunAutosize = true;
2934 void FrameView::setAutoSizeFixedMinimumHeight(int fixedMinimumHeight)
2936 if (m_autoSizeFixedMinimumHeight == fixedMinimumHeight)
2939 m_autoSizeFixedMinimumHeight = fixedMinimumHeight;
2944 void FrameView::updateOverflowStatus(bool horizontalOverflow, bool verticalOverflow)
2946 if (!m_viewportRenderer)
2949 if (m_overflowStatusDirty) {
2950 m_horizontalOverflow = horizontalOverflow;
2951 m_verticalOverflow = verticalOverflow;
2952 m_overflowStatusDirty = false;
2956 bool horizontalOverflowChanged = (m_horizontalOverflow != horizontalOverflow);
2957 bool verticalOverflowChanged = (m_verticalOverflow != verticalOverflow);
2959 if (horizontalOverflowChanged || verticalOverflowChanged) {
2960 m_horizontalOverflow = horizontalOverflow;
2961 m_verticalOverflow = verticalOverflow;
2963 RefPtr<OverflowEvent> overflowEvent = OverflowEvent::create(horizontalOverflowChanged, horizontalOverflow,
2964 verticalOverflowChanged, verticalOverflow);
2965 overflowEvent->setTarget(m_viewportRenderer->element());
2967 frame().document()->enqueueOverflowEvent(overflowEvent.release());
2972 const Pagination& FrameView::pagination() const
2974 if (m_pagination != Pagination())
2975 return m_pagination;
2977 if (frame().isMainFrame())
2978 return frame().page()->pagination();
2980 return m_pagination;
2983 void FrameView::setPagination(const Pagination& pagination)
2985 if (m_pagination == pagination)
2988 m_pagination = pagination;
2990 frame().document()->styleResolverChanged(DeferRecalcStyle);
2993 IntRect FrameView::windowClipRect(bool clipToContents) const
2995 ASSERT(frame().view() == this);
2997 if (paintsEntireContents())
2998 return IntRect(IntPoint(), totalContentsSize());
3000 // Set our clip rect to be our contents.
3003 clipRect = contentsToWindow(visibleContentRect(LegacyIOSDocumentVisibleRect));
3005 clipRect = contentsToWindow(visibleContentRectIncludingScrollbars(LegacyIOSDocumentVisibleRect));
3006 if (!frame().ownerElement())
3009 // Take our owner element and get its clip rect.
3010 HTMLFrameOwnerElement* ownerElement = frame().ownerElement();
3011 if (FrameView* parentView = ownerElement->document().view())
3012 clipRect.intersect(parentView->windowClipRectForFrameOwner(ownerElement, true));
3016 IntRect FrameView::windowClipRectForFrameOwner(const HTMLFrameOwnerElement* ownerElement, bool clipToLayerContents) const
3018 // The renderer can sometimes be null when style="display:none" interacts
3019 // with external content and plugins.
3020 if (!ownerElement->renderer())
3021 return windowClipRect();
3023 // If we have no layer, just return our window clip rect.
3024 const RenderLayer* enclosingLayer = ownerElement->renderer()->enclosingLayer();
3025 if (!enclosingLayer)
3026 return windowClipRect();
3028 // Apply the clip from the layer.
3030 if (clipToLayerContents)
3031 clipRect = pixelSnappedIntRect(enclosingLayer->childrenClipRect());
3033 clipRect = pixelSnappedIntRect(enclosingLayer->selfClipRect());
3034 clipRect = contentsToWindow(clipRect);
3035 return intersection(clipRect, windowClipRect());
3038 bool FrameView::isActive() const
3040 Page* page = frame().page();
3041 return page && page->focusController().isActive();
3044 bool FrameView::updatesScrollLayerPositionOnMainThread() const
3046 if (Page* page = frame().page()) {
3047 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
3048 return scrollingCoordinator->shouldUpdateScrollLayerPositionSynchronously();
3054 void FrameView::scrollTo(const IntSize& newOffset)
3056 LayoutSize offset = scrollOffset();
3057 IntPoint oldPosition = scrollPosition();
3058 ScrollView::scrollTo(newOffset);
3059 if (offset != scrollOffset())
3060 scrollPositionChanged(oldPosition, scrollPosition());
3061 frame().loader().client().didChangeScrollOffset();
3064 void FrameView::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
3066 // Add in our offset within the FrameView.
3067 IntRect dirtyRect = rect;
3068 dirtyRect.moveBy(scrollbar->location());
3069 invalidateRect(dirtyRect);
3072 IntRect FrameView::windowResizerRect() const
3074 if (Page* page = frame().page())
3075 return page->chrome().windowResizerRect();
3079 float FrameView::visibleContentScaleFactor() const
3081 if (!frame().isMainFrame() || !frame().settings().delegatesPageScaling())
3084 return frame().page()->pageScaleFactor();
3087 void FrameView::setVisibleScrollerThumbRect(const IntRect& scrollerThumb)
3089 if (!frame().isMainFrame())
3092 frame().page()->chrome().client().notifyScrollerThumbIsVisibleInRect(scrollerThumb);
3095 ScrollableArea* FrameView::enclosingScrollableArea() const
3097 // FIXME: Walk up the frame tree and look for a scrollable parent frame or RenderLayer.
3101 IntRect FrameView::scrollableAreaBoundingBox() const
3103 RenderWidget* ownerRenderer = frame().ownerRenderer();
3107 return ownerRenderer->absoluteContentQuad().enclosingBoundingBox();
3110 bool FrameView::isScrollable()
3113 // 1) If there an actual overflow.
3114 // 2) display:none or visibility:hidden set to self or inherited.
3115 // 3) overflow{-x,-y}: hidden;
3116 // 4) scrolling: no;
3119 IntSize totalContentsSize = this->totalContentsSize();
3120 IntSize visibleContentSize = visibleContentRect(LegacyIOSDocumentVisibleRect).size();
3121 if ((totalContentsSize.height() <= visibleContentSize.height() && totalContentsSize.width() <= visibleContentSize.width()))
3125 HTMLFrameOwnerElement* owner = frame().ownerElement();
3126 if (owner && (!owner->renderer() || !owner->renderer()->visibleToHitTesting()))
3130 ScrollbarMode horizontalMode;
3131 ScrollbarMode verticalMode;
3132 calculateScrollbarModesForLayout(horizontalMode, verticalMode, RulesFromWebContentOnly);
3133 if (horizontalMode == ScrollbarAlwaysOff && verticalMode == ScrollbarAlwaysOff)
3139 void FrameView::updateScrollableAreaSet()
3141 // That ensures that only inner frames are cached.
3142 FrameView* parentFrameView = this->parentFrameView();
3143 if (!parentFrameView)
3146 if (!isScrollable()) {
3147 parentFrameView->removeScrollableArea(this);
3151 parentFrameView->addScrollableArea(this);
3154 bool FrameView::shouldSuspendScrollAnimations() const
3156 return frame().loader().state() != FrameStateComplete;
3159 void FrameView::scrollbarStyleChanged(int newStyle, bool forceUpdate)
3161 if (!frame().isMainFrame())
3164 frame().page()->chrome().client().recommendedScrollbarStyleDidChange(newStyle);
3167 ScrollView::scrollbarStyleChanged(newStyle, forceUpdate);
3170 void FrameView::notifyPageThatContentAreaWillPaint() const
3172 Page* page = frame().page();
3176 contentAreaWillPaint();
3178 if (!m_scrollableAreas)
3181 for (auto& scrollableArea : *m_scrollableAreas)
3182 scrollableArea->contentAreaWillPaint();
3185 bool FrameView::scrollAnimatorEnabled() const
3187 #if ENABLE(SMOOTH_SCROLLING)
3188 if (Page* page = frame().page())
3189 return page->settings().scrollAnimatorEnabled();
3195 #if ENABLE(DASHBOARD_SUPPORT)
3196 void FrameView::updateAnnotatedRegions()
3198 Document* document = frame().document();
3199 if (!document->hasAnnotatedRegions())
3201 Vector<AnnotatedRegionValue> newRegions;
3202 document->renderBox()->collectAnnotatedRegions(newRegions);
3203 if (newRegions == document->annotatedRegions())
3205 document->setAnnotatedRegions(newRegions);
3206 Page* page = frame().page();
3209 page->chrome().client().annotatedRegionsChanged();
3213 void FrameView::updateScrollCorner()
3215 RenderElement* renderer = 0;
3216 RefPtr<RenderStyle> cornerStyle;
3217 IntRect cornerRect = scrollCornerRect();
3219 if (!cornerRect.isEmpty()) {
3220 // Try the <body> element first as a scroll corner source.
3221 Document* doc = frame().document();
3222 Element* body = doc ? doc->body() : 0;
3223 if (body && body->renderer()) {
3224 renderer = body->renderer();
3225 cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), &renderer->style());
3229 // If the <body> didn't have a custom style, then the root element might.
3230 Element* docElement = doc ? doc->documentElement() : 0;
3231 if (docElement && docElement->renderer()) {
3232 renderer = docElement->renderer();
3233 cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), &renderer->style());
3238 // If we have an owning iframe/frame element, then it can set the custom scrollbar also.
3239 if (RenderWidget* renderer = frame().ownerRenderer())
3240 cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), &renderer->style());
3245 m_scrollCorner = nullptr;
3247 if (!m_scrollCorner) {
3248 m_scrollCorner = createRenderer<RenderScrollbarPart>(renderer->document(), cornerStyle.releaseNonNull());
3249 m_scrollCorner->initializeStyle();
3251 m_scrollCorner->setStyle(cornerStyle.releaseNonNull());
3252 invalidateScrollCorner(cornerRect);
3255 ScrollView::updateScrollCorner();
3258 void FrameView::paintScrollCorner(GraphicsContext* context, const IntRect& cornerRect)
3260 if (context->updatingControlTints()) {
3261 updateScrollCorner();
3265 if (m_scrollCorner) {
3266 if (frame().isMainFrame())
3267 context->fillRect(cornerRect, baseBackgroundColor(), ColorSpaceDeviceRGB);
3268 m_scrollCorner->paintIntoRect(context, cornerRect.location(), cornerRect);
3272 ScrollView::paintScrollCorner(context, cornerRect);
3275 void FrameView::paintScrollbar(GraphicsContext* context, Scrollbar* bar, const IntRect& rect)
3277 if (bar->isCustomScrollbar() && frame().isMainFrame()) {
3278 IntRect toFill = bar->frameRect();
3279 toFill.intersect(rect);
3280 context->fillRect(toFill, baseBackgroundColor(), ColorSpaceDeviceRGB);
3283 ScrollView::paintScrollbar(context, bar, rect);
3286 Color FrameView::documentBackgroundColor() const
3288 // <https://bugs.webkit.org/show_bug.cgi?id=59540> We blend the background color of
3289 // the document and the body against the base background color of the frame view.
3290 // Background images are unfortunately impractical to include.
3292 // Return invalid Color objects whenever there is insufficient information.
3293 if (!frame().document())
3296 Element* htmlElement = frame().document()->documentElement();
3297 Element* bodyElement = frame().document()->body();
3299 // Start with invalid colors.
3300 Color htmlBackgroundColor;
3301 Color bodyBackgroundColor;
3302 if (htmlElement && htmlElement->renderer())
3303 htmlBackgroundColor = htmlElement->renderer()->style().visitedDependentColor(CSSPropertyBackgroundColor);
3304 if (bodyElement && bodyElement->renderer())
3305 bodyBackgroundColor = bodyElement->renderer()->style().visitedDependentColor(CSSPropertyBackgroundColor);
3307 if (!bodyBackgroundColor.isValid()) {
3308 if (!htmlBackgroundColor.isValid())
3310 return baseBackgroundColor().blend(htmlBackgroundColor);
3313 if (!htmlBackgroundColor.isValid())
3314 return baseBackgroundColor().blend(bodyBackgroundColor);
3316 // We take the aggregate of the base background color
3317 // the <html> background color, and the <body>
3318 // background color to find the document color. The
3319 // addition of the base background color is not
3320 // technically part of the document background, but it
3321 // otherwise poses problems when the aggregate is not
3323 return baseBackgroundColor().blend(htmlBackgroundColor).blend(bodyBackgroundColor);
3326 bool FrameView::hasCustomScrollbars() const
3328 for (auto& widget : children()) {
3329 if (widget->isFrameView()) {
3330 if (toFrameView(*widget).hasCustomScrollbars())
3332 } else if (widget->isScrollbar()) {
3333 if (toScrollbar(*widget).isCustomScrollbar())
3341 FrameView* FrameView::parentFrameView() const
3346 if (Frame* parentFrame = frame().tree().parent())
3347 return parentFrame->view();
3352 bool FrameView::isInChildFrameWithFrameFlattening() const
3354 if (!parent() || !frame().ownerElement())
3357 // Frame flattening applies when the owner element is either in a frameset or
3358 // an iframe with flattening parameters.
3359 if (frame().ownerElement()->hasTagName(iframeTag)) {
3360 RenderIFrame* iframeRenderer = toRenderIFrame(frame().ownerElement()->renderWidget());
3361 if (iframeRenderer->flattenFrame())
3365 if (!frameFlatteningEnabled())
3368 if (frame().ownerElement()->hasTagName(frameTag))
3374 void FrameView::startLayoutAtMainFrameViewIfNeeded(bool allowSubtree)
3376 // When we start a layout at the child level as opposed to the topmost frame view and this child
3377 // frame requires flattening, we need to re-initiate the layout at the topmost view. Layout
3378 // will hit this view eventually.
3379 FrameView* parentView = parentFrameView();
3383 // In the middle of parent layout, no need to restart from topmost.
3384 if (parentView->m_nestedLayoutCount)
3387 // Parent tree is clean. Starting layout from it would have no effect.
3388 if (!parentView->needsLayout())
3391 while (parentView->parentFrameView())
3392 parentView = parentView->parentFrameView();
3394 parentView->layout(allowSubtree);
3396 RenderElement* root = m_layoutRoot ? m_layoutRoot : frame().document()->renderView();
3397 ASSERT_UNUSED(root, !root->needsLayout());
3400 void FrameView::updateControlTints()
3402 // This is called when control tints are changed from aqua/graphite to clear and vice versa.
3403 // We do a "fake" paint, and when the theme gets a paint call, it can then do an invalidate.
3404 // This is only done if the theme supports control tinting. It's up to the theme and platform
3405 // to define when controls get the tint and to call this function when that changes.
3407 // Optimize the common case where we bring a window to the front while it's still empty.
3408 if (frame().document()->url().isEmpty())
3411 RenderView* renderView = this->renderView();
3412 if ((renderView && renderView->theme().supportsControlTints()) || hasCustomScrollbars())
3413 paintControlTints();
3416 void FrameView::paintControlTints()
3420 PlatformGraphicsContext* const noContext = 0;
3421 GraphicsContext context(noContext);
3422 context.setUpdatingControlTints(true);
3423 if (platformWidget()) {
3424 // FIXME: consult paintsEntireContents().
3425 paintContents(&context, visibleContentRect(LegacyIOSDocumentVisibleRect));
3427 paint(&context, frameRect());
3430 bool FrameView::wasScrolledByUser() const
3432 return m_wasScrolledByUser;
3435 void FrameView::setWasScrolledByUser(bool wasScrolledByUser)
3437 if (m_inProgrammaticScroll)
3439 m_maintainScrollPositionAnchor = 0;
3440 if (m_wasScrolledByUser == wasScrolledByUser)
3442 m_wasScrolledByUser = wasScrolledByUser;
3443 adjustTiledBackingCoverage();
3446 void FrameView::willPaintContents(GraphicsContext* context, const IntRect& dirtyRect, PaintingState& paintingState)
3448 Document* document = frame().document();
3450 if (!context->paintingDisabled())
3451 InspectorInstrumentation::willPaint(renderView());
3453 paintingState.isTopLevelPainter = !sCurrentPaintTimeStamp;
3455 if (paintingState.isTopLevelPainter && memoryPressureHandler().isUnderMemoryPressure()) {
3456 LOG(MemoryPressure, "Under memory pressure: %s", WTF_PRETTY_FUNCTION);
3458 // To avoid unnecessary image decoding, we don't prune recently-decoded live resources here since
3459 // we might need some live bitmaps on painting.
3460 memoryCache()->prune();
3463 if (paintingState.isTopLevelPainter)
3464 sCurrentPaintTimeStamp = monotonicallyIncreasingTime();
3466 paintingState.paintBehavior = m_paintBehavior;
3468 if (FrameView* parentView = parentFrameView()) {
3469 if (parentView->paintBehavior() & PaintBehaviorFlattenCompositingLayers)
3470 m_paintBehavior |= PaintBehaviorFlattenCompositingLayers;
3473 if (m_paintBehavior == PaintBehaviorNormal)
3474 document->markers().invalidateRenderedRectsForMarkersInRect(dirtyRect);
3476 if (document->printing())
3477 m_paintBehavior |= PaintBehaviorFlattenCompositingLayers;
3479 paintingState.isFlatteningPaintOfRootFrame = (m_paintBehavior & PaintBehaviorFlattenCompositingLayers) && !frame().ownerElement();
3480 if (paintingState.isFlatteningPaintOfRootFrame)
3481 notifyWidgetsInAllFrames(WillPaintFlattened);
3483 ASSERT(!m_isPainting);
3484 m_isPainting = true;
3487 void FrameView::didPaintContents(GraphicsContext* context, const IntRect& dirtyRect, PaintingState& paintingState)
3489 m_isPainting = false;
3491 if (paintingState.isFlatteningPaintOfRootFrame)
3492 notifyWidgetsInAllFrames(DidPaintFlattened);
3494 m_paintBehavior = paintingState.paintBehavior;
3495 m_lastPaintTime = monotonicallyIncreasingTime();
3497 // Painting can lead to decoding of large amounts of bitmaps
3498 // If we are low on memory, wipe them out after the paint.
3499 if (paintingState.isTopLevelPainter && memoryPressureHandler().isUnderMemoryPressure())
3500 memoryCache()->pruneLiveResources(true);
3502 // Regions may have changed as a result of the visibility/z-index of element changing.
3503 #if ENABLE(DASHBOARD_SUPPORT)
3504 if (frame().document()->annotatedRegionsDirty())
3505 updateAnnotatedRegions();
3508 if (paintingState.isTopLevelPainter)
3509 sCurrentPaintTimeStamp = 0;
3511 if (!context->paintingDisabled()) {
3512 InspectorInstrumentation::didPaint(renderView(), context, dirtyRect);
3513 // FIXME: should probably not fire milestones for snapshot painting. https://bugs.webkit.org/show_bug.cgi?id=117623
3514 firePaintRelatedMilestonesIfNeeded();
3518 void FrameView::paintContents(GraphicsContext* context, const IntRect& dirtyRect)
3522 if (frame().document()->printing())
3523 fillWithRed = false; // Printing, don't fill with red (can't remember why).
3524 else if (frame().ownerElement())
3525 fillWithRed = false; // Subframe, don't fill with red.
3526 else if (isTransparent())
3527 fillWithRed = false; // Transparent, don't fill with red.
3528 else if (m_paintBehavior & PaintBehaviorSelectionOnly)
3529 fillWithRed = false; // Selections are transparent, don't fill with red.
3530 else if (m_nodeToDraw)
3531 fillWithRed = false; // Element images are transparent, don't fill with red.
3536 context->fillRect(dirtyRect, Color(0xFF, 0, 0), ColorSpaceDeviceRGB);
3539 RenderView* renderView = this->renderView();
3541 LOG_ERROR("called FrameView::paint with nil renderer");
3545 ASSERT(!needsLayout());
3549 PaintingState paintingState;
3550 willPaintContents(context, dirtyRect, paintingState);
3552 FontCachePurgePreventer fontCachePurgePreventer;
3554 // m_nodeToDraw is used to draw only one element (and its descendants)
3555 RenderObject* eltRenderer = m_nodeToDraw ? m_nodeToDraw->renderer() : 0;
3556 RenderLayer* rootLayer = renderView->layer();
3559 RenderElement::SetLayoutNeededForbiddenScope forbidSetNeedsLayout(&rootLayer->renderer());
3562 rootLayer->paint(context, dirtyRect, m_paintBehavior, eltRenderer);
3563 if (rootLayer->containsDirtyOverlayScrollbars())
3564 rootLayer->paintOverlayScrollbars(context, dirtyRect, m_paintBehavior, eltRenderer);
3566 didPaintContents(context, dirtyRect, paintingState);
3569 void FrameView::setPaintBehavior(PaintBehavior behavior)
3571 m_paintBehavior = behavior;
3574 PaintBehavior FrameView::paintBehavior() const
3576 return m_paintBehavior;
3579 bool FrameView::isPainting() const
3581 return m_isPainting;
3584 // FIXME: change this to use the subtreePaint terminology.
3585 void FrameView::setNodeToDraw(Node* node)
3587 m_nodeToDraw = node;
3590 void FrameView::paintContentsForSnapshot(GraphicsContext* context, const IntRect& imageRect, SelectionInSnapshot shouldPaintSelection, CoordinateSpaceForSnapshot coordinateSpace)
3592 updateLayoutAndStyleIfNeededRecursive();
3594 // Cache paint behavior and set a new behavior appropriate for snapshots.
3595 PaintBehavior oldBehavior = paintBehavior();
3596 setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
3598 // If the snapshot should exclude selection, then we'll clear the current selection
3599 // in the render tree only. This will allow us to restore the selection from the DOM
3600 // after we paint the snapshot.
3601 if (shouldPaintSelection == ExcludeSelection) {
3602 for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) {
3603 if (RenderView* root = frame->contentRenderer())
3604 root->clearSelection();
3608 if (coordinateSpace == DocumentCoordinates)
3609 paintContents(context, imageRect);
3611 // A snapshot in ViewCoordinates will include a scrollbar, and the snapshot will contain
3612 // whatever content the document is currently scrolled to.
3613 paint(context, imageRect);