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"
57 #include "MainFrame.h"
58 #include "OverflowEvent.h"
59 #include "ProgressTracker.h"
60 #include "RenderEmbeddedObject.h"
61 #include "RenderFullScreen.h"
62 #include "RenderIFrame.h"
63 #include "RenderLayer.h"
64 #include "RenderLayerBacking.h"
65 #include "RenderScrollbar.h"
66 #include "RenderScrollbarPart.h"
67 #include "RenderStyle.h"
68 #include "RenderTheme.h"
69 #include "RenderView.h"
70 #include "RenderWidget.h"
71 #include "ScrollAnimator.h"
72 #include "ScrollingCoordinator.h"
74 #include "StyleResolver.h"
75 #include "TextResourceDecoder.h"
76 #include "TextStream.h"
78 #include <wtf/CurrentTime.h>
80 #include <wtf/TemporaryChange.h>
82 #if USE(ACCELERATED_COMPOSITING)
83 #include "RenderLayerCompositor.h"
84 #include "TiledBacking.h"
88 #include "RenderSVGRoot.h"
89 #include "SVGDocument.h"
90 #include "SVGSVGElement.h"
93 #if USE(TILED_BACKING_STORE)
94 #include "TiledBackingStore.h"
97 #if ENABLE(TEXT_AUTOSIZING)
98 #include "TextAutosizer.h"
103 using namespace HTMLNames;
105 double FrameView::sCurrentPaintTimeStamp = 0.0;
108 // REPAINT_THROTTLING now chooses default values for throttling parameters.
109 // Should be removed when applications start using runtime configuration.
110 #if ENABLE(REPAINT_THROTTLING)
112 double FrameView::s_normalDeferredRepaintDelay = 0.016;
113 // Negative value would mean that first few repaints happen without a delay
114 double FrameView::s_initialDeferredRepaintDelayDuringLoading = 0;
115 // The delay grows on each repaint to this maximum value
116 double FrameView::s_maxDeferredRepaintDelayDuringLoading = 2.5;
117 // On each repaint the delay increses by this amount
118 double FrameView::s_deferredRepaintDelayIncrementDuringLoading = 0.5;
120 // FIXME: Repaint throttling could be good to have on all platform.
121 // The balance between CPU use and repaint frequency will need some tuning for desktop.
122 // More hooks may be needed to reset the delay on things like GIF and CSS animations.
123 double FrameView::s_normalDeferredRepaintDelay = 0;
124 double FrameView::s_initialDeferredRepaintDelayDuringLoading = 0;
125 double FrameView::s_maxDeferredRepaintDelayDuringLoading = 0;
126 double FrameView::s_deferredRepaintDelayIncrementDuringLoading = 0;
129 // The maximum number of updateEmbeddedObjects iterations that should be done before returning.
130 static const unsigned maxUpdateEmbeddedObjectsIterations = 2;
132 static RenderLayer::UpdateLayerPositionsFlags updateLayerPositionFlags(RenderLayer* layer, bool isRelayoutingSubtree, bool didFullRepaint)
134 RenderLayer::UpdateLayerPositionsFlags flags = RenderLayer::defaultFlags;
135 if (didFullRepaint) {
136 flags &= ~RenderLayer::CheckForRepaint;
137 flags |= RenderLayer::NeedsFullRepaintInBacking;
139 if (isRelayoutingSubtree && layer->isPaginated())
140 flags |= RenderLayer::UpdatePagination;
144 Pagination::Mode paginationModeForRenderStyle(const RenderStyle& style)
146 EOverflow overflow = style.overflowY();
147 if (overflow != OPAGEDX && overflow != OPAGEDY)
148 return Pagination::Unpaginated;
150 bool isHorizontalWritingMode = style.isHorizontalWritingMode();
151 TextDirection textDirection = style.direction();
152 WritingMode writingMode = style.writingMode();
154 // paged-x always corresponds to LeftToRightPaginated or RightToLeftPaginated. If the WritingMode
155 // is horizontal, then we use TextDirection to choose between those options. If the WritingMode
156 // is vertical, then the direction of the verticality dictates the choice.
157 if (overflow == OPAGEDX) {
158 if ((isHorizontalWritingMode && textDirection == LTR) || writingMode == LeftToRightWritingMode)
159 return Pagination::LeftToRightPaginated;
160 return Pagination::RightToLeftPaginated;
163 // paged-y always corresponds to TopToBottomPaginated or BottomToTopPaginated. If the WritingMode
164 // is horizontal, then the direction of the horizontality dictates the choice. If the WritingMode
165 // is vertical, then we use TextDirection to choose between those options.
166 if (writingMode == TopToBottomWritingMode || (!isHorizontalWritingMode && textDirection == RTL))
167 return Pagination::TopToBottomPaginated;
168 return Pagination::BottomToTopPaginated;
171 FrameView::FrameView(Frame& frame)
173 , m_canHaveScrollbars(true)
174 , m_layoutTimer(this, &FrameView::layoutTimerFired)
176 , m_layoutPhase(OutsideLayout)
177 , m_inSynchronousPostLayout(false)
178 , m_postLayoutTasksTimer(this, &FrameView::postLayoutTimerFired)
179 , m_isTransparent(false)
180 , m_baseBackgroundColor(Color::white)
181 , m_mediaType("screen")
182 , m_overflowStatusDirty(true)
183 , m_viewportRenderer(0)
184 , m_wasScrolledByUser(false)
185 , m_inProgrammaticScroll(false)
186 , m_safeToPropagateScrollToParent(true)
187 , m_deferredRepaintTimer(this, &FrameView::deferredRepaintTimerFired)
188 , m_isTrackingRepaints(false)
189 , m_shouldUpdateWhileOffscreen(true)
190 , m_deferSetNeedsLayouts(0)
191 , m_setNeedsLayoutWasDeferred(false)
193 , m_shouldAutoSize(false)
194 , m_inAutoSize(false)
195 , m_didRunAutosize(false)
196 , m_autoSizeFixedMinimumHeight(0)
199 , m_milestonesPendingPaint(0)
200 , m_visualUpdatesAllowedByClient(true)
201 , m_scrollPinningBehavior(DoNotPin)
202 , m_scheduledEventSuppressionCount(0)
206 if (frame.isMainFrame()) {
207 ScrollableArea::setVerticalScrollElasticity(ScrollElasticityAllowed);
208 ScrollableArea::setHorizontalScrollElasticity(ScrollElasticityAutomatic);
212 PassRefPtr<FrameView> FrameView::create(Frame& frame)
214 RefPtr<FrameView> view = adoptRef(new FrameView(frame));
216 return view.release();
219 PassRefPtr<FrameView> FrameView::create(Frame& frame, const IntSize& initialSize)
221 RefPtr<FrameView> view = adoptRef(new FrameView(frame));
222 view->Widget::setFrameRect(IntRect(view->location(), initialSize));
224 return view.release();
227 FrameView::~FrameView()
229 if (m_postLayoutTasksTimer.isActive()) {
230 m_postLayoutTasksTimer.stop();
231 m_scheduledEventSuppressionCount = 0;
232 m_scheduledEvents.clear();
235 removeFromAXObjectCache();
238 // Custom scrollbars should already be destroyed at this point
239 ASSERT(!horizontalScrollbar() || !horizontalScrollbar()->isCustomScrollbar());
240 ASSERT(!verticalScrollbar() || !verticalScrollbar()->isCustomScrollbar());
242 setHasHorizontalScrollbar(false); // Remove native scrollbars now before we lose the connection to the HostWindow.
243 setHasVerticalScrollbar(false);
245 ASSERT(!m_scrollCorner);
246 ASSERT(m_scheduledEvents.isEmpty());
248 ASSERT(frame().view() != this || !frame().contentRenderer());
251 void FrameView::reset()
253 m_cannotBlitToWindow = false;
254 m_isOverlapped = false;
255 m_contentIsOpaque = false;
258 m_layoutTimer.stop();
260 m_delayedLayout = false;
261 m_needsFullRepaint = true;
262 m_layoutSchedulingEnabled = true;
263 m_layoutPhase = OutsideLayout;
264 m_inSynchronousPostLayout = false;
266 m_nestedLayoutCount = 0;
267 m_postLayoutTasksTimer.stop();
268 m_firstLayout = true;
269 m_firstLayoutCallbackPending = false;
270 m_wasScrolledByUser = false;
271 m_safeToPropagateScrollToParent = true;
272 m_lastViewportSize = IntSize();
273 m_lastZoomFactor = 1.0f;
274 m_deferringRepaints = 0;
276 m_repaintRects.clear();
277 m_deferredRepaintDelay = s_initialDeferredRepaintDelayDuringLoading;
278 m_deferredRepaintTimer.stop();
279 m_isTrackingRepaints = false;
280 m_trackedRepaintRects.clear();
282 m_paintBehavior = PaintBehaviorNormal;
283 m_isPainting = false;
284 m_visuallyNonEmptyCharacterCount = 0;
285 m_visuallyNonEmptyPixelCount = 0;
286 m_isVisuallyNonEmpty = false;
287 m_firstVisuallyNonEmptyLayoutCallbackPending = true;
288 m_maintainScrollPositionAnchor = 0;
291 void FrameView::removeFromAXObjectCache()
293 if (AXObjectCache* cache = axObjectCache())
297 void FrameView::resetScrollbars()
299 // Reset the document's scrollbars back to our defaults before we yield the floor.
300 m_firstLayout = true;
301 setScrollbarsSuppressed(true);
302 if (m_canHaveScrollbars)
303 setScrollbarModes(ScrollbarAuto, ScrollbarAuto);
305 setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff);
306 setScrollbarsSuppressed(false);
309 void FrameView::resetScrollbarsAndClearContentsSize()
313 setScrollbarsSuppressed(true);
314 setContentsSize(IntSize());
315 setScrollbarsSuppressed(false);
318 void FrameView::init()
322 m_margins = LayoutSize(-1, -1); // undefined
323 m_size = LayoutSize();
325 // Propagate the marginwidth/height and scrolling modes to the view.
326 Element* ownerElement = frame().ownerElement();
327 if (ownerElement && (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag))) {
328 HTMLFrameElementBase* frameElt = toHTMLFrameElementBase(ownerElement);
329 if (frameElt->scrollingMode() == ScrollbarAlwaysOff)
330 setCanHaveScrollbars(false);
331 LayoutUnit marginWidth = frameElt->marginWidth();
332 LayoutUnit marginHeight = frameElt->marginHeight();
333 if (marginWidth != -1)
334 setMarginWidth(marginWidth);
335 if (marginHeight != -1)
336 setMarginHeight(marginHeight);
339 Page* page = frame().page();
340 if (page && page->chrome().client().shouldPaintEntireContents())
341 setPaintsEntireContents(true);
344 void FrameView::prepareForDetach()
346 detachCustomScrollbars();
347 // When the view is no longer associated with a frame, it needs to be removed from the ax object cache
348 // right now, otherwise it won't be able to reach the topDocument()'s axObject cache later.
349 removeFromAXObjectCache();
351 if (frame().page()) {
352 if (ScrollingCoordinator* scrollingCoordinator = frame().page()->scrollingCoordinator())
353 scrollingCoordinator->willDestroyScrollableArea(this);
357 void FrameView::detachCustomScrollbars()
359 Scrollbar* horizontalBar = horizontalScrollbar();
360 if (horizontalBar && horizontalBar->isCustomScrollbar())
361 setHasHorizontalScrollbar(false);
363 Scrollbar* verticalBar = verticalScrollbar();
364 if (verticalBar && verticalBar->isCustomScrollbar())
365 setHasVerticalScrollbar(false);
367 if (m_scrollCorner) {
368 m_scrollCorner->destroy();
373 void FrameView::recalculateScrollbarOverlayStyle()
375 ScrollbarOverlayStyle oldOverlayStyle = scrollbarOverlayStyle();
376 ScrollbarOverlayStyle overlayStyle = ScrollbarOverlayStyleDefault;
378 Color backgroundColor = documentBackgroundColor();
379 if (backgroundColor.isValid()) {
380 // Reduce the background color from RGB to a lightness value
381 // and determine which scrollbar style to use based on a lightness
383 double hue, saturation, lightness;
384 backgroundColor.getHSL(hue, saturation, lightness);
385 if (lightness <= .5 && backgroundColor.alpha() > 0)
386 overlayStyle = ScrollbarOverlayStyleLight;
389 if (oldOverlayStyle != overlayStyle)
390 setScrollbarOverlayStyle(overlayStyle);
393 void FrameView::clear()
395 setCanBlitOnScroll(true);
399 setScrollbarsSuppressed(true);
402 bool FrameView::didFirstLayout() const
404 return !m_firstLayout;
407 void FrameView::invalidateRect(const IntRect& rect)
410 if (HostWindow* window = hostWindow())
411 window->invalidateContentsAndRootView(rect, false /*immediate*/);
415 RenderWidget* renderer = frame().ownerRenderer();
419 IntRect repaintRect = rect;
420 repaintRect.move(renderer->borderLeft() + renderer->paddingLeft(),
421 renderer->borderTop() + renderer->paddingTop());
422 renderer->repaintRectangle(repaintRect);
425 void FrameView::setFrameRect(const IntRect& newRect)
427 IntRect oldRect = frameRect();
428 if (newRect == oldRect)
431 #if ENABLE(TEXT_AUTOSIZING)
432 // Autosized font sizes depend on the width of the viewing area.
433 if (newRect.width() != oldRect.width()) {
434 Page* page = frame().page();
435 if (frame().isMainFrame() && page->settings().textAutosizingEnabled()) {
436 for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext())
437 frame().document()->textAutosizer()->recalculateMultipliers();
442 ScrollView::setFrameRect(newRect);
444 updateScrollableAreaSet();
446 #if USE(ACCELERATED_COMPOSITING)
447 if (RenderView* renderView = this->renderView()) {
448 if (renderView->usesCompositing())
449 renderView->compositor().frameViewDidChangeSize();
453 if (!frameFlatteningEnabled())
454 sendResizeEventIfNeeded();
457 #if ENABLE(REQUEST_ANIMATION_FRAME)
458 bool FrameView::scheduleAnimation()
460 if (HostWindow* window = hostWindow()) {
461 window->scheduleAnimation();
468 void FrameView::setMarginWidth(LayoutUnit w)
470 // make it update the rendering area when set
471 m_margins.setWidth(w);
474 void FrameView::setMarginHeight(LayoutUnit h)
476 // make it update the rendering area when set
477 m_margins.setHeight(h);
480 bool FrameView::frameFlatteningEnabled() const
482 return frame().settings().frameFlatteningEnabled();
485 bool FrameView::isFrameFlatteningValidForThisFrame() const
487 if (!frameFlatteningEnabled())
490 HTMLFrameOwnerElement* owner = frame().ownerElement();
494 // Frame flattening is valid only for <frame> and <iframe>.
495 return owner->hasTagName(frameTag) || owner->hasTagName(iframeTag);
498 bool FrameView::avoidScrollbarCreation() const
500 // with frame flattening no subframe can have scrollbars
501 // but we also cannot turn scrollbars off as we determine
502 // our flattening policy using that.
503 return isFrameFlatteningValidForThisFrame();
506 void FrameView::setCanHaveScrollbars(bool canHaveScrollbars)
508 m_canHaveScrollbars = canHaveScrollbars;
509 ScrollView::setCanHaveScrollbars(canHaveScrollbars);
512 void FrameView::updateCanHaveScrollbars()
516 scrollbarModes(hMode, vMode);
517 if (hMode == ScrollbarAlwaysOff && vMode == ScrollbarAlwaysOff)
518 setCanHaveScrollbars(false);
520 setCanHaveScrollbars(true);
523 PassRefPtr<Scrollbar> FrameView::createScrollbar(ScrollbarOrientation orientation)
525 if (!frame().settings().allowCustomScrollbarInMainFrame() && frame().isMainFrame())
526 return ScrollView::createScrollbar(orientation);
528 // FIXME: We need to update the scrollbar dynamically as documents change (or as doc elements and bodies get discovered that have custom styles).
529 Document* doc = frame().document();
531 // Try the <body> element first as a scrollbar source.
532 Element* body = doc ? doc->body() : 0;
533 if (body && body->renderer() && body->renderer()->style().hasPseudoStyle(SCROLLBAR))
534 return RenderScrollbar::createCustomScrollbar(this, orientation, body);
536 // If the <body> didn't have a custom style, then the root element might.
537 Element* docElement = doc ? doc->documentElement() : 0;
538 if (docElement && docElement->renderer() && docElement->renderer()->style().hasPseudoStyle(SCROLLBAR))
539 return RenderScrollbar::createCustomScrollbar(this, orientation, docElement);
541 // If we have an owning iframe/frame element, then it can set the custom scrollbar also.
542 RenderWidget* frameRenderer = frame().ownerRenderer();
543 if (frameRenderer && frameRenderer->style().hasPseudoStyle(SCROLLBAR))
544 return RenderScrollbar::createCustomScrollbar(this, orientation, 0, &frame());
546 // Nobody set a custom style, so we just use a native scrollbar.
547 return ScrollView::createScrollbar(orientation);
550 void FrameView::setContentsSize(const IntSize& size)
552 if (size == contentsSize())
555 m_deferSetNeedsLayouts++;
557 ScrollView::setContentsSize(size);
558 ScrollView::contentsResized();
560 Page* page = frame().page();
564 updateScrollableAreaSet();
566 page->chrome().contentsSizeChanged(&frame(), size); // Notify only.
568 ASSERT(m_deferSetNeedsLayouts);
569 m_deferSetNeedsLayouts--;
571 if (!m_deferSetNeedsLayouts)
572 m_setNeedsLayoutWasDeferred = false; // FIXME: Find a way to make the deferred layout actually happen.
575 void FrameView::adjustViewSize()
577 RenderView* renderView = this->renderView();
581 ASSERT(frame().view() == this);
583 const IntRect rect = renderView->documentRect();
584 const IntSize& size = rect.size();
585 ScrollView::setScrollOrigin(IntPoint(-rect.x(), -rect.y()), !frame().document()->printing(), size == contentsSize());
587 setContentsSize(size);
590 void FrameView::applyOverflowToViewport(RenderElement* o, ScrollbarMode& hMode, ScrollbarMode& vMode)
592 // Handle the overflow:hidden/scroll case for the body/html elements. WinIE treats
593 // overflow:hidden and overflow:scroll on <body> as applying to the document's
594 // scrollbars. The CSS2.1 draft states that HTML UAs should use the <html> or <body> element and XML/XHTML UAs should
595 // use the root element.
597 // To combat the inability to scroll on a page with overflow:hidden on the root when scaled, disregard hidden when
598 // there is a frameScaleFactor that is greater than one on the main frame. Also disregard hidden if there is a
601 bool overrideHidden = frame().isMainFrame() && ((frame().frameScaleFactor() > 1) || headerHeight() || footerHeight());
603 EOverflow overflowX = o->style().overflowX();
604 EOverflow overflowY = o->style().overflowY();
607 if (o->isSVGRoot()) {
608 // overflow is ignored in stand-alone SVG documents.
609 if (!toRenderSVGRoot(o)->isEmbeddedThroughFrameContainingSVGDocument())
619 hMode = ScrollbarAuto;
621 hMode = ScrollbarAlwaysOff;
624 hMode = ScrollbarAlwaysOn;
627 hMode = ScrollbarAuto;
630 // Don't set it at all.
637 vMode = ScrollbarAuto;
639 vMode = ScrollbarAlwaysOff;
642 vMode = ScrollbarAlwaysOn;
645 vMode = ScrollbarAuto;
648 // Don't set it at all. Values of OPAGEDX and OPAGEDY are handled by applyPaginationToViewPort().
652 m_viewportRenderer = o;
655 void FrameView::applyPaginationToViewport()
657 Document* document = frame().document();
658 auto documentElement = document->documentElement();
659 RenderElement* documentRenderer = documentElement ? documentElement->renderer() : nullptr;
660 RenderElement* documentOrBodyRenderer = documentRenderer;
661 auto body = document->body();
662 if (body && body->renderer()) {
663 if (body->hasTagName(bodyTag))
664 documentOrBodyRenderer = documentRenderer->style().overflowX() == OVISIBLE && documentElement->hasTagName(htmlTag) ? body->renderer() : documentRenderer;
667 Pagination pagination;
669 if (!documentOrBodyRenderer) {
670 setPagination(pagination);
674 EOverflow overflowY = documentOrBodyRenderer->style().overflowY();
675 if (overflowY == OPAGEDX || overflowY == OPAGEDY) {
676 pagination.mode = WebCore::paginationModeForRenderStyle(documentOrBodyRenderer->style());
677 pagination.gap = static_cast<unsigned>(documentOrBodyRenderer->style().columnGap());
680 setPagination(pagination);
683 void FrameView::calculateScrollbarModesForLayout(ScrollbarMode& hMode, ScrollbarMode& vMode, ScrollbarModesCalculationStrategy strategy)
685 m_viewportRenderer = 0;
687 const HTMLFrameOwnerElement* owner = frame().ownerElement();
688 if (owner && (owner->scrollingMode() == ScrollbarAlwaysOff)) {
689 hMode = ScrollbarAlwaysOff;
690 vMode = ScrollbarAlwaysOff;
694 if (m_canHaveScrollbars || strategy == RulesFromWebContentOnly) {
695 hMode = ScrollbarAuto;
696 // Seamless documents begin with heights of 0; we special case that here
697 // to correctly render documents that don't need scrollbars.
698 IntSize fullVisibleSize = visibleContentRect(IncludeScrollbars).size();
699 bool isSeamlessDocument = frame().document() && frame().document()->shouldDisplaySeamlesslyWithParent();
700 vMode = (isSeamlessDocument && !fullVisibleSize.height()) ? ScrollbarAlwaysOff : ScrollbarAuto;
702 hMode = ScrollbarAlwaysOff;
703 vMode = ScrollbarAlwaysOff;
707 Document* document = frame().document();
708 auto documentElement = document->documentElement();
709 RenderElement* rootRenderer = documentElement ? documentElement->renderer() : nullptr;
710 auto body = document->body();
711 if (body && body->renderer()) {
712 if (body->hasTagName(framesetTag) && !frameFlatteningEnabled()) {
713 vMode = ScrollbarAlwaysOff;
714 hMode = ScrollbarAlwaysOff;
715 } else if (body->hasTagName(bodyTag)) {
716 // It's sufficient to just check the X overflow,
717 // since it's illegal to have visible in only one direction.
718 RenderElement* o = rootRenderer->style().overflowX() == OVISIBLE && document->documentElement()->hasTagName(htmlTag) ? body->renderer() : rootRenderer;
719 applyOverflowToViewport(o, hMode, vMode);
721 } else if (rootRenderer)
722 applyOverflowToViewport(rootRenderer, hMode, vMode);
726 #if USE(ACCELERATED_COMPOSITING)
727 void FrameView::updateCompositingLayersAfterStyleChange()
729 RenderView* renderView = this->renderView();
733 // If we expect to update compositing after an incipient layout, don't do so here.
734 if (inPreLayoutStyleUpdate() || layoutPending() || renderView->needsLayout())
737 RenderLayerCompositor& compositor = renderView->compositor();
738 // This call will make sure the cached hasAcceleratedCompositing is updated from the pref
739 compositor.cacheAcceleratedCompositingFlags();
740 compositor.updateCompositingLayers(CompositingUpdateAfterStyleChange);
743 void FrameView::updateCompositingLayersAfterLayout()
745 RenderView* renderView = this->renderView();
749 // This call will make sure the cached hasAcceleratedCompositing is updated from the pref
750 renderView->compositor().cacheAcceleratedCompositingFlags();
751 renderView->compositor().updateCompositingLayers(CompositingUpdateAfterLayout);
754 void FrameView::clearBackingStores()
756 RenderView* renderView = this->renderView();
760 RenderLayerCompositor& compositor = renderView->compositor();
761 ASSERT(compositor.inCompositingMode());
762 compositor.enableCompositingMode(false);
763 compositor.clearBackingForAllLayers();
766 void FrameView::restoreBackingStores()
768 RenderView* renderView = this->renderView();
772 RenderLayerCompositor& compositor = renderView->compositor();
773 compositor.enableCompositingMode(true);
774 compositor.updateCompositingLayers(CompositingUpdateAfterLayout);
777 bool FrameView::usesCompositedScrolling() const
779 RenderView* renderView = this->renderView();
782 if (frame().settings().compositedScrollingForFramesEnabled())
783 return renderView->compositor().inForcedCompositingMode();
787 GraphicsLayer* FrameView::layerForScrolling() const
789 RenderView* renderView = this->renderView();
792 return renderView->compositor().scrollLayer();
795 GraphicsLayer* FrameView::layerForHorizontalScrollbar() const
797 RenderView* renderView = this->renderView();
800 return renderView->compositor().layerForHorizontalScrollbar();
803 GraphicsLayer* FrameView::layerForVerticalScrollbar() const
805 RenderView* renderView = this->renderView();
808 return renderView->compositor().layerForVerticalScrollbar();
811 GraphicsLayer* FrameView::layerForScrollCorner() const
813 RenderView* renderView = this->renderView();
816 return renderView->compositor().layerForScrollCorner();
819 TiledBacking* FrameView::tiledBacking()
821 RenderView* renderView = this->renderView();
825 RenderLayerBacking* backing = renderView->layer()->backing();
829 return backing->graphicsLayer()->tiledBacking();
832 uint64_t FrameView::scrollLayerID() const
834 RenderView* renderView = this->renderView();
838 RenderLayerBacking* backing = renderView->layer()->backing();
842 return backing->scrollLayerID();
845 #if ENABLE(RUBBER_BANDING)
846 GraphicsLayer* FrameView::layerForOverhangAreas() const
848 RenderView* renderView = this->renderView();
851 return renderView->compositor().layerForOverhangAreas();
854 GraphicsLayer* FrameView::setWantsLayerForTopOverHangArea(bool wantsLayer) const
856 RenderView* renderView = this->renderView();
860 return renderView->compositor().updateLayerForTopOverhangArea(wantsLayer);
863 GraphicsLayer* FrameView::setWantsLayerForBottomOverHangArea(bool wantsLayer) const
865 RenderView* renderView = this->renderView();
869 return renderView->compositor().updateLayerForBottomOverhangArea(wantsLayer);
872 #endif // ENABLE(RUBBER_BANDING)
874 bool FrameView::flushCompositingStateForThisFrame(Frame* rootFrameForFlush)
876 RenderView* renderView = this->renderView();
878 return true; // We don't want to keep trying to update layers if we have no renderer.
880 ASSERT(frame().view() == this);
882 // If we sync compositing layers when a layout is pending, we may cause painting of compositing
883 // layer content to occur before layout has happened, which will cause paintContents() to bail.
887 // If we sync compositing layers and allow the repaint to be deferred, there is time for a
888 // visible flash to occur. Instead, stop the deferred repaint timer and repaint immediately.
889 flushDeferredRepaints();
891 renderView->compositor().flushPendingLayerChanges(rootFrameForFlush == &frame());
896 void FrameView::setNeedsOneShotDrawingSynchronization()
898 if (Page* page = frame().page())
899 page->chrome().client().setNeedsOneShotDrawingSynchronization();
902 #endif // USE(ACCELERATED_COMPOSITING)
904 void FrameView::setHeaderHeight(int headerHeight)
907 ASSERT(frame().isMainFrame());
908 m_headerHeight = headerHeight;
910 if (RenderView* renderView = this->renderView())
911 renderView->setNeedsLayout();
914 void FrameView::setFooterHeight(int footerHeight)
917 ASSERT(frame().isMainFrame());
918 m_footerHeight = footerHeight;
920 if (RenderView* renderView = this->renderView())
921 renderView->setNeedsLayout();
924 bool FrameView::hasCompositedContent() const
926 #if USE(ACCELERATED_COMPOSITING)
927 if (RenderView* renderView = this->renderView())
928 return renderView->compositor().inCompositingMode();
933 bool FrameView::hasCompositedContentIncludingDescendants() const
935 #if USE(ACCELERATED_COMPOSITING)
936 for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) {
937 RenderView* renderView = frame->contentRenderer();
938 if (RenderLayerCompositor* compositor = renderView ? &renderView->compositor() : 0) {
939 if (compositor->inCompositingMode())
942 if (!RenderLayerCompositor::allowsIndependentlyCompositedFrames(this))
950 bool FrameView::hasCompositingAncestor() const
952 #if USE(ACCELERATED_COMPOSITING)
953 for (Frame* frame = this->frame().tree().parent(); frame; frame = frame->tree().parent()) {
954 if (FrameView* view = frame->view()) {
955 if (view->hasCompositedContent())
963 // Sometimes (for plug-ins) we need to eagerly go into compositing mode.
964 void FrameView::enterCompositingMode()
966 #if USE(ACCELERATED_COMPOSITING)
967 if (RenderView* renderView = this->renderView()) {
968 renderView->compositor().enableCompositingMode();
970 renderView->compositor().scheduleCompositingLayerUpdate();
975 bool FrameView::isEnclosedInCompositingLayer() const
977 #if USE(ACCELERATED_COMPOSITING)
978 auto frameOwnerRenderer = frame().ownerRenderer();
979 if (frameOwnerRenderer && frameOwnerRenderer->containerForRepaint())
982 if (FrameView* parentView = parentFrameView())
983 return parentView->isEnclosedInCompositingLayer();
988 bool FrameView::flushCompositingStateIncludingSubframes()
990 #if USE(ACCELERATED_COMPOSITING)
991 bool allFramesFlushed = flushCompositingStateForThisFrame(&frame());
993 for (Frame* child = frame().tree().firstChild(); child; child = child->tree().traverseNext(&frame())) {
994 bool flushed = child->view()->flushCompositingStateForThisFrame(&frame());
995 allFramesFlushed &= flushed;
997 return allFramesFlushed;
998 #else // USE(ACCELERATED_COMPOSITING)
1003 bool FrameView::isSoftwareRenderable() const
1005 #if USE(ACCELERATED_COMPOSITING)
1006 RenderView* renderView = this->renderView();
1007 return !renderView || !renderView->compositor().has3DContent();
1013 void FrameView::didMoveOnscreen()
1015 contentAreaDidShow();
1018 void FrameView::willMoveOffscreen()
1020 contentAreaDidHide();
1023 void FrameView::setIsInWindow(bool isInWindow)
1025 if (RenderView* renderView = this->renderView())
1026 renderView->setIsInWindow(isInWindow);
1029 RenderObject* FrameView::layoutRoot(bool onlyDuringLayout) const
1031 return onlyDuringLayout && layoutPending() ? 0 : m_layoutRoot;
1034 inline void FrameView::forceLayoutParentViewIfNeeded()
1037 RenderWidget* ownerRenderer = frame().ownerRenderer();
1041 RenderBox* contentBox = embeddedContentBox();
1045 RenderSVGRoot* svgRoot = toRenderSVGRoot(contentBox);
1046 if (svgRoot->everHadLayout() && !svgRoot->needsLayout())
1049 // If the embedded SVG document appears the first time, the ownerRenderer has already finished
1050 // layout without knowing about the existence of the embedded SVG document, because RenderReplaced
1051 // embeddedContentBox() returns 0, as long as the embedded document isn't loaded yet. Before
1052 // bothering to lay out the SVG document, mark the ownerRenderer needing layout and ask its
1053 // FrameView for a layout. After that the RenderEmbeddedObject (ownerRenderer) carries the
1054 // correct size, which RenderSVGRoot::computeReplacedLogicalWidth/Height rely on, when laying
1055 // out for the first time, or when the RenderSVGRoot size has changed dynamically (eg. via <script>).
1056 Ref<FrameView> frameView(ownerRenderer->view().frameView());
1058 // Mark the owner renderer as needing layout.
1059 ownerRenderer->setNeedsLayoutAndPrefWidthsRecalc();
1061 // Synchronously enter layout, to layout the view containing the host object/embed/iframe.
1062 frameView->layout();
1066 void FrameView::layout(bool allowSubtree)
1071 // Many of the tasks performed during layout can cause this function to be re-entered,
1072 // so save the layout phase now and restore it on exit.
1073 TemporaryChange<LayoutPhase> layoutPhaseRestorer(m_layoutPhase, InPreLayout);
1075 // Protect the view from being deleted during layout (in recalcStyle)
1076 Ref<FrameView> protect(*this);
1078 // Every scroll that happens during layout is programmatic.
1079 TemporaryChange<bool> changeInProgrammaticScroll(m_inProgrammaticScroll, true);
1081 bool inChildFrameLayoutWithFrameFlattening = isInChildFrameWithFrameFlattening();
1083 if (inChildFrameLayoutWithFrameFlattening) {
1084 startLayoutAtMainFrameViewIfNeeded(allowSubtree);
1085 RenderElement* root = m_layoutRoot ? m_layoutRoot : frame().document()->renderView();
1086 if (!root->needsLayout())
1090 m_layoutTimer.stop();
1091 m_delayedLayout = false;
1092 m_setNeedsLayoutWasDeferred = false;
1094 // we shouldn't enter layout() while painting
1095 ASSERT(!isPainting());
1099 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willLayout(&frame());
1101 if (!allowSubtree && m_layoutRoot) {
1102 m_layoutRoot->markContainingBlocksForLayout(false);
1106 ASSERT(frame().view() == this);
1107 ASSERT(frame().document());
1109 Document& document = *frame().document();
1110 ASSERT(!document.inPageCache());
1113 RenderElement* root;
1116 TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
1118 if (!m_nestedLayoutCount && !m_inSynchronousPostLayout && m_postLayoutTasksTimer.isActive() && !inChildFrameLayoutWithFrameFlattening) {
1119 // This is a new top-level layout. If there are any remaining tasks from the previous
1120 // layout, finish them now.
1121 TemporaryChange<bool> inSynchronousPostLayoutChange(m_inSynchronousPostLayout, true);
1122 performPostLayoutTasks();
1125 m_layoutPhase = InPreLayoutStyleUpdate;
1127 // Viewport-dependent media queries may cause us to need completely different style information.
1128 StyleResolver* styleResolver = document.styleResolverIfExists();
1129 if (!styleResolver || styleResolver->affectedByViewportChange()) {
1130 document.styleResolverChanged(DeferRecalcStyle);
1131 // FIXME: This instrumentation event is not strictly accurate since cached media query results do not persist across StyleResolver rebuilds.
1132 InspectorInstrumentation::mediaQueryResultChanged(&document);
1134 document.evaluateMediaQueryList();
1136 // If there is any pagination to apply, it will affect the RenderView's style, so we should
1137 // take care of that now.
1138 applyPaginationToViewport();
1140 // Always ensure our style info is up-to-date. This can happen in situations where
1141 // the layout beats any sort of style recalc update that needs to occur.
1142 document.updateStyleIfNeeded();
1143 m_layoutPhase = InPreLayout;
1145 subtree = m_layoutRoot;
1147 // If there is only one ref to this view left, then its going to be destroyed as soon as we exit,
1148 // so there's no point to continuing to layout
1152 root = subtree ? m_layoutRoot : document.renderView();
1154 // FIXME: Do we need to set m_size here?
1158 // Close block here so we can set up the font cache purge preventer, which we will still
1159 // want in scope even after we want m_layoutSchedulingEnabled to be restored again.
1160 // The next block sets m_layoutSchedulingEnabled back to false once again.
1163 FontCachePurgePreventer fontCachePurgePreventer;
1166 ++m_nestedLayoutCount;
1169 TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
1171 if (!m_layoutRoot) {
1172 HTMLElement* body = document.body();
1173 if (body && body->renderer()) {
1174 if (body->hasTagName(framesetTag) && !frameFlatteningEnabled()) {
1175 body->renderer()->setChildNeedsLayout();
1176 } else if (body->hasTagName(bodyTag)) {
1177 if (!m_firstLayout && m_size.height() != layoutHeight() && body->renderer()->enclosingBox()->stretchesToViewport())
1178 body->renderer()->setChildNeedsLayout();
1182 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1183 if (m_firstLayout && !frame().ownerElement())
1184 printf("Elapsed time before first layout: %d\n", document.elapsedTime());
1188 autoSizeIfEnabled();
1190 m_needsFullRepaint = !subtree && (m_firstLayout || toRenderView(*root).printing());
1193 ScrollbarMode hMode;
1194 ScrollbarMode vMode;
1195 calculateScrollbarModesForLayout(hMode, vMode);
1197 if (m_firstLayout || (hMode != horizontalScrollbarMode() || vMode != verticalScrollbarMode())) {
1198 if (m_firstLayout) {
1199 setScrollbarsSuppressed(true);
1201 m_firstLayout = false;
1202 m_firstLayoutCallbackPending = true;
1203 if (useFixedLayout() && !fixedLayoutSize().isEmpty() && delegatesScrolling())
1204 m_lastViewportSize = fixedLayoutSize();
1206 m_lastViewportSize = visibleContentRect(IncludeScrollbars).size();
1208 m_lastZoomFactor = root->style().zoom();
1210 // Set the initial vMode to AlwaysOn if we're auto.
1211 if (vMode == ScrollbarAuto)
1212 setVerticalScrollbarMode(ScrollbarAlwaysOn); // This causes a vertical scrollbar to appear.
1213 // Set the initial hMode to AlwaysOff if we're auto.
1214 if (hMode == ScrollbarAuto)
1215 setHorizontalScrollbarMode(ScrollbarAlwaysOff); // This causes a horizontal scrollbar to disappear.
1217 setScrollbarModes(hMode, vMode);
1218 setScrollbarsSuppressed(false, true);
1220 setScrollbarModes(hMode, vMode);
1223 LayoutSize oldSize = m_size;
1225 m_size = layoutSize();
1227 if (oldSize != m_size) {
1228 m_needsFullRepaint = true;
1229 if (!m_firstLayout) {
1230 RenderBox* rootRenderer = document.documentElement() ? document.documentElement()->renderBox() : 0;
1231 RenderBox* bodyRenderer = rootRenderer && document.body() ? document.body()->renderBox() : 0;
1232 if (bodyRenderer && bodyRenderer->stretchesToViewport())
1233 bodyRenderer->setChildNeedsLayout();
1234 else if (rootRenderer && rootRenderer->stretchesToViewport())
1235 rootRenderer->setChildNeedsLayout();
1239 m_layoutPhase = InPreLayout;
1242 layer = root->enclosingLayer();
1244 pauseScheduledEvents();
1246 bool disableLayoutState = false;
1248 disableLayoutState = root->view().shouldDisableLayoutStateForSubtree(root);
1249 root->view().pushLayoutState(*root);
1251 LayoutStateDisabler layoutStateDisabler(disableLayoutState ? &root->view() : 0);
1253 ASSERT(m_layoutPhase == InPreLayout);
1254 m_layoutPhase = InLayout;
1256 beginDeferredRepaints();
1257 forceLayoutParentViewIfNeeded();
1259 ASSERT(m_layoutPhase == InLayout);
1262 #if ENABLE(IOS_TEXT_AUTOSIZING)
1263 float minZoomFontSize = frame().settings().minimumZoomFontSize();
1264 float visWidth = frame().page()->mainFrame().textAutosizingWidth();
1265 if (minZoomFontSize && visWidth && !root->view().printing()) {
1266 root->adjustComputedFontSizesOnBlocks(minZoomFontSize, visWidth);
1267 bool needsLayout = root->needsLayout();
1272 #if ENABLE(TEXT_AUTOSIZING)
1273 if (document.textAutosizer()->processSubtree(root) && root->needsLayout())
1276 endDeferredRepaints();
1278 ASSERT(m_layoutPhase == InLayout);
1281 root->view().popLayoutState(*root);
1285 // Close block here to end the scope of changeSchedulingEnabled and layoutStateDisabler.
1288 m_layoutPhase = InViewSizeAdjust;
1290 bool neededFullRepaint = m_needsFullRepaint;
1292 if (!subtree && !toRenderView(*root).printing())
1295 m_layoutPhase = InPostLayout;
1297 m_needsFullRepaint = neededFullRepaint;
1299 // Now update the positions of all layers.
1300 beginDeferredRepaints();
1301 if (m_needsFullRepaint)
1302 root->view().repaintRootContents();
1304 layer->updateLayerPositionsAfterLayout(renderView()->layer(), updateLayerPositionFlags(layer, subtree, m_needsFullRepaint));
1306 endDeferredRepaints();
1308 #if USE(ACCELERATED_COMPOSITING)
1309 updateCompositingLayersAfterLayout();
1314 #if PLATFORM(MAC) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(EFL)
1315 if (AXObjectCache* cache = root->document().existingAXObjectCache())
1316 cache->postNotification(root, AXObjectCache::AXLayoutComplete);
1319 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
1320 updateAnnotatedRegions();
1323 ASSERT(!root->needsLayout());
1325 updateCanBlitOnScrollRecursively();
1327 if (document.hasListenerType(Document::OVERFLOWCHANGED_LISTENER))
1328 updateOverflowStatus(layoutWidth() < contentsWidth(), layoutHeight() < contentsHeight());
1330 if (m_postLayoutTasksTimer.isActive())
1331 resumeScheduledEvents();
1333 if (!m_inSynchronousPostLayout) {
1334 if (inChildFrameLayoutWithFrameFlattening)
1335 updateWidgetPositions();
1337 TemporaryChange<bool> inSynchronousPostLayoutChange(m_inSynchronousPostLayout, true);
1338 performPostLayoutTasks(); // Calls resumeScheduledEvents().
1342 if (!m_postLayoutTasksTimer.isActive() && (needsLayout() || m_inSynchronousPostLayout || inChildFrameLayoutWithFrameFlattening)) {
1343 // If we need layout or are already in a synchronous call to postLayoutTasks(),
1344 // defer widget updates and event dispatch until after we return. postLayoutTasks()
1345 // can make us need to update again, and we can get stuck in a nasty cycle unless
1346 // we call it through the timer here.
1347 m_postLayoutTasksTimer.startOneShot(0);
1348 if (needsLayout()) {
1349 pauseScheduledEvents();
1355 InspectorInstrumentation::didLayout(cookie, root);
1357 --m_nestedLayoutCount;
1359 if (m_nestedLayoutCount)
1362 if (Page* page = frame().page())
1363 page->chrome().client().layoutUpdated(&frame());
1366 RenderBox* FrameView::embeddedContentBox() const
1369 RenderView* renderView = this->renderView();
1373 RenderObject* firstChild = renderView->firstChild();
1374 if (!firstChild || !firstChild->isBox())
1377 // Curently only embedded SVG documents participate in the size-negotiation logic.
1378 if (toRenderBox(firstChild)->isSVGRoot())
1379 return toRenderBox(firstChild);
1385 void FrameView::addEmbeddedObjectToUpdate(RenderEmbeddedObject& embeddedObject)
1387 if (!m_embeddedObjectsToUpdate)
1388 m_embeddedObjectsToUpdate = adoptPtr(new ListHashSet<RenderEmbeddedObject*>);
1390 HTMLFrameOwnerElement& element = embeddedObject.frameOwnerElement();
1391 if (isHTMLObjectElement(element) || isHTMLEmbedElement(element)) {
1392 // Tell the DOM element that it needs a widget update.
1393 HTMLPlugInImageElement& pluginElement = toHTMLPlugInImageElement(element);
1394 if (!pluginElement.needsCheckForSizeChange())
1395 pluginElement.setNeedsWidgetUpdate(true);
1398 m_embeddedObjectsToUpdate->add(&embeddedObject);
1401 void FrameView::removeEmbeddedObjectToUpdate(RenderEmbeddedObject& embeddedObject)
1403 if (!m_embeddedObjectsToUpdate)
1406 m_embeddedObjectsToUpdate->remove(&embeddedObject);
1409 void FrameView::setMediaType(const String& mediaType)
1411 m_mediaType = mediaType;
1414 String FrameView::mediaType() const
1416 // See if we have an override type.
1417 String overrideType = frame().loader().client().overrideMediaType();
1418 InspectorInstrumentation::applyEmulatedMedia(&frame(), &overrideType);
1419 if (!overrideType.isNull())
1420 return overrideType;
1424 void FrameView::adjustMediaTypeForPrinting(bool printing)
1427 if (m_mediaTypeWhenNotPrinting.isNull())
1428 m_mediaTypeWhenNotPrinting = mediaType();
1429 setMediaType("print");
1431 if (!m_mediaTypeWhenNotPrinting.isNull())
1432 setMediaType(m_mediaTypeWhenNotPrinting);
1433 m_mediaTypeWhenNotPrinting = String();
1437 bool FrameView::useSlowRepaints(bool considerOverlap) const
1439 bool mustBeSlow = hasSlowRepaintObjects() || (platformWidget() && hasViewportConstrainedObjects());
1441 // FIXME: WidgetMac.mm makes the assumption that useSlowRepaints ==
1442 // m_contentIsOpaque, so don't take the fast path for composited layers
1443 // if they are a platform widget in order to get painting correctness
1444 // for transparent layers. See the comment in WidgetMac::paint.
1445 if (contentsInCompositedLayer() && !platformWidget())
1448 bool isOverlapped = m_isOverlapped && considerOverlap;
1450 if (mustBeSlow || m_cannotBlitToWindow || isOverlapped || !m_contentIsOpaque)
1453 if (FrameView* parentView = parentFrameView())
1454 return parentView->useSlowRepaints(considerOverlap);
1459 bool FrameView::useSlowRepaintsIfNotOverlapped() const
1461 return useSlowRepaints(false);
1464 void FrameView::updateCanBlitOnScrollRecursively()
1466 for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) {
1467 if (FrameView* view = frame->view())
1468 view->setCanBlitOnScroll(!view->useSlowRepaints());
1472 bool FrameView::contentsInCompositedLayer() const
1474 #if USE(ACCELERATED_COMPOSITING)
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 = adoptPtr(new 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 = adoptPtr(new 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
1560 LayoutRect viewportRect = visibleContentRect();
1561 viewportRect.setLocation(toPoint(scrollOffsetForFixedPosition()));
1562 return viewportRect;
1565 IntSize FrameView::scrollOffsetForFixedPosition(const IntRect& visibleContentRect, const IntSize& totalContentsSize, const IntPoint& scrollPosition, const IntPoint& scrollOrigin, float frameScaleFactor, bool fixedElementsLayoutRelativeToFrame, ScrollBehaviorForFixedElements behaviorForFixed, int headerHeight, int footerHeight)
1568 if (behaviorForFixed == StickToDocumentBounds)
1569 position = ScrollableArea::constrainScrollPositionForOverhang(visibleContentRect, totalContentsSize, scrollPosition, scrollOrigin, headerHeight, footerHeight);
1571 position = scrollPosition;
1572 position.setY(position.y() - headerHeight);
1575 IntSize maxSize = totalContentsSize - visibleContentRect.size();
1577 float dragFactorX = (fixedElementsLayoutRelativeToFrame || !maxSize.width()) ? 1 : (totalContentsSize.width() - visibleContentRect.width() * frameScaleFactor) / maxSize.width();
1578 float dragFactorY = (fixedElementsLayoutRelativeToFrame || !maxSize.height()) ? 1 : (totalContentsSize.height() - visibleContentRect.height() * frameScaleFactor) / maxSize.height();
1580 return IntSize(position.x() * dragFactorX / frameScaleFactor, position.y() * dragFactorY / frameScaleFactor);
1583 IntSize FrameView::scrollOffsetForFixedPosition() const
1585 IntRect visibleContentRect = this->visibleContentRect();
1586 IntSize totalContentsSize = this->totalContentsSize();
1587 IntPoint scrollPosition = this->scrollPosition();
1588 IntPoint scrollOrigin = this->scrollOrigin();
1589 float frameScaleFactor = frame().frameScaleFactor();
1590 ScrollBehaviorForFixedElements behaviorForFixed = scrollBehaviorForFixedElements();
1591 return scrollOffsetForFixedPosition(visibleContentRect, totalContentsSize, scrollPosition, scrollOrigin, frameScaleFactor, fixedElementsLayoutRelativeToFrame(), behaviorForFixed, headerHeight(), footerHeight());
1594 IntPoint FrameView::minimumScrollPosition() const
1596 IntPoint minimumPosition(ScrollView::minimumScrollPosition());
1598 if (frame().isMainFrame() && m_scrollPinningBehavior == PinToBottom)
1599 minimumPosition.setY(maximumScrollPosition().y());
1601 return minimumPosition;
1604 IntPoint FrameView::maximumScrollPosition() const
1606 IntPoint maximumOffset(contentsWidth() - visibleWidth() - scrollOrigin().x(), totalContentsSize().height() - visibleHeight() - scrollOrigin().y());
1608 maximumOffset.clampNegativeToZero();
1610 if (frame().isMainFrame() && m_scrollPinningBehavior == PinToTop)
1611 maximumOffset.setY(minimumScrollPosition().y());
1613 return maximumOffset;
1616 bool FrameView::fixedElementsLayoutRelativeToFrame() const
1618 return frame().settings().fixedElementsLayoutRelativeToFrame();
1621 IntPoint FrameView::lastKnownMousePosition() const
1623 return frame().eventHandler().lastKnownMousePosition();
1626 bool FrameView::isHandlingWheelEvent() const
1628 return frame().eventHandler().isHandlingWheelEvent();
1631 bool FrameView::shouldSetCursor() const
1633 Page* page = frame().page();
1634 return page && page->isOnscreen() && page->focusController().isActive();
1637 bool FrameView::scrollContentsFastPath(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect)
1639 if (!m_viewportConstrainedObjects || m_viewportConstrainedObjects->isEmpty()) {
1640 hostWindow()->scroll(scrollDelta, rectToScroll, clipRect);
1644 const bool isCompositedContentLayer = contentsInCompositedLayer();
1646 // Get the rects of the fixed objects visible in the rectToScroll
1647 Region regionToUpdate;
1648 for (auto& renderer : *m_viewportConstrainedObjects) {
1649 if (!renderer->style().hasViewportConstrainedPosition())
1651 #if USE(ACCELERATED_COMPOSITING)
1652 if (renderer->isComposited())
1656 // Fixed items should always have layers.
1657 ASSERT(renderer->hasLayer());
1658 RenderLayer* layer = toRenderBoxModelObject(renderer)->layer();
1660 #if USE(ACCELERATED_COMPOSITING)
1661 if (layer->viewportConstrainedNotCompositedReason() == RenderLayer::NotCompositedForBoundsOutOfView
1662 || layer->viewportConstrainedNotCompositedReason() == RenderLayer::NotCompositedForNoVisibleContent) {
1663 // Don't invalidate for invisible fixed layers.
1668 #if ENABLE(CSS_FILTERS)
1669 if (layer->hasAncestorWithFilterOutsets()) {
1670 // If the fixed layer has a blur/drop-shadow filter applied on at least one of its parents, we cannot
1671 // scroll using the fast path, otherwise the outsets of the filter will be moved around the page.
1675 IntRect updateRect = pixelSnappedIntRect(layer->repaintRectIncludingNonCompositingDescendants());
1676 updateRect = contentsToRootView(updateRect);
1677 if (!isCompositedContentLayer && clipsRepaints())
1678 updateRect.intersect(rectToScroll);
1679 if (!updateRect.isEmpty())
1680 regionToUpdate.unite(updateRect);
1684 hostWindow()->scroll(scrollDelta, rectToScroll, clipRect);
1686 // 2) update the area of fixed objects that has been invalidated
1687 Vector<IntRect> subRectsToUpdate = regionToUpdate.rects();
1688 size_t viewportConstrainedObjectsCount = subRectsToUpdate.size();
1689 for (size_t i = 0; i < viewportConstrainedObjectsCount; ++i) {
1690 IntRect updateRect = subRectsToUpdate[i];
1691 IntRect scrolledRect = updateRect;
1692 scrolledRect.move(scrollDelta);
1693 updateRect.unite(scrolledRect);
1694 #if USE(ACCELERATED_COMPOSITING)
1695 if (isCompositedContentLayer) {
1696 updateRect = rootViewToContents(updateRect);
1697 ASSERT(renderView());
1698 renderView()->layer()->setBackingNeedsRepaintInRect(updateRect);
1702 if (clipsRepaints())
1703 updateRect.intersect(rectToScroll);
1704 hostWindow()->invalidateContentsAndRootView(updateRect, false);
1710 void FrameView::scrollContentsSlowPath(const IntRect& updateRect)
1712 #if USE(ACCELERATED_COMPOSITING)
1713 if (contentsInCompositedLayer()) {
1714 IntRect updateRect = visibleContentRect();
1716 // Make sure to "apply" the scale factor here since we're converting from frame view
1717 // coordinates to layer backing coordinates.
1718 updateRect.scale(1 / frame().frameScaleFactor());
1720 ASSERT(renderView());
1721 renderView()->layer()->setBackingNeedsRepaintInRect(updateRect);
1724 repaintSlowRepaintObjects();
1726 if (RenderWidget* frameRenderer = frame().ownerRenderer()) {
1727 if (isEnclosedInCompositingLayer()) {
1728 LayoutRect rect(frameRenderer->borderLeft() + frameRenderer->paddingLeft(),
1729 frameRenderer->borderTop() + frameRenderer->paddingTop(),
1730 visibleWidth(), visibleHeight());
1731 frameRenderer->repaintRectangle(rect);
1737 ScrollView::scrollContentsSlowPath(updateRect);
1740 void FrameView::repaintSlowRepaintObjects()
1742 if (!m_slowRepaintObjects)
1745 // Renderers with fixed backgrounds may be in compositing layers, so we need to explicitly
1746 // repaint them after scrolling.
1747 for (auto& renderer : *m_slowRepaintObjects)
1748 renderer->repaint();
1751 // Note that this gets called at painting time.
1752 void FrameView::setIsOverlapped(bool isOverlapped)
1754 if (isOverlapped == m_isOverlapped)
1757 m_isOverlapped = isOverlapped;
1758 updateCanBlitOnScrollRecursively();
1760 #if USE(ACCELERATED_COMPOSITING)
1761 if (hasCompositedContentIncludingDescendants()) {
1762 // Overlap can affect compositing tests, so if it changes, we need to trigger
1763 // a layer update in the parent document.
1764 if (Frame* parentFrame = frame().tree().parent()) {
1765 if (RenderView* parentView = parentFrame->contentRenderer()) {
1766 RenderLayerCompositor& compositor = parentView->compositor();
1767 compositor.setCompositingLayersNeedRebuild();
1768 compositor.scheduleCompositingLayerUpdate();
1772 if (RenderLayerCompositor::allowsIndependentlyCompositedFrames(this)) {
1773 // We also need to trigger reevaluation for this and all descendant frames,
1774 // since a frame uses compositing if any ancestor is compositing.
1775 for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) {
1776 if (RenderView* view = frame->contentRenderer()) {
1777 RenderLayerCompositor& compositor = view->compositor();
1778 compositor.setCompositingLayersNeedRebuild();
1779 compositor.scheduleCompositingLayerUpdate();
1787 bool FrameView::isOverlappedIncludingAncestors() const
1792 if (FrameView* parentView = parentFrameView()) {
1793 if (parentView->isOverlapped())
1800 void FrameView::setContentIsOpaque(bool contentIsOpaque)
1802 if (contentIsOpaque == m_contentIsOpaque)
1805 m_contentIsOpaque = contentIsOpaque;
1806 updateCanBlitOnScrollRecursively();
1809 void FrameView::restoreScrollbar()
1811 setScrollbarsSuppressed(false);
1814 bool FrameView::scrollToFragment(const URL& url)
1816 // If our URL has no ref, then we have no place we need to jump to.
1817 // OTOH If CSS target was set previously, we want to set it to 0, recalc
1818 // and possibly repaint because :target pseudo class may have been
1819 // set (see bug 11321).
1820 if (!url.hasFragmentIdentifier() && !frame().document()->cssTarget())
1823 String fragmentIdentifier = url.fragmentIdentifier();
1824 if (scrollToAnchor(fragmentIdentifier))
1827 // Try again after decoding the ref, based on the document's encoding.
1828 if (TextResourceDecoder* decoder = frame().document()->decoder())
1829 return scrollToAnchor(decodeURLEscapeSequences(fragmentIdentifier, decoder->encoding()));
1834 bool FrameView::scrollToAnchor(const String& name)
1836 ASSERT(frame().document());
1838 if (!frame().document()->haveStylesheetsLoaded()) {
1839 frame().document()->setGotoAnchorNeededAfterStylesheetsLoad(true);
1843 frame().document()->setGotoAnchorNeededAfterStylesheetsLoad(false);
1845 Element* anchorElement = frame().document()->findAnchor(name);
1847 // Setting to null will clear the current target.
1848 frame().document()->setCSSTarget(anchorElement);
1851 if (frame().document()->isSVGDocument()) {
1852 if (SVGSVGElement* svg = toSVGDocument(frame().document())->rootElement()) {
1853 svg->setupInitialView(name, anchorElement);
1860 // Implement the rule that "" and "top" both mean top of page as in other browsers.
1861 if (!anchorElement && !(name.isEmpty() || equalIgnoringCase(name, "top")))
1864 maintainScrollPositionAtAnchor(anchorElement ? static_cast<Node*>(anchorElement) : frame().document());
1866 // If the anchor accepts keyboard focus, move focus there to aid users relying on keyboard navigation.
1867 if (anchorElement && anchorElement->isFocusable())
1868 frame().document()->setFocusedElement(anchorElement);
1873 void FrameView::maintainScrollPositionAtAnchor(Node* anchorNode)
1875 m_maintainScrollPositionAnchor = anchorNode;
1876 if (!m_maintainScrollPositionAnchor)
1879 // We need to update the layout before scrolling, otherwise we could
1880 // really mess things up if an anchor scroll comes at a bad moment.
1881 frame().document()->updateStyleIfNeeded();
1882 // Only do a layout if changes have occurred that make it necessary.
1883 RenderView* renderView = this->renderView();
1884 if (renderView && renderView->needsLayout())
1890 void FrameView::scrollElementToRect(Element* element, const IntRect& rect)
1892 frame().document()->updateLayoutIgnorePendingStylesheets();
1894 LayoutRect bounds = element->boundingBox();
1895 int centeringOffsetX = (rect.width() - bounds.width()) / 2;
1896 int centeringOffsetY = (rect.height() - bounds.height()) / 2;
1897 setScrollPosition(IntPoint(bounds.x() - centeringOffsetX - rect.x(), bounds.y() - centeringOffsetY - rect.y()));
1900 void FrameView::setScrollPosition(const IntPoint& scrollPoint)
1902 TemporaryChange<bool> changeInProgrammaticScroll(m_inProgrammaticScroll, true);
1903 m_maintainScrollPositionAnchor = 0;
1904 ScrollView::setScrollPosition(scrollPoint);
1907 void FrameView::delegatesScrollingDidChange()
1909 #if USE(ACCELERATED_COMPOSITING)
1910 // When we switch to delgatesScrolling mode, we should destroy the scrolling/clipping layers in RenderLayerCompositor.
1911 if (hasCompositedContent())
1912 clearBackingStores();
1916 void FrameView::setFixedVisibleContentRect(const IntRect& visibleContentRect)
1918 bool visibleContentSizeDidChange = false;
1919 if (visibleContentRect.size() != this->fixedVisibleContentRect().size()) {
1920 // When the viewport size changes or the content is scaled, we need to
1921 // reposition the fixed and sticky positioned elements.
1922 setViewportConstrainedObjectsNeedLayout();
1923 visibleContentSizeDidChange = true;
1926 IntSize offset = scrollOffset();
1927 ScrollView::setFixedVisibleContentRect(visibleContentRect);
1928 if (offset != scrollOffset()) {
1929 updateLayerPositionsAfterScrolling();
1930 if (frame().page()->settings().acceleratedCompositingForFixedPositionEnabled())
1931 updateCompositingLayersAfterScrolling();
1932 scrollAnimator()->setCurrentPosition(scrollPosition());
1933 scrollPositionChanged();
1935 if (visibleContentSizeDidChange) {
1936 // Update the scroll-bars to calculate new page-step size.
1937 updateScrollbars(scrollOffset());
1939 frame().loader().client().didChangeScrollOffset();
1942 void FrameView::setViewportConstrainedObjectsNeedLayout()
1944 if (!hasViewportConstrainedObjects())
1947 for (auto& renderer : *m_viewportConstrainedObjects)
1948 renderer->setNeedsLayout();
1951 void FrameView::scrollPositionChangedViaPlatformWidget()
1953 updateLayerPositionsAfterScrolling();
1954 updateCompositingLayersAfterScrolling();
1955 repaintSlowRepaintObjects();
1956 scrollPositionChanged();
1959 void FrameView::scrollPositionChanged()
1961 frame().eventHandler().sendScrollEvent();
1962 frame().eventHandler().dispatchFakeMouseMoveEventSoon();
1964 #if USE(ACCELERATED_COMPOSITING)
1965 if (RenderView* renderView = this->renderView()) {
1966 if (renderView->usesCompositing())
1967 renderView->compositor().frameViewDidScroll();
1972 void FrameView::updateLayerPositionsAfterScrolling()
1974 // If we're scrolling as a result of updating the view size after layout, we'll update widgets and layer positions soon anyway.
1975 if (m_layoutPhase == InViewSizeAdjust)
1978 if (m_nestedLayoutCount <= 1 && hasViewportConstrainedObjects()) {
1979 if (RenderView* renderView = this->renderView()) {
1980 updateWidgetPositions();
1981 renderView->layer()->updateLayerPositionsAfterDocumentScroll();
1986 bool FrameView::shouldUpdateCompositingLayersAfterScrolling() const
1988 #if ENABLE(THREADED_SCROLLING)
1989 // If the scrolling thread is updating the fixed elements, then the FrameView should not update them as well.
1991 Page* page = frame().page();
1995 if (&page->mainFrame() != &frame())
1998 ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator();
1999 if (!scrollingCoordinator)
2002 if (!scrollingCoordinator->supportsFixedPositionLayers())
2005 if (scrollingCoordinator->shouldUpdateScrollLayerPositionOnMainThread())
2008 if (inProgrammaticScroll())
2016 void FrameView::updateCompositingLayersAfterScrolling()
2018 #if USE(ACCELERATED_COMPOSITING)
2019 if (!shouldUpdateCompositingLayersAfterScrolling())
2022 if (m_nestedLayoutCount <= 1 && hasViewportConstrainedObjects()) {
2023 if (RenderView* renderView = this->renderView())
2024 renderView->compositor().updateCompositingLayers(CompositingUpdateOnScroll);
2029 bool FrameView::isRubberBandInProgress() const
2031 if (scrollbarsSuppressed())
2034 // If the scrolling thread updates the scroll position for this FrameView, then we should return
2035 // ScrollingCoordinator::isRubberBandInProgress().
2036 if (Page* page = frame().page()) {
2037 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator()) {
2038 if (!scrollingCoordinator->shouldUpdateScrollLayerPositionOnMainThread())
2039 return scrollingCoordinator->isRubberBandInProgress();
2043 // If the main thread updates the scroll position for this FrameView, we should return
2044 // ScrollAnimator::isRubberBandInProgress().
2045 if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
2046 return scrollAnimator->isRubberBandInProgress();
2051 bool FrameView::requestScrollPositionUpdate(const IntPoint& position)
2053 #if ENABLE(THREADED_SCROLLING)
2054 if (TiledBacking* tiledBacking = this->tiledBacking()) {
2055 IntRect visibleRect = visibleContentRect();
2056 visibleRect.setLocation(position);
2057 tiledBacking->prepopulateRect(visibleRect);
2060 if (Page* page = frame().page()) {
2061 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
2062 return scrollingCoordinator->requestScrollPositionUpdate(this, position);
2065 UNUSED_PARAM(position);
2071 HostWindow* FrameView::hostWindow() const
2073 if (Page* page = frame().page())
2074 return &page->chrome();
2078 void FrameView::addTrackedRepaintRect(const IntRect& r)
2080 if (!m_isTrackingRepaints || r.isEmpty())
2083 IntRect repaintRect = r;
2084 repaintRect.move(-scrollOffset());
2085 m_trackedRepaintRects.append(repaintRect);
2088 const unsigned cRepaintRectUnionThreshold = 25;
2090 void FrameView::repaintContentRectangle(const IntRect& r, bool immediate)
2092 ASSERT(!frame().ownerElement());
2094 addTrackedRepaintRect(r);
2096 double delay = m_deferringRepaints ? 0 : adjustedDeferredRepaintDelay();
2097 if ((m_deferringRepaints || m_deferredRepaintTimer.isActive() || delay) && !immediate) {
2098 IntRect paintRect = r;
2099 if (clipsRepaints() && !paintsEntireContents())
2100 paintRect.intersect(visibleContentRect());
2101 if (paintRect.isEmpty())
2103 if (m_repaintCount == cRepaintRectUnionThreshold) {
2104 IntRect unionedRect;
2105 for (unsigned i = 0; i < cRepaintRectUnionThreshold; ++i)
2106 unionedRect.unite(pixelSnappedIntRect(m_repaintRects[i]));
2107 m_repaintRects.clear();
2108 m_repaintRects.append(unionedRect);
2110 if (m_repaintCount < cRepaintRectUnionThreshold)
2111 m_repaintRects.append(paintRect);
2113 m_repaintRects[0].unite(paintRect);
2116 if (!m_deferringRepaints)
2117 startDeferredRepaintTimer(delay);
2122 if (!shouldUpdate(immediate))
2125 #if USE(TILED_BACKING_STORE)
2126 if (frame().tiledBackingStore()) {
2127 frame().tiledBackingStore()->invalidate(r);
2131 ScrollView::repaintContentRectangle(r, immediate);
2134 void FrameView::contentsResized()
2136 ScrollView::contentsResized();
2140 void FrameView::fixedLayoutSizeChanged()
2142 // Can be triggered before the view is set, see comment in FrameView::visibleContentsResized().
2143 // An ASSERT is triggered when a view schedules a layout before being attached to a frame.
2144 if (!frame().view())
2146 ScrollView::fixedLayoutSizeChanged();
2149 void FrameView::visibleContentsResized()
2151 // We check to make sure the view is attached to a frame() as this method can
2152 // be triggered before the view is attached by Frame::createView(...) setting
2153 // various values such as setScrollBarModes(...) for example. An ASSERT is
2154 // triggered when a view is layout before being attached to a frame().
2155 if (!frame().view())
2158 if (!useFixedLayout() && needsLayout())
2161 #if USE(ACCELERATED_COMPOSITING)
2162 if (RenderView* renderView = this->renderView()) {
2163 if (renderView->usesCompositing())
2164 renderView->compositor().frameViewDidChangeSize();
2169 void FrameView::addedOrRemovedScrollbar()
2171 #if USE(ACCELERATED_COMPOSITING)
2172 if (RenderView* renderView = this->renderView()) {
2173 if (renderView->usesCompositing())
2174 renderView->compositor().frameViewDidAddOrRemoveScrollbars();
2179 void FrameView::beginDeferredRepaints()
2181 if (!frame().isMainFrame()) {
2182 frame().mainFrame().view()->beginDeferredRepaints();
2186 m_deferringRepaints++;
2189 void FrameView::endDeferredRepaints()
2191 if (!frame().isMainFrame()) {
2192 frame().mainFrame().view()->endDeferredRepaints();
2196 ASSERT(m_deferringRepaints > 0);
2198 if (--m_deferringRepaints)
2201 if (m_deferredRepaintTimer.isActive())
2204 if (double delay = adjustedDeferredRepaintDelay()) {
2205 startDeferredRepaintTimer(delay);
2209 doDeferredRepaints();
2212 void FrameView::startDeferredRepaintTimer(double delay)
2214 if (m_deferredRepaintTimer.isActive())
2217 m_deferredRepaintTimer.startOneShot(delay);
2220 void FrameView::handleLoadCompleted()
2222 // Once loading has completed, allow autoSize one last opportunity to
2223 // reduce the size of the frame.
2224 autoSizeIfEnabled();
2225 if (shouldUseLoadTimeDeferredRepaintDelay())
2227 m_deferredRepaintDelay = s_normalDeferredRepaintDelay;
2228 flushDeferredRepaints();
2231 void FrameView::flushDeferredRepaints()
2233 if (!m_deferredRepaintTimer.isActive())
2235 m_deferredRepaintTimer.stop();
2236 doDeferredRepaints();
2239 void FrameView::doDeferredRepaints()
2241 ASSERT(!m_deferringRepaints);
2242 if (!shouldUpdate()) {
2243 m_repaintRects.clear();
2247 unsigned size = m_repaintRects.size();
2248 for (unsigned i = 0; i < size; i++) {
2249 #if USE(TILED_BACKING_STORE)
2250 if (frame().tiledBackingStore()) {
2251 frame().tiledBackingStore()->invalidate(pixelSnappedIntRect(m_repaintRects[i]));
2255 ScrollView::repaintContentRectangle(pixelSnappedIntRect(m_repaintRects[i]), false);
2257 m_repaintRects.clear();
2260 updateDeferredRepaintDelayAfterRepaint();
2263 bool FrameView::shouldUseLoadTimeDeferredRepaintDelay() const
2265 // Don't defer after the initial load of the page has been completed.
2266 if (frame().tree().top().loader().isComplete())
2268 Document* document = frame().document();
2271 if (document->parsing())
2273 if (document->cachedResourceLoader()->requestCount())
2278 void FrameView::updateDeferredRepaintDelayAfterRepaint()
2280 if (!shouldUseLoadTimeDeferredRepaintDelay()) {
2281 m_deferredRepaintDelay = s_normalDeferredRepaintDelay;
2284 double incrementedRepaintDelay = m_deferredRepaintDelay + s_deferredRepaintDelayIncrementDuringLoading;
2285 m_deferredRepaintDelay = std::min(incrementedRepaintDelay, s_maxDeferredRepaintDelayDuringLoading);
2288 void FrameView::resetDeferredRepaintDelay()
2290 m_deferredRepaintDelay = 0;
2291 if (m_deferredRepaintTimer.isActive()) {
2292 m_deferredRepaintTimer.stop();
2293 if (!m_deferringRepaints)
2294 doDeferredRepaints();
2296 #if USE(ACCELERATED_COMPOSITING)
2297 if (RenderView* view = renderView())
2298 view->compositor().disableLayerFlushThrottlingTemporarilyForInteraction();
2302 double FrameView::adjustedDeferredRepaintDelay() const
2304 ASSERT(!m_deferringRepaints);
2305 if (!m_deferredRepaintDelay)
2307 double timeSinceLastPaint = monotonicallyIncreasingTime() - m_lastPaintTime;
2308 return std::max<double>(0, m_deferredRepaintDelay - timeSinceLastPaint);
2311 void FrameView::deferredRepaintTimerFired(Timer<FrameView>*)
2313 doDeferredRepaints();
2316 void FrameView::updateLayerFlushThrottlingInAllFrames()
2318 #if USE(ACCELERATED_COMPOSITING)
2319 bool isMainLoadProgressing = frame().page()->progress().isMainLoadProgressing();
2320 for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) {
2321 if (RenderView* renderView = frame->contentRenderer())
2322 renderView->compositor().setLayerFlushThrottlingEnabled(isMainLoadProgressing);
2327 void FrameView::adjustTiledBackingCoverage()
2329 #if USE(ACCELERATED_COMPOSITING)
2330 RenderView* renderView = this->renderView();
2331 if (renderView && renderView->layer()->backing())
2332 renderView->layer()->backing()->adjustTiledBackingCoverage();
2336 void FrameView::layoutTimerFired(Timer<FrameView>*)
2338 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2339 if (!frame().document()->ownerElement())
2340 printf("Layout timer fired at %d\n", frame().document()->elapsedTime());
2345 void FrameView::scheduleRelayout()
2347 // FIXME: We should assert the page is not in the page cache, but that is causing
2348 // too many false assertions. See <rdar://problem/7218118>.
2349 ASSERT(frame().view() == this);
2352 m_layoutRoot->markContainingBlocksForLayout(false);
2355 if (!m_layoutSchedulingEnabled)
2359 if (!frame().document()->shouldScheduleLayout())
2361 InspectorInstrumentation::didInvalidateLayout(&frame());
2362 // When frame flattening is enabled, the contents of the frame could affect the layout of the parent frames.
2363 // Also invalidate parent frame starting from the owner element of this frame.
2364 if (frame().ownerRenderer() && isInChildFrameWithFrameFlattening())
2365 frame().ownerRenderer()->setNeedsLayout(MarkContainingBlockChain);
2367 int delay = frame().document()->minimumLayoutDelay();
2368 if (m_layoutTimer.isActive() && m_delayedLayout && !delay)
2369 unscheduleRelayout();
2370 if (m_layoutTimer.isActive())
2373 m_delayedLayout = delay != 0;
2375 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2376 if (!frame().document()->ownerElement())
2377 printf("Scheduling layout for %d\n", delay);
2380 m_layoutTimer.startOneShot(delay * 0.001);
2383 static bool isObjectAncestorContainerOf(RenderObject* ancestor, RenderObject* descendant)
2385 for (RenderObject* r = descendant; r; r = r->container()) {
2392 void FrameView::scheduleRelayoutOfSubtree(RenderElement& newRelayoutRoot)
2394 ASSERT(renderView());
2395 RenderView& renderView = *this->renderView();
2397 // Try to catch unnecessary work during render tree teardown.
2398 ASSERT(!renderView.documentBeingDestroyed());
2399 ASSERT(frame().view() == this);
2401 if (renderView.needsLayout()) {
2402 newRelayoutRoot.markContainingBlocksForLayout(false);
2406 if (!layoutPending() && m_layoutSchedulingEnabled) {
2407 int delay = renderView.document().minimumLayoutDelay();
2408 ASSERT(!newRelayoutRoot.container() || !newRelayoutRoot.container()->needsLayout());
2409 m_layoutRoot = &newRelayoutRoot;
2410 InspectorInstrumentation::didInvalidateLayout(&frame());
2411 m_delayedLayout = delay != 0;
2412 m_layoutTimer.startOneShot(delay * 0.001);
2416 if (m_layoutRoot == &newRelayoutRoot)
2419 if (!m_layoutRoot) {
2420 // Just relayout the subtree.
2421 newRelayoutRoot.markContainingBlocksForLayout(false);
2422 InspectorInstrumentation::didInvalidateLayout(&frame());
2426 if (isObjectAncestorContainerOf(m_layoutRoot, &newRelayoutRoot)) {
2427 // Keep the current root.
2428 newRelayoutRoot.markContainingBlocksForLayout(false, m_layoutRoot);
2429 ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
2433 if (isObjectAncestorContainerOf(&newRelayoutRoot, m_layoutRoot)) {
2434 // Re-root at newRelayoutRoot.
2435 m_layoutRoot->markContainingBlocksForLayout(false, &newRelayoutRoot);
2436 m_layoutRoot = &newRelayoutRoot;
2437 ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
2438 InspectorInstrumentation::didInvalidateLayout(&frame());
2442 // Just do a full relayout.
2443 m_layoutRoot->markContainingBlocksForLayout(false);
2445 newRelayoutRoot.markContainingBlocksForLayout(false);
2446 InspectorInstrumentation::didInvalidateLayout(&frame());
2449 bool FrameView::layoutPending() const
2451 return m_layoutTimer.isActive();
2454 bool FrameView::needsLayout() const
2456 // This can return true in cases where the document does not have a body yet.
2457 // Document::shouldScheduleLayout takes care of preventing us from scheduling
2458 // layout in that case.
2459 RenderView* renderView = this->renderView();
2460 return layoutPending()
2461 || (renderView && renderView->needsLayout())
2463 || (m_deferSetNeedsLayouts && m_setNeedsLayoutWasDeferred);
2466 void FrameView::setNeedsLayout()
2468 if (m_deferSetNeedsLayouts) {
2469 m_setNeedsLayoutWasDeferred = true;
2473 if (RenderView* renderView = this->renderView())
2474 renderView->setNeedsLayout();
2477 void FrameView::unscheduleRelayout()
2479 if (!m_layoutTimer.isActive())
2482 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2483 if (!frame().document()->ownerElement())
2484 printf("Layout timer unscheduled at %d\n", frame().document()->elapsedTime());
2487 m_layoutTimer.stop();
2488 m_delayedLayout = false;
2491 #if ENABLE(REQUEST_ANIMATION_FRAME)
2492 void FrameView::serviceScriptedAnimations(double monotonicAnimationStartTime)
2494 for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext()) {
2495 frame->view()->serviceScrollAnimations();
2496 frame->animation().serviceAnimations();
2499 Vector<RefPtr<Document>> documents;
2500 for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext())
2501 documents.append(frame->document());
2503 for (size_t i = 0; i < documents.size(); ++i)
2504 documents[i]->serviceScriptedAnimations(monotonicAnimationStartTime);
2508 bool FrameView::isTransparent() const
2510 return m_isTransparent;
2513 void FrameView::setTransparent(bool isTransparent)
2515 m_isTransparent = isTransparent;
2518 bool FrameView::hasOpaqueBackground() const
2520 return !m_isTransparent && !m_baseBackgroundColor.hasAlpha();
2523 Color FrameView::baseBackgroundColor() const
2525 return m_baseBackgroundColor;
2528 void FrameView::setBaseBackgroundColor(const Color& backgroundColor)
2530 if (!backgroundColor.isValid())
2531 m_baseBackgroundColor = Color::white;
2533 m_baseBackgroundColor = backgroundColor;
2535 recalculateScrollbarOverlayStyle();
2538 void FrameView::updateBackgroundRecursively(const Color& backgroundColor, bool transparent)
2540 for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) {
2541 if (FrameView* view = frame->view()) {
2542 view->setTransparent(transparent);
2543 view->setBaseBackgroundColor(backgroundColor);
2548 bool FrameView::shouldUpdateWhileOffscreen() const
2550 return m_shouldUpdateWhileOffscreen;
2553 void FrameView::setShouldUpdateWhileOffscreen(bool shouldUpdateWhileOffscreen)
2555 m_shouldUpdateWhileOffscreen = shouldUpdateWhileOffscreen;
2558 bool FrameView::shouldUpdate(bool immediateRequested) const
2560 if (!immediateRequested && isOffscreen() && !shouldUpdateWhileOffscreen())
2565 struct FrameView::ScheduledEvent {
2566 ScheduledEvent(PassRefPtr<Event> e, PassRefPtr<Node> t) : event(e), target(t) { }
2567 RefPtr<Event> event;
2568 RefPtr<Node> target;
2571 void FrameView::scheduleEvent(PassRefPtr<Event> event, PassRefPtr<Node> eventTarget)
2573 if (!m_scheduledEventSuppressionCount) {
2574 eventTarget->dispatchEvent(event, IGNORE_EXCEPTION);
2577 m_scheduledEvents.append(ScheduledEvent(event, eventTarget));
2580 void FrameView::pauseScheduledEvents()
2582 ++m_scheduledEventSuppressionCount;
2585 void FrameView::resumeScheduledEvents()
2587 ASSERT(m_scheduledEventSuppressionCount);
2588 --m_scheduledEventSuppressionCount;
2589 if (m_scheduledEventSuppressionCount)
2592 Vector<ScheduledEvent> eventsToDispatch = std::move(m_scheduledEvents);
2593 for (auto& scheduledEvent : eventsToDispatch) {
2594 if (!scheduledEvent.target->inDocument())
2596 scheduledEvent.target->dispatchEvent(scheduledEvent.event.release(), IGNORE_EXCEPTION);
2600 void FrameView::scrollToAnchor()
2602 RefPtr<Node> anchorNode = m_maintainScrollPositionAnchor;
2606 if (!anchorNode->renderer())
2610 if (anchorNode != frame().document())
2611 rect = anchorNode->boundingBox();
2613 // Scroll nested layers and frames to reveal the anchor.
2614 // Align to the top and to the closest side (this matches other browsers).
2615 anchorNode->renderer()->scrollRectToVisible(rect, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
2617 if (AXObjectCache* cache = frame().document()->existingAXObjectCache())
2618 cache->handleScrolledToAnchor(anchorNode.get());
2620 // scrollRectToVisible can call into setScrollPosition(), which resets m_maintainScrollPositionAnchor.
2621 m_maintainScrollPositionAnchor = anchorNode;
2624 void FrameView::updateEmbeddedObject(RenderEmbeddedObject& embeddedObject)
2626 // No need to update if it's already crashed or known to be missing.
2627 if (embeddedObject.isPluginUnavailable())
2630 HTMLFrameOwnerElement& element = embeddedObject.frameOwnerElement();
2632 if (embeddedObject.isSnapshottedPlugIn()) {
2633 if (isHTMLObjectElement(element) || isHTMLEmbedElement(element)) {
2634 HTMLPlugInImageElement& pluginElement = toHTMLPlugInImageElement(element);
2635 pluginElement.checkSnapshotStatus();
2640 auto weakRenderer = embeddedObject.createWeakPtr();
2642 // FIXME: This could turn into a real virtual dispatch if we defined
2643 // updateWidget(PluginCreationOption) on HTMLElement.
2644 if (isHTMLObjectElement(element) || isHTMLEmbedElement(element) || isHTMLAppletElement(element)) {
2645 HTMLPlugInImageElement& pluginElement = toHTMLPlugInImageElement(element);
2646 if (pluginElement.needsCheckForSizeChange()) {
2647 pluginElement.checkSnapshotStatus();
2650 if (pluginElement.needsWidgetUpdate())
2651 pluginElement.updateWidget(CreateAnyWidgetType);
2654 // FIXME: It is not clear that Media elements need or want this updateWidget() call.
2655 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
2656 else if (element.isMediaElement())
2657 toHTMLMediaElement(element).updateWidget(CreateAnyWidgetType);
2660 ASSERT_NOT_REACHED();
2662 // It's possible the renderer was destroyed below updateWidget() since loading a plugin may execute arbitrary JavaScript.
2666 embeddedObject.updateWidgetPosition();
2669 bool FrameView::updateEmbeddedObjects()
2671 if (m_nestedLayoutCount > 1 || !m_embeddedObjectsToUpdate || m_embeddedObjectsToUpdate->isEmpty())
2674 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
2676 // Insert a marker for where we should stop.
2677 ASSERT(!m_embeddedObjectsToUpdate->contains(nullptr));
2678 m_embeddedObjectsToUpdate->add(nullptr);
2680 while (!m_embeddedObjectsToUpdate->isEmpty()) {
2681 RenderEmbeddedObject* embeddedObject = m_embeddedObjectsToUpdate->takeFirst();
2682 if (!embeddedObject)
2684 updateEmbeddedObject(*embeddedObject);
2687 return m_embeddedObjectsToUpdate->isEmpty();
2690 void FrameView::flushAnyPendingPostLayoutTasks()
2692 if (!m_postLayoutTasksTimer.isActive())
2695 performPostLayoutTasks();
2698 void FrameView::performPostLayoutTasks()
2700 m_postLayoutTasksTimer.stop();
2702 frame().selection().setCaretRectNeedsUpdate();
2703 frame().selection().updateAppearance();
2705 LayoutMilestones requestedMilestones = 0;
2706 LayoutMilestones milestonesAchieved = 0;
2707 Page* page = frame().page();
2709 requestedMilestones = page->requestedLayoutMilestones();
2711 if (m_nestedLayoutCount <= 1 && frame().document()->documentElement()) {
2712 if (m_firstLayoutCallbackPending) {
2713 m_firstLayoutCallbackPending = false;
2714 frame().loader().didFirstLayout();
2715 if (requestedMilestones & DidFirstLayout)
2716 milestonesAchieved |= DidFirstLayout;
2717 if (frame().isMainFrame())
2718 page->startCountingRelevantRepaintedObjects();
2720 updateIsVisuallyNonEmpty();
2722 // If the layout was done with pending sheets, we are not in fact visually non-empty yet.
2723 if (m_isVisuallyNonEmpty && !frame().document()->didLayoutWithPendingStylesheets() && m_firstVisuallyNonEmptyLayoutCallbackPending) {
2724 m_firstVisuallyNonEmptyLayoutCallbackPending = false;
2725 if (requestedMilestones & DidFirstVisuallyNonEmptyLayout)
2726 milestonesAchieved |= DidFirstVisuallyNonEmptyLayout;
2730 if (milestonesAchieved && frame().isMainFrame())
2731 frame().loader().didLayout(milestonesAchieved);
2733 #if ENABLE(FONT_LOAD_EVENTS)
2734 if (RuntimeEnabledFeatures::sharedFeatures().fontLoadEventsEnabled())
2735 frame().document()->fontloader()->didLayout();
2738 // FIXME: We should consider adding DidLayout as a LayoutMilestone. That would let us merge this
2739 // with didLayout(LayoutMilestones).
2740 frame().loader().client().dispatchDidLayout();
2742 updateWidgetPositions();
2744 // layout() protects FrameView, but it still can get destroyed when updateEmbeddedObjects()
2745 // is called through the post layout timer.
2746 Ref<FrameView> protect(*this);
2748 for (unsigned i = 0; i < maxUpdateEmbeddedObjectsIterations; i++) {
2749 if (updateEmbeddedObjects())
2754 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
2755 scrollingCoordinator->frameViewLayoutUpdated(this);
2758 #if USE(ACCELERATED_COMPOSITING)
2759 if (RenderView* renderView = this->renderView()) {
2760 if (renderView->usesCompositing())
2761 renderView->compositor().frameViewDidLayout();
2767 resumeScheduledEvents();
2769 sendResizeEventIfNeeded();
2772 void FrameView::sendResizeEventIfNeeded()
2774 RenderView* renderView = this->renderView();
2775 if (!renderView || renderView->printing())
2777 if (frame().page() && frame().page()->chrome().client().isSVGImageChromeClient())
2780 IntSize currentSize;
2781 if (useFixedLayout() && !fixedLayoutSize().isEmpty() && delegatesScrolling())
2782 currentSize = fixedLayoutSize();
2784 currentSize = visibleContentRect(IncludeScrollbars).size();
2786 float currentZoomFactor = renderView->style().zoom();
2787 bool shouldSendResizeEvent = !m_firstLayout && (currentSize != m_lastViewportSize || currentZoomFactor != m_lastZoomFactor);
2789 m_lastViewportSize = currentSize;
2790 m_lastZoomFactor = currentZoomFactor;
2792 if (!shouldSendResizeEvent)
2795 bool isMainFrame = frame().isMainFrame();
2796 bool canSendResizeEventSynchronously = isMainFrame && !isInLayout();
2798 // If we resized during layout, queue up a resize event for later, otherwise fire it right away.
2799 RefPtr<Event> resizeEvent = Event::create(eventNames().resizeEvent, false, false);
2800 if (canSendResizeEventSynchronously)
2801 frame().document()->dispatchWindowEvent(resizeEvent.release(), frame().document()->domWindow());
2803 frame().document()->enqueueWindowEvent(resizeEvent.release());
2805 #if ENABLE(INSPECTOR)
2806 Page* page = frame().page();
2807 if (InspectorInstrumentation::hasFrontends() && isMainFrame) {
2808 if (InspectorClient* inspectorClient = page ? page->inspectorController()->inspectorClient() : 0)
2809 inspectorClient->didResizeMainFrame(&frame());
2814 void FrameView::willStartLiveResize()
2816 ScrollView::willStartLiveResize();
2817 adjustTiledBackingCoverage();
2820 void FrameView::willEndLiveResize()
2822 ScrollView::willEndLiveResize();
2823 adjustTiledBackingCoverage();
2826 void FrameView::postLayoutTimerFired(Timer<FrameView>*)
2828 performPostLayoutTasks();
2831 void FrameView::autoSizeIfEnabled()
2833 if (!m_shouldAutoSize)
2839 TemporaryChange<bool> changeInAutoSize(m_inAutoSize, true);
2841 Document* document = frame().document();
2845 RenderView* documentView = document->renderView();
2846 Element* documentElement = document->documentElement();
2847 if (!documentView || !documentElement)
2850 // Start from the minimum size and allow it to grow.
2851 resize(m_minAutoSize.width(), m_minAutoSize.height());
2853 IntSize size = frameRect().size();
2855 // Do the resizing twice. The first time is basically a rough calculation using the preferred width
2856 // which may result in a height change during the second iteration.
2857 for (int i = 0; i < 2; i++) {
2858 // Update various sizes including contentsSize, scrollHeight, etc.
2859 document->updateLayoutIgnorePendingStylesheets();
2860 int width = documentView->minPreferredLogicalWidth();
2861 int height = documentView->documentRect().height();
2862 IntSize newSize(width, height);
2864 // Check to see if a scrollbar is needed for a given dimension and
2865 // if so, increase the other dimension to account for the scrollbar.
2866 // Since the dimensions are only for the view rectangle, once a
2867 // dimension exceeds the maximum, there is no need to increase it further.
2868 if (newSize.width() > m_maxAutoSize.width()) {
2869 RefPtr<Scrollbar> localHorizontalScrollbar = horizontalScrollbar();
2870 if (!localHorizontalScrollbar)
2871 localHorizontalScrollbar = createScrollbar(HorizontalScrollbar);
2872 if (!localHorizontalScrollbar->isOverlayScrollbar())
2873 newSize.setHeight(newSize.height() + localHorizontalScrollbar->height());
2875 // Don't bother checking for a vertical scrollbar because the width is at
2876 // already greater the maximum.
2877 } else if (newSize.height() > m_maxAutoSize.height()) {
2878 RefPtr<Scrollbar> localVerticalScrollbar = verticalScrollbar();
2879 if (!localVerticalScrollbar)
2880 localVerticalScrollbar = createScrollbar(VerticalScrollbar);
2881 if (!localVerticalScrollbar->isOverlayScrollbar())
2882 newSize.setWidth(newSize.width() + localVerticalScrollbar->width());
2884 // Don't bother checking for a horizontal scrollbar because the height is
2885 // already greater the maximum.
2888 // Ensure the size is at least the min bounds.
2889 newSize = newSize.expandedTo(m_minAutoSize);
2891 // Bound the dimensions by the max bounds and determine what scrollbars to show.
2892 ScrollbarMode horizonalScrollbarMode = ScrollbarAlwaysOff;
2893 if (newSize.width() > m_maxAutoSize.width()) {
2894 newSize.setWidth(m_maxAutoSize.width());
2895 horizonalScrollbarMode = ScrollbarAlwaysOn;
2897 ScrollbarMode verticalScrollbarMode = ScrollbarAlwaysOff;
2898 if (newSize.height() > m_maxAutoSize.height()) {
2899 newSize.setHeight(m_maxAutoSize.height());
2900 verticalScrollbarMode = ScrollbarAlwaysOn;
2903 if (newSize == size)
2906 // While loading only allow the size to increase (to avoid twitching during intermediate smaller states)
2907 // unless autoresize has just been turned on or the maximum size is smaller than the current size.
2908 if (m_didRunAutosize && size.height() <= m_maxAutoSize.height() && size.width() <= m_maxAutoSize.width()
2909 && !frame().loader().isComplete() && (newSize.height() < size.height() || newSize.width() < size.width()))
2912 resize(newSize.width(), newSize.height());
2913 // Force the scrollbar state to avoid the scrollbar code adding them and causing them to be needed. For example,
2914 // a vertical scrollbar may cause text to wrap and thus increase the height (which is the only reason the scollbar is needed).
2915 setVerticalScrollbarLock(false);
2916 setHorizontalScrollbarLock(false);
2917 setScrollbarModes(horizonalScrollbarMode, verticalScrollbarMode, true, true);
2920 m_autoSizeContentSize = contentsSize();
2922 if (m_autoSizeFixedMinimumHeight) {
2923 resize(m_autoSizeContentSize.width(), std::max(m_autoSizeFixedMinimumHeight, m_autoSizeContentSize.height()));
2924 document->updateLayoutIgnorePendingStylesheets();
2927 m_didRunAutosize = true;
2930 void FrameView::setAutoSizeFixedMinimumHeight(int fixedMinimumHeight)
2932 if (m_autoSizeFixedMinimumHeight == fixedMinimumHeight)
2935 m_autoSizeFixedMinimumHeight = fixedMinimumHeight;
2940 void FrameView::updateOverflowStatus(bool horizontalOverflow, bool verticalOverflow)
2942 if (!m_viewportRenderer)
2945 if (m_overflowStatusDirty) {
2946 m_horizontalOverflow = horizontalOverflow;
2947 m_verticalOverflow = verticalOverflow;
2948 m_overflowStatusDirty = false;
2952 bool horizontalOverflowChanged = (m_horizontalOverflow != horizontalOverflow);
2953 bool verticalOverflowChanged = (m_verticalOverflow != verticalOverflow);
2955 if (horizontalOverflowChanged || verticalOverflowChanged) {
2956 m_horizontalOverflow = horizontalOverflow;
2957 m_verticalOverflow = verticalOverflow;
2959 scheduleEvent(OverflowEvent::create(horizontalOverflowChanged, horizontalOverflow,
2960 verticalOverflowChanged, verticalOverflow), m_viewportRenderer->element());
2965 const Pagination& FrameView::pagination() const
2967 if (m_pagination != Pagination())
2968 return m_pagination;
2970 if (frame().isMainFrame())
2971 return frame().page()->pagination();
2973 return m_pagination;
2976 void FrameView::setPagination(const Pagination& pagination)
2978 if (m_pagination == pagination)
2981 m_pagination = pagination;
2983 frame().document()->styleResolverChanged(DeferRecalcStyle);
2986 IntRect FrameView::windowClipRect(bool clipToContents) const
2988 ASSERT(frame().view() == this);
2990 if (paintsEntireContents())
2991 return IntRect(IntPoint(), totalContentsSize());
2993 // Set our clip rect to be our contents.
2994 IntRect clipRect = contentsToWindow(visibleContentRect(clipToContents ? ExcludeScrollbars : IncludeScrollbars));
2995 if (!frame().ownerElement())
2998 // Take our owner element and get its clip rect.
2999 HTMLFrameOwnerElement* ownerElement = frame().ownerElement();
3000 if (FrameView* parentView = ownerElement->document().view())
3001 clipRect.intersect(parentView->windowClipRectForFrameOwner(ownerElement, true));
3005 IntRect FrameView::windowClipRectForFrameOwner(const HTMLFrameOwnerElement* ownerElement, bool clipToLayerContents) const
3007 // The renderer can sometimes be null when style="display:none" interacts
3008 // with external content and plugins.
3009 if (!ownerElement->renderer())
3010 return windowClipRect();
3012 // If we have no layer, just return our window clip rect.
3013 const RenderLayer* enclosingLayer = ownerElement->renderer()->enclosingLayer();
3014 if (!enclosingLayer)
3015 return windowClipRect();
3017 // Apply the clip from the layer.
3019 if (clipToLayerContents)
3020 clipRect = pixelSnappedIntRect(enclosingLayer->childrenClipRect());
3022 clipRect = pixelSnappedIntRect(enclosingLayer->selfClipRect());
3023 clipRect = contentsToWindow(clipRect);
3024 return intersection(clipRect, windowClipRect());
3027 bool FrameView::isActive() const
3029 Page* page = frame().page();
3030 return page && page->focusController().isActive();
3033 bool FrameView::updatesScrollLayerPositionOnMainThread() const
3035 if (Page* page = frame().page()) {
3036 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
3037 return scrollingCoordinator->shouldUpdateScrollLayerPositionOnMainThread();
3043 void FrameView::scrollTo(const IntSize& newOffset)
3045 LayoutSize offset = scrollOffset();
3046 ScrollView::scrollTo(newOffset);
3047 if (offset != scrollOffset())
3048 scrollPositionChanged();
3049 frame().loader().client().didChangeScrollOffset();
3052 void FrameView::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
3054 // Add in our offset within the FrameView.
3055 IntRect dirtyRect = rect;
3056 dirtyRect.moveBy(scrollbar->location());
3057 invalidateRect(dirtyRect);
3060 IntRect FrameView::windowResizerRect() const
3062 if (Page* page = frame().page())
3063 return page->chrome().windowResizerRect();
3067 float FrameView::visibleContentScaleFactor() const
3069 if (!frame().isMainFrame() || !frame().settings().delegatesPageScaling())
3072 return frame().page()->pageScaleFactor();
3075 void FrameView::setVisibleScrollerThumbRect(const IntRect& scrollerThumb)
3077 if (!frame().isMainFrame())
3080 frame().page()->chrome().client().notifyScrollerThumbIsVisibleInRect(scrollerThumb);
3083 ScrollableArea* FrameView::enclosingScrollableArea() const
3085 // FIXME: Walk up the frame tree and look for a scrollable parent frame or RenderLayer.
3089 IntRect FrameView::scrollableAreaBoundingBox() const
3091 RenderWidget* ownerRenderer = frame().ownerRenderer();
3095 return ownerRenderer->absoluteContentQuad().enclosingBoundingBox();
3098 bool FrameView::isScrollable()
3101 // 1) If there an actual overflow.
3102 // 2) display:none or visibility:hidden set to self or inherited.
3103 // 3) overflow{-x,-y}: hidden;
3104 // 4) scrolling: no;
3107 IntSize totalContentsSize = this->totalContentsSize();
3108 IntSize visibleContentSize = visibleContentRect().size();
3109 if ((totalContentsSize.height() <= visibleContentSize.height() && totalContentsSize.width() <= visibleContentSize.width()))
3113 HTMLFrameOwnerElement* owner = frame().ownerElement();
3114 if (owner && (!owner->renderer() || !owner->renderer()->visibleToHitTesting()))
3118 ScrollbarMode horizontalMode;
3119 ScrollbarMode verticalMode;
3120 calculateScrollbarModesForLayout(horizontalMode, verticalMode, RulesFromWebContentOnly);
3121 if (horizontalMode == ScrollbarAlwaysOff && verticalMode == ScrollbarAlwaysOff)
3127 void FrameView::updateScrollableAreaSet()
3129 // That ensures that only inner frames are cached.
3130 FrameView* parentFrameView = this->parentFrameView();
3131 if (!parentFrameView)
3134 if (!isScrollable()) {
3135 parentFrameView->removeScrollableArea(this);
3139 parentFrameView->addScrollableArea(this);
3142 bool FrameView::shouldSuspendScrollAnimations() const
3144 return frame().loader().state() != FrameStateComplete;
3147 void FrameView::scrollbarStyleChanged(int newStyle, bool forceUpdate)
3149 if (!frame().isMainFrame())
3152 frame().page()->chrome().client().recommendedScrollbarStyleDidChange(newStyle);
3155 ScrollView::scrollbarStyleChanged(newStyle, forceUpdate);
3158 void FrameView::notifyPageThatContentAreaWillPaint() const
3160 Page* page = frame().page();
3164 contentAreaWillPaint();
3166 if (!m_scrollableAreas)
3169 for (auto& scrollableArea : *m_scrollableAreas)
3170 scrollableArea->contentAreaWillPaint();
3173 bool FrameView::scrollAnimatorEnabled() const
3175 #if ENABLE(SMOOTH_SCROLLING)
3176 if (Page* page = frame().page())
3177 return page->settings().scrollAnimatorEnabled();
3183 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
3184 void FrameView::updateAnnotatedRegions()
3186 Document* document = frame().document();
3187 if (!document->hasAnnotatedRegions())
3189 Vector<AnnotatedRegionValue> newRegions;
3190 document->renderBox()->collectAnnotatedRegions(newRegions);
3191 if (newRegions == document->annotatedRegions())
3193 document->setAnnotatedRegions(newRegions);
3194 Page* page = frame().page();
3197 page->chrome().client().annotatedRegionsChanged();
3201 void FrameView::updateScrollCorner()
3203 RenderElement* renderer = 0;
3204 RefPtr<RenderStyle> cornerStyle;
3205 IntRect cornerRect = scrollCornerRect();
3207 if (!cornerRect.isEmpty()) {
3208 // Try the <body> element first as a scroll corner source.
3209 Document* doc = frame().document();
3210 Element* body = doc ? doc->body() : 0;
3211 if (body && body->renderer()) {
3212 renderer = body->renderer();
3213 cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), &renderer->style());
3217 // If the <body> didn't have a custom style, then the root element might.
3218 Element* docElement = doc ? doc->documentElement() : 0;
3219 if (docElement && docElement->renderer()) {
3220 renderer = docElement->renderer();
3221 cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), &renderer->style());
3226 // If we have an owning iframe/frame element, then it can set the custom scrollbar also.
3227 if (RenderWidget* renderer = frame().ownerRenderer())
3228 cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), &renderer->style());
3233 if (!m_scrollCorner) {
3234 m_scrollCorner = new RenderScrollbarPart(renderer->document(), cornerStyle.releaseNonNull());
3235 m_scrollCorner->initializeStyle();
3237 m_scrollCorner->setStyle(cornerStyle.releaseNonNull());
3238 invalidateScrollCorner(cornerRect);
3239 } else if (m_scrollCorner) {
3240 m_scrollCorner->destroy();
3244 ScrollView::updateScrollCorner();
3247 void FrameView::paintScrollCorner(GraphicsContext* context, const IntRect& cornerRect)
3249 if (context->updatingControlTints()) {
3250 updateScrollCorner();
3254 if (m_scrollCorner) {
3255 if (frame().isMainFrame())
3256 context->fillRect(cornerRect, baseBackgroundColor(), ColorSpaceDeviceRGB);
3257 m_scrollCorner->paintIntoRect(context, cornerRect.location(), cornerRect);
3261 ScrollView::paintScrollCorner(context, cornerRect);
3264 void FrameView::paintScrollbar(GraphicsContext* context, Scrollbar* bar, const IntRect& rect)
3266 if (bar->isCustomScrollbar() && frame().isMainFrame()) {
3267 IntRect toFill = bar->frameRect();
3268 toFill.intersect(rect);
3269 context->fillRect(toFill, baseBackgroundColor(), ColorSpaceDeviceRGB);
3272 ScrollView::paintScrollbar(context, bar, rect);
3275 Color FrameView::documentBackgroundColor() const
3277 // <https://bugs.webkit.org/show_bug.cgi?id=59540> We blend the background color of
3278 // the document and the body against the base background color of the frame view.
3279 // Background images are unfortunately impractical to include.
3281 // Return invalid Color objects whenever there is insufficient information.
3282 if (!frame().document())
3285 Element* htmlElement = frame().document()->documentElement();
3286 Element* bodyElement = frame().document()->body();
3288 // Start with invalid colors.
3289 Color htmlBackgroundColor;
3290 Color bodyBackgroundColor;
3291 if (htmlElement && htmlElement->renderer())
3292 htmlBackgroundColor = htmlElement->renderer()->style().visitedDependentColor(CSSPropertyBackgroundColor);
3293 if (bodyElement && bodyElement->renderer())
3294 bodyBackgroundColor = bodyElement->renderer()->style().visitedDependentColor(CSSPropertyBackgroundColor);
3296 if (!bodyBackgroundColor.isValid()) {
3297 if (!htmlBackgroundColor.isValid())
3299 return baseBackgroundColor().blend(htmlBackgroundColor);
3302 if (!htmlBackgroundColor.isValid())
3303 return baseBackgroundColor().blend(bodyBackgroundColor);
3305 // We take the aggregate of the base background color
3306 // the <html> background color, and the <body>
3307 // background color to find the document color. The
3308 // addition of the base background color is not
3309 // technically part of the document background, but it
3310 // otherwise poses problems when the aggregate is not
3312 return baseBackgroundColor().blend(htmlBackgroundColor).blend(bodyBackgroundColor);
3315 bool FrameView::hasCustomScrollbars() const
3317 for (auto& widget : children()) {
3318 if (widget->isFrameView()) {
3319 if (toFrameView(*widget).hasCustomScrollbars())
3321 } else if (widget->isScrollbar()) {
3322 if (toScrollbar(*widget).isCustomScrollbar())
3330 FrameView* FrameView::parentFrameView() const
3335 if (Frame* parentFrame = frame().tree().parent())
3336 return parentFrame->view();
3341 bool FrameView::isInChildFrameWithFrameFlattening() const
3343 if (!parent() || !frame().ownerElement())
3346 // Frame flattening applies when the owner element is either in a frameset or
3347 // an iframe with flattening parameters.
3348 if (frame().ownerElement()->hasTagName(iframeTag)) {
3349 RenderIFrame* iframeRenderer = toRenderIFrame(frame().ownerElement()->renderWidget());
3350 if (iframeRenderer->flattenFrame() || iframeRenderer->isSeamless())
3354 if (!frameFlatteningEnabled())
3357 if (frame().ownerElement()->hasTagName(frameTag))
3363 void FrameView::startLayoutAtMainFrameViewIfNeeded(bool allowSubtree)
3365 // When we start a layout at the child level as opposed to the topmost frame view and this child
3366 // frame requires flattening, we need to re-initiate the layout at the topmost view. Layout
3367 // will hit this view eventually.
3368 FrameView* parentView = parentFrameView();
3372 // In the middle of parent layout, no need to restart from topmost.
3373 if (parentView->m_nestedLayoutCount)
3376 // Parent tree is clean. Starting layout from it would have no effect.
3377 if (!parentView->needsLayout())
3380 while (parentView->parentFrameView())
3381 parentView = parentView->parentFrameView();
3383 parentView->layout(allowSubtree);
3385 RenderElement* root = m_layoutRoot ? m_layoutRoot : frame().document()->renderView();
3386 ASSERT_UNUSED(root, !root->needsLayout());
3389 void FrameView::updateControlTints()
3391 // This is called when control tints are changed from aqua/graphite to clear and vice versa.
3392 // We do a "fake" paint, and when the theme gets a paint call, it can then do an invalidate.
3393 // This is only done if the theme supports control tinting. It's up to the theme and platform
3394 // to define when controls get the tint and to call this function when that changes.
3396 // Optimize the common case where we bring a window to the front while it's still empty.
3397 if (frame().document()->url().isEmpty())
3400 RenderView* renderView = this->renderView();
3401 if ((renderView && renderView->theme().supportsControlTints()) || hasCustomScrollbars())
3402 paintControlTints();
3405 void FrameView::paintControlTints()
3409 PlatformGraphicsContext* const noContext = 0;
3410 GraphicsContext context(noContext);
3411 context.setUpdatingControlTints(true);
3412 if (platformWidget())
3413 paintContents(&context, visibleContentRect());
3415 paint(&context, frameRect());
3418 bool FrameView::wasScrolledByUser() const
3420 return m_wasScrolledByUser;
3423 void FrameView::setWasScrolledByUser(bool wasScrolledByUser)
3425 if (m_inProgrammaticScroll)
3427 m_maintainScrollPositionAnchor = 0;
3428 if (m_wasScrolledByUser == wasScrolledByUser)
3430 m_wasScrolledByUser = wasScrolledByUser;
3431 adjustTiledBackingCoverage();
3434 void FrameView::paintContents(GraphicsContext* p, const IntRect& rect)
3436 Document* document = frame().document();
3440 if (document->printing())
3441 fillWithRed = false; // Printing, don't fill with red (can't remember why).
3442 else if (frame().ownerElement())
3443 fillWithRed = false; // Subframe, don't fill with red.
3444 else if (isTransparent())
3445 fillWithRed = false; // Transparent, don't fill with red.
3446 else if (m_paintBehavior & PaintBehaviorSelectionOnly)
3447 fillWithRed = false; // Selections are transparent, don't fill with red.
3448 else if (m_nodeToDraw)
3449 fillWithRed = false; // Element images are transparent, don't fill with red.
3454 p->fillRect(rect, Color(0xFF, 0, 0), ColorSpaceDeviceRGB);
3457 RenderView* renderView = this->renderView();
3459 LOG_ERROR("called FrameView::paint with nil renderer");
3463 ASSERT(!needsLayout());
3467 if (!p->paintingDisabled())
3468 InspectorInstrumentation::willPaint(renderView);
3470 bool isTopLevelPainter = !sCurrentPaintTimeStamp;
3471 if (isTopLevelPainter)
3472 sCurrentPaintTimeStamp = monotonicallyIncreasingTime();
3474 FontCachePurgePreventer fontCachePurgePreventer;
3476 #if USE(ACCELERATED_COMPOSITING)
3477 if (!p->paintingDisabled() && !document->printing())
3478 flushCompositingStateForThisFrame(&frame());
3481 PaintBehavior oldPaintBehavior = m_paintBehavior;
3483 if (FrameView* parentView = parentFrameView()) {
3484 if (parentView->paintBehavior() & PaintBehaviorFlattenCompositingLayers)
3485 m_paintBehavior |= PaintBehaviorFlattenCompositingLayers;
3488 if (m_paintBehavior == PaintBehaviorNormal)
3489 document->markers().invalidateRenderedRectsForMarkersInRect(rect);
3491 if (document->printing())
3492 m_paintBehavior |= PaintBehaviorFlattenCompositingLayers;
3494 bool flatteningPaint = m_paintBehavior & PaintBehaviorFlattenCompositingLayers;
3495 bool isRootFrame = !frame().ownerElement();
3496 if (flatteningPaint && isRootFrame)
3497 notifyWidgetsInAllFrames(WillPaintFlattened);
3499 ASSERT(!m_isPainting);
3500 m_isPainting = true;
3502 // m_nodeToDraw is used to draw only one element (and its descendants)
3503 RenderObject* eltRenderer = m_nodeToDraw ? m_nodeToDraw->renderer() : 0;
3504 RenderLayer* rootLayer = renderView->layer();
3507 RenderElement::SetLayoutNeededForbiddenScope forbidSetNeedsLayout(&rootLayer->renderer());
3510 rootLayer->paint(p, rect, m_paintBehavior, eltRenderer);
3512 if (rootLayer->containsDirtyOverlayScrollbars())
3513 rootLayer->paintOverlayScrollbars(p, rect, m_paintBehavior, eltRenderer);
3515 m_isPainting = false;
3517 if (flatteningPaint && isRootFrame)
3518 notifyWidgetsInAllFrames(DidPaintFlattened);
3520 m_paintBehavior = oldPaintBehavior;
3521 m_lastPaintTime = monotonicallyIncreasingTime();
3523 // Regions may have changed as a result of the visibility/z-index of element changing.
3524 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
3525 if (document->annotatedRegionsDirty())
3526 updateAnnotatedRegions();
3529 if (isTopLevelPainter)
3530 sCurrentPaintTimeStamp = 0;
3532 if (!p->paintingDisabled()) {
3533 InspectorInstrumentation::didPaint(renderView, p, rect);
3534 // FIXME: should probably not fire milestones for snapshot painting. https://bugs.webkit.org/show_bug.cgi?id=117623
3535 firePaintRelatedMilestones();
3539 void FrameView::setPaintBehavior(PaintBehavior behavior)
3541 m_paintBehavior = behavior;
3544 PaintBehavior FrameView::paintBehavior() const
3546 return m_paintBehavior;
3549 bool FrameView::isPainting() const
3551 return m_isPainting;
3554 // FIXME: change this to use the subtreePaint terminology.
3555 void FrameView::setNodeToDraw(Node* node)
3557 m_nodeToDraw = node;
3560 void FrameView::paintContentsForSnapshot(GraphicsContext* context, const IntRect& imageRect, SelectionInSnapshot shouldPaintSelection, CoordinateSpaceForSnapshot coordinateSpace)
3562 updateLayoutAndStyleIfNeededRecursive();
3564 // Cache paint behavior and set a new behavior appropriate for snapshots.
3565 PaintBehavior oldBehavior = paintBehavior();
3566 setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
3568 // If the snapshot should exclude selection, then we'll clear the current selection
3569 // in the render tree only. This will allow us to restore the selection from the DOM
3570 // after we paint the snapshot.
3571 if (shouldPaintSelection == ExcludeSelection) {
3572 for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) {
3573 if (RenderView* root = frame->contentRenderer())
3574 root->clearSelection();
3578 if (coordinateSpace == DocumentCoordinates)
3579 paintContents(context, imageRect);
3581 // A snapshot in ViewCoordinates will include a scrollbar, and the snapshot will contain
3582 // whatever content the document is currently scrolled to.
3583 paint(context, imageRect);
3586 // Restore selection.
3587 if (shouldPaintSelection == ExcludeSelection) {
3588 for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get()))
3589 frame->selection().updateAppearance();
3592 // Restore cached paint behavior.
3593 setPaintBehavior(oldBehavior);
3596 void FrameView::paintOverhangAreas(GraphicsContext* context, const IntRect& horizontalOverhangArea, const IntRect& verticalOverhangArea, const IntRect& dirtyRect)
3598 if (context->paintingDisabled())
3601 if (frame().document()->printing())
3604 ScrollView::paintOverhangAreas(context, horizontalOverhangArea, verticalOverhangArea, dirtyRect);
3607 void FrameView::updateLayoutAndStyleIfNeededRecursive()
3609 // We have to crawl our entire tree looking for any FrameViews that need
3610 // layout and make sure they are up to date.
3611 // Mac actually tests for intersection with the dirty region and tries not to
3612 // update layout for frames that are outside the dirty region. Not only does this seem
3613 // pointless (since those frames will have set a zero timer to layout anyway), but
3614 // it is also incorrect, since if two frames overlap, the first could be excluded from the dirty
3615 // region but then become included later by the second frame adding rects to the dirty region
3616 // when it lays out.
3618 frame().document()->updateStyleIfNeeded();
3623 // Grab a copy of the children() set, as it may be mutated by the following updateLayoutAndStyleIfNeededRecursive
3624 // calls, as they can potentially re-enter a layout of the parent frame view, which may add/remove scrollbars
3625 // and thus mutates the children()