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 "GraphicsLayer.h"
39 #include "HTMLCanvasElement.h"
40 #include "HTMLIFrameElement.h"
41 #include "HTMLNames.h"
42 #include "HitTestResult.h"
43 #include "InspectorInstrumentation.h"
47 #include "PageOverlayController.h"
48 #include "RenderEmbeddedObject.h"
49 #include "RenderFragmentedFlow.h"
50 #include "RenderFullScreen.h"
51 #include "RenderGeometryMap.h"
52 #include "RenderIFrame.h"
53 #include "RenderLayerBacking.h"
54 #include "RenderReplica.h"
55 #include "RenderVideo.h"
56 #include "RenderView.h"
57 #include "RuntimeEnabledFeatures.h"
58 #include "ScrollingConstraints.h"
59 #include "ScrollingCoordinator.h"
61 #include "TiledBacking.h"
62 #include "TransformState.h"
63 #include <wtf/HexNumber.h>
64 #include <wtf/MemoryPressureHandler.h>
65 #include <wtf/SetForScope.h>
66 #include <wtf/text/CString.h>
67 #include <wtf/text/StringBuilder.h>
68 #include <wtf/text/StringConcatenateNumbers.h>
69 #include <wtf/text/TextStream.h>
71 #if PLATFORM(IOS_FAMILY)
72 #include "LegacyTileCache.h"
73 #include "RenderScrollbar.h"
77 #include "LocalDefaultSystemAppearance.h"
80 #if ENABLE(TREE_DEBUGGING)
81 #include "RenderTreeAsText.h"
84 #if ENABLE(3D_TRANSFORMS)
85 // This symbol is used to determine from a script whether 3D rendering is enabled (via 'nm').
86 WEBCORE_EXPORT bool WebCoreHas3DRendering = true;
89 #if !PLATFORM(MAC) && !PLATFORM(IOS_FAMILY)
90 #define USE_COMPOSITING_FOR_SMALL_CANVASES 1
95 #if !USE(COMPOSITING_FOR_SMALL_CANVASES)
96 static const int canvasAreaThresholdRequiringCompositing = 50 * 100;
98 // During page loading delay layer flushes up to this many seconds to allow them coalesce, reducing workload.
99 #if PLATFORM(IOS_FAMILY)
100 static const Seconds throttledLayerFlushInitialDelay { 500_ms };
101 static const Seconds throttledLayerFlushDelay { 1.5_s };
103 static const Seconds throttledLayerFlushInitialDelay { 500_ms };
104 static const Seconds throttledLayerFlushDelay { 500_ms };
107 using namespace HTMLNames;
109 struct ScrollingTreeState {
110 Optional<ScrollingNodeID> parentNodeID;
111 size_t nextChildIndex { 0 };
114 class OverlapMapContainer {
116 void add(const LayoutRect& bounds)
118 m_layerRects.append(bounds);
119 m_boundingBox.unite(bounds);
122 bool overlapsLayers(const LayoutRect& bounds) const
124 // Checking with the bounding box will quickly reject cases when
125 // layers are created for lists of items going in one direction and
126 // never overlap with each other.
127 if (!bounds.intersects(m_boundingBox))
129 for (const auto& layerRect : m_layerRects) {
130 if (layerRect.intersects(bounds))
136 void unite(const OverlapMapContainer& otherContainer)
138 m_layerRects.appendVector(otherContainer.m_layerRects);
139 m_boundingBox.unite(otherContainer.m_boundingBox);
142 Vector<LayoutRect> m_layerRects;
143 LayoutRect m_boundingBox;
146 class RenderLayerCompositor::OverlapMap {
147 WTF_MAKE_NONCOPYABLE(OverlapMap);
150 : m_geometryMap(UseTransforms)
152 // Begin assuming the root layer will be composited so that there is
153 // something on the stack. The root layer should also never get an
154 // popCompositingContainer call.
155 pushCompositingContainer();
158 void add(const LayoutRect& bounds)
160 // Layers do not contribute to overlap immediately--instead, they will
161 // contribute to overlap as soon as their composited ancestor has been
162 // recursively processed and popped off the stack.
163 ASSERT(m_overlapStack.size() >= 2);
164 m_overlapStack[m_overlapStack.size() - 2].add(bounds);
168 bool overlapsLayers(const LayoutRect& bounds) const
170 return m_overlapStack.last().overlapsLayers(bounds);
178 void pushCompositingContainer()
180 m_overlapStack.append(OverlapMapContainer());
183 void popCompositingContainer()
185 m_overlapStack[m_overlapStack.size() - 2].unite(m_overlapStack.last());
186 m_overlapStack.removeLast();
189 const RenderGeometryMap& geometryMap() const { return m_geometryMap; }
190 RenderGeometryMap& geometryMap() { return m_geometryMap; }
194 Vector<LayoutRect> rects;
195 LayoutRect boundingRect;
197 void append(const LayoutRect& rect)
200 boundingRect.unite(rect);
203 void append(const RectList& rectList)
205 rects.appendVector(rectList.rects);
206 boundingRect.unite(rectList.boundingRect);
209 bool intersects(const LayoutRect& rect) const
211 if (!rects.size() || !boundingRect.intersects(rect))
214 for (const auto& currentRect : rects) {
215 if (currentRect.intersects(rect))
222 Vector<OverlapMapContainer> m_overlapStack;
223 RenderGeometryMap m_geometryMap;
224 bool m_isEmpty { true };
227 struct RenderLayerCompositor::CompositingState {
228 CompositingState(RenderLayer* compAncestor, bool testOverlap = true)
229 : compositingAncestor(compAncestor)
230 , testingOverlap(testOverlap)
234 CompositingState(const CompositingState& other)
235 : compositingAncestor(other.compositingAncestor)
236 , subtreeIsCompositing(other.subtreeIsCompositing)
237 , testingOverlap(other.testingOverlap)
238 , fullPaintOrderTraversalRequired(other.fullPaintOrderTraversalRequired)
239 , descendantsRequireCompositingUpdate(other.descendantsRequireCompositingUpdate)
240 , ancestorHasTransformAnimation(other.ancestorHasTransformAnimation)
241 #if ENABLE(CSS_COMPOSITING)
242 , hasNotIsolatedCompositedBlendingDescendants(other.hasNotIsolatedCompositedBlendingDescendants)
244 #if ENABLE(TREE_DEBUGGING)
245 , depth(other.depth + 1)
250 RenderLayer* compositingAncestor;
251 bool subtreeIsCompositing { false };
252 bool testingOverlap { true };
253 bool fullPaintOrderTraversalRequired { false };
254 bool descendantsRequireCompositingUpdate { false };
255 bool ancestorHasTransformAnimation { false };
256 #if ENABLE(CSS_COMPOSITING)
257 bool hasNotIsolatedCompositedBlendingDescendants { false };
259 #if ENABLE(TREE_DEBUGGING)
264 struct RenderLayerCompositor::OverlapExtent {
266 bool extentComputed { false };
267 bool hasTransformAnimation { false };
268 bool animationCausesExtentUncertainty { false };
270 bool knownToBeHaveExtentUncertainty() const { return extentComputed && animationCausesExtentUncertainty; }
274 static inline bool compositingLogEnabled()
276 return LogCompositing.state == WTFLogChannelOn;
280 RenderLayerCompositor::RenderLayerCompositor(RenderView& renderView)
281 : m_renderView(renderView)
282 , m_updateCompositingLayersTimer(*this, &RenderLayerCompositor::updateCompositingLayersTimerFired)
283 , m_layerFlushTimer(*this, &RenderLayerCompositor::layerFlushTimerFired)
285 #if PLATFORM(IOS_FAMILY)
286 if (m_renderView.frameView().platformWidget())
287 m_legacyScrollingLayerCoordinator = std::make_unique<LegacyWebKitScrollingLayerCoordinator>(page().chrome().client(), isMainFrameCompositor());
291 RenderLayerCompositor::~RenderLayerCompositor()
293 // Take care that the owned GraphicsLayers are deleted first as their destructors may call back here.
294 m_clipLayer = nullptr;
295 m_scrolledContentsLayer = nullptr;
296 ASSERT(m_rootLayerAttachment == RootLayerUnattached);
299 void RenderLayerCompositor::enableCompositingMode(bool enable /* = true */)
301 if (enable != m_compositing) {
302 m_compositing = enable;
306 notifyIFramesOfCompositingChange();
311 m_renderView.layer()->setNeedsPostLayoutCompositingUpdate();
315 void RenderLayerCompositor::cacheAcceleratedCompositingFlags()
317 auto& settings = m_renderView.settings();
318 bool hasAcceleratedCompositing = settings.acceleratedCompositingEnabled();
320 // We allow the chrome to override the settings, in case the page is rendered
321 // on a chrome that doesn't allow accelerated compositing.
322 if (hasAcceleratedCompositing) {
323 m_compositingTriggers = page().chrome().client().allowedCompositingTriggers();
324 hasAcceleratedCompositing = m_compositingTriggers;
327 bool showDebugBorders = settings.showDebugBorders();
328 bool showRepaintCounter = settings.showRepaintCounter();
329 bool acceleratedDrawingEnabled = settings.acceleratedDrawingEnabled();
330 bool displayListDrawingEnabled = settings.displayListDrawingEnabled();
332 // forceCompositingMode for subframes can only be computed after layout.
333 bool forceCompositingMode = m_forceCompositingMode;
334 if (isMainFrameCompositor())
335 forceCompositingMode = m_renderView.settings().forceCompositingMode() && hasAcceleratedCompositing;
337 if (hasAcceleratedCompositing != m_hasAcceleratedCompositing || showDebugBorders != m_showDebugBorders || showRepaintCounter != m_showRepaintCounter || forceCompositingMode != m_forceCompositingMode) {
338 if (auto* rootLayer = m_renderView.layer()) {
339 rootLayer->setNeedsCompositingConfigurationUpdate();
340 rootLayer->setDescendantsNeedUpdateBackingAndHierarchyTraversal();
344 bool debugBordersChanged = m_showDebugBorders != showDebugBorders;
345 m_hasAcceleratedCompositing = hasAcceleratedCompositing;
346 m_forceCompositingMode = forceCompositingMode;
347 m_showDebugBorders = showDebugBorders;
348 m_showRepaintCounter = showRepaintCounter;
349 m_acceleratedDrawingEnabled = acceleratedDrawingEnabled;
350 m_displayListDrawingEnabled = displayListDrawingEnabled;
352 if (debugBordersChanged) {
353 if (m_layerForHorizontalScrollbar)
354 m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
356 if (m_layerForVerticalScrollbar)
357 m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
359 if (m_layerForScrollCorner)
360 m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
363 if (updateCompositingPolicy())
364 rootRenderLayer().setDescendantsNeedCompositingRequirementsTraversal();
367 void RenderLayerCompositor::cacheAcceleratedCompositingFlagsAfterLayout()
369 cacheAcceleratedCompositingFlags();
371 if (isMainFrameCompositor())
374 RequiresCompositingData queryData;
375 bool forceCompositingMode = m_hasAcceleratedCompositing && m_renderView.settings().forceCompositingMode() && requiresCompositingForScrollableFrame(queryData);
376 if (forceCompositingMode != m_forceCompositingMode) {
377 m_forceCompositingMode = forceCompositingMode;
378 rootRenderLayer().setDescendantsNeedCompositingRequirementsTraversal();
382 bool RenderLayerCompositor::updateCompositingPolicy()
384 if (!usesCompositing())
387 auto currentPolicy = m_compositingPolicy;
388 if (page().compositingPolicyOverride()) {
389 m_compositingPolicy = page().compositingPolicyOverride().value();
390 return m_compositingPolicy != currentPolicy;
393 auto memoryPolicy = MemoryPressureHandler::currentMemoryUsagePolicy();
394 m_compositingPolicy = memoryPolicy == WTF::MemoryUsagePolicy::Unrestricted ? CompositingPolicy::Normal : CompositingPolicy::Conservative;
395 return m_compositingPolicy != currentPolicy;
398 bool RenderLayerCompositor::canRender3DTransforms() const
400 return hasAcceleratedCompositing() && (m_compositingTriggers & ChromeClient::ThreeDTransformTrigger);
403 void RenderLayerCompositor::willRecalcStyle()
405 cacheAcceleratedCompositingFlags();
408 bool RenderLayerCompositor::didRecalcStyleWithNoPendingLayout()
410 return updateCompositingLayers(CompositingUpdateType::AfterStyleChange);
413 void RenderLayerCompositor::customPositionForVisibleRectComputation(const GraphicsLayer* graphicsLayer, FloatPoint& position) const
415 if (graphicsLayer != m_scrolledContentsLayer.get())
418 FloatPoint scrollPosition = -position;
420 if (m_renderView.frameView().scrollBehaviorForFixedElements() == StickToDocumentBounds)
421 scrollPosition = m_renderView.frameView().constrainScrollPositionForOverhang(roundedIntPoint(scrollPosition));
423 position = -scrollPosition;
426 void RenderLayerCompositor::notifyFlushRequired(const GraphicsLayer* layer)
428 scheduleLayerFlush(layer->canThrottleLayerFlush());
431 void RenderLayerCompositor::scheduleLayerFlushNow()
433 m_hasPendingLayerFlush = false;
434 page().chrome().client().scheduleCompositingLayerFlush();
437 void RenderLayerCompositor::scheduleLayerFlush(bool canThrottle)
439 ASSERT(!m_flushingLayers);
442 startInitialLayerFlushTimerIfNeeded();
444 if (canThrottle && isThrottlingLayerFlushes()) {
445 m_hasPendingLayerFlush = true;
448 scheduleLayerFlushNow();
451 FloatRect RenderLayerCompositor::visibleRectForLayerFlushing() const
453 const FrameView& frameView = m_renderView.frameView();
454 #if PLATFORM(IOS_FAMILY)
455 return frameView.exposedContentRect();
457 // Having a m_scrolledContentsLayer indicates that we're doing scrolling via GraphicsLayers.
458 FloatRect visibleRect = m_scrolledContentsLayer ? FloatRect({ }, frameView.sizeForVisibleContent()) : frameView.visibleContentRect();
460 if (frameView.viewExposedRect())
461 visibleRect.intersect(frameView.viewExposedRect().value());
467 void RenderLayerCompositor::flushPendingLayerChanges(bool isFlushRoot)
469 // FrameView::flushCompositingStateIncludingSubframes() flushes each subframe,
470 // but GraphicsLayer::flushCompositingState() will cross frame boundaries
471 // if the GraphicsLayers are connected (the RootLayerAttachedViaEnclosingFrame case).
472 // As long as we're not the root of the flush, we can bail.
473 if (!isFlushRoot && rootLayerAttachment() == RootLayerAttachedViaEnclosingFrame)
476 if (rootLayerAttachment() == RootLayerUnattached) {
477 #if PLATFORM(IOS_FAMILY)
478 startLayerFlushTimerIfNeeded();
480 m_shouldFlushOnReattach = true;
484 auto& frameView = m_renderView.frameView();
485 AnimationUpdateBlock animationUpdateBlock(&frameView.frame().animation());
487 ASSERT(!m_flushingLayers);
489 SetForScope<bool> flushingLayersScope(m_flushingLayers, true);
491 if (auto* rootLayer = rootGraphicsLayer()) {
492 FloatRect visibleRect = visibleRectForLayerFlushing();
493 LOG_WITH_STREAM(Compositing, stream << "\nRenderLayerCompositor " << this << " flushPendingLayerChanges (is root " << isFlushRoot << ") visible rect " << visibleRect);
494 rootLayer->flushCompositingState(visibleRect);
497 ASSERT(m_flushingLayers);
500 #if PLATFORM(IOS_FAMILY)
501 updateScrollCoordinatedLayersAfterFlushIncludingSubframes();
504 page().chrome().client().didFlushCompositingLayers();
508 startLayerFlushTimerIfNeeded();
511 #if PLATFORM(IOS_FAMILY)
512 void RenderLayerCompositor::updateScrollCoordinatedLayersAfterFlushIncludingSubframes()
514 updateScrollCoordinatedLayersAfterFlush();
516 auto& frame = m_renderView.frameView().frame();
517 for (Frame* subframe = frame.tree().firstChild(); subframe; subframe = subframe->tree().traverseNext(&frame)) {
518 auto* view = subframe->contentRenderer();
522 view->compositor().updateScrollCoordinatedLayersAfterFlush();
526 void RenderLayerCompositor::updateScrollCoordinatedLayersAfterFlush()
528 if (m_legacyScrollingLayerCoordinator) {
529 m_legacyScrollingLayerCoordinator->registerAllViewportConstrainedLayers(*this);
530 m_legacyScrollingLayerCoordinator->registerScrollingLayersNeedingUpdate();
535 void RenderLayerCompositor::didChangePlatformLayerForLayer(RenderLayer& layer, const GraphicsLayer*)
537 #if PLATFORM(IOS_FAMILY)
538 if (m_legacyScrollingLayerCoordinator)
539 m_legacyScrollingLayerCoordinator->didChangePlatformLayerForLayer(layer);
542 auto* scrollingCoordinator = this->scrollingCoordinator();
543 if (!scrollingCoordinator)
546 auto* backing = layer.backing();
547 if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::Scrolling))
548 updateScrollingNodeLayers(nodeID, layer, *scrollingCoordinator);
550 if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::ViewportConstrained))
551 scrollingCoordinator->setNodeLayers(nodeID, { backing->graphicsLayer() });
553 if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::FrameHosting))
554 scrollingCoordinator->setNodeLayers(nodeID, { backing->graphicsLayer() });
557 void RenderLayerCompositor::didPaintBacking(RenderLayerBacking*)
559 auto& frameView = m_renderView.frameView();
560 frameView.setLastPaintTime(MonotonicTime::now());
561 if (frameView.milestonesPendingPaint())
562 frameView.firePaintRelatedMilestonesIfNeeded();
565 void RenderLayerCompositor::didChangeVisibleRect()
567 auto* rootLayer = rootGraphicsLayer();
571 FloatRect visibleRect = visibleRectForLayerFlushing();
572 bool requiresFlush = rootLayer->visibleRectChangeRequiresFlush(visibleRect);
573 LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor::didChangeVisibleRect " << visibleRect << " requiresFlush " << requiresFlush);
575 scheduleLayerFlushNow();
578 void RenderLayerCompositor::notifyFlushBeforeDisplayRefresh(const GraphicsLayer*)
580 if (!m_layerUpdater) {
581 PlatformDisplayID displayID = page().chrome().displayID();
582 m_layerUpdater = std::make_unique<GraphicsLayerUpdater>(*this, displayID);
585 m_layerUpdater->scheduleUpdate();
588 void RenderLayerCompositor::flushLayersSoon(GraphicsLayerUpdater&)
590 scheduleLayerFlush(true);
593 void RenderLayerCompositor::layerTiledBackingUsageChanged(const GraphicsLayer* graphicsLayer, bool usingTiledBacking)
595 if (usingTiledBacking) {
596 ++m_layersWithTiledBackingCount;
597 graphicsLayer->tiledBacking()->setIsInWindow(page().isInWindow());
599 ASSERT(m_layersWithTiledBackingCount > 0);
600 --m_layersWithTiledBackingCount;
604 void RenderLayerCompositor::scheduleCompositingLayerUpdate()
606 if (!m_updateCompositingLayersTimer.isActive())
607 m_updateCompositingLayersTimer.startOneShot(0_s);
610 void RenderLayerCompositor::updateCompositingLayersTimerFired()
612 updateCompositingLayers(CompositingUpdateType::AfterLayout);
615 void RenderLayerCompositor::cancelCompositingLayerUpdate()
617 m_updateCompositingLayersTimer.stop();
620 static Optional<ScrollingNodeID> frameHostingNodeForFrame(Frame& frame)
622 if (!frame.document() || !frame.view())
625 // Find the frame's enclosing layer in our render tree.
626 auto* ownerElement = frame.document()->ownerElement();
630 auto* frameRenderer = ownerElement->renderer();
631 if (!frameRenderer || !is<RenderWidget>(frameRenderer))
634 auto& widgetRenderer = downcast<RenderWidget>(*frameRenderer);
635 if (!widgetRenderer.hasLayer() || !widgetRenderer.layer()->isComposited()) {
636 LOG(Scrolling, "frameHostingNodeForFrame: frame renderer has no layer or is not composited.");
640 if (auto frameHostingNodeID = widgetRenderer.layer()->backing()->scrollingNodeIDForRole(ScrollCoordinationRole::FrameHosting))
641 return frameHostingNodeID;
646 // Returns true on a successful update.
647 bool RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType updateType, RenderLayer* updateRoot)
649 LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor " << this << " updateCompositingLayers " << updateType << " contentLayersCount " << m_contentLayersCount);
651 #if ENABLE(TREE_DEBUGGING)
652 if (compositingLogEnabled())
653 showPaintOrderTree(m_renderView.layer());
656 if (updateType == CompositingUpdateType::AfterStyleChange || updateType == CompositingUpdateType::AfterLayout)
657 cacheAcceleratedCompositingFlagsAfterLayout(); // Some flags (e.g. forceCompositingMode) depend on layout.
659 m_updateCompositingLayersTimer.stop();
661 ASSERT(m_renderView.document().pageCacheState() == Document::NotInPageCache);
663 // Compositing layers will be updated in Document::setVisualUpdatesAllowed(bool) if suppressed here.
664 if (!m_renderView.document().visualUpdatesAllowed())
667 // Avoid updating the layers with old values. Compositing layers will be updated after the layout is finished.
668 // This happens when m_updateCompositingLayersTimer fires before layout is updated.
669 if (m_renderView.needsLayout()) {
670 LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor " << this << " updateCompositingLayers " << updateType << " - m_renderView.needsLayout, bailing ");
674 if (!m_compositing && (m_forceCompositingMode || (isMainFrameCompositor() && page().pageOverlayController().overlayCount())))
675 enableCompositingMode(true);
677 bool isPageScroll = !updateRoot || updateRoot == &rootRenderLayer();
678 updateRoot = &rootRenderLayer();
680 if (updateType == CompositingUpdateType::OnScroll || updateType == CompositingUpdateType::OnCompositedScroll) {
681 // We only get here if we didn't scroll on the scrolling thread, so this update needs to re-position viewport-constrained layers.
682 if (m_renderView.settings().acceleratedCompositingForFixedPositionEnabled() && isPageScroll) {
683 if (auto* viewportConstrainedObjects = m_renderView.frameView().viewportConstrainedObjects()) {
684 for (auto* renderer : *viewportConstrainedObjects) {
685 if (auto* layer = renderer->layer())
686 layer->setNeedsCompositingGeometryUpdate();
691 // Scrolling can affect overlap. FIXME: avoid for page scrolling.
692 updateRoot->setDescendantsNeedCompositingRequirementsTraversal();
695 if (updateType == CompositingUpdateType::AfterLayout) {
696 // Ensure that post-layout updates push new scroll position and viewport rects onto the root node.
697 rootRenderLayer().setNeedsScrollingTreeUpdate();
700 if (!updateRoot->hasDescendantNeedingCompositingRequirementsTraversal() && !m_compositing) {
701 LOG_WITH_STREAM(Compositing, stream << " no compositing work to do");
705 if (!updateRoot->needsAnyCompositingTraversal()) {
706 LOG_WITH_STREAM(Compositing, stream << " updateRoot has no dirty child and doesn't need update");
710 ++m_compositingUpdateCount;
712 AnimationUpdateBlock animationUpdateBlock(&m_renderView.frameView().frame().animation());
714 SetForScope<bool> postLayoutChange(m_inPostLayoutUpdate, true);
717 MonotonicTime startTime;
718 if (compositingLogEnabled()) {
719 ++m_rootLayerUpdateCount;
720 startTime = MonotonicTime::now();
723 if (compositingLogEnabled()) {
724 m_obligateCompositedLayerCount = 0;
725 m_secondaryCompositedLayerCount = 0;
726 m_obligatoryBackingStoreBytes = 0;
727 m_secondaryBackingStoreBytes = 0;
729 auto& frame = m_renderView.frameView().frame();
730 bool isMainFrame = isMainFrameCompositor();
731 LOG_WITH_STREAM(Compositing, stream << "\nUpdate " << m_rootLayerUpdateCount << " of " << (isMainFrame ? "main frame" : frame.tree().uniqueName().string().utf8().data()) << " - compositing policy is " << m_compositingPolicy);
735 // FIXME: optimize root-only update.
736 if (updateRoot->hasDescendantNeedingCompositingRequirementsTraversal() || updateRoot->needsCompositingRequirementsTraversal()) {
737 CompositingState compositingState(updateRoot);
738 OverlapMap overlapMap;
740 bool descendantHas3DTransform = false;
741 computeCompositingRequirements(nullptr, rootRenderLayer(), overlapMap, compositingState, descendantHas3DTransform);
744 LOG(Compositing, "\nRenderLayerCompositor::updateCompositingLayers - mid");
745 #if ENABLE(TREE_DEBUGGING)
746 if (compositingLogEnabled())
747 showPaintOrderTree(m_renderView.layer());
750 if (updateRoot->hasDescendantNeedingUpdateBackingOrHierarchyTraversal() || updateRoot->needsUpdateBackingOrHierarchyTraversal()) {
751 ScrollingTreeState scrollingTreeState = { 0, 0 };
752 if (!m_renderView.frame().isMainFrame())
753 scrollingTreeState.parentNodeID = frameHostingNodeForFrame(m_renderView.frame());
755 Vector<Ref<GraphicsLayer>> childList;
756 updateBackingAndHierarchy(*updateRoot, childList, scrollingTreeState);
758 // Host the document layer in the RenderView's root layer.
759 appendDocumentOverlayLayers(childList);
760 // Even when childList is empty, don't drop out of compositing mode if there are
761 // composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
762 if (childList.isEmpty() && !needsCompositingForContentOrOverlays())
764 else if (m_rootContentsLayer)
765 m_rootContentsLayer->setChildren(WTFMove(childList));
769 if (compositingLogEnabled()) {
770 MonotonicTime endTime = MonotonicTime::now();
771 LOG(Compositing, "Total layers primary secondary obligatory backing (KB) secondary backing(KB) total backing (KB) update time (ms)\n");
773 LOG(Compositing, "%8d %11d %9d %20.2f %22.2f %22.2f %18.2f\n",
774 m_obligateCompositedLayerCount + m_secondaryCompositedLayerCount, m_obligateCompositedLayerCount,
775 m_secondaryCompositedLayerCount, m_obligatoryBackingStoreBytes / 1024, m_secondaryBackingStoreBytes / 1024, (m_obligatoryBackingStoreBytes + m_secondaryBackingStoreBytes) / 1024, (endTime - startTime).milliseconds());
779 // FIXME: Only do if dirty.
780 updateRootLayerPosition();
782 #if ENABLE(TREE_DEBUGGING)
783 if (compositingLogEnabled()) {
784 LOG(Compositing, "RenderLayerCompositor::updateCompositingLayers - post");
785 showPaintOrderTree(m_renderView.layer());
786 LOG(Compositing, "RenderLayerCompositor::updateCompositingLayers - GraphicsLayers post, contentLayersCount %d", m_contentLayersCount);
787 showGraphicsLayerTree(m_rootContentsLayer.get());
791 InspectorInstrumentation::layerTreeDidChange(&page());
796 void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer& layer, OverlapMap& overlapMap, CompositingState& compositingState, bool& descendantHas3DTransform)
798 if (!layer.hasDescendantNeedingCompositingRequirementsTraversal() && !layer.needsCompositingRequirementsTraversal() && !compositingState.fullPaintOrderTraversalRequired && !compositingState.descendantsRequireCompositingUpdate) {
799 traverseUnchangedSubtree(ancestorLayer, layer, overlapMap, compositingState, descendantHas3DTransform);
803 #if ENABLE(TREE_DEBUGGING)
804 LOG(Compositing, "%*p computeCompositingRequirements", 12 + compositingState.depth * 2, &layer);
807 // FIXME: maybe we can avoid updating all remaining layers in paint order.
808 compositingState.fullPaintOrderTraversalRequired |= layer.needsCompositingRequirementsTraversal();
809 compositingState.descendantsRequireCompositingUpdate |= layer.descendantsNeedCompositingRequirementsTraversal();
811 layer.updateDescendantDependentFlags();
812 layer.updateLayerListsIfNeeded();
814 layer.setHasCompositingDescendant(false);
816 // We updated compositing for direct reasons in layerStyleChanged(). Here, check for compositing that can only be evaluated after layout.
817 RequiresCompositingData queryData;
818 bool willBeComposited = layer.isComposited();
819 if (layer.needsPostLayoutCompositingUpdate() || compositingState.fullPaintOrderTraversalRequired || compositingState.descendantsRequireCompositingUpdate) {
820 layer.setIndirectCompositingReason(RenderLayer::IndirectCompositingReason::None);
821 willBeComposited = needsToBeComposited(layer, queryData);
824 compositingState.fullPaintOrderTraversalRequired |= layer.subsequentLayersNeedCompositingRequirementsTraversal();
826 OverlapExtent layerExtent;
827 // Use the fact that we're composited as a hint to check for an animating transform.
828 // FIXME: Maybe needsToBeComposited() should return a bitmask of reasons, to avoid the need to recompute things.
829 if (willBeComposited && !layer.isRenderViewLayer())
830 layerExtent.hasTransformAnimation = isRunningTransformAnimation(layer.renderer());
832 bool respectTransforms = !layerExtent.hasTransformAnimation;
833 overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer, respectTransforms);
835 RenderLayer::IndirectCompositingReason compositingReason = compositingState.subtreeIsCompositing ? RenderLayer::IndirectCompositingReason::Stacking : RenderLayer::IndirectCompositingReason::None;
837 // If we know for sure the layer is going to be composited, don't bother looking it up in the overlap map
838 if (!willBeComposited && !overlapMap.isEmpty() && compositingState.testingOverlap) {
839 computeExtent(overlapMap, layer, layerExtent);
840 // If we're testing for overlap, we only need to composite if we overlap something that is already composited.
841 compositingReason = overlapMap.overlapsLayers(layerExtent.bounds) ? RenderLayer::IndirectCompositingReason::Overlap : RenderLayer::IndirectCompositingReason::None;
845 // Video is special. It's the only RenderLayer type that can both have
846 // RenderLayer children and whose children can't use its backing to render
847 // into. These children (the controls) always need to be promoted into their
848 // own layers to draw on top of the accelerated video.
849 if (compositingState.compositingAncestor && compositingState.compositingAncestor->renderer().isVideo())
850 compositingReason = RenderLayer::IndirectCompositingReason::Overlap;
853 if (compositingReason != RenderLayer::IndirectCompositingReason::None)
854 layer.setIndirectCompositingReason(compositingReason);
856 // Check if the computed indirect reason will force the layer to become composited.
857 if (!willBeComposited && layer.mustCompositeForIndirectReasons() && canBeComposited(layer))
858 willBeComposited = true;
860 // The children of this layer don't need to composite, unless there is
861 // a compositing layer among them, so start by inheriting the compositing
862 // ancestor with subtreeIsCompositing set to false.
863 CompositingState childState(compositingState);
864 childState.subtreeIsCompositing = false;
865 #if ENABLE(CSS_COMPOSITING)
866 childState.hasNotIsolatedCompositedBlendingDescendants = false;
869 if (willBeComposited) {
870 // Tell the parent it has compositing descendants.
871 compositingState.subtreeIsCompositing = true;
872 // This layer now acts as the ancestor for kids.
873 childState.compositingAncestor = &layer;
875 overlapMap.pushCompositingContainer();
876 // This layer is going to be composited, so children can safely ignore the fact that there's an
877 // animation running behind this layer, meaning they can rely on the overlap map testing again.
878 childState.testingOverlap = true;
880 computeExtent(overlapMap, layer, layerExtent);
881 childState.ancestorHasTransformAnimation |= layerExtent.hasTransformAnimation;
882 // Too hard to compute animated bounds if both us and some ancestor is animating transform.
883 layerExtent.animationCausesExtentUncertainty |= layerExtent.hasTransformAnimation && compositingState.ancestorHasTransformAnimation;
887 LayerListMutationDetector mutationChecker(layer);
890 bool anyDescendantHas3DTransform = false;
892 for (auto* childLayer : layer.negativeZOrderLayers()) {
893 computeCompositingRequirements(&layer, *childLayer, overlapMap, childState, anyDescendantHas3DTransform);
895 // If we have to make a layer for this child, make one now so we can have a contents layer
896 // (since we need to ensure that the -ve z-order child renders underneath our contents).
897 if (!willBeComposited && childState.subtreeIsCompositing) {
898 // make layer compositing
899 layer.setIndirectCompositingReason(RenderLayer::IndirectCompositingReason::BackgroundLayer);
900 childState.compositingAncestor = &layer;
901 overlapMap.pushCompositingContainer();
902 // This layer is going to be composited, so children can safely ignore the fact that there's an
903 // animation running behind this layer, meaning they can rely on the overlap map testing again
904 childState.testingOverlap = true;
905 willBeComposited = true;
909 for (auto* childLayer : layer.normalFlowLayers())
910 computeCompositingRequirements(&layer, *childLayer, overlapMap, childState, anyDescendantHas3DTransform);
912 for (auto* childLayer : layer.positiveZOrderLayers())
913 computeCompositingRequirements(&layer, *childLayer, overlapMap, childState, anyDescendantHas3DTransform);
915 // If we just entered compositing mode, the root will have become composited (as long as accelerated compositing is enabled).
916 if (layer.isRenderViewLayer()) {
917 if (usesCompositing() && m_hasAcceleratedCompositing)
918 willBeComposited = true;
921 // All layers (even ones that aren't being composited) need to get added to
922 // the overlap map. Layers that do not composite will draw into their
923 // compositing ancestor's backing, and so are still considered for overlap.
924 // FIXME: When layerExtent has taken animation bounds into account, we also know that the bounds
925 // include descendants, so we don't need to add them all to the overlap map.
926 if (childState.compositingAncestor && !childState.compositingAncestor->isRenderViewLayer())
927 addToOverlapMap(overlapMap, layer, layerExtent);
929 #if ENABLE(CSS_COMPOSITING)
930 layer.setHasNotIsolatedCompositedBlendingDescendants(childState.hasNotIsolatedCompositedBlendingDescendants);
931 ASSERT(!layer.hasNotIsolatedCompositedBlendingDescendants() || layer.hasNotIsolatedBlendingDescendants());
933 // Now check for reasons to become composited that depend on the state of descendant layers.
934 RenderLayer::IndirectCompositingReason indirectCompositingReason;
935 if (!willBeComposited && canBeComposited(layer)
936 && requiresCompositingForIndirectReason(layer.renderer(), childState.subtreeIsCompositing, anyDescendantHas3DTransform, indirectCompositingReason)) {
937 layer.setIndirectCompositingReason(indirectCompositingReason);
938 childState.compositingAncestor = &layer;
939 overlapMap.pushCompositingContainer();
940 addToOverlapMapRecursive(overlapMap, layer);
941 willBeComposited = true;
944 if (layer.reflectionLayer()) {
945 // FIXME: Shouldn't we call computeCompositingRequirements to handle a reflection overlapping with another renderer?
946 layer.reflectionLayer()->setIndirectCompositingReason(willBeComposited ? RenderLayer::IndirectCompositingReason::Stacking : RenderLayer::IndirectCompositingReason::None);
949 // Subsequent layers in the parent stacking context also need to composite.
950 compositingState.subtreeIsCompositing |= childState.subtreeIsCompositing;
951 compositingState.fullPaintOrderTraversalRequired |= childState.fullPaintOrderTraversalRequired;
953 // Set the flag to say that this layer has compositing children.
954 layer.setHasCompositingDescendant(childState.subtreeIsCompositing);
956 // setHasCompositingDescendant() may have changed the answer to needsToBeComposited() when clipping, so test that again.
957 bool isCompositedClippingLayer = canBeComposited(layer) && clipsCompositingDescendants(layer);
959 // Turn overlap testing off for later layers if it's already off, or if we have an animating transform.
960 // Note that if the layer clips its descendants, there's no reason to propagate the child animation to the parent layers. That's because
961 // we know for sure the animation is contained inside the clipping rectangle, which is already added to the overlap map.
962 if ((!childState.testingOverlap && !isCompositedClippingLayer) || layerExtent.knownToBeHaveExtentUncertainty())
963 compositingState.testingOverlap = false;
965 if (isCompositedClippingLayer) {
966 if (!willBeComposited) {
967 childState.compositingAncestor = &layer;
968 overlapMap.pushCompositingContainer();
969 addToOverlapMapRecursive(overlapMap, layer);
970 willBeComposited = true;
974 #if ENABLE(CSS_COMPOSITING)
975 if ((willBeComposited && layer.hasBlendMode())
976 || (layer.hasNotIsolatedCompositedBlendingDescendants() && !layer.isolatesCompositedBlending()))
977 compositingState.hasNotIsolatedCompositedBlendingDescendants = true;
980 if (childState.compositingAncestor == &layer && !layer.isRenderViewLayer())
981 overlapMap.popCompositingContainer();
983 // If we're back at the root, and no other layers need to be composited, and the root layer itself doesn't need
984 // to be composited, then we can drop out of compositing mode altogether. However, don't drop out of compositing mode
985 // if there are composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
986 RequiresCompositingData rootLayerQueryData;
987 if (layer.isRenderViewLayer() && !childState.subtreeIsCompositing && !requiresCompositingLayer(layer, rootLayerQueryData) && !m_forceCompositingMode && !needsCompositingForContentOrOverlays()) {
988 // Don't drop out of compositing on iOS, because we may flash. See <rdar://problem/8348337>.
989 #if !PLATFORM(IOS_FAMILY)
990 enableCompositingMode(false);
991 willBeComposited = false;
995 ASSERT(willBeComposited == needsToBeComposited(layer, queryData));
997 // Create or destroy backing here. However, we can't update geometry because layers above us may become composited
998 // during post-order traversal (e.g. for clipping).
999 if (updateBacking(layer, queryData, CompositingChangeRepaintNow, willBeComposited ? BackingRequired::Yes : BackingRequired::No)) {
1000 layer.setNeedsCompositingLayerConnection();
1001 // Child layers need to get a geometry update to recompute their position.
1002 layer.setChildrenNeedCompositingGeometryUpdate();
1003 // The composited bounds of enclosing layers depends on which descendants are composited, so they need a geometry update.
1004 layer.setNeedsCompositingGeometryUpdateOnAncestors();
1007 if (layer.reflectionLayer() && updateLayerCompositingState(*layer.reflectionLayer(), queryData, CompositingChangeRepaintNow))
1008 layer.setNeedsCompositingLayerConnection();
1010 descendantHas3DTransform |= anyDescendantHas3DTransform || layer.has3DTransform();
1012 // FIXME: clarify needsCompositingPaintOrderChildrenUpdate. If a composited layer gets a new ancestor, it needs geometry computations.
1013 if (layer.needsCompositingPaintOrderChildrenUpdate()) {
1014 layer.setChildrenNeedCompositingGeometryUpdate();
1015 layer.setNeedsCompositingLayerConnection();
1018 #if ENABLE(TREE_DEBUGGING)
1019 LOG(Compositing, "%*p computeCompositingRequirements - willBeComposited %d", 12 + compositingState.depth * 2, &layer, willBeComposited);
1022 layer.clearCompositingRequirementsTraversalState();
1024 overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
1027 // We have to traverse unchanged layers to fill in the overlap map.
1028 void RenderLayerCompositor::traverseUnchangedSubtree(RenderLayer* ancestorLayer, RenderLayer& layer, OverlapMap& overlapMap, CompositingState& compositingState, bool& descendantHas3DTransform)
1030 ASSERT(!compositingState.fullPaintOrderTraversalRequired);
1031 ASSERT(!layer.hasDescendantNeedingCompositingRequirementsTraversal());
1032 ASSERT(!layer.needsCompositingRequirementsTraversal());
1034 #if ENABLE(TREE_DEBUGGING)
1035 LOG(Compositing, "%*p traverseUnchangedSubtree", 12 + compositingState.depth * 2, &layer);
1038 layer.updateDescendantDependentFlags();
1039 layer.updateLayerListsIfNeeded();
1041 bool layerIsComposited = layer.isComposited();
1043 OverlapExtent layerExtent;
1044 if (layerIsComposited && !layer.isRenderViewLayer())
1045 layerExtent.hasTransformAnimation = isRunningTransformAnimation(layer.renderer());
1047 bool respectTransforms = !layerExtent.hasTransformAnimation;
1048 overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer, respectTransforms);
1050 // If we know for sure the layer is going to be composited, don't bother looking it up in the overlap map
1051 if (!layerIsComposited && !overlapMap.isEmpty() && compositingState.testingOverlap)
1052 computeExtent(overlapMap, layer, layerExtent);
1054 CompositingState childState(compositingState);
1055 childState.subtreeIsCompositing = false;
1056 #if ENABLE(CSS_COMPOSITING)
1057 childState.hasNotIsolatedCompositedBlendingDescendants = false;
1060 if (layerIsComposited) {
1061 // Tell the parent it has compositing descendants.
1062 compositingState.subtreeIsCompositing = true;
1063 // This layer now acts as the ancestor for kids.
1064 childState.compositingAncestor = &layer;
1066 overlapMap.pushCompositingContainer();
1067 // This layer is going to be composited, so children can safely ignore the fact that there's an
1068 // animation running behind this layer, meaning they can rely on the overlap map testing again.
1069 childState.testingOverlap = true;
1071 computeExtent(overlapMap, layer, layerExtent);
1072 childState.ancestorHasTransformAnimation |= layerExtent.hasTransformAnimation;
1073 // Too hard to compute animated bounds if both us and some ancestor is animating transform.
1074 layerExtent.animationCausesExtentUncertainty |= layerExtent.hasTransformAnimation && compositingState.ancestorHasTransformAnimation;
1077 #if !ASSERT_DISABLED
1078 LayerListMutationDetector mutationChecker(layer);
1081 bool anyDescendantHas3DTransform = false;
1083 for (auto* childLayer : layer.negativeZOrderLayers()) {
1084 traverseUnchangedSubtree(&layer, *childLayer, overlapMap, childState, anyDescendantHas3DTransform);
1085 if (childState.subtreeIsCompositing)
1086 ASSERT(layerIsComposited);
1089 for (auto* childLayer : layer.normalFlowLayers())
1090 traverseUnchangedSubtree(&layer, *childLayer, overlapMap, childState, anyDescendantHas3DTransform);
1092 for (auto* childLayer : layer.positiveZOrderLayers())
1093 traverseUnchangedSubtree(&layer, *childLayer, overlapMap, childState, anyDescendantHas3DTransform);
1095 // All layers (even ones that aren't being composited) need to get added to
1096 // the overlap map. Layers that do not composite will draw into their
1097 // compositing ancestor's backing, and so are still considered for overlap.
1098 // FIXME: When layerExtent has taken animation bounds into account, we also know that the bounds
1099 // include descendants, so we don't need to add them all to the overlap map.
1100 if (childState.compositingAncestor && !childState.compositingAncestor->isRenderViewLayer())
1101 addToOverlapMap(overlapMap, layer, layerExtent);
1103 // Subsequent layers in the parent stacking context also need to composite.
1104 if (childState.subtreeIsCompositing)
1105 compositingState.subtreeIsCompositing = true;
1107 // Set the flag to say that this layer has compositing children.
1108 ASSERT(layer.hasCompositingDescendant() == childState.subtreeIsCompositing);
1110 // setHasCompositingDescendant() may have changed the answer to needsToBeComposited() when clipping, so test that again.
1111 bool isCompositedClippingLayer = canBeComposited(layer) && clipsCompositingDescendants(layer);
1113 // Turn overlap testing off for later layers if it's already off, or if we have an animating transform.
1114 // Note that if the layer clips its descendants, there's no reason to propagate the child animation to the parent layers. That's because
1115 // we know for sure the animation is contained inside the clipping rectangle, which is already added to the overlap map.
1116 if ((!childState.testingOverlap && !isCompositedClippingLayer) || layerExtent.knownToBeHaveExtentUncertainty())
1117 compositingState.testingOverlap = false;
1119 if (isCompositedClippingLayer)
1120 ASSERT(layerIsComposited);
1122 #if ENABLE(CSS_COMPOSITING)
1123 if ((layerIsComposited && layer.hasBlendMode())
1124 || (layer.hasNotIsolatedCompositedBlendingDescendants() && !layer.isolatesCompositedBlending()))
1125 compositingState.hasNotIsolatedCompositedBlendingDescendants = true;
1128 if (childState.compositingAncestor == &layer && !layer.isRenderViewLayer())
1129 overlapMap.popCompositingContainer();
1131 descendantHas3DTransform |= anyDescendantHas3DTransform || layer.has3DTransform();
1133 ASSERT(!layer.needsCompositingRequirementsTraversal());
1135 overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
1138 void RenderLayerCompositor::updateBackingAndHierarchy(RenderLayer& layer, Vector<Ref<GraphicsLayer>>& childLayersOfEnclosingLayer, ScrollingTreeState& scrollingTreeState, OptionSet<UpdateLevel> updateLevel, int depth)
1140 layer.updateDescendantDependentFlags();
1141 layer.updateLayerListsIfNeeded();
1143 bool layerNeedsUpdate = !updateLevel.isEmpty();
1144 if (layer.descendantsNeedUpdateBackingAndHierarchyTraversal())
1145 updateLevel.add(UpdateLevel::AllDescendants);
1147 ScrollingTreeState stateForDescendants = scrollingTreeState;
1149 auto* layerBacking = layer.backing();
1151 updateLevel.remove(UpdateLevel::CompositedChildren);
1153 // We updated the composited bounds in RenderLayerBacking::updateAfterLayout(), but it may have changed
1154 // based on which descendants are now composited.
1155 if (layerBacking->updateCompositedBounds()) {
1156 layer.setNeedsCompositingGeometryUpdate();
1157 // Our geometry can affect descendants.
1158 updateLevel.add(UpdateLevel::CompositedChildren);
1161 if (layerNeedsUpdate || layer.needsCompositingConfigurationUpdate()) {
1162 if (layerBacking->updateConfiguration()) {
1163 layerNeedsUpdate = true; // We also need to update geometry.
1164 layer.setNeedsCompositingLayerConnection();
1167 layerBacking->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
1170 OptionSet<ScrollingNodeChangeFlags> scrollingNodeChanges = { ScrollingNodeChangeFlags::Layer };
1171 if (layerNeedsUpdate || layer.needsCompositingGeometryUpdate()) {
1172 layerBacking->updateGeometry();
1173 scrollingNodeChanges.add(ScrollingNodeChangeFlags::LayerGeometry);
1174 } else if (layer.needsScrollingTreeUpdate())
1175 scrollingNodeChanges.add(ScrollingNodeChangeFlags::LayerGeometry);
1177 if (auto* reflection = layer.reflectionLayer()) {
1178 if (auto* reflectionBacking = reflection->backing()) {
1179 reflectionBacking->updateCompositedBounds();
1180 reflectionBacking->updateGeometry();
1181 reflectionBacking->updateAfterDescendants();
1185 if (!layer.parent())
1186 updateRootLayerPosition();
1188 // FIXME: do based on dirty flags. Need to do this for changes of geometry, configuration and hierarchy.
1189 // Need to be careful to do the right thing when a scroll-coordinated layer loses a scroll-coordinated ancestor.
1190 stateForDescendants.parentNodeID = updateScrollCoordinationForLayer(layer, scrollingTreeState, layerBacking->coordinatedScrollingRoles(), scrollingNodeChanges);
1191 stateForDescendants.nextChildIndex = 0;
1194 logLayerInfo(layer, "updateBackingAndHierarchy", depth);
1196 UNUSED_PARAM(depth);
1200 if (layer.childrenNeedCompositingGeometryUpdate())
1201 updateLevel.add(UpdateLevel::CompositedChildren);
1203 // If this layer has backing, then we are collecting its children, otherwise appending
1204 // to the compositing child list of an enclosing layer.
1205 Vector<Ref<GraphicsLayer>> layerChildren;
1206 auto& childList = layerBacking ? layerChildren : childLayersOfEnclosingLayer;
1208 bool requireDescendantTraversal = layer.hasDescendantNeedingUpdateBackingOrHierarchyTraversal()
1209 || (layer.hasCompositingDescendant() && (!layerBacking || layer.needsCompositingLayerConnection() || !updateLevel.isEmpty()));
1211 bool requiresChildRebuild = layerBacking && layer.needsCompositingLayerConnection() && !layer.hasCompositingDescendant();
1213 #if !ASSERT_DISABLED
1214 LayerListMutationDetector mutationChecker(layer);
1217 auto appendForegroundLayerIfNecessary = [&] () {
1218 // If a negative z-order child is compositing, we get a foreground layer which needs to get parented.
1219 if (layer.negativeZOrderLayers().size()) {
1220 if (layerBacking && layerBacking->foregroundLayer())
1221 childList.append(*layerBacking->foregroundLayer());
1225 if (requireDescendantTraversal) {
1226 for (auto* renderLayer : layer.negativeZOrderLayers())
1227 updateBackingAndHierarchy(*renderLayer, childList, stateForDescendants, updateLevel, depth + 1);
1229 appendForegroundLayerIfNecessary();
1231 for (auto* renderLayer : layer.normalFlowLayers())
1232 updateBackingAndHierarchy(*renderLayer, childList, stateForDescendants, updateLevel, depth + 1);
1234 for (auto* renderLayer : layer.positiveZOrderLayers())
1235 updateBackingAndHierarchy(*renderLayer, childList, stateForDescendants, updateLevel, depth + 1);
1236 } else if (requiresChildRebuild)
1237 appendForegroundLayerIfNecessary();
1240 if (requireDescendantTraversal || requiresChildRebuild) {
1241 bool parented = false;
1242 if (is<RenderWidget>(layer.renderer()))
1243 parented = parentFrameContentLayers(downcast<RenderWidget>(layer.renderer()));
1246 layerBacking->parentForSublayers()->setChildren(WTFMove(layerChildren));
1248 // If the layer has a clipping layer the overflow controls layers will be siblings of the clipping layer.
1249 // Otherwise, the overflow control layers are normal children.
1250 if (!layerBacking->hasClippingLayer() && !layerBacking->hasScrollingLayer()) {
1251 if (auto* overflowControlLayer = layerBacking->layerForHorizontalScrollbar())
1252 layerBacking->parentForSublayers()->addChild(*overflowControlLayer);
1254 if (auto* overflowControlLayer = layerBacking->layerForVerticalScrollbar())
1255 layerBacking->parentForSublayers()->addChild(*overflowControlLayer);
1257 if (auto* overflowControlLayer = layerBacking->layerForScrollCorner())
1258 layerBacking->parentForSublayers()->addChild(*overflowControlLayer);
1262 childLayersOfEnclosingLayer.append(*layerBacking->childForSuperlayers());
1264 layerBacking->updateAfterDescendants();
1267 layer.clearUpdateBackingOrHierarchyTraversalState();
1270 void RenderLayerCompositor::appendDocumentOverlayLayers(Vector<Ref<GraphicsLayer>>& childList)
1272 if (!isMainFrameCompositor() || !m_compositing)
1275 if (!page().pageOverlayController().hasDocumentOverlays())
1278 Ref<GraphicsLayer> overlayHost = page().pageOverlayController().layerWithDocumentOverlays();
1279 childList.append(WTFMove(overlayHost));
1282 bool RenderLayerCompositor::needsCompositingForContentOrOverlays() const
1284 return m_contentLayersCount + page().pageOverlayController().overlayCount();
1287 void RenderLayerCompositor::layerBecameComposited(const RenderLayer& layer)
1289 if (&layer != m_renderView.layer())
1290 ++m_contentLayersCount;
1293 void RenderLayerCompositor::layerBecameNonComposited(const RenderLayer& layer)
1295 // Inform the inspector that the given RenderLayer was destroyed.
1296 // FIXME: "destroyed" is a misnomer.
1297 InspectorInstrumentation::renderLayerDestroyed(&page(), layer);
1299 if (&layer != m_renderView.layer()) {
1300 ASSERT(m_contentLayersCount > 0);
1301 --m_contentLayersCount;
1306 void RenderLayerCompositor::logLayerInfo(const RenderLayer& layer, const char* phase, int depth)
1308 if (!compositingLogEnabled())
1311 auto* backing = layer.backing();
1312 RequiresCompositingData queryData;
1313 if (requiresCompositingLayer(layer, queryData) || layer.isRenderViewLayer()) {
1314 ++m_obligateCompositedLayerCount;
1315 m_obligatoryBackingStoreBytes += backing->backingStoreMemoryEstimate();
1317 ++m_secondaryCompositedLayerCount;
1318 m_secondaryBackingStoreBytes += backing->backingStoreMemoryEstimate();
1321 LayoutRect absoluteBounds = backing->compositedBounds();
1322 absoluteBounds.move(layer.offsetFromAncestor(m_renderView.layer()));
1324 StringBuilder logString;
1325 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"));
1327 if (!layer.renderer().style().hasAutoZIndex())
1328 logString.append(makeString(" z-index: ", layer.renderer().style().zIndex()));
1330 logString.appendLiteral(" (");
1331 logString.append(logReasonsForCompositing(layer));
1332 logString.appendLiteral(") ");
1334 if (backing->graphicsLayer()->contentsOpaque() || backing->paintsIntoCompositedAncestor() || backing->foregroundLayer() || backing->backgroundLayer()) {
1335 logString.append('[');
1336 bool prependSpace = false;
1337 if (backing->graphicsLayer()->contentsOpaque()) {
1338 logString.appendLiteral("opaque");
1339 prependSpace = true;
1342 if (backing->paintsIntoCompositedAncestor()) {
1344 logString.appendLiteral(", ");
1345 logString.appendLiteral("paints into ancestor");
1346 prependSpace = true;
1349 if (backing->foregroundLayer() || backing->backgroundLayer()) {
1351 logString.appendLiteral(", ");
1352 if (backing->foregroundLayer() && backing->backgroundLayer()) {
1353 logString.appendLiteral("+foreground+background");
1354 prependSpace = true;
1355 } else if (backing->foregroundLayer()) {
1356 logString.appendLiteral("+foreground");
1357 prependSpace = true;
1359 logString.appendLiteral("+background");
1360 prependSpace = true;
1364 if (backing->paintsSubpixelAntialiasedText()) {
1366 logString.appendLiteral(", ");
1367 logString.appendLiteral("texty");
1370 logString.appendLiteral("] ");
1373 logString.append(layer.name());
1375 logString.appendLiteral(" - ");
1376 logString.append(phase);
1378 LOG(Compositing, "%s", logString.toString().utf8().data());
1382 static bool clippingChanged(const RenderStyle& oldStyle, const RenderStyle& newStyle)
1384 return oldStyle.overflowX() != newStyle.overflowX() || oldStyle.overflowY() != newStyle.overflowY()
1385 || oldStyle.hasClip() != newStyle.hasClip() || oldStyle.clip() != newStyle.clip();
1388 static bool styleAffectsLayerGeometry(const RenderStyle& style)
1390 return style.hasClip() || style.clipPath() || style.hasBorderRadius();
1393 void RenderLayerCompositor::layerStyleChanged(StyleDifference diff, RenderLayer& layer, const RenderStyle* oldStyle)
1395 if (diff == StyleDifference::Equal)
1398 // Create or destroy backing here so that code that runs during layout can reliably use isComposited() (though this
1399 // is only true for layers composited for direct reasons).
1400 // Also, it allows us to avoid a tree walk in updateCompositingLayers() when no layer changed its compositing state.
1401 RequiresCompositingData queryData;
1402 queryData.layoutUpToDate = LayoutUpToDate::No;
1404 bool layerChanged = updateBacking(layer, queryData, CompositingChangeRepaintNow);
1406 layer.setChildrenNeedCompositingGeometryUpdate();
1407 layer.setNeedsCompositingLayerConnection();
1408 layer.setSubsequentLayersNeedCompositingRequirementsTraversal();
1409 // Ancestor layers that composited for indirect reasons (things listed in styleChangeMayAffectIndirectCompositingReasons()) need to get updated.
1410 // This could be optimized by only setting this flag on layers with the relevant styles.
1411 layer.setNeedsPostLayoutCompositingUpdateOnAncestors();
1414 if (queryData.reevaluateAfterLayout)
1415 layer.setNeedsPostLayoutCompositingUpdate();
1417 if (diff >= StyleDifference::LayoutPositionedMovementOnly && hasContentCompositingLayers()) {
1418 layer.setNeedsPostLayoutCompositingUpdate();
1419 layer.setNeedsCompositingGeometryUpdate();
1422 auto* backing = layer.backing();
1426 backing->updateConfigurationAfterStyleChange();
1428 const auto& newStyle = layer.renderer().style();
1430 if (diff >= StyleDifference::Repaint) {
1431 // Visibility change may affect geometry of the enclosing composited layer.
1432 if (oldStyle && oldStyle->visibility() != newStyle.visibility())
1433 layer.setNeedsCompositingGeometryUpdate();
1435 // We'll get a diff of Repaint when things like clip-path change; these might affect layer or inner-layer geometry.
1436 if (layer.isComposited() && oldStyle) {
1437 if (styleAffectsLayerGeometry(*oldStyle) || styleAffectsLayerGeometry(newStyle))
1438 layer.setNeedsCompositingGeometryUpdate();
1442 // This is necessary to get iframe layers hooked up in response to scheduleInvalidateStyleAndLayerComposition().
1443 if (diff == StyleDifference::RecompositeLayer && layer.isComposited() && is<RenderWidget>(layer.renderer()))
1444 layer.setNeedsCompositingConfigurationUpdate();
1446 if (diff >= StyleDifference::RecompositeLayer && oldStyle) {
1447 if (oldStyle->transform() != newStyle.transform()) {
1448 // FIXME: transform changes really need to trigger layout. See RenderElement::adjustStyleDifference().
1449 layer.setNeedsPostLayoutCompositingUpdate();
1450 layer.setNeedsCompositingGeometryUpdate();
1454 if (diff >= StyleDifference::Layout) {
1455 // FIXME: only set flags here if we know we have a composited descendant, but we might not know at this point.
1456 if (oldStyle && clippingChanged(*oldStyle, newStyle)) {
1457 if (layer.isStackingContext()) {
1458 layer.setNeedsPostLayoutCompositingUpdate(); // Layer needs to become composited if it has composited descendants.
1459 layer.setNeedsCompositingConfigurationUpdate(); // If already composited, layer needs to create/destroy clipping layer.
1461 // Descendant (in containing block order) compositing layers need to re-evaluate their clipping,
1462 // but they might be siblings in z-order so go up to our stacking context.
1463 if (auto* stackingContext = layer.stackingContext())
1464 stackingContext->setDescendantsNeedUpdateBackingAndHierarchyTraversal();
1468 // These properties trigger compositing if some descendant is composited.
1469 if (oldStyle && styleChangeMayAffectIndirectCompositingReasons(*oldStyle, newStyle))
1470 layer.setNeedsPostLayoutCompositingUpdate();
1472 layer.setNeedsCompositingGeometryUpdate();
1476 bool RenderLayerCompositor::needsCompositingUpdateForStyleChangeOnNonCompositedLayer(RenderLayer& layer, const RenderStyle* oldStyle) const
1478 // Needed for scroll bars.
1479 if (layer.isRenderViewLayer())
1485 const RenderStyle& newStyle = layer.renderer().style();
1486 // Visibility change may affect geometry of the enclosing composited layer.
1487 if (oldStyle->visibility() != newStyle.visibility())
1490 // We don't have any direct reasons for this style change to affect layer composition. Test if it might affect things indirectly.
1491 if (styleChangeMayAffectIndirectCompositingReasons(*oldStyle, newStyle))
1497 bool RenderLayerCompositor::canCompositeClipPath(const RenderLayer& layer)
1499 ASSERT(layer.isComposited());
1500 ASSERT(layer.renderer().style().clipPath());
1502 if (layer.renderer().hasMask())
1505 auto& clipPath = *layer.renderer().style().clipPath();
1506 return (clipPath.type() != ClipPathOperation::Shape || clipPath.type() == ClipPathOperation::Shape) && GraphicsLayer::supportsLayerType(GraphicsLayer::Type::Shape);
1509 // FIXME: remove and never ask questions about reflection layers.
1510 static RenderLayerModelObject& rendererForCompositingTests(const RenderLayer& layer)
1512 auto* renderer = &layer.renderer();
1514 // The compositing state of a reflection should match that of its reflected layer.
1515 if (layer.isReflection())
1516 renderer = downcast<RenderLayerModelObject>(renderer->parent()); // The RenderReplica's parent is the object being reflected.
1521 void RenderLayerCompositor::updateRootContentLayerClipping()
1523 m_rootContentsLayer->setMasksToBounds(!m_renderView.settings().backgroundShouldExtendBeyondPage());
1526 bool RenderLayerCompositor::updateBacking(RenderLayer& layer, RequiresCompositingData& queryData, CompositingChangeRepaint shouldRepaint, BackingRequired backingRequired)
1528 bool layerChanged = false;
1529 if (backingRequired == BackingRequired::Unknown)
1530 backingRequired = needsToBeComposited(layer, queryData) ? BackingRequired::Yes : BackingRequired::No;
1532 // Need to fetch viewportConstrainedNotCompositedReason, but without doing all the work that needsToBeComposited does.
1533 requiresCompositingForPosition(rendererForCompositingTests(layer), layer, queryData);
1536 if (backingRequired == BackingRequired::Yes) {
1537 enableCompositingMode();
1539 if (!layer.backing()) {
1540 // If we need to repaint, do so before making backing
1541 if (shouldRepaint == CompositingChangeRepaintNow)
1542 repaintOnCompositingChange(layer);
1544 layer.ensureBacking();
1546 if (layer.isRenderViewLayer() && useCoordinatedScrollingForLayer(layer)) {
1547 auto& frameView = m_renderView.frameView();
1548 if (auto* scrollingCoordinator = this->scrollingCoordinator())
1549 scrollingCoordinator->frameViewRootLayerDidChange(frameView);
1550 #if ENABLE(RUBBER_BANDING)
1551 updateLayerForHeader(frameView.headerHeight());
1552 updateLayerForFooter(frameView.footerHeight());
1554 updateRootContentLayerClipping();
1556 if (auto* tiledBacking = layer.backing()->tiledBacking())
1557 tiledBacking->setTopContentInset(frameView.topContentInset());
1560 // This layer and all of its descendants have cached repaints rects that are relative to
1561 // the repaint container, so change when compositing changes; we need to update them here.
1563 layer.computeRepaintRectsIncludingDescendants();
1565 layer.setNeedsCompositingGeometryUpdate();
1566 layer.setNeedsCompositingConfigurationUpdate();
1567 layer.setNeedsCompositingPaintOrderChildrenUpdate();
1569 layerChanged = true;
1572 if (layer.backing()) {
1573 // If we're removing backing on a reflection, clear the source GraphicsLayer's pointer to
1574 // its replica GraphicsLayer. In practice this should never happen because reflectee and reflection
1575 // are both either composited, or not composited.
1576 if (layer.isReflection()) {
1577 auto* sourceLayer = downcast<RenderLayerModelObject>(*layer.renderer().parent()).layer();
1578 if (auto* backing = sourceLayer->backing()) {
1579 ASSERT(backing->graphicsLayer()->replicaLayer() == layer.backing()->graphicsLayer());
1580 backing->graphicsLayer()->setReplicatedByLayer(nullptr);
1584 layer.clearBacking();
1585 layerChanged = true;
1587 // This layer and all of its descendants have cached repaints rects that are relative to
1588 // the repaint container, so change when compositing changes; we need to update them here.
1589 layer.computeRepaintRectsIncludingDescendants();
1591 // If we need to repaint, do so now that we've removed the backing
1592 if (shouldRepaint == CompositingChangeRepaintNow)
1593 repaintOnCompositingChange(layer);
1598 if (layerChanged && is<RenderVideo>(layer.renderer())) {
1599 // If it's a video, give the media player a chance to hook up to the layer.
1600 downcast<RenderVideo>(layer.renderer()).acceleratedRenderingStateChanged();
1604 if (layerChanged && is<RenderWidget>(layer.renderer())) {
1605 auto* innerCompositor = frameContentsCompositor(downcast<RenderWidget>(layer.renderer()));
1606 if (innerCompositor && innerCompositor->usesCompositing())
1607 innerCompositor->updateRootLayerAttachment();
1611 layer.clearClipRectsIncludingDescendants(PaintingClipRects);
1613 // If a fixed position layer gained/lost a backing or the reason not compositing it changed,
1614 // the scrolling coordinator needs to recalculate whether it can do fast scrolling.
1615 if (layer.renderer().isFixedPositioned()) {
1616 if (layer.viewportConstrainedNotCompositedReason() != queryData.nonCompositedForPositionReason) {
1617 layer.setViewportConstrainedNotCompositedReason(queryData.nonCompositedForPositionReason);
1618 layerChanged = true;
1621 if (auto* scrollingCoordinator = this->scrollingCoordinator())
1622 scrollingCoordinator->frameViewFixedObjectsDidChange(m_renderView.frameView());
1625 layer.setViewportConstrainedNotCompositedReason(RenderLayer::NoNotCompositedReason);
1627 if (layer.backing())
1628 layer.backing()->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
1630 return layerChanged;
1633 bool RenderLayerCompositor::updateLayerCompositingState(RenderLayer& layer, RequiresCompositingData& queryData, CompositingChangeRepaint shouldRepaint)
1635 bool layerChanged = updateBacking(layer, queryData, shouldRepaint);
1637 // See if we need content or clipping layers. Methods called here should assume
1638 // that the compositing state of descendant layers has not been updated yet.
1639 if (layer.backing() && layer.backing()->updateConfiguration())
1640 layerChanged = true;
1642 return layerChanged;
1645 void RenderLayerCompositor::repaintOnCompositingChange(RenderLayer& layer)
1647 // If the renderer is not attached yet, no need to repaint.
1648 if (&layer.renderer() != &m_renderView && !layer.renderer().parent())
1651 auto* repaintContainer = layer.renderer().containerForRepaint();
1652 if (!repaintContainer)
1653 repaintContainer = &m_renderView;
1655 layer.repaintIncludingNonCompositingDescendants(repaintContainer);
1656 if (repaintContainer == &m_renderView) {
1657 // The contents of this layer may be moving between the window
1658 // and a GraphicsLayer, so we need to make sure the window system
1659 // synchronizes those changes on the screen.
1660 m_renderView.frameView().setNeedsOneShotDrawingSynchronization();
1664 // This method assumes that layout is up-to-date, unlike repaintOnCompositingChange().
1665 void RenderLayerCompositor::repaintInCompositedAncestor(RenderLayer& layer, const LayoutRect& rect)
1667 auto* compositedAncestor = layer.enclosingCompositingLayerForRepaint(ExcludeSelf);
1668 if (!compositedAncestor)
1671 ASSERT(compositedAncestor->backing());
1672 LayoutRect repaintRect = rect;
1673 repaintRect.move(layer.offsetFromAncestor(compositedAncestor));
1674 compositedAncestor->setBackingNeedsRepaintInRect(repaintRect);
1676 // The contents of this layer may be moving from a GraphicsLayer to the window,
1677 // so we need to make sure the window system synchronizes those changes on the screen.
1678 if (compositedAncestor->isRenderViewLayer())
1679 m_renderView.frameView().setNeedsOneShotDrawingSynchronization();
1683 void RenderLayerCompositor::layerWasAdded(RenderLayer&, RenderLayer&)
1687 void RenderLayerCompositor::layerWillBeRemoved(RenderLayer& parent, RenderLayer& child)
1689 if (!child.isComposited() || parent.renderer().renderTreeBeingDestroyed())
1692 repaintInCompositedAncestor(child, child.backing()->compositedBounds()); // FIXME: do via dirty bits?
1694 child.setNeedsCompositingLayerConnection();
1697 RenderLayer* RenderLayerCompositor::enclosingNonStackingClippingLayer(const RenderLayer& layer) const
1699 for (auto* parent = layer.parent(); parent; parent = parent->parent()) {
1700 if (parent->isStackingContext())
1702 if (parent->renderer().hasClipOrOverflowClip())
1708 void RenderLayerCompositor::computeExtent(const OverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& extent) const
1710 if (extent.extentComputed)
1713 LayoutRect layerBounds;
1714 if (extent.hasTransformAnimation)
1715 extent.animationCausesExtentUncertainty = !layer.getOverlapBoundsIncludingChildrenAccountingForTransformAnimations(layerBounds);
1717 layerBounds = layer.overlapBounds();
1719 // In the animating transform case, we avoid double-accounting for the transform because
1720 // we told pushMappingsToAncestor() to ignore transforms earlier.
1721 extent.bounds = enclosingLayoutRect(overlapMap.geometryMap().absoluteRect(layerBounds));
1723 // Empty rects never intersect, but we need them to for the purposes of overlap testing.
1724 if (extent.bounds.isEmpty())
1725 extent.bounds.setSize(LayoutSize(1, 1));
1728 RenderLayerModelObject& renderer = layer.renderer();
1729 if (renderer.isFixedPositioned() && renderer.container() == &m_renderView) {
1730 // Because fixed elements get moved around without re-computing overlap, we have to compute an overlap
1731 // rect that covers all the locations that the fixed element could move to.
1732 // FIXME: need to handle sticky too.
1733 extent.bounds = m_renderView.frameView().fixedScrollableAreaBoundsInflatedForScrolling(extent.bounds);
1736 extent.extentComputed = true;
1739 void RenderLayerCompositor::addToOverlapMap(OverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& extent)
1741 if (layer.isRenderViewLayer())
1744 computeExtent(overlapMap, layer, extent);
1746 LayoutRect clipRect = layer.backgroundClipRect(RenderLayer::ClipRectsContext(&rootRenderLayer(), AbsoluteClipRects)).rect(); // FIXME: Incorrect for CSS regions.
1748 // On iOS, pageScaleFactor() is not applied by RenderView, so we should not scale here.
1749 if (!m_renderView.settings().delegatesPageScaling())
1750 clipRect.scale(pageScaleFactor());
1751 clipRect.intersect(extent.bounds);
1752 overlapMap.add(clipRect);
1755 void RenderLayerCompositor::addToOverlapMapRecursive(OverlapMap& overlapMap, const RenderLayer& layer, const RenderLayer* ancestorLayer)
1757 if (!canBeComposited(layer))
1760 // A null ancestorLayer is an indication that 'layer' has already been pushed.
1762 overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer);
1764 OverlapExtent layerExtent;
1765 addToOverlapMap(overlapMap, layer, layerExtent);
1767 #if !ASSERT_DISABLED
1768 LayerListMutationDetector mutationChecker(const_cast<RenderLayer&>(layer));
1771 for (auto* renderLayer : layer.negativeZOrderLayers())
1772 addToOverlapMapRecursive(overlapMap, *renderLayer, &layer);
1774 for (auto* renderLayer : layer.normalFlowLayers())
1775 addToOverlapMapRecursive(overlapMap, *renderLayer, &layer);
1777 for (auto* renderLayer : layer.positiveZOrderLayers())
1778 addToOverlapMapRecursive(overlapMap, *renderLayer, &layer);
1781 overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
1785 bool RenderLayerCompositor::canAccelerateVideoRendering(RenderVideo& video) const
1787 if (!m_hasAcceleratedCompositing)
1790 return video.supportsAcceleratedRendering();
1794 void RenderLayerCompositor::frameViewDidChangeLocation(const IntPoint& contentsOffset)
1796 if (m_overflowControlsHostLayer)
1797 m_overflowControlsHostLayer->setPosition(contentsOffset);
1800 void RenderLayerCompositor::frameViewDidChangeSize()
1802 if (auto* layer = m_renderView.layer())
1803 layer->setNeedsCompositingGeometryUpdate();
1805 if (m_scrolledContentsLayer) {
1806 updateScrollLayerClipping();
1807 frameViewDidScroll();
1808 updateOverflowControlsLayers();
1810 #if ENABLE(RUBBER_BANDING)
1811 if (m_layerForOverhangAreas) {
1812 auto& frameView = m_renderView.frameView();
1813 m_layerForOverhangAreas->setSize(frameView.frameRect().size());
1814 m_layerForOverhangAreas->setPosition(FloatPoint(0, frameView.topContentInset()));
1820 bool RenderLayerCompositor::hasCoordinatedScrolling() const
1822 auto* scrollingCoordinator = this->scrollingCoordinator();
1823 return scrollingCoordinator && scrollingCoordinator->coordinatesScrollingForFrameView(m_renderView.frameView());
1826 void RenderLayerCompositor::updateScrollLayerPosition()
1828 ASSERT(!hasCoordinatedScrolling());
1829 ASSERT(m_scrolledContentsLayer);
1831 auto& frameView = m_renderView.frameView();
1832 IntPoint scrollPosition = frameView.scrollPosition();
1834 m_scrolledContentsLayer->setPosition(FloatPoint(-scrollPosition.x(), -scrollPosition.y()));
1836 if (auto* fixedBackgroundLayer = fixedRootBackgroundLayer())
1837 fixedBackgroundLayer->setPosition(frameView.scrollPositionForFixedPosition());
1840 void RenderLayerCompositor::updateScrollLayerClipping()
1842 auto* layerForClipping = this->layerForClipping();
1843 if (!layerForClipping)
1846 layerForClipping->setSize(m_renderView.frameView().sizeForVisibleContent());
1847 layerForClipping->setPosition(positionForClipLayer());
1850 FloatPoint RenderLayerCompositor::positionForClipLayer() const
1852 auto& frameView = m_renderView.frameView();
1855 frameView.shouldPlaceBlockDirectionScrollbarOnLeft() ? frameView.horizontalScrollbarIntrusion() : 0,
1856 FrameView::yPositionForInsetClipLayer(frameView.scrollPosition(), frameView.topContentInset()));
1859 void RenderLayerCompositor::frameViewDidScroll()
1861 if (!m_scrolledContentsLayer)
1864 // If there's a scrolling coordinator that manages scrolling for this frame view,
1865 // it will also manage updating the scroll layer position.
1866 if (hasCoordinatedScrolling()) {
1867 // We have to schedule a flush in order for the main TiledBacking to update its tile coverage.
1868 scheduleLayerFlushNow();
1872 updateScrollLayerPosition();
1875 void RenderLayerCompositor::frameViewDidAddOrRemoveScrollbars()
1877 updateOverflowControlsLayers();
1880 void RenderLayerCompositor::frameViewDidLayout()
1882 if (auto* renderViewBacking = m_renderView.layer()->backing())
1883 renderViewBacking->adjustTiledBackingCoverage();
1886 void RenderLayerCompositor::rootLayerConfigurationChanged()
1888 auto* renderViewBacking = m_renderView.layer()->backing();
1889 if (renderViewBacking && renderViewBacking->isFrameLayerWithTiledBacking()) {
1890 m_renderView.layer()->setNeedsCompositingConfigurationUpdate();
1891 scheduleCompositingLayerUpdate();
1895 String RenderLayerCompositor::layerTreeAsText(LayerTreeFlags flags)
1897 updateCompositingLayers(CompositingUpdateType::AfterLayout);
1899 if (!m_rootContentsLayer)
1902 flushPendingLayerChanges(true);
1904 LayerTreeAsTextBehavior layerTreeBehavior = LayerTreeAsTextBehaviorNormal;
1905 if (flags & LayerTreeFlagsIncludeDebugInfo)
1906 layerTreeBehavior |= LayerTreeAsTextDebug;
1907 if (flags & LayerTreeFlagsIncludeVisibleRects)
1908 layerTreeBehavior |= LayerTreeAsTextIncludeVisibleRects;
1909 if (flags & LayerTreeFlagsIncludeTileCaches)
1910 layerTreeBehavior |= LayerTreeAsTextIncludeTileCaches;
1911 if (flags & LayerTreeFlagsIncludeRepaintRects)
1912 layerTreeBehavior |= LayerTreeAsTextIncludeRepaintRects;
1913 if (flags & LayerTreeFlagsIncludePaintingPhases)
1914 layerTreeBehavior |= LayerTreeAsTextIncludePaintingPhases;
1915 if (flags & LayerTreeFlagsIncludeContentLayers)
1916 layerTreeBehavior |= LayerTreeAsTextIncludeContentLayers;
1917 if (flags & LayerTreeFlagsIncludeAcceleratesDrawing)
1918 layerTreeBehavior |= LayerTreeAsTextIncludeAcceleratesDrawing;
1919 if (flags & LayerTreeFlagsIncludeBackingStoreAttached)
1920 layerTreeBehavior |= LayerTreeAsTextIncludeBackingStoreAttached;
1921 if (flags & LayerTreeFlagsIncludeRootLayerProperties)
1922 layerTreeBehavior |= LayerTreeAsTextIncludeRootLayerProperties;
1924 // We skip dumping the scroll and clip layers to keep layerTreeAsText output
1925 // similar between platforms.
1926 String layerTreeText = m_rootContentsLayer->layerTreeAsText(layerTreeBehavior);
1928 // Dump an empty layer tree only if the only composited layer is the main frame's tiled backing,
1929 // so that tests expecting us to drop out of accelerated compositing when there are no layers succeed.
1930 if (!hasContentCompositingLayers() && documentUsesTiledBacking() && !(layerTreeBehavior & LayerTreeAsTextIncludeTileCaches) && !(layerTreeBehavior & LayerTreeAsTextIncludeRootLayerProperties))
1931 layerTreeText = emptyString();
1933 // The true root layer is not included in the dump, so if we want to report
1934 // its repaint rects, they must be included here.
1935 if (flags & LayerTreeFlagsIncludeRepaintRects)
1936 return m_renderView.frameView().trackedRepaintRectsAsText() + layerTreeText;
1938 return layerTreeText;
1941 static RenderView* frameContentsRenderView(RenderWidget& renderer)
1943 if (auto* contentDocument = renderer.frameOwnerElement().contentDocument())
1944 return contentDocument->renderView();
1949 RenderLayerCompositor* RenderLayerCompositor::frameContentsCompositor(RenderWidget& renderer)
1951 if (auto* view = frameContentsRenderView(renderer))
1952 return &view->compositor();
1957 bool RenderLayerCompositor::parentFrameContentLayers(RenderWidget& renderer)
1959 auto* innerCompositor = frameContentsCompositor(renderer);
1960 if (!innerCompositor || !innerCompositor->usesCompositing() || innerCompositor->rootLayerAttachment() != RootLayerAttachedViaEnclosingFrame)
1963 auto* layer = renderer.layer();
1964 if (!layer->isComposited())
1967 auto* backing = layer->backing();
1968 auto* hostingLayer = backing->parentForSublayers();
1969 auto* rootLayer = innerCompositor->rootGraphicsLayer();
1970 if (hostingLayer->children().size() != 1 || hostingLayer->children()[0].ptr() != rootLayer) {
1971 hostingLayer->removeAllChildren();
1972 hostingLayer->addChild(*rootLayer);
1975 if (auto frameHostingNodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::FrameHosting)) {
1976 auto* contentsRenderView = frameContentsRenderView(renderer);
1977 if (auto frameRootScrollingNodeID = contentsRenderView->frameView().scrollingNodeID()) {
1978 if (auto* scrollingCoordinator = this->scrollingCoordinator())
1979 scrollingCoordinator->insertNode(ScrollingNodeType::Subframe, frameRootScrollingNodeID, frameHostingNodeID, 0);
1983 // FIXME: Why always return true and not just when the layers changed?
1987 void RenderLayerCompositor::repaintCompositedLayers()
1989 recursiveRepaintLayer(rootRenderLayer());
1992 void RenderLayerCompositor::recursiveRepaintLayer(RenderLayer& layer)
1994 layer.updateLayerListsIfNeeded();
1996 // FIXME: This method does not work correctly with transforms.
1997 if (layer.isComposited() && !layer.backing()->paintsIntoCompositedAncestor())
1998 layer.setBackingNeedsRepaint();
2000 #if !ASSERT_DISABLED
2001 LayerListMutationDetector mutationChecker(layer);
2004 if (layer.hasCompositingDescendant()) {
2005 for (auto* renderLayer : layer.negativeZOrderLayers())
2006 recursiveRepaintLayer(*renderLayer);
2008 for (auto* renderLayer : layer.positiveZOrderLayers())
2009 recursiveRepaintLayer(*renderLayer);
2012 for (auto* renderLayer : layer.normalFlowLayers())
2013 recursiveRepaintLayer(*renderLayer);
2016 RenderLayer& RenderLayerCompositor::rootRenderLayer() const
2018 return *m_renderView.layer();
2021 GraphicsLayer* RenderLayerCompositor::rootGraphicsLayer() const
2023 if (m_overflowControlsHostLayer)
2024 return m_overflowControlsHostLayer.get();
2025 return m_rootContentsLayer.get();
2028 void RenderLayerCompositor::setIsInWindow(bool isInWindow)
2030 LOG(Compositing, "RenderLayerCompositor %p setIsInWindow %d", this, isInWindow);
2032 if (!usesCompositing())
2035 if (auto* rootLayer = rootGraphicsLayer()) {
2036 GraphicsLayer::traverse(*rootLayer, [isInWindow](GraphicsLayer& layer) {
2037 layer.setIsInWindow(isInWindow);
2042 if (m_rootLayerAttachment != RootLayerUnattached)
2045 RootLayerAttachment attachment = isMainFrameCompositor() ? RootLayerAttachedViaChromeClient : RootLayerAttachedViaEnclosingFrame;
2046 attachRootLayer(attachment);
2047 #if PLATFORM(IOS_FAMILY)
2048 if (m_legacyScrollingLayerCoordinator) {
2049 m_legacyScrollingLayerCoordinator->registerAllViewportConstrainedLayers(*this);
2050 m_legacyScrollingLayerCoordinator->registerAllScrollingLayers();
2054 if (m_rootLayerAttachment == RootLayerUnattached)
2058 #if PLATFORM(IOS_FAMILY)
2059 if (m_legacyScrollingLayerCoordinator) {
2060 m_legacyScrollingLayerCoordinator->unregisterAllViewportConstrainedLayers();
2061 m_legacyScrollingLayerCoordinator->unregisterAllScrollingLayers();
2067 void RenderLayerCompositor::clearBackingForLayerIncludingDescendants(RenderLayer& layer)
2069 if (layer.isComposited())
2070 layer.clearBacking();
2072 for (auto* childLayer = layer.firstChild(); childLayer; childLayer = childLayer->nextSibling())
2073 clearBackingForLayerIncludingDescendants(*childLayer);
2076 void RenderLayerCompositor::clearBackingForAllLayers()
2078 clearBackingForLayerIncludingDescendants(*m_renderView.layer());
2081 void RenderLayerCompositor::updateRootLayerPosition()
2083 if (m_rootContentsLayer) {
2084 m_rootContentsLayer->setSize(m_renderView.frameView().contentsSize());
2085 m_rootContentsLayer->setPosition(m_renderView.frameView().positionForRootContentLayer());
2086 m_rootContentsLayer->setAnchorPoint(FloatPoint3D());
2089 updateScrollLayerClipping();
2091 #if ENABLE(RUBBER_BANDING)
2092 if (m_contentShadowLayer && m_rootContentsLayer) {
2093 m_contentShadowLayer->setPosition(m_rootContentsLayer->position());
2094 m_contentShadowLayer->setSize(m_rootContentsLayer->size());
2097 updateLayerForTopOverhangArea(m_layerForTopOverhangArea != nullptr);
2098 updateLayerForBottomOverhangArea(m_layerForBottomOverhangArea != nullptr);
2099 updateLayerForHeader(m_layerForHeader != nullptr);
2100 updateLayerForFooter(m_layerForFooter != nullptr);
2104 bool RenderLayerCompositor::has3DContent() const
2106 return layerHas3DContent(rootRenderLayer());
2109 bool RenderLayerCompositor::needsToBeComposited(const RenderLayer& layer, RequiresCompositingData& queryData) const
2111 if (!canBeComposited(layer))
2114 return requiresCompositingLayer(layer, queryData) || layer.mustCompositeForIndirectReasons() || (usesCompositing() && layer.isRenderViewLayer());
2117 // Note: this specifies whether the RL needs a compositing layer for intrinsic reasons.
2118 // Use needsToBeComposited() to determine if a RL actually needs a compositing layer.
2119 // FIXME: is clipsCompositingDescendants() an intrinsic reason?
2120 bool RenderLayerCompositor::requiresCompositingLayer(const RenderLayer& layer, RequiresCompositingData& queryData) const
2122 auto& renderer = rendererForCompositingTests(layer);
2124 // The root layer always has a compositing layer, but it may not have backing.
2125 return requiresCompositingForTransform(renderer)
2126 || requiresCompositingForAnimation(renderer)
2127 || clipsCompositingDescendants(*renderer.layer())
2128 || requiresCompositingForPosition(renderer, *renderer.layer(), queryData)
2129 || requiresCompositingForCanvas(renderer)
2130 || requiresCompositingForFilters(renderer)
2131 || requiresCompositingForWillChange(renderer)
2132 || requiresCompositingForBackfaceVisibility(renderer)
2133 || requiresCompositingForVideo(renderer)
2134 || requiresCompositingForFrame(renderer, queryData)
2135 || requiresCompositingForPlugin(renderer, queryData)
2136 || requiresCompositingForEditableImage(renderer)
2137 || requiresCompositingForOverflowScrolling(*renderer.layer(), queryData);
2140 bool RenderLayerCompositor::canBeComposited(const RenderLayer& layer) const
2142 if (m_hasAcceleratedCompositing && layer.isSelfPaintingLayer()) {
2143 if (!layer.isInsideFragmentedFlow())
2146 // CSS Regions flow threads do not need to be composited as we use composited RenderFragmentContainers
2147 // to render the background of the RenderFragmentedFlow.
2148 if (layer.isRenderFragmentedFlow())
2156 #if ENABLE(FULLSCREEN_API)
2157 enum class FullScreenDescendant { Yes, No, NotApplicable };
2158 static FullScreenDescendant isDescendantOfFullScreenLayer(const RenderLayer& layer)
2160 auto& document = layer.renderer().document();
2162 if (!document.webkitIsFullScreen() || !document.fullScreenRenderer())
2163 return FullScreenDescendant::NotApplicable;
2165 auto* fullScreenLayer = document.fullScreenRenderer()->layer();
2166 if (!fullScreenLayer) {
2167 ASSERT_NOT_REACHED();
2168 return FullScreenDescendant::NotApplicable;
2171 return layer.isDescendantOf(*fullScreenLayer) ? FullScreenDescendant::Yes : FullScreenDescendant::No;
2175 bool RenderLayerCompositor::requiresOwnBackingStore(const RenderLayer& layer, const RenderLayer* compositingAncestorLayer, const LayoutRect& layerCompositedBoundsInAncestor, const LayoutRect& ancestorCompositedBounds) const
2177 auto& renderer = layer.renderer();
2179 if (compositingAncestorLayer
2180 && !(compositingAncestorLayer->backing()->graphicsLayer()->drawsContent()
2181 || compositingAncestorLayer->backing()->paintsIntoWindow()
2182 || compositingAncestorLayer->backing()->paintsIntoCompositedAncestor()))
2185 RequiresCompositingData queryData;
2186 if (layer.isRenderViewLayer()
2187 || layer.transform() // note: excludes perspective and transformStyle3D.
2188 || requiresCompositingForAnimation(renderer)
2189 || requiresCompositingForPosition(renderer, layer, queryData)
2190 || requiresCompositingForCanvas(renderer)
2191 || requiresCompositingForFilters(renderer)
2192 || requiresCompositingForWillChange(renderer)
2193 || requiresCompositingForBackfaceVisibility(renderer)
2194 || requiresCompositingForVideo(renderer)
2195 || requiresCompositingForFrame(renderer, queryData)
2196 || requiresCompositingForPlugin(renderer, queryData)
2197 || requiresCompositingForEditableImage(renderer)
2198 || requiresCompositingForOverflowScrolling(layer, queryData)
2199 || renderer.isTransparent()
2200 || renderer.hasMask()
2201 || renderer.hasReflection()
2202 || renderer.hasFilter()
2203 || renderer.hasBackdropFilter())
2206 if (layer.mustCompositeForIndirectReasons()) {
2207 RenderLayer::IndirectCompositingReason reason = layer.indirectCompositingReason();
2208 return reason == RenderLayer::IndirectCompositingReason::Overlap
2209 || reason == RenderLayer::IndirectCompositingReason::Stacking
2210 || reason == RenderLayer::IndirectCompositingReason::BackgroundLayer
2211 || reason == RenderLayer::IndirectCompositingReason::GraphicalEffect
2212 || reason == RenderLayer::IndirectCompositingReason::Preserve3D; // preserve-3d has to create backing store to ensure that 3d-transformed elements intersect.
2215 if (!ancestorCompositedBounds.contains(layerCompositedBoundsInAncestor))
2221 OptionSet<CompositingReason> RenderLayerCompositor::reasonsForCompositing(const RenderLayer& layer) const
2223 OptionSet<CompositingReason> reasons;
2225 if (!layer.isComposited())
2228 RequiresCompositingData queryData;
2230 auto& renderer = rendererForCompositingTests(layer);
2232 if (requiresCompositingForTransform(renderer))
2233 reasons.add(CompositingReason::Transform3D);
2235 if (requiresCompositingForVideo(renderer))
2236 reasons.add(CompositingReason::Video);
2237 else if (requiresCompositingForCanvas(renderer))
2238 reasons.add(CompositingReason::Canvas);
2239 else if (requiresCompositingForPlugin(renderer, queryData))
2240 reasons.add(CompositingReason::Plugin);
2241 else if (requiresCompositingForFrame(renderer, queryData))
2242 reasons.add(CompositingReason::IFrame);
2243 else if (requiresCompositingForEditableImage(renderer))
2244 reasons.add(CompositingReason::EmbeddedView);
2246 if ((canRender3DTransforms() && renderer.style().backfaceVisibility() == BackfaceVisibility::Hidden))
2247 reasons.add(CompositingReason::BackfaceVisibilityHidden);
2249 if (clipsCompositingDescendants(*renderer.layer()))
2250 reasons.add(CompositingReason::ClipsCompositingDescendants);
2252 if (requiresCompositingForAnimation(renderer))
2253 reasons.add(CompositingReason::Animation);
2255 if (requiresCompositingForFilters(renderer))
2256 reasons.add(CompositingReason::Filters);
2258 if (requiresCompositingForWillChange(renderer))
2259 reasons.add(CompositingReason::WillChange);
2261 if (requiresCompositingForPosition(renderer, *renderer.layer(), queryData))
2262 reasons.add(renderer.isFixedPositioned() ? CompositingReason::PositionFixed : CompositingReason::PositionSticky);
2264 if (requiresCompositingForOverflowScrolling(*renderer.layer(), queryData))
2265 reasons.add(CompositingReason::OverflowScrollingTouch);
2267 switch (renderer.layer()->indirectCompositingReason()) {
2268 case RenderLayer::IndirectCompositingReason::None:
2270 case RenderLayer::IndirectCompositingReason::Stacking:
2271 reasons.add(CompositingReason::Stacking);
2273 case RenderLayer::IndirectCompositingReason::Overlap:
2274 reasons.add(CompositingReason::Overlap);
2276 case RenderLayer::IndirectCompositingReason::BackgroundLayer:
2277 reasons.add(CompositingReason::NegativeZIndexChildren);
2279 case RenderLayer::IndirectCompositingReason::GraphicalEffect:
2280 if (renderer.hasTransform())
2281 reasons.add(CompositingReason::TransformWithCompositedDescendants);
2283 if (renderer.isTransparent())
2284 reasons.add(CompositingReason::OpacityWithCompositedDescendants);
2286 if (renderer.hasMask())
2287 reasons.add(CompositingReason::MaskWithCompositedDescendants);
2289 if (renderer.hasReflection())
2290 reasons.add(CompositingReason::ReflectionWithCompositedDescendants);
2292 if (renderer.hasFilter() || renderer.hasBackdropFilter())
2293 reasons.add(CompositingReason::FilterWithCompositedDescendants);
2295 #if ENABLE(CSS_COMPOSITING)
2296 if (layer.isolatesCompositedBlending())
2297 reasons.add(CompositingReason::IsolatesCompositedBlendingDescendants);
2299 if (layer.hasBlendMode())
2300 reasons.add(CompositingReason::BlendingWithCompositedDescendants);
2303 case RenderLayer::IndirectCompositingReason::Perspective:
2304 reasons.add(CompositingReason::Perspective);
2306 case RenderLayer::IndirectCompositingReason::Preserve3D:
2307 reasons.add(CompositingReason::Preserve3D);
2311 if (usesCompositing() && renderer.layer()->isRenderViewLayer())
2312 reasons.add(CompositingReason::Root);
2318 const char* RenderLayerCompositor::logReasonsForCompositing(const RenderLayer& layer)
2320 OptionSet<CompositingReason> reasons = reasonsForCompositing(layer);
2322 if (reasons & CompositingReason::Transform3D)
2323 return "3D transform";
2325 if (reasons & CompositingReason::Video)
2328 if (reasons & CompositingReason::Canvas)
2331 if (reasons & CompositingReason::Plugin)
2334 if (reasons & CompositingReason::IFrame)
2337 if (reasons & CompositingReason::BackfaceVisibilityHidden)
2338 return "backface-visibility: hidden";
2340 if (reasons & CompositingReason::ClipsCompositingDescendants)
2341 return "clips compositing descendants";
2343 if (reasons & CompositingReason::Animation)
2346 if (reasons & CompositingReason::Filters)
2349 if (reasons & CompositingReason::PositionFixed)
2350 return "position: fixed";
2352 if (reasons & CompositingReason::PositionSticky)
2353 return "position: sticky";
2355 if (reasons & CompositingReason::OverflowScrollingTouch)
2356 return "-webkit-overflow-scrolling: touch";
2358 if (reasons & CompositingReason::Stacking)
2361 if (reasons & CompositingReason::Overlap)
2364 if (reasons & CompositingReason::NegativeZIndexChildren)
2365 return "negative z-index children";
2367 if (reasons & CompositingReason::TransformWithCompositedDescendants)
2368 return "transform with composited descendants";
2370 if (reasons & CompositingReason::OpacityWithCompositedDescendants)
2371 return "opacity with composited descendants";
2373 if (reasons & CompositingReason::MaskWithCompositedDescendants)
2374 return "mask with composited descendants";
2376 if (reasons & CompositingReason::ReflectionWithCompositedDescendants)
2377 return "reflection with composited descendants";
2379 if (reasons & CompositingReason::FilterWithCompositedDescendants)
2380 return "filter with composited descendants";
2382 #if ENABLE(CSS_COMPOSITING)
2383 if (reasons & CompositingReason::BlendingWithCompositedDescendants)
2384 return "blending with composited descendants";
2386 if (reasons & CompositingReason::IsolatesCompositedBlendingDescendants)
2387 return "isolates composited blending descendants";
2390 if (reasons & CompositingReason::Perspective)
2391 return "perspective";
2393 if (reasons & CompositingReason::Preserve3D)
2394 return "preserve-3d";
2396 if (reasons & CompositingReason::Root)
2403 // Return true if the given layer has some ancestor in the RenderLayer hierarchy that clips,
2404 // up to the enclosing compositing ancestor. This is required because compositing layers are parented
2405 // according to the z-order hierarchy, yet clipping goes down the renderer hierarchy.
2406 // Thus, a RenderLayer can be clipped by a RenderLayer that is an ancestor in the renderer hierarchy,
2407 // but a sibling in the z-order hierarchy.
2408 // FIXME: can we do this without a tree walk?
2409 bool RenderLayerCompositor::clippedByAncestor(RenderLayer& layer) const
2411 ASSERT(layer.isComposited());
2412 if (!layer.parent())
2415 // On first pass in WK1, the root may not have become composited yet.
2416 auto* compositingAncestor = layer.ancestorCompositingLayer();
2417 if (!compositingAncestor)
2420 // If the compositingAncestor clips, that will be taken care of by clipsCompositingDescendants(),
2421 // so we only care about clipping between its first child that is our ancestor (the computeClipRoot),
2422 // and layer. The exception is when the compositingAncestor isolates composited blending children,
2423 // in this case it is not allowed to clipsCompositingDescendants() and each of its children
2424 // will be clippedByAncestor()s, including the compositingAncestor.
2425 auto* computeClipRoot = compositingAncestor;
2426 if (!compositingAncestor->isolatesCompositedBlending()) {
2427 computeClipRoot = nullptr;
2428 auto* parent = &layer;
2430 auto* next = parent->parent();
2431 if (next == compositingAncestor) {
2432 computeClipRoot = parent;
2438 if (!computeClipRoot || computeClipRoot == &layer)
2442 return !layer.backgroundClipRect(RenderLayer::ClipRectsContext(computeClipRoot, TemporaryClipRects)).isInfinite(); // FIXME: Incorrect for CSS regions.
2445 // Return true if the given layer is a stacking context and has compositing child
2446 // layers that it needs to clip. In this case we insert a clipping GraphicsLayer
2447 // into the hierarchy between this layer and its children in the z-order hierarchy.
2448 bool RenderLayerCompositor::clipsCompositingDescendants(const RenderLayer& layer) const
2450 return layer.hasCompositingDescendant() && layer.renderer().hasClipOrOverflowClip() && !layer.isolatesCompositedBlending();
2453 bool RenderLayerCompositor::requiresCompositingForAnimation(RenderLayerModelObject& renderer) const
2455 if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
2458 if (auto* element = renderer.element()) {
2459 if (auto* timeline = element->document().existingTimeline()) {
2460 if (timeline->runningAnimationsForElementAreAllAccelerated(*element))
2465 if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled())
2468 auto& animController = renderer.animation();
2469 return (animController.isRunningAnimationOnRenderer(renderer, CSSPropertyOpacity)
2470 && (usesCompositing() || (m_compositingTriggers & ChromeClient::AnimatedOpacityTrigger)))
2471 || animController.isRunningAnimationOnRenderer(renderer, CSSPropertyFilter)
2472 #if ENABLE(FILTERS_LEVEL_2)
2473 || animController.isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitBackdropFilter)
2475 || animController.isRunningAnimationOnRenderer(renderer, CSSPropertyTransform);
2478 bool RenderLayerCompositor::requiresCompositingForTransform(RenderLayerModelObject& renderer) const
2480 if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
2483 // Note that we ask the renderer if it has a transform, because the style may have transforms,
2484 // but the renderer may be an inline that doesn't suppport them.
2485 if (!renderer.hasTransform())
2488 switch (m_compositingPolicy) {
2489 case CompositingPolicy::Normal:
2490 return renderer.style().transform().has3DOperation();
2491 case CompositingPolicy::Conservative:
2492 // Continue to allow pages to avoid the very slow software filter path.
2493 if (renderer.style().transform().has3DOperation() && renderer.hasFilter())
2495 return renderer.style().transform().isRepresentableIn2D() ? false : true;
2500 bool RenderLayerCompositor::requiresCompositingForBackfaceVisibility(RenderLayerModelObject& renderer) const
2502 if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
2505 if (renderer.style().backfaceVisibility() != BackfaceVisibility::Hidden)
2508 if (renderer.layer()->has3DTransformedAncestor())
2511 // FIXME: workaround for webkit.org/b/132801
2512 auto* stackingContext = renderer.layer()->stackingContext();
2513 if (stackingContext && stackingContext->renderer().style().transformStyle3D() == TransformStyle3D::Preserve3D)
2519 bool RenderLayerCompositor::requiresCompositingForVideo(RenderLayerModelObject& renderer) const
2521 if (!(m_compositingTriggers & ChromeClient::VideoTrigger))
2525 if (!is<RenderVideo>(renderer))
2528 auto& video = downcast<RenderVideo>(renderer);
2529 if ((video.requiresImmediateCompositing() || video.shouldDisplayVideo()) && canAccelerateVideoRendering(video))
2532 UNUSED_PARAM(renderer);
2537 bool RenderLayerCompositor::requiresCompositingForCanvas(RenderLayerModelObject& renderer) const
2539 if (!(m_compositingTriggers & ChromeClient::CanvasTrigger))
2542 if (!renderer.isCanvas())
2545 bool isCanvasLargeEnoughToForceCompositing = true;
2546 #if !USE(COMPOSITING_FOR_SMALL_CANVASES)
2547 auto* canvas = downcast<HTMLCanvasElement>(renderer.element());
2548 auto canvasArea = canvas->size().area<RecordOverflow>();
2549 isCanvasLargeEnoughToForceCompositing = !canvasArea.hasOverflowed() && canvasArea.unsafeGet() >= canvasAreaThresholdRequiringCompositing;
2552 CanvasCompositingStrategy compositingStrategy = canvasCompositingStrategy(renderer);
2553 if (compositingStrategy == CanvasAsLayerContents)
2556 if (m_compositingPolicy == CompositingPolicy::Normal)
2557 return compositingStrategy == CanvasPaintedToLayer && isCanvasLargeEnoughToForceCompositing;
2562 bool RenderLayerCompositor::requiresCompositingForFilters(RenderLayerModelObject& renderer) const
2564 #if ENABLE(FILTERS_LEVEL_2)
2565 if (renderer.hasBackdropFilter())
2569 if (!(m_compositingTriggers & ChromeClient::FilterTrigger))
2572 return renderer.hasFilter();
2575 bool RenderLayerCompositor::requiresCompositingForWillChange(RenderLayerModelObject& renderer) const
2577 if (!renderer.style().willChange() || !renderer.style().willChange()->canTriggerCompositing())
2580 #if ENABLE(FULLSCREEN_API)
2581 // FIXME: does this require layout?
2582 if (renderer.layer() && isDescendantOfFullScreenLayer(*renderer.layer()) == FullScreenDescendant::No)
2586 if (m_compositingPolicy == CompositingPolicy::Conservative)
2589 if (is<RenderBox>(renderer))
2592 return renderer.style().willChange()->canTriggerCompositingOnInline();
2595 bool RenderLayerCompositor::requiresCompositingForPlugin(RenderLayerModelObject& renderer, RequiresCompositingData& queryData) const
2597 if (!(m_compositingTriggers & ChromeClient::PluginTrigger))
2600 bool isCompositedPlugin = is<RenderEmbeddedObject>(renderer) && downcast<RenderEmbeddedObject>(renderer).allowsAcceleratedCompositing();
2601 if (!isCompositedPlugin)
2604 auto& pluginRenderer = downcast<RenderWidget>(renderer);
2605 if (pluginRenderer.style().visibility() != Visibility::Visible)
2608 // If we can't reliably know the size of the plugin yet, don't change compositing state.
2609 if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2610 queryData.reevaluateAfterLayout = true;
2611 return pluginRenderer.isComposited();
2614 // Don't go into compositing mode if height or width are zero, or size is 1x1.
2615 IntRect contentBox = snappedIntRect(pluginRenderer.contentBoxRect());
2616 return (contentBox.height() * contentBox.width() > 1);
2619 bool RenderLayerCompositor::requiresCompositingForEditableImage(RenderLayerModelObject& renderer) const
2621 if (!renderer.isRenderImage())
2624 auto& image = downcast<RenderImage>(renderer);
2625 if (!image.isEditableImage())
2631 bool RenderLayerCompositor::requiresCompositingForFrame(RenderLayerModelObject& renderer, RequiresCompositingData& queryData) const
2633 if (!is<RenderWidget>(renderer))
2636 auto& frameRenderer = downcast<RenderWidget>(renderer);
2637 if (frameRenderer.style().visibility() != Visibility::Visible)
2640 if (!frameRenderer.requiresAcceleratedCompositing())
2643 if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2644 queryData.reevaluateAfterLayout = true;
2645 return frameRenderer.isComposited();
2648 // Don't go into compositing mode if height or width are zero.
2649 return !snappedIntRect(frameRenderer.contentBoxRect()).isEmpty();
2652 bool RenderLayerCompositor::requiresCompositingForScrollableFrame(RequiresCompositingData& queryData) const
2654 if (isMainFrameCompositor())
2657 #if PLATFORM(MAC) || PLATFORM(IOS_FAMILY)
2658 if (!m_renderView.settings().asyncFrameScrollingEnabled())
2662 if (!(m_compositingTriggers & ChromeClient::ScrollableNonMainFrameTrigger))
2665 if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2666 queryData.reevaluateAfterLayout = true;
2667 return m_renderView.isComposited();
2670 return m_renderView.frameView().isScrollable();
2673 bool RenderLayerCompositor::requiresCompositingForPosition(RenderLayerModelObject& renderer, const RenderLayer& layer, RequiresCompositingData& queryData) const
2675 // position:fixed elements that create their own stacking context (e.g. have an explicit z-index,
2676 // opacity, transform) can get their own composited layer. A stacking context is required otherwise
2677 // z-index and clipping will be broken.
2678 if (!renderer.isPositioned())
2681 #if ENABLE(FULLSCREEN_API)
2682 if (isDescendantOfFullScreenLayer(layer) == FullScreenDescendant::No)
2686 auto position = renderer.style().position();
2687 bool isFixed = renderer.isOutOfFlowPositioned() && position == PositionType::Fixed;
2688 if (isFixed && !layer.isStackingContext())
2691 bool isSticky = renderer.isInFlowPositioned() && position == PositionType::Sticky;
2692 if (!isFixed && !isSticky)
2695 // FIXME: acceleratedCompositingForFixedPositionEnabled should probably be renamed acceleratedCompositingForViewportConstrainedPositionEnabled().
2696 if (!m_renderView.settings().acceleratedCompositingForFixedPositionEnabled())
2700 return isAsyncScrollableStickyLayer(layer);
2702 if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2703 queryData.reevaluateAfterLayout = true;
2704 return layer.isComposited();
2707 auto container = renderer.container();
2710 // Don't promote fixed position elements that are descendants of a non-view container, e.g. transformed elements.
2711 // They will stay fixed wrt the container rather than the enclosing frame.j
2712 if (container != &m_renderView) {
2713 queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForNonViewContainer;
2717 bool paintsContent = layer.isVisuallyNonEmpty() || layer.hasVisibleDescendant();
2718 if (!paintsContent) {
2719 queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForNoVisibleContent;
2723 bool intersectsViewport = fixedLayerIntersectsViewport(layer);
2724 if (!intersectsViewport) {
2725 queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForBoundsOutOfView;
2726 LOG_WITH_STREAM(Compositing, stream << "Layer " << &layer << " is outside the viewport");
2733 bool RenderLayerCompositor::requiresCompositingForOverflowScrolling(const RenderLayer& layer, RequiresCompositingData& queryData) const
2735 if (!layer.canUseCompositedScrolling())
2738 if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2739 queryData.reevaluateAfterLayout = true;
2740 return layer.isComposited();
2743 return layer.hasCompositedScrollableOverflow();
2746 // FIXME: why doesn't this handle the clipping cases?
2747 bool RenderLayerCompositor::requiresCompositingForIndirectReason(RenderLayerModelObject& renderer, bool hasCompositedDescendants, bool has3DTransformedDescendants, RenderLayer::IndirectCompositingReason& reason) const
2749 auto& layer = *downcast<RenderBoxModelObject>(renderer).layer();
2751 // When a layer has composited descendants, some effects, like 2d transforms, filters, masks etc must be implemented
2752 // via compositing so that they also apply to those composited descendants.
2753 if (hasCompositedDescendants && (layer.isolatesCompositedBlending() || layer.transform() || renderer.createsGroup() || renderer.hasReflection())) {
2754 reason = RenderLayer::IndirectCompositingReason::GraphicalEffect;
2758 // A layer with preserve-3d or perspective only needs to be composited if there are descendant layers that
2759 // will be affected by the preserve-3d or perspective.
2760 if (has3DTransformedDescendants) {
2761 if (renderer.style().transformStyle3D() == TransformStyle3D::Preserve3D) {
2762 reason = RenderLayer::IndirectCompositingReason::Preserve3D;
2766 if (renderer.style().hasPerspective()) {
2767 reason = RenderLayer::IndirectCompositingReason::Perspective;
2772 reason = RenderLayer::IndirectCompositingReason::None;
2776 bool RenderLayerCompositor::styleChangeMayAffectIndirectCompositingReasons(const RenderStyle& oldStyle, const RenderStyle& newStyle)
2778 if (RenderElement::createsGroupForStyle(newStyle) != RenderElement::createsGroupForStyle(oldStyle))
2780 if (newStyle.isolation() != oldStyle.isolation())
2782 if (newStyle.hasTransform() != oldStyle.hasTransform())
2784 if (newStyle.boxReflect() != oldStyle.boxReflect())
2786 if (newStyle.transformStyle3D() != oldStyle.transformStyle3D())
2788 if (newStyle.hasPerspective() != oldStyle.hasPerspective())
2794 bool RenderLayerCompositor::isAsyncScrollableStickyLayer(const RenderLayer& layer, const RenderLayer** enclosingAcceleratedOverflowLayer) const
2796 ASSERT(layer.renderer().isStickilyPositioned());
2798 auto* enclosingOverflowLayer = layer.enclosingOverflowClipLayer(ExcludeSelf);
2800 #if PLATFORM(IOS_FAMILY)
2801 if (enclosingOverflowLayer && enclosingOverflowLayer->hasCompositedScrollableOverflow()) {
2802 if (enclosingAcceleratedOverflowLayer)
2803 *enclosingAcceleratedOverflowLayer = enclosingOverflowLayer;
2807 UNUSED_PARAM(enclosingAcceleratedOverflowLayer);
2809 // If the layer is inside normal overflow, it's not async-scrollable.
2810 if (enclosingOverflowLayer)
2813 // No overflow ancestor, so see if the frame supports async scrolling.
2814 if (hasCoordinatedScrolling())
2817 #if PLATFORM(IOS_FAMILY)
2818 // iOS WK1 has fixed/sticky support in the main frame via WebFixedPositionContent.
2819 return isMainFrameCompositor();
2825 bool RenderLayerCompositor::isViewportConstrainedFixedOrStickyLayer(const RenderLayer& layer) const
2827 if (layer.renderer().isStickilyPositioned())
2828 return isAsyncScrollableStickyLayer(layer);
2830 if (layer.renderer().style().position() != PositionType::Fixed)
2833 // FIXME: Handle fixed inside of a transform, which should not behave as fixed.
2834 for (auto* stackingContext = layer.stackingContext(); stackingContext; stackingContext = stackingContext->stackingContext()) {
2835 if (stackingContext->isComposited() && stackingContext->renderer().isFixedPositioned())
2842 bool RenderLayerCompositor::fixedLayerIntersectsViewport(const RenderLayer& layer) const
2844 ASSERT(layer.renderer().style().position() == PositionType::Fixed);
2846 // Fixed position elements that are invisible in the current view don't get their own layer.
2847 // FIXME: We shouldn't have to check useFixedLayout() here; one of the viewport rects needs to give the correct answer.
2848 LayoutRect viewBounds;
2849 if (m_renderView.frameView().useFixedLayout())
2850 viewBounds = m_renderView.unscaledDocumentRect();
2852 viewBounds = m_renderView.frameView().rectForFixedPositionLayout();
2854 LayoutRect layerBounds = layer.calculateLayerBounds(&layer, LayoutSize(), { RenderLayer::UseLocalClipRectIfPossible, RenderLayer::IncludeFilterOutsets, RenderLayer::UseFragmentBoxesExcludingCompositing,
2855 RenderLayer::ExcludeHiddenDescendants, RenderLayer::DontConstrainForMask, RenderLayer::IncludeCompositedDescendants });
2856 // Map to m_renderView to ignore page scale.
2857 FloatRect absoluteBounds = layer.renderer().localToContainerQuad(FloatRect(layerBounds), &m_renderView).boundingBox();
2858 return viewBounds.intersects(enclosingIntRect(absoluteBounds));
2861 bool RenderLayerCompositor::useCoordinatedScrollingForLayer(const RenderLayer& layer) const
2863 if (layer.isRenderViewLayer() && hasCoordinatedScrolling())
2866 if (auto* scrollingCoordinator = this->scrollingCoordinator())
2867 return scrollingCoordinator->coordinatesScrollingForOverflowLayer(layer);
2872 ScrollPositioningBehavior RenderLayerCompositor::computeCoordinatedPositioningForLayer(const RenderLayer& layer) const
2874 if (layer.isRenderViewLayer())
2875 return ScrollPositioningBehavior::None;
2877 // FIXME: This will look at the containing block and stacking context ancestor chains and determine
2878 // whether this layer needs to be repositioned when a composited overflow scroll scrolls.
2880 return ScrollPositioningBehavior::None;
2883 bool RenderLayerCompositor::isLayerForIFrameWithScrollCoordinatedContents(const RenderLayer& layer) const
2885 if (!is<RenderWidget>(layer.renderer()))
2888 auto* contentDocument = downcast<RenderWidget>(layer.renderer()).frameOwnerElement().contentDocument();
2889 if (!contentDocument)
2892 auto* view = contentDocument->renderView();
2896 if (auto* scrollingCoordinator = this->scrollingCoordinator())
2897 return scrollingCoordinator->coordinatesScrollingForFrameView(view->frameView());
2902 bool RenderLayerCompositor::isRunningTransformAnimation(RenderLayerModelObject& renderer) const
2904 if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
2907 if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled()) {
2908 if (auto* element = renderer.element()) {
2909 if (auto* timeline = element->document().existingTimeline())
2910 return timeline->isRunningAnimationOnRenderer(renderer, CSSPropertyTransform);
2914 return renderer.animation().isRunningAnimationOnRenderer(renderer, CSSPropertyTransform);
2917 // If an element has negative z-index children, those children render in front of the
2918 // layer background, so we need an extra 'contents' layer for the foreground of the layer object.
2919 bool RenderLayerCompositor::needsContentsCompositingLayer(const RenderLayer& layer) const
2921 return layer.hasNegativeZOrderLayers();
2924 bool RenderLayerCompositor::requiresScrollLayer(RootLayerAttachment attachment) const
2926 auto& frameView = m_renderView.frameView();
2928 // This applies when the application UI handles scrolling, in which case RenderLayerCompositor doesn't need to manage it.
2929 if (frameView.delegatesScrolling() && isMainFrameCompositor())
2932 // We need to handle our own scrolling if we're:
2933 return !m_renderView.frameView().platformWidget() // viewless (i.e. non-Mac, or Mac in WebKit2)
2934 || attachment == RootLayerAttachedViaEnclosingFrame; // a composited frame on Mac
2937 void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
2943 const IntRect& scrollbarRect = scrollbar->frameRect();
2944 context.translate(-scrollbarRect.location());
2945 IntRect transformedClip = clip;
2946 transformedClip.moveBy(scrollbarRect.location());
2947 scrollbar->paint(context, transformedClip);
2951 void RenderLayerCompositor::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, GraphicsLayerPaintingPhase, const FloatRect& clip, GraphicsLayerPaintBehavior)
2954 LocalDefaultSystemAppearance localAppearance(m_renderView.useDarkAppearance());
2957 IntRect pixelSnappedRectForIntegralPositionedItems = snappedIntRect(LayoutRect(clip));
2958 if (graphicsLayer == layerForHorizontalScrollbar())
2959 paintScrollbar(m_renderView.frameView().horizontalScrollbar(), context, pixelSnappedRectForIntegralPositionedItems);
2960 else if (graphicsLayer == layerForVerticalScrollbar())
2961 paintScrollbar(m_renderView.frameView().verticalScrollbar(), context, pixelSnappedRectForIntegralPositionedItems);
2962 else if (graphicsLayer == layerForScrollCorner()) {
2963 const IntRect& scrollCorner = m_renderView.frameView().scrollCornerRect();
2965 context.translate(-scrollCorner.location());
2966 IntRect transformedClip = pixelSnappedRectForIntegralPositionedItems;
2967 transformedClip.moveBy(scrollCorner.location());
2968 m_renderView.frameView().paintScrollCorner(context, transformedClip);
2973 bool RenderLayerCompositor::supportsFixedRootBackgroundCompositing() const
2975 auto* renderViewBacking = m_renderView.layer()->backing();
2976 return renderViewBacking && renderViewBacking->isFrameLayerWithTiledBacking();
2979 bool RenderLayerCompositor::needsFixedRootBackgroundLayer(const RenderLayer& layer) const
2981 if (!layer.isRenderViewLayer())
2984 if (m_renderView.settings().fixedBackgroundsPaintRelativeToDocument())
2987 return supportsFixedRootBackgroundCompositing() && m_renderView.rootBackgroundIsEntirelyFixed();
2990 GraphicsLayer* RenderLayerCompositor::fixedRootBackgroundLayer() const
2992 // Get the fixed root background from the RenderView layer's backing.
2993 auto* viewLayer = m_renderView.layer();
2997 if (viewLayer->isComposited() && viewLayer->backing()->backgroundLayerPaintsFixedRootBackground())
2998 return viewLayer->backing()->backgroundLayer();
3003 void RenderLayerCompositor::resetTrackedRepaintRects()
3005 if (auto* rootLayer = rootGraphicsLayer()) {
3006 GraphicsLayer::traverse(*rootLayer, [](GraphicsLayer& layer) {
3007 layer.resetTrackedRepaints();
3012 float RenderLayerCompositor::deviceScaleFactor() const
3014 return m_renderView.document().deviceScaleFactor();
3017 float RenderLayerCompositor::pageScaleFactor() const
3019 return page().pageScaleFactor();
3022 float RenderLayerCompositor::zoomedOutPageScaleFactor() const
3024 return page().zoomedOutPageScaleFactor();
3027 float RenderLayerCompositor::contentsScaleMultiplierForNewTiles(const GraphicsLayer*) const
3029 #if PLATFORM(IOS_FAMILY)
3030 LegacyTileCache* tileCache = nullptr;
3031 if (auto* frameView = page().mainFrame().view())
3032 tileCache = frameView->legacyTileCache();
3037 return tileCache->tileControllerShouldUseLowScaleTiles() ? 0.125 : 1;
3043 bool RenderLayerCompositor::documentUsesTiledBacking() const
3045 auto* layer = m_renderView.layer();
3049 auto* backing = layer->backing();
3053 return backing->isFrameLayerWithTiledBacking();
3056 bool RenderLayerCompositor::isMainFrameCompositor() const
3058 return m_renderView.frameView().frame().isMainFrame();
3061 bool RenderLayerCompositor::shouldCompositeOverflowControls() const
3063 auto& frameView = m_renderView.frameView();
3065 if (!frameView.managesScrollbars())
3068 if (documentUsesTiledBacking())
3071 if (m_overflowControlsHostLayer && isMainFrameCompositor())
3074 #if !USE(COORDINATED_GRAPHICS)
3075 if (!frameView.hasOverlayScrollbars())
3082 bool RenderLayerCompositor::requiresHorizontalScrollbarLayer() const
3084 return shouldCompositeOverflowControls() && m_renderView.frameView().horizontalScrollbar();
3087 bool RenderLayerCompositor::requiresVerticalScrollbarLayer() const
3089 return shouldCompositeOverflowControls() && m_renderView.frameView().verticalScrollbar();
3092 bool RenderLayerCompositor::requiresScrollCornerLayer() const
3094 return shouldCompositeOverflowControls() && m_renderView.frameView().isScrollCornerVisible();
3097 #if ENABLE(RUBBER_BANDING)
3098 bool RenderLayerCompositor::requiresOverhangAreasLayer() const
3100 if (!isMainFrameCompositor())
3103 // We do want a layer if we're using tiled drawing and can scroll.
3104 if (documentUsesTiledBacking() && m_renderView.frameView().hasOpaqueBackground() && !m_renderView.frameView().prohibitsScrolling())
3110 bool RenderLayerCompositor::requiresContentShadowLayer() const
3112 if (!isMainFrameCompositor())
3116 if (viewHasTransparentBackground())
3119 // If the background is going to extend, then it doesn't make sense to have a shadow layer.
3120 if (m_renderView.settings().backgroundShouldExtendBeyondPage())
3123 // On Mac, we want a content shadow layer if we're using tiled drawing and can scroll.
3124 if (documentUsesTiledBacking() && !m_renderView.frameView().prohibitsScrolling())
3131 GraphicsLayer* RenderLayerCompositor::updateLayerForTopOverhangArea(bool wantsLayer)
3133 if (!isMainFrameCompositor())
3137 GraphicsLayer::unparentAndClear(m_layerForTopOverhangArea);
3141 if (!m_layerForTopOverhangArea) {
3142 m_layerForTopOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), *this);
3143 m_layerForTopOverhangArea->setName("top overhang");
3144 m_scrolledContentsLayer->addChildBelow(*m_layerForTopOverhangArea, m_rootContentsLayer.get());
3147 return m_layerForTopOverhangArea.get();
3150 GraphicsLayer* RenderLayerCompositor::updateLayerForBottomOverhangArea(bool wantsLayer)
3152 if (!isMainFrameCompositor())
3156 GraphicsLayer::unparentAndClear(m_layerForBottomOverhangArea);
3160 if (!m_layerForBottomOverhangArea) {
3161 m_layerForBottomOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), *this);
3162 m_layerForBottomOverhangArea->setName("bottom overhang");
3163 m_scrolledContentsLayer->addChildBelow(*m_layerForBottomOverhangArea, m_rootContentsLayer.get());
3166 m_layerForBottomOverhangArea->setPosition(FloatPoint(0, m_rootContentsLayer->size().height() + m_renderView.frameView().headerHeight()
3167 + m_renderView.frameView().footerHeight() + m_renderView.frameView().topContentInset()));
3168 return m_layerForBottomOverhangArea.get();
3171 GraphicsLayer* RenderLayerCompositor::updateLayerForHeader(bool wantsLayer)
3173 if (!isMainFrameCompositor())
3177 if (m_layerForHeader) {
3178 GraphicsLayer::unparentAndClear(m_layerForHeader);
3180 // The ScrollingTree knows about the header layer, and the position of the root layer is affected
3181 // by the header layer, so if we remove the header, we need to tell the scrolling tree.
3182 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3183 scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
3188 if (!m_layerForHeader) {
3189 m_layerForHeader = GraphicsLayer::create(graphicsLayerFactory(), *this);
3190 m_layerForHeader->setName("header");
3191 m_scrolledContentsLayer->addChildAbove(*m_layerForHeader, m_rootContentsLayer.get());
3192 m_renderView.frameView().addPaintPendingMilestones(DidFirstFlushForHeaderLayer);
3195 m_layerForHeader->setPosition(FloatPoint(0,
3196 FrameView::yPositionForHeaderLayer(m_renderView.frameView().scrollPosition(), m_renderView.frameView().topContentInset())));
3197 m_layerForHeader->setAnchorPoint(FloatPoint3D());
3198 m_layerForHeader->setSize(FloatSize(m_renderView.frameView().visibleWidth(), m_renderView.frameView().headerHeight()));
3200 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3201 scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
3203 page().chrome().client().didAddHeaderLayer(*m_layerForHeader);
3205 return m_layerForHeader.get();
3208 GraphicsLayer* RenderLayerCompositor::updateLayerForFooter(bool wantsLayer)
3210 if (!isMainFrameCompositor())
3214 if (m_layerForFooter) {
3215 GraphicsLayer::unparentAndClear(m_layerForFooter);
3217 // The ScrollingTree knows about the footer layer, and the total scrollable size is affected
3218 // by the footer layer, so if we remove the footer, we need to tell the scrolling tree.
3219 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3220 scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
3225 if (!m_layerForFooter) {
3226 m_layerForFooter = GraphicsLayer::create(graphicsLayerFactory(), *this);
3227 m_layerForFooter->setName("footer");
3228 m_scrolledContentsLayer->addChildAbove(*m_layerForFooter, m_rootContentsLayer.get());
3231 float totalContentHeight = m_rootContentsLayer->size().height() + m_renderView.frameView().headerHeight() + m_renderView.frameView().footerHeight();
3232 m_layerForFooter->setPosition(FloatPoint(0, FrameView::yPositionForFooterLayer(m_renderView.frameView().scrollPosition(),
3233 m_renderView.frameView().topContentInset(), totalContentHeight, m_renderView.frameView().footerHeight())));
3234 m_layerForFooter->setAnchorPoint(FloatPoint3D());
3235 m_layerForFooter->setSize(FloatSize(m_renderView.frameView().visibleWidth(), m_renderView.frameView().footerHeight()));
3237 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3238 scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
3240 page().chrome().client().didAddFooterLayer(*m_layerForFooter);
3242 return m_layerForFooter.get();
3247 bool RenderLayerCompositor::viewHasTransparentBackground(Color* backgroundColor) const
3249 if (m_renderView.frameView().isTransparent()) {
3250 if (backgroundColor)
3251 *backgroundColor = Color(); // Return an invalid color.
3255 Color documentBackgroundColor = m_renderView.frameView().documentBackgroundColor();
3256 if (!documentBackgroundColor.isValid())
3257 documentBackgroundColor = m_renderView.frameView().baseBackgroundColor();
3259 ASSERT(documentBackgroundColor.isValid());
3261 if (backgroundColor)
3262 *backgroundColor = documentBackgroundColor;
3264 return !documentBackgroundColor.isOpaque();
3267 // We can't rely on getting layerStyleChanged() for a style change that affects the root background, because the style change may
3268 // be on the body which has no RenderLayer.
3269 void RenderLayerCompositor::rootOrBodyStyleChanged(RenderElement& renderer, const RenderStyle* oldStyle)
3271 if (!usesCompositing())
3274 Color oldBackgroundColor;
3276 oldBackgroundColor = oldStyle->visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor);
3278 if (oldBackgroundColor != renderer.style().visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor))
3279 rootBackgroundColorOrTransparencyChanged();
3281 bool hadFixedBackground = oldStyle && oldStyle->hasEntirelyFixedBackground();
3282 if (hadFixedBackground != renderer.style().hasEntirelyFixedBackground())
3283 rootLayerConfigurationChanged();
3286 void RenderLayerCompositor::rootBackgroundColorOrTransparencyChanged()
3288 if (!usesCompositing())
3291 Color backgroundColor;
3292 bool isTransparent = viewHasTransparentBackground(&backgroundColor);
3294 Color extendedBackgroundColor = m_renderView.settings().backgroundShouldExtendBeyondPage() ? backgroundColor : Color();
3296 bool transparencyChanged = m_viewBackgroundIsTransparent != isTransparent;
3297 bool backgroundColorChanged = m_viewBackgroundColor != backgroundColor;
3298 bool extendedBackgroundColorChanged = m_rootExtendedBackgroundColor != extendedBackgroundColor;
3300 if (!transparencyChanged && !backgroundColorChanged && !extendedBackgroundColorChanged)
3303 LOG(Compositing, "RenderLayerCompositor %p rootBackgroundColorOrTransparencyChanged. isTransparent=%d", this, isTransparent);
3305 m_viewBackgroundIsTransparent = isTransparent;
3306 m_viewBackgroundColor = backgroundColor;
3307 m_rootExtendedBackgroundColor = extendedBackgroundColor;
3309 if (extendedBackgroundColorChanged) {
3310 page().chrome().client().pageExtendedBackgroundColorDidChange(m_rootExtendedBackgroundColor);
3312 #if ENABLE(RUBBER_BANDING)
3313 if (m_layerForOverhangAreas) {
3314 m_layerForOverhangAreas->setBackgroundColor(m_rootExtendedBackgroundColor);
3316 if (!m_rootExtendedBackgroundColor.isValid())
3317 m_layerForOverhangAreas->setCustomAppearance(GraphicsLayer::CustomAppearance::ScrollingOverhang);
3322 rootLayerConfigurationChanged();
3325 void RenderLayerCompositor::updateOverflowControlsLayers()
3327 #if ENABLE(RUBBER_BANDING)
3328 if (requiresOverhangAreasLayer()) {
3329 if (!m_layerForOverhangAreas) {
3330 m_layerForOverhangAreas = GraphicsLayer::create(graphicsLayerFactory(), *this);
3331 m_layerForOverhangAreas->setName("overhang areas");
3332 m_layerForOverhangAreas->setDrawsContent(false);
3334 float topContentInset = m_renderView.frameView().topContentInset();
3335 IntSize overhangAreaSize = m_renderView.frameView().frameRect().size();
3336 overhangAreaSize.setHeight(overhangAreaSize.height() - topContentInset);
3337 m_layerForOverhangAreas->setSize(overhangAreaSize);
3338 m_layerForOverhangAreas->setPosition(FloatPoint(0, topContentInset));
3339 m_layerForOverhangAreas->setAnchorPoint(FloatPoint3D());
3341 if (m_renderView.settings().backgroundShouldExtendBeyondPage())
3342 m_layerForOverhangAreas->setBackgroundColor(m_renderView.frameView().documentBackgroundColor());
3344 m_layerForOverhangAreas->setCustomAppearance(GraphicsLayer::CustomAppearance::ScrollingOverhang);
3346 // We want the overhang areas layer to be positioned below the frame contents,
3347 // so insert it below the clip layer.
3348 m_overflowControlsHostLayer->addChildBelow(*m_layerForOverhangAreas, layerForClipping());
3351 GraphicsLayer::unparentAndClear(m_layerForOverhangAreas);
3353 if (requiresContentShadowLayer()) {
3354 if (!m_contentShadowLayer) {
3355 m_contentShadowLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3356 m_contentShadowLayer->setName("content shadow");
3357 m_contentShadowLayer->setSize(m_rootContentsLayer->size());
3358 m_contentShadowLayer->setPosition(m_rootContentsLayer->position());
3359 m_contentShadowLayer->setAnchorPoint(FloatPoint3D());
3360 m_contentShadowLayer->setCustomAppearance(GraphicsLayer::CustomAppearance::ScrollingShadow);
3362 m_scrolledContentsLayer->addChildBelow(*m_contentShadowLayer, m_rootContentsLayer.get());
3365 GraphicsLayer::unparentAndClear(m_contentShadowLayer);
3368 if (requiresHorizontalScrollbarLayer()) {
3369 if (!m_layerForHorizontalScrollbar) {
3370 m_layerForHorizontalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), *this);
3371 m_layerForHorizontalScrollbar->setCanDetachBackingStore(false);
3372 m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
3373 m_layerForHorizontalScrollbar->setName("horizontal scrollbar container");
3374 #if PLATFORM(COCOA) && USE(CA)
3375 m_layerForHorizontalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
3377 m_overflowControlsHostLayer->addChild(*m_layerForHorizontalScrollbar);
3379 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3380 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), HorizontalScrollbar);
3382 } else if (m_layerForHorizontalScrollbar) {
3383 GraphicsLayer::unparentAndClear(m_layerForHorizontalScrollbar);
3385 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3386 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), HorizontalScrollbar);
3389 if (requiresVerticalScrollbarLayer()) {
3390 if (!m_layerForVerticalScrollbar) {
3391 m_layerForVerticalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), *this);
3392 m_layerForVerticalScrollbar->setCanDetachBackingStore(false);
3393 m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
3394 m_layerForVerticalScrollbar->setName("vertical scrollbar container");
3395 #if PLATFORM(COCOA) && USE(CA)
3396 m_layerForVerticalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
3398 m_overflowControlsHostLayer->addChild(*m_layerForVerticalScrollbar);
3400 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3401 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), VerticalScrollbar);
3403 } else if (m_layerForVerticalScrollbar) {
3404 GraphicsLayer::unparentAndClear(m_layerForVerticalScrollbar);
3406 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3407 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), VerticalScrollbar);
3410 if (requiresScrollCornerLayer()) {
3411 if (!m_layerForScrollCorner) {
3412 m_layerForScrollCorner = GraphicsLayer::create(graphicsLayerFactory(), *this);
3413 m_layerForScrollCorner->setCanDetachBackingStore(false);
3414 m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
3415 m_layerForScrollCorner->setName("scroll corner");
3416 #if PLATFORM(COCOA) && USE(CA)
3417 m_layerForScrollCorner->setAcceleratesDrawing(acceleratedDrawingEnabled());
3419 m_overflowControlsHostLayer->addChild(*m_layerForScrollCorner);
3422 GraphicsLayer::unparentAndClear(m_layerForScrollCorner);
3424 m_renderView.frameView().positionScrollbarLayers();
3427 void RenderLayerCompositor::ensureRootLayer()
3429 RootLayerAttachment expectedAttachment = isMainFrameCompositor() ? RootLayerAttachedViaChromeClient : RootLayerAttachedViaEnclosingFrame;
3430 if (expectedAttachment == m_rootLayerAttachment)
3433 if (!m_rootContentsLayer) {
3434 m_rootContentsLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3435 m_rootContentsLayer->setName("content root");
3436 IntRect overflowRect = snappedIntRect(m_renderView.layoutOverflowRect());
3437 m_rootContentsLayer->setSize(FloatSize(overflowRect.maxX(), overflowRect.maxY()));
3438 m_rootContentsLayer->setPosition(FloatPoint());
3440 #if PLATFORM(IOS_FAMILY)
3441 // Page scale is applied above this on iOS, so we'll just say that our root layer applies it.
3442 auto& frame = m_renderView.frameView().frame();
3443 if (frame.isMainFrame())
3444 m_rootContentsLayer->setAppliesPageScale();
3447 // Need to clip to prevent transformed content showing outside this frame
3448 updateRootContentLayerClipping();
3451 if (requiresScrollLayer(expectedAttachment)) {
3452 if (!m_overflowControlsHostLayer) {
3453 ASSERT(!m_scrolledContentsLayer);
3454 ASSERT(!m_clipLayer);
3456 // Create a layer to host the clipping layer and the overflow controls layers.
3457 m_overflowControlsHostLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3458 m_overflowControlsHostLayer->setName("overflow controls host");
3460 m_scrolledContentsLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3461 m_scrolledContentsLayer->setName("scrolled contents");
3462 m_scrolledContentsLayer->setAnchorPoint({ });
3464 #if PLATFORM(IOS_FAMILY)
3465 if (m_renderView.settings().asyncFrameScrollingEnabled()) {
3466 m_scrollContainerLayer = GraphicsLayer::create(graphicsLayerFactory(), *this, GraphicsLayer::Type::ScrollContainer);
3468 m_scrollContainerLayer->setName("scroll container");
3469 m_scrollContainerLayer->setMasksToBounds(true);
3470 m_scrollContainerLayer->setAnchorPoint({ });
3472 m_scrollContainerLayer->addChild(*m_scrolledContentsLayer);
3473 m_overflowControlsHostLayer->addChild(*m_scrollContainerLayer);
3476 if (!m_scrollContainerLayer) {
3477 m_clipLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3478 m_clipLayer->setName("frame clipping");
3479 m_clipLayer->setMasksToBounds(true);
3480 m_clipLayer->setAnchorPoint({ });
3482 m_clipLayer->addChild(*m_scrolledContentsLayer);
3483 m_overflowControlsHostLayer->addChild(*m_clipLayer);
3486 m_scrolledContentsLayer->addChild(*m_rootContentsLayer);
3488 updateScrollLayerClipping();
3489 updateOverflowControlsLayers();
3491 if (hasCoordinatedScrolling())
3492 scheduleLayerFlush(true);
3494 updateScrollLayerPosition();
3497 if (m_overflowControlsHostLayer) {
3498 GraphicsLayer::unparentAndClear(m_overflowControlsHostLayer);
3499 GraphicsLayer::unparentAndClear(m_clipLayer);
3500 GraphicsLayer::unparentAndClear(m_scrollContainerLayer);
3501 GraphicsLayer::unparentAndClear(m_scrolledContentsLayer);
3505 // Check to see if we have to change the attachment
3506 if (m_rootLayerAttachment != RootLayerUnattached)
3509 attachRootLayer(expectedAttachment);
3512 void RenderLayerCompositor::destroyRootLayer()
3514 if (!m_rootContentsLayer)
3519 #if ENABLE(RUBBER_BANDING)
3520 GraphicsLayer::unparentAndClear(m_layerForOverhangAreas);
3523 if (m_layerForHorizontalScrollbar) {
3524 GraphicsLayer::unparentAndClear(m_layerForHorizontalScrollbar);
3525 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3526 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), HorizontalScrollbar);
3527 if (auto* horizontalScrollbar = m_renderView.frameView().verticalScrollbar())
3528 m_renderView.frameView().invalidateScrollbar(*horizontalScrollbar, IntRect(IntPoint(0, 0), horizontalScrollbar->frameRect().size()));
3531 if (m_layerForVerticalScrollbar) {
3532 GraphicsLayer::unparentAndClear(m_layerForVerticalScrollbar);
3533 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3534 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), VerticalScrollbar);
3535 if (auto* verticalScrollbar = m_renderView.frameView().verticalScrollbar())
3536 m_renderView.frameView().invalidateScrollbar(*verticalScrollbar, IntRect(IntPoint(0, 0), verticalScrollbar->frameRect().size()));
3539 if (m_layerForScrollCorner) {
3540 GraphicsLayer::unparentAndClear(m_layerForScrollCorner);
3541 m_renderView.frameView().invalidateScrollCorner(m_renderView.frameView().scrollCornerRect());
3544 if (m_overflowControlsHostLayer) {
3545 GraphicsLayer::unparentAndClear(m_overflowControlsHostLayer);
3546 GraphicsLayer::unparentAndClear(m_clipLayer);
3547 GraphicsLayer::unparentAndClear(m_scrollContainerLayer);
3548 GraphicsLayer::unparentAndClear(m_scrolledContentsLayer);
3550 ASSERT(!m_scrolledContentsLayer);
3551 GraphicsLayer::unparentAndClear(m_rootContentsLayer);
3553 m_layerUpdater = nullptr;
3556 void RenderLayerCompositor::attachRootLayer(RootLayerAttachment attachment)
3558 if (!m_rootContentsLayer)
3561 LOG(Compositing, "RenderLayerCompositor %p attachRootLayer %d", this, attachment);
3563 switch (attachment) {
3564 case RootLayerUnattached:
3565 ASSERT_NOT_REACHED();
3567 case RootLayerAttachedViaChromeClient: {
3568 auto& frame = m_renderView.frameView().frame();
3569 page().chrome().client().attachRootGraphicsLayer(frame, rootGraphicsLayer());
3572 case RootLayerAttachedViaEnclosingFrame: {
3573 // The layer will get hooked up via RenderLayerBacking::updateConfiguration()
3574 // for the frame's renderer in the parent document.
3575 if (auto* ownerElement = m_renderView.document().ownerElement())
3576 ownerElement->scheduleInvalidateStyleAndLayerComposition();
3581 m_rootLayerAttachment = attachment;
3582 rootLayerAttachmentChanged();
3584 if (m_shouldFlushOnReattach) {
3585 scheduleLayerFlushNow();
3586 m_shouldFlushOnReattach = false;
3590 void RenderLayerCompositor::detachRootLayer()
3592 if (!m_rootContentsLayer || m_rootLayerAttachment == RootLayerUnattached)
3595 switch (m_rootLayerAttachment) {
3596 case RootLayerAttachedViaEnclosingFrame: {
3597 // The layer will get unhooked up via RenderLayerBacking::updateConfiguration()
3598 // for the frame's renderer in the parent document.
3599 if (m_overflowControlsHostLayer)
3600 m_overflowControlsHostLayer->removeFromParent();
3602 m_rootContentsLayer->removeFromParent();
3604 if (auto* ownerElement = m_renderView.document().ownerElement())
3605 ownerElement->scheduleInvalidateStyleAndLayerComposition();
3607 if (auto frameRootScrollingNodeID = m_renderView.frameView().scrollingNodeID()) {
3608 if (auto* scrollingCoordinator = this->scrollingCoordinator())
3609 scrollingCoordinator->unparentNode(frameRootScrollingNodeID);
3613 case RootLayerAttachedViaChromeClient: {
3614 auto& frame = m_renderView.frameView().frame();
3615 page().chrome().client().attachRootGraphicsLayer(frame, nullptr);
3618 case RootLayerUnattached:
3622 m_rootLayerAttachment = RootLayerUnattached;
3623 rootLayerAttachmentChanged();
3626 void RenderLayerCompositor::updateRootLayerAttachment()
3631 void RenderLayerCompositor::rootLayerAttachmentChanged()
3633 // The document-relative page overlay layer (which is pinned to the main frame's layer tree)
3634 // is moved between different RenderLayerCompositors' layer trees, and needs to be
3635 // reattached whenever we swap in a new RenderLayerCompositor.
3636 if (m_rootLayerAttachment == RootLayerUnattached)
3639 auto& frame = m_renderView.frameView().frame();
3641 // The attachment can affect whether the RenderView layer's paintsIntoWindow() behavior,
3642 // so call updateDrawsContent() to update that.
3643 auto* layer = m_renderView.layer();
3644 if (auto* backing = layer ? layer->backing() : nullptr)
3645 backing->updateDrawsContent();
3647 if (!frame.isMainFrame())
3650 Ref<GraphicsLayer> overlayHost = page().pageOverlayController().layerWithDocumentOverlays();
3651 m_rootContentsLayer->addChild(WTFMove(overlayHost));
3654 void RenderLayerCompositor::notifyIFramesOfCompositingChange()
3656 // Compositing affects the answer to RenderIFrame::requiresAcceleratedCompositing(), so
3657 // we need to schedule a style recalc in our parent document.
3658 if (auto* ownerElement = m_renderView.document().ownerElement())
3659 ownerElement->scheduleInvalidateStyleAndLayerComposition();
3662 bool RenderLayerCompositor::layerHas3DContent(const RenderLayer& layer) const
3664 const RenderStyle& style = layer.renderer().style();
3666 if (style.transformStyle3D() == TransformStyle3D::Preserve3D || style.hasPerspective() || style.transform().has3DOperation())
3669 const_cast<RenderLayer&>(layer).updateLayerListsIfNeeded();
3671 #if !ASSERT_DISABLED
3672 LayerListMutationDetector mutationChecker(const_cast<RenderLayer&>(layer));
3675 for (auto* renderLayer : layer.negativeZOrderLayers()) {
3676 if (layerHas3DContent(*renderLayer))
3680 for (auto* renderLayer : layer.positiveZOrderLayers()) {
3681 if (layerHas3DContent(*renderLayer))
3685 for (auto* renderLayer : layer.normalFlowLayers()) {
3686 if (layerHas3DContent(*renderLayer))
3693 void RenderLayerCompositor::deviceOrPageScaleFactorChanged()
3695 // Page scale will only be applied at to the RenderView and sublayers, but the device scale factor
3696 // needs to be applied at the level of rootGraphicsLayer().
3697 if (auto* rootLayer = rootGraphicsLayer())
3698 rootLayer->noteDeviceOrPageScaleFactorChangedIncludingDescendants();
3701 void RenderLayerCompositor::removeFromScrollCoordinatedLayers(RenderLayer& layer)
3703 #if PLATFORM(IOS_FAMILY)
3704 if (m_legacyScrollingLayerCoordinator)
3705 m_legacyScrollingLayerCoordinator->removeLayer(layer);
3708 detachScrollCoordinatedLayer(layer, { ScrollCoordinationRole::Scrolling, ScrollCoordinationRole::ViewportConstrained, ScrollCoordinationRole::FrameHosting });
3711 FixedPositionViewportConstraints RenderLayerCompositor::computeFixedViewportConstraints(RenderLayer& layer) const
3713 ASSERT(layer.isComposited());
3715 auto* graphicsLayer = layer.backing()->graphicsLayer();
3717 FixedPositionViewportConstraints constraints;
3718 constraints.setLayerPositionAtLastLayout(graphicsLayer->position());
3719 constraints.setViewportRectAtLastLayout(m_renderView.frameView().rectForFixedPositionLayout());
3720 constraints.setAlignmentOffset(graphicsLayer->pixelAlignmentOffset());
3722 const RenderStyle& style = layer.renderer().style();
3723 if (!style.left().isAuto())
3724 constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeLeft);
3726 if (!style.right().isAuto())
3727 constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeRight);
3729 if (!style.top().isAuto())
3730 constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeTop);
3732 if (!style.bottom().isAuto())
3733 constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeBottom);
3735 // If left and right are auto, use left.
3736 if (style.left().isAuto() && style.right().isAuto())
3737 constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeLeft);
3739 // If top and bottom are auto, use top.
3740 if (style.top().isAuto() && style.bottom().isAuto())
3741 constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeTop);
3746 StickyPositionViewportConstraints RenderLayerCompositor::computeStickyViewportConstraints(RenderLayer& layer) const
3748 ASSERT(layer.isComposited());
3749 #if !PLATFORM(IOS_FAMILY)
3750 // We should never get here for stickies constrained by an enclosing clipping layer.
3751 // FIXME: Why does this assertion fail on iOS?
3752 ASSERT(!layer.enclosingOverflowClipLayer(ExcludeSelf));
3755 auto& renderer = downcast<RenderBoxModelObject>(layer.renderer());
3757 StickyPositionViewportConstraints constraints;
3758 renderer.computeStickyPositionConstraints(constraints, renderer.constrainingRectForStickyPosition());
3760 auto* graphicsLayer = layer.backing()->graphicsLayer();
3761 constraints.setLayerPositionAtLastLayout(graphicsLayer->position());
3762 constraints.setStickyOffsetAtLastLayout(renderer.stickyPositionOffset());
3763 constraints.setAlignmentOffset(graphicsLayer->pixelAlignmentOffset());
3768 static inline ScrollCoordinationRole scrollCoordinationRoleForNodeType(ScrollingNodeType nodeType)
3771 case ScrollingNodeType::MainFrame:
3772 case ScrollingNodeType::Subframe:
3773 case ScrollingNodeType::Overflow:
3774 return ScrollCoordinationRole::Scrolling;
3775 case ScrollingNodeType::FrameHosting:
3776 return ScrollCoordinationRole::FrameHosting;
3777 case ScrollingNodeType::Fixed:
3778 case ScrollingNodeType::Sticky:
3779 return ScrollCoordinationRole::ViewportConstrained;
3780 case ScrollingNodeType::Positioned:
3781 return ScrollCoordinationRole::Positioning;
3783 ASSERT_NOT_REACHED();
3784 return ScrollCoordinationRole::Scrolling;
3787 ScrollingNodeID RenderLayerCompositor::attachScrollingNode(RenderLayer& layer, ScrollingNodeType nodeType, ScrollingTreeState& treeState)
3789 auto* scrollingCoordinator = this->scrollingCoordinator();
3790 auto* backing = layer.backing();
3791 // Crash logs suggest that backing can be null here, but we don't know how: rdar://problem/18545452.
3796 ASSERT(treeState.parentNodeID || nodeType == ScrollingNodeType::Subframe);
3797 ASSERT_IMPLIES(nodeType == ScrollingNodeType::MainFrame, !treeState.parentNodeID.value());
3799 ScrollCoordinationRole role = scrollCoordinationRoleForNodeType(nodeType);
3800 ScrollingNodeID nodeID = backing->scrollingNodeIDForRole(role);
3802 nodeID = scrollingCoordinator->uniqueScrollingNodeID();
3804 LOG_WITH_STREAM(Scrolling, stream << "RenderLayerCompositor " << this << " attachScrollingNode " << nodeID << " (layer " << backing->graphicsLayer()->primaryLayerID() << ") type " << nodeType << " parent " << treeState.parentNodeID.valueOr(0));
3806 if (nodeType == ScrollingNodeType::Subframe && !treeState.parentNodeID)
3807 nodeID = scrollingCoordinator->createNode(nodeType, nodeID);
3809 auto newNodeID = scrollingCoordinator->insertNode(nodeType, nodeID, treeState.parentNodeID.valueOr(0), treeState.nextChildIndex);
3810 if (newNodeID != nodeID) {
3811 // We'll get a new nodeID if the type changed (and not if the node is new).
3812 scrollingCoordinator->unparentChildrenAndDestroyNode(nodeID);
3813 m_scrollingNodeToLayerMap.remove(nodeID);
3822 backing->setScrollingNodeIDForRole(nodeID, role);
3823 m_scrollingNodeToLayerMap.add(nodeID, &layer);
3825 ++treeState.nextChildIndex;
3829 void RenderLayerCompositor::detachScrollCoordinatedLayerWithRole(RenderLayer& layer, ScrollingCoordinator& scrollingCoordinator, ScrollCoordinationRole role)
3831 auto nodeID = layer.backing()->scrollingNodeIDForRole(role);
3835 auto childNodes = scrollingCoordinator.childrenOfNode(nodeID);
3836 for (auto childNodeID : childNodes) {
3837 // FIXME: The child might be in a child frame. Need to do something that crosses frame boundaries.
3838 if (auto* layer = m_scrollingNodeToLayerMap.get(childNodeID))
3839 layer->setNeedsScrollingTreeUpdate();
3842 m_scrollingNodeToLayerMap.remove(nodeID);