RenderLayerCompositor.cpp [plain text]
#include "config.h"
#include "RenderLayerCompositor.h"
#include "CSSAnimationController.h"
#include "CSSPropertyNames.h"
#include "CanvasRenderingContext.h"
#include "Chrome.h"
#include "ChromeClient.h"
#include "DocumentTimeline.h"
#include "Frame.h"
#include "FrameView.h"
#include "GraphicsLayer.h"
#include "HTMLCanvasElement.h"
#include "HTMLIFrameElement.h"
#include "HTMLNames.h"
#include "HitTestResult.h"
#include "InspectorInstrumentation.h"
#include "Logging.h"
#include "NodeList.h"
#include "Page.h"
#include "PageOverlayController.h"
#include "RenderEmbeddedObject.h"
#include "RenderFragmentedFlow.h"
#include "RenderFullScreen.h"
#include "RenderGeometryMap.h"
#include "RenderIFrame.h"
#include "RenderLayerBacking.h"
#include "RenderReplica.h"
#include "RenderVideo.h"
#include "RenderView.h"
#include "RuntimeEnabledFeatures.h"
#include "ScrollingConstraints.h"
#include "ScrollingCoordinator.h"
#include "Settings.h"
#include "TiledBacking.h"
#include "TransformState.h"
#include <wtf/MemoryPressureHandler.h>
#include <wtf/SetForScope.h>
#include <wtf/text/CString.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/TextStream.h>
#if PLATFORM(IOS_FAMILY)
#include "LegacyTileCache.h"
#include "RenderScrollbar.h"
#endif
#if PLATFORM(MAC)
#include "LocalDefaultSystemAppearance.h"
#endif
#if ENABLE(TREE_DEBUGGING)
#include "RenderTreeAsText.h"
#endif
#if ENABLE(3D_TRANSFORMS)
WEBCORE_EXPORT bool WebCoreHas3DRendering = true;
#endif
#if !PLATFORM(MAC) && !PLATFORM(IOS_FAMILY)
#define USE_COMPOSITING_FOR_SMALL_CANVASES 1
#endif
namespace WebCore {
#if !USE(COMPOSITING_FOR_SMALL_CANVASES)
static const int canvasAreaThresholdRequiringCompositing = 50 * 100;
#endif
#if PLATFORM(IOS_FAMILY)
static const Seconds throttledLayerFlushInitialDelay { 500_ms };
static const Seconds throttledLayerFlushDelay { 1.5_s };
#else
static const Seconds throttledLayerFlushInitialDelay { 500_ms };
static const Seconds throttledLayerFlushDelay { 500_ms };
#endif
using namespace HTMLNames;
class OverlapMapContainer {
public:
void add(const LayoutRect& bounds)
{
m_layerRects.append(bounds);
m_boundingBox.unite(bounds);
}
bool overlapsLayers(const LayoutRect& bounds) const
{
if (!bounds.intersects(m_boundingBox))
return false;
for (const auto& layerRect : m_layerRects) {
if (layerRect.intersects(bounds))
return true;
}
return false;
}
void unite(const OverlapMapContainer& otherContainer)
{
m_layerRects.appendVector(otherContainer.m_layerRects);
m_boundingBox.unite(otherContainer.m_boundingBox);
}
private:
Vector<LayoutRect> m_layerRects;
LayoutRect m_boundingBox;
};
class RenderLayerCompositor::OverlapMap {
WTF_MAKE_NONCOPYABLE(OverlapMap);
public:
OverlapMap()
: m_geometryMap(UseTransforms)
{
pushCompositingContainer();
}
void add(const LayoutRect& bounds)
{
ASSERT(m_overlapStack.size() >= 2);
m_overlapStack[m_overlapStack.size() - 2].add(bounds);
m_isEmpty = false;
}
bool overlapsLayers(const LayoutRect& bounds) const
{
return m_overlapStack.last().overlapsLayers(bounds);
}
bool isEmpty() const
{
return m_isEmpty;
}
void pushCompositingContainer()
{
m_overlapStack.append(OverlapMapContainer());
}
void popCompositingContainer()
{
m_overlapStack[m_overlapStack.size() - 2].unite(m_overlapStack.last());
m_overlapStack.removeLast();
}
const RenderGeometryMap& geometryMap() const { return m_geometryMap; }
RenderGeometryMap& geometryMap() { return m_geometryMap; }
private:
struct RectList {
Vector<LayoutRect> rects;
LayoutRect boundingRect;
void append(const LayoutRect& rect)
{
rects.append(rect);
boundingRect.unite(rect);
}
void append(const RectList& rectList)
{
rects.appendVector(rectList.rects);
boundingRect.unite(rectList.boundingRect);
}
bool intersects(const LayoutRect& rect) const
{
if (!rects.size() || !boundingRect.intersects(rect))
return false;
for (const auto& currentRect : rects) {
if (currentRect.intersects(rect))
return true;
}
return false;
}
};
Vector<OverlapMapContainer> m_overlapStack;
RenderGeometryMap m_geometryMap;
bool m_isEmpty { true };
};
struct RenderLayerCompositor::CompositingState {
CompositingState(RenderLayer* compAncestor, bool testOverlap = true)
: compositingAncestor(compAncestor)
, testingOverlap(testOverlap)
{
}
CompositingState(const CompositingState& other)
: compositingAncestor(other.compositingAncestor)
, subtreeIsCompositing(other.subtreeIsCompositing)
, testingOverlap(other.testingOverlap)
, fullPaintOrderTraversalRequired(other.fullPaintOrderTraversalRequired)
, descendantsRequireCompositingUpdate(other.descendantsRequireCompositingUpdate)
, ancestorHasTransformAnimation(other.ancestorHasTransformAnimation)
#if ENABLE(CSS_COMPOSITING)
, hasNotIsolatedCompositedBlendingDescendants(other.hasNotIsolatedCompositedBlendingDescendants)
#endif
#if ENABLE(TREE_DEBUGGING)
, depth(other.depth + 1)
#endif
{
}
RenderLayer* compositingAncestor;
bool subtreeIsCompositing { false };
bool testingOverlap { true };
bool fullPaintOrderTraversalRequired { false };
bool descendantsRequireCompositingUpdate { false };
bool ancestorHasTransformAnimation { false };
#if ENABLE(CSS_COMPOSITING)
bool hasNotIsolatedCompositedBlendingDescendants { false };
#endif
#if ENABLE(TREE_DEBUGGING)
int depth { 0 };
#endif
};
struct RenderLayerCompositor::OverlapExtent {
LayoutRect bounds;
bool extentComputed { false };
bool hasTransformAnimation { false };
bool animationCausesExtentUncertainty { false };
bool knownToBeHaveExtentUncertainty() const { return extentComputed && animationCausesExtentUncertainty; }
};
#if !LOG_DISABLED
static inline bool compositingLogEnabled()
{
return LogCompositing.state == WTFLogChannelOn;
}
#endif
RenderLayerCompositor::RenderLayerCompositor(RenderView& renderView)
: m_renderView(renderView)
, m_updateCompositingLayersTimer(*this, &RenderLayerCompositor::updateCompositingLayersTimerFired)
, m_layerFlushTimer(*this, &RenderLayerCompositor::layerFlushTimerFired)
{
#if PLATFORM(IOS_FAMILY)
if (m_renderView.frameView().platformWidget())
m_legacyScrollingLayerCoordinator = std::make_unique<LegacyWebKitScrollingLayerCoordinator>(page().chrome().client(), isMainFrameCompositor());
#endif
}
RenderLayerCompositor::~RenderLayerCompositor()
{
m_clipLayer = nullptr;
m_scrollLayer = nullptr;
ASSERT(m_rootLayerAttachment == RootLayerUnattached);
}
void RenderLayerCompositor::enableCompositingMode(bool enable )
{
if (enable != m_compositing) {
m_compositing = enable;
if (m_compositing) {
ensureRootLayer();
notifyIFramesOfCompositingChange();
} else
destroyRootLayer();
m_renderView.layer()->setNeedsPostLayoutCompositingUpdate();
}
}
void RenderLayerCompositor::cacheAcceleratedCompositingFlags()
{
auto& settings = m_renderView.settings();
bool hasAcceleratedCompositing = settings.acceleratedCompositingEnabled();
if (hasAcceleratedCompositing) {
m_compositingTriggers = page().chrome().client().allowedCompositingTriggers();
hasAcceleratedCompositing = m_compositingTriggers;
}
bool showDebugBorders = settings.showDebugBorders();
bool showRepaintCounter = settings.showRepaintCounter();
bool acceleratedDrawingEnabled = settings.acceleratedDrawingEnabled();
bool displayListDrawingEnabled = settings.displayListDrawingEnabled();
bool forceCompositingMode = m_forceCompositingMode;
if (isMainFrameCompositor())
forceCompositingMode = m_renderView.settings().forceCompositingMode() && hasAcceleratedCompositing;
if (hasAcceleratedCompositing != m_hasAcceleratedCompositing || showDebugBorders != m_showDebugBorders || showRepaintCounter != m_showRepaintCounter || forceCompositingMode != m_forceCompositingMode) {
if (auto* rootLayer = m_renderView.layer()) {
rootLayer->setNeedsCompositingConfigurationUpdate();
rootLayer->setDescendantsNeedUpdateBackingAndHierarchyTraversal();
}
}
bool debugBordersChanged = m_showDebugBorders != showDebugBorders;
m_hasAcceleratedCompositing = hasAcceleratedCompositing;
m_forceCompositingMode = forceCompositingMode;
m_showDebugBorders = showDebugBorders;
m_showRepaintCounter = showRepaintCounter;
m_acceleratedDrawingEnabled = acceleratedDrawingEnabled;
m_displayListDrawingEnabled = displayListDrawingEnabled;
if (debugBordersChanged) {
if (m_layerForHorizontalScrollbar)
m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
if (m_layerForVerticalScrollbar)
m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
if (m_layerForScrollCorner)
m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
}
if (updateCompositingPolicy())
rootRenderLayer().setDescendantsNeedCompositingRequirementsTraversal();
}
void RenderLayerCompositor::cacheAcceleratedCompositingFlagsAfterLayout()
{
cacheAcceleratedCompositingFlags();
if (isMainFrameCompositor())
return;
RequiresCompositingData queryData;
bool forceCompositingMode = m_hasAcceleratedCompositing && m_renderView.settings().forceCompositingMode() && requiresCompositingForScrollableFrame(queryData);
if (forceCompositingMode != m_forceCompositingMode) {
m_forceCompositingMode = forceCompositingMode;
rootRenderLayer().setDescendantsNeedCompositingRequirementsTraversal();
}
}
bool RenderLayerCompositor::updateCompositingPolicy()
{
if (!usesCompositing())
return false;
auto currentPolicy = m_compositingPolicy;
if (page().compositingPolicyOverride()) {
m_compositingPolicy = page().compositingPolicyOverride().value();
return m_compositingPolicy != currentPolicy;
}
auto memoryPolicy = MemoryPressureHandler::currentMemoryUsagePolicy();
m_compositingPolicy = memoryPolicy == WTF::MemoryUsagePolicy::Unrestricted ? CompositingPolicy::Normal : CompositingPolicy::Conservative;
return m_compositingPolicy != currentPolicy;
}
bool RenderLayerCompositor::canRender3DTransforms() const
{
return hasAcceleratedCompositing() && (m_compositingTriggers & ChromeClient::ThreeDTransformTrigger);
}
void RenderLayerCompositor::willRecalcStyle()
{
cacheAcceleratedCompositingFlags();
}
bool RenderLayerCompositor::didRecalcStyleWithNoPendingLayout()
{
return updateCompositingLayers(CompositingUpdateType::AfterStyleChange);
}
void RenderLayerCompositor::customPositionForVisibleRectComputation(const GraphicsLayer* graphicsLayer, FloatPoint& position) const
{
if (graphicsLayer != m_scrollLayer.get())
return;
FloatPoint scrollPosition = -position;
if (m_renderView.frameView().scrollBehaviorForFixedElements() == StickToDocumentBounds)
scrollPosition = m_renderView.frameView().constrainScrollPositionForOverhang(roundedIntPoint(scrollPosition));
position = -scrollPosition;
}
void RenderLayerCompositor::notifyFlushRequired(const GraphicsLayer* layer)
{
scheduleLayerFlush(layer->canThrottleLayerFlush());
}
void RenderLayerCompositor::scheduleLayerFlushNow()
{
m_hasPendingLayerFlush = false;
page().chrome().client().scheduleCompositingLayerFlush();
}
void RenderLayerCompositor::scheduleLayerFlush(bool canThrottle)
{
ASSERT(!m_flushingLayers);
if (canThrottle)
startInitialLayerFlushTimerIfNeeded();
if (canThrottle && isThrottlingLayerFlushes()) {
m_hasPendingLayerFlush = true;
return;
}
scheduleLayerFlushNow();
}
FloatRect RenderLayerCompositor::visibleRectForLayerFlushing() const
{
const FrameView& frameView = m_renderView.frameView();
#if PLATFORM(IOS_FAMILY)
return frameView.exposedContentRect();
#else
FloatRect visibleRect = m_clipLayer ? FloatRect({ }, frameView.sizeForVisibleContent()) : frameView.visibleContentRect();
if (frameView.viewExposedRect())
visibleRect.intersect(frameView.viewExposedRect().value());
return visibleRect;
#endif
}
void RenderLayerCompositor::flushPendingLayerChanges(bool isFlushRoot)
{
if (!isFlushRoot && rootLayerAttachment() == RootLayerAttachedViaEnclosingFrame)
return;
if (rootLayerAttachment() == RootLayerUnattached) {
#if PLATFORM(IOS_FAMILY)
startLayerFlushTimerIfNeeded();
#endif
m_shouldFlushOnReattach = true;
return;
}
auto& frameView = m_renderView.frameView();
AnimationUpdateBlock animationUpdateBlock(&frameView.frame().animation());
ASSERT(!m_flushingLayers);
{
SetForScope<bool> flushingLayersScope(m_flushingLayers, true);
if (auto* rootLayer = rootGraphicsLayer()) {
FloatRect visibleRect = visibleRectForLayerFlushing();
LOG_WITH_STREAM(Compositing, stream << "\nRenderLayerCompositor " << this << " flushPendingLayerChanges (is root " << isFlushRoot << ") visible rect " << visibleRect);
rootLayer->flushCompositingState(visibleRect);
}
ASSERT(m_flushingLayers);
}
updateScrollCoordinatedLayersAfterFlushIncludingSubframes();
#if PLATFORM(IOS_FAMILY)
if (isFlushRoot)
page().chrome().client().didFlushCompositingLayers();
#endif
++m_layerFlushCount;
startLayerFlushTimerIfNeeded();
}
void RenderLayerCompositor::updateScrollCoordinatedLayersAfterFlushIncludingSubframes()
{
updateScrollCoordinatedLayersAfterFlush();
auto& frame = m_renderView.frameView().frame();
for (Frame* subframe = frame.tree().firstChild(); subframe; subframe = subframe->tree().traverseNext(&frame)) {
auto* view = subframe->contentRenderer();
if (!view)
continue;
view->compositor().updateScrollCoordinatedLayersAfterFlush();
}
}
void RenderLayerCompositor::updateScrollCoordinatedLayersAfterFlush()
{
updateCustomLayersAfterFlush();
HashSet<RenderLayer*> layersNeedingUpdate;
std::swap(m_scrollCoordinatedLayersNeedingUpdate, layersNeedingUpdate);
for (auto* layer : layersNeedingUpdate)
updateScrollCoordinatedStatus(*layer, ScrollingNodeChangeFlags::Layer);
}
void RenderLayerCompositor::updateCustomLayersAfterFlush()
{
#if PLATFORM(IOS_FAMILY)
if (m_legacyScrollingLayerCoordinator) {
m_legacyScrollingLayerCoordinator->registerAllViewportConstrainedLayers(*this, m_scrollCoordinatedLayers);
m_legacyScrollingLayerCoordinator->registerScrollingLayersNeedingUpdate();
}
#endif
}
void RenderLayerCompositor::didFlushChangesForLayer(RenderLayer& layer, const GraphicsLayer* graphicsLayer)
{
if (m_scrollCoordinatedLayers.contains(&layer))
m_scrollCoordinatedLayersNeedingUpdate.add(&layer);
#if PLATFORM(IOS_FAMILY)
if (m_legacyScrollingLayerCoordinator)
m_legacyScrollingLayerCoordinator->didFlushChangesForLayer(layer);
#endif
auto* backing = layer.backing();
if (backing->backgroundLayerPaintsFixedRootBackground() && graphicsLayer == backing->backgroundLayer())
fixedRootBackgroundLayerChanged();
}
void RenderLayerCompositor::didPaintBacking(RenderLayerBacking*)
{
auto& frameView = m_renderView.frameView();
frameView.setLastPaintTime(MonotonicTime::now());
if (frameView.milestonesPendingPaint())
frameView.firePaintRelatedMilestonesIfNeeded();
}
void RenderLayerCompositor::didChangeVisibleRect()
{
auto* rootLayer = rootGraphicsLayer();
if (!rootLayer)
return;
FloatRect visibleRect = visibleRectForLayerFlushing();
bool requiresFlush = rootLayer->visibleRectChangeRequiresFlush(visibleRect);
LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor::didChangeVisibleRect " << visibleRect << " requiresFlush " << requiresFlush);
if (requiresFlush)
scheduleLayerFlushNow();
}
void RenderLayerCompositor::notifyFlushBeforeDisplayRefresh(const GraphicsLayer*)
{
if (!m_layerUpdater) {
PlatformDisplayID displayID = page().chrome().displayID();
m_layerUpdater = std::make_unique<GraphicsLayerUpdater>(*this, displayID);
}
m_layerUpdater->scheduleUpdate();
}
void RenderLayerCompositor::flushLayersSoon(GraphicsLayerUpdater&)
{
scheduleLayerFlush(true);
}
void RenderLayerCompositor::layerTiledBackingUsageChanged(const GraphicsLayer* graphicsLayer, bool usingTiledBacking)
{
if (usingTiledBacking) {
++m_layersWithTiledBackingCount;
graphicsLayer->tiledBacking()->setIsInWindow(page().isInWindow());
} else {
ASSERT(m_layersWithTiledBackingCount > 0);
--m_layersWithTiledBackingCount;
}
}
void RenderLayerCompositor::scheduleCompositingLayerUpdate()
{
if (!m_updateCompositingLayersTimer.isActive())
m_updateCompositingLayersTimer.startOneShot(0_s);
}
void RenderLayerCompositor::updateCompositingLayersTimerFired()
{
updateCompositingLayers(CompositingUpdateType::AfterLayout);
}
void RenderLayerCompositor::cancelCompositingLayerUpdate()
{
m_updateCompositingLayersTimer.stop();
}
bool RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType updateType, RenderLayer* updateRoot)
{
LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor " << this << " updateCompositingLayers " << updateType << " contentLayersCount " << m_contentLayersCount);
#if ENABLE(TREE_DEBUGGING)
if (compositingLogEnabled())
showPaintOrderTree(m_renderView.layer());
#endif
if (updateType == CompositingUpdateType::AfterStyleChange || updateType == CompositingUpdateType::AfterLayout)
cacheAcceleratedCompositingFlagsAfterLayout();
m_updateCompositingLayersTimer.stop();
ASSERT(m_renderView.document().pageCacheState() == Document::NotInPageCache);
if (!m_renderView.document().visualUpdatesAllowed())
return false;
if (m_renderView.needsLayout())
return false;
if (!m_compositing && (m_forceCompositingMode || (isMainFrameCompositor() && page().pageOverlayController().overlayCount())))
enableCompositingMode(true);
bool isPageScroll = !updateRoot || updateRoot == &rootRenderLayer();
updateRoot = &rootRenderLayer();
if (updateType == CompositingUpdateType::OnScroll || updateType == CompositingUpdateType::OnCompositedScroll) {
if (m_renderView.settings().acceleratedCompositingForFixedPositionEnabled() && isPageScroll) {
if (auto* viewportConstrainedObjects = m_renderView.frameView().viewportConstrainedObjects()) {
for (auto* renderer : *viewportConstrainedObjects) {
if (auto* layer = renderer->layer())
layer->setNeedsCompositingGeometryUpdate();
}
}
}
updateRoot->setDescendantsNeedCompositingRequirementsTraversal();
}
if (!updateRoot->hasDescendantNeedingCompositingRequirementsTraversal() && !m_compositing) {
LOG_WITH_STREAM(Compositing, stream << " no compositing work to do");
return true;
}
if (!updateRoot->needsAnyCompositingTraversal()) {
LOG_WITH_STREAM(Compositing, stream << " updateRoot has no dirty child and doesn't need update");
return true;
}
bool isFullUpdate = true;
++m_compositingUpdateCount;
AnimationUpdateBlock animationUpdateBlock(&m_renderView.frameView().frame().animation());
SetForScope<bool> postLayoutChange(m_inPostLayoutUpdate, true);
#if !LOG_DISABLED
MonotonicTime startTime;
if (compositingLogEnabled()) {
++m_rootLayerUpdateCount;
startTime = MonotonicTime::now();
}
if (compositingLogEnabled()) {
m_obligateCompositedLayerCount = 0;
m_secondaryCompositedLayerCount = 0;
m_obligatoryBackingStoreBytes = 0;
m_secondaryBackingStoreBytes = 0;
auto& frame = m_renderView.frameView().frame();
bool isMainFrame = isMainFrameCompositor();
LOG_WITH_STREAM(Compositing, stream << "\nUpdate " << m_rootLayerUpdateCount << " of " << (isMainFrame ? "main frame" : frame.tree().uniqueName().string().utf8().data()) << " - compositing policy is " << m_compositingPolicy);
}
#endif
if (updateRoot->hasDescendantNeedingCompositingRequirementsTraversal() || updateRoot->needsCompositingRequirementsTraversal()) {
CompositingState compositingState(updateRoot);
OverlapMap overlapMap;
bool descendantHas3DTransform = false;
computeCompositingRequirements(nullptr, rootRenderLayer(), overlapMap, compositingState, descendantHas3DTransform);
}
LOG(Compositing, "\nRenderLayerCompositor::updateCompositingLayers - mid");
#if ENABLE(TREE_DEBUGGING)
if (compositingLogEnabled())
showPaintOrderTree(m_renderView.layer());
#endif
if (updateRoot->hasDescendantNeedingUpdateBackingOrHierarchyTraversal() || updateRoot->needsUpdateBackingOrHierarchyTraversal()) {
Vector<Ref<GraphicsLayer>> childList;
updateBackingAndHierarchy(*updateRoot, childList);
if (isFullUpdate) {
appendDocumentOverlayLayers(childList);
if (childList.isEmpty() && !needsCompositingForContentOrOverlays())
destroyRootLayer();
else if (m_rootContentLayer)
m_rootContentLayer->setChildren(WTFMove(childList));
}
reattachSubframeScrollLayers();
}
#if !LOG_DISABLED
if (compositingLogEnabled()) {
MonotonicTime endTime = MonotonicTime::now();
LOG(Compositing, "Total layers primary secondary obligatory backing (KB) secondary backing(KB) total backing (KB) update time (ms)\n");
LOG(Compositing, "%8d %11d %9d %20.2f %22.2f %22.2f %18.2f\n",
m_obligateCompositedLayerCount + m_secondaryCompositedLayerCount, m_obligateCompositedLayerCount,
m_secondaryCompositedLayerCount, m_obligatoryBackingStoreBytes / 1024, m_secondaryBackingStoreBytes / 1024, (m_obligatoryBackingStoreBytes + m_secondaryBackingStoreBytes) / 1024, (endTime - startTime).milliseconds());
}
#endif
updateRootLayerPosition();
#if ENABLE(TREE_DEBUGGING)
if (compositingLogEnabled()) {
LOG(Compositing, "RenderLayerCompositor::updateCompositingLayers - post");
showPaintOrderTree(m_renderView.layer());
LOG(Compositing, "RenderLayerCompositor::updateCompositingLayers - GraphicsLayers post, contentLayersCount %d", m_contentLayersCount);
showGraphicsLayerTree(m_rootContentLayer.get());
}
#endif
InspectorInstrumentation::layerTreeDidChange(&page());
return true;
}
void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer& layer, OverlapMap& overlapMap, CompositingState& compositingState, bool& descendantHas3DTransform)
{
if (!layer.hasDescendantNeedingCompositingRequirementsTraversal() && !layer.needsCompositingRequirementsTraversal() && !compositingState.fullPaintOrderTraversalRequired && !compositingState.descendantsRequireCompositingUpdate) {
traverseUnchangedSubtree(ancestorLayer, layer, overlapMap, compositingState, descendantHas3DTransform);
return;
}
#if ENABLE(TREE_DEBUGGING)
LOG(Compositing, "%*p computeCompositingRequirements", 12 + compositingState.depth * 2, &layer);
#endif
compositingState.fullPaintOrderTraversalRequired |= layer.needsCompositingRequirementsTraversal();
compositingState.descendantsRequireCompositingUpdate |= layer.descendantsNeedCompositingRequirementsTraversal();
layer.updateDescendantDependentFlags();
layer.updateLayerListsIfNeeded();
layer.setHasCompositingDescendant(false);
RequiresCompositingData queryData;
bool willBeComposited = layer.isComposited();
if (layer.needsPostLayoutCompositingUpdate() || compositingState.fullPaintOrderTraversalRequired || compositingState.descendantsRequireCompositingUpdate) {
layer.setIndirectCompositingReason(RenderLayer::IndirectCompositingReason::None);
willBeComposited = needsToBeComposited(layer, queryData);
}
compositingState.fullPaintOrderTraversalRequired |= layer.subsequentLayersNeedCompositingRequirementsTraversal();
OverlapExtent layerExtent;
if (willBeComposited && !layer.isRenderViewLayer())
layerExtent.hasTransformAnimation = isRunningTransformAnimation(layer.renderer());
bool respectTransforms = !layerExtent.hasTransformAnimation;
overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer, respectTransforms);
RenderLayer::IndirectCompositingReason compositingReason = compositingState.subtreeIsCompositing ? RenderLayer::IndirectCompositingReason::Stacking : RenderLayer::IndirectCompositingReason::None;
if (!willBeComposited && !overlapMap.isEmpty() && compositingState.testingOverlap) {
computeExtent(overlapMap, layer, layerExtent);
compositingReason = overlapMap.overlapsLayers(layerExtent.bounds) ? RenderLayer::IndirectCompositingReason::Overlap : RenderLayer::IndirectCompositingReason::None;
}
#if ENABLE(VIDEO)
if (compositingState.compositingAncestor && compositingState.compositingAncestor->renderer().isVideo())
compositingReason = RenderLayer::IndirectCompositingReason::Overlap;
#endif
if (compositingReason != RenderLayer::IndirectCompositingReason::None)
layer.setIndirectCompositingReason(compositingReason);
if (!willBeComposited && layer.mustCompositeForIndirectReasons() && canBeComposited(layer))
willBeComposited = true;
CompositingState childState(compositingState);
childState.subtreeIsCompositing = false;
#if ENABLE(CSS_COMPOSITING)
childState.hasNotIsolatedCompositedBlendingDescendants = false;
#endif
if (willBeComposited) {
compositingState.subtreeIsCompositing = true;
childState.compositingAncestor = &layer;
overlapMap.pushCompositingContainer();
childState.testingOverlap = true;
computeExtent(overlapMap, layer, layerExtent);
childState.ancestorHasTransformAnimation |= layerExtent.hasTransformAnimation;
layerExtent.animationCausesExtentUncertainty |= layerExtent.hasTransformAnimation && compositingState.ancestorHasTransformAnimation;
}
#if !ASSERT_DISABLED
LayerListMutationDetector mutationChecker(layer);
#endif
bool anyDescendantHas3DTransform = false;
for (auto* childLayer : layer.negativeZOrderLayers()) {
computeCompositingRequirements(&layer, *childLayer, overlapMap, childState, anyDescendantHas3DTransform);
if (!willBeComposited && childState.subtreeIsCompositing) {
layer.setIndirectCompositingReason(RenderLayer::IndirectCompositingReason::BackgroundLayer);
childState.compositingAncestor = &layer;
overlapMap.pushCompositingContainer();
childState.testingOverlap = true;
willBeComposited = true;
}
}
for (auto* childLayer : layer.normalFlowLayers())
computeCompositingRequirements(&layer, *childLayer, overlapMap, childState, anyDescendantHas3DTransform);
for (auto* childLayer : layer.positiveZOrderLayers())
computeCompositingRequirements(&layer, *childLayer, overlapMap, childState, anyDescendantHas3DTransform);
if (layer.isRenderViewLayer()) {
if (usesCompositing() && m_hasAcceleratedCompositing)
willBeComposited = true;
}
if (childState.compositingAncestor && !childState.compositingAncestor->isRenderViewLayer())
addToOverlapMap(overlapMap, layer, layerExtent);
#if ENABLE(CSS_COMPOSITING)
layer.setHasNotIsolatedCompositedBlendingDescendants(childState.hasNotIsolatedCompositedBlendingDescendants);
ASSERT(!layer.hasNotIsolatedCompositedBlendingDescendants() || layer.hasNotIsolatedBlendingDescendants());
#endif
RenderLayer::IndirectCompositingReason indirectCompositingReason;
if (!willBeComposited && canBeComposited(layer)
&& requiresCompositingForIndirectReason(layer.renderer(), childState.subtreeIsCompositing, anyDescendantHas3DTransform, indirectCompositingReason)) {
layer.setIndirectCompositingReason(indirectCompositingReason);
childState.compositingAncestor = &layer;
overlapMap.pushCompositingContainer();
addToOverlapMapRecursive(overlapMap, layer);
willBeComposited = true;
}
if (layer.reflectionLayer()) {
layer.reflectionLayer()->setIndirectCompositingReason(willBeComposited ? RenderLayer::IndirectCompositingReason::Stacking : RenderLayer::IndirectCompositingReason::None);
}
compositingState.subtreeIsCompositing |= childState.subtreeIsCompositing;
compositingState.fullPaintOrderTraversalRequired |= childState.fullPaintOrderTraversalRequired;
layer.setHasCompositingDescendant(childState.subtreeIsCompositing);
bool isCompositedClippingLayer = canBeComposited(layer) && clipsCompositingDescendants(layer);
if ((!childState.testingOverlap && !isCompositedClippingLayer) || layerExtent.knownToBeHaveExtentUncertainty())
compositingState.testingOverlap = false;
if (isCompositedClippingLayer) {
if (!willBeComposited) {
childState.compositingAncestor = &layer;
overlapMap.pushCompositingContainer();
addToOverlapMapRecursive(overlapMap, layer);
willBeComposited = true;
}
}
#if ENABLE(CSS_COMPOSITING)
if ((willBeComposited && layer.hasBlendMode())
|| (layer.hasNotIsolatedCompositedBlendingDescendants() && !layer.isolatesCompositedBlending()))
compositingState.hasNotIsolatedCompositedBlendingDescendants = true;
#endif
if (childState.compositingAncestor == &layer && !layer.isRenderViewLayer())
overlapMap.popCompositingContainer();
RequiresCompositingData rootLayerQueryData;
if (layer.isRenderViewLayer() && !childState.subtreeIsCompositing && !requiresCompositingLayer(layer, rootLayerQueryData) && !m_forceCompositingMode && !needsCompositingForContentOrOverlays()) {
#if !PLATFORM(IOS_FAMILY)
enableCompositingMode(false);
willBeComposited = false;
#endif
}
ASSERT(willBeComposited == needsToBeComposited(layer, queryData));
if (updateBacking(layer, queryData, CompositingChangeRepaintNow, willBeComposited ? BackingRequired::Yes : BackingRequired::No)) {
layer.setNeedsCompositingLayerConnection();
layer.setChildrenNeedCompositingGeometryUpdate();
layer.setNeedsCompositingGeometryUpdateOnAncestors();
}
if (layer.reflectionLayer() && updateLayerCompositingState(*layer.reflectionLayer(), queryData, CompositingChangeRepaintNow))
layer.setNeedsCompositingLayerConnection();
descendantHas3DTransform |= anyDescendantHas3DTransform || layer.has3DTransform();
if (layer.needsCompositingPaintOrderChildrenUpdate()) {
layer.setChildrenNeedCompositingGeometryUpdate();
layer.setNeedsCompositingLayerConnection();
}
#if ENABLE(TREE_DEBUGGING)
LOG(Compositing, "%*p computeCompositingRequirements - willBeComposited %d", 12 + compositingState.depth * 2, &layer, willBeComposited);
#endif
layer.clearCompositingRequirementsTraversalState();
overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
}
void RenderLayerCompositor::traverseUnchangedSubtree(RenderLayer* ancestorLayer, RenderLayer& layer, OverlapMap& overlapMap, CompositingState& compositingState, bool& descendantHas3DTransform)
{
ASSERT(!compositingState.fullPaintOrderTraversalRequired);
ASSERT(!layer.hasDescendantNeedingCompositingRequirementsTraversal());
ASSERT(!layer.needsCompositingRequirementsTraversal());
#if ENABLE(TREE_DEBUGGING)
LOG(Compositing, "%*p traverseUnchangedSubtree", 12 + compositingState.depth * 2, &layer);
#endif
layer.updateDescendantDependentFlags();
layer.updateLayerListsIfNeeded();
bool layerIsComposited = layer.isComposited();
OverlapExtent layerExtent;
if (layerIsComposited && !layer.isRenderViewLayer())
layerExtent.hasTransformAnimation = isRunningTransformAnimation(layer.renderer());
bool respectTransforms = !layerExtent.hasTransformAnimation;
overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer, respectTransforms);
if (!layerIsComposited && !overlapMap.isEmpty() && compositingState.testingOverlap)
computeExtent(overlapMap, layer, layerExtent);
CompositingState childState(compositingState);
childState.subtreeIsCompositing = false;
#if ENABLE(CSS_COMPOSITING)
childState.hasNotIsolatedCompositedBlendingDescendants = false;
#endif
if (layerIsComposited) {
compositingState.subtreeIsCompositing = true;
childState.compositingAncestor = &layer;
overlapMap.pushCompositingContainer();
childState.testingOverlap = true;
computeExtent(overlapMap, layer, layerExtent);
childState.ancestorHasTransformAnimation |= layerExtent.hasTransformAnimation;
layerExtent.animationCausesExtentUncertainty |= layerExtent.hasTransformAnimation && compositingState.ancestorHasTransformAnimation;
}
#if !ASSERT_DISABLED
LayerListMutationDetector mutationChecker(layer);
#endif
bool anyDescendantHas3DTransform = false;
for (auto* childLayer : layer.negativeZOrderLayers()) {
traverseUnchangedSubtree(&layer, *childLayer, overlapMap, childState, anyDescendantHas3DTransform);
if (childState.subtreeIsCompositing)
ASSERT(layerIsComposited);
}
for (auto* childLayer : layer.normalFlowLayers())
traverseUnchangedSubtree(&layer, *childLayer, overlapMap, childState, anyDescendantHas3DTransform);
for (auto* childLayer : layer.positiveZOrderLayers())
traverseUnchangedSubtree(&layer, *childLayer, overlapMap, childState, anyDescendantHas3DTransform);
if (childState.compositingAncestor && !childState.compositingAncestor->isRenderViewLayer())
addToOverlapMap(overlapMap, layer, layerExtent);
if (childState.subtreeIsCompositing)
compositingState.subtreeIsCompositing = true;
ASSERT(layer.hasCompositingDescendant() == childState.subtreeIsCompositing);
bool isCompositedClippingLayer = canBeComposited(layer) && clipsCompositingDescendants(layer);
if ((!childState.testingOverlap && !isCompositedClippingLayer) || layerExtent.knownToBeHaveExtentUncertainty())
compositingState.testingOverlap = false;
if (isCompositedClippingLayer)
ASSERT(layerIsComposited);
#if ENABLE(CSS_COMPOSITING)
if ((layerIsComposited && layer.hasBlendMode())
|| (layer.hasNotIsolatedCompositedBlendingDescendants() && !layer.isolatesCompositedBlending()))
compositingState.hasNotIsolatedCompositedBlendingDescendants = true;
#endif
if (childState.compositingAncestor == &layer && !layer.isRenderViewLayer())
overlapMap.popCompositingContainer();
descendantHas3DTransform |= anyDescendantHas3DTransform || layer.has3DTransform();
ASSERT(!layer.needsCompositingRequirementsTraversal());
overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
}
void RenderLayerCompositor::updateBackingAndHierarchy(RenderLayer& layer, Vector<Ref<GraphicsLayer>>& childLayersOfEnclosingLayer, OptionSet<UpdateLevel> updateLevel, int depth)
{
layer.updateDescendantDependentFlags();
layer.updateLayerListsIfNeeded();
bool layerNeedsUpdate = !updateLevel.isEmpty();
if (layer.descendantsNeedUpdateBackingAndHierarchyTraversal())
updateLevel.add(UpdateLevel::AllDescendants);
auto* layerBacking = layer.backing();
if (layerBacking) {
updateLevel.remove(UpdateLevel::CompositedChildren);
if (layerBacking->updateCompositedBounds()) {
layer.setNeedsCompositingGeometryUpdate();
updateLevel.add(UpdateLevel::CompositedChildren);
}
if (layerNeedsUpdate || layer.needsCompositingConfigurationUpdate()) {
if (layerBacking->updateConfiguration()) {
layerNeedsUpdate = true; layer.setNeedsCompositingLayerConnection();
}
layerBacking->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
}
if (layerNeedsUpdate || layer.needsCompositingGeometryUpdate())
layerBacking->updateGeometry();
if (auto* reflection = layer.reflectionLayer()) {
if (auto* reflectionBacking = reflection->backing()) {
reflectionBacking->updateCompositedBounds();
reflectionBacking->updateGeometry();
reflectionBacking->updateAfterDescendants();
}
}
if (!layer.parent())
updateRootLayerPosition();
#if !LOG_DISABLED
logLayerInfo(layer, "updateBackingAndHierarchy", depth);
#else
UNUSED_PARAM(depth);
#endif
}
if (layer.childrenNeedCompositingGeometryUpdate())
updateLevel.add(UpdateLevel::CompositedChildren);
Vector<Ref<GraphicsLayer>> layerChildren;
auto& childList = layerBacking ? layerChildren : childLayersOfEnclosingLayer;
bool requireDescendantTraversal = layer.hasDescendantNeedingUpdateBackingOrHierarchyTraversal()
|| (layer.hasCompositingDescendant() && (!layerBacking || layer.needsCompositingLayerConnection() || !updateLevel.isEmpty()));
bool requiresChildRebuild = layerBacking && layer.needsCompositingLayerConnection() && !layer.hasCompositingDescendant();
#if !ASSERT_DISABLED
LayerListMutationDetector mutationChecker(layer);
#endif
auto appendForegroundLayerIfNecessary = [&] () {
if (layer.negativeZOrderLayers().size()) {
if (layerBacking && layerBacking->foregroundLayer())
childList.append(*layerBacking->foregroundLayer());
}
};
if (requireDescendantTraversal) {
for (auto* renderLayer : layer.negativeZOrderLayers())
updateBackingAndHierarchy(*renderLayer, childList, updateLevel, depth + 1);
appendForegroundLayerIfNecessary();
for (auto* renderLayer : layer.normalFlowLayers())
updateBackingAndHierarchy(*renderLayer, childList, updateLevel, depth + 1);
for (auto* renderLayer : layer.positiveZOrderLayers())
updateBackingAndHierarchy(*renderLayer, childList, updateLevel, depth + 1);
} else if (requiresChildRebuild)
appendForegroundLayerIfNecessary();
if (layerBacking) {
if (requireDescendantTraversal || requiresChildRebuild) {
bool parented = false;
if (is<RenderWidget>(layer.renderer()))
parented = parentFrameContentLayers(&downcast<RenderWidget>(layer.renderer()));
if (!parented)
layerBacking->parentForSublayers()->setChildren(WTFMove(layerChildren));
if (!layerBacking->hasClippingLayer() && !layerBacking->hasScrollingLayer()) {
if (auto* overflowControlLayer = layerBacking->layerForHorizontalScrollbar())
layerBacking->parentForSublayers()->addChild(*overflowControlLayer);
if (auto* overflowControlLayer = layerBacking->layerForVerticalScrollbar())
layerBacking->parentForSublayers()->addChild(*overflowControlLayer);
if (auto* overflowControlLayer = layerBacking->layerForScrollCorner())
layerBacking->parentForSublayers()->addChild(*overflowControlLayer);
}
}
childLayersOfEnclosingLayer.append(*layerBacking->childForSuperlayers());
layerBacking->updateAfterDescendants();
}
layer.clearUpdateBackingOrHierarchyTraversalState();
}
void RenderLayerCompositor::appendDocumentOverlayLayers(Vector<Ref<GraphicsLayer>>& childList)
{
if (!isMainFrameCompositor() || !m_compositing)
return;
Ref<GraphicsLayer> overlayHost = page().pageOverlayController().layerWithDocumentOverlays();
childList.append(WTFMove(overlayHost));
}
bool RenderLayerCompositor::needsCompositingForContentOrOverlays() const
{
return m_contentLayersCount + page().pageOverlayController().overlayCount();
}
void RenderLayerCompositor::layerBecameComposited(const RenderLayer& layer)
{
if (&layer != m_renderView.layer())
++m_contentLayersCount;
}
void RenderLayerCompositor::layerBecameNonComposited(const RenderLayer& layer)
{
InspectorInstrumentation::renderLayerDestroyed(&page(), layer);
if (&layer != m_renderView.layer()) {
ASSERT(m_contentLayersCount > 0);
--m_contentLayersCount;
}
}
#if !LOG_DISABLED
void RenderLayerCompositor::logLayerInfo(const RenderLayer& layer, const char* phase, int depth)
{
if (!compositingLogEnabled())
return;
auto* backing = layer.backing();
RequiresCompositingData queryData;
if (requiresCompositingLayer(layer, queryData) || layer.isRenderViewLayer()) {
++m_obligateCompositedLayerCount;
m_obligatoryBackingStoreBytes += backing->backingStoreMemoryEstimate();
} else {
++m_secondaryCompositedLayerCount;
m_secondaryBackingStoreBytes += backing->backingStoreMemoryEstimate();
}
LayoutRect absoluteBounds = backing->compositedBounds();
absoluteBounds.move(layer.offsetFromAncestor(m_renderView.layer()));
StringBuilder logString;
logString.append(String::format("%*p id %" PRIu64 " (%.3f,%.3f-%.3f,%.3f) %.2fKB", 12 + depth * 2, &layer, backing->graphicsLayer()->primaryLayerID(),
absoluteBounds.x().toFloat(), absoluteBounds.y().toFloat(), absoluteBounds.maxX().toFloat(), absoluteBounds.maxY().toFloat(),
backing->backingStoreMemoryEstimate() / 1024));
if (!layer.renderer().style().hasAutoZIndex())
logString.append(String::format(" z-index: %d", layer.renderer().style().zIndex()));
logString.appendLiteral(" (");
logString.append(logReasonsForCompositing(layer));
logString.appendLiteral(") ");
if (backing->graphicsLayer()->contentsOpaque() || backing->paintsIntoCompositedAncestor() || backing->foregroundLayer() || backing->backgroundLayer()) {
logString.append('[');
bool prependSpace = false;
if (backing->graphicsLayer()->contentsOpaque()) {
logString.appendLiteral("opaque");
prependSpace = true;
}
if (backing->paintsIntoCompositedAncestor()) {
if (prependSpace)
logString.appendLiteral(", ");
logString.appendLiteral("paints into ancestor");
prependSpace = true;
}
if (backing->foregroundLayer() || backing->backgroundLayer()) {
if (prependSpace)
logString.appendLiteral(", ");
if (backing->foregroundLayer() && backing->backgroundLayer()) {
logString.appendLiteral("+foreground+background");
prependSpace = true;
} else if (backing->foregroundLayer()) {
logString.appendLiteral("+foreground");
prependSpace = true;
} else {
logString.appendLiteral("+background");
prependSpace = true;
}
}
if (backing->paintsSubpixelAntialiasedText()) {
if (prependSpace)
logString.appendLiteral(", ");
logString.appendLiteral("texty");
}
logString.appendLiteral("] ");
}
logString.append(layer.name());
logString.appendLiteral(" - ");
logString.append(phase);
LOG(Compositing, "%s", logString.toString().utf8().data());
}
#endif
static bool clippingChanged(const RenderStyle& oldStyle, const RenderStyle& newStyle)
{
return oldStyle.overflowX() != newStyle.overflowX() || oldStyle.overflowY() != newStyle.overflowY()
|| oldStyle.hasClip() != newStyle.hasClip() || oldStyle.clip() != newStyle.clip();
}
static bool styleAffectsLayerGeometry(const RenderStyle& style)
{
return style.hasClip() || style.clipPath() || style.hasBorderRadius();
}
void RenderLayerCompositor::layerStyleChanged(StyleDifference diff, RenderLayer& layer, const RenderStyle* oldStyle)
{
if (diff == StyleDifference::Equal)
return;
RequiresCompositingData queryData;
queryData.layoutUpToDate = LayoutUpToDate::No;
bool layerChanged = updateBacking(layer, queryData, CompositingChangeRepaintNow);
if (layerChanged) {
layer.setChildrenNeedCompositingGeometryUpdate();
layer.setNeedsCompositingLayerConnection();
layer.setSubsequentLayersNeedCompositingRequirementsTraversal();
layer.setNeedsPostLayoutCompositingUpdateOnAncestors();
}
if (queryData.reevaluateAfterLayout)
layer.setNeedsPostLayoutCompositingUpdate();
if (diff >= StyleDifference::LayoutPositionedMovementOnly && hasContentCompositingLayers()) {
layer.setNeedsPostLayoutCompositingUpdate();
layer.setNeedsCompositingGeometryUpdate();
}
auto* backing = layer.backing();
if (!backing)
return;
backing->updateConfigurationAfterStyleChange();
const auto& newStyle = layer.renderer().style();
if (diff >= StyleDifference::Repaint) {
if (oldStyle && oldStyle->visibility() != newStyle.visibility())
layer.setNeedsCompositingGeometryUpdate();
if (layer.isComposited() && oldStyle) {
if (styleAffectsLayerGeometry(*oldStyle) || styleAffectsLayerGeometry(newStyle))
layer.setNeedsCompositingGeometryUpdate();
}
}
if (diff == StyleDifference::RecompositeLayer && layer.isComposited() && is<RenderWidget>(layer.renderer()))
layer.setNeedsCompositingConfigurationUpdate();
if (diff >= StyleDifference::RecompositeLayer && oldStyle) {
if (oldStyle->transform() != newStyle.transform()) {
layer.setNeedsPostLayoutCompositingUpdate();
layer.setNeedsCompositingGeometryUpdate();
}
}
if (diff >= StyleDifference::Layout) {
if (oldStyle && clippingChanged(*oldStyle, newStyle)) {
if (layer.isStackingContext()) {
layer.setNeedsPostLayoutCompositingUpdate(); layer.setNeedsCompositingConfigurationUpdate(); } else {
if (auto* stackingContext = layer.stackingContext())
stackingContext->setDescendantsNeedUpdateBackingAndHierarchyTraversal();
}
}
if (oldStyle && styleChangeMayAffectIndirectCompositingReasons(*oldStyle, newStyle))
layer.setNeedsPostLayoutCompositingUpdate();
layer.setNeedsCompositingGeometryUpdate();
}
}
bool RenderLayerCompositor::needsCompositingUpdateForStyleChangeOnNonCompositedLayer(RenderLayer& layer, const RenderStyle* oldStyle) const
{
if (layer.isRenderViewLayer())
return true;
if (!oldStyle)
return false;
const RenderStyle& newStyle = layer.renderer().style();
if (oldStyle->visibility() != newStyle.visibility())
return true;
if (styleChangeMayAffectIndirectCompositingReasons(*oldStyle, newStyle))
return true;
return false;
}
bool RenderLayerCompositor::canCompositeClipPath(const RenderLayer& layer)
{
ASSERT(layer.isComposited());
ASSERT(layer.renderer().style().clipPath());
if (layer.renderer().hasMask())
return false;
auto& clipPath = *layer.renderer().style().clipPath();
return (clipPath.type() != ClipPathOperation::Shape || clipPath.type() == ClipPathOperation::Shape) && GraphicsLayer::supportsLayerType(GraphicsLayer::Type::Shape);
}
static RenderLayerModelObject& rendererForCompositingTests(const RenderLayer& layer)
{
auto* renderer = &layer.renderer();
if (layer.isReflection())
renderer = downcast<RenderLayerModelObject>(renderer->parent());
return *renderer;
}
void RenderLayerCompositor::updateRootContentLayerClipping()
{
m_rootContentLayer->setMasksToBounds(!m_renderView.settings().backgroundShouldExtendBeyondPage());
}
bool RenderLayerCompositor::updateBacking(RenderLayer& layer, RequiresCompositingData& queryData, CompositingChangeRepaint shouldRepaint, BackingRequired backingRequired)
{
bool layerChanged = false;
if (backingRequired == BackingRequired::Unknown)
backingRequired = needsToBeComposited(layer, queryData) ? BackingRequired::Yes : BackingRequired::No;
else {
requiresCompositingForPosition(rendererForCompositingTests(layer), layer, queryData);
}
if (backingRequired == BackingRequired::Yes) {
enableCompositingMode();
if (!layer.backing()) {
if (shouldRepaint == CompositingChangeRepaintNow)
repaintOnCompositingChange(layer);
layer.ensureBacking();
if (layer.isRenderViewLayer() && useCoordinatedScrollingForLayer(layer)) {
updateScrollCoordinatedStatus(layer, { ScrollingNodeChangeFlags::Layer, ScrollingNodeChangeFlags::LayerGeometry });
if (auto* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
#if ENABLE(RUBBER_BANDING)
updateLayerForHeader(page().headerHeight());
updateLayerForFooter(page().footerHeight());
#endif
updateRootContentLayerClipping();
if (auto* tiledBacking = layer.backing()->tiledBacking())
tiledBacking->setTopContentInset(m_renderView.frameView().topContentInset());
}
if (layer.parent())
layer.computeRepaintRectsIncludingDescendants();
layer.setNeedsCompositingGeometryUpdate();
layer.setNeedsCompositingConfigurationUpdate();
layer.setNeedsCompositingPaintOrderChildrenUpdate();
layerChanged = true;
}
} else {
if (layer.backing()) {
if (layer.isReflection()) {
auto* sourceLayer = downcast<RenderLayerModelObject>(*layer.renderer().parent()).layer();
if (auto* backing = sourceLayer->backing()) {
ASSERT(backing->graphicsLayer()->replicaLayer() == layer.backing()->graphicsLayer());
backing->graphicsLayer()->setReplicatedByLayer(nullptr);
}
}
removeFromScrollCoordinatedLayers(layer);
layer.clearBacking();
layerChanged = true;
layer.computeRepaintRectsIncludingDescendants();
if (shouldRepaint == CompositingChangeRepaintNow)
repaintOnCompositingChange(layer);
}
}
#if ENABLE(VIDEO)
if (layerChanged && is<RenderVideo>(layer.renderer())) {
downcast<RenderVideo>(layer.renderer()).acceleratedRenderingStateChanged();
}
#endif
if (layerChanged && is<RenderWidget>(layer.renderer())) {
auto* innerCompositor = frameContentsCompositor(&downcast<RenderWidget>(layer.renderer()));
if (innerCompositor && innerCompositor->usesCompositing())
innerCompositor->updateRootLayerAttachment();
}
if (layerChanged)
layer.clearClipRectsIncludingDescendants(PaintingClipRects);
if (layer.renderer().isFixedPositioned()) {
if (layer.viewportConstrainedNotCompositedReason() != queryData.nonCompositedForPositionReason) {
layer.setViewportConstrainedNotCompositedReason(queryData.nonCompositedForPositionReason);
layerChanged = true;
}
if (layerChanged) {
if (auto* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewFixedObjectsDidChange(m_renderView.frameView());
}
} else
layer.setViewportConstrainedNotCompositedReason(RenderLayer::NoNotCompositedReason);
if (layer.backing())
layer.backing()->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
return layerChanged;
}
bool RenderLayerCompositor::updateLayerCompositingState(RenderLayer& layer, RequiresCompositingData& queryData, CompositingChangeRepaint shouldRepaint)
{
bool layerChanged = updateBacking(layer, queryData, shouldRepaint);
if (layer.backing() && layer.backing()->updateConfiguration())
layerChanged = true;
return layerChanged;
}
void RenderLayerCompositor::repaintOnCompositingChange(RenderLayer& layer)
{
if (&layer.renderer() != &m_renderView && !layer.renderer().parent())
return;
auto* repaintContainer = layer.renderer().containerForRepaint();
if (!repaintContainer)
repaintContainer = &m_renderView;
layer.repaintIncludingNonCompositingDescendants(repaintContainer);
if (repaintContainer == &m_renderView) {
m_renderView.frameView().setNeedsOneShotDrawingSynchronization();
}
}
void RenderLayerCompositor::repaintInCompositedAncestor(RenderLayer& layer, const LayoutRect& rect)
{
auto* compositedAncestor = layer.enclosingCompositingLayerForRepaint(ExcludeSelf);
if (!compositedAncestor)
return;
ASSERT(compositedAncestor->backing());
LayoutRect repaintRect = rect;
repaintRect.move(layer.offsetFromAncestor(compositedAncestor));
compositedAncestor->setBackingNeedsRepaintInRect(repaintRect);
if (compositedAncestor->isRenderViewLayer())
m_renderView.frameView().setNeedsOneShotDrawingSynchronization();
}
void RenderLayerCompositor::layerWasAdded(RenderLayer&, RenderLayer&)
{
}
void RenderLayerCompositor::layerWillBeRemoved(RenderLayer& parent, RenderLayer& child)
{
if (!child.isComposited() || parent.renderer().renderTreeBeingDestroyed())
return;
removeFromScrollCoordinatedLayers(child);
repaintInCompositedAncestor(child, child.backing()->compositedBounds());
setCompositingParent(child, nullptr);
child.setNeedsCompositingLayerConnection();
}
RenderLayer* RenderLayerCompositor::enclosingNonStackingClippingLayer(const RenderLayer& layer) const
{
for (auto* parent = layer.parent(); parent; parent = parent->parent()) {
if (parent->isStackingContext())
return nullptr;
if (parent->renderer().hasClipOrOverflowClip())
return parent;
}
return nullptr;
}
void RenderLayerCompositor::computeExtent(const OverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& extent) const
{
if (extent.extentComputed)
return;
LayoutRect layerBounds;
if (extent.hasTransformAnimation)
extent.animationCausesExtentUncertainty = !layer.getOverlapBoundsIncludingChildrenAccountingForTransformAnimations(layerBounds);
else
layerBounds = layer.overlapBounds();
extent.bounds = enclosingLayoutRect(overlapMap.geometryMap().absoluteRect(layerBounds));
if (extent.bounds.isEmpty())
extent.bounds.setSize(LayoutSize(1, 1));
RenderLayerModelObject& renderer = layer.renderer();
if (renderer.isFixedPositioned() && renderer.container() == &m_renderView) {
extent.bounds = m_renderView.frameView().fixedScrollableAreaBoundsInflatedForScrolling(extent.bounds);
}
extent.extentComputed = true;
}
void RenderLayerCompositor::addToOverlapMap(OverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& extent)
{
if (layer.isRenderViewLayer())
return;
computeExtent(overlapMap, layer, extent);
LayoutRect clipRect = layer.backgroundClipRect(RenderLayer::ClipRectsContext(&rootRenderLayer(), AbsoluteClipRects)).rect();
if (!m_renderView.settings().delegatesPageScaling())
clipRect.scale(pageScaleFactor());
clipRect.intersect(extent.bounds);
overlapMap.add(clipRect);
}
void RenderLayerCompositor::addToOverlapMapRecursive(OverlapMap& overlapMap, const RenderLayer& layer, const RenderLayer* ancestorLayer)
{
if (!canBeComposited(layer))
return;
if (ancestorLayer)
overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer);
OverlapExtent layerExtent;
addToOverlapMap(overlapMap, layer, layerExtent);
#if !ASSERT_DISABLED
LayerListMutationDetector mutationChecker(const_cast<RenderLayer&>(layer));
#endif
for (auto* renderLayer : layer.negativeZOrderLayers())
addToOverlapMapRecursive(overlapMap, *renderLayer, &layer);
for (auto* renderLayer : layer.normalFlowLayers())
addToOverlapMapRecursive(overlapMap, *renderLayer, &layer);
for (auto* renderLayer : layer.positiveZOrderLayers())
addToOverlapMapRecursive(overlapMap, *renderLayer, &layer);
if (ancestorLayer)
overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
}
void RenderLayerCompositor::setCompositingParent(RenderLayer& childLayer, RenderLayer* parentLayer)
{
ASSERT(!parentLayer || childLayer.ancestorCompositingLayer() == parentLayer);
ASSERT(childLayer.isComposited());
if (!parentLayer || !parentLayer->isComposited())
return;
if (parentLayer) {
auto* hostingLayer = parentLayer->backing()->parentForSublayers();
auto* hostedLayer = childLayer.backing()->childForSuperlayers();
hostingLayer->addChild(*hostedLayer);
} else
childLayer.backing()->childForSuperlayers()->removeFromParent();
}
void RenderLayerCompositor::removeCompositedChildren(RenderLayer& layer)
{
ASSERT(layer.isComposited());
layer.backing()->parentForSublayers()->removeAllChildren();
}
#if ENABLE(VIDEO)
bool RenderLayerCompositor::canAccelerateVideoRendering(RenderVideo& video) const
{
if (!m_hasAcceleratedCompositing)
return false;
return video.supportsAcceleratedRendering();
}
#endif
void RenderLayerCompositor::frameViewDidChangeLocation(const IntPoint& contentsOffset)
{
if (m_overflowControlsHostLayer)
m_overflowControlsHostLayer->setPosition(contentsOffset);
}
void RenderLayerCompositor::frameViewDidChangeSize()
{
if (auto* layer = m_renderView.layer())
layer->setNeedsCompositingGeometryUpdate();
if (m_clipLayer) {
const FrameView& frameView = m_renderView.frameView();
m_clipLayer->setSize(frameView.sizeForVisibleContent());
m_clipLayer->setPosition(positionForClipLayer());
frameViewDidScroll();
updateOverflowControlsLayers();
#if ENABLE(RUBBER_BANDING)
if (m_layerForOverhangAreas) {
m_layerForOverhangAreas->setSize(frameView.frameRect().size());
m_layerForOverhangAreas->setPosition(FloatPoint(0, m_renderView.frameView().topContentInset()));
}
#endif
}
}
bool RenderLayerCompositor::hasCoordinatedScrolling() const
{
auto* scrollingCoordinator = this->scrollingCoordinator();
return scrollingCoordinator && scrollingCoordinator->coordinatesScrollingForFrameView(m_renderView.frameView());
}
void RenderLayerCompositor::updateScrollLayerPosition()
{
ASSERT(m_scrollLayer);
auto& frameView = m_renderView.frameView();
IntPoint scrollPosition = frameView.scrollPosition();
m_scrollLayer->setPosition(FloatPoint(-scrollPosition.x(), -scrollPosition.y()));
if (auto* fixedBackgroundLayer = fixedRootBackgroundLayer())
fixedBackgroundLayer->setPosition(frameView.scrollPositionForFixedPosition());
}
FloatPoint RenderLayerCompositor::positionForClipLayer() const
{
auto& frameView = m_renderView.frameView();
return FloatPoint(
frameView.shouldPlaceBlockDirectionScrollbarOnLeft() ? frameView.horizontalScrollbarIntrusion() : 0,
FrameView::yPositionForInsetClipLayer(frameView.scrollPosition(), frameView.topContentInset()));
}
void RenderLayerCompositor::frameViewDidScroll()
{
if (!m_scrollLayer)
return;
if (hasCoordinatedScrolling()) {
scheduleLayerFlushNow();
return;
}
updateScrollLayerPosition();
}
void RenderLayerCompositor::frameViewDidAddOrRemoveScrollbars()
{
updateOverflowControlsLayers();
}
void RenderLayerCompositor::frameViewDidLayout()
{
if (auto* renderViewBacking = m_renderView.layer()->backing())
renderViewBacking->adjustTiledBackingCoverage();
}
void RenderLayerCompositor::rootLayerConfigurationChanged()
{
auto* renderViewBacking = m_renderView.layer()->backing();
if (renderViewBacking && renderViewBacking->isFrameLayerWithTiledBacking()) {
m_renderView.layer()->setNeedsCompositingConfigurationUpdate();
scheduleCompositingLayerUpdate();
}
}
void RenderLayerCompositor::scrollingLayerDidChange(RenderLayer& layer)
{
if (auto* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->scrollableAreaScrollLayerDidChange(layer);
}
void RenderLayerCompositor::fixedRootBackgroundLayerChanged()
{
if (m_renderView.renderTreeBeingDestroyed())
return;
if (m_renderView.layer()->isComposited())
updateScrollCoordinatedStatus(*m_renderView.layer(), ScrollingNodeChangeFlags::Layer);
}
String RenderLayerCompositor::layerTreeAsText(LayerTreeFlags flags)
{
updateCompositingLayers(CompositingUpdateType::AfterLayout);
if (!m_rootContentLayer)
return String();
flushPendingLayerChanges(true);
LayerTreeAsTextBehavior layerTreeBehavior = LayerTreeAsTextBehaviorNormal;
if (flags & LayerTreeFlagsIncludeDebugInfo)
layerTreeBehavior |= LayerTreeAsTextDebug;
if (flags & LayerTreeFlagsIncludeVisibleRects)
layerTreeBehavior |= LayerTreeAsTextIncludeVisibleRects;
if (flags & LayerTreeFlagsIncludeTileCaches)
layerTreeBehavior |= LayerTreeAsTextIncludeTileCaches;
if (flags & LayerTreeFlagsIncludeRepaintRects)
layerTreeBehavior |= LayerTreeAsTextIncludeRepaintRects;
if (flags & LayerTreeFlagsIncludePaintingPhases)
layerTreeBehavior |= LayerTreeAsTextIncludePaintingPhases;
if (flags & LayerTreeFlagsIncludeContentLayers)
layerTreeBehavior |= LayerTreeAsTextIncludeContentLayers;
if (flags & LayerTreeFlagsIncludeAcceleratesDrawing)
layerTreeBehavior |= LayerTreeAsTextIncludeAcceleratesDrawing;
if (flags & LayerTreeFlagsIncludeBackingStoreAttached)
layerTreeBehavior |= LayerTreeAsTextIncludeBackingStoreAttached;
if (flags & LayerTreeFlagsIncludeRootLayerProperties)
layerTreeBehavior |= LayerTreeAsTextIncludeRootLayerProperties;
String layerTreeText = m_rootContentLayer->layerTreeAsText(layerTreeBehavior);
if (!hasContentCompositingLayers() && documentUsesTiledBacking() && !(layerTreeBehavior & LayerTreeAsTextIncludeTileCaches) && !(layerTreeBehavior & LayerTreeAsTextIncludeRootLayerProperties))
layerTreeText = emptyString();
if (flags & LayerTreeFlagsIncludeRepaintRects)
return m_renderView.frameView().trackedRepaintRectsAsText() + layerTreeText;
return layerTreeText;
}
RenderLayerCompositor* RenderLayerCompositor::frameContentsCompositor(RenderWidget* renderer)
{
if (auto* contentDocument = renderer->frameOwnerElement().contentDocument()) {
if (auto* view = contentDocument->renderView())
return &view->compositor();
}
return nullptr;
}
bool RenderLayerCompositor::parentFrameContentLayers(RenderWidget* renderer)
{
auto* innerCompositor = frameContentsCompositor(renderer);
if (!innerCompositor || !innerCompositor->usesCompositing() || innerCompositor->rootLayerAttachment() != RootLayerAttachedViaEnclosingFrame)
return false;
auto* layer = renderer->layer();
if (!layer->isComposited())
return false;
auto* backing = layer->backing();
auto* hostingLayer = backing->parentForSublayers();
auto* rootLayer = innerCompositor->rootGraphicsLayer();
if (hostingLayer->children().size() != 1 || hostingLayer->children()[0].ptr() != rootLayer) {
hostingLayer->removeAllChildren();
hostingLayer->addChild(*rootLayer);
}
return true;
}
void RenderLayerCompositor::repaintCompositedLayers()
{
recursiveRepaintLayer(rootRenderLayer());
}
void RenderLayerCompositor::recursiveRepaintLayer(RenderLayer& layer)
{
layer.updateLayerListsIfNeeded();
if (layer.isComposited() && !layer.backing()->paintsIntoCompositedAncestor())
layer.setBackingNeedsRepaint();
#if !ASSERT_DISABLED
LayerListMutationDetector mutationChecker(layer);
#endif
if (layer.hasCompositingDescendant()) {
for (auto* renderLayer : layer.negativeZOrderLayers())
recursiveRepaintLayer(*renderLayer);
for (auto* renderLayer : layer.positiveZOrderLayers())
recursiveRepaintLayer(*renderLayer);
}
for (auto* renderLayer : layer.normalFlowLayers())
recursiveRepaintLayer(*renderLayer);
}
RenderLayer& RenderLayerCompositor::rootRenderLayer() const
{
return *m_renderView.layer();
}
GraphicsLayer* RenderLayerCompositor::rootGraphicsLayer() const
{
if (m_overflowControlsHostLayer)
return m_overflowControlsHostLayer.get();
return m_rootContentLayer.get();
}
void RenderLayerCompositor::setIsInWindow(bool isInWindow)
{
LOG(Compositing, "RenderLayerCompositor %p setIsInWindow %d", this, isInWindow);
if (!usesCompositing())
return;
if (auto* rootLayer = rootGraphicsLayer()) {
GraphicsLayer::traverse(*rootLayer, [isInWindow](GraphicsLayer& layer) {
layer.setIsInWindow(isInWindow);
});
}
if (isInWindow) {
if (m_rootLayerAttachment != RootLayerUnattached)
return;
RootLayerAttachment attachment = isMainFrameCompositor() ? RootLayerAttachedViaChromeClient : RootLayerAttachedViaEnclosingFrame;
attachRootLayer(attachment);
#if PLATFORM(IOS_FAMILY)
if (m_legacyScrollingLayerCoordinator) {
m_legacyScrollingLayerCoordinator->registerAllViewportConstrainedLayers(*this, m_scrollCoordinatedLayers);
m_legacyScrollingLayerCoordinator->registerAllScrollingLayers();
}
#endif
} else {
if (m_rootLayerAttachment == RootLayerUnattached)
return;
detachRootLayer();
#if PLATFORM(IOS_FAMILY)
if (m_legacyScrollingLayerCoordinator) {
m_legacyScrollingLayerCoordinator->unregisterAllViewportConstrainedLayers();
m_legacyScrollingLayerCoordinator->unregisterAllScrollingLayers();
}
#endif
}
}
void RenderLayerCompositor::clearBackingForLayerIncludingDescendants(RenderLayer& layer)
{
if (layer.isComposited()) {
removeFromScrollCoordinatedLayers(layer);
layer.clearBacking();
}
for (auto* childLayer = layer.firstChild(); childLayer; childLayer = childLayer->nextSibling())
clearBackingForLayerIncludingDescendants(*childLayer);
}
void RenderLayerCompositor::clearBackingForAllLayers()
{
clearBackingForLayerIncludingDescendants(*m_renderView.layer());
}
void RenderLayerCompositor::updateRootLayerPosition()
{
if (m_rootContentLayer) {
m_rootContentLayer->setSize(m_renderView.frameView().contentsSize());
m_rootContentLayer->setPosition(m_renderView.frameView().positionForRootContentLayer());
m_rootContentLayer->setAnchorPoint(FloatPoint3D());
}
if (m_clipLayer) {
m_clipLayer->setSize(m_renderView.frameView().sizeForVisibleContent());
m_clipLayer->setPosition(positionForClipLayer());
}
#if ENABLE(RUBBER_BANDING)
if (m_contentShadowLayer && m_rootContentLayer) {
m_contentShadowLayer->setPosition(m_rootContentLayer->position());
m_contentShadowLayer->setSize(m_rootContentLayer->size());
}
updateLayerForTopOverhangArea(m_layerForTopOverhangArea != nullptr);
updateLayerForBottomOverhangArea(m_layerForBottomOverhangArea != nullptr);
updateLayerForHeader(m_layerForHeader != nullptr);
updateLayerForFooter(m_layerForFooter != nullptr);
#endif
}
bool RenderLayerCompositor::has3DContent() const
{
return layerHas3DContent(rootRenderLayer());
}
bool RenderLayerCompositor::needsToBeComposited(const RenderLayer& layer, RequiresCompositingData& queryData) const
{
if (!canBeComposited(layer))
return false;
return requiresCompositingLayer(layer, queryData) || layer.mustCompositeForIndirectReasons() || (usesCompositing() && layer.isRenderViewLayer());
}
bool RenderLayerCompositor::requiresCompositingLayer(const RenderLayer& layer, RequiresCompositingData& queryData) const
{
auto& renderer = rendererForCompositingTests(layer);
return requiresCompositingForTransform(renderer)
|| requiresCompositingForAnimation(renderer)
|| clipsCompositingDescendants(*renderer.layer())
|| requiresCompositingForPosition(renderer, *renderer.layer(), queryData)
|| requiresCompositingForCanvas(renderer)
|| requiresCompositingForFilters(renderer)
|| requiresCompositingForWillChange(renderer)
|| requiresCompositingForBackfaceVisibility(renderer)
|| requiresCompositingForVideo(renderer)
|| requiresCompositingForFrame(renderer, queryData)
|| requiresCompositingForPlugin(renderer, queryData)
|| requiresCompositingForEditableImage(renderer)
|| requiresCompositingForOverflowScrolling(*renderer.layer(), queryData);
}
bool RenderLayerCompositor::canBeComposited(const RenderLayer& layer) const
{
if (m_hasAcceleratedCompositing && layer.isSelfPaintingLayer()) {
if (!layer.isInsideFragmentedFlow())
return true;
if (layer.isRenderFragmentedFlow())
return false;
return true;
}
return false;
}
#if ENABLE(FULLSCREEN_API)
enum class FullScreenDescendant { Yes, No, NotApplicable };
static FullScreenDescendant isDescendantOfFullScreenLayer(const RenderLayer& layer)
{
auto& document = layer.renderer().document();
if (!document.webkitIsFullScreen() || !document.fullScreenRenderer())
return FullScreenDescendant::NotApplicable;
auto* fullScreenLayer = document.fullScreenRenderer()->layer();
if (!fullScreenLayer) {
ASSERT_NOT_REACHED();
return FullScreenDescendant::NotApplicable;
}
return layer.isDescendantOf(*fullScreenLayer) ? FullScreenDescendant::Yes : FullScreenDescendant::No;
}
#endif
bool RenderLayerCompositor::requiresOwnBackingStore(const RenderLayer& layer, const RenderLayer* compositingAncestorLayer, const LayoutRect& layerCompositedBoundsInAncestor, const LayoutRect& ancestorCompositedBounds) const
{
auto& renderer = layer.renderer();
if (compositingAncestorLayer
&& !(compositingAncestorLayer->backing()->graphicsLayer()->drawsContent()
|| compositingAncestorLayer->backing()->paintsIntoWindow()
|| compositingAncestorLayer->backing()->paintsIntoCompositedAncestor()))
return true;
RequiresCompositingData queryData;
if (layer.isRenderViewLayer()
|| layer.transform() || requiresCompositingForAnimation(renderer)
|| requiresCompositingForPosition(renderer, layer, queryData)
|| requiresCompositingForCanvas(renderer)
|| requiresCompositingForFilters(renderer)
|| requiresCompositingForWillChange(renderer)
|| requiresCompositingForBackfaceVisibility(renderer)
|| requiresCompositingForVideo(renderer)
|| requiresCompositingForFrame(renderer, queryData)
|| requiresCompositingForPlugin(renderer, queryData)
|| requiresCompositingForEditableImage(renderer)
|| requiresCompositingForOverflowScrolling(layer, queryData)
|| needsContentsCompositingLayer(layer)
|| renderer.isTransparent()
|| renderer.hasMask()
|| renderer.hasReflection()
|| renderer.hasFilter()
|| renderer.hasBackdropFilter())
return true;
if (layer.mustCompositeForIndirectReasons()) {
RenderLayer::IndirectCompositingReason reason = layer.indirectCompositingReason();
return reason == RenderLayer::IndirectCompositingReason::Overlap
|| reason == RenderLayer::IndirectCompositingReason::Stacking
|| reason == RenderLayer::IndirectCompositingReason::BackgroundLayer
|| reason == RenderLayer::IndirectCompositingReason::GraphicalEffect
|| reason == RenderLayer::IndirectCompositingReason::Preserve3D; }
if (!ancestorCompositedBounds.contains(layerCompositedBoundsInAncestor))
return true;
return false;
}
OptionSet<CompositingReason> RenderLayerCompositor::reasonsForCompositing(const RenderLayer& layer) const
{
OptionSet<CompositingReason> reasons;
if (!layer.isComposited())
return reasons;
RequiresCompositingData queryData;
auto& renderer = rendererForCompositingTests(layer);
if (requiresCompositingForTransform(renderer))
reasons.add(CompositingReason::Transform3D);
if (requiresCompositingForVideo(renderer))
reasons.add(CompositingReason::Video);
else if (requiresCompositingForCanvas(renderer))
reasons.add(CompositingReason::Canvas);
else if (requiresCompositingForPlugin(renderer, queryData))
reasons.add(CompositingReason::Plugin);
else if (requiresCompositingForFrame(renderer, queryData))
reasons.add(CompositingReason::IFrame);
else if (requiresCompositingForEditableImage(renderer))
reasons.add(CompositingReason::EmbeddedView);
if ((canRender3DTransforms() && renderer.style().backfaceVisibility() == BackfaceVisibility::Hidden))
reasons.add(CompositingReason::BackfaceVisibilityHidden);
if (clipsCompositingDescendants(*renderer.layer()))
reasons.add(CompositingReason::ClipsCompositingDescendants);
if (requiresCompositingForAnimation(renderer))
reasons.add(CompositingReason::Animation);
if (requiresCompositingForFilters(renderer))
reasons.add(CompositingReason::Filters);
if (requiresCompositingForWillChange(renderer))
reasons.add(CompositingReason::WillChange);
if (requiresCompositingForPosition(renderer, *renderer.layer(), queryData))
reasons.add(renderer.isFixedPositioned() ? CompositingReason::PositionFixed : CompositingReason::PositionSticky);
if (requiresCompositingForOverflowScrolling(*renderer.layer(), queryData))
reasons.add(CompositingReason::OverflowScrollingTouch);
switch (renderer.layer()->indirectCompositingReason()) {
case RenderLayer::IndirectCompositingReason::None:
break;
case RenderLayer::IndirectCompositingReason::Stacking:
reasons.add(CompositingReason::Stacking);
break;
case RenderLayer::IndirectCompositingReason::Overlap:
reasons.add(CompositingReason::Overlap);
break;
case RenderLayer::IndirectCompositingReason::BackgroundLayer:
reasons.add(CompositingReason::NegativeZIndexChildren);
break;
case RenderLayer::IndirectCompositingReason::GraphicalEffect:
if (renderer.hasTransform())
reasons.add(CompositingReason::TransformWithCompositedDescendants);
if (renderer.isTransparent())
reasons.add(CompositingReason::OpacityWithCompositedDescendants);
if (renderer.hasMask())
reasons.add(CompositingReason::MaskWithCompositedDescendants);
if (renderer.hasReflection())
reasons.add(CompositingReason::ReflectionWithCompositedDescendants);
if (renderer.hasFilter() || renderer.hasBackdropFilter())
reasons.add(CompositingReason::FilterWithCompositedDescendants);
#if ENABLE(CSS_COMPOSITING)
if (layer.isolatesCompositedBlending())
reasons.add(CompositingReason::IsolatesCompositedBlendingDescendants);
if (layer.hasBlendMode())
reasons.add(CompositingReason::BlendingWithCompositedDescendants);
#endif
break;
case RenderLayer::IndirectCompositingReason::Perspective:
reasons.add(CompositingReason::Perspective);
break;
case RenderLayer::IndirectCompositingReason::Preserve3D:
reasons.add(CompositingReason::Preserve3D);
break;
}
if (usesCompositing() && renderer.layer()->isRenderViewLayer())
reasons.add(CompositingReason::Root);
return reasons;
}
#if !LOG_DISABLED
const char* RenderLayerCompositor::logReasonsForCompositing(const RenderLayer& layer)
{
OptionSet<CompositingReason> reasons = reasonsForCompositing(layer);
if (reasons & CompositingReason::Transform3D)
return "3D transform";
if (reasons & CompositingReason::Video)
return "video";
if (reasons & CompositingReason::Canvas)
return "canvas";
if (reasons & CompositingReason::Plugin)
return "plugin";
if (reasons & CompositingReason::IFrame)
return "iframe";
if (reasons & CompositingReason::BackfaceVisibilityHidden)
return "backface-visibility: hidden";
if (reasons & CompositingReason::ClipsCompositingDescendants)
return "clips compositing descendants";
if (reasons & CompositingReason::Animation)
return "animation";
if (reasons & CompositingReason::Filters)
return "filters";
if (reasons & CompositingReason::PositionFixed)
return "position: fixed";
if (reasons & CompositingReason::PositionSticky)
return "position: sticky";
if (reasons & CompositingReason::OverflowScrollingTouch)
return "-webkit-overflow-scrolling: touch";
if (reasons & CompositingReason::Stacking)
return "stacking";
if (reasons & CompositingReason::Overlap)
return "overlap";
if (reasons & CompositingReason::NegativeZIndexChildren)
return "negative z-index children";
if (reasons & CompositingReason::TransformWithCompositedDescendants)
return "transform with composited descendants";
if (reasons & CompositingReason::OpacityWithCompositedDescendants)
return "opacity with composited descendants";
if (reasons & CompositingReason::MaskWithCompositedDescendants)
return "mask with composited descendants";
if (reasons & CompositingReason::ReflectionWithCompositedDescendants)
return "reflection with composited descendants";
if (reasons & CompositingReason::FilterWithCompositedDescendants)
return "filter with composited descendants";
#if ENABLE(CSS_COMPOSITING)
if (reasons & CompositingReason::BlendingWithCompositedDescendants)
return "blending with composited descendants";
if (reasons & CompositingReason::IsolatesCompositedBlendingDescendants)
return "isolates composited blending descendants";
#endif
if (reasons & CompositingReason::Perspective)
return "perspective";
if (reasons & CompositingReason::Preserve3D)
return "preserve-3d";
if (reasons & CompositingReason::Root)
return "root";
return "";
}
#endif
bool RenderLayerCompositor::clippedByAncestor(RenderLayer& layer) const
{
ASSERT(layer.isComposited());
if (!layer.parent())
return false;
auto* compositingAncestor = layer.ancestorCompositingLayer();
if (!compositingAncestor)
return false;
auto* computeClipRoot = compositingAncestor;
if (!compositingAncestor->isolatesCompositedBlending()) {
computeClipRoot = nullptr;
auto* parent = &layer;
while (parent) {
auto* next = parent->parent();
if (next == compositingAncestor) {
computeClipRoot = parent;
break;
}
parent = next;
}
if (!computeClipRoot || computeClipRoot == &layer)
return false;
}
return !layer.backgroundClipRect(RenderLayer::ClipRectsContext(computeClipRoot, TemporaryClipRects)).isInfinite(); }
bool RenderLayerCompositor::clipsCompositingDescendants(const RenderLayer& layer) const
{
return layer.hasCompositingDescendant() && layer.renderer().hasClipOrOverflowClip() && !layer.isolatesCompositedBlending();
}
bool RenderLayerCompositor::requiresCompositingForAnimation(RenderLayerModelObject& renderer) const
{
if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
return false;
if (auto* element = renderer.element()) {
if (auto* timeline = element->document().existingTimeline()) {
if (timeline->runningAnimationsForElementAreAllAccelerated(*element))
return true;
}
}
if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled())
return false;
const AnimationBase::RunningState activeAnimationState = AnimationBase::Running | AnimationBase::Paused;
auto& animController = renderer.animation();
return (animController.isRunningAnimationOnRenderer(renderer, CSSPropertyOpacity, activeAnimationState)
&& (usesCompositing() || (m_compositingTriggers & ChromeClient::AnimatedOpacityTrigger)))
|| animController.isRunningAnimationOnRenderer(renderer, CSSPropertyFilter, activeAnimationState)
#if ENABLE(FILTERS_LEVEL_2)
|| animController.isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitBackdropFilter, activeAnimationState)
#endif
|| animController.isRunningAnimationOnRenderer(renderer, CSSPropertyTransform, activeAnimationState);
}
bool RenderLayerCompositor::requiresCompositingForTransform(RenderLayerModelObject& renderer) const
{
if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
return false;
if (!renderer.hasTransform())
return false;
switch (m_compositingPolicy) {
case CompositingPolicy::Normal:
return renderer.style().transform().has3DOperation();
case CompositingPolicy::Conservative:
if (renderer.style().transform().has3DOperation() && renderer.hasFilter())
return true;
return renderer.style().transform().isRepresentableIn2D() ? false : true;
}
return false;
}
bool RenderLayerCompositor::requiresCompositingForBackfaceVisibility(RenderLayerModelObject& renderer) const
{
if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
return false;
if (renderer.style().backfaceVisibility() != BackfaceVisibility::Hidden)
return false;
if (renderer.layer()->has3DTransformedAncestor())
return true;
auto* stackingContext = renderer.layer()->stackingContext();
if (stackingContext && stackingContext->renderer().style().transformStyle3D() == TransformStyle3D::Preserve3D)
return true;
return false;
}
bool RenderLayerCompositor::requiresCompositingForVideo(RenderLayerModelObject& renderer) const
{
if (!(m_compositingTriggers & ChromeClient::VideoTrigger))
return false;
#if ENABLE(VIDEO)
if (!is<RenderVideo>(renderer))
return false;
auto& video = downcast<RenderVideo>(renderer);
if ((video.requiresImmediateCompositing() || video.shouldDisplayVideo()) && canAccelerateVideoRendering(video))
return true;
#else
UNUSED_PARAM(renderer);
#endif
return false;
}
bool RenderLayerCompositor::requiresCompositingForCanvas(RenderLayerModelObject& renderer) const
{
if (!(m_compositingTriggers & ChromeClient::CanvasTrigger))
return false;
if (!renderer.isCanvas())
return false;
bool isCanvasLargeEnoughToForceCompositing = true;
#if !USE(COMPOSITING_FOR_SMALL_CANVASES)
auto* canvas = downcast<HTMLCanvasElement>(renderer.element());
auto canvasArea = canvas->size().area<RecordOverflow>();
isCanvasLargeEnoughToForceCompositing = !canvasArea.hasOverflowed() && canvasArea.unsafeGet() >= canvasAreaThresholdRequiringCompositing;
#endif
CanvasCompositingStrategy compositingStrategy = canvasCompositingStrategy(renderer);
if (compositingStrategy == CanvasAsLayerContents)
return true;
if (m_compositingPolicy == CompositingPolicy::Normal)
return compositingStrategy == CanvasPaintedToLayer && isCanvasLargeEnoughToForceCompositing;
return false;
}
bool RenderLayerCompositor::requiresCompositingForFilters(RenderLayerModelObject& renderer) const
{
#if ENABLE(FILTERS_LEVEL_2)
if (renderer.hasBackdropFilter())
return true;
#endif
if (!(m_compositingTriggers & ChromeClient::FilterTrigger))
return false;
return renderer.hasFilter();
}
bool RenderLayerCompositor::requiresCompositingForWillChange(RenderLayerModelObject& renderer) const
{
if (!renderer.style().willChange() || !renderer.style().willChange()->canTriggerCompositing())
return false;
#if ENABLE(FULLSCREEN_API)
if (renderer.layer() && isDescendantOfFullScreenLayer(*renderer.layer()) == FullScreenDescendant::No)
return false;
#endif
if (m_compositingPolicy == CompositingPolicy::Conservative)
return false;
if (is<RenderBox>(renderer))
return true;
return renderer.style().willChange()->canTriggerCompositingOnInline();
}
bool RenderLayerCompositor::requiresCompositingForPlugin(RenderLayerModelObject& renderer, RequiresCompositingData& queryData) const
{
if (!(m_compositingTriggers & ChromeClient::PluginTrigger))
return false;
bool isCompositedPlugin = is<RenderEmbeddedObject>(renderer) && downcast<RenderEmbeddedObject>(renderer).allowsAcceleratedCompositing();
if (!isCompositedPlugin)
return false;
auto& pluginRenderer = downcast<RenderWidget>(renderer);
if (pluginRenderer.style().visibility() != Visibility::Visible)
return false;
if (queryData.layoutUpToDate == LayoutUpToDate::No) {
queryData.reevaluateAfterLayout = true;
return pluginRenderer.isComposited();
}
IntRect contentBox = snappedIntRect(pluginRenderer.contentBoxRect());
return (contentBox.height() * contentBox.width() > 1);
}
bool RenderLayerCompositor::requiresCompositingForEditableImage(RenderLayerModelObject& renderer) const
{
if (!renderer.isRenderImage())
return false;
auto& image = downcast<RenderImage>(renderer);
if (!image.isEditableImage())
return false;
return true;
}
bool RenderLayerCompositor::requiresCompositingForFrame(RenderLayerModelObject& renderer, RequiresCompositingData& queryData) const
{
if (!is<RenderWidget>(renderer))
return false;
auto& frameRenderer = downcast<RenderWidget>(renderer);
if (frameRenderer.style().visibility() != Visibility::Visible)
return false;
if (!frameRenderer.requiresAcceleratedCompositing())
return false;
if (queryData.layoutUpToDate == LayoutUpToDate::No) {
queryData.reevaluateAfterLayout = true;
return frameRenderer.isComposited();
}
return !snappedIntRect(frameRenderer.contentBoxRect()).isEmpty();
}
bool RenderLayerCompositor::requiresCompositingForScrollableFrame(RequiresCompositingData& queryData) const
{
if (isMainFrameCompositor())
return false;
#if PLATFORM(MAC) || PLATFORM(IOS_FAMILY)
if (!m_renderView.settings().asyncFrameScrollingEnabled())
return false;
#endif
if (!(m_compositingTriggers & ChromeClient::ScrollableNonMainFrameTrigger))
return false;
if (queryData.layoutUpToDate == LayoutUpToDate::No) {
queryData.reevaluateAfterLayout = true;
return m_renderView.isComposited();
}
return m_renderView.frameView().isScrollable();
}
bool RenderLayerCompositor::requiresCompositingForPosition(RenderLayerModelObject& renderer, const RenderLayer& layer, RequiresCompositingData& queryData) const
{
if (!renderer.isPositioned())
return false;
#if ENABLE(FULLSCREEN_API)
if (isDescendantOfFullScreenLayer(layer) == FullScreenDescendant::No)
return false;
#endif
auto position = renderer.style().position();
bool isFixed = renderer.isOutOfFlowPositioned() && position == PositionType::Fixed;
if (isFixed && !layer.isStackingContext())
return false;
bool isSticky = renderer.isInFlowPositioned() && position == PositionType::Sticky;
if (!isFixed && !isSticky)
return false;
if (!m_renderView.settings().acceleratedCompositingForFixedPositionEnabled())
return false;
if (isSticky)
return isAsyncScrollableStickyLayer(layer);
if (queryData.layoutUpToDate == LayoutUpToDate::No) {
queryData.reevaluateAfterLayout = true;
return layer.isComposited();
}
auto container = renderer.container();
ASSERT(container);
if (container != &m_renderView) {
queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForNonViewContainer;
return false;
}
bool paintsContent = layer.isVisuallyNonEmpty() || layer.hasVisibleDescendant();
if (!paintsContent) {
queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForNoVisibleContent;
return false;
}
bool intersectsViewport = fixedLayerIntersectsViewport(layer);
if (!intersectsViewport) {
queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForBoundsOutOfView;
LOG_WITH_STREAM(Compositing, stream << "Layer " << &layer << " is outside the viewport");
return false;
}
return true;
}
bool RenderLayerCompositor::requiresCompositingForOverflowScrolling(const RenderLayer& layer, RequiresCompositingData& queryData) const
{
if (!layer.canUseCompositedScrolling())
return false;
if (queryData.layoutUpToDate == LayoutUpToDate::No) {
queryData.reevaluateAfterLayout = true;
return layer.isComposited();
}
return layer.hasCompositedScrollableOverflow();
}
bool RenderLayerCompositor::requiresCompositingForIndirectReason(RenderLayerModelObject& renderer, bool hasCompositedDescendants, bool has3DTransformedDescendants, RenderLayer::IndirectCompositingReason& reason) const
{
auto& layer = *downcast<RenderBoxModelObject>(renderer).layer();
if (hasCompositedDescendants && (layer.isolatesCompositedBlending() || layer.transform() || renderer.createsGroup() || renderer.hasReflection())) {
reason = RenderLayer::IndirectCompositingReason::GraphicalEffect;
return true;
}
if (has3DTransformedDescendants) {
if (renderer.style().transformStyle3D() == TransformStyle3D::Preserve3D) {
reason = RenderLayer::IndirectCompositingReason::Preserve3D;
return true;
}
if (renderer.style().hasPerspective()) {
reason = RenderLayer::IndirectCompositingReason::Perspective;
return true;
}
}
reason = RenderLayer::IndirectCompositingReason::None;
return false;
}
bool RenderLayerCompositor::styleChangeMayAffectIndirectCompositingReasons(const RenderStyle& oldStyle, const RenderStyle& newStyle)
{
if (RenderElement::createsGroupForStyle(newStyle) != RenderElement::createsGroupForStyle(oldStyle))
return true;
if (newStyle.isolation() != oldStyle.isolation())
return true;
if (newStyle.hasTransform() != oldStyle.hasTransform())
return true;
if (newStyle.boxReflect() != oldStyle.boxReflect())
return true;
if (newStyle.transformStyle3D() != oldStyle.transformStyle3D())
return true;
if (newStyle.hasPerspective() != oldStyle.hasPerspective())
return true;
return false;
}
bool RenderLayerCompositor::isAsyncScrollableStickyLayer(const RenderLayer& layer, const RenderLayer** enclosingAcceleratedOverflowLayer) const
{
ASSERT(layer.renderer().isStickilyPositioned());
auto* enclosingOverflowLayer = layer.enclosingOverflowClipLayer(ExcludeSelf);
#if PLATFORM(IOS_FAMILY)
if (enclosingOverflowLayer && enclosingOverflowLayer->hasCompositedScrollableOverflow()) {
if (enclosingAcceleratedOverflowLayer)
*enclosingAcceleratedOverflowLayer = enclosingOverflowLayer;
return true;
}
#else
UNUSED_PARAM(enclosingAcceleratedOverflowLayer);
#endif
if (enclosingOverflowLayer)
return false;
if (hasCoordinatedScrolling())
return true;
#if PLATFORM(IOS_FAMILY)
return isMainFrameCompositor();
#else
return false;
#endif
}
bool RenderLayerCompositor::isViewportConstrainedFixedOrStickyLayer(const RenderLayer& layer) const
{
if (layer.renderer().isStickilyPositioned())
return isAsyncScrollableStickyLayer(layer);
if (layer.renderer().style().position() != PositionType::Fixed)
return false;
for (auto* stackingContext = layer.stackingContext(); stackingContext; stackingContext = stackingContext->stackingContext()) {
if (stackingContext->isComposited() && stackingContext->renderer().isFixedPositioned())
return false;
}
return true;
}
bool RenderLayerCompositor::fixedLayerIntersectsViewport(const RenderLayer& layer) const
{
ASSERT(layer.renderer().style().position() == PositionType::Fixed);
LayoutRect viewBounds;
if (m_renderView.frameView().useFixedLayout())
viewBounds = m_renderView.unscaledDocumentRect();
else
viewBounds = m_renderView.frameView().rectForFixedPositionLayout();
LayoutRect layerBounds = layer.calculateLayerBounds(&layer, LayoutSize(), { RenderLayer::UseLocalClipRectIfPossible, RenderLayer::IncludeFilterOutsets, RenderLayer::UseFragmentBoxesExcludingCompositing,
RenderLayer::ExcludeHiddenDescendants, RenderLayer::DontConstrainForMask, RenderLayer::IncludeCompositedDescendants });
FloatRect absoluteBounds = layer.renderer().localToContainerQuad(FloatRect(layerBounds), &m_renderView).boundingBox();
return viewBounds.intersects(enclosingIntRect(absoluteBounds));
}
bool RenderLayerCompositor::useCoordinatedScrollingForLayer(const RenderLayer& layer) const
{
if (layer.isRenderViewLayer() && hasCoordinatedScrolling())
return true;
#if PLATFORM(IOS_FAMILY)
return layer.hasCompositedScrollableOverflow();
#endif
return false; }
bool RenderLayerCompositor::isRunningTransformAnimation(RenderLayerModelObject& renderer) const
{
if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
return false;
if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled()) {
if (auto* element = renderer.element()) {
if (auto* timeline = element->document().existingTimeline())
return timeline->isRunningAnimationOnRenderer(renderer, CSSPropertyTransform);
}
return false;
}
return renderer.animation().isRunningAnimationOnRenderer(renderer, CSSPropertyTransform, AnimationBase::Running | AnimationBase::Paused);
}
bool RenderLayerCompositor::needsContentsCompositingLayer(const RenderLayer& layer) const
{
return layer.hasNegativeZOrderLayers();
}
bool RenderLayerCompositor::requiresScrollLayer(RootLayerAttachment attachment) const
{
auto& frameView = m_renderView.frameView();
if (frameView.delegatesScrolling() && isMainFrameCompositor())
return false;
return !m_renderView.frameView().platformWidget() || attachment == RootLayerAttachedViaEnclosingFrame; }
void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
{
if (!scrollbar)
return;
context.save();
const IntRect& scrollbarRect = scrollbar->frameRect();
context.translate(-scrollbarRect.location());
IntRect transformedClip = clip;
transformedClip.moveBy(scrollbarRect.location());
scrollbar->paint(context, transformedClip);
context.restore();
}
void RenderLayerCompositor::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, GraphicsLayerPaintingPhase, const FloatRect& clip, GraphicsLayerPaintBehavior)
{
#if PLATFORM(MAC)
LocalDefaultSystemAppearance localAppearance(m_renderView.useDarkAppearance());
#endif
IntRect pixelSnappedRectForIntegralPositionedItems = snappedIntRect(LayoutRect(clip));
if (graphicsLayer == layerForHorizontalScrollbar())
paintScrollbar(m_renderView.frameView().horizontalScrollbar(), context, pixelSnappedRectForIntegralPositionedItems);
else if (graphicsLayer == layerForVerticalScrollbar())
paintScrollbar(m_renderView.frameView().verticalScrollbar(), context, pixelSnappedRectForIntegralPositionedItems);
else if (graphicsLayer == layerForScrollCorner()) {
const IntRect& scrollCorner = m_renderView.frameView().scrollCornerRect();
context.save();
context.translate(-scrollCorner.location());
IntRect transformedClip = pixelSnappedRectForIntegralPositionedItems;
transformedClip.moveBy(scrollCorner.location());
m_renderView.frameView().paintScrollCorner(context, transformedClip);
context.restore();
}
}
bool RenderLayerCompositor::supportsFixedRootBackgroundCompositing() const
{
auto* renderViewBacking = m_renderView.layer()->backing();
return renderViewBacking && renderViewBacking->isFrameLayerWithTiledBacking();
}
bool RenderLayerCompositor::needsFixedRootBackgroundLayer(const RenderLayer& layer) const
{
if (!layer.isRenderViewLayer())
return false;
if (m_renderView.settings().fixedBackgroundsPaintRelativeToDocument())
return false;
return supportsFixedRootBackgroundCompositing() && m_renderView.rootBackgroundIsEntirelyFixed();
}
GraphicsLayer* RenderLayerCompositor::fixedRootBackgroundLayer() const
{
auto* viewLayer = m_renderView.layer();
if (!viewLayer)
return nullptr;
if (viewLayer->isComposited() && viewLayer->backing()->backgroundLayerPaintsFixedRootBackground())
return viewLayer->backing()->backgroundLayer();
return nullptr;
}
void RenderLayerCompositor::resetTrackedRepaintRects()
{
if (auto* rootLayer = rootGraphicsLayer()) {
GraphicsLayer::traverse(*rootLayer, [](GraphicsLayer& layer) {
layer.resetTrackedRepaints();
});
}
}
float RenderLayerCompositor::deviceScaleFactor() const
{
return m_renderView.document().deviceScaleFactor();
}
float RenderLayerCompositor::pageScaleFactor() const
{
return page().pageScaleFactor();
}
float RenderLayerCompositor::zoomedOutPageScaleFactor() const
{
return page().zoomedOutPageScaleFactor();
}
float RenderLayerCompositor::contentsScaleMultiplierForNewTiles(const GraphicsLayer*) const
{
#if PLATFORM(IOS_FAMILY)
LegacyTileCache* tileCache = nullptr;
if (auto* frameView = page().mainFrame().view())
tileCache = frameView->legacyTileCache();
if (!tileCache)
return 1;
return tileCache->tileControllerShouldUseLowScaleTiles() ? 0.125 : 1;
#else
return 1;
#endif
}
void RenderLayerCompositor::didCommitChangesForLayer(const GraphicsLayer*) const
{
}
bool RenderLayerCompositor::documentUsesTiledBacking() const
{
auto* layer = m_renderView.layer();
if (!layer)
return false;
auto* backing = layer->backing();
if (!backing)
return false;
return backing->isFrameLayerWithTiledBacking();
}
bool RenderLayerCompositor::isMainFrameCompositor() const
{
return m_renderView.frameView().frame().isMainFrame();
}
bool RenderLayerCompositor::shouldCompositeOverflowControls() const
{
auto& frameView = m_renderView.frameView();
if (frameView.platformWidget())
return false;
if (frameView.delegatesScrolling())
return false;
if (documentUsesTiledBacking())
return true;
if (m_overflowControlsHostLayer && isMainFrameCompositor())
return true;
#if !USE(COORDINATED_GRAPHICS_THREADED)
if (!frameView.hasOverlayScrollbars())
return false;
#endif
return true;
}
bool RenderLayerCompositor::requiresHorizontalScrollbarLayer() const
{
return shouldCompositeOverflowControls() && m_renderView.frameView().horizontalScrollbar();
}
bool RenderLayerCompositor::requiresVerticalScrollbarLayer() const
{
return shouldCompositeOverflowControls() && m_renderView.frameView().verticalScrollbar();
}
bool RenderLayerCompositor::requiresScrollCornerLayer() const
{
return shouldCompositeOverflowControls() && m_renderView.frameView().isScrollCornerVisible();
}
#if ENABLE(RUBBER_BANDING)
bool RenderLayerCompositor::requiresOverhangAreasLayer() const
{
if (!isMainFrameCompositor())
return false;
if (documentUsesTiledBacking() && m_renderView.frameView().hasOpaqueBackground() && !m_renderView.frameView().prohibitsScrolling())
return true;
return false;
}
bool RenderLayerCompositor::requiresContentShadowLayer() const
{
if (!isMainFrameCompositor())
return false;
#if PLATFORM(COCOA)
if (viewHasTransparentBackground())
return false;
if (m_renderView.settings().backgroundShouldExtendBeyondPage())
return false;
if (documentUsesTiledBacking() && !m_renderView.frameView().prohibitsScrolling())
return true;
#endif
return false;
}
GraphicsLayer* RenderLayerCompositor::updateLayerForTopOverhangArea(bool wantsLayer)
{
if (!isMainFrameCompositor())
return nullptr;
if (!wantsLayer) {
GraphicsLayer::unparentAndClear(m_layerForTopOverhangArea);
return nullptr;
}
if (!m_layerForTopOverhangArea) {
m_layerForTopOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_layerForTopOverhangArea->setName("top overhang");
m_scrollLayer->addChildBelow(*m_layerForTopOverhangArea, m_rootContentLayer.get());
}
return m_layerForTopOverhangArea.get();
}
GraphicsLayer* RenderLayerCompositor::updateLayerForBottomOverhangArea(bool wantsLayer)
{
if (!isMainFrameCompositor())
return nullptr;
if (!wantsLayer) {
GraphicsLayer::unparentAndClear(m_layerForBottomOverhangArea);
return nullptr;
}
if (!m_layerForBottomOverhangArea) {
m_layerForBottomOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_layerForBottomOverhangArea->setName("bottom overhang");
m_scrollLayer->addChildBelow(*m_layerForBottomOverhangArea, m_rootContentLayer.get());
}
m_layerForBottomOverhangArea->setPosition(FloatPoint(0, m_rootContentLayer->size().height() + m_renderView.frameView().headerHeight()
+ m_renderView.frameView().footerHeight() + m_renderView.frameView().topContentInset()));
return m_layerForBottomOverhangArea.get();
}
GraphicsLayer* RenderLayerCompositor::updateLayerForHeader(bool wantsLayer)
{
if (!isMainFrameCompositor())
return nullptr;
if (!wantsLayer) {
if (m_layerForHeader) {
GraphicsLayer::unparentAndClear(m_layerForHeader);
if (auto* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
}
return nullptr;
}
if (!m_layerForHeader) {
m_layerForHeader = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_layerForHeader->setName("header");
m_scrollLayer->addChildAbove(*m_layerForHeader, m_rootContentLayer.get());
m_renderView.frameView().addPaintPendingMilestones(DidFirstFlushForHeaderLayer);
}
m_layerForHeader->setPosition(FloatPoint(0,
FrameView::yPositionForHeaderLayer(m_renderView.frameView().scrollPosition(), m_renderView.frameView().topContentInset())));
m_layerForHeader->setAnchorPoint(FloatPoint3D());
m_layerForHeader->setSize(FloatSize(m_renderView.frameView().visibleWidth(), m_renderView.frameView().headerHeight()));
if (auto* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
page().chrome().client().didAddHeaderLayer(*m_layerForHeader);
return m_layerForHeader.get();
}
GraphicsLayer* RenderLayerCompositor::updateLayerForFooter(bool wantsLayer)
{
if (!isMainFrameCompositor())
return nullptr;
if (!wantsLayer) {
if (m_layerForFooter) {
GraphicsLayer::unparentAndClear(m_layerForFooter);
if (auto* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
}
return nullptr;
}
if (!m_layerForFooter) {
m_layerForFooter = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_layerForFooter->setName("footer");
m_scrollLayer->addChildAbove(*m_layerForFooter, m_rootContentLayer.get());
}
float totalContentHeight = m_rootContentLayer->size().height() + m_renderView.frameView().headerHeight() + m_renderView.frameView().footerHeight();
m_layerForFooter->setPosition(FloatPoint(0, FrameView::yPositionForFooterLayer(m_renderView.frameView().scrollPosition(),
m_renderView.frameView().topContentInset(), totalContentHeight, m_renderView.frameView().footerHeight())));
m_layerForFooter->setAnchorPoint(FloatPoint3D());
m_layerForFooter->setSize(FloatSize(m_renderView.frameView().visibleWidth(), m_renderView.frameView().footerHeight()));
if (auto* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
page().chrome().client().didAddFooterLayer(*m_layerForFooter);
return m_layerForFooter.get();
}
#endif
bool RenderLayerCompositor::viewHasTransparentBackground(Color* backgroundColor) const
{
if (m_renderView.frameView().isTransparent()) {
if (backgroundColor)
*backgroundColor = Color(); return true;
}
Color documentBackgroundColor = m_renderView.frameView().documentBackgroundColor();
if (!documentBackgroundColor.isValid())
documentBackgroundColor = m_renderView.frameView().baseBackgroundColor();
ASSERT(documentBackgroundColor.isValid());
if (backgroundColor)
*backgroundColor = documentBackgroundColor;
return !documentBackgroundColor.isOpaque();
}
void RenderLayerCompositor::rootOrBodyStyleChanged(RenderElement& renderer, const RenderStyle* oldStyle)
{
if (!usesCompositing())
return;
Color oldBackgroundColor;
if (oldStyle)
oldBackgroundColor = oldStyle->visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor);
if (oldBackgroundColor != renderer.style().visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor))
rootBackgroundColorOrTransparencyChanged();
bool hadFixedBackground = oldStyle && oldStyle->hasEntirelyFixedBackground();
if (hadFixedBackground != renderer.style().hasEntirelyFixedBackground())
rootLayerConfigurationChanged();
}
void RenderLayerCompositor::rootBackgroundColorOrTransparencyChanged()
{
if (!usesCompositing())
return;
Color backgroundColor;
bool isTransparent = viewHasTransparentBackground(&backgroundColor);
Color extendedBackgroundColor = m_renderView.settings().backgroundShouldExtendBeyondPage() ? backgroundColor : Color();
bool transparencyChanged = m_viewBackgroundIsTransparent != isTransparent;
bool backgroundColorChanged = m_viewBackgroundColor != backgroundColor;
bool extendedBackgroundColorChanged = m_rootExtendedBackgroundColor != extendedBackgroundColor;
if (!transparencyChanged && !backgroundColorChanged && !extendedBackgroundColorChanged)
return;
LOG(Compositing, "RenderLayerCompositor %p rootBackgroundColorOrTransparencyChanged. isTransparent=%d", this, isTransparent);
m_viewBackgroundIsTransparent = isTransparent;
m_viewBackgroundColor = backgroundColor;
m_rootExtendedBackgroundColor = extendedBackgroundColor;
if (extendedBackgroundColorChanged) {
page().chrome().client().pageExtendedBackgroundColorDidChange(m_rootExtendedBackgroundColor);
#if ENABLE(RUBBER_BANDING)
if (m_layerForOverhangAreas) {
m_layerForOverhangAreas->setBackgroundColor(m_rootExtendedBackgroundColor);
if (!m_rootExtendedBackgroundColor.isValid())
m_layerForOverhangAreas->setCustomAppearance(GraphicsLayer::CustomAppearance::ScrollingOverhang);
}
#endif
}
rootLayerConfigurationChanged();
}
void RenderLayerCompositor::updateOverflowControlsLayers()
{
#if ENABLE(RUBBER_BANDING)
if (requiresOverhangAreasLayer()) {
if (!m_layerForOverhangAreas) {
m_layerForOverhangAreas = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_layerForOverhangAreas->setName("overhang areas");
m_layerForOverhangAreas->setDrawsContent(false);
float topContentInset = m_renderView.frameView().topContentInset();
IntSize overhangAreaSize = m_renderView.frameView().frameRect().size();
overhangAreaSize.setHeight(overhangAreaSize.height() - topContentInset);
m_layerForOverhangAreas->setSize(overhangAreaSize);
m_layerForOverhangAreas->setPosition(FloatPoint(0, topContentInset));
m_layerForOverhangAreas->setAnchorPoint(FloatPoint3D());
if (m_renderView.settings().backgroundShouldExtendBeyondPage())
m_layerForOverhangAreas->setBackgroundColor(m_renderView.frameView().documentBackgroundColor());
else
m_layerForOverhangAreas->setCustomAppearance(GraphicsLayer::CustomAppearance::ScrollingOverhang);
m_overflowControlsHostLayer->addChildBelow(*m_layerForOverhangAreas, m_clipLayer.get());
}
} else
GraphicsLayer::unparentAndClear(m_layerForOverhangAreas);
if (requiresContentShadowLayer()) {
if (!m_contentShadowLayer) {
m_contentShadowLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_contentShadowLayer->setName("content shadow");
m_contentShadowLayer->setSize(m_rootContentLayer->size());
m_contentShadowLayer->setPosition(m_rootContentLayer->position());
m_contentShadowLayer->setAnchorPoint(FloatPoint3D());
m_contentShadowLayer->setCustomAppearance(GraphicsLayer::CustomAppearance::ScrollingShadow);
m_scrollLayer->addChildBelow(*m_contentShadowLayer, m_rootContentLayer.get());
}
} else
GraphicsLayer::unparentAndClear(m_contentShadowLayer);
#endif
if (requiresHorizontalScrollbarLayer()) {
if (!m_layerForHorizontalScrollbar) {
m_layerForHorizontalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_layerForHorizontalScrollbar->setCanDetachBackingStore(false);
m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
m_layerForHorizontalScrollbar->setName("horizontal scrollbar container");
#if PLATFORM(COCOA) && USE(CA)
m_layerForHorizontalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
#endif
m_overflowControlsHostLayer->addChild(*m_layerForHorizontalScrollbar);
if (auto* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), HorizontalScrollbar);
}
} else if (m_layerForHorizontalScrollbar) {
GraphicsLayer::unparentAndClear(m_layerForHorizontalScrollbar);
if (auto* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), HorizontalScrollbar);
}
if (requiresVerticalScrollbarLayer()) {
if (!m_layerForVerticalScrollbar) {
m_layerForVerticalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_layerForVerticalScrollbar->setCanDetachBackingStore(false);
m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
m_layerForVerticalScrollbar->setName("vertical scrollbar container");
#if PLATFORM(COCOA) && USE(CA)
m_layerForVerticalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
#endif
m_overflowControlsHostLayer->addChild(*m_layerForVerticalScrollbar);
if (auto* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), VerticalScrollbar);
}
} else if (m_layerForVerticalScrollbar) {
GraphicsLayer::unparentAndClear(m_layerForVerticalScrollbar);
if (auto* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), VerticalScrollbar);
}
if (requiresScrollCornerLayer()) {
if (!m_layerForScrollCorner) {
m_layerForScrollCorner = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_layerForScrollCorner->setCanDetachBackingStore(false);
m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
m_layerForScrollCorner->setName("scroll corner");
#if PLATFORM(COCOA) && USE(CA)
m_layerForScrollCorner->setAcceleratesDrawing(acceleratedDrawingEnabled());
#endif
m_overflowControlsHostLayer->addChild(*m_layerForScrollCorner);
}
} else
GraphicsLayer::unparentAndClear(m_layerForScrollCorner);
m_renderView.frameView().positionScrollbarLayers();
}
void RenderLayerCompositor::ensureRootLayer()
{
RootLayerAttachment expectedAttachment = isMainFrameCompositor() ? RootLayerAttachedViaChromeClient : RootLayerAttachedViaEnclosingFrame;
if (expectedAttachment == m_rootLayerAttachment)
return;
if (!m_rootContentLayer) {
m_rootContentLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_rootContentLayer->setName("content root");
IntRect overflowRect = snappedIntRect(m_renderView.layoutOverflowRect());
m_rootContentLayer->setSize(FloatSize(overflowRect.maxX(), overflowRect.maxY()));
m_rootContentLayer->setPosition(FloatPoint());
#if PLATFORM(IOS_FAMILY)
auto& frame = m_renderView.frameView().frame();
if (frame.isMainFrame())
m_rootContentLayer->setAppliesPageScale();
#endif
updateRootContentLayerClipping();
}
if (requiresScrollLayer(expectedAttachment)) {
if (!m_overflowControlsHostLayer) {
ASSERT(!m_scrollLayer);
ASSERT(!m_clipLayer);
m_overflowControlsHostLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_overflowControlsHostLayer->setName("overflow controls host");
m_clipLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_clipLayer->setName("frame clipping");
m_clipLayer->setMasksToBounds(true);
m_scrollLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_scrollLayer->setName("frame scrolling");
m_overflowControlsHostLayer->addChild(*m_clipLayer);
m_clipLayer->addChild(*m_scrollLayer);
m_scrollLayer->addChild(*m_rootContentLayer);
m_clipLayer->setSize(m_renderView.frameView().sizeForVisibleContent());
m_clipLayer->setPosition(positionForClipLayer());
m_clipLayer->setAnchorPoint(FloatPoint3D());
updateOverflowControlsLayers();
if (hasCoordinatedScrolling())
scheduleLayerFlush(true);
else
updateScrollLayerPosition();
}
} else {
if (m_overflowControlsHostLayer) {
GraphicsLayer::unparentAndClear(m_overflowControlsHostLayer);
GraphicsLayer::unparentAndClear(m_clipLayer);
GraphicsLayer::unparentAndClear(m_scrollLayer);
}
}
if (m_rootLayerAttachment != RootLayerUnattached)
detachRootLayer();
attachRootLayer(expectedAttachment);
}
void RenderLayerCompositor::destroyRootLayer()
{
if (!m_rootContentLayer)
return;
detachRootLayer();
#if ENABLE(RUBBER_BANDING)
GraphicsLayer::unparentAndClear(m_layerForOverhangAreas);
#endif
if (m_layerForHorizontalScrollbar) {
GraphicsLayer::unparentAndClear(m_layerForHorizontalScrollbar);
if (auto* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), HorizontalScrollbar);
if (auto* horizontalScrollbar = m_renderView.frameView().verticalScrollbar())
m_renderView.frameView().invalidateScrollbar(*horizontalScrollbar, IntRect(IntPoint(0, 0), horizontalScrollbar->frameRect().size()));
}
if (m_layerForVerticalScrollbar) {
GraphicsLayer::unparentAndClear(m_layerForVerticalScrollbar);
if (auto* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), VerticalScrollbar);
if (auto* verticalScrollbar = m_renderView.frameView().verticalScrollbar())
m_renderView.frameView().invalidateScrollbar(*verticalScrollbar, IntRect(IntPoint(0, 0), verticalScrollbar->frameRect().size()));
}
if (m_layerForScrollCorner) {
GraphicsLayer::unparentAndClear(m_layerForScrollCorner);
m_renderView.frameView().invalidateScrollCorner(m_renderView.frameView().scrollCornerRect());
}
if (m_overflowControlsHostLayer) {
GraphicsLayer::unparentAndClear(m_overflowControlsHostLayer);
GraphicsLayer::unparentAndClear(m_clipLayer);
GraphicsLayer::unparentAndClear(m_scrollLayer);
}
ASSERT(!m_scrollLayer);
GraphicsLayer::unparentAndClear(m_rootContentLayer);
m_layerUpdater = nullptr;
}
void RenderLayerCompositor::attachRootLayer(RootLayerAttachment attachment)
{
if (!m_rootContentLayer)
return;
LOG(Compositing, "RenderLayerCompositor %p attachRootLayer %d", this, attachment);
switch (attachment) {
case RootLayerUnattached:
ASSERT_NOT_REACHED();
break;
case RootLayerAttachedViaChromeClient: {
auto& frame = m_renderView.frameView().frame();
page().chrome().client().attachRootGraphicsLayer(frame, rootGraphicsLayer());
if (frame.isMainFrame())
page().chrome().client().attachViewOverlayGraphicsLayer(frame, &page().pageOverlayController().layerWithViewOverlays());
break;
}
case RootLayerAttachedViaEnclosingFrame: {
if (auto* ownerElement = m_renderView.document().ownerElement())
ownerElement->scheduleInvalidateStyleAndLayerComposition();
break;
}
}
m_rootLayerAttachment = attachment;
rootLayerAttachmentChanged();
if (m_shouldFlushOnReattach) {
scheduleLayerFlushNow();
m_shouldFlushOnReattach = false;
}
}
void RenderLayerCompositor::detachRootLayer()
{
if (!m_rootContentLayer || m_rootLayerAttachment == RootLayerUnattached)
return;
switch (m_rootLayerAttachment) {
case RootLayerAttachedViaEnclosingFrame: {
if (m_overflowControlsHostLayer)
m_overflowControlsHostLayer->removeFromParent();
else
m_rootContentLayer->removeFromParent();
if (auto* ownerElement = m_renderView.document().ownerElement())
ownerElement->scheduleInvalidateStyleAndLayerComposition();
break;
}
case RootLayerAttachedViaChromeClient: {
auto& frame = m_renderView.frameView().frame();
page().chrome().client().attachRootGraphicsLayer(frame, nullptr);
if (frame.isMainFrame()) {
page().chrome().client().attachViewOverlayGraphicsLayer(frame, nullptr);
page().pageOverlayController().willDetachRootLayer();
}
}
break;
case RootLayerUnattached:
break;
}
m_rootLayerAttachment = RootLayerUnattached;
rootLayerAttachmentChanged();
}
void RenderLayerCompositor::updateRootLayerAttachment()
{
ensureRootLayer();
}
void RenderLayerCompositor::rootLayerAttachmentChanged()
{
if (m_rootLayerAttachment == RootLayerUnattached)
return;
auto& frame = m_renderView.frameView().frame();
auto* layer = m_renderView.layer();
if (auto* backing = layer ? layer->backing() : nullptr)
backing->updateDrawsContent();
if (!frame.isMainFrame())
return;
Ref<GraphicsLayer> overlayHost = page().pageOverlayController().layerWithDocumentOverlays();
m_rootContentLayer->addChild(WTFMove(overlayHost));
}
void RenderLayerCompositor::notifyIFramesOfCompositingChange()
{
if (auto* ownerElement = m_renderView.document().ownerElement())
ownerElement->scheduleInvalidateStyleAndLayerComposition();
}
bool RenderLayerCompositor::layerHas3DContent(const RenderLayer& layer) const
{
const RenderStyle& style = layer.renderer().style();
if (style.transformStyle3D() == TransformStyle3D::Preserve3D || style.hasPerspective() || style.transform().has3DOperation())
return true;
const_cast<RenderLayer&>(layer).updateLayerListsIfNeeded();
#if !ASSERT_DISABLED
LayerListMutationDetector mutationChecker(const_cast<RenderLayer&>(layer));
#endif
for (auto* renderLayer : layer.negativeZOrderLayers()) {
if (layerHas3DContent(*renderLayer))
return true;
}
for (auto* renderLayer : layer.positiveZOrderLayers()) {
if (layerHas3DContent(*renderLayer))
return true;
}
for (auto* renderLayer : layer.normalFlowLayers()) {
if (layerHas3DContent(*renderLayer))
return true;
}
return false;
}
void RenderLayerCompositor::deviceOrPageScaleFactorChanged()
{
if (auto* rootLayer = rootGraphicsLayer())
rootLayer->noteDeviceOrPageScaleFactorChangedIncludingDescendants();
}
static bool canCoordinateScrollingForLayer(const RenderLayer& layer)
{
return (layer.isRenderViewLayer() || layer.parent()) && layer.isComposited();
}
void RenderLayerCompositor::updateScrollCoordinatedStatus(RenderLayer& layer, OptionSet<ScrollingNodeChangeFlags> changes)
{
OptionSet<ScrollCoordinationRole> coordinationRoles;
if (isViewportConstrainedFixedOrStickyLayer(layer))
coordinationRoles.add(ScrollCoordinationRole::ViewportConstrained);
if (useCoordinatedScrollingForLayer(layer))
coordinationRoles.add(ScrollCoordinationRole::Scrolling);
if (layer.isComposited())
layer.backing()->setIsScrollCoordinatedWithViewportConstrainedRole(coordinationRoles.contains(ScrollCoordinationRole::ViewportConstrained));
if (coordinationRoles && canCoordinateScrollingForLayer(layer)) {
if (m_scrollCoordinatedLayers.add(&layer).isNewEntry)
m_subframeScrollLayersNeedReattach = true;
updateScrollCoordinatedLayer(layer, coordinationRoles, changes);
} else
removeFromScrollCoordinatedLayers(layer);
}
void RenderLayerCompositor::removeFromScrollCoordinatedLayers(RenderLayer& layer)
{
if (!m_scrollCoordinatedLayers.contains(&layer))
return;
m_subframeScrollLayersNeedReattach = true;
m_scrollCoordinatedLayers.remove(&layer);
m_scrollCoordinatedLayersNeedingUpdate.remove(&layer);
detachScrollCoordinatedLayer(layer, { ScrollCoordinationRole::Scrolling, ScrollCoordinationRole::ViewportConstrained });
}
FixedPositionViewportConstraints RenderLayerCompositor::computeFixedViewportConstraints(RenderLayer& layer) const
{
ASSERT(layer.isComposited());
auto* graphicsLayer = layer.backing()->graphicsLayer();
FixedPositionViewportConstraints constraints;
constraints.setLayerPositionAtLastLayout(graphicsLayer->position());
constraints.setViewportRectAtLastLayout(m_renderView.frameView().rectForFixedPositionLayout());
constraints.setAlignmentOffset(graphicsLayer->pixelAlignmentOffset());
const RenderStyle& style = layer.renderer().style();
if (!style.left().isAuto())
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeLeft);
if (!style.right().isAuto())
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeRight);
if (!style.top().isAuto())
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeTop);
if (!style.bottom().isAuto())
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeBottom);
if (style.left().isAuto() && style.right().isAuto())
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeLeft);
if (style.top().isAuto() && style.bottom().isAuto())
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeTop);
return constraints;
}
StickyPositionViewportConstraints RenderLayerCompositor::computeStickyViewportConstraints(RenderLayer& layer) const
{
ASSERT(layer.isComposited());
#if !PLATFORM(IOS_FAMILY)
ASSERT(!layer.enclosingOverflowClipLayer(ExcludeSelf));
#endif
auto& renderer = downcast<RenderBoxModelObject>(layer.renderer());
StickyPositionViewportConstraints constraints;
renderer.computeStickyPositionConstraints(constraints, renderer.constrainingRectForStickyPosition());
auto* graphicsLayer = layer.backing()->graphicsLayer();
constraints.setLayerPositionAtLastLayout(graphicsLayer->position());
constraints.setStickyOffsetAtLastLayout(renderer.stickyPositionOffset());
constraints.setAlignmentOffset(graphicsLayer->pixelAlignmentOffset());
return constraints;
}
static ScrollingNodeID enclosingScrollingNodeID(RenderLayer& layer, IncludeSelfOrNot includeSelf)
{
auto* currLayer = includeSelf == IncludeSelf ? &layer : layer.parent();
while (currLayer) {
if (auto* backing = currLayer->backing()) {
if (ScrollingNodeID nodeID = backing->scrollingNodeIDForChildren())
return nodeID;
}
currLayer = currLayer->parent();
}
return 0;
}
static ScrollingNodeID scrollCoordinatedAncestorInParentOfFrame(Frame& frame)
{
if (!frame.document() || !frame.view())
return 0;
auto* ownerElement = frame.document()->ownerElement();
auto* frameRenderer = ownerElement ? ownerElement->renderer() : nullptr;
if (!frameRenderer)
return 0;
auto* layerInParentDocument = frameRenderer->enclosingLayer();
if (!layerInParentDocument)
return 0;
return enclosingScrollingNodeID(*layerInParentDocument, IncludeSelf);
}
void RenderLayerCompositor::reattachSubframeScrollLayers()
{
if (!m_subframeScrollLayersNeedReattach)
return;
m_subframeScrollLayersNeedReattach = false;
auto* scrollingCoordinator = this->scrollingCoordinator();
for (Frame* child = m_renderView.frameView().frame().tree().firstChild(); child; child = child->tree().nextSibling()) {
if (!child->document() || !child->view())
continue;
auto* childFrameView = child->view();
ScrollingNodeID frameScrollingNodeID = childFrameView->scrollLayerID();
if (!frameScrollingNodeID)
continue;
ScrollingNodeID parentNodeID = scrollCoordinatedAncestorInParentOfFrame(*child);
if (!parentNodeID)
continue;
scrollingCoordinator->attachToStateTree(child->isMainFrame() ? ScrollingNodeType::MainFrame : ScrollingNodeType::Subframe, frameScrollingNodeID, parentNodeID);
}
}
static inline ScrollCoordinationRole scrollCoordinationRoleForNodeType(ScrollingNodeType nodeType)
{
switch (nodeType) {
case ScrollingNodeType::MainFrame:
case ScrollingNodeType::Subframe:
case ScrollingNodeType::Overflow:
return ScrollCoordinationRole::Scrolling;
case ScrollingNodeType::Fixed:
case ScrollingNodeType::Sticky:
return ScrollCoordinationRole::ViewportConstrained;
}
ASSERT_NOT_REACHED();
return ScrollCoordinationRole::Scrolling;
}
ScrollingNodeID RenderLayerCompositor::attachScrollingNode(RenderLayer& layer, ScrollingNodeType nodeType, ScrollingNodeID parentNodeID)
{
auto* scrollingCoordinator = this->scrollingCoordinator();
auto* backing = layer.backing();
ASSERT(backing);
if (!backing)
return 0;
ScrollCoordinationRole role = scrollCoordinationRoleForNodeType(nodeType);
ScrollingNodeID nodeID = backing->scrollingNodeIDForRole(role);
if (!nodeID)
nodeID = scrollingCoordinator->uniqueScrollingNodeID();
nodeID = scrollingCoordinator->attachToStateTree(nodeType, nodeID, parentNodeID);
if (!nodeID)
return 0;
backing->setScrollingNodeIDForRole(nodeID, role);
m_scrollingNodeToLayerMap.add(nodeID, &layer);
return nodeID;
}
void RenderLayerCompositor::detachScrollCoordinatedLayer(RenderLayer& layer, OptionSet<ScrollCoordinationRole> roles)
{
auto* backing = layer.backing();
if (!backing)
return;
if (roles.contains(ScrollCoordinationRole::Scrolling)) {
if (ScrollingNodeID nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::Scrolling))
m_scrollingNodeToLayerMap.remove(nodeID);
}
if (roles.contains(ScrollCoordinationRole::ViewportConstrained)) {
if (ScrollingNodeID nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::ViewportConstrained))
m_scrollingNodeToLayerMap.remove(nodeID);
}
backing->detachFromScrollingCoordinator(roles);
}
void RenderLayerCompositor::updateScrollCoordinationForThisFrame(ScrollingNodeID parentNodeID)
{
auto* scrollingCoordinator = this->scrollingCoordinator();
FrameView& frameView = m_renderView.frameView();
ASSERT(scrollingCoordinator->coordinatesScrollingForFrameView(frameView));
ScrollingNodeID nodeID = attachScrollingNode(*m_renderView.layer(), m_renderView.frame().isMainFrame() ? ScrollingNodeType::MainFrame : ScrollingNodeType::Subframe, parentNodeID);
ScrollingCoordinator::ScrollingGeometry scrollingGeometry;
scrollingGeometry.scrollOrigin = frameView.scrollOrigin();
scrollingGeometry.scrollableAreaSize = frameView.visibleContentRect().size();
scrollingGeometry.contentSize = frameView.totalContentsSize();
scrollingGeometry.reachableContentSize = frameView.totalContentsSize();
#if ENABLE(CSS_SCROLL_SNAP)
frameView.updateSnapOffsets();
scrollingCoordinator->updateScrollSnapPropertiesWithFrameView(frameView);
#endif
scrollingCoordinator->updateFrameScrollingNode(nodeID, m_scrollLayer.get(), m_rootContentLayer.get(), fixedRootBackgroundLayer(), clipLayer(), scrollingGeometry);
}
void RenderLayerCompositor::updateScrollCoordinatedLayer(RenderLayer& layer, OptionSet<ScrollCoordinationRole> roles, OptionSet<ScrollingNodeChangeFlags> changes)
{
bool isRenderViewLayer = layer.isRenderViewLayer();
ASSERT(m_scrollCoordinatedLayers.contains(&layer));
ASSERT(layer.isComposited());
auto* scrollingCoordinator = this->scrollingCoordinator();
if (!scrollingCoordinator || !scrollingCoordinator->coordinatesScrollingForFrameView(m_renderView.frameView()))
return;
if (!m_renderView.frame().isMainFrame()) {
ScrollingNodeID parentDocumentHostingNodeID = scrollCoordinatedAncestorInParentOfFrame(m_renderView.frame());
if (!parentDocumentHostingNodeID)
return;
updateScrollCoordinationForThisFrame(parentDocumentHostingNodeID);
if (!(roles.contains(ScrollCoordinationRole::ViewportConstrained)) && isRenderViewLayer)
return;
}
ScrollingNodeID parentNodeID = enclosingScrollingNodeID(layer, ExcludeSelf);
if (!parentNodeID && !isRenderViewLayer)
return;
auto* backing = layer.backing();
if (roles.contains(ScrollCoordinationRole::ViewportConstrained)) {
ScrollingNodeType nodeType = ScrollingNodeType::MainFrame;
if (layer.renderer().isFixedPositioned())
nodeType = ScrollingNodeType::Fixed;
else if (layer.renderer().style().position() == PositionType::Sticky)
nodeType = ScrollingNodeType::Sticky;
else
ASSERT_NOT_REACHED();
ScrollingNodeID nodeID = attachScrollingNode(layer, nodeType, parentNodeID);
if (!nodeID)
return;
LOG_WITH_STREAM(Compositing, stream << "Registering ViewportConstrained " << nodeType << " node " << nodeID << " (layer " << backing->graphicsLayer()->primaryLayerID() << ") as child of " << parentNodeID);
if (changes & ScrollingNodeChangeFlags::Layer)
scrollingCoordinator->updateNodeLayer(nodeID, backing->graphicsLayer());
if (changes & ScrollingNodeChangeFlags::LayerGeometry) {
switch (nodeType) {
case ScrollingNodeType::Fixed:
scrollingCoordinator->updateNodeViewportConstraints(nodeID, computeFixedViewportConstraints(layer));
break;
case ScrollingNodeType::Sticky:
scrollingCoordinator->updateNodeViewportConstraints(nodeID, computeStickyViewportConstraints(layer));
break;
case ScrollingNodeType::MainFrame:
case ScrollingNodeType::Subframe:
case ScrollingNodeType::Overflow:
break;
}
}
parentNodeID = nodeID;
} else
detachScrollCoordinatedLayer(layer, ScrollCoordinationRole::ViewportConstrained);
if (roles.contains(ScrollCoordinationRole::Scrolling)) {
if (isRenderViewLayer)
updateScrollCoordinationForThisFrame(parentNodeID);
else {
ScrollingNodeType nodeType = ScrollingNodeType::Overflow;
ScrollingNodeID nodeID = attachScrollingNode(layer, nodeType, parentNodeID);
if (!nodeID)
return;
ScrollingCoordinator::ScrollingGeometry scrollingGeometry;
scrollingGeometry.scrollOrigin = layer.scrollOrigin();
scrollingGeometry.scrollPosition = layer.scrollPosition();
scrollingGeometry.scrollableAreaSize = layer.visibleSize();
scrollingGeometry.contentSize = layer.contentsSize();
scrollingGeometry.reachableContentSize = layer.scrollableContentsSize();
#if ENABLE(CSS_SCROLL_SNAP)
if (const Vector<LayoutUnit>* offsets = layer.horizontalSnapOffsets())
scrollingGeometry.horizontalSnapOffsets = *offsets;
if (const Vector<LayoutUnit>* offsets = layer.verticalSnapOffsets())
scrollingGeometry.verticalSnapOffsets = *offsets;
if (const Vector<ScrollOffsetRange<LayoutUnit>>* ranges = layer.horizontalSnapOffsetRanges())
scrollingGeometry.horizontalSnapOffsetRanges = *ranges;
if (const Vector<ScrollOffsetRange<LayoutUnit>>* ranges = layer.verticalSnapOffsetRanges())
scrollingGeometry.verticalSnapOffsetRanges = *ranges;
scrollingGeometry.currentHorizontalSnapPointIndex = layer.currentHorizontalSnapPointIndex();
scrollingGeometry.currentVerticalSnapPointIndex = layer.currentVerticalSnapPointIndex();
#endif
LOG(Compositing, "Registering Scrolling scrolling node %" PRIu64 " (layer %" PRIu64 ") as child of %" PRIu64, nodeID, backing->graphicsLayer()->primaryLayerID(), parentNodeID);
scrollingCoordinator->updateOverflowScrollingNode(nodeID, backing->scrollingLayer(), backing->scrollingContentsLayer(), scrollingGeometry);
}
} else
detachScrollCoordinatedLayer(layer, ScrollCoordinationRole::Scrolling);
}
ScrollableArea* RenderLayerCompositor::scrollableAreaForScrollLayerID(ScrollingNodeID nodeID) const
{
if (!nodeID)
return nullptr;
return m_scrollingNodeToLayerMap.get(nodeID);
}
void RenderLayerCompositor::willRemoveScrollingLayerWithBacking(RenderLayer& layer, RenderLayerBacking& backing)
{
if (auto* scrollingCoordinator = this->scrollingCoordinator()) {
backing.detachFromScrollingCoordinator(ScrollCoordinationRole::Scrolling);
scrollingCoordinator->scrollableAreaScrollLayerDidChange(layer);
return;
}
#if PLATFORM(IOS_FAMILY)
ASSERT(m_renderView.document().pageCacheState() == Document::NotInPageCache);
if (m_legacyScrollingLayerCoordinator)
m_legacyScrollingLayerCoordinator->removeScrollingLayer(layer, backing);
#endif
}
void RenderLayerCompositor::didAddScrollingLayer(RenderLayer& layer)
{
updateScrollCoordinatedStatus(layer, { ScrollingNodeChangeFlags::Layer, ScrollingNodeChangeFlags::LayerGeometry });
if (auto* scrollingCoordinator = this->scrollingCoordinator()) {
scrollingCoordinator->scrollableAreaScrollLayerDidChange(layer);
return;
}
#if PLATFORM(IOS_FAMILY)
ASSERT(m_renderView.document().pageCacheState() == Document::NotInPageCache);
if (m_legacyScrollingLayerCoordinator)
m_legacyScrollingLayerCoordinator->addScrollingLayer(layer);
#endif
}
void RenderLayerCompositor::windowScreenDidChange(PlatformDisplayID displayID)
{
if (m_layerUpdater)
m_layerUpdater->screenDidChange(displayID);
}
ScrollingCoordinator* RenderLayerCompositor::scrollingCoordinator() const
{
return page().scrollingCoordinator();
}
GraphicsLayerFactory* RenderLayerCompositor::graphicsLayerFactory() const
{
return page().chrome().client().graphicsLayerFactory();
}
void RenderLayerCompositor::setLayerFlushThrottlingEnabled(bool enabled)
{
m_layerFlushThrottlingEnabled = enabled;
if (m_layerFlushThrottlingEnabled)
return;
m_layerFlushTimer.stop();
if (!m_hasPendingLayerFlush)
return;
scheduleLayerFlushNow();
}
void RenderLayerCompositor::disableLayerFlushThrottlingTemporarilyForInteraction()
{
if (m_layerFlushThrottlingTemporarilyDisabledForInteraction)
return;
m_layerFlushThrottlingTemporarilyDisabledForInteraction = true;
}
bool RenderLayerCompositor::isThrottlingLayerFlushes() const
{
if (!m_layerFlushThrottlingEnabled)
return false;
if (!m_layerFlushTimer.isActive())
return false;
if (m_layerFlushThrottlingTemporarilyDisabledForInteraction)
return false;
return true;
}
void RenderLayerCompositor::startLayerFlushTimerIfNeeded()
{
m_layerFlushThrottlingTemporarilyDisabledForInteraction = false;
m_layerFlushTimer.stop();
if (!m_layerFlushThrottlingEnabled)
return;
m_layerFlushTimer.startOneShot(throttledLayerFlushDelay);
}
void RenderLayerCompositor::startInitialLayerFlushTimerIfNeeded()
{
if (!m_layerFlushThrottlingEnabled)
return;
if (m_layerFlushTimer.isActive())
return;
m_layerFlushTimer.startOneShot(throttledLayerFlushInitialDelay);
}
void RenderLayerCompositor::layerFlushTimerFired()
{
if (!m_hasPendingLayerFlush)
return;
scheduleLayerFlushNow();
}
#if USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR)
RefPtr<DisplayRefreshMonitor> RenderLayerCompositor::createDisplayRefreshMonitor(PlatformDisplayID displayID) const
{
if (auto monitor = page().chrome().client().createDisplayRefreshMonitor(displayID))
return monitor;
return DisplayRefreshMonitor::createDefaultDisplayRefreshMonitor(displayID);
}
#endif
#if ENABLE(CSS_SCROLL_SNAP)
void RenderLayerCompositor::updateScrollSnapPropertiesWithFrameView(const FrameView& frameView)
{
if (auto* coordinator = scrollingCoordinator())
coordinator->updateScrollSnapPropertiesWithFrameView(frameView);
}
#endif
Page& RenderLayerCompositor::page() const
{
return m_renderView.page();
}
TextStream& operator<<(TextStream& ts, CompositingUpdateType updateType)
{
switch (updateType) {
case CompositingUpdateType::AfterStyleChange: ts << "after style change"; break;
case CompositingUpdateType::AfterLayout: ts << "after layout"; break;
case CompositingUpdateType::OnScroll: ts << "on scroll"; break;
case CompositingUpdateType::OnCompositedScroll: ts << "on composited scroll"; break;
}
return ts;
}
TextStream& operator<<(TextStream& ts, CompositingPolicy compositingPolicy)
{
switch (compositingPolicy) {
case CompositingPolicy::Normal: ts << "normal"; break;
case CompositingPolicy::Conservative: ts << "conservative"; break;
}
return ts;
}
#if PLATFORM(IOS_FAMILY)
typedef HashMap<PlatformLayer*, std::unique_ptr<ViewportConstraints>> LayerMap;
typedef HashMap<PlatformLayer*, PlatformLayer*> StickyContainerMap;
void LegacyWebKitScrollingLayerCoordinator::registerAllViewportConstrainedLayers(RenderLayerCompositor& compositor, const HashSet<RenderLayer*>& layers)
{
if (!m_coordinateViewportConstainedLayers)
return;
LayerMap layerMap;
StickyContainerMap stickyContainerMap;
for (auto* layer : layers) {
ASSERT(layer->isComposited());
std::unique_ptr<ViewportConstraints> constraints;
if (layer->renderer().isStickilyPositioned()) {
constraints = std::make_unique<StickyPositionViewportConstraints>(compositor.computeStickyViewportConstraints(*layer));
const RenderLayer* enclosingTouchScrollableLayer = nullptr;
if (compositor.isAsyncScrollableStickyLayer(*layer, &enclosingTouchScrollableLayer) && enclosingTouchScrollableLayer) {
ASSERT(enclosingTouchScrollableLayer->isComposited());
stickyContainerMap.add(layer->backing()->graphicsLayer()->platformLayer(), enclosingTouchScrollableLayer->backing()->scrollingLayer()->platformLayer());
}
} else if (layer->renderer().isFixedPositioned())
constraints = std::make_unique<FixedPositionViewportConstraints>(compositor.computeFixedViewportConstraints(*layer));
else
continue;
layerMap.add(layer->backing()->graphicsLayer()->platformLayer(), WTFMove(constraints));
}
m_chromeClient.updateViewportConstrainedLayers(layerMap, stickyContainerMap);
}
void LegacyWebKitScrollingLayerCoordinator::unregisterAllViewportConstrainedLayers()
{
if (!m_coordinateViewportConstainedLayers)
return;
LayerMap layerMap;
m_chromeClient.updateViewportConstrainedLayers(layerMap, { });
}
static bool scrollbarHasDisplayNone(Scrollbar* scrollbar)
{
if (!scrollbar || !scrollbar->isCustomScrollbar())
return false;
std::unique_ptr<RenderStyle> scrollbarStyle = static_cast<RenderScrollbar*>(scrollbar)->getScrollbarPseudoStyle(ScrollbarBGPart, PseudoId::Scrollbar);
return scrollbarStyle && scrollbarStyle->display() == DisplayType::None;
}
void LegacyWebKitScrollingLayerCoordinator::updateScrollingLayer(RenderLayer& layer)
{
auto* backing = layer.backing();
ASSERT(backing);
bool allowHorizontalScrollbar = !scrollbarHasDisplayNone(layer.horizontalScrollbar());
bool allowVerticalScrollbar = !scrollbarHasDisplayNone(layer.verticalScrollbar());
m_chromeClient.addOrUpdateScrollingLayer(layer.renderer().element(), backing->scrollingLayer()->platformLayer(), backing->scrollingContentsLayer()->platformLayer(),
layer.scrollableContentsSize(), allowHorizontalScrollbar, allowVerticalScrollbar);
}
void LegacyWebKitScrollingLayerCoordinator::registerAllScrollingLayers()
{
for (auto* layer : m_scrollingLayers)
updateScrollingLayer(*layer);
}
void LegacyWebKitScrollingLayerCoordinator::registerScrollingLayersNeedingUpdate()
{
for (auto* layer : m_scrollingLayersNeedingUpdate)
updateScrollingLayer(*layer);
m_scrollingLayersNeedingUpdate.clear();
}
void LegacyWebKitScrollingLayerCoordinator::unregisterAllScrollingLayers()
{
for (auto* layer : m_scrollingLayers) {
auto* backing = layer->backing();
ASSERT(backing);
m_chromeClient.removeScrollingLayer(layer->renderer().element(), backing->scrollingLayer()->platformLayer(), backing->scrollingContentsLayer()->platformLayer());
}
}
void LegacyWebKitScrollingLayerCoordinator::addScrollingLayer(RenderLayer& layer)
{
m_scrollingLayers.add(&layer);
}
void LegacyWebKitScrollingLayerCoordinator::removeScrollingLayer(RenderLayer& layer, RenderLayerBacking& backing)
{
m_scrollingLayersNeedingUpdate.remove(&layer);
m_scrollingLayers.remove(&layer);
auto* scrollingLayer = backing.scrollingLayer()->platformLayer();
auto* contentsLayer = backing.scrollingContentsLayer()->platformLayer();
m_chromeClient.removeScrollingLayer(layer.renderer().element(), scrollingLayer, contentsLayer);
}
void LegacyWebKitScrollingLayerCoordinator::didFlushChangesForLayer(RenderLayer& layer)
{
if (m_scrollingLayers.contains(&layer))
m_scrollingLayersNeedingUpdate.add(&layer);
}
#endif
}
#if ENABLE(TREE_DEBUGGING)
void showGraphicsLayerTreeForCompositor(WebCore::RenderLayerCompositor& compositor)
{
showGraphicsLayerTree(compositor.rootGraphicsLayer());
}
#endif