2 * Copyright (C) 2009, 2010 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "RenderLayerCompositor.h"
30 #include "CSSAnimationController.h"
31 #include "CSSPropertyNames.h"
32 #include "CanvasRenderingContext.h"
34 #include "ChromeClient.h"
35 #include "DocumentTimeline.h"
37 #include "FrameView.h"
38 #include "FullscreenManager.h"
39 #include "GraphicsLayer.h"
40 #include "HTMLCanvasElement.h"
41 #include "HTMLIFrameElement.h"
42 #include "HTMLNames.h"
43 #include "HitTestResult.h"
44 #include "InspectorInstrumentation.h"
45 #include "LayerOverlapMap.h"
49 #include "PageOverlayController.h"
50 #include "RenderEmbeddedObject.h"
51 #include "RenderFragmentedFlow.h"
52 #include "RenderFullScreen.h"
53 #include "RenderGeometryMap.h"
54 #include "RenderIFrame.h"
55 #include "RenderLayerBacking.h"
56 #include "RenderReplica.h"
57 #include "RenderVideo.h"
58 #include "RenderView.h"
59 #include "RuntimeEnabledFeatures.h"
60 #include "ScrollingConstraints.h"
61 #include "ScrollingCoordinator.h"
63 #include "TiledBacking.h"
64 #include "TransformState.h"
65 #include <wtf/HexNumber.h>
66 #include <wtf/MemoryPressureHandler.h>
67 #include <wtf/SetForScope.h>
68 #include <wtf/text/CString.h>
69 #include <wtf/text/StringBuilder.h>
70 #include <wtf/text/StringConcatenateNumbers.h>
71 #include <wtf/text/TextStream.h>
73 #if PLATFORM(IOS_FAMILY)
74 #include "LegacyTileCache.h"
75 #include "RenderScrollbar.h"
79 #include "LocalDefaultSystemAppearance.h"
82 #if ENABLE(TREE_DEBUGGING)
83 #include "RenderTreeAsText.h"
86 #if ENABLE(3D_TRANSFORMS)
87 // This symbol is used to determine from a script whether 3D rendering is enabled (via 'nm').
88 WEBCORE_EXPORT bool WebCoreHas3DRendering = true;
91 #if !PLATFORM(MAC) && !PLATFORM(IOS_FAMILY)
92 #define USE_COMPOSITING_FOR_SMALL_CANVASES 1
97 #if !USE(COMPOSITING_FOR_SMALL_CANVASES)
98 static const int canvasAreaThresholdRequiringCompositing = 50 * 100;
100 // During page loading delay layer flushes up to this many seconds to allow them coalesce, reducing workload.
101 #if PLATFORM(IOS_FAMILY)
102 static const Seconds throttledLayerFlushInitialDelay { 500_ms };
103 static const Seconds throttledLayerFlushDelay { 1.5_s };
105 static const Seconds throttledLayerFlushInitialDelay { 500_ms };
106 static const Seconds throttledLayerFlushDelay { 500_ms };
109 using namespace HTMLNames;
111 struct ScrollingTreeState {
112 Optional<ScrollingNodeID> parentNodeID;
113 size_t nextChildIndex { 0 };
116 struct RenderLayerCompositor::OverlapExtent {
118 bool extentComputed { false };
119 bool hasTransformAnimation { false };
120 bool animationCausesExtentUncertainty { false };
122 bool knownToBeHaveExtentUncertainty() const { return extentComputed && animationCausesExtentUncertainty; }
125 struct RenderLayerCompositor::CompositingState {
126 CompositingState(RenderLayer* compAncestor, bool testOverlap = true)
127 : compositingAncestor(compAncestor)
128 , testingOverlap(testOverlap)
132 CompositingState stateForPaintOrderChildren(RenderLayer& layer) const
135 CompositingState childState(compositingAncestor);
136 if (layer.isStackingContext())
137 childState.stackingContextAncestor = &layer;
139 childState.stackingContextAncestor = stackingContextAncestor;
141 childState.backingSharingAncestor = backingSharingAncestor;
142 childState.subtreeIsCompositing = false;
143 childState.testingOverlap = testingOverlap;
144 childState.fullPaintOrderTraversalRequired = fullPaintOrderTraversalRequired;
145 childState.descendantsRequireCompositingUpdate = descendantsRequireCompositingUpdate;
146 childState.ancestorHasTransformAnimation = ancestorHasTransformAnimation;
147 #if ENABLE(CSS_COMPOSITING)
148 childState.hasNotIsolatedCompositedBlendingDescendants = false; // FIXME: should this only be reset for stacking contexts?
151 childState.depth = depth + 1;
156 void updateWithDescendantStateAndLayer(const CompositingState& childState, const RenderLayer& layer, const OverlapExtent& layerExtent, bool isUnchangedSubtree = false)
158 // Subsequent layers in the parent stacking context also need to composite.
159 subtreeIsCompositing |= childState.subtreeIsCompositing | layer.isComposited();
160 if (!isUnchangedSubtree)
161 fullPaintOrderTraversalRequired |= childState.fullPaintOrderTraversalRequired;
163 // Turn overlap testing off for later layers if it's already off, or if we have an animating transform.
164 // Note that if the layer clips its descendants, there's no reason to propagate the child animation to the parent layers. That's because
165 // we know for sure the animation is contained inside the clipping rectangle, which is already added to the overlap map.
166 auto canReenableOverlapTesting = [&layer]() {
167 return layer.isComposited() && RenderLayerCompositor::clipsCompositingDescendants(layer);
169 if ((!childState.testingOverlap && !canReenableOverlapTesting()) || layerExtent.knownToBeHaveExtentUncertainty())
170 testingOverlap = false;
172 #if ENABLE(CSS_COMPOSITING)
173 if ((layer.isComposited() && layer.hasBlendMode()) || (layer.hasNotIsolatedCompositedBlendingDescendants() && !layer.isolatesCompositedBlending()))
174 hasNotIsolatedCompositedBlendingDescendants = true;
178 bool hasNonRootCompositedAncestor() const
180 return compositingAncestor && !compositingAncestor->isRenderViewLayer();
183 RenderLayer* compositingAncestor;
184 RenderLayer* backingSharingAncestor { nullptr };
185 RenderLayer* stackingContextAncestor { nullptr };
186 bool subtreeIsCompositing { false };
187 bool testingOverlap { true };
188 bool fullPaintOrderTraversalRequired { false };
189 bool descendantsRequireCompositingUpdate { false };
190 bool ancestorHasTransformAnimation { false };
191 #if ENABLE(CSS_COMPOSITING)
192 bool hasNotIsolatedCompositedBlendingDescendants { false };
195 unsigned depth { 0 };
199 class RenderLayerCompositor::BackingSharingState {
200 WTF_MAKE_NONCOPYABLE(BackingSharingState);
202 BackingSharingState() = default;
204 RenderLayer* backingProviderCandidate() const { return m_backingProviderCandidate; };
206 void appendSharingLayer(RenderLayer& layer)
208 m_backingSharingLayers.append(makeWeakPtr(layer));
211 void updateBeforeDescendantTraversal(RenderLayer&, bool willBeComposited);
212 void updateAfterDescendantTraversal(RenderLayer&, RenderLayer* stackingContextAncestor);
215 void layerWillBeComposited(RenderLayer&);
217 void startBackingSharingSequence(RenderLayer& candidateLayer, RenderLayer* candidateStackingContext);
218 void endBackingSharingSequence();
220 RenderLayer* m_backingProviderCandidate { nullptr };
221 RenderLayer* m_backingProviderStackingContext { nullptr };
222 Vector<WeakPtr<RenderLayer>> m_backingSharingLayers;
225 void RenderLayerCompositor::BackingSharingState::startBackingSharingSequence(RenderLayer& candidateLayer, RenderLayer* candidateStackingContext)
227 ASSERT(!m_backingProviderCandidate);
228 ASSERT(m_backingSharingLayers.isEmpty());
230 m_backingProviderCandidate = &candidateLayer;
231 m_backingProviderStackingContext = candidateStackingContext;
234 void RenderLayerCompositor::BackingSharingState::endBackingSharingSequence()
236 if (m_backingProviderCandidate) {
237 m_backingProviderCandidate->backing()->setBackingSharingLayers(WTFMove(m_backingSharingLayers));
238 m_backingSharingLayers.clear();
241 m_backingProviderCandidate = nullptr;
244 void RenderLayerCompositor::BackingSharingState::updateBeforeDescendantTraversal(RenderLayer& layer, bool willBeComposited)
246 layer.setBackingProviderLayer(nullptr);
248 // A layer that composites resets backing-sharing, since subsequent layers need to composite to overlap it.
249 if (willBeComposited) {
250 m_backingSharingLayers.removeAll(&layer);
251 endBackingSharingSequence();
255 void RenderLayerCompositor::BackingSharingState::updateAfterDescendantTraversal(RenderLayer& layer, RenderLayer* stackingContextAncestor)
257 if (layer.isComposited()) {
258 // If this layer is being composited, clean up sharing-related state.
259 layer.disconnectFromBackingProviderLayer();
260 m_backingSharingLayers.removeAll(&layer);
263 if (m_backingProviderCandidate && &layer == m_backingProviderStackingContext) {
264 LOG_WITH_STREAM(Compositing, stream << "End of stacking context for backing provider " << m_backingProviderCandidate << ", ending sharing sequence with " << m_backingSharingLayers.size() << " sharing layers");
265 endBackingSharingSequence();
266 } else if (!m_backingProviderCandidate && layer.isComposited()) {
267 LOG_WITH_STREAM(Compositing, stream << "Post-descendant compositing of " << &layer << ", ending sharing sequence for " << m_backingProviderCandidate << " with " << m_backingSharingLayers.size() << " sharing layers");
268 endBackingSharingSequence();
269 startBackingSharingSequence(layer, stackingContextAncestor);
272 if (&layer != m_backingProviderCandidate && layer.isComposited())
273 layer.backing()->clearBackingSharingLayers();
277 static inline bool compositingLogEnabled()
279 return LogCompositing.state == WTFLogChannelState::On;
282 static inline bool layersLogEnabled()
284 return LogLayers.state == WTFLogChannelState::On;
288 RenderLayerCompositor::RenderLayerCompositor(RenderView& renderView)
289 : m_renderView(renderView)
290 , m_updateCompositingLayersTimer(*this, &RenderLayerCompositor::updateCompositingLayersTimerFired)
291 , m_layerFlushTimer(*this, &RenderLayerCompositor::layerFlushTimerFired)
293 #if PLATFORM(IOS_FAMILY)
294 if (m_renderView.frameView().platformWidget())
295 m_legacyScrollingLayerCoordinator = std::make_unique<LegacyWebKitScrollingLayerCoordinator>(page().chrome().client(), isMainFrameCompositor());
299 RenderLayerCompositor::~RenderLayerCompositor()
301 // Take care that the owned GraphicsLayers are deleted first as their destructors may call back here.
302 GraphicsLayer::unparentAndClear(m_rootContentsLayer);
304 GraphicsLayer::unparentAndClear(m_clipLayer);
305 GraphicsLayer::unparentAndClear(m_scrollContainerLayer);
306 GraphicsLayer::unparentAndClear(m_scrolledContentsLayer);
308 GraphicsLayer::unparentAndClear(m_overflowControlsHostLayer);
310 GraphicsLayer::unparentAndClear(m_layerForHorizontalScrollbar);
311 GraphicsLayer::unparentAndClear(m_layerForVerticalScrollbar);
312 GraphicsLayer::unparentAndClear(m_layerForScrollCorner);
314 #if ENABLE(RUBBER_BANDING)
315 GraphicsLayer::unparentAndClear(m_layerForOverhangAreas);
316 GraphicsLayer::unparentAndClear(m_contentShadowLayer);
317 GraphicsLayer::unparentAndClear(m_layerForTopOverhangArea);
318 GraphicsLayer::unparentAndClear(m_layerForBottomOverhangArea);
319 GraphicsLayer::unparentAndClear(m_layerForHeader);
320 GraphicsLayer::unparentAndClear(m_layerForFooter);
323 ASSERT(m_rootLayerAttachment == RootLayerUnattached);
326 void RenderLayerCompositor::enableCompositingMode(bool enable /* = true */)
328 if (enable != m_compositing) {
329 m_compositing = enable;
333 notifyIFramesOfCompositingChange();
338 m_renderView.layer()->setNeedsPostLayoutCompositingUpdate();
342 void RenderLayerCompositor::cacheAcceleratedCompositingFlags()
344 auto& settings = m_renderView.settings();
345 bool hasAcceleratedCompositing = settings.acceleratedCompositingEnabled();
347 // We allow the chrome to override the settings, in case the page is rendered
348 // on a chrome that doesn't allow accelerated compositing.
349 if (hasAcceleratedCompositing) {
350 m_compositingTriggers = page().chrome().client().allowedCompositingTriggers();
351 hasAcceleratedCompositing = m_compositingTriggers;
354 bool showDebugBorders = settings.showDebugBorders();
355 bool showRepaintCounter = settings.showRepaintCounter();
356 bool acceleratedDrawingEnabled = settings.acceleratedDrawingEnabled();
357 bool displayListDrawingEnabled = settings.displayListDrawingEnabled();
359 // forceCompositingMode for subframes can only be computed after layout.
360 bool forceCompositingMode = m_forceCompositingMode;
361 if (isMainFrameCompositor())
362 forceCompositingMode = m_renderView.settings().forceCompositingMode() && hasAcceleratedCompositing;
364 if (hasAcceleratedCompositing != m_hasAcceleratedCompositing || showDebugBorders != m_showDebugBorders || showRepaintCounter != m_showRepaintCounter || forceCompositingMode != m_forceCompositingMode) {
365 if (auto* rootLayer = m_renderView.layer()) {
366 rootLayer->setNeedsCompositingConfigurationUpdate();
367 rootLayer->setDescendantsNeedUpdateBackingAndHierarchyTraversal();
371 bool debugBordersChanged = m_showDebugBorders != showDebugBorders;
372 m_hasAcceleratedCompositing = hasAcceleratedCompositing;
373 m_forceCompositingMode = forceCompositingMode;
374 m_showDebugBorders = showDebugBorders;
375 m_showRepaintCounter = showRepaintCounter;
376 m_acceleratedDrawingEnabled = acceleratedDrawingEnabled;
377 m_displayListDrawingEnabled = displayListDrawingEnabled;
379 if (debugBordersChanged) {
380 if (m_layerForHorizontalScrollbar)
381 m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
383 if (m_layerForVerticalScrollbar)
384 m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
386 if (m_layerForScrollCorner)
387 m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
390 if (updateCompositingPolicy())
391 rootRenderLayer().setDescendantsNeedCompositingRequirementsTraversal();
394 void RenderLayerCompositor::cacheAcceleratedCompositingFlagsAfterLayout()
396 cacheAcceleratedCompositingFlags();
398 if (isMainFrameCompositor())
401 RequiresCompositingData queryData;
402 bool forceCompositingMode = m_hasAcceleratedCompositing && m_renderView.settings().forceCompositingMode() && requiresCompositingForScrollableFrame(queryData);
403 if (forceCompositingMode != m_forceCompositingMode) {
404 m_forceCompositingMode = forceCompositingMode;
405 rootRenderLayer().setDescendantsNeedCompositingRequirementsTraversal();
409 bool RenderLayerCompositor::updateCompositingPolicy()
411 if (!usesCompositing())
414 auto currentPolicy = m_compositingPolicy;
415 if (page().compositingPolicyOverride()) {
416 m_compositingPolicy = page().compositingPolicyOverride().value();
417 return m_compositingPolicy != currentPolicy;
420 auto memoryPolicy = MemoryPressureHandler::currentMemoryUsagePolicy();
421 m_compositingPolicy = memoryPolicy == WTF::MemoryUsagePolicy::Unrestricted ? CompositingPolicy::Normal : CompositingPolicy::Conservative;
422 return m_compositingPolicy != currentPolicy;
425 bool RenderLayerCompositor::canRender3DTransforms() const
427 return hasAcceleratedCompositing() && (m_compositingTriggers & ChromeClient::ThreeDTransformTrigger);
430 void RenderLayerCompositor::willRecalcStyle()
432 cacheAcceleratedCompositingFlags();
435 bool RenderLayerCompositor::didRecalcStyleWithNoPendingLayout()
437 return updateCompositingLayers(CompositingUpdateType::AfterStyleChange);
440 void RenderLayerCompositor::customPositionForVisibleRectComputation(const GraphicsLayer* graphicsLayer, FloatPoint& position) const
442 if (graphicsLayer != m_scrolledContentsLayer.get())
445 FloatPoint scrollPosition = -position;
447 if (m_renderView.frameView().scrollBehaviorForFixedElements() == StickToDocumentBounds)
448 scrollPosition = m_renderView.frameView().constrainScrollPositionForOverhang(roundedIntPoint(scrollPosition));
450 position = -scrollPosition;
453 void RenderLayerCompositor::notifyFlushRequired(const GraphicsLayer* layer)
455 scheduleLayerFlush(layer->canThrottleLayerFlush());
458 void RenderLayerCompositor::scheduleLayerFlush(bool canThrottle)
460 ASSERT(!m_flushingLayers);
463 startInitialLayerFlushTimerIfNeeded();
465 if (canThrottle && isThrottlingLayerFlushes())
466 m_hasPendingLayerFlush = true;
468 m_hasPendingLayerFlush = false;
469 page().renderingUpdateScheduler().scheduleRenderingUpdate();
473 FloatRect RenderLayerCompositor::visibleRectForLayerFlushing() const
475 const FrameView& frameView = m_renderView.frameView();
476 #if PLATFORM(IOS_FAMILY)
477 return frameView.exposedContentRect();
479 // Having a m_scrolledContentsLayer indicates that we're doing scrolling via GraphicsLayers.
480 FloatRect visibleRect = m_scrolledContentsLayer ? FloatRect({ }, frameView.sizeForVisibleContent()) : frameView.visibleContentRect();
482 if (frameView.viewExposedRect())
483 visibleRect.intersect(frameView.viewExposedRect().value());
489 void RenderLayerCompositor::flushPendingLayerChanges(bool isFlushRoot)
491 // FrameView::flushCompositingStateIncludingSubframes() flushes each subframe,
492 // but GraphicsLayer::flushCompositingState() will cross frame boundaries
493 // if the GraphicsLayers are connected (the RootLayerAttachedViaEnclosingFrame case).
494 // As long as we're not the root of the flush, we can bail.
495 if (!isFlushRoot && rootLayerAttachment() == RootLayerAttachedViaEnclosingFrame)
498 if (rootLayerAttachment() == RootLayerUnattached) {
499 #if PLATFORM(IOS_FAMILY)
500 startLayerFlushTimerIfNeeded();
502 m_shouldFlushOnReattach = true;
506 auto& frameView = m_renderView.frameView();
507 AnimationUpdateBlock animationUpdateBlock(&frameView.frame().animation());
509 ASSERT(!m_flushingLayers);
511 SetForScope<bool> flushingLayersScope(m_flushingLayers, true);
513 if (auto* rootLayer = rootGraphicsLayer()) {
514 FloatRect visibleRect = visibleRectForLayerFlushing();
515 LOG_WITH_STREAM(Compositing, stream << "\nRenderLayerCompositor " << this << " flushPendingLayerChanges (is root " << isFlushRoot << ") visible rect " << visibleRect);
516 rootLayer->flushCompositingState(visibleRect);
519 ASSERT(m_flushingLayers);
521 #if ENABLE(TREE_DEBUGGING)
522 if (layersLogEnabled()) {
523 LOG(Layers, "RenderLayerCompositor::flushPendingLayerChanges");
524 showGraphicsLayerTree(m_rootContentsLayer.get());
529 #if PLATFORM(IOS_FAMILY)
530 updateScrollCoordinatedLayersAfterFlushIncludingSubframes();
533 page().chrome().client().didFlushCompositingLayers();
537 startLayerFlushTimerIfNeeded();
540 #if PLATFORM(IOS_FAMILY)
541 void RenderLayerCompositor::updateScrollCoordinatedLayersAfterFlushIncludingSubframes()
543 updateScrollCoordinatedLayersAfterFlush();
545 auto& frame = m_renderView.frameView().frame();
546 for (Frame* subframe = frame.tree().firstChild(); subframe; subframe = subframe->tree().traverseNext(&frame)) {
547 auto* view = subframe->contentRenderer();
551 view->compositor().updateScrollCoordinatedLayersAfterFlush();
555 void RenderLayerCompositor::updateScrollCoordinatedLayersAfterFlush()
557 if (m_legacyScrollingLayerCoordinator) {
558 m_legacyScrollingLayerCoordinator->registerAllViewportConstrainedLayers(*this);
559 m_legacyScrollingLayerCoordinator->registerScrollingLayersNeedingUpdate();
564 void RenderLayerCompositor::didChangePlatformLayerForLayer(RenderLayer& layer, const GraphicsLayer*)
566 #if PLATFORM(IOS_FAMILY)
567 if (m_legacyScrollingLayerCoordinator)
568 m_legacyScrollingLayerCoordinator->didChangePlatformLayerForLayer(layer);
571 auto* scrollingCoordinator = this->scrollingCoordinator();
572 if (!scrollingCoordinator)
575 auto* backing = layer.backing();
576 if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::Scrolling))
577 updateScrollingNodeLayers(nodeID, layer, *scrollingCoordinator);
579 if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::ViewportConstrained))
580 scrollingCoordinator->setNodeLayers(nodeID, { backing->graphicsLayer() });
582 if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::FrameHosting))
583 scrollingCoordinator->setNodeLayers(nodeID, { backing->graphicsLayer() });
585 if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::Positioning))
586 scrollingCoordinator->setNodeLayers(nodeID, { backing->graphicsLayer() });
589 void RenderLayerCompositor::didPaintBacking(RenderLayerBacking*)
591 auto& frameView = m_renderView.frameView();
592 frameView.setLastPaintTime(MonotonicTime::now());
593 if (frameView.milestonesPendingPaint())
594 frameView.firePaintRelatedMilestonesIfNeeded();
597 void RenderLayerCompositor::didChangeVisibleRect()
599 auto* rootLayer = rootGraphicsLayer();
603 FloatRect visibleRect = visibleRectForLayerFlushing();
604 bool requiresFlush = rootLayer->visibleRectChangeRequiresFlush(visibleRect);
605 LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor::didChangeVisibleRect " << visibleRect << " requiresFlush " << requiresFlush);
607 scheduleLayerFlush();
610 void RenderLayerCompositor::notifyFlushBeforeDisplayRefresh(const GraphicsLayer*)
612 if (!m_layerUpdater) {
613 PlatformDisplayID displayID = page().chrome().displayID();
614 m_layerUpdater = std::make_unique<GraphicsLayerUpdater>(*this, displayID);
617 m_layerUpdater->scheduleUpdate();
620 void RenderLayerCompositor::flushLayersSoon(GraphicsLayerUpdater&)
622 scheduleLayerFlush(true);
625 void RenderLayerCompositor::layerTiledBackingUsageChanged(const GraphicsLayer* graphicsLayer, bool usingTiledBacking)
627 if (usingTiledBacking) {
628 ++m_layersWithTiledBackingCount;
629 graphicsLayer->tiledBacking()->setIsInWindow(page().isInWindow());
631 ASSERT(m_layersWithTiledBackingCount > 0);
632 --m_layersWithTiledBackingCount;
636 void RenderLayerCompositor::scheduleCompositingLayerUpdate()
638 if (!m_updateCompositingLayersTimer.isActive())
639 m_updateCompositingLayersTimer.startOneShot(0_s);
642 void RenderLayerCompositor::updateCompositingLayersTimerFired()
644 updateCompositingLayers(CompositingUpdateType::AfterLayout);
647 void RenderLayerCompositor::cancelCompositingLayerUpdate()
649 m_updateCompositingLayersTimer.stop();
652 static Optional<ScrollingNodeID> frameHostingNodeForFrame(Frame& frame)
654 if (!frame.document() || !frame.view())
657 // Find the frame's enclosing layer in our render tree.
658 auto* ownerElement = frame.document()->ownerElement();
662 auto* frameRenderer = ownerElement->renderer();
663 if (!frameRenderer || !is<RenderWidget>(frameRenderer))
666 auto& widgetRenderer = downcast<RenderWidget>(*frameRenderer);
667 if (!widgetRenderer.hasLayer() || !widgetRenderer.layer()->isComposited()) {
668 LOG(Scrolling, "frameHostingNodeForFrame: frame renderer has no layer or is not composited.");
672 if (auto frameHostingNodeID = widgetRenderer.layer()->backing()->scrollingNodeIDForRole(ScrollCoordinationRole::FrameHosting))
673 return frameHostingNodeID;
678 // Returns true on a successful update.
679 bool RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType updateType, RenderLayer* updateRoot)
681 LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor " << this << " updateCompositingLayers " << updateType << " contentLayersCount " << m_contentLayersCount);
683 #if ENABLE(TREE_DEBUGGING)
684 if (compositingLogEnabled())
685 showPaintOrderTree(m_renderView.layer());
688 if (updateType == CompositingUpdateType::AfterStyleChange || updateType == CompositingUpdateType::AfterLayout)
689 cacheAcceleratedCompositingFlagsAfterLayout(); // Some flags (e.g. forceCompositingMode) depend on layout.
691 m_updateCompositingLayersTimer.stop();
693 ASSERT(m_renderView.document().pageCacheState() == Document::NotInPageCache);
695 // Compositing layers will be updated in Document::setVisualUpdatesAllowed(bool) if suppressed here.
696 if (!m_renderView.document().visualUpdatesAllowed())
699 // Avoid updating the layers with old values. Compositing layers will be updated after the layout is finished.
700 // This happens when m_updateCompositingLayersTimer fires before layout is updated.
701 if (m_renderView.needsLayout()) {
702 LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor " << this << " updateCompositingLayers " << updateType << " - m_renderView.needsLayout, bailing ");
706 if (!m_compositing && (m_forceCompositingMode || (isMainFrameCompositor() && page().pageOverlayController().overlayCount())))
707 enableCompositingMode(true);
709 bool isPageScroll = !updateRoot || updateRoot == &rootRenderLayer();
710 updateRoot = &rootRenderLayer();
712 if (updateType == CompositingUpdateType::OnScroll || updateType == CompositingUpdateType::OnCompositedScroll) {
713 // We only get here if we didn't scroll on the scrolling thread, so this update needs to re-position viewport-constrained layers.
714 if (m_renderView.settings().acceleratedCompositingForFixedPositionEnabled() && isPageScroll) {
715 if (auto* viewportConstrainedObjects = m_renderView.frameView().viewportConstrainedObjects()) {
716 for (auto* renderer : *viewportConstrainedObjects) {
717 if (auto* layer = renderer->layer())
718 layer->setNeedsCompositingGeometryUpdate();
723 // Scrolling can affect overlap. FIXME: avoid for page scrolling.
724 updateRoot->setDescendantsNeedCompositingRequirementsTraversal();
727 if (updateType == CompositingUpdateType::AfterLayout) {
728 // Ensure that post-layout updates push new scroll position and viewport rects onto the root node.
729 rootRenderLayer().setNeedsScrollingTreeUpdate();
732 if (!updateRoot->hasDescendantNeedingCompositingRequirementsTraversal() && !m_compositing) {
733 LOG_WITH_STREAM(Compositing, stream << " no compositing work to do");
737 if (!updateRoot->needsAnyCompositingTraversal()) {
738 LOG_WITH_STREAM(Compositing, stream << " updateRoot has no dirty child and doesn't need update");
742 ++m_compositingUpdateCount;
744 AnimationUpdateBlock animationUpdateBlock(&m_renderView.frameView().frame().animation());
746 SetForScope<bool> postLayoutChange(m_inPostLayoutUpdate, true);
749 MonotonicTime startTime;
750 if (compositingLogEnabled()) {
751 ++m_rootLayerUpdateCount;
752 startTime = MonotonicTime::now();
755 if (compositingLogEnabled()) {
756 m_obligateCompositedLayerCount = 0;
757 m_secondaryCompositedLayerCount = 0;
758 m_obligatoryBackingStoreBytes = 0;
759 m_secondaryBackingStoreBytes = 0;
761 auto& frame = m_renderView.frameView().frame();
762 bool isMainFrame = isMainFrameCompositor();
763 LOG_WITH_STREAM(Compositing, stream << "\nUpdate " << m_rootLayerUpdateCount << " of " << (isMainFrame ? "main frame" : frame.tree().uniqueName().string().utf8().data()) << " - compositing policy is " << m_compositingPolicy);
767 // FIXME: optimize root-only update.
768 if (updateRoot->hasDescendantNeedingCompositingRequirementsTraversal() || updateRoot->needsCompositingRequirementsTraversal()) {
769 auto& rootLayer = rootRenderLayer();
770 CompositingState compositingState(updateRoot);
771 BackingSharingState backingSharingState;
772 LayerOverlapMap overlapMap(rootLayer);
774 bool descendantHas3DTransform = false;
775 computeCompositingRequirements(nullptr, rootLayer, overlapMap, compositingState, backingSharingState, descendantHas3DTransform);
778 LOG(Compositing, "\nRenderLayerCompositor::updateCompositingLayers - mid");
779 #if ENABLE(TREE_DEBUGGING)
780 if (compositingLogEnabled())
781 showPaintOrderTree(m_renderView.layer());
784 if (updateRoot->hasDescendantNeedingUpdateBackingOrHierarchyTraversal() || updateRoot->needsUpdateBackingOrHierarchyTraversal()) {
785 ScrollingTreeState scrollingTreeState = { 0, 0 };
786 if (!m_renderView.frame().isMainFrame())
787 scrollingTreeState.parentNodeID = frameHostingNodeForFrame(m_renderView.frame());
789 Vector<Ref<GraphicsLayer>> childList;
790 updateBackingAndHierarchy(*updateRoot, childList, scrollingTreeState);
792 // Host the document layer in the RenderView's root layer.
793 appendDocumentOverlayLayers(childList);
794 // Even when childList is empty, don't drop out of compositing mode if there are
795 // composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
796 if (childList.isEmpty() && !needsCompositingForContentOrOverlays())
798 else if (m_rootContentsLayer)
799 m_rootContentsLayer->setChildren(WTFMove(childList));
803 if (compositingLogEnabled()) {
804 MonotonicTime endTime = MonotonicTime::now();
805 LOG(Compositing, "Total layers primary secondary obligatory backing (KB) secondary backing(KB) total backing (KB) update time (ms)\n");
807 LOG(Compositing, "%8d %11d %9d %20.2f %22.2f %22.2f %18.2f\n",
808 m_obligateCompositedLayerCount + m_secondaryCompositedLayerCount, m_obligateCompositedLayerCount,
809 m_secondaryCompositedLayerCount, m_obligatoryBackingStoreBytes / 1024, m_secondaryBackingStoreBytes / 1024, (m_obligatoryBackingStoreBytes + m_secondaryBackingStoreBytes) / 1024, (endTime - startTime).milliseconds());
813 // FIXME: Only do if dirty.
814 updateRootLayerPosition();
816 #if ENABLE(TREE_DEBUGGING)
817 if (compositingLogEnabled()) {
818 LOG(Compositing, "RenderLayerCompositor::updateCompositingLayers - post");
819 showPaintOrderTree(m_renderView.layer());
823 InspectorInstrumentation::layerTreeDidChange(&page());
828 static bool backingProviderLayerCanIncludeLayer(const RenderLayer& sharedLayer, const RenderLayer& layer)
830 // Disable sharing when painting shared layers doesn't work correctly.
831 if (layer.hasReflection())
834 return layer.ancestorLayerIsInContainingBlockChain(sharedLayer);
837 void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer& layer, LayerOverlapMap& overlapMap, CompositingState& compositingState, BackingSharingState& backingSharingState, bool& descendantHas3DTransform)
839 if (!layer.hasDescendantNeedingCompositingRequirementsTraversal()
840 && !layer.needsCompositingRequirementsTraversal()
841 && !compositingState.fullPaintOrderTraversalRequired
842 && !compositingState.descendantsRequireCompositingUpdate) {
843 traverseUnchangedSubtree(ancestorLayer, layer, overlapMap, compositingState, backingSharingState, descendantHas3DTransform);
847 LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(compositingState.depth * 2, ' ') << &layer << (layer.isNormalFlowOnly() ? " n" : " s") << " computeCompositingRequirements (backing provider candidate " << backingSharingState.backingProviderCandidate() << ")");
849 // FIXME: maybe we can avoid updating all remaining layers in paint order.
850 compositingState.fullPaintOrderTraversalRequired |= layer.needsCompositingRequirementsTraversal();
851 compositingState.descendantsRequireCompositingUpdate |= layer.descendantsNeedCompositingRequirementsTraversal();
853 layer.updateDescendantDependentFlags();
854 layer.updateLayerListsIfNeeded();
856 layer.setHasCompositingDescendant(false);
858 // We updated compositing for direct reasons in layerStyleChanged(). Here, check for compositing that can only be evaluated after layout.
859 RequiresCompositingData queryData;
860 bool willBeComposited = layer.isComposited();
861 bool becameCompositedAfterDescendantTraversal = false;
863 if (layer.needsPostLayoutCompositingUpdate() || compositingState.fullPaintOrderTraversalRequired || compositingState.descendantsRequireCompositingUpdate) {
864 layer.setIndirectCompositingReason(IndirectCompositingReason::None);
865 willBeComposited = needsToBeComposited(layer, queryData);
868 compositingState.fullPaintOrderTraversalRequired |= layer.subsequentLayersNeedCompositingRequirementsTraversal();
870 OverlapExtent layerExtent;
871 // Use the fact that we're composited as a hint to check for an animating transform.
872 // FIXME: Maybe needsToBeComposited() should return a bitmask of reasons, to avoid the need to recompute things.
873 if (willBeComposited && !layer.isRenderViewLayer())
874 layerExtent.hasTransformAnimation = isRunningTransformAnimation(layer.renderer());
876 bool respectTransforms = !layerExtent.hasTransformAnimation;
877 overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer, respectTransforms);
879 IndirectCompositingReason compositingReason = compositingState.subtreeIsCompositing ? IndirectCompositingReason::Stacking : IndirectCompositingReason::None;
880 bool layerPaintsIntoProvidedBacking = false;
881 bool didPushOverlapContainer = false;
883 // If we know for sure the layer is going to be composited, don't bother looking it up in the overlap map
884 if (!willBeComposited && !overlapMap.isEmpty() && compositingState.testingOverlap) {
885 // If we're testing for overlap, we only need to composite if we overlap something that is already composited.
886 if (layerOverlaps(overlapMap, layer, layerExtent)) {
887 if (backingSharingState.backingProviderCandidate() && canBeComposited(layer) && backingProviderLayerCanIncludeLayer(*backingSharingState.backingProviderCandidate(), layer)) {
888 backingSharingState.appendSharingLayer(layer);
889 LOG(Compositing, " layer %p can share with %p", &layer, backingSharingState.backingProviderCandidate());
890 compositingReason = IndirectCompositingReason::None;
891 layerPaintsIntoProvidedBacking = true;
893 compositingReason = IndirectCompositingReason::Overlap;
895 compositingReason = IndirectCompositingReason::None;
899 // Video is special. It's the only RenderLayer type that can both have
900 // RenderLayer children and whose children can't use its backing to render
901 // into. These children (the controls) always need to be promoted into their
902 // own layers to draw on top of the accelerated video.
903 if (compositingState.compositingAncestor && compositingState.compositingAncestor->renderer().isVideo())
904 compositingReason = IndirectCompositingReason::Overlap;
907 if (compositingReason != IndirectCompositingReason::None)
908 layer.setIndirectCompositingReason(compositingReason);
910 // Check if the computed indirect reason will force the layer to become composited.
911 if (!willBeComposited && layer.mustCompositeForIndirectReasons() && canBeComposited(layer)) {
912 LOG_WITH_STREAM(Compositing, stream << "layer " << &layer << " compositing for indirect reason " << layer.indirectCompositingReason() << " (was sharing: " << layerPaintsIntoProvidedBacking << ")");
913 willBeComposited = true;
914 layerPaintsIntoProvidedBacking = false;
917 // The children of this layer don't need to composite, unless there is
918 // a compositing layer among them, so start by inheriting the compositing
919 // ancestor with subtreeIsCompositing set to false.
920 CompositingState currentState = compositingState.stateForPaintOrderChildren(layer);
922 auto layerWillComposite = [&] {
923 // This layer is going to be composited, so children can safely ignore the fact that there's an
924 // animation running behind this layer, meaning they can rely on the overlap map testing again.
925 currentState.testingOverlap = true;
926 // This layer now acts as the ancestor for kids.
927 currentState.compositingAncestor = &layer;
928 // Compositing turns off backing sharing.
929 currentState.backingSharingAncestor = nullptr;
931 if (layerPaintsIntoProvidedBacking) {
932 layerPaintsIntoProvidedBacking = false;
933 // layerPaintsIntoProvidedBacking was only true for layers that would otherwise composite because of overlap. If we can
934 // no longer share, put this this indirect reason back on the layer so that requiresOwnBackingStore() sees it.
935 layer.setIndirectCompositingReason(IndirectCompositingReason::Overlap);
936 LOG_WITH_STREAM(Compositing, stream << "layer " << &layer << " was sharing now will composite");
938 overlapMap.pushCompositingContainer();
939 didPushOverlapContainer = true;
940 LOG_WITH_STREAM(CompositingOverlap, stream << "layer " << &layer << " will composite, pushed container " << overlapMap);
943 willBeComposited = true;
946 auto layerWillCompositePostDescendants = [&] {
947 layerWillComposite();
948 currentState.subtreeIsCompositing = true;
949 becameCompositedAfterDescendantTraversal = true;
952 if (willBeComposited) {
953 layerWillComposite();
955 computeExtent(overlapMap, layer, layerExtent);
956 currentState.ancestorHasTransformAnimation |= layerExtent.hasTransformAnimation;
957 // Too hard to compute animated bounds if both us and some ancestor is animating transform.
958 layerExtent.animationCausesExtentUncertainty |= layerExtent.hasTransformAnimation && compositingState.ancestorHasTransformAnimation;
959 } else if (layerPaintsIntoProvidedBacking) {
960 currentState.backingSharingAncestor = &layer;
961 overlapMap.pushCompositingContainer();
962 didPushOverlapContainer = true;
963 LOG_WITH_STREAM(CompositingOverlap, stream << "layer " << &layer << " will share, pushed container " << overlapMap);
966 backingSharingState.updateBeforeDescendantTraversal(layer, willBeComposited);
969 LayerListMutationDetector mutationChecker(layer);
972 bool anyDescendantHas3DTransform = false;
973 bool descendantsAddedToOverlap = currentState.hasNonRootCompositedAncestor();
975 for (auto* childLayer : layer.negativeZOrderLayers()) {
976 computeCompositingRequirements(&layer, *childLayer, overlapMap, currentState, backingSharingState, anyDescendantHas3DTransform);
978 // If we have to make a layer for this child, make one now so we can have a contents layer
979 // (since we need to ensure that the -ve z-order child renders underneath our contents).
980 if (!willBeComposited && currentState.subtreeIsCompositing) {
981 // make layer compositing
982 layer.setIndirectCompositingReason(IndirectCompositingReason::BackgroundLayer);
983 layerWillComposite();
987 for (auto* childLayer : layer.normalFlowLayers())
988 computeCompositingRequirements(&layer, *childLayer, overlapMap, currentState, backingSharingState, anyDescendantHas3DTransform);
990 for (auto* childLayer : layer.positiveZOrderLayers())
991 computeCompositingRequirements(&layer, *childLayer, overlapMap, currentState, backingSharingState, anyDescendantHas3DTransform);
993 // If we just entered compositing mode, the root will have become composited (as long as accelerated compositing is enabled).
994 if (layer.isRenderViewLayer()) {
995 if (usesCompositing() && m_hasAcceleratedCompositing)
996 willBeComposited = true;
999 #if ENABLE(CSS_COMPOSITING)
1000 bool isolatedCompositedBlending = layer.isolatesCompositedBlending();
1001 layer.setHasNotIsolatedCompositedBlendingDescendants(currentState.hasNotIsolatedCompositedBlendingDescendants);
1002 if (layer.isolatesCompositedBlending() != isolatedCompositedBlending) {
1003 // isolatedCompositedBlending affects the result of clippedByAncestor().
1004 layer.setChildrenNeedCompositingGeometryUpdate();
1007 ASSERT(!layer.hasNotIsolatedCompositedBlendingDescendants() || layer.hasNotIsolatedBlendingDescendants());
1009 // Now check for reasons to become composited that depend on the state of descendant layers.
1010 IndirectCompositingReason indirectCompositingReason;
1011 if (!willBeComposited && canBeComposited(layer)
1012 && requiresCompositingForIndirectReason(layer, compositingState.compositingAncestor, currentState.subtreeIsCompositing, anyDescendantHas3DTransform, layerPaintsIntoProvidedBacking, indirectCompositingReason)) {
1013 layer.setIndirectCompositingReason(indirectCompositingReason);
1014 layerWillCompositePostDescendants();
1017 if (layer.reflectionLayer()) {
1018 // FIXME: Shouldn't we call computeCompositingRequirements to handle a reflection overlapping with another renderer?
1019 layer.reflectionLayer()->setIndirectCompositingReason(willBeComposited ? IndirectCompositingReason::Stacking : IndirectCompositingReason::None);
1022 // Set the flag to say that this layer has compositing children.
1023 layer.setHasCompositingDescendant(currentState.subtreeIsCompositing);
1025 // setHasCompositingDescendant() may have changed the answer to needsToBeComposited() when clipping, so test that now.
1026 bool isCompositedClippingLayer = canBeComposited(layer) && clipsCompositingDescendants(layer);
1027 if (isCompositedClippingLayer & !willBeComposited)
1028 layerWillCompositePostDescendants();
1030 // If we're back at the root, and no other layers need to be composited, and the root layer itself doesn't need
1031 // to be composited, then we can drop out of compositing mode altogether. However, don't drop out of compositing mode
1032 // if there are composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
1033 RequiresCompositingData rootLayerQueryData;
1034 if (layer.isRenderViewLayer() && !currentState.subtreeIsCompositing && !requiresCompositingLayer(layer, rootLayerQueryData) && !m_forceCompositingMode && !needsCompositingForContentOrOverlays()) {
1035 // Don't drop out of compositing on iOS, because we may flash. See <rdar://problem/8348337>.
1036 #if !PLATFORM(IOS_FAMILY)
1037 enableCompositingMode(false);
1038 willBeComposited = false;
1042 ASSERT(willBeComposited == needsToBeComposited(layer, queryData));
1044 // Create or destroy backing here. However, we can't update geometry because layers above us may become composited
1045 // during post-order traversal (e.g. for clipping).
1046 if (updateBacking(layer, queryData, CompositingChangeRepaintNow, willBeComposited ? BackingRequired::Yes : BackingRequired::No)) {
1047 layer.setNeedsCompositingLayerConnection();
1048 // Child layers need to get a geometry update to recompute their position.
1049 layer.setChildrenNeedCompositingGeometryUpdate();
1050 // The composited bounds of enclosing layers depends on which descendants are composited, so they need a geometry update.
1051 layer.setNeedsCompositingGeometryUpdateOnAncestors();
1054 // Update layer state bits.
1055 if (layer.reflectionLayer() && updateLayerCompositingState(*layer.reflectionLayer(), queryData, CompositingChangeRepaintNow))
1056 layer.setNeedsCompositingLayerConnection();
1058 // FIXME: clarify needsCompositingPaintOrderChildrenUpdate. If a composited layer gets a new ancestor, it needs geometry computations.
1059 if (layer.needsCompositingPaintOrderChildrenUpdate()) {
1060 layer.setChildrenNeedCompositingGeometryUpdate();
1061 layer.setNeedsCompositingLayerConnection();
1064 layer.clearCompositingRequirementsTraversalState();
1066 // Compute state passed to the caller.
1067 descendantHas3DTransform |= anyDescendantHas3DTransform || layer.has3DTransform();
1068 compositingState.updateWithDescendantStateAndLayer(currentState, layer, layerExtent);
1069 backingSharingState.updateAfterDescendantTraversal(layer, compositingState.stackingContextAncestor);
1071 bool layerContributesToOverlap = (currentState.compositingAncestor && !currentState.compositingAncestor->isRenderViewLayer()) || currentState.backingSharingAncestor;
1072 updateOverlapMap(overlapMap, layer, layerExtent, didPushOverlapContainer, layerContributesToOverlap, becameCompositedAfterDescendantTraversal && !descendantsAddedToOverlap);
1074 overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
1076 LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(compositingState.depth * 2, ' ') << &layer << " computeCompositingRequirements - willBeComposited " << willBeComposited << " (backing provider candidate " << backingSharingState.backingProviderCandidate() << ")");
1079 // We have to traverse unchanged layers to fill in the overlap map.
1080 void RenderLayerCompositor::traverseUnchangedSubtree(RenderLayer* ancestorLayer, RenderLayer& layer, LayerOverlapMap& overlapMap, CompositingState& compositingState, BackingSharingState& backingSharingState, bool& descendantHas3DTransform)
1082 ASSERT(!compositingState.fullPaintOrderTraversalRequired);
1083 ASSERT(!layer.hasDescendantNeedingCompositingRequirementsTraversal());
1084 ASSERT(!layer.needsCompositingRequirementsTraversal());
1086 LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(compositingState.depth * 2, ' ') << &layer << (layer.isNormalFlowOnly() ? " n" : " s") << " traverseUnchangedSubtree");
1088 layer.updateDescendantDependentFlags();
1089 layer.updateLayerListsIfNeeded();
1091 bool layerIsComposited = layer.isComposited();
1092 bool layerPaintsIntoProvidedBacking = false;
1093 bool didPushOverlapContainer = false;
1095 OverlapExtent layerExtent;
1096 if (layerIsComposited && !layer.isRenderViewLayer())
1097 layerExtent.hasTransformAnimation = isRunningTransformAnimation(layer.renderer());
1099 bool respectTransforms = !layerExtent.hasTransformAnimation;
1100 overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer, respectTransforms);
1102 // If we know for sure the layer is going to be composited, don't bother looking it up in the overlap map
1103 if (!layerIsComposited && !overlapMap.isEmpty() && compositingState.testingOverlap)
1104 computeExtent(overlapMap, layer, layerExtent);
1106 if (layer.paintsIntoProvidedBacking()) {
1107 ASSERT(backingSharingState.backingProviderCandidate());
1108 ASSERT(backingProviderLayerCanIncludeLayer(*backingSharingState.backingProviderCandidate(), layer));
1109 backingSharingState.appendSharingLayer(layer);
1110 layerPaintsIntoProvidedBacking = true;
1113 CompositingState currentState = compositingState.stateForPaintOrderChildren(layer);
1115 if (layerIsComposited) {
1116 // This layer is going to be composited, so children can safely ignore the fact that there's an
1117 // animation running behind this layer, meaning they can rely on the overlap map testing again.
1118 currentState.testingOverlap = true;
1119 // This layer now acts as the ancestor for kids.
1120 currentState.compositingAncestor = &layer;
1121 currentState.backingSharingAncestor = nullptr;
1122 overlapMap.pushCompositingContainer();
1123 didPushOverlapContainer = true;
1124 LOG_WITH_STREAM(CompositingOverlap, stream << "unchangedSubtree: layer " << &layer << " will composite, pushed container " << overlapMap);
1126 computeExtent(overlapMap, layer, layerExtent);
1127 currentState.ancestorHasTransformAnimation |= layerExtent.hasTransformAnimation;
1128 // Too hard to compute animated bounds if both us and some ancestor is animating transform.
1129 layerExtent.animationCausesExtentUncertainty |= layerExtent.hasTransformAnimation && compositingState.ancestorHasTransformAnimation;
1130 } else if (layerPaintsIntoProvidedBacking) {
1131 overlapMap.pushCompositingContainer();
1132 currentState.backingSharingAncestor = &layer;
1133 didPushOverlapContainer = true;
1134 LOG_WITH_STREAM(CompositingOverlap, stream << "unchangedSubtree: layer " << &layer << " will share, pushed container " << overlapMap);
1137 backingSharingState.updateBeforeDescendantTraversal(layer, layerIsComposited);
1139 #if !ASSERT_DISABLED
1140 LayerListMutationDetector mutationChecker(layer);
1143 bool anyDescendantHas3DTransform = false;
1145 for (auto* childLayer : layer.negativeZOrderLayers()) {
1146 traverseUnchangedSubtree(&layer, *childLayer, overlapMap, currentState, backingSharingState, anyDescendantHas3DTransform);
1147 if (currentState.subtreeIsCompositing)
1148 ASSERT(layerIsComposited);
1151 for (auto* childLayer : layer.normalFlowLayers())
1152 traverseUnchangedSubtree(&layer, *childLayer, overlapMap, currentState, backingSharingState, anyDescendantHas3DTransform);
1154 for (auto* childLayer : layer.positiveZOrderLayers())
1155 traverseUnchangedSubtree(&layer, *childLayer, overlapMap, currentState, backingSharingState, anyDescendantHas3DTransform);
1157 // Set the flag to say that this layer has compositing children.
1158 ASSERT(layer.hasCompositingDescendant() == currentState.subtreeIsCompositing);
1159 ASSERT_IMPLIES(canBeComposited(layer) && clipsCompositingDescendants(layer), layerIsComposited);
1161 descendantHas3DTransform |= anyDescendantHas3DTransform || layer.has3DTransform();
1163 ASSERT(!currentState.fullPaintOrderTraversalRequired);
1164 compositingState.updateWithDescendantStateAndLayer(currentState, layer, layerExtent, true);
1165 backingSharingState.updateAfterDescendantTraversal(layer, compositingState.stackingContextAncestor);
1167 bool layerContributesToOverlap = (currentState.compositingAncestor && !currentState.compositingAncestor->isRenderViewLayer()) || currentState.backingSharingAncestor;
1168 updateOverlapMap(overlapMap, layer, layerExtent, didPushOverlapContainer, layerContributesToOverlap);
1170 overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
1172 ASSERT(!layer.needsCompositingRequirementsTraversal());
1175 void RenderLayerCompositor::updateBackingAndHierarchy(RenderLayer& layer, Vector<Ref<GraphicsLayer>>& childLayersOfEnclosingLayer, ScrollingTreeState& scrollingTreeState, OptionSet<UpdateLevel> updateLevel, int depth)
1177 layer.updateDescendantDependentFlags();
1178 layer.updateLayerListsIfNeeded();
1180 bool layerNeedsUpdate = !updateLevel.isEmpty();
1181 if (layer.descendantsNeedUpdateBackingAndHierarchyTraversal())
1182 updateLevel.add(UpdateLevel::AllDescendants);
1184 ScrollingTreeState stateForDescendants = scrollingTreeState;
1186 auto* layerBacking = layer.backing();
1188 updateLevel.remove(UpdateLevel::CompositedChildren);
1190 // We updated the composited bounds in RenderLayerBacking::updateAfterLayout(), but it may have changed
1191 // based on which descendants are now composited.
1192 if (layerBacking->updateCompositedBounds()) {
1193 layer.setNeedsCompositingGeometryUpdate();
1194 // Our geometry can affect descendants.
1195 updateLevel.add(UpdateLevel::CompositedChildren);
1198 if (layerNeedsUpdate || layer.needsCompositingConfigurationUpdate()) {
1199 if (layerBacking->updateConfiguration()) {
1200 layerNeedsUpdate = true; // We also need to update geometry.
1201 layer.setNeedsCompositingLayerConnection();
1204 layerBacking->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
1207 OptionSet<ScrollingNodeChangeFlags> scrollingNodeChanges = { ScrollingNodeChangeFlags::Layer };
1208 if (layerNeedsUpdate || layer.needsCompositingGeometryUpdate()) {
1209 layerBacking->updateGeometry();
1210 scrollingNodeChanges.add(ScrollingNodeChangeFlags::LayerGeometry);
1211 } else if (layer.needsScrollingTreeUpdate())
1212 scrollingNodeChanges.add(ScrollingNodeChangeFlags::LayerGeometry);
1214 if (auto* reflection = layer.reflectionLayer()) {
1215 if (auto* reflectionBacking = reflection->backing()) {
1216 reflectionBacking->updateCompositedBounds();
1217 reflectionBacking->updateGeometry();
1218 reflectionBacking->updateAfterDescendants();
1222 if (!layer.parent())
1223 updateRootLayerPosition();
1225 // FIXME: do based on dirty flags. Need to do this for changes of geometry, configuration and hierarchy.
1226 // Need to be careful to do the right thing when a scroll-coordinated layer loses a scroll-coordinated ancestor.
1227 stateForDescendants.parentNodeID = updateScrollCoordinationForLayer(layer, scrollingTreeState, layerBacking->coordinatedScrollingRoles(), scrollingNodeChanges);
1228 stateForDescendants.nextChildIndex = 0;
1231 logLayerInfo(layer, "updateBackingAndHierarchy", depth);
1233 UNUSED_PARAM(depth);
1237 if (layer.childrenNeedCompositingGeometryUpdate())
1238 updateLevel.add(UpdateLevel::CompositedChildren);
1240 // If this layer has backing, then we are collecting its children, otherwise appending
1241 // to the compositing child list of an enclosing layer.
1242 Vector<Ref<GraphicsLayer>> layerChildren;
1243 auto& childList = layerBacking ? layerChildren : childLayersOfEnclosingLayer;
1245 bool requireDescendantTraversal = layer.hasDescendantNeedingUpdateBackingOrHierarchyTraversal()
1246 || (layer.hasCompositingDescendant() && (!layerBacking || layer.needsCompositingLayerConnection() || !updateLevel.isEmpty()));
1248 bool requiresChildRebuild = layerBacking && layer.needsCompositingLayerConnection() && !layer.hasCompositingDescendant();
1250 #if !ASSERT_DISABLED
1251 LayerListMutationDetector mutationChecker(layer);
1254 auto appendForegroundLayerIfNecessary = [&] {
1255 // If a negative z-order child is compositing, we get a foreground layer which needs to get parented.
1256 if (layer.negativeZOrderLayers().size()) {
1257 if (layerBacking && layerBacking->foregroundLayer())
1258 childList.append(*layerBacking->foregroundLayer());
1262 if (requireDescendantTraversal) {
1263 for (auto* renderLayer : layer.negativeZOrderLayers())
1264 updateBackingAndHierarchy(*renderLayer, childList, stateForDescendants, updateLevel, depth + 1);
1266 appendForegroundLayerIfNecessary();
1268 for (auto* renderLayer : layer.normalFlowLayers())
1269 updateBackingAndHierarchy(*renderLayer, childList, stateForDescendants, updateLevel, depth + 1);
1271 for (auto* renderLayer : layer.positiveZOrderLayers())
1272 updateBackingAndHierarchy(*renderLayer, childList, stateForDescendants, updateLevel, depth + 1);
1273 } else if (requiresChildRebuild)
1274 appendForegroundLayerIfNecessary();
1277 if (requireDescendantTraversal || requiresChildRebuild) {
1278 bool parented = false;
1279 if (is<RenderWidget>(layer.renderer()))
1280 parented = parentFrameContentLayers(downcast<RenderWidget>(layer.renderer()));
1283 layerBacking->parentForSublayers()->setChildren(WTFMove(layerChildren));
1285 // If the layer has a clipping layer the overflow controls layers will be siblings of the clipping layer.
1286 // Otherwise, the overflow control layers are normal children.
1287 if (!layerBacking->hasClippingLayer() && !layerBacking->hasScrollingLayer()) {
1288 if (auto* overflowControlLayer = layerBacking->layerForHorizontalScrollbar())
1289 layerBacking->parentForSublayers()->addChild(*overflowControlLayer);
1291 if (auto* overflowControlLayer = layerBacking->layerForVerticalScrollbar())
1292 layerBacking->parentForSublayers()->addChild(*overflowControlLayer);
1294 if (auto* overflowControlLayer = layerBacking->layerForScrollCorner())
1295 layerBacking->parentForSublayers()->addChild(*overflowControlLayer);
1299 childLayersOfEnclosingLayer.append(*layerBacking->childForSuperlayers());
1301 layerBacking->updateAfterDescendants();
1304 layer.clearUpdateBackingOrHierarchyTraversalState();
1307 void RenderLayerCompositor::appendDocumentOverlayLayers(Vector<Ref<GraphicsLayer>>& childList)
1309 if (!isMainFrameCompositor() || !m_compositing)
1312 if (!page().pageOverlayController().hasDocumentOverlays())
1315 Ref<GraphicsLayer> overlayHost = page().pageOverlayController().layerWithDocumentOverlays();
1316 childList.append(WTFMove(overlayHost));
1319 bool RenderLayerCompositor::needsCompositingForContentOrOverlays() const
1321 return m_contentLayersCount + page().pageOverlayController().overlayCount();
1324 void RenderLayerCompositor::layerBecameComposited(const RenderLayer& layer)
1326 if (&layer != m_renderView.layer())
1327 ++m_contentLayersCount;
1330 void RenderLayerCompositor::layerBecameNonComposited(const RenderLayer& layer)
1332 // Inform the inspector that the given RenderLayer was destroyed.
1333 // FIXME: "destroyed" is a misnomer.
1334 InspectorInstrumentation::renderLayerDestroyed(&page(), layer);
1336 if (&layer != m_renderView.layer()) {
1337 ASSERT(m_contentLayersCount > 0);
1338 --m_contentLayersCount;
1343 void RenderLayerCompositor::logLayerInfo(const RenderLayer& layer, const char* phase, int depth)
1345 if (!compositingLogEnabled())
1348 auto* backing = layer.backing();
1349 RequiresCompositingData queryData;
1350 if (requiresCompositingLayer(layer, queryData) || layer.isRenderViewLayer()) {
1351 ++m_obligateCompositedLayerCount;
1352 m_obligatoryBackingStoreBytes += backing->backingStoreMemoryEstimate();
1354 ++m_secondaryCompositedLayerCount;
1355 m_secondaryBackingStoreBytes += backing->backingStoreMemoryEstimate();
1358 LayoutRect absoluteBounds = backing->compositedBounds();
1359 absoluteBounds.move(layer.offsetFromAncestor(m_renderView.layer()));
1361 StringBuilder logString;
1362 logString.append(makeString(pad(' ', 12 + depth * 2, hex(reinterpret_cast<uintptr_t>(&layer))), " id ", backing->graphicsLayer()->primaryLayerID(), " (", FormattedNumber::fixedWidth(absoluteBounds.x().toFloat(), 3), ',', FormattedNumber::fixedWidth(absoluteBounds.y().toFloat(), 3), '-', FormattedNumber::fixedWidth(absoluteBounds.maxX().toFloat(), 3), ',', FormattedNumber::fixedWidth(absoluteBounds.maxY().toFloat(), 3), ") ", FormattedNumber::fixedWidth(backing->backingStoreMemoryEstimate() / 1024, 2), "KB"));
1364 if (!layer.renderer().style().hasAutoZIndex())
1365 logString.append(makeString(" z-index: ", layer.renderer().style().zIndex()));
1367 logString.appendLiteral(" (");
1368 logString.append(logReasonsForCompositing(layer));
1369 logString.appendLiteral(") ");
1371 if (backing->graphicsLayer()->contentsOpaque() || backing->paintsIntoCompositedAncestor() || backing->foregroundLayer() || backing->backgroundLayer()) {
1372 logString.append('[');
1373 bool prependSpace = false;
1374 if (backing->graphicsLayer()->contentsOpaque()) {
1375 logString.appendLiteral("opaque");
1376 prependSpace = true;
1379 if (backing->paintsIntoCompositedAncestor()) {
1381 logString.appendLiteral(", ");
1382 logString.appendLiteral("paints into ancestor");
1383 prependSpace = true;
1386 if (backing->foregroundLayer() || backing->backgroundLayer()) {
1388 logString.appendLiteral(", ");
1389 if (backing->foregroundLayer() && backing->backgroundLayer()) {
1390 logString.appendLiteral("+foreground+background");
1391 prependSpace = true;
1392 } else if (backing->foregroundLayer()) {
1393 logString.appendLiteral("+foreground");
1394 prependSpace = true;
1396 logString.appendLiteral("+background");
1397 prependSpace = true;
1401 if (backing->paintsSubpixelAntialiasedText()) {
1403 logString.appendLiteral(", ");
1404 logString.appendLiteral("texty");
1407 logString.appendLiteral("] ");
1410 logString.append(layer.name());
1412 logString.appendLiteral(" - ");
1413 logString.append(phase);
1415 LOG(Compositing, "%s", logString.toString().utf8().data());
1419 static bool clippingChanged(const RenderStyle& oldStyle, const RenderStyle& newStyle)
1421 return oldStyle.overflowX() != newStyle.overflowX() || oldStyle.overflowY() != newStyle.overflowY()
1422 || oldStyle.hasClip() != newStyle.hasClip() || oldStyle.clip() != newStyle.clip();
1425 static bool styleAffectsLayerGeometry(const RenderStyle& style)
1427 return style.hasClip() || style.clipPath() || style.hasBorderRadius();
1430 static bool recompositeChangeRequiresGeometryUpdate(const RenderStyle& oldStyle, const RenderStyle& newStyle)
1432 return oldStyle.transform() != newStyle.transform()
1433 || oldStyle.transformOriginX() != newStyle.transformOriginX()
1434 || oldStyle.transformOriginY() != newStyle.transformOriginY()
1435 || oldStyle.transformOriginZ() != newStyle.transformOriginZ()
1436 || oldStyle.transformStyle3D() != newStyle.transformStyle3D()
1437 || oldStyle.perspective() != newStyle.perspective()
1438 || oldStyle.perspectiveOriginX() != newStyle.perspectiveOriginX()
1439 || oldStyle.perspectiveOriginY() != newStyle.perspectiveOriginY()
1440 || oldStyle.backfaceVisibility() != newStyle.backfaceVisibility()
1441 || !arePointingToEqualData(oldStyle.clipPath(), newStyle.clipPath());
1444 void RenderLayerCompositor::layerStyleChanged(StyleDifference diff, RenderLayer& layer, const RenderStyle* oldStyle)
1446 if (diff == StyleDifference::Equal)
1449 // Create or destroy backing here so that code that runs during layout can reliably use isComposited() (though this
1450 // is only true for layers composited for direct reasons).
1451 // Also, it allows us to avoid a tree walk in updateCompositingLayers() when no layer changed its compositing state.
1452 RequiresCompositingData queryData;
1453 queryData.layoutUpToDate = LayoutUpToDate::No;
1455 bool layerChanged = updateBacking(layer, queryData, CompositingChangeRepaintNow);
1457 layer.setChildrenNeedCompositingGeometryUpdate();
1458 layer.setNeedsCompositingLayerConnection();
1459 layer.setSubsequentLayersNeedCompositingRequirementsTraversal();
1460 // Ancestor layers that composited for indirect reasons (things listed in styleChangeMayAffectIndirectCompositingReasons()) need to get updated.
1461 // This could be optimized by only setting this flag on layers with the relevant styles.
1462 layer.setNeedsPostLayoutCompositingUpdateOnAncestors();
1465 if (queryData.reevaluateAfterLayout)
1466 layer.setNeedsPostLayoutCompositingUpdate();
1468 if (diff >= StyleDifference::LayoutPositionedMovementOnly && hasContentCompositingLayers()) {
1469 layer.setNeedsPostLayoutCompositingUpdate();
1470 layer.setNeedsCompositingGeometryUpdate();
1473 auto* backing = layer.backing();
1477 backing->updateConfigurationAfterStyleChange();
1479 const auto& newStyle = layer.renderer().style();
1481 if (diff >= StyleDifference::Repaint) {
1482 // Visibility change may affect geometry of the enclosing composited layer.
1483 if (oldStyle && oldStyle->visibility() != newStyle.visibility())
1484 layer.setNeedsCompositingGeometryUpdate();
1486 // We'll get a diff of Repaint when things like clip-path change; these might affect layer or inner-layer geometry.
1487 if (layer.isComposited() && oldStyle) {
1488 if (styleAffectsLayerGeometry(*oldStyle) || styleAffectsLayerGeometry(newStyle))
1489 layer.setNeedsCompositingGeometryUpdate();
1493 // This is necessary to get iframe layers hooked up in response to scheduleInvalidateStyleAndLayerComposition().
1494 if (diff == StyleDifference::RecompositeLayer && layer.isComposited() && is<RenderWidget>(layer.renderer()))
1495 layer.setNeedsCompositingConfigurationUpdate();
1497 if (diff >= StyleDifference::RecompositeLayer && oldStyle && recompositeChangeRequiresGeometryUpdate(*oldStyle, newStyle)) {
1498 // FIXME: transform changes really need to trigger layout. See RenderElement::adjustStyleDifference().
1499 layer.setNeedsPostLayoutCompositingUpdate();
1500 layer.setNeedsCompositingGeometryUpdate();
1503 if (diff >= StyleDifference::Layout) {
1504 // FIXME: only set flags here if we know we have a composited descendant, but we might not know at this point.
1505 if (oldStyle && clippingChanged(*oldStyle, newStyle)) {
1506 if (layer.isStackingContext()) {
1507 layer.setNeedsPostLayoutCompositingUpdate(); // Layer needs to become composited if it has composited descendants.
1508 layer.setNeedsCompositingConfigurationUpdate(); // If already composited, layer needs to create/destroy clipping layer.
1510 // Descendant (in containing block order) compositing layers need to re-evaluate their clipping,
1511 // but they might be siblings in z-order so go up to our stacking context.
1512 if (auto* stackingContext = layer.stackingContext())
1513 stackingContext->setDescendantsNeedUpdateBackingAndHierarchyTraversal();
1517 // These properties trigger compositing if some descendant is composited.
1518 if (oldStyle && styleChangeMayAffectIndirectCompositingReasons(*oldStyle, newStyle))
1519 layer.setNeedsPostLayoutCompositingUpdate();
1521 layer.setNeedsCompositingGeometryUpdate();
1525 bool RenderLayerCompositor::needsCompositingUpdateForStyleChangeOnNonCompositedLayer(RenderLayer& layer, const RenderStyle* oldStyle) const
1527 // Needed for scroll bars.
1528 if (layer.isRenderViewLayer())
1534 const RenderStyle& newStyle = layer.renderer().style();
1535 // Visibility change may affect geometry of the enclosing composited layer.
1536 if (oldStyle->visibility() != newStyle.visibility())
1539 // We don't have any direct reasons for this style change to affect layer composition. Test if it might affect things indirectly.
1540 if (styleChangeMayAffectIndirectCompositingReasons(*oldStyle, newStyle))
1546 bool RenderLayerCompositor::canCompositeClipPath(const RenderLayer& layer)
1548 ASSERT(layer.isComposited());
1549 ASSERT(layer.renderer().style().clipPath());
1551 if (layer.renderer().hasMask())
1554 auto& clipPath = *layer.renderer().style().clipPath();
1555 return (clipPath.type() != ClipPathOperation::Shape || clipPath.type() == ClipPathOperation::Shape) && GraphicsLayer::supportsLayerType(GraphicsLayer::Type::Shape);
1558 // FIXME: remove and never ask questions about reflection layers.
1559 static RenderLayerModelObject& rendererForCompositingTests(const RenderLayer& layer)
1561 auto* renderer = &layer.renderer();
1563 // The compositing state of a reflection should match that of its reflected layer.
1564 if (layer.isReflection())
1565 renderer = downcast<RenderLayerModelObject>(renderer->parent()); // The RenderReplica's parent is the object being reflected.
1570 void RenderLayerCompositor::updateRootContentLayerClipping()
1572 m_rootContentsLayer->setMasksToBounds(!m_renderView.settings().backgroundShouldExtendBeyondPage());
1575 bool RenderLayerCompositor::updateBacking(RenderLayer& layer, RequiresCompositingData& queryData, CompositingChangeRepaint shouldRepaint, BackingRequired backingRequired)
1577 bool layerChanged = false;
1578 if (backingRequired == BackingRequired::Unknown)
1579 backingRequired = needsToBeComposited(layer, queryData) ? BackingRequired::Yes : BackingRequired::No;
1581 // Need to fetch viewportConstrainedNotCompositedReason, but without doing all the work that needsToBeComposited does.
1582 requiresCompositingForPosition(rendererForCompositingTests(layer), layer, queryData);
1585 if (backingRequired == BackingRequired::Yes) {
1586 layer.disconnectFromBackingProviderLayer();
1588 enableCompositingMode();
1590 if (!layer.backing()) {
1591 // If we need to repaint, do so before making backing
1592 if (shouldRepaint == CompositingChangeRepaintNow)
1593 repaintOnCompositingChange(layer); // wrong backing
1595 layer.ensureBacking();
1597 if (layer.isRenderViewLayer() && useCoordinatedScrollingForLayer(layer)) {
1598 auto& frameView = m_renderView.frameView();
1599 if (auto* scrollingCoordinator = this->scrollingCoordinator())
1600 scrollingCoordinator->frameViewRootLayerDidChange(frameView);
1601 #if ENABLE(RUBBER_BANDING)
1602 updateLayerForHeader(frameView.headerHeight());
1603 updateLayerForFooter(frameView.footerHeight());
1605 updateRootContentLayerClipping();
1607 if (auto* tiledBacking = layer.backing()->tiledBacking())
1608 tiledBacking->setTopContentInset(frameView.topContentInset());
1611 // This layer and all of its descendants have cached repaints rects that are relative to
1612 // the repaint container, so change when compositing changes; we need to update them here.
1614 layer.computeRepaintRectsIncludingDescendants();
1616 layer.setNeedsCompositingGeometryUpdate();
1617 layer.setNeedsCompositingConfigurationUpdate();
1618 layer.setNeedsCompositingPaintOrderChildrenUpdate();
1620 layerChanged = true;
1623 if (layer.backing()) {
1624 // If we're removing backing on a reflection, clear the source GraphicsLayer's pointer to
1625 // its replica GraphicsLayer. In practice this should never happen because reflectee and reflection
1626 // are both either composited, or not composited.
1627 if (layer.isReflection()) {
1628 auto* sourceLayer = downcast<RenderLayerModelObject>(*layer.renderer().parent()).layer();
1629 if (auto* backing = sourceLayer->backing()) {
1630 ASSERT(backing->graphicsLayer()->replicaLayer() == layer.backing()->graphicsLayer());
1631 backing->graphicsLayer()->setReplicatedByLayer(nullptr);
1635 layer.clearBacking();
1636 layerChanged = true;
1638 // This layer and all of its descendants have cached repaints rects that are relative to
1639 // the repaint container, so change when compositing changes; we need to update them here.
1640 layer.computeRepaintRectsIncludingDescendants();
1642 // If we need to repaint, do so now that we've removed the backing
1643 if (shouldRepaint == CompositingChangeRepaintNow)
1644 repaintOnCompositingChange(layer);
1649 if (layerChanged && is<RenderVideo>(layer.renderer())) {
1650 // If it's a video, give the media player a chance to hook up to the layer.
1651 downcast<RenderVideo>(layer.renderer()).acceleratedRenderingStateChanged();
1655 if (layerChanged && is<RenderWidget>(layer.renderer())) {
1656 auto* innerCompositor = frameContentsCompositor(downcast<RenderWidget>(layer.renderer()));
1657 if (innerCompositor && innerCompositor->usesCompositing())
1658 innerCompositor->updateRootLayerAttachment();
1662 layer.clearClipRectsIncludingDescendants(PaintingClipRects);
1664 // If a fixed position layer gained/lost a backing or the reason not compositing it changed,
1665 // the scrolling coordinator needs to recalculate whether it can do fast scrolling.
1666 if (layer.renderer().isFixedPositioned()) {
1667 if (layer.viewportConstrainedNotCompositedReason() != queryData.nonCompositedForPositionReason) {
1668 layer.setViewportConstrainedNotCompositedReason(queryData.nonCompositedForPositionReason);
1669 layerChanged = true;
1672 if (auto* scrollingCoordinator = this->scrollingCoordinator())
1673 scrollingCoordinator->frameViewFixedObjectsDidChange(m_renderView.frameView());
1676 layer.setViewportConstrainedNotCompositedReason(RenderLayer::NoNotCompositedReason);
1678 if (layer.backing())
1679 layer.backing()->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
1681 return layerChanged;
1684 bool RenderLayerCompositor::updateLayerCompositingState(RenderLayer& layer, RequiresCompositingData& queryData, CompositingChangeRepaint shouldRepaint)
1686 bool layerChanged = updateBacking(layer, queryData, shouldRepaint);
1688 // See if we need content or clipping layers. Methods called here should assume
1689 // that the compositing state of descendant layers has not been updated yet.
1690 if (layer.backing() && layer.backing()->updateConfiguration())
1691 layerChanged = true;
1693 return layerChanged;
1696 void RenderLayerCompositor::repaintOnCompositingChange(RenderLayer& layer)
1698 // If the renderer is not attached yet, no need to repaint.
1699 if (&layer.renderer() != &m_renderView && !layer.renderer().parent())
1702 auto* repaintContainer = layer.renderer().containerForRepaint();
1703 if (!repaintContainer)
1704 repaintContainer = &m_renderView;
1706 layer.repaintIncludingNonCompositingDescendants(repaintContainer);
1707 if (repaintContainer == &m_renderView) {
1708 // The contents of this layer may be moving between the window
1709 // and a GraphicsLayer, so we need to make sure the window system
1710 // synchronizes those changes on the screen.
1711 m_renderView.frameView().setNeedsOneShotDrawingSynchronization();
1715 // This method assumes that layout is up-to-date, unlike repaintOnCompositingChange().
1716 void RenderLayerCompositor::repaintInCompositedAncestor(RenderLayer& layer, const LayoutRect& rect)
1718 auto* compositedAncestor = layer.enclosingCompositingLayerForRepaint(ExcludeSelf);
1719 if (!compositedAncestor)
1722 ASSERT(compositedAncestor->backing());
1723 LayoutRect repaintRect = rect;
1724 repaintRect.move(layer.offsetFromAncestor(compositedAncestor));
1725 compositedAncestor->setBackingNeedsRepaintInRect(repaintRect);
1727 // The contents of this layer may be moving from a GraphicsLayer to the window,
1728 // so we need to make sure the window system synchronizes those changes on the screen.
1729 if (compositedAncestor->isRenderViewLayer())
1730 m_renderView.frameView().setNeedsOneShotDrawingSynchronization();
1734 void RenderLayerCompositor::layerWasAdded(RenderLayer&, RenderLayer&)
1738 void RenderLayerCompositor::layerWillBeRemoved(RenderLayer& parent, RenderLayer& child)
1740 if (parent.renderer().renderTreeBeingDestroyed())
1743 if (child.isComposited())
1744 repaintInCompositedAncestor(child, child.backing()->compositedBounds()); // FIXME: do via dirty bits?
1745 else if (child.paintsIntoProvidedBacking()) {
1746 auto* backingProviderLayer = child.backingProviderLayer();
1747 // FIXME: Optimize this repaint.
1748 backingProviderLayer->setBackingNeedsRepaint();
1749 backingProviderLayer->backing()->removeBackingSharingLayer(child);
1753 child.setNeedsCompositingLayerConnection();
1756 RenderLayer* RenderLayerCompositor::enclosingNonStackingClippingLayer(const RenderLayer& layer) const
1758 for (auto* parent = layer.parent(); parent; parent = parent->parent()) {
1759 if (parent->isStackingContext())
1761 if (parent->renderer().hasClipOrOverflowClip())
1767 void RenderLayerCompositor::computeExtent(const LayerOverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& extent) const
1769 if (extent.extentComputed)
1772 LayoutRect layerBounds;
1773 if (extent.hasTransformAnimation)
1774 extent.animationCausesExtentUncertainty = !layer.getOverlapBoundsIncludingChildrenAccountingForTransformAnimations(layerBounds);
1776 layerBounds = layer.overlapBounds();
1778 // In the animating transform case, we avoid double-accounting for the transform because
1779 // we told pushMappingsToAncestor() to ignore transforms earlier.
1780 extent.bounds = enclosingLayoutRect(overlapMap.geometryMap().absoluteRect(layerBounds));
1782 // Empty rects never intersect, but we need them to for the purposes of overlap testing.
1783 if (extent.bounds.isEmpty())
1784 extent.bounds.setSize(LayoutSize(1, 1));
1786 RenderLayerModelObject& renderer = layer.renderer();
1787 if (renderer.isFixedPositioned() && renderer.container() == &m_renderView) {
1788 // Because fixed elements get moved around without re-computing overlap, we have to compute an overlap
1789 // rect that covers all the locations that the fixed element could move to.
1790 // FIXME: need to handle sticky too.
1791 extent.bounds = m_renderView.frameView().fixedScrollableAreaBoundsInflatedForScrolling(extent.bounds);
1794 extent.extentComputed = true;
1797 enum class AncestorTraversal { Continue, Stop };
1799 // This is a simplified version of containing block walking that only handles absolute position.
1800 template <typename Function>
1801 static AncestorTraversal traverseAncestorLayers(const RenderLayer& layer, Function&& function)
1803 bool containingBlockCanSkipLayers = layer.renderer().isAbsolutelyPositioned();
1804 RenderLayer* nextPaintOrderParent = layer.paintOrderParent();
1806 for (const auto* ancestorLayer = layer.parent(); ancestorLayer; ancestorLayer = ancestorLayer->parent()) {
1807 bool inContainingBlockChain = true;
1809 if (containingBlockCanSkipLayers)
1810 inContainingBlockChain = ancestorLayer->renderer().canContainAbsolutelyPositionedObjects();
1812 if (function(*ancestorLayer, inContainingBlockChain, ancestorLayer == nextPaintOrderParent) == AncestorTraversal::Stop)
1813 return AncestorTraversal::Stop;
1815 if (inContainingBlockChain)
1816 containingBlockCanSkipLayers = ancestorLayer->renderer().isAbsolutelyPositioned();
1818 if (ancestorLayer == nextPaintOrderParent)
1819 nextPaintOrderParent = ancestorLayer->paintOrderParent();
1822 return AncestorTraversal::Continue;
1825 static bool createsClippingScope(const RenderLayer& layer)
1827 return layer.hasCompositedScrollableOverflow();
1830 static Vector<LayerOverlapMap::LayerAndBounds> enclosingClippingScopes(const RenderLayer& layer, const RenderLayer& rootLayer)
1832 Vector<LayerOverlapMap::LayerAndBounds> clippingScopes;
1833 clippingScopes.append({ const_cast<RenderLayer&>(rootLayer), { } });
1835 if (!layer.hasCompositedScrollingAncestor())
1836 return clippingScopes;
1838 traverseAncestorLayers(layer, [&](const RenderLayer& ancestorLayer, bool inContainingBlockChain, bool) {
1839 if (inContainingBlockChain && createsClippingScope(ancestorLayer)) {
1840 LayoutRect clipRect;
1841 if (is<RenderBox>(ancestorLayer.renderer())) {
1842 // FIXME: This is expensive. Broken with transforms.
1843 LayoutPoint offsetFromRoot = ancestorLayer.convertToLayerCoords(&rootLayer, { });
1844 clipRect = downcast<RenderBox>(ancestorLayer.renderer()).overflowClipRect(offsetFromRoot);
1847 LayerOverlapMap::LayerAndBounds layerAndBounds { const_cast<RenderLayer&>(ancestorLayer), clipRect };
1848 clippingScopes.insert(1, layerAndBounds); // Order is roots to leaves.
1850 return AncestorTraversal::Continue;
1853 return clippingScopes;
1856 void RenderLayerCompositor::addToOverlapMap(LayerOverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& extent) const
1858 if (layer.isRenderViewLayer())
1861 computeExtent(overlapMap, layer, extent);
1863 // FIXME: constrain the scopes (by composited stacking context ancestor I think).
1864 auto clippingScopes = enclosingClippingScopes(layer, rootRenderLayer());
1866 LayoutRect clipRect;
1867 if (layer.hasCompositedScrollingAncestor()) {
1868 // Compute a clip up to the composited scrolling ancestor, then convert it to absolute coordinates.
1869 auto& scrollingScope = clippingScopes.last();
1870 clipRect = layer.backgroundClipRect(RenderLayer::ClipRectsContext(&scrollingScope.layer, TemporaryClipRects, IgnoreOverlayScrollbarSize, IgnoreOverflowClip)).rect();
1871 if (!clipRect.isInfinite())
1872 clipRect.setLocation(layer.convertToLayerCoords(&rootRenderLayer(), clipRect.location()));
1874 clipRect = layer.backgroundClipRect(RenderLayer::ClipRectsContext(&rootRenderLayer(), AbsoluteClipRects)).rect(); // FIXME: Incorrect for CSS regions.
1876 auto clippedBounds = extent.bounds;
1877 if (!clipRect.isInfinite()) {
1878 // On iOS, pageScaleFactor() is not applied by RenderView, so we should not scale here.
1879 if (!m_renderView.settings().delegatesPageScaling())
1880 clipRect.scale(pageScaleFactor());
1882 clippedBounds.intersect(clipRect);
1885 overlapMap.add(layer, clippedBounds, clippingScopes);
1888 void RenderLayerCompositor::addDescendantsToOverlapMapRecursive(LayerOverlapMap& overlapMap, const RenderLayer& layer, const RenderLayer* ancestorLayer) const
1890 if (!canBeComposited(layer))
1893 // A null ancestorLayer is an indication that 'layer' has already been pushed.
1894 if (ancestorLayer) {
1895 overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer);
1897 OverlapExtent layerExtent;
1898 addToOverlapMap(overlapMap, layer, layerExtent);
1901 #if !ASSERT_DISABLED
1902 LayerListMutationDetector mutationChecker(const_cast<RenderLayer&>(layer));
1905 for (auto* renderLayer : layer.negativeZOrderLayers())
1906 addDescendantsToOverlapMapRecursive(overlapMap, *renderLayer, &layer);
1908 for (auto* renderLayer : layer.normalFlowLayers())
1909 addDescendantsToOverlapMapRecursive(overlapMap, *renderLayer, &layer);
1911 for (auto* renderLayer : layer.positiveZOrderLayers())
1912 addDescendantsToOverlapMapRecursive(overlapMap, *renderLayer, &layer);
1915 overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
1918 void RenderLayerCompositor::updateOverlapMap(LayerOverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& layerExtent, bool didPushContainer, bool addLayerToOverlap, bool addDescendantsToOverlap) const
1920 if (addLayerToOverlap) {
1921 auto clippingScopes = enclosingClippingScopes(layer, rootRenderLayer());
1922 addToOverlapMap(overlapMap, layer, layerExtent);
1923 LOG_WITH_STREAM(CompositingOverlap, stream << "layer " << &layer << " contributes to overlap, added to map " << overlapMap);
1926 if (addDescendantsToOverlap) {
1927 // If this is the first non-root layer to composite, we need to add all the descendants we already traversed to the overlap map.
1928 addDescendantsToOverlapMapRecursive(overlapMap, layer);
1929 LOG_WITH_STREAM(CompositingOverlap, stream << "layer " << &layer << " composited post descendant traversal, added recursive " << overlapMap);
1932 if (didPushContainer) {
1933 overlapMap.popCompositingContainer();
1934 LOG_WITH_STREAM(CompositingOverlap, stream << "layer " << &layer << " is composited or shared, popped container " << overlapMap);
1938 bool RenderLayerCompositor::layerOverlaps(const LayerOverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& layerExtent) const
1940 computeExtent(overlapMap, layer, layerExtent);
1942 auto clippingScopes = enclosingClippingScopes(layer, rootRenderLayer());
1943 return overlapMap.overlapsLayers(layer, layerExtent.bounds, clippingScopes);
1947 bool RenderLayerCompositor::canAccelerateVideoRendering(RenderVideo& video) const
1949 if (!m_hasAcceleratedCompositing)
1952 return video.supportsAcceleratedRendering();
1956 void RenderLayerCompositor::frameViewDidChangeLocation(const IntPoint& contentsOffset)
1958 if (m_overflowControlsHostLayer)
1959 m_overflowControlsHostLayer->setPosition(contentsOffset);
1962 void RenderLayerCompositor::frameViewDidChangeSize()
1964 if (auto* layer = m_renderView.layer())
1965 layer->setNeedsCompositingGeometryUpdate();
1967 if (m_scrolledContentsLayer) {
1968 updateScrollLayerClipping();
1969 frameViewDidScroll();
1970 updateOverflowControlsLayers();
1972 #if ENABLE(RUBBER_BANDING)
1973 if (m_layerForOverhangAreas) {
1974 auto& frameView = m_renderView.frameView();
1975 m_layerForOverhangAreas->setSize(frameView.frameRect().size());
1976 m_layerForOverhangAreas->setPosition(FloatPoint(0, frameView.topContentInset()));
1982 bool RenderLayerCompositor::hasCoordinatedScrolling() const
1984 auto* scrollingCoordinator = this->scrollingCoordinator();
1985 return scrollingCoordinator && scrollingCoordinator->coordinatesScrollingForFrameView(m_renderView.frameView());
1988 void RenderLayerCompositor::updateScrollLayerPosition()
1990 ASSERT(!hasCoordinatedScrolling());
1991 ASSERT(m_scrolledContentsLayer);
1993 auto& frameView = m_renderView.frameView();
1994 IntPoint scrollPosition = frameView.scrollPosition();
1996 m_scrolledContentsLayer->setPosition(FloatPoint(-scrollPosition.x(), -scrollPosition.y()));
1998 if (auto* fixedBackgroundLayer = fixedRootBackgroundLayer())
1999 fixedBackgroundLayer->setPosition(frameView.scrollPositionForFixedPosition());
2002 void RenderLayerCompositor::updateScrollLayerClipping()
2004 auto* layerForClipping = this->layerForClipping();
2005 if (!layerForClipping)
2008 layerForClipping->setSize(m_renderView.frameView().sizeForVisibleContent());
2009 layerForClipping->setPosition(positionForClipLayer());
2012 FloatPoint RenderLayerCompositor::positionForClipLayer() const
2014 auto& frameView = m_renderView.frameView();
2017 frameView.shouldPlaceBlockDirectionScrollbarOnLeft() ? frameView.horizontalScrollbarIntrusion() : 0,
2018 FrameView::yPositionForInsetClipLayer(frameView.scrollPosition(), frameView.topContentInset()));
2021 void RenderLayerCompositor::frameViewDidScroll()
2023 if (!m_scrolledContentsLayer)
2026 // If there's a scrolling coordinator that manages scrolling for this frame view,
2027 // it will also manage updating the scroll layer position.
2028 if (hasCoordinatedScrolling()) {
2029 // We have to schedule a flush in order for the main TiledBacking to update its tile coverage.
2030 scheduleLayerFlush();
2034 updateScrollLayerPosition();
2037 void RenderLayerCompositor::frameViewDidAddOrRemoveScrollbars()
2039 updateOverflowControlsLayers();
2042 void RenderLayerCompositor::frameViewDidLayout()
2044 if (auto* renderViewBacking = m_renderView.layer()->backing())
2045 renderViewBacking->adjustTiledBackingCoverage();
2048 void RenderLayerCompositor::rootLayerConfigurationChanged()
2050 auto* renderViewBacking = m_renderView.layer()->backing();
2051 if (renderViewBacking && renderViewBacking->isFrameLayerWithTiledBacking()) {
2052 m_renderView.layer()->setNeedsCompositingConfigurationUpdate();
2053 scheduleCompositingLayerUpdate();
2057 String RenderLayerCompositor::layerTreeAsText(LayerTreeFlags flags)
2059 updateCompositingLayers(CompositingUpdateType::AfterLayout);
2061 if (!m_rootContentsLayer)
2064 flushPendingLayerChanges(true);
2065 page().renderingUpdateScheduler().scheduleCompositingLayerFlush();
2067 LayerTreeAsTextBehavior layerTreeBehavior = LayerTreeAsTextBehaviorNormal;
2068 if (flags & LayerTreeFlagsIncludeDebugInfo)
2069 layerTreeBehavior |= LayerTreeAsTextDebug;
2070 if (flags & LayerTreeFlagsIncludeVisibleRects)
2071 layerTreeBehavior |= LayerTreeAsTextIncludeVisibleRects;
2072 if (flags & LayerTreeFlagsIncludeTileCaches)
2073 layerTreeBehavior |= LayerTreeAsTextIncludeTileCaches;
2074 if (flags & LayerTreeFlagsIncludeRepaintRects)
2075 layerTreeBehavior |= LayerTreeAsTextIncludeRepaintRects;
2076 if (flags & LayerTreeFlagsIncludePaintingPhases)
2077 layerTreeBehavior |= LayerTreeAsTextIncludePaintingPhases;
2078 if (flags & LayerTreeFlagsIncludeContentLayers)
2079 layerTreeBehavior |= LayerTreeAsTextIncludeContentLayers;
2080 if (flags & LayerTreeFlagsIncludeAcceleratesDrawing)
2081 layerTreeBehavior |= LayerTreeAsTextIncludeAcceleratesDrawing;
2082 if (flags & LayerTreeFlagsIncludeBackingStoreAttached)
2083 layerTreeBehavior |= LayerTreeAsTextIncludeBackingStoreAttached;
2084 if (flags & LayerTreeFlagsIncludeRootLayerProperties)
2085 layerTreeBehavior |= LayerTreeAsTextIncludeRootLayerProperties;
2086 if (flags & LayerTreeFlagsIncludeEventRegion)
2087 layerTreeBehavior |= LayerTreeAsTextIncludeEventRegion;
2089 // We skip dumping the scroll and clip layers to keep layerTreeAsText output
2090 // similar between platforms.
2091 String layerTreeText = m_rootContentsLayer->layerTreeAsText(layerTreeBehavior);
2093 // Dump an empty layer tree only if the only composited layer is the main frame's tiled backing,
2094 // so that tests expecting us to drop out of accelerated compositing when there are no layers succeed.
2095 if (!hasContentCompositingLayers() && documentUsesTiledBacking() && !(layerTreeBehavior & LayerTreeAsTextIncludeTileCaches) && !(layerTreeBehavior & LayerTreeAsTextIncludeRootLayerProperties))
2096 layerTreeText = emptyString();
2098 // The true root layer is not included in the dump, so if we want to report
2099 // its repaint rects, they must be included here.
2100 if (flags & LayerTreeFlagsIncludeRepaintRects)
2101 return m_renderView.frameView().trackedRepaintRectsAsText() + layerTreeText;
2103 return layerTreeText;
2106 static RenderView* frameContentsRenderView(RenderWidget& renderer)
2108 if (auto* contentDocument = renderer.frameOwnerElement().contentDocument())
2109 return contentDocument->renderView();
2114 RenderLayerCompositor* RenderLayerCompositor::frameContentsCompositor(RenderWidget& renderer)
2116 if (auto* view = frameContentsRenderView(renderer))
2117 return &view->compositor();
2122 bool RenderLayerCompositor::parentFrameContentLayers(RenderWidget& renderer)
2124 auto* innerCompositor = frameContentsCompositor(renderer);
2125 if (!innerCompositor || !innerCompositor->usesCompositing() || innerCompositor->rootLayerAttachment() != RootLayerAttachedViaEnclosingFrame)
2128 auto* layer = renderer.layer();
2129 if (!layer->isComposited())
2132 auto* backing = layer->backing();
2133 auto* hostingLayer = backing->parentForSublayers();
2134 auto* rootLayer = innerCompositor->rootGraphicsLayer();
2135 if (hostingLayer->children().size() != 1 || hostingLayer->children()[0].ptr() != rootLayer) {
2136 hostingLayer->removeAllChildren();
2137 hostingLayer->addChild(*rootLayer);
2140 if (auto frameHostingNodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::FrameHosting)) {
2141 auto* contentsRenderView = frameContentsRenderView(renderer);
2142 if (auto frameRootScrollingNodeID = contentsRenderView->frameView().scrollingNodeID()) {
2143 if (auto* scrollingCoordinator = this->scrollingCoordinator())
2144 scrollingCoordinator->insertNode(ScrollingNodeType::Subframe, frameRootScrollingNodeID, frameHostingNodeID, 0);
2148 // FIXME: Why always return true and not just when the layers changed?
2152 void RenderLayerCompositor::repaintCompositedLayers()
2154 recursiveRepaintLayer(rootRenderLayer());
2157 void RenderLayerCompositor::recursiveRepaintLayer(RenderLayer& layer)
2159 layer.updateLayerListsIfNeeded();
2161 // FIXME: This method does not work correctly with transforms.
2162 if (layer.isComposited() && !layer.backing()->paintsIntoCompositedAncestor())
2163 layer.setBackingNeedsRepaint();
2165 #if !ASSERT_DISABLED
2166 LayerListMutationDetector mutationChecker(layer);
2169 if (layer.hasCompositingDescendant()) {
2170 for (auto* renderLayer : layer.negativeZOrderLayers())
2171 recursiveRepaintLayer(*renderLayer);
2173 for (auto* renderLayer : layer.positiveZOrderLayers())
2174 recursiveRepaintLayer(*renderLayer);
2177 for (auto* renderLayer : layer.normalFlowLayers())
2178 recursiveRepaintLayer(*renderLayer);
2181 RenderLayer& RenderLayerCompositor::rootRenderLayer() const
2183 return *m_renderView.layer();
2186 GraphicsLayer* RenderLayerCompositor::rootGraphicsLayer() const
2188 if (m_overflowControlsHostLayer)
2189 return m_overflowControlsHostLayer.get();
2190 return m_rootContentsLayer.get();
2193 void RenderLayerCompositor::setIsInWindow(bool isInWindow)
2195 LOG(Compositing, "RenderLayerCompositor %p setIsInWindow %d", this, isInWindow);
2197 if (!usesCompositing())
2200 if (auto* rootLayer = rootGraphicsLayer()) {
2201 GraphicsLayer::traverse(*rootLayer, [isInWindow](GraphicsLayer& layer) {
2202 layer.setIsInWindow(isInWindow);
2207 if (m_rootLayerAttachment != RootLayerUnattached)
2210 RootLayerAttachment attachment = isMainFrameCompositor() ? RootLayerAttachedViaChromeClient : RootLayerAttachedViaEnclosingFrame;
2211 attachRootLayer(attachment);
2212 #if PLATFORM(IOS_FAMILY)
2213 if (m_legacyScrollingLayerCoordinator) {
2214 m_legacyScrollingLayerCoordinator->registerAllViewportConstrainedLayers(*this);
2215 m_legacyScrollingLayerCoordinator->registerAllScrollingLayers();
2219 if (m_rootLayerAttachment == RootLayerUnattached)
2223 #if PLATFORM(IOS_FAMILY)
2224 if (m_legacyScrollingLayerCoordinator) {
2225 m_legacyScrollingLayerCoordinator->unregisterAllViewportConstrainedLayers();
2226 m_legacyScrollingLayerCoordinator->unregisterAllScrollingLayers();
2232 void RenderLayerCompositor::clearBackingForLayerIncludingDescendants(RenderLayer& layer)
2234 if (layer.isComposited())
2235 layer.clearBacking();
2237 for (auto* childLayer = layer.firstChild(); childLayer; childLayer = childLayer->nextSibling())
2238 clearBackingForLayerIncludingDescendants(*childLayer);
2241 void RenderLayerCompositor::clearBackingForAllLayers()
2243 clearBackingForLayerIncludingDescendants(*m_renderView.layer());
2246 void RenderLayerCompositor::updateRootLayerPosition()
2248 if (m_rootContentsLayer) {
2249 m_rootContentsLayer->setSize(m_renderView.frameView().contentsSize());
2250 m_rootContentsLayer->setPosition(m_renderView.frameView().positionForRootContentLayer());
2251 m_rootContentsLayer->setAnchorPoint(FloatPoint3D());
2254 updateScrollLayerClipping();
2256 #if ENABLE(RUBBER_BANDING)
2257 if (m_contentShadowLayer && m_rootContentsLayer) {
2258 m_contentShadowLayer->setPosition(m_rootContentsLayer->position());
2259 m_contentShadowLayer->setSize(m_rootContentsLayer->size());
2262 updateLayerForTopOverhangArea(m_layerForTopOverhangArea != nullptr);
2263 updateLayerForBottomOverhangArea(m_layerForBottomOverhangArea != nullptr);
2264 updateLayerForHeader(m_layerForHeader != nullptr);
2265 updateLayerForFooter(m_layerForFooter != nullptr);
2269 bool RenderLayerCompositor::has3DContent() const
2271 return layerHas3DContent(rootRenderLayer());
2274 bool RenderLayerCompositor::needsToBeComposited(const RenderLayer& layer, RequiresCompositingData& queryData) const
2276 if (!canBeComposited(layer))
2279 return requiresCompositingLayer(layer, queryData) || layer.mustCompositeForIndirectReasons() || (usesCompositing() && layer.isRenderViewLayer());
2282 // Note: this specifies whether the RL needs a compositing layer for intrinsic reasons.
2283 // Use needsToBeComposited() to determine if a RL actually needs a compositing layer.
2284 // FIXME: is clipsCompositingDescendants() an intrinsic reason?
2285 bool RenderLayerCompositor::requiresCompositingLayer(const RenderLayer& layer, RequiresCompositingData& queryData) const
2287 auto& renderer = rendererForCompositingTests(layer);
2289 // The root layer always has a compositing layer, but it may not have backing.
2290 return requiresCompositingForTransform(renderer)
2291 || requiresCompositingForAnimation(renderer)
2292 || clipsCompositingDescendants(*renderer.layer())
2293 || requiresCompositingForPosition(renderer, *renderer.layer(), queryData)
2294 || requiresCompositingForCanvas(renderer)
2295 || requiresCompositingForFilters(renderer)
2296 || requiresCompositingForWillChange(renderer)
2297 || requiresCompositingForBackfaceVisibility(renderer)
2298 || requiresCompositingForVideo(renderer)
2299 || requiresCompositingForFrame(renderer, queryData)
2300 || requiresCompositingForPlugin(renderer, queryData)
2301 || requiresCompositingForEditableImage(renderer)
2302 || requiresCompositingForOverflowScrolling(*renderer.layer(), queryData);
2305 bool RenderLayerCompositor::canBeComposited(const RenderLayer& layer) const
2307 if (m_hasAcceleratedCompositing && layer.isSelfPaintingLayer()) {
2308 if (!layer.isInsideFragmentedFlow())
2311 // CSS Regions flow threads do not need to be composited as we use composited RenderFragmentContainers
2312 // to render the background of the RenderFragmentedFlow.
2313 if (layer.isRenderFragmentedFlow())
2321 #if ENABLE(FULLSCREEN_API)
2322 enum class FullScreenDescendant { Yes, No, NotApplicable };
2323 static FullScreenDescendant isDescendantOfFullScreenLayer(const RenderLayer& layer)
2325 auto& document = layer.renderer().document();
2327 if (!document.fullscreenManager().isFullscreen() || !document.fullscreenManager().fullscreenRenderer())
2328 return FullScreenDescendant::NotApplicable;
2330 auto* fullScreenLayer = document.fullscreenManager().fullscreenRenderer()->layer();
2331 if (!fullScreenLayer) {
2332 ASSERT_NOT_REACHED();
2333 return FullScreenDescendant::NotApplicable;
2336 return layer.isDescendantOf(*fullScreenLayer) ? FullScreenDescendant::Yes : FullScreenDescendant::No;
2340 bool RenderLayerCompositor::requiresOwnBackingStore(const RenderLayer& layer, const RenderLayer* compositingAncestorLayer, const LayoutRect& layerCompositedBoundsInAncestor, const LayoutRect& ancestorCompositedBounds) const
2342 auto& renderer = layer.renderer();
2344 if (compositingAncestorLayer
2345 && !(compositingAncestorLayer->backing()->graphicsLayer()->drawsContent()
2346 || compositingAncestorLayer->backing()->paintsIntoWindow()
2347 || compositingAncestorLayer->backing()->paintsIntoCompositedAncestor()))
2350 RequiresCompositingData queryData;
2351 if (layer.isRenderViewLayer()
2352 || layer.transform() // note: excludes perspective and transformStyle3D.
2353 || requiresCompositingForAnimation(renderer)
2354 || requiresCompositingForPosition(renderer, layer, queryData)
2355 || requiresCompositingForCanvas(renderer)
2356 || requiresCompositingForFilters(renderer)
2357 || requiresCompositingForWillChange(renderer)
2358 || requiresCompositingForBackfaceVisibility(renderer)
2359 || requiresCompositingForVideo(renderer)
2360 || requiresCompositingForFrame(renderer, queryData)
2361 || requiresCompositingForPlugin(renderer, queryData)
2362 || requiresCompositingForEditableImage(renderer)
2363 || requiresCompositingForOverflowScrolling(layer, queryData)
2364 || needsContentsCompositingLayer(layer)
2365 || renderer.isTransparent()
2366 || renderer.hasMask()
2367 || renderer.hasReflection()
2368 || renderer.hasFilter()
2369 || renderer.hasBackdropFilter())
2372 if (layer.mustCompositeForIndirectReasons()) {
2373 IndirectCompositingReason reason = layer.indirectCompositingReason();
2374 return reason == IndirectCompositingReason::Overlap
2375 || reason == IndirectCompositingReason::OverflowScrollPositioning
2376 || reason == IndirectCompositingReason::Stacking
2377 || reason == IndirectCompositingReason::BackgroundLayer
2378 || reason == IndirectCompositingReason::GraphicalEffect
2379 || reason == IndirectCompositingReason::Preserve3D; // preserve-3d has to create backing store to ensure that 3d-transformed elements intersect.
2382 if (!ancestorCompositedBounds.contains(layerCompositedBoundsInAncestor))
2385 if (layer.isComposited() && layer.backing()->hasBackingSharingLayers())
2391 OptionSet<CompositingReason> RenderLayerCompositor::reasonsForCompositing(const RenderLayer& layer) const
2393 OptionSet<CompositingReason> reasons;
2395 if (!layer.isComposited())
2398 RequiresCompositingData queryData;
2400 auto& renderer = rendererForCompositingTests(layer);
2402 if (requiresCompositingForTransform(renderer))
2403 reasons.add(CompositingReason::Transform3D);
2405 if (requiresCompositingForVideo(renderer))
2406 reasons.add(CompositingReason::Video);
2407 else if (requiresCompositingForCanvas(renderer))
2408 reasons.add(CompositingReason::Canvas);
2409 else if (requiresCompositingForPlugin(renderer, queryData))
2410 reasons.add(CompositingReason::Plugin);
2411 else if (requiresCompositingForFrame(renderer, queryData))
2412 reasons.add(CompositingReason::IFrame);
2413 else if (requiresCompositingForEditableImage(renderer))
2414 reasons.add(CompositingReason::EmbeddedView);
2416 if ((canRender3DTransforms() && renderer.style().backfaceVisibility() == BackfaceVisibility::Hidden))
2417 reasons.add(CompositingReason::BackfaceVisibilityHidden);
2419 if (clipsCompositingDescendants(*renderer.layer()))
2420 reasons.add(CompositingReason::ClipsCompositingDescendants);
2422 if (requiresCompositingForAnimation(renderer))
2423 reasons.add(CompositingReason::Animation);
2425 if (requiresCompositingForFilters(renderer))
2426 reasons.add(CompositingReason::Filters);
2428 if (requiresCompositingForWillChange(renderer))
2429 reasons.add(CompositingReason::WillChange);
2431 if (requiresCompositingForPosition(renderer, *renderer.layer(), queryData))
2432 reasons.add(renderer.isFixedPositioned() ? CompositingReason::PositionFixed : CompositingReason::PositionSticky);
2434 if (requiresCompositingForOverflowScrolling(*renderer.layer(), queryData))
2435 reasons.add(CompositingReason::OverflowScrolling);
2437 switch (renderer.layer()->indirectCompositingReason()) {
2438 case IndirectCompositingReason::None:
2440 case IndirectCompositingReason::Stacking:
2441 reasons.add(CompositingReason::Stacking);
2443 case IndirectCompositingReason::OverflowScrollPositioning:
2444 reasons.add(CompositingReason::OverflowScrollPositioning);
2446 case IndirectCompositingReason::Overlap:
2447 reasons.add(CompositingReason::Overlap);
2449 case IndirectCompositingReason::BackgroundLayer:
2450 reasons.add(CompositingReason::NegativeZIndexChildren);
2452 case IndirectCompositingReason::GraphicalEffect:
2453 if (renderer.hasTransform())
2454 reasons.add(CompositingReason::TransformWithCompositedDescendants);
2456 if (renderer.isTransparent())
2457 reasons.add(CompositingReason::OpacityWithCompositedDescendants);
2459 if (renderer.hasMask())
2460 reasons.add(CompositingReason::MaskWithCompositedDescendants);
2462 if (renderer.hasReflection())
2463 reasons.add(CompositingReason::ReflectionWithCompositedDescendants);
2465 if (renderer.hasFilter() || renderer.hasBackdropFilter())
2466 reasons.add(CompositingReason::FilterWithCompositedDescendants);
2468 #if ENABLE(CSS_COMPOSITING)
2469 if (layer.isolatesCompositedBlending())
2470 reasons.add(CompositingReason::IsolatesCompositedBlendingDescendants);
2472 if (layer.hasBlendMode())
2473 reasons.add(CompositingReason::BlendingWithCompositedDescendants);
2476 case IndirectCompositingReason::Perspective:
2477 reasons.add(CompositingReason::Perspective);
2479 case IndirectCompositingReason::Preserve3D:
2480 reasons.add(CompositingReason::Preserve3D);
2484 if (usesCompositing() && renderer.layer()->isRenderViewLayer())
2485 reasons.add(CompositingReason::Root);
2491 const char* RenderLayerCompositor::logReasonsForCompositing(const RenderLayer& layer)
2493 OptionSet<CompositingReason> reasons = reasonsForCompositing(layer);
2495 if (reasons & CompositingReason::Transform3D)
2496 return "3D transform";
2498 if (reasons & CompositingReason::Video)
2501 if (reasons & CompositingReason::Canvas)
2504 if (reasons & CompositingReason::Plugin)
2507 if (reasons & CompositingReason::IFrame)
2510 if (reasons & CompositingReason::BackfaceVisibilityHidden)
2511 return "backface-visibility: hidden";
2513 if (reasons & CompositingReason::ClipsCompositingDescendants)
2514 return "clips compositing descendants";
2516 if (reasons & CompositingReason::Animation)
2519 if (reasons & CompositingReason::Filters)
2522 if (reasons & CompositingReason::PositionFixed)
2523 return "position: fixed";
2525 if (reasons & CompositingReason::PositionSticky)
2526 return "position: sticky";
2528 if (reasons & CompositingReason::OverflowScrolling)
2529 return "async overflow scrolling";
2531 if (reasons & CompositingReason::Stacking)
2534 if (reasons & CompositingReason::Overlap)
2537 if (reasons & CompositingReason::NegativeZIndexChildren)
2538 return "negative z-index children";
2540 if (reasons & CompositingReason::TransformWithCompositedDescendants)
2541 return "transform with composited descendants";
2543 if (reasons & CompositingReason::OpacityWithCompositedDescendants)
2544 return "opacity with composited descendants";
2546 if (reasons & CompositingReason::MaskWithCompositedDescendants)
2547 return "mask with composited descendants";
2549 if (reasons & CompositingReason::ReflectionWithCompositedDescendants)
2550 return "reflection with composited descendants";
2552 if (reasons & CompositingReason::FilterWithCompositedDescendants)
2553 return "filter with composited descendants";
2555 #if ENABLE(CSS_COMPOSITING)
2556 if (reasons & CompositingReason::BlendingWithCompositedDescendants)
2557 return "blending with composited descendants";
2559 if (reasons & CompositingReason::IsolatesCompositedBlendingDescendants)
2560 return "isolates composited blending descendants";
2563 if (reasons & CompositingReason::Perspective)
2564 return "perspective";
2566 if (reasons & CompositingReason::Preserve3D)
2567 return "preserve-3d";
2569 if (reasons & CompositingReason::Root)
2576 // Return true if the given layer has some ancestor in the RenderLayer hierarchy that clips,
2577 // up to the enclosing compositing ancestor. This is required because compositing layers are parented
2578 // according to the z-order hierarchy, yet clipping goes down the renderer hierarchy.
2579 // Thus, a RenderLayer can be clipped by a RenderLayer that is an ancestor in the renderer hierarchy,
2580 // but a sibling in the z-order hierarchy.
2581 // FIXME: can we do this without a tree walk?
2582 bool RenderLayerCompositor::clippedByAncestor(RenderLayer& layer) const
2584 ASSERT(layer.isComposited());
2585 if (!layer.parent())
2588 // On first pass in WK1, the root may not have become composited yet.
2589 auto* compositingAncestor = layer.ancestorCompositingLayer();
2590 if (!compositingAncestor)
2593 // If the compositingAncestor clips, that will be taken care of by clipsCompositingDescendants(),
2594 // so we only care about clipping between its first child that is our ancestor (the computeClipRoot),
2595 // and layer. The exception is when the compositingAncestor isolates composited blending children,
2596 // in this case it is not allowed to clipsCompositingDescendants() and each of its children
2597 // will be clippedByAncestor()s, including the compositingAncestor.
2598 auto* computeClipRoot = compositingAncestor;
2599 if (!compositingAncestor->isolatesCompositedBlending()) {
2600 computeClipRoot = nullptr;
2601 auto* parent = &layer;
2603 auto* next = parent->parent();
2604 if (next == compositingAncestor) {
2605 computeClipRoot = parent;
2611 if (!computeClipRoot || computeClipRoot == &layer)
2615 return !layer.backgroundClipRect(RenderLayer::ClipRectsContext(computeClipRoot, TemporaryClipRects)).isInfinite(); // FIXME: Incorrect for CSS regions.
2618 // Return true if the given layer is a stacking context and has compositing child
2619 // layers that it needs to clip. In this case we insert a clipping GraphicsLayer
2620 // into the hierarchy between this layer and its children in the z-order hierarchy.
2621 bool RenderLayerCompositor::clipsCompositingDescendants(const RenderLayer& layer)
2623 return layer.hasCompositingDescendant() && layer.renderer().hasClipOrOverflowClip() && !layer.isolatesCompositedBlending();
2626 bool RenderLayerCompositor::requiresCompositingForAnimation(RenderLayerModelObject& renderer) const
2628 if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
2631 if (auto* element = renderer.element()) {
2632 if (auto* timeline = element->document().existingTimeline()) {
2633 if (timeline->runningAnimationsForElementAreAllAccelerated(*element))
2638 if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled())
2641 auto& animController = renderer.animation();
2642 return (animController.isRunningAnimationOnRenderer(renderer, CSSPropertyOpacity)
2643 && (usesCompositing() || (m_compositingTriggers & ChromeClient::AnimatedOpacityTrigger)))
2644 || animController.isRunningAnimationOnRenderer(renderer, CSSPropertyFilter)
2645 #if ENABLE(FILTERS_LEVEL_2)
2646 || animController.isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitBackdropFilter)
2648 || animController.isRunningAnimationOnRenderer(renderer, CSSPropertyTransform);
2651 bool RenderLayerCompositor::requiresCompositingForTransform(RenderLayerModelObject& renderer) const
2653 if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
2656 // Note that we ask the renderer if it has a transform, because the style may have transforms,
2657 // but the renderer may be an inline that doesn't suppport them.
2658 if (!renderer.hasTransform())
2661 switch (m_compositingPolicy) {
2662 case CompositingPolicy::Normal:
2663 return renderer.style().transform().has3DOperation();
2664 case CompositingPolicy::Conservative:
2665 // Continue to allow pages to avoid the very slow software filter path.
2666 if (renderer.style().transform().has3DOperation() && renderer.hasFilter())
2668 return renderer.style().transform().isRepresentableIn2D() ? false : true;
2673 bool RenderLayerCompositor::requiresCompositingForBackfaceVisibility(RenderLayerModelObject& renderer) const
2675 if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
2678 if (renderer.style().backfaceVisibility() != BackfaceVisibility::Hidden)
2681 if (renderer.layer()->has3DTransformedAncestor())
2684 // FIXME: workaround for webkit.org/b/132801
2685 auto* stackingContext = renderer.layer()->stackingContext();
2686 if (stackingContext && stackingContext->renderer().style().transformStyle3D() == TransformStyle3D::Preserve3D)
2692 bool RenderLayerCompositor::requiresCompositingForVideo(RenderLayerModelObject& renderer) const
2694 if (!(m_compositingTriggers & ChromeClient::VideoTrigger))
2698 if (!is<RenderVideo>(renderer))
2701 auto& video = downcast<RenderVideo>(renderer);
2702 if ((video.requiresImmediateCompositing() || video.shouldDisplayVideo()) && canAccelerateVideoRendering(video))
2705 UNUSED_PARAM(renderer);
2710 bool RenderLayerCompositor::requiresCompositingForCanvas(RenderLayerModelObject& renderer) const
2712 if (!(m_compositingTriggers & ChromeClient::CanvasTrigger))
2715 if (!renderer.isCanvas())
2718 bool isCanvasLargeEnoughToForceCompositing = true;
2719 #if !USE(COMPOSITING_FOR_SMALL_CANVASES)
2720 auto* canvas = downcast<HTMLCanvasElement>(renderer.element());
2721 auto canvasArea = canvas->size().area<RecordOverflow>();
2722 isCanvasLargeEnoughToForceCompositing = !canvasArea.hasOverflowed() && canvasArea.unsafeGet() >= canvasAreaThresholdRequiringCompositing;
2725 CanvasCompositingStrategy compositingStrategy = canvasCompositingStrategy(renderer);
2726 if (compositingStrategy == CanvasAsLayerContents)
2729 if (m_compositingPolicy == CompositingPolicy::Normal)
2730 return compositingStrategy == CanvasPaintedToLayer && isCanvasLargeEnoughToForceCompositing;
2735 bool RenderLayerCompositor::requiresCompositingForFilters(RenderLayerModelObject& renderer) const
2737 #if ENABLE(FILTERS_LEVEL_2)
2738 if (renderer.hasBackdropFilter())
2742 if (!(m_compositingTriggers & ChromeClient::FilterTrigger))
2745 return renderer.hasFilter();
2748 bool RenderLayerCompositor::requiresCompositingForWillChange(RenderLayerModelObject& renderer) const
2750 if (!renderer.style().willChange() || !renderer.style().willChange()->canTriggerCompositing())
2753 #if ENABLE(FULLSCREEN_API)
2754 // FIXME: does this require layout?
2755 if (renderer.layer() && isDescendantOfFullScreenLayer(*renderer.layer()) == FullScreenDescendant::No)
2759 if (m_compositingPolicy == CompositingPolicy::Conservative)
2762 if (is<RenderBox>(renderer))
2765 return renderer.style().willChange()->canTriggerCompositingOnInline();
2768 bool RenderLayerCompositor::requiresCompositingForPlugin(RenderLayerModelObject& renderer, RequiresCompositingData& queryData) const
2770 if (!(m_compositingTriggers & ChromeClient::PluginTrigger))
2773 bool isCompositedPlugin = is<RenderEmbeddedObject>(renderer) && downcast<RenderEmbeddedObject>(renderer).allowsAcceleratedCompositing();
2774 if (!isCompositedPlugin)
2777 auto& pluginRenderer = downcast<RenderWidget>(renderer);
2778 if (pluginRenderer.style().visibility() != Visibility::Visible)
2781 // If we can't reliably know the size of the plugin yet, don't change compositing state.
2782 if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2783 queryData.reevaluateAfterLayout = true;
2784 return pluginRenderer.isComposited();
2787 // Don't go into compositing mode if height or width are zero, or size is 1x1.
2788 IntRect contentBox = snappedIntRect(pluginRenderer.contentBoxRect());
2789 return (contentBox.height() * contentBox.width() > 1);
2792 bool RenderLayerCompositor::requiresCompositingForEditableImage(RenderLayerModelObject& renderer) const
2794 if (!renderer.isRenderImage())
2797 auto& image = downcast<RenderImage>(renderer);
2798 if (!image.isEditableImage())
2804 bool RenderLayerCompositor::requiresCompositingForFrame(RenderLayerModelObject& renderer, RequiresCompositingData& queryData) const
2806 if (!is<RenderWidget>(renderer))
2809 auto& frameRenderer = downcast<RenderWidget>(renderer);
2810 if (frameRenderer.style().visibility() != Visibility::Visible)
2813 if (!frameRenderer.requiresAcceleratedCompositing())
2816 if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2817 queryData.reevaluateAfterLayout = true;
2818 return frameRenderer.isComposited();
2821 // Don't go into compositing mode if height or width are zero.
2822 return !snappedIntRect(frameRenderer.contentBoxRect()).isEmpty();
2825 bool RenderLayerCompositor::requiresCompositingForScrollableFrame(RequiresCompositingData& queryData) const
2827 if (isMainFrameCompositor())
2830 #if PLATFORM(MAC) || PLATFORM(IOS_FAMILY)
2831 if (!m_renderView.settings().asyncFrameScrollingEnabled())
2835 if (!(m_compositingTriggers & ChromeClient::ScrollableNonMainFrameTrigger))
2838 if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2839 queryData.reevaluateAfterLayout = true;
2840 return m_renderView.isComposited();
2843 return m_renderView.frameView().isScrollable();
2846 bool RenderLayerCompositor::requiresCompositingForPosition(RenderLayerModelObject& renderer, const RenderLayer& layer, RequiresCompositingData& queryData) const
2848 // position:fixed elements that create their own stacking context (e.g. have an explicit z-index,
2849 // opacity, transform) can get their own composited layer. A stacking context is required otherwise
2850 // z-index and clipping will be broken.
2851 if (!renderer.isPositioned())
2854 #if ENABLE(FULLSCREEN_API)
2855 if (isDescendantOfFullScreenLayer(layer) == FullScreenDescendant::No)
2859 auto position = renderer.style().position();
2860 bool isFixed = renderer.isFixedPositioned();
2861 if (isFixed && !layer.isStackingContext())
2864 bool isSticky = renderer.isInFlowPositioned() && position == PositionType::Sticky;
2865 if (!isFixed && !isSticky)
2868 // FIXME: acceleratedCompositingForFixedPositionEnabled should probably be renamed acceleratedCompositingForViewportConstrainedPositionEnabled().
2869 if (!m_renderView.settings().acceleratedCompositingForFixedPositionEnabled())
2873 return isAsyncScrollableStickyLayer(layer);
2875 if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2876 queryData.reevaluateAfterLayout = true;
2877 return layer.isComposited();
2880 auto container = renderer.container();
2883 // Don't promote fixed position elements that are descendants of a non-view container, e.g. transformed elements.
2884 // They will stay fixed wrt the container rather than the enclosing frame.j
2885 if (container != &m_renderView) {
2886 queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForNonViewContainer;
2890 bool paintsContent = layer.isVisuallyNonEmpty() || layer.hasVisibleDescendant();
2891 if (!paintsContent) {
2892 queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForNoVisibleContent;
2896 bool intersectsViewport = fixedLayerIntersectsViewport(layer);
2897 if (!intersectsViewport) {
2898 queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForBoundsOutOfView;
2899 LOG_WITH_STREAM(Compositing, stream << "Layer " << &layer << " is outside the viewport");
2906 bool RenderLayerCompositor::requiresCompositingForOverflowScrolling(const RenderLayer& layer, RequiresCompositingData& queryData) const
2908 if (!layer.canUseCompositedScrolling())
2911 if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2912 queryData.reevaluateAfterLayout = true;
2913 return layer.isComposited();
2916 return layer.hasCompositedScrollableOverflow();
2919 // FIXME: why doesn't this handle the clipping cases?
2920 bool RenderLayerCompositor::requiresCompositingForIndirectReason(const RenderLayer& layer, const RenderLayer* compositingAncestor, bool hasCompositedDescendants, bool has3DTransformedDescendants, bool paintsIntoProvidedBacking, IndirectCompositingReason& reason) const
2922 // When a layer has composited descendants, some effects, like 2d transforms, filters, masks etc must be implemented
2923 // via compositing so that they also apply to those composited descendants.
2924 auto& renderer = layer.renderer();
2925 if (hasCompositedDescendants && (layer.isolatesCompositedBlending() || layer.transform() || renderer.createsGroup() || renderer.hasReflection())) {
2926 reason = IndirectCompositingReason::GraphicalEffect;
2930 // A layer with preserve-3d or perspective only needs to be composited if there are descendant layers that
2931 // will be affected by the preserve-3d or perspective.
2932 if (has3DTransformedDescendants) {
2933 if (renderer.style().transformStyle3D() == TransformStyle3D::Preserve3D) {
2934 reason = IndirectCompositingReason::Preserve3D;
2938 if (renderer.style().hasPerspective()) {
2939 reason = IndirectCompositingReason::Perspective;
2944 if (!paintsIntoProvidedBacking && renderer.isAbsolutelyPositioned() && compositingAncestor && layer.hasCompositedScrollingAncestor()) {
2945 if (layerContainingBlockCrossesCoordinatedScrollingBoundary(layer, *compositingAncestor)) {
2946 reason = IndirectCompositingReason::OverflowScrollPositioning;
2951 reason = IndirectCompositingReason::None;
2955 bool RenderLayerCompositor::styleChangeMayAffectIndirectCompositingReasons(const RenderStyle& oldStyle, const RenderStyle& newStyle)
2957 if (RenderElement::createsGroupForStyle(newStyle) != RenderElement::createsGroupForStyle(oldStyle))
2959 if (newStyle.isolation() != oldStyle.isolation())
2961 if (newStyle.hasTransform() != oldStyle.hasTransform())
2963 if (newStyle.boxReflect() != oldStyle.boxReflect())
2965 if (newStyle.transformStyle3D() != oldStyle.transformStyle3D())
2967 if (newStyle.hasPerspective() != oldStyle.hasPerspective())
2973 bool RenderLayerCompositor::isAsyncScrollableStickyLayer(const RenderLayer& layer, const RenderLayer** enclosingAcceleratedOverflowLayer) const
2975 ASSERT(layer.renderer().isStickilyPositioned());
2977 auto* enclosingOverflowLayer = layer.enclosingOverflowClipLayer(ExcludeSelf);
2979 if (enclosingOverflowLayer && enclosingOverflowLayer->hasCompositedScrollableOverflow()) {
2980 if (enclosingAcceleratedOverflowLayer)
2981 *enclosingAcceleratedOverflowLayer = enclosingOverflowLayer;
2985 // If the layer is inside normal overflow, it's not async-scrollable.
2986 if (enclosingOverflowLayer)
2989 // No overflow ancestor, so see if the frame supports async scrolling.
2990 if (hasCoordinatedScrolling())
2993 #if PLATFORM(IOS_FAMILY)
2994 // iOS WK1 has fixed/sticky support in the main frame via WebFixedPositionContent.
2995 return isMainFrameCompositor();
3001 bool RenderLayerCompositor::isViewportConstrainedFixedOrStickyLayer(const RenderLayer& layer) const
3003 if (layer.renderer().isStickilyPositioned())
3004 return isAsyncScrollableStickyLayer(layer);
3006 if (!layer.renderer().isFixedPositioned())
3009 // FIXME: Handle fixed inside of a transform, which should not behave as fixed.
3010 for (auto* stackingContext = layer.stackingContext(); stackingContext; stackingContext = stackingContext->stackingContext()) {
3011 if (stackingContext->isComposited() && stackingContext->renderer().isFixedPositioned())
3018 bool RenderLayerCompositor::fixedLayerIntersectsViewport(const RenderLayer& layer) const
3020 ASSERT(layer.renderer().isFixedPositioned());
3022 // Fixed position elements that are invisible in the current view don't get their own layer.
3023 // FIXME: We shouldn't have to check useFixedLayout() here; one of the viewport rects needs to give the correct answer.
3024 LayoutRect viewBounds;
3025 if (m_renderView.frameView().useFixedLayout())
3026 viewBounds = m_renderView.unscaledDocumentRect();
3028 viewBounds = m_renderView.frameView().rectForFixedPositionLayout();
3030 LayoutRect layerBounds = layer.calculateLayerBounds(&layer, LayoutSize(), { RenderLayer::UseLocalClipRectIfPossible, RenderLayer::IncludeFilterOutsets, RenderLayer::UseFragmentBoxesExcludingCompositing,
3031 RenderLayer::ExcludeHiddenDescendants, RenderLayer::DontConstrainForMask, RenderLayer::IncludeCompositedDescendants });
3032 // Map to m_renderView to ignore page scale.
3033 FloatRect absoluteBounds = layer.renderer().localToContainerQuad(FloatRect(layerBounds), &m_renderView).boundingBox();
3034 return viewBounds.intersects(enclosingIntRect(absoluteBounds));
3037 bool RenderLayerCompositor::useCoordinatedScrollingForLayer(const RenderLayer& layer) const
3039 if (layer.isRenderViewLayer() && hasCoordinatedScrolling())
3042 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3043 return scrollingCoordinator->coordinatesScrollingForOverflowLayer(layer);
3048 static RenderLayer* enclosingCompositedScrollingLayer(const RenderLayer& layer, const RenderLayer& intermediateLayer, bool& sawIntermediateLayer)
3050 const auto* currLayer = layer.parent();
3052 if (currLayer == &intermediateLayer)
3053 sawIntermediateLayer = true;
3055 if (currLayer->hasCompositedScrollableOverflow())
3056 return const_cast<RenderLayer*>(currLayer);
3058 currLayer = currLayer->parent();
3064 static bool isScrolledByOverflowScrollLayer(const RenderLayer& layer, const RenderLayer& overflowScrollLayer)
3066 bool scrolledByOverflowScroll = false;
3067 traverseAncestorLayers(layer, [&](const RenderLayer& ancestorLayer, bool inContainingBlockChain, bool) {
3068 if (&ancestorLayer == &overflowScrollLayer) {
3069 scrolledByOverflowScroll = inContainingBlockChain;
3070 return AncestorTraversal::Stop;
3072 return AncestorTraversal::Continue;
3074 return scrolledByOverflowScroll;
3077 static bool isNonScrolledLayerInsideScrolledCompositedAncestor(const RenderLayer& layer, const RenderLayer& compositedAncestor, const RenderLayer& scrollingAncestor)
3079 bool ancestorMovedByScroller = &compositedAncestor == &scrollingAncestor || isScrolledByOverflowScrollLayer(compositedAncestor, scrollingAncestor);
3080 bool layerMovedByScroller = isScrolledByOverflowScrollLayer(layer, scrollingAncestor);
3082 return ancestorMovedByScroller && !layerMovedByScroller;
3085 bool RenderLayerCompositor::layerContainingBlockCrossesCoordinatedScrollingBoundary(const RenderLayer& layer, const RenderLayer& compositedAncestor)
3087 bool compositedAncestorIsInsideScroller = false;
3088 auto* scrollingAncestor = enclosingCompositedScrollingLayer(layer, compositedAncestor, compositedAncestorIsInsideScroller);
3089 if (!scrollingAncestor) {
3090 ASSERT_NOT_REACHED(); // layer.hasCompositedScrollingAncestor() should guarantee we have one.
3094 if (!compositedAncestorIsInsideScroller)
3097 return isNonScrolledLayerInsideScrolledCompositedAncestor(layer, compositedAncestor, *scrollingAncestor);
3100 static void collectStationaryLayerRelatedOverflowNodes(const RenderLayer& layer, const RenderLayer&, Vector<ScrollingNodeID>& scrollingNodes)
3102 ASSERT(layer.isComposited());
3104 auto appendOverflowLayerNodeID = [&scrollingNodes] (const RenderLayer& overflowLayer) {
3105 ASSERT(overflowLayer.isComposited());
3106 auto scrollingNodeID = overflowLayer.backing()->scrollingNodeIDForRole(ScrollCoordinationRole::Scrolling);
3107 if (scrollingNodeID)
3108 scrollingNodes.append(scrollingNodeID);
3110 LOG(Scrolling, "Layer %p doesn't have scrolling node ID yet", &overflowLayer);
3113 // Collect all the composited scrollers which affect the position of this layer relative to its compositing ancestor (which might be inside the scroller or the scroller itself).
3114 bool seenPaintOrderAncestor = false;
3115 traverseAncestorLayers(layer, [&](const RenderLayer& ancestorLayer, bool isContainingBlockChain, bool isPaintOrderAncestor) {
3116 seenPaintOrderAncestor |= isPaintOrderAncestor;
3117 if (isContainingBlockChain && isPaintOrderAncestor)
3118 return AncestorTraversal::Stop;
3120 if (seenPaintOrderAncestor && !isContainingBlockChain && ancestorLayer.hasCompositedScrollableOverflow())
3121 appendOverflowLayerNodeID(ancestorLayer);
3123 return AncestorTraversal::Continue;
3127 ScrollPositioningBehavior RenderLayerCompositor::computeCoordinatedPositioningForLayer(const RenderLayer& layer) const
3129 if (layer.isRenderViewLayer())
3130 return ScrollPositioningBehavior::None;
3132 if (layer.renderer().isFixedPositioned())
3133 return ScrollPositioningBehavior::None;
3135 if (!layer.hasCompositedScrollingAncestor())
3136 return ScrollPositioningBehavior::None;
3138 auto* scrollingCoordinator = this->scrollingCoordinator();
3139 if (!scrollingCoordinator)
3140 return ScrollPositioningBehavior::None;
3142 auto* compositedAncestor = layer.ancestorCompositingLayer();
3143 if (!compositedAncestor) {
3144 ASSERT_NOT_REACHED();
3145 return ScrollPositioningBehavior::None;
3148 bool compositedAncestorIsScrolling = false;
3149 auto* scrollingAncestor = enclosingCompositedScrollingLayer(layer, *compositedAncestor, compositedAncestorIsScrolling);
3150 if (!scrollingAncestor) {
3151 ASSERT_NOT_REACHED(); // layer.hasCompositedScrollingAncestor() should guarantee we have one.
3152 return ScrollPositioningBehavior::None;
3155 // There are two cases we have to deal with here:
3156 // 1. There's a composited overflow:scroll in the parent chain between the renderer and its containing block, and the layer's
3157 // composited (z-order) ancestor is inside the scroller or is the scroller. In this case, we have to compensate for scroll position
3158 // changes to make the positioned layer stay in the same place. This only applies to position:absolute or descendants of position:absolute.
3159 if (compositedAncestorIsScrolling && isNonScrolledLayerInsideScrolledCompositedAncestor(layer, *compositedAncestor, *scrollingAncestor))
3160 return ScrollPositioningBehavior::Stationary;
3162 // 2. The layer's containing block is the overflow or inside the overflow:scroll, but its z-order ancestor is
3163 // outside the overflow:scroll. In that case, we have to move the layer via the scrolling tree to make
3164 // it move along with the overflow scrolling.
3165 if (!compositedAncestorIsScrolling && isScrolledByOverflowScrollLayer(layer, *scrollingAncestor))
3166 return ScrollPositioningBehavior::Moves;
3168 return ScrollPositioningBehavior::None;
3171 static Vector<ScrollingNodeID> collectRelatedCoordinatedScrollingNodes(const RenderLayer& layer, ScrollPositioningBehavior positioningBehavior)
3173 Vector<ScrollingNodeID> overflowNodeData;
3175 switch (positioningBehavior) {
3176 case ScrollPositioningBehavior::Moves: {
3177 // Collect all the composited scrollers between this layer and its composited ancestor.
3178 auto* compositedAncestor = layer.ancestorCompositingLayer();
3179 for (const auto* currLayer = layer.parent(); currLayer != compositedAncestor; currLayer = currLayer->parent()) {
3180 if (currLayer->hasCompositedScrollableOverflow()) {
3181 auto scrollingNodeID = currLayer->isComposited() ? currLayer->backing()->scrollingNodeIDForRole(ScrollCoordinationRole::Scrolling) : 0;
3182 if (scrollingNodeID)
3183 overflowNodeData.append(scrollingNodeID);
3185 LOG(Scrolling, "Layer %p isn't composited or doesn't have scrolling node ID yet", &layer);
3190 case ScrollPositioningBehavior::Stationary: {
3191 auto* compositedAncestor = layer.ancestorCompositingLayer();
3192 if (!compositedAncestor)
3193 return overflowNodeData;
3194 collectStationaryLayerRelatedOverflowNodes(layer, *compositedAncestor, overflowNodeData);
3197 case ScrollPositioningBehavior::None:
3198 ASSERT_NOT_REACHED();
3202 return overflowNodeData;
3205 bool RenderLayerCompositor::isLayerForIFrameWithScrollCoordinatedContents(const RenderLayer& layer) const
3207 if (!is<RenderWidget>(layer.renderer()))
3210 auto* contentDocument = downcast<RenderWidget>(layer.renderer()).frameOwnerElement().contentDocument();
3211 if (!contentDocument)
3214 auto* view = contentDocument->renderView();
3218 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3219 return scrollingCoordinator->coordinatesScrollingForFrameView(view->frameView());
3224 bool RenderLayerCompositor::isRunningTransformAnimation(RenderLayerModelObject& renderer) const
3226 if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
3229 if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled()) {
3230 if (auto* element = renderer.element()) {
3231 if (auto* timeline = element->document().existingTimeline())
3232 return timeline->isRunningAnimationOnRenderer(renderer, CSSPropertyTransform);
3236 return renderer.animation().isRunningAnimationOnRenderer(renderer, CSSPropertyTransform);
3239 // If an element has negative z-index children, those children render in front of the
3240 // layer background, so we need an extra 'contents' layer for the foreground of the layer object.
3241 bool RenderLayerCompositor::needsContentsCompositingLayer(const RenderLayer& layer) const
3243 return layer.hasNegativeZOrderLayers();
3246 bool RenderLayerCompositor::requiresScrollLayer(RootLayerAttachment attachment) const
3248 auto& frameView = m_renderView.frameView();
3250 // This applies when the application UI handles scrolling, in which case RenderLayerCompositor doesn't need to manage it.
3251 if (frameView.delegatesScrolling() && isMainFrameCompositor())
3254 // We need to handle our own scrolling if we're:
3255 return !m_renderView.frameView().platformWidget() // viewless (i.e. non-Mac, or Mac in WebKit2)
3256 || attachment == RootLayerAttachedViaEnclosingFrame; // a composited frame on Mac
3259 void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
3265 const IntRect& scrollbarRect = scrollbar->frameRect();
3266 context.translate(-scrollbarRect.location());
3267 IntRect transformedClip = clip;
3268 transformedClip.moveBy(scrollbarRect.location());
3269 scrollbar->paint(context, transformedClip);
3273 void RenderLayerCompositor::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, GraphicsLayerPaintingPhase, const FloatRect& clip, GraphicsLayerPaintBehavior)
3276 LocalDefaultSystemAppearance localAppearance(m_renderView.useDarkAppearance());
3279 IntRect pixelSnappedRectForIntegralPositionedItems = snappedIntRect(LayoutRect(clip));
3280 if (graphicsLayer == layerForHorizontalScrollbar())
3281 paintScrollbar(m_renderView.frameView().horizontalScrollbar(), context, pixelSnappedRectForIntegralPositionedItems);
3282 else if (graphicsLayer == layerForVerticalScrollbar())
3283 paintScrollbar(m_renderView.frameView().verticalScrollbar(), context, pixelSnappedRectForIntegralPositionedItems);
3284 else if (graphicsLayer == layerForScrollCorner()) {
3285 const IntRect& scrollCorner = m_renderView.frameView().scrollCornerRect();
3287 context.translate(-scrollCorner.location());
3288 IntRect transformedClip = pixelSnappedRectForIntegralPositionedItems;
3289 transformedClip.moveBy(scrollCorner.location());
3290 m_renderView.frameView().paintScrollCorner(context, transformedClip);
3295 bool RenderLayerCompositor::supportsFixedRootBackgroundCompositing() const
3297 auto* renderViewBacking = m_renderView.layer()->backing();
3298 return renderViewBacking && renderViewBacking->isFrameLayerWithTiledBacking();
3301 bool RenderLayerCompositor::needsFixedRootBackgroundLayer(const RenderLayer& layer) const
3303 if (!layer.isRenderViewLayer())
3306 if (m_renderView.settings().fixedBackgroundsPaintRelativeToDocument())
3309 return supportsFixedRootBackgroundCompositing() && m_renderView.rootBackgroundIsEntirelyFixed();
3312 GraphicsLayer* RenderLayerCompositor::fixedRootBackgroundLayer() const
3314 // Get the fixed root background from the RenderView layer's backing.
3315 auto* viewLayer = m_renderView.layer();
3319 if (viewLayer->isComposited() && viewLayer->backing()->backgroundLayerPaintsFixedRootBackground())
3320 return viewLayer->backing()->backgroundLayer();
3325 void RenderLayerCompositor::resetTrackedRepaintRects()
3327 if (auto* rootLayer = rootGraphicsLayer()) {
3328 GraphicsLayer::traverse(*rootLayer, [](GraphicsLayer& layer) {
3329 layer.resetTrackedRepaints();
3334 float RenderLayerCompositor::deviceScaleFactor() const
3336 return m_renderView.document().deviceScaleFactor();
3339 float RenderLayerCompositor::pageScaleFactor() const
3341 return page().pageScaleFactor();
3344 float RenderLayerCompositor::zoomedOutPageScaleFactor() const
3346 return page().zoomedOutPageScaleFactor();
3349 float RenderLayerCompositor::contentsScaleMultiplierForNewTiles(const GraphicsLayer*) const
3351 #if PLATFORM(IOS_FAMILY)
3352 LegacyTileCache* tileCache = nullptr;
3353 if (auto* frameView = page().mainFrame().view())
3354 tileCache = frameView->legacyTileCache();
3359 return tileCache->tileControllerShouldUseLowScaleTiles() ? 0.125 : 1;
3365 bool RenderLayerCompositor::documentUsesTiledBacking() const
3367 auto* layer = m_renderView.layer();
3371 auto* backing = layer->backing();
3375 return backing->isFrameLayerWithTiledBacking();
3378 bool RenderLayerCompositor::isMainFrameCompositor() const
3380 return m_renderView.frameView().frame().isMainFrame();
3383 bool RenderLayerCompositor::shouldCompositeOverflowControls() const
3385 auto& frameView = m_renderView.frameView();
3387 if (!frameView.managesScrollbars())
3390 if (documentUsesTiledBacking())
3393 if (m_overflowControlsHostLayer && isMainFrameCompositor())
3396 #if !USE(COORDINATED_GRAPHICS)
3397 if (!frameView.hasOverlayScrollbars())
3404 bool RenderLayerCompositor::requiresHorizontalScrollbarLayer() const
3406 return shouldCompositeOverflowControls() && m_renderView.frameView().horizontalScrollbar();
3409 bool RenderLayerCompositor::requiresVerticalScrollbarLayer() const
3411 return shouldCompositeOverflowControls() && m_renderView.frameView().verticalScrollbar();
3414 bool RenderLayerCompositor::requiresScrollCornerLayer() const
3416 return shouldCompositeOverflowControls() && m_renderView.frameView().isScrollCornerVisible();
3419 #if ENABLE(RUBBER_BANDING)
3420 bool RenderLayerCompositor::requiresOverhangAreasLayer() const
3422 if (!isMainFrameCompositor())
3425 // We do want a layer if we're using tiled drawing and can scroll.
3426 if (documentUsesTiledBacking() && m_renderView.frameView().hasOpaqueBackground() && !m_renderView.frameView().prohibitsScrolling())
3432 bool RenderLayerCompositor::requiresContentShadowLayer() const
3434 if (!isMainFrameCompositor())
3438 if (viewHasTransparentBackground())
3441 // If the background is going to extend, then it doesn't make sense to have a shadow layer.
3442 if (m_renderView.settings().backgroundShouldExtendBeyondPage())
3445 // On Mac, we want a content shadow layer if we're using tiled drawing and can scroll.
3446 if (documentUsesTiledBacking() && !m_renderView.frameView().prohibitsScrolling())
3453 GraphicsLayer* RenderLayerCompositor::updateLayerForTopOverhangArea(bool wantsLayer)
3455 if (!isMainFrameCompositor())
3459 GraphicsLayer::unparentAndClear(m_layerForTopOverhangArea);
3463 if (!m_layerForTopOverhangArea) {
3464 m_layerForTopOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), *this);
3465 m_layerForTopOverhangArea->setName("top overhang");
3466 m_scrolledContentsLayer->addChildBelow(*m_layerForTopOverhangArea, m_rootContentsLayer.get());
3469 return m_layerForTopOverhangArea.get();
3472 GraphicsLayer* RenderLayerCompositor::updateLayerForBottomOverhangArea(bool wantsLayer)
3474 if (!isMainFrameCompositor())
3478 GraphicsLayer::unparentAndClear(m_layerForBottomOverhangArea);
3482 if (!m_layerForBottomOverhangArea) {
3483 m_layerForBottomOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), *this);
3484 m_layerForBottomOverhangArea->setName("bottom overhang");
3485 m_scrolledContentsLayer->addChildBelow(*m_layerForBottomOverhangArea, m_rootContentsLayer.get());
3488 m_layerForBottomOverhangArea->setPosition(FloatPoint(0, m_rootContentsLayer->size().height() + m_renderView.frameView().headerHeight()
3489 + m_renderView.frameView().footerHeight() + m_renderView.frameView().topContentInset()));
3490 return m_layerForBottomOverhangArea.get();
3493 GraphicsLayer* RenderLayerCompositor::updateLayerForHeader(bool wantsLayer)
3495 if (!isMainFrameCompositor())
3499 if (m_layerForHeader) {
3500 GraphicsLayer::unparentAndClear(m_layerForHeader);
3502 // The ScrollingTree knows about the header layer, and the position of the root layer is affected
3503 // by the header layer, so if we remove the header, we need to tell the scrolling tree.
3504 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3505 scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
3510 if (!m_layerForHeader) {
3511 m_layerForHeader = GraphicsLayer::create(graphicsLayerFactory(), *this);
3512 m_layerForHeader->setName("header");
3513 m_scrolledContentsLayer->addChildAbove(*m_layerForHeader, m_rootContentsLayer.get());
3514 m_renderView.frameView().addPaintPendingMilestones(DidFirstFlushForHeaderLayer);
3517 m_layerForHeader->setPosition(FloatPoint(0,
3518 FrameView::yPositionForHeaderLayer(m_renderView.frameView().scrollPosition(), m_renderView.frameView().topContentInset())));
3519 m_layerForHeader->setAnchorPoint(FloatPoint3D());
3520 m_layerForHeader->setSize(FloatSize(m_renderView.frameView().visibleWidth(), m_renderView.frameView().headerHeight()));
3522 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3523 scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
3525 page().chrome().client().didAddHeaderLayer(*m_layerForHeader);
3527 return m_layerForHeader.get();
3530 GraphicsLayer* RenderLayerCompositor::updateLayerForFooter(bool wantsLayer)
3532 if (!isMainFrameCompositor())
3536 if (m_layerForFooter) {
3537 GraphicsLayer::unparentAndClear(m_layerForFooter);
3539 // The ScrollingTree knows about the footer layer, and the total scrollable size is affected
3540 // by the footer layer, so if we remove the footer, we need to tell the scrolling tree.
3541 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3542 scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
3547 if (!m_layerForFooter) {
3548 m_layerForFooter = GraphicsLayer::create(graphicsLayerFactory(), *this);
3549 m_layerForFooter->setName("footer");
3550 m_scrolledContentsLayer->addChildAbove(*m_layerForFooter, m_rootContentsLayer.get());
3553 float totalContentHeight = m_rootContentsLayer->size().height() + m_renderView.frameView().headerHeight() + m_renderView.frameView().footerHeight();
3554 m_layerForFooter->setPosition(FloatPoint(0, FrameView::yPositionForFooterLayer(m_renderView.frameView().scrollPosition(),
3555 m_renderView.frameView().topContentInset(), totalContentHeight, m_renderView.frameView().footerHeight())));
3556 m_layerForFooter->setAnchorPoint(FloatPoint3D());
3557 m_layerForFooter->setSize(FloatSize(m_renderView.frameView().visibleWidth(), m_renderView.frameView().footerHeight()));
3559 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3560 scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
3562 page().chrome().client().didAddFooterLayer(*m_layerForFooter);
3564 return m_layerForFooter.get();
3569 bool RenderLayerCompositor::viewHasTransparentBackground(Color* backgroundColor) const
3571 if (m_renderView.frameView().isTransparent()) {
3572 if (backgroundColor)
3573 *backgroundColor = Color(); // Return an invalid color.
3577 Color documentBackgroundColor = m_renderView.frameView().documentBackgroundColor();
3578 if (!documentBackgroundColor.isValid())
3579 documentBackgroundColor = m_renderView.frameView().baseBackgroundColor();
3581 ASSERT(documentBackgroundColor.isValid());
3583 if (backgroundColor)
3584 *backgroundColor = documentBackgroundColor;
3586 return !documentBackgroundColor.isOpaque();
3589 // We can't rely on getting layerStyleChanged() for a style change that affects the root background, because the style change may
3590 // be on the body which has no RenderLayer.
3591 void RenderLayerCompositor::rootOrBodyStyleChanged(RenderElement& renderer, const RenderStyle* oldStyle)
3593 if (!usesCompositing())
3596 Color oldBackgroundColor;
3598 oldBackgroundColor = oldStyle->visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor);
3600 if (oldBackgroundColor != renderer.style().visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor))
3601 rootBackgroundColorOrTransparencyChanged();
3603 bool hadFixedBackground = oldStyle && oldStyle->hasEntirelyFixedBackground();
3604 if (hadFixedBackground != renderer.style().hasEntirelyFixedBackground())
3605 rootLayerConfigurationChanged();
3608 void RenderLayerCompositor::rootBackgroundColorOrTransparencyChanged()
3610 if (!usesCompositing())
3613 Color backgroundColor;
3614 bool isTransparent = viewHasTransparentBackground(&backgroundColor);
3616 Color extendedBackgroundColor = m_renderView.settings().backgroundShouldExtendBeyondPage() ? backgroundColor : Color();
3618 bool transparencyChanged = m_viewBackgroundIsTransparent != isTransparent;
3619 bool backgroundColorChanged = m_viewBackgroundColor != backgroundColor;
3620 bool extendedBackgroundColorChanged = m_rootExtendedBackgroundColor != extendedBackgroundColor;
3622 if (!transparencyChanged && !backgroundColorChanged && !extendedBackgroundColorChanged)
3625 LOG(Compositing, "RenderLayerCompositor %p rootBackgroundColorOrTransparencyChanged. isTransparent=%d", this, isTransparent);
3627 m_viewBackgroundIsTransparent = isTransparent;
3628 m_viewBackgroundColor = backgroundColor;
3629 m_rootExtendedBackgroundColor = extendedBackgroundColor;
3631 if (extendedBackgroundColorChanged) {
3632 page().chrome().client().pageExtendedBackgroundColorDidChange(m_rootExtendedBackgroundColor);
3634 #if ENABLE(RUBBER_BANDING)
3635 if (m_layerForOverhangAreas) {
3636 m_layerForOverhangAreas->setBackgroundColor(m_rootExtendedBackgroundColor);
3638 if (!m_rootExtendedBackgroundColor.isValid())
3639 m_layerForOverhangAreas->setCustomAppearance(GraphicsLayer::CustomAppearance::ScrollingOverhang);
3644 rootLayerConfigurationChanged();
3647 void RenderLayerCompositor::updateOverflowControlsLayers()
3649 #if ENABLE(RUBBER_BANDING)
3650 if (requiresOverhangAreasLayer()) {
3651 if (!m_layerForOverhangAreas) {
3652 m_layerForOverhangAreas = GraphicsLayer::create(graphicsLayerFactory(), *this);
3653 m_layerForOverhangAreas->setName("overhang areas");
3654 m_layerForOverhangAreas->setDrawsContent(false);
3656 float topContentInset = m_renderView.frameView().topContentInset();
3657 IntSize overhangAreaSize = m_renderView.frameView().frameRect().size();
3658 overhangAreaSize.setHeight(overhangAreaSize.height() - topContentInset);
3659 m_layerForOverhangAreas->setSize(overhangAreaSize);
3660 m_layerForOverhangAreas->setPosition(FloatPoint(0, topContentInset));
3661 m_layerForOverhangAreas->setAnchorPoint(FloatPoint3D());
3663 if (m_renderView.settings().backgroundShouldExtendBeyondPage())
3664 m_layerForOverhangAreas->setBackgroundColor(m_renderView.frameView().documentBackgroundColor());
3666 m_layerForOverhangAreas->setCustomAppearance(GraphicsLayer::CustomAppearance::ScrollingOverhang);
3668 // We want the overhang areas layer to be positioned below the frame contents,
3669 // so insert it below the clip layer.
3670 m_overflowControlsHostLayer->addChildBelow(*m_layerForOverhangAreas, layerForClipping());
3673 GraphicsLayer::unparentAndClear(m_layerForOverhangAreas);
3675 if (requiresContentShadowLayer()) {
3676 if (!m_contentShadowLayer) {
3677 m_contentShadowLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3678 m_contentShadowLayer->setName("content shadow");
3679 m_contentShadowLayer->setSize(m_rootContentsLayer->size());
3680 m_contentShadowLayer->setPosition(m_rootContentsLayer->position());
3681 m_contentShadowLayer->setAnchorPoint(FloatPoint3D());
3682 m_contentShadowLayer->setCustomAppearance(GraphicsLayer::CustomAppearance::ScrollingShadow);
3684 m_scrolledContentsLayer->addChildBelow(*m_contentShadowLayer, m_rootContentsLayer.get());
3687 GraphicsLayer::unparentAndClear(m_contentShadowLayer);
3690 if (requiresHorizontalScrollbarLayer()) {
3691 if (!m_layerForHorizontalScrollbar) {
3692 m_layerForHorizontalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), *this);
3693 m_layerForHorizontalScrollbar->setCanDetachBackingStore(false);
3694 m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
3695 m_layerForHorizontalScrollbar->setName("horizontal scrollbar container");
3696 #if PLATFORM(COCOA) && USE(CA)
3697 m_layerForHorizontalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
3699 m_overflowControlsHostLayer->addChild(*m_layerForHorizontalScrollbar);
3701 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3702 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), HorizontalScrollbar);
3704 } else if (m_layerForHorizontalScrollbar) {
3705 GraphicsLayer::unparentAndClear(m_layerForHorizontalScrollbar);
3707 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3708 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), HorizontalScrollbar);
3711 if (requiresVerticalScrollbarLayer()) {
3712 if (!m_layerForVerticalScrollbar) {
3713 m_layerForVerticalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), *this);
3714 m_layerForVerticalScrollbar->setCanDetachBackingStore(false);
3715 m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
3716 m_layerForVerticalScrollbar->setName("vertical scrollbar container");
3717 #if PLATFORM(COCOA) && USE(CA)
3718 m_layerForVerticalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
3720 m_overflowControlsHostLayer->addChild(*m_layerForVerticalScrollbar);
3722 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3723 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), VerticalScrollbar);
3725 } else if (m_layerForVerticalScrollbar) {
3726 GraphicsLayer::unparentAndClear(m_layerForVerticalScrollbar);
3728 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3729 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), VerticalScrollbar);
3732 if (requiresScrollCornerLayer()) {
3733 if (!m_layerForScrollCorner) {
3734 m_layerForScrollCorner = GraphicsLayer::create(graphicsLayerFactory(), *this);
3735 m_layerForScrollCorner->setCanDetachBackingStore(false);
3736 m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
3737 m_layerForScrollCorner->setName("scroll corner");
3738 #if PLATFORM(COCOA) && USE(CA)
3739 m_layerForScrollCorner->setAcceleratesDrawing(acceleratedDrawingEnabled());
3741 m_overflowControlsHostLayer->addChild(*m_layerForScrollCorner);
3744 GraphicsLayer::unparentAndClear(m_layerForScrollCorner);
3746 m_renderView.frameView().positionScrollbarLayers();
3749 void RenderLayerCompositor::ensureRootLayer()
3751 RootLayerAttachment expectedAttachment = isMainFrameCompositor() ? RootLayerAttachedViaChromeClient : RootLayerAttachedViaEnclosingFrame;
3752 if (expectedAttachment == m_rootLayerAttachment)
3755 if (!m_rootContentsLayer) {
3756 m_rootContentsLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3757 m_rootContentsLayer->setName("content root");
3758 IntRect overflowRect = snappedIntRect(m_renderView.layoutOverflowRect());
3759 m_rootContentsLayer->setSize(FloatSize(overflowRect.maxX(), overflowRect.maxY()));
3760 m_rootContentsLayer->setPosition(FloatPoint());
3762 #if PLATFORM(IOS_FAMILY)
3763 // Page scale is applied above this on iOS, so we'll just say that our root layer applies it.
3764 auto& frame = m_renderView.frameView().frame();
3765 if (frame.isMainFrame())
3766 m_rootContentsLayer->setAppliesPageScale();
3769 // Need to clip to prevent transformed content showing outside this frame
3770 updateRootContentLayerClipping();
3773 if (requiresScrollLayer(expectedAttachment)) {
3774 if (!m_overflowControlsHostLayer) {
3775 ASSERT(!m_scrolledContentsLayer);
3776 ASSERT(!m_clipLayer);
3778 // Create a layer to host the clipping layer and the overflow controls layers.
3779 m_overflowControlsHostLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3780 m_overflowControlsHostLayer->setName("overflow controls host");
3782 m_scrolledContentsLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3783 m_scrolledContentsLayer->setName("scrolled contents");
3784 m_scrolledContentsLayer->setAnchorPoint({ });
3786 #if PLATFORM(IOS_FAMILY)
3787 if (m_renderView.settings().asyncFrameScrollingEnabled()) {
3788 m_scrollContainerLayer = GraphicsLayer::create(graphicsLayerFactory(), *this, GraphicsLayer::Type::ScrollContainer);
3790 m_scrollContainerLayer->setName("scroll container");
3791 m_scrollContainerLayer->setMasksToBounds(true);
3792 m_scrollContainerLayer->setAnchorPoint({ });
3794 m_scrollContainerLayer->addChild(*m_scrolledContentsLayer);
3795 m_overflowControlsHostLayer->addChild(*m_scrollContainerLayer);
3798 if (!m_scrollContainerLayer) {
3799 m_clipLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3800 m_clipLayer->setName("frame clipping");
3801 m_clipLayer->setMasksToBounds(true);
3802 m_clipLayer->setAnchorPoint({ });
3804 m_clipLayer->addChild(*m_scrolledContentsLayer);
3805 m_overflowControlsHostLayer->addChild(*m_clipLayer);
3808 m_scrolledContentsLayer->addChild(*m_rootContentsLayer);
3810 updateScrollLayerClipping();
3811 updateOverflowControlsLayers();
3813 if (hasCoordinatedScrolling())
3814 scheduleLayerFlush(true);
3816 updateScrollLayerPosition();
3819 if (m_overflowControlsHostLayer) {
3820 GraphicsLayer::unparentAndClear(m_overflowControlsHostLayer);
3821 GraphicsLayer::unparentAndClear(m_clipLayer);
3822 GraphicsLayer::unparentAndClear(m_scrollContainerLayer);
3823 GraphicsLayer::unparentAndClear(m_scrolledContentsLayer);
3827 // Check to see if we have to change the attachment
3828 if (m_rootLayerAttachment != RootLayerUnattached)