/*
 * Copyright (C) 2009, 2010, 2011 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

#include "config.h"

#if USE(ACCELERATED_COMPOSITING)

#include "RenderLayerBacking.h"

#include "CanvasRenderingContext.h"
#include "CSSPropertyNames.h"
#include "Chrome.h"
#include "FloatPoint.h"
#include "FontCache.h"
#include "FrameView.h"
#include "GraphicsContext.h"
#include "GraphicsLayer.h"
#include "HTMLBodyElement.h"
#include "HTMLCanvasElement.h"
#include "HTMLIFrameElement.h"
#include "HTMLMediaElement.h"
#include "HTMLNames.h"
#include "InspectorInstrumentation.h"
#include "KeyframeList.h"
#include "PluginViewBase.h"
#include "RenderApplet.h"
#include "RenderFragmentedFlow.h"
#include "RenderIFrame.h"
#include "RenderImage.h"
#include "RenderLayerCompositor.h"
#include "RenderLayerModelObject.h"
#include "RenderEmbeddedObject.h"
#include "RenderFragmentContainer.h"
#include "RenderVideo.h"
#include "RenderView.h"
#include "ScrollingCoordinator.h"
#include "Settings.h"
#include "StyleResolver.h"
#include "TiledBacking.h"
#include <functional>
#include <wtf/CurrentTime.h>
#include <wtf/text/StringBuilder.h>

#if ENABLE(CSS_FILTERS)
#include "CSSFilter.h"
#endif

#if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
#include "GraphicsContext3D.h"
#endif

namespace WebCore {

using namespace HTMLNames;

static bool canDirectlyCompositeBackgroundBackgroundImage(const RenderElement&);
static bool hasPaintedBoxDecorationsOrBackgroundImage(const RenderElement&);

static inline bool isAcceleratedCanvas(RenderElement& renderer)
{
#if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
    if (renderer.isCanvas()) {
        HTMLCanvasElement* canvas = static_cast<HTMLCanvasElement*>(renderer.element());
        if (CanvasRenderingContext* context = canvas->renderingContext())
            return context->isAccelerated();
    }
#else
    UNUSED_PARAM(renderer);
#endif
    return false;
}

// Get the scrolling coordinator in a way that works inside RenderLayerBacking's destructor.
static ScrollingCoordinator* scrollingCoordinatorFromLayer(RenderLayer* layer)
{
    Page* page = layer->renderer().frame().page();
    if (!page)
        return 0;

    return page->scrollingCoordinator();
}

RenderLayerBacking::RenderLayerBacking(RenderLayer& layer)
    : m_owningLayer(layer)
	, m_scrollLayerID(0)
    , m_artificiallyInflatedBounds(false)
    , m_isMainFrameRenderViewLayer(false)
	, m_isFrameLayerWithTiledBacking(false)
    , m_usingTiledCacheLayer(false)
    , m_requiresOwnBackingStore(true)
#if ENABLE(CSS_FILTERS)
    , m_canCompositeFilters(false)
#endif
#if ENABLE(FILTERS_LEVEL_2)
    , m_canCompositeBackdropFilters(false)
#endif
	, m_backgroundLayerPaintsFixedRootBackground(false)
	, m_requiresBackgroundLayer(false)
	, m_hasSubpixelRounding(false)
{
	Page* page = renderer().frame().page();

    if (layer.isRenderViewLayer() && page) {
        m_isMainFrameRenderViewLayer = renderer().frame().isMainFrame();

#if PLATFORM(MAC)
        m_usingTiledCacheLayer = page->chrome().client().shouldUseTiledBackingForFrameView(renderer().frame().view());
#endif
    }
    
    createPrimaryGraphicsLayer();

    if (m_usingTiledCacheLayer && page) {
        TiledBacking* tiledBacking = this->tiledBacking();
		tiledBacking->setIsInWindow(page->isVisible());
		tiledBacking->setCanHaveScrollbars(renderer().view().frameView().canHaveScrollbars());
		adjustTileCacheCoverage();
    }
}

RenderLayerBacking::~RenderLayerBacking()
{
    updateAncestorClippingLayer(false);
    updateChildClippingStrategy(false);
    updateDescendantClippingLayer(false);
    updateOverflowControlsLayers(false, false, false);
    updateForegroundLayer(false);
    updateBackgroundLayer(false);
    updateMaskingLayer(false, false);
    updateScrollingLayers(false);
    detachFromScrollingCoordinator();
    destroyGraphicsLayers();
}

void RenderLayerBacking::willDestroyLayer(const GraphicsLayer* layer)
{
#if 0
	if (layer && layer->type() == GraphicsLayer::Type::Normal && layer->tiledBacking())
		compositor().layerTiledBackingUsageChanged(layer, false);
#endif
}

PassOwnPtr<GraphicsLayer> RenderLayerBacking::createGraphicsLayer(const String& name, GraphicsLayer::Type type)
{
    OwnPtr<GraphicsLayer> graphicsLayer = GraphicsLayer::create(this, type);
#ifndef NDEBUG
    graphicsLayer->setName(name);
#else
    UNUSED_PARAM(name);
#endif
    graphicsLayer->setMaintainsPixelAlignment(compositor().keepLayersPixelAligned());

#if PLATFORM(MAC) && USE(CA)
    graphicsLayer->setAcceleratesDrawing(compositor().acceleratedDrawingEnabled());
#endif    
    
    return graphicsLayer.release();
}

TiledBacking* RenderLayerBacking::tiledBacking() const
{
    return m_graphicsLayer->tiledBacking();
}

void RenderLayerBacking::adjustTileCacheCoverage()
{
    if (!m_usingTiledCacheLayer)
        return;

    TiledBacking::TileCoverage tileCoverage = TiledBacking::CoverageForVisibleArea;

    // FIXME: When we use TiledBacking for overflow, this should look at RenderView scrollability.
    auto& frameView = renderer().view().frameView();
	if (frameView.horizontalScrollbarMode() != ScrollbarAlwaysOff)
		tileCoverage |= TiledBacking::CoverageForHorizontalScrolling;

	if (frameView.verticalScrollbarMode() != ScrollbarAlwaysOff)
		tileCoverage |= TiledBacking::CoverageForVerticalScrolling;

#if ENABLE(THREADED_SCROLLING)
	if (ScrollingCoordinator* scrollingCoordinator = frame->page()->scrollingCoordinator()) {
		if (scrollingCoordinator->shouldUpdateScrollLayerPositionOnMainThread())
			tileCoverage |= TiledBacking::CoverageForSlowScrolling;
	}
#endif

    tiledBacking()->setTileCoverage(tileCoverage);
}

void RenderLayerBacking::updateDebugIndicators(bool showBorder, bool showRepaintCounter)
{
    m_graphicsLayer->setShowDebugBorder(showBorder);
    m_graphicsLayer->setShowRepaintCounter(showRepaintCounter);

    if (m_ancestorClippingLayer)
        m_ancestorClippingLayer->setShowDebugBorder(showBorder);

    if (m_foregroundLayer) {
        m_foregroundLayer->setShowDebugBorder(showBorder);
        m_foregroundLayer->setShowRepaintCounter(showRepaintCounter);
    }

    if (m_contentsContainmentLayer)
        m_contentsContainmentLayer->setShowDebugBorder(showBorder);

    if (m_backgroundLayer) {
        m_backgroundLayer->setShowDebugBorder(showBorder);
        m_backgroundLayer->setShowRepaintCounter(showRepaintCounter);
    }

    if (m_maskLayer) {
        m_maskLayer->setShowDebugBorder(showBorder);
        m_maskLayer->setShowRepaintCounter(showRepaintCounter);
    }

    if (m_layerForHorizontalScrollbar)
        m_layerForHorizontalScrollbar->setShowDebugBorder(showBorder);

    if (m_layerForVerticalScrollbar)
        m_layerForVerticalScrollbar->setShowDebugBorder(showBorder);

    if (m_layerForScrollCorner)
        m_layerForScrollCorner->setShowDebugBorder(showBorder);

    if (m_scrollContainerLayer)
        m_scrollContainerLayer->setShowDebugBorder(showBorder);

    if (m_scrolledContentsLayer) {
        m_scrolledContentsLayer->setShowDebugBorder(showBorder);
        m_scrolledContentsLayer->setShowRepaintCounter(showRepaintCounter);
    }
}

void RenderLayerBacking::createPrimaryGraphicsLayer()
{
    String layerName;
#ifndef NDEBUG
    layerName = nameForLayer();
#endif
    
    // The call to createGraphicsLayer ends calling back into here as
    // a GraphicsLayerClient to ask if it shouldUseTileCache(). We only want
    // the tile cache on our main layer. This is pretty ugly, but saves us from
    // exposing the API to all clients.

    m_graphicsLayer = createGraphicsLayer(layerName, m_usingTiledCacheLayer ? GraphicsLayer::Type::PageTiledBacking : GraphicsLayer::Type::Normal);

    if (m_usingTiledCacheLayer) {
        m_childContainmentLayer = createGraphicsLayer("TileCache Flattening Layer");
        m_graphicsLayer->addChild(m_childContainmentLayer.get());
	}

    if (m_isMainFrameRenderViewLayer) {
#if !PLATFORM(IOS)
        // Page scale is applied above the RenderView on iOS.
        m_graphicsLayer->setContentsOpaque(true);
        m_graphicsLayer->setAppliesPageScale();
#endif
    }

#if PLATFORM(MAC) && USE(CA)
    if (!compositor().acceleratedDrawingEnabled() && renderer().isCanvas()) {
        HTMLCanvasElement* canvas = static_cast<HTMLCanvasElement*>(renderer().element());
        if (canvas->shouldAccelerate(canvas->size()))
            m_graphicsLayer->setAcceleratesDrawing(true);
    }
#endif    
    
    updateOpacity(renderer().style());
    updateLayerTransform(renderer().style());
#if ENABLE(CSS_FILTERS)
    updateLayerFilters(renderer().style());
#endif
#if ENABLE(FILTERS_LEVEL_2)
    updateBackdropFilters(renderer().style());
#endif
#if ENABLE(CSS_COMPOSITING)
    updateBlendMode(renderer().style());
#endif
}

#if PLATFORM(IOS)
void RenderLayerBacking::layerWillBeDestroyed()
{
    RenderObject& renderer = this->renderer();
    if (renderer.isRenderEmbeddedObject() && toRenderEmbeddedObject(renderer).allowsAcceleratedCompositing()) {
        PluginViewBase* pluginViewBase = toPluginViewBase(toRenderWidget(renderer).widget());
        if (pluginViewBase && m_graphicsLayer->contentsLayerForMedia())
            pluginViewBase->detachPluginLayer();
    }
}
#endif

void RenderLayerBacking::destroyGraphicsLayers()
{
    if (m_graphicsLayer) {
        willDestroyLayer(m_graphicsLayer.get());
        m_graphicsLayer->removeFromParent();
    }

    m_transformFlatteningLayer = nullptr;
    m_ancestorClippingLayer = nullptr;
    m_contentsContainmentLayer = nullptr;
    m_graphicsLayer = nullptr;
    m_foregroundLayer = nullptr;
    m_backgroundLayer = nullptr;
    m_childContainmentLayer = nullptr;
    m_maskLayer = nullptr;
    m_childClippingMaskLayer = nullptr;

    m_scrollContainerLayer = nullptr;
    m_scrolledContentsLayer = nullptr;
}

static LayoutRect scrollContainerLayerBox(const RenderBox& renderBox)
{
    return renderBox.paddingBoxRect();
}

static LayoutRect clippingLayerBox(const RenderBox& renderBox)
{
    LayoutRect result = LayoutRect::infiniteRect();
    if (renderBox.hasNonVisibleOverflow())
        result = const_cast<RenderBox&>(renderBox).overflowClipRect(LayoutPoint(), nullptr); // FIXME: Incorrect for CSS regions.

    if (renderBox.hasClip())
        result.intersect(const_cast<RenderBox&>(renderBox).clipRect(LayoutPoint(), nullptr)); // FIXME: Incorrect for CSS regions.

    return result;
}

static LayoutRect overflowControlsHostLayerBox(const RenderBox& renderBox)
{
    return renderBox.paddingBoxRectIncludingScrollbar();
}

void RenderLayerBacking::updateOpacity(const RenderStyle* style)
{
    m_graphicsLayer->setOpacity(compositingOpacity(style->opacity()));
}

void RenderLayerBacking::updateLayerTransform(const RenderStyle* style)
{
    // FIXME: This could use m_owningLayer.transform(), but that currently has transform-origin
    // baked into it, and we don't want that.
    TransformationMatrix t;
    if (m_owningLayer.isTransformed())
        m_owningLayer.updateTransformFromStyle(t, *style, RenderStyle::individualTransformOperations());

    if (m_contentsContainmentLayer) {
        m_contentsContainmentLayer->setTransform(t);
        m_graphicsLayer->setTransform(TransformationMatrix());
    } else
    	m_graphicsLayer->setTransform(t);
}

void RenderLayerBacking::updateChildrenTransformAndAnchorPoint(const LayoutRect& primaryGraphicsLayerRect, LayoutSize offsetFromParentGraphicsLayer)
{
	FloatPoint3D defaultAnchorPoint = FloatPoint3D(0.5, 0.5, 0);
    if (!renderer().hasTransformRelatedProperty()) {
        m_graphicsLayer->setAnchorPoint(defaultAnchorPoint);
        if (m_contentsContainmentLayer)
            m_contentsContainmentLayer->setAnchorPoint(defaultAnchorPoint);

        if (m_childContainmentLayer)
            m_childContainmentLayer->setAnchorPoint(defaultAnchorPoint);

        if (m_scrollContainerLayer)
            m_scrollContainerLayer->setAnchorPoint(defaultAnchorPoint);

        if (m_scrolledContentsLayer)
            m_scrolledContentsLayer->setPreserves3D(false);
        return;
    }

    auto& renderBox = toRenderBox(renderer());
    const float deviceScaleFactor = this->deviceScaleFactor();
    auto transformOrigin = m_owningLayer.transformOriginPixelSnappedIfNeeded();
    auto layerOffset = roundPointToDevicePixels(toLayoutPoint(offsetFromParentGraphicsLayer), deviceScaleFactor);
    auto anchor = FloatPoint3D(
        primaryGraphicsLayerRect.width() ? ((layerOffset.x() - primaryGraphicsLayerRect.x()) + transformOrigin.x()) / primaryGraphicsLayerRect.width() : 0.5f,
        primaryGraphicsLayerRect.height() ? ((layerOffset.y() - primaryGraphicsLayerRect.y())+ transformOrigin.y()) / primaryGraphicsLayerRect.height() : 0.5f,
        transformOrigin.z()
    );

    if (m_contentsContainmentLayer)
        m_contentsContainmentLayer->setAnchorPoint(anchor);
    else
        m_graphicsLayer->setAnchorPoint(anchor);

    auto removeChildrenTransformFromLayers = [&](GraphicsLayer* layerToIgnore = nullptr) {
        auto* clippingLayer = this->clippingLayer();
        if (clippingLayer && clippingLayer != layerToIgnore) {
            clippingLayer->setChildrenTransform(TransformationMatrix());
            clippingLayer->setAnchorPoint(defaultAnchorPoint);
        }

        if (m_scrollContainerLayer && m_scrollContainerLayer != layerToIgnore) {
            m_scrollContainerLayer->setChildrenTransform(TransformationMatrix());
            m_scrollContainerLayer->setAnchorPoint(defaultAnchorPoint);
            m_scrolledContentsLayer->setPreserves3D(false);
        }

        if (m_graphicsLayer != layerToIgnore)
            m_graphicsLayer->setChildrenTransform(TransformationMatrix());
    };

    if (!renderer().style()->hasPerspective()) {
        removeChildrenTransformFromLayers();
        return;
    }

    GraphicsLayer* layerForPerspective = nullptr;
    FloatRect layerForPerspectiveRect;
	if (m_scrollContainerLayer) {
		layerForPerspective = m_scrollContainerLayer.get();
		layerForPerspectiveRect = scrollContainerLayerBox(renderBox);
	} else if (auto* layer = clippingLayer()) {
		layerForPerspective = layer;
		layerForPerspectiveRect = clippingLayerBox(renderBox);
	} else {
		layerForPerspective = m_graphicsLayer.get();
		layerForPerspectiveRect = renderer().transformReferenceBoxRect();
	}

    // FIXME: perspectiveRelativeBox isn't quite right here. This needs work: webkit.org/b/211787.
	if (layerForPerspective != m_graphicsLayer) {
		// If we have scrolling layers, we need the children transform on m_scrollContainerLayer to
		// affect children of m_scrolledContentsLayer, so set setPreserves3D(true).
		if (layerForPerspective == m_scrollContainerLayer)
			m_scrolledContentsLayer->setPreserves3D(true);

		auto perspectiveAnchorPoint = FloatPoint3D {
			layerForPerspectiveRect.width() ? (transformOrigin.x() - layerForPerspectiveRect.x()) / layerForPerspectiveRect.width() : 0.5f,
			layerForPerspectiveRect.height() ? (transformOrigin.y() - layerForPerspectiveRect.y()) / layerForPerspectiveRect.height() : 0.5f,
			transformOrigin.z()
		};

		layerForPerspective->setAnchorPoint(perspectiveAnchorPoint);
	}

	layerForPerspective->setChildrenTransform(m_owningLayer.perspectiveTransform());
    removeChildrenTransformFromLayers(layerForPerspective);
}

#if ENABLE(CSS_FILTERS)
void RenderLayerBacking::updateLayerFilters(const RenderStyle* style)
{
    m_canCompositeFilters = m_graphicsLayer->setFilters(style->filter());
}
#endif

#if ENABLE(FILTERS_LEVEL_2)
void RenderLayerBacking::updateBackdropFilters(const RenderStyle* style)
{
    m_canCompositeBackdropFilters = m_graphicsLayer->setBackdropFilters(style->backdropFilter());
}

void RenderLayerBacking::updateBackdropFiltersGeometry()
{
    if (!m_canCompositeBackdropFilters)
        return;

    if (!renderer().isBox())
        return;

    RenderBox& renderBox = toRenderBox(this->renderer());

    FloatRoundedRect backdropFiltersRect;
    if (renderBox.style()->hasBorderRadius() && !renderBox.hasClip()) {
        auto roundedBoxRect = renderBox.roundedBorderBoxRect();
        roundedBoxRect.move(contentOffsetInCompositingLayer());
        backdropFiltersRect = roundedBoxRect.pixelSnappedRoundedRectForPainting(deviceScaleFactor());
    } else {
        auto boxRect = renderBox.borderBoxRect();
        if (renderBox.hasClip())
            boxRect.intersect(renderBox.clipRect(LayoutPoint(), nullptr));
        boxRect.move(contentOffsetInCompositingLayer());
        backdropFiltersRect = FloatRoundedRect(snapRectToDevicePixels(boxRect, deviceScaleFactor()));
    }

    m_graphicsLayer->setBackdropFiltersRect(backdropFiltersRect);
}
#endif

#if ENABLE(CSS_COMPOSITING)
void RenderLayerBacking::updateBlendMode(const RenderStyle* style)
{
    if (m_ancestorClippingLayer) {
        m_ancestorClippingLayer->setBlendMode(style->blendMode());
        m_graphicsLayer->setBlendMode(BlendModeNormal);
    } else
        m_graphicsLayer->setBlendMode(style->blendMode());
}
#endif


inline void RenderLayerBacking::updateCustomAppearance(const RenderStyle* style)
{
#if !PLATFORM(ESPIAL)
    ControlPart appearance = style->effectiveAppearance();
    if (appearance == MediaControlsLightBarBackgroundPart)
        m_graphicsLayer->setCustomAppearance(GraphicsLayer::CustomAppearance::LightBackdrop);
    else if (appearance == MediaControlsDarkBarBackgroundPart)
        m_graphicsLayer->setCustomAppearance(GraphicsLayer::CustomAppearance::DarkBackdrop);
    else
        m_graphicsLayer->setCustomAppearance(GraphicsLayer::CustomAppearance::None);
#endif
}

static bool hasNonZeroTransformOrigin(const RenderElement& renderer)
{
    auto* style = renderer.style();
    return (style->transformOriginX().type() == LengthType::Fixed && style->transformOriginX().value())
        || (style->transformOriginY().type() == LengthType::Fixed && style->transformOriginY().value());
}

#if PLATFORM(IOS)
// FIXME: We should merge the concept of RenderLayer::{hasAcceleratedTouchScrolling, needsCompositedScrolling}()
// so that we can remove this iOS-specific variant.
static bool layerOrAncestorIsTransformedOrScrolling(RenderLayer& layer)
{
    for (RenderLayer* curr = &layer; curr; curr = curr->parent()) {
        if (curr->isTransformed() || curr->hasAcceleratedTouchScrolling())
            return true;
    }

    return false;
}
#else
static bool layerOrAncestorIsTransformedOrUsingCompositedScrolling(RenderLayer& layer)
{
    for (RenderLayer* curr = &layer; curr; curr = curr->parent()) {
        if (curr->isTransformed() || curr->usesCompositedScrolling())
            return true;
    }
    
    return false;
}
#endif

bool RenderLayerBacking::shouldClipCompositedBounds() const
{
#if !PLATFORM(IOS)
    // Scrollbar layers use this layer for relative positioning, so don't clip.
    if (layerForHorizontalScrollbar() || layerForVerticalScrollbar())
        return false;
#endif

    if (m_usingTiledCacheLayer)
        return false;

#if !PLATFORM(IOS)
    if (layerOrAncestorIsTransformedOrUsingCompositedScrolling(m_owningLayer))
        return false;
#else
    if (layerOrAncestorIsTransformedOrScrolling(m_owningLayer))
        return false;
#endif

    return true;
}

bool RenderLayerBacking::updateCompositedBounds()
{
    LayoutRect layerBounds = m_owningLayer.calculateLayerBounds(&m_owningLayer, LayoutSize(), RenderLayer::DefaultCalculateLayerBoundsFlags | RenderLayer::ExcludeHiddenDescendants | RenderLayer::DontConstrainForMask);
    // Clip to the size of the document or enclosing overflow-scroll layer.
    // If this or an ancestor is transformed, we can't currently compute the correct rect to intersect with.
    // We'd need RenderObject::convertContainerToLocalQuad(), which doesn't yet exist.
    if (shouldClipCompositedBounds()) {
        RenderView& view = renderer().view();
        RenderLayer* rootLayer = view.layer();

        LayoutRect clippingBounds;
        if (renderer().isFixedPositioned() && renderer().container() == &view)
            clippingBounds = view.frameView().rectForFixedPositionLayout();
        else
            clippingBounds = view.unscaledDocumentRect();

        if (&m_owningLayer != rootLayer)
            clippingBounds.intersect(m_owningLayer.backgroundClipRect(RenderLayer::ClipRectsContext(rootLayer, AbsoluteClipRects)).rect()); // FIXME: Incorrect for CSS regions.

        LayoutPoint delta = m_owningLayer.convertToLayerCoords(rootLayer, LayoutPoint(), RenderLayer::AdjustForColumns);
        clippingBounds.move(-delta.x(), -delta.y());

        layerBounds.intersect(clippingBounds);
    }
    
    // If the element has a transform-origin that has fixed lengths, and the renderer has zero size,
    // then we need to ensure that the compositing layer has non-zero size so that we can apply
    // the transform-origin via the GraphicsLayer anchorPoint (which is expressed as a fractional value).
    if (layerBounds.isEmpty() && (hasNonZeroTransformOrigin(renderer()) || renderer().style()->hasPerspective())) {
    	layerBounds.setWidth(1);
        layerBounds.setHeight(1);
        m_artificiallyInflatedBounds = true;
    } else
        m_artificiallyInflatedBounds = false;

    return setCompositedBounds(layerBounds);
}

void RenderLayerBacking::updateAfterWidgetResize()
{
    if (!renderer().isWidget())
        return;

	if (RenderLayerCompositor* innerCompositor = RenderLayerCompositor::frameContentsCompositor(toRenderWidget(renderer()))) {
		innerCompositor->frameViewDidChangeSize();
		innerCompositor->frameViewDidChangeLocation(flooredIntPoint(contentsBox().location()));
	}
}

void RenderLayerBacking::updateAfterLayout(bool needsClippingUpdate, bool needsFullRepaint)
{
    //LOG(Compositing, "RenderLayerBacking %p updateAfterLayout (layer %p)", this, &m_owningLayer);

    // This is the main trigger for layout changing layer geometry, but we have to do the work again in updateBackingAndHierarchy()
    // when we know the final compositing hierarchy. We can't just set dirty bits from RenderLayer::setSize() because that doesn't
    // take overflow into account.
    if (updateCompositedBounds()) {
        m_owningLayer.setNeedsCompositingGeometryUpdate();
        // This layer's geometry affects those of its children.
        m_owningLayer.setChildrenNeedCompositingGeometryUpdate();
    } else if (needsClippingUpdate)
        m_owningLayer.setNeedsCompositingGeometryUpdate();

    if (needsFullRepaint && canIssueSetNeedsDisplay())
        setContentsNeedDisplay();
}

// This can only update things that don't require up-to-date layout.
void RenderLayerBacking::updateConfigurationAfterStyleChange()
{
    updateMaskingLayer(renderer().hasMask(), renderer().hasClipPath());

    if (m_owningLayer.hasReflection()) {
        if (m_owningLayer.reflectionLayer()->backing()) {
            auto* reflectionLayer = m_owningLayer.reflectionLayer()->backing()->graphicsLayer();
            m_graphicsLayer->setReplicatedByLayer(reflectionLayer);
        }
    } else
        m_graphicsLayer->setReplicatedByLayer(nullptr);

    // FIXME: do we care if opacity is animating?
    auto* style = renderer().style();
    updateOpacity(style);
    updateLayerFilters(style);

#if ENABLE(FILTERS_LEVEL_2)
    updateBackdropFilters(style);
#endif
#if ENABLE(CSS_COMPOSITING)
    updateBlendMode(style);
#endif
    updateCustomAppearance(style);
}

bool RenderLayerBacking::updateConfiguration()
{
    ASSERT(!m_owningLayer.normalFlowListDirty());
    ASSERT(!m_owningLayer.zOrderListsDirty());
    ASSERT(!renderer().view().needsLayout());

    auto* compositingAncestor = m_owningLayer.ancestorCompositingLayer();

    bool layerConfigChanged = false;
    auto& compositor = this->compositor();

    if (updateTransformFlatteningLayer(compositingAncestor))
        layerConfigChanged = true;

    setBackgroundLayerPaintsFixedRootBackground(compositor.needsFixedRootBackgroundLayer(m_owningLayer));

    if (updateBackgroundLayer(m_backgroundLayerPaintsFixedRootBackground))
        layerConfigChanged = true;

    if (updateForegroundLayer(compositor.needsContentsCompositingLayer(m_owningLayer)))
        layerConfigChanged = true;

    // This requires descendants to have been updated.
    bool needsDescendantsClippingLayer = RenderLayerCompositor::clipsCompositingDescendants(m_owningLayer);

#if PLATFORM(IOS)
    // Our scrolling layer will clip.
    if (m_owningLayer.hasAcceleratedTouchScrolling())
    	needsDescendantsClippingLayer = false;
#else
    // Our scrolling layer will clip.
    if (m_owningLayer.usesCompositedScrolling())
    	needsDescendantsClippingLayer = false;
#endif // PLATFORM(IOS)

#if PLATFORM(IOS)
    if (updateScrollingLayers(m_owningLayer.hasAcceleratedTouchScrolling()))
        layerConfigChanged = true;
#else
    if (updateScrollingLayers(m_owningLayer.usesCompositedScrolling()))
        layerConfigChanged = true;
#endif // PLATFORM(IOS)

    if (updateDescendantClippingLayer(needsDescendantsClippingLayer))
        layerConfigChanged = true;

    if (updateAncestorClippingLayer(compositor.clippedByAncestor(m_owningLayer, compositingAncestor)))
        layerConfigChanged = true;

    if (updateOverflowControlsLayers(requiresHorizontalScrollbarLayer(), requiresVerticalScrollbarLayer(), requiresScrollCornerLayer()))
        layerConfigChanged = true;

    if (layerConfigChanged)
        updateInternalHierarchy();

    if (GraphicsLayer* flatteningLayer = tileCacheFlatteningLayer()) {
        if (layerConfigChanged || flatteningLayer->parent() != m_graphicsLayer)
        	m_graphicsLayer->addChild(flatteningLayer);
    }

    if (updateMaskingLayer(renderer().hasMask(), renderer().hasClipPath()))
        layerConfigChanged = true;

    updateChildClippingStrategy(needsDescendantsClippingLayer);

    if (m_owningLayer.hasReflection()) {
        if (m_owningLayer.reflectionLayer()->backing()) {
            GraphicsLayer* reflectionLayer = m_owningLayer.reflectionLayer()->backing()->graphicsLayer();
            m_graphicsLayer->setReplicatedByLayer(reflectionLayer);
        }
    } else
        m_graphicsLayer->setReplicatedByLayer(nullptr);

    // Requires layout.
    if (!m_owningLayer.isRenderViewLayer()) {
		bool isSimpleContainer = isSimpleContainerCompositingLayer();
		bool didUpdateContentsRect = false;
		updateDirectlyCompositedBoxDecorations(isSimpleContainer, didUpdateContentsRect);
    } else
    	updateRootLayerConfiguration();

    // Requires layout.
    if (isDirectlyCompositedImage())
        updateImageContents();

    if (renderer().isRenderEmbeddedObject() && toRenderEmbeddedObject(renderer()).allowsAcceleratedCompositing()) {
        PluginViewBase* pluginViewBase = static_cast<PluginViewBase*>(toRenderWidget(renderer()).widget());
#if PLATFORM(IOS)
        if (pluginViewBase && !m_graphicsLayer->contentsLayerForMedia()) {
            pluginViewBase->detachPluginLayer();
            pluginViewBase->attachPluginLayer();
        }
#else
        m_graphicsLayer->setContentsToMedia(pluginViewBase->platformLayer());
#endif
    }
#if ENABLE(VIDEO)
    else if (renderer().isVideo() && toRenderVideo(renderer()).shouldDisplayVideo()) {
        HTMLMediaElement* mediaElement = static_cast<HTMLMediaElement*>(renderer().element());
        m_graphicsLayer->setContentsToMedia(mediaElement->platformLayer());
        updateContentsRects();
	}
#endif
#if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
    else if (isAcceleratedCanvas(renderer())) {
        HTMLCanvasElement* canvas = static_cast<HTMLCanvasElement*>(renderer().element());
        if (CanvasRenderingContext* context = canvas->renderingContext())
            m_graphicsLayer->setContentsToCanvas(context->platformLayer());

        layerConfigChanged = true;
    }
#endif
    if (renderer().isWidget() && RenderLayerCompositor::parentFrameContentLayers(toRenderWidget(renderer()))) {
        m_owningLayer.setNeedsCompositingGeometryUpdate();
        layerConfigChanged = true;
    }

    if (RenderLayerCompositor::isCompositedSubframeRenderer(renderer())) {
        m_graphicsLayer->setContentsRectClipsDescendants(true);
        updateContentsRects();
    }

    if (layerConfigChanged)
        updatePaintingPhases();

    return layerConfigChanged;
}

static LayoutRect clipBox(RenderBox& renderer)
{
    LayoutRect result = LayoutRect::infiniteRect();
    if (renderer.hasNonVisibleOverflow())
        result = renderer.overflowClipRect(LayoutPoint(), nullptr); // FIXME: Incorrect for CSS regions.

    if (renderer.hasClip())
        result.intersect(renderer.clipRect(LayoutPoint(), nullptr)); // FIXME: Incorrect for CSS regions.

    return result;
}

static bool subpixelOffsetFromRendererChanged(const LayoutSize& oldSubpixelOffsetFromRenderer, const LayoutSize& newSubpixelOffsetFromRenderer, float deviceScaleFactor)
{
    FloatSize previous = snapSizeToDevicePixel(oldSubpixelOffsetFromRenderer, LayoutPoint(), deviceScaleFactor);
    FloatSize current = snapSizeToDevicePixel(newSubpixelOffsetFromRenderer, LayoutPoint(), deviceScaleFactor);
    return previous != current;
}

static FloatSize subpixelForLayerPainting(const LayoutPoint& point, float pixelSnappingFactor)
{
    LayoutUnit x = point.x();
    LayoutUnit y = point.y();
    x = x >= 0 ? floorToDevicePixel(x, pixelSnappingFactor) : ceilToDevicePixel(x, pixelSnappingFactor);
    y = y >= 0 ? floorToDevicePixel(y, pixelSnappingFactor) : ceilToDevicePixel(y, pixelSnappingFactor);
    return point - LayoutPoint(x, y);
}

struct OffsetFromRenderer {
    // 1.2px - > { m_devicePixelOffset = 1px m_subpixelOffset = 0.2px }
    LayoutSize m_devicePixelOffset;
    LayoutSize m_subpixelOffset;
};

static OffsetFromRenderer computeOffsetFromRenderer(const LayoutSize& offset, float deviceScaleFactor)
{
    OffsetFromRenderer offsetFromRenderer;
    offsetFromRenderer.m_subpixelOffset = LayoutSize(subpixelForLayerPainting(toLayoutPoint(offset), deviceScaleFactor));
    offsetFromRenderer.m_devicePixelOffset = offset - offsetFromRenderer.m_subpixelOffset;
    return offsetFromRenderer;
}

struct SnappedRectInfo {
    LayoutRect m_snappedRect;
    LayoutSize m_snapDelta;
};

static SnappedRectInfo snappedGraphicsLayer(const LayoutSize& offset, const LayoutSize& size, float deviceScaleFactor)
{
    SnappedRectInfo snappedGraphicsLayer;
    LayoutRect graphicsLayerRect = LayoutRect(toLayoutPoint(offset), size);
    snappedGraphicsLayer.m_snappedRect = LayoutRect(snapRectToDevicePixels(graphicsLayerRect, deviceScaleFactor));
    snappedGraphicsLayer.m_snapDelta = snappedGraphicsLayer.m_snappedRect.location() - toLayoutPoint(offset);
    return snappedGraphicsLayer;
}

static LayoutSize computeOffsetFromAncestorGraphicsLayer(RenderLayer* compositedAncestor, const LayoutPoint& location, float deviceScaleFactor)
{
    if (!compositedAncestor)
        return toLayoutSize(location);

    // FIXME: This is a workaround until after webkit.org/b/162634 gets fixed. ancestorSubpixelOffsetFromRenderer
    // could be stale when a dynamic composited state change triggers a pre-order updateGeometry() traversal.
    LayoutSize ancestorSubpixelOffsetFromRenderer = compositedAncestor->backing()->subpixelOffsetFromRenderer();
    LayoutRect ancestorCompositedBounds = compositedAncestor->backing()->compositedBounds();
    LayoutSize floored = toLayoutSize(LayoutPoint(floorPointToDevicePixels(ancestorCompositedBounds.location() - ancestorSubpixelOffsetFromRenderer, deviceScaleFactor)));
    LayoutSize ancestorRendererOffsetFromAncestorGraphicsLayer = -(floored + ancestorSubpixelOffsetFromRenderer);
    return ancestorRendererOffsetFromAncestorGraphicsLayer + toLayoutSize(location);
}

class ComputedOffsets {
public:
    ComputedOffsets(const RenderLayer& renderLayer, const LayoutRect& localRect, const LayoutRect& parentGraphicsLayerRect, const LayoutRect& primaryGraphicsLayerRect)
        : m_renderLayer(renderLayer)
        , m_location(localRect.location())
        , m_parentGraphicsLayerOffset(toLayoutSize(parentGraphicsLayerRect.location()))
        , m_primaryGraphicsLayerOffset(toLayoutSize(primaryGraphicsLayerRect.location()))
		, m_deviceScaleFactor(renderLayer.renderer().document().deviceScaleFactor())
    {
    }

    LayoutSize fromParentGraphicsLayer()
    {
        if (!m_fromParentGraphicsLayer)
            m_fromParentGraphicsLayer = fromAncestorGraphicsLayer() - m_parentGraphicsLayerOffset;
        return m_fromParentGraphicsLayer.value();
    }

    LayoutSize fromPrimaryGraphicsLayer()
    {
        if (!m_fromPrimaryGraphicsLayer)
            m_fromPrimaryGraphicsLayer = fromAncestorGraphicsLayer() - m_parentGraphicsLayerOffset - m_primaryGraphicsLayerOffset;
        return m_fromPrimaryGraphicsLayer.value();
    }

private:
    LayoutSize fromAncestorGraphicsLayer()
    {
        if (!m_fromAncestorGraphicsLayer) {
            RenderLayer* compositedAncestor = m_renderLayer.ancestorCompositingLayer();
            LayoutPoint localPointInAncestorRenderLayerCoords = m_renderLayer.convertToLayerCoords(compositedAncestor, m_location, RenderLayer::AdjustForColumns);
            m_fromAncestorGraphicsLayer = computeOffsetFromAncestorGraphicsLayer(compositedAncestor, localPointInAncestorRenderLayerCoords, m_deviceScaleFactor);
        }
        return m_fromAncestorGraphicsLayer.value();
    }

    Optional<LayoutSize> m_fromAncestorGraphicsLayer;
    Optional<LayoutSize> m_fromParentGraphicsLayer;
    Optional<LayoutSize> m_fromPrimaryGraphicsLayer;

    const RenderLayer& m_renderLayer;
    // Location is relative to the renderer.
    const LayoutPoint m_location;
    const LayoutSize m_parentGraphicsLayerOffset;
    const LayoutSize m_primaryGraphicsLayerOffset;
    float m_deviceScaleFactor;
};

LayoutRect RenderLayerBacking::computePrimaryGraphicsLayerRect(const LayoutRect& parentGraphicsLayerRect) const
{
    ComputedOffsets compositedBoundsOffset(m_owningLayer, compositedBounds(), parentGraphicsLayerRect, LayoutRect());
    return LayoutRect(encloseRectToDevicePixels(LayoutRect(toLayoutPoint(compositedBoundsOffset.fromParentGraphicsLayer()), compositedBounds().size()),
        deviceScaleFactor()));
}

// FIXME: See if we need this now that updateGeometry() is always called in post-order traversal.
LayoutRect RenderLayerBacking::computeParentGraphicsLayerRect(RenderLayer* compositedAncestor, LayoutSize& ancestorClippingLayerOffset) const
{
    if (!compositedAncestor || !compositedAncestor->backing())
        return renderer().view().documentRect();

    auto* ancestorBackingLayer = compositedAncestor->backing();
    LayoutRect parentGraphicsLayerRect;
    if (m_owningLayer.isInsideFlowThread()) {
        /// FIXME: flows/columns need work.
        LayoutRect ancestorCompositedBounds = ancestorBackingLayer->compositedBounds();
        ancestorCompositedBounds.setLocation(LayoutPoint());
        parentGraphicsLayerRect = ancestorCompositedBounds;
    }

    if (ancestorBackingLayer->hasClippingLayer()) {
        // If the compositing ancestor has a layer to clip children, we parent in that, and therefore position relative to it.
        LayoutRect clippingBox = clipBox(toRenderBox(compositedAncestor->renderer()));
        LayoutSize clippingBoxOffset = computeOffsetFromAncestorGraphicsLayer(compositedAncestor, clippingBox.location(), deviceScaleFactor());
        parentGraphicsLayerRect = snappedGraphicsLayer(clippingBoxOffset, clippingBox.size(), deviceScaleFactor()).m_snappedRect;
    }

#if PLATFORM(IOS)
    if (compositedAncestor->hasTouchScrollableOverflow()) {
        auto& renderBox = downcast<RenderBox>(compositedAncestor->renderer());
        LayoutRect paddingBox(renderBox.borderLeft(), renderBox.borderTop(),
            renderBox.width() - renderBox.borderLeft() - renderBox.borderRight(),
            renderBox.height() - renderBox.borderTop() - renderBox.borderBottom());
        ScrollOffset scrollOffset = compositedAncestor->scrollOffset();
        parentGraphicsLayerRect = LayoutRect((paddingBox.location() - toLayoutSize(scrollOffset)), paddingBox.size());
    }
#else
    if (compositedAncestor->usesCompositedScrolling()) {
        auto& renderBox = toRenderBox(compositedAncestor->renderer());
        LayoutPoint scrollOrigin(renderBox.borderLeft(), renderBox.borderTop());
        parentGraphicsLayerRect = LayoutRect(scrollOrigin - toLayoutSize(compositedAncestor->scrollOffset()), renderBox.borderBoxRect().size());
    }
#endif

    if (m_ancestorClippingLayer) {
        // Call calculateRects to get the backgroundRect which is what is used to clip the contents of this
        // layer. Note that we call it with temporaryClipRects = true because normally when computing clip rects
        // for a compositing layer, rootLayer is the layer itself.
        ShouldRespectOverflowClip shouldRespectOverflowClip = compositedAncestor->isolatesCompositedBlending() ? RespectOverflowClip : IgnoreOverflowClip;
        RenderLayer::ClipRectsContext clipRectsContext(compositedAncestor, TemporaryClipRects, IgnoreOverlayScrollbarSize, shouldRespectOverflowClip);
        LayoutRect parentClipRect = m_owningLayer.backgroundClipRect(clipRectsContext).rect(); // FIXME: Incorrect for CSS regions.
        ASSERT(!parentClipRect.isInfinite());
        LayoutSize clippingOffset = computeOffsetFromAncestorGraphicsLayer(compositedAncestor, parentClipRect.location(), deviceScaleFactor());
        LayoutRect snappedClippingLayerRect = snappedGraphicsLayer(clippingOffset, parentClipRect.size(), deviceScaleFactor()).m_snappedRect;
        // The primary layer is then parented in, and positioned relative to this clipping layer.
        ancestorClippingLayerOffset = snappedClippingLayerRect.location() - parentGraphicsLayerRect.location();
        parentGraphicsLayerRect = snappedClippingLayerRect;
    }
    return parentGraphicsLayerRect;
}

void RenderLayerBacking::updateGeometry()
{
    ASSERT(!m_owningLayer.normalFlowListDirty());
    ASSERT(!m_owningLayer.zOrderListsDirty());
    ASSERT(!m_owningLayer.descendantDependentFlagsAreDirty());
    ASSERT(!renderer().view().needsLayout());

    auto* style = renderer().style();
    const auto deviceScaleFactor = this->deviceScaleFactor();

#if 0
    bool isRunningAcceleratedTransformAnimation = false;
	if (auto* timeline = renderer().documentTimeline())
		isRunningAcceleratedTransformAnimation = timeline->isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyTransform);
#endif

    updateLayerTransform(style);
    updateOpacity(style);
#if ENABLE(CSS_FILTERS)
    updateLayerFilters(style);
#endif
#if ENABLE(FILTERS_LEVEL_2)
    updateBackdropFilters(style);
#endif
#if ENABLE(CSS_COMPOSITING)
    updateBlendMode(style);
#endif

    // FIXME: reflections should force transform-style to be flat in the style: https://bugs.webkit.org/show_bug.cgi?id=106959
	bool preserves3D = style->preserves3D() && !renderer().hasReflection();
	m_graphicsLayer->setPreserves3D(preserves3D);
    m_graphicsLayer->setBackfaceVisibility(style->backfaceVisibility() == BackfaceVisibilityVisible);

    RenderLayer* compositedAncestor = m_owningLayer.ancestorCompositingLayer();
    LayoutSize ancestorClippingLayerOffset;
    LayoutRect parentGraphicsLayerRect = computeParentGraphicsLayerRect(compositedAncestor, ancestorClippingLayerOffset);
    LayoutRect primaryGraphicsLayerRect = computePrimaryGraphicsLayerRect(parentGraphicsLayerRect);

    ComputedOffsets compositedBoundsOffset(m_owningLayer, compositedBounds(), parentGraphicsLayerRect, primaryGraphicsLayerRect);
    m_compositedBoundsOffsetFromGraphicsLayer = compositedBoundsOffset.fromPrimaryGraphicsLayer();
    m_graphicsLayer->setPosition(primaryGraphicsLayerRect.location());
    m_graphicsLayer->setSize(primaryGraphicsLayerRect.size());

#if 0
    auto computeAnimationExtent = [&] () -> Optional<FloatRect> {
        LayoutRect animatedBounds;
        if (isRunningAcceleratedTransformAnimation && m_owningLayer.getOverlapBoundsIncludingChildrenAccountingForTransformAnimations(animatedBounds, RenderLayer::IncludeCompositedDescendants))
            return FloatRect(animatedBounds);
        return Nullopt;
    };
    m_graphicsLayer->setAnimationExtent(computeAnimationExtent());
#endif

    ComputedOffsets rendererOffset(m_owningLayer, LayoutRect(), parentGraphicsLayerRect, primaryGraphicsLayerRect);
    if (m_ancestorClippingLayer) {
        // Clipping layer is parented in the ancestor layer.
        m_ancestorClippingLayer->setPosition(toLayoutPoint(ancestorClippingLayerOffset));
        m_ancestorClippingLayer->setSize(parentGraphicsLayerRect.size());
        m_ancestorClippingLayer->setOffsetFromRenderer(-rendererOffset.fromParentGraphicsLayer());
    }

    if (m_contentsContainmentLayer) {
        m_contentsContainmentLayer->setPreserves3D(preserves3D);
        m_contentsContainmentLayer->setPosition(primaryGraphicsLayerRect.location());
        m_graphicsLayer->setPosition(FloatPoint());
        // Use the same size as m_graphicsLayer so transforms behave correctly.
        m_contentsContainmentLayer->setSize(primaryGraphicsLayerRect.size());
    }

#if ENABLE(CSS_TRANSFORM_STYLE_OPTIMIZED_3D)
    // FIXME: Take ancestry into account and remove unnecessary structural layers.
    m_graphicsLayer->setIsSeparated(style.usedTransformStyle3D() == TransformStyle3D::Optimized3D);
#endif

    // Compute renderer offset from primary graphics layer. Note that primaryGraphicsLayerRect is in parentGraphicsLayer's coordinate system which is not necessarily
	// the same as the ancestor graphics layer.
    OffsetFromRenderer primaryGraphicsLayerOffsetFromRenderer;
    LayoutSize oldSubpixelOffsetFromRenderer = m_subpixelOffsetFromRenderer;
    primaryGraphicsLayerOffsetFromRenderer = computeOffsetFromRenderer(-rendererOffset.fromPrimaryGraphicsLayer(), deviceScaleFactor);
    m_subpixelOffsetFromRenderer = primaryGraphicsLayerOffsetFromRenderer.m_subpixelOffset;
    m_hasSubpixelRounding = !m_subpixelOffsetFromRenderer.isZero() || compositedBounds().size() != primaryGraphicsLayerRect.size();

    if (primaryGraphicsLayerOffsetFromRenderer.m_devicePixelOffset != m_graphicsLayer->offsetFromRenderer()) {
        m_graphicsLayer->setOffsetFromRenderer(primaryGraphicsLayerOffsetFromRenderer.m_devicePixelOffset);
        positionOverflowControlsLayers();
    }

    // If we have a layer that clips children, position it.
    LayoutRect clippingBox;
    if (GraphicsLayer* clipLayer = clippingLayer()) {
        auto& renderBox = toRenderBox(renderer());
        // clipLayer is the m_childContainmentLayer.
        clippingBox = clipBox(toRenderBox(renderer()));
        // Clipping layer is parented in the primary graphics layer.
        LayoutSize clipBoxOffsetFromGraphicsLayer = toLayoutSize(clippingBox.location()) + rendererOffset.fromPrimaryGraphicsLayer();
        SnappedRectInfo snappedClippingGraphicsLayer = snappedGraphicsLayer(clipBoxOffsetFromGraphicsLayer, clippingBox.size(), deviceScaleFactor);
        clipLayer->setPosition(snappedClippingGraphicsLayer.m_snappedRect.location());
        clipLayer->setSize(snappedClippingGraphicsLayer.m_snappedRect.size());
        clipLayer->setOffsetFromRenderer(toLayoutSize(clippingBox.location() - snappedClippingGraphicsLayer.m_snapDelta));

        auto computeMasksToBoundsRect = [&] {
        if ((renderer().style()->clipPath() || renderer().style()->hasBorderRadius()) && !m_childClippingMaskLayer) {
				FloatRoundedRect contentsClippingRect = renderBox.roundedBorderBoxRect().pixelSnappedRoundedRectForPainting(deviceScaleFactor);
				contentsClippingRect.move(LayoutSize(-clipLayer->offsetFromRenderer()));
				return contentsClippingRect;
			}

			return FloatRoundedRect(FloatRect(FloatPoint(), snappedClippingGraphicsLayer.m_snappedRect.size()));
		};

		clipLayer->setMasksToBoundsRect(computeMasksToBoundsRect());

        if (m_childClippingMaskLayer && !m_scrollContainerLayer) {
            m_childClippingMaskLayer->setSize(clipLayer->size());
            m_childClippingMaskLayer->setPosition(FloatPoint());
            m_childClippingMaskLayer->setOffsetFromRenderer(clipLayer->offsetFromRenderer());
        }
    }

    if (m_maskLayer)
        updateMaskingLayerGeometry();

    updateChildrenTransformAndAnchorPoint(primaryGraphicsLayerRect, rendererOffset.fromParentGraphicsLayer());

    if (m_foregroundLayer) {
        FloatPoint foregroundPosition;
        FloatSize foregroundSize = primaryGraphicsLayerRect.size();
        FloatSize foregroundOffset = m_graphicsLayer->offsetFromRenderer();
        if (hasClippingLayer()) {
            // If we have a clipping layer (which clips descendants), then the foreground layer is a child of it,
            // so that it gets correctly sorted with children. In that case, position relative to the clipping layer.
            foregroundSize = FloatSize(clippingBox.size());
            foregroundOffset = toFloatSize(clippingBox.location());
        }

        m_foregroundLayer->setPosition(foregroundPosition);
		m_foregroundLayer->setSize(foregroundSize);
        m_foregroundLayer->setOffsetFromRenderer(foregroundOffset);
    }

    if (m_backgroundLayer) {
        FloatPoint backgroundPosition;
        FloatSize backgroundSize = primaryGraphicsLayerRect.size();
        if (backgroundLayerPaintsFixedRootBackground()) {
            FrameView& frameView = toRenderView(renderer()).frameView();
            backgroundPosition = frameView.scrollPositionForFixedPosition();
            backgroundSize = frameView.layoutSize();
        }
        m_backgroundLayer->setPosition(backgroundPosition);
		m_backgroundLayer->setSize(backgroundSize);
        m_backgroundLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
    }

    if (m_owningLayer.reflectionLayer() && m_owningLayer.reflectionLayer()->isComposited()) {
        RenderLayerBacking* reflectionBacking = m_owningLayer.reflectionLayer()->backing();
        reflectionBacking->updateGeometry();
        
        // The reflection layer has the bounds of m_owningLayer.reflectionLayer(),
        // but the reflected layer is the bounds of this layer, so we need to position it appropriately.
        FloatRect layerBounds = this->compositedBounds();
        FloatRect reflectionLayerBounds = reflectionBacking->compositedBounds();
        reflectionBacking->graphicsLayer()->setReplicatedLayerPosition(FloatPoint() + (layerBounds.location() - reflectionLayerBounds.location()));
    }

    if (m_scrollContainerLayer) {
        ASSERT(m_scrolledContentsLayer);
        RenderBox& renderBox = toRenderBox(renderer());
        LayoutRect paddingBox = renderBox.paddingBoxRect();
		ScrollOffset scrollOffset = m_owningLayer.scrollOffset();

        // FIXME: need to do some pixel snapping here.
        m_scrollContainerLayer->setPosition(FloatPoint(paddingBox.location() - compositedBounds().location()));
        m_scrollContainerLayer->setSize(roundedIntSize(LayoutSize(renderBox.clientWidth(), renderBox.clientHeight())));

        m_scrolledContentsLayer->setPosition(-scrollOffset);

        FloatSize oldScrollingLayerOffset = m_scrollContainerLayer->offsetFromRenderer();
        m_scrollContainerLayer->setOffsetFromRenderer(-toFloatSize(paddingBox.location()));

        if (m_childClippingMaskLayer) {
            m_childClippingMaskLayer->setPosition(m_scrollContainerLayer->position());
            m_childClippingMaskLayer->setSize(m_scrollContainerLayer->size());
            m_childClippingMaskLayer->setOffsetFromRenderer(toFloatSize(paddingBox.location()));
        }

        bool paddingBoxOffsetChanged = oldScrollingLayerOffset != m_scrollContainerLayer->offsetFromRenderer();

        IntSize scrollSize(m_owningLayer.scrollWidth(), m_owningLayer.scrollHeight());
        if (scrollSize != m_scrolledContentsLayer->size() || paddingBoxOffsetChanged)
            m_scrolledContentsLayer->setNeedsDisplay();

        LayoutSize scrollingContentsOffset = toLayoutSize(paddingBox.location() - toLayoutSize(scrollOffset));
        if (scrollingContentsOffset != m_scrolledContentsLayer->offsetFromRenderer() || scrollSize != m_scrolledContentsLayer->size())
            compositor().scrollingLayerDidChange(m_owningLayer);

        m_scrolledContentsLayer->setSize(scrollSize);
        // FIXME: Scrolling the content layer does not need to trigger a repaint. The offset will be compensated away during painting.
        // FIXME: The paint offset and the scroll offset should really be separate concepts.
        m_scrolledContentsLayer->setOffsetFromRenderer(scrollingContentsOffset);

        if (m_foregroundLayer) {
			m_foregroundLayer->setSize(m_scrolledContentsLayer->size());
            m_foregroundLayer->setOffsetFromRenderer(m_scrolledContentsLayer->offsetFromRenderer());
        }
    }

    // If this layer was created just for clipping or to apply perspective, it doesn't need its own backing store.
    LayoutRect ancestorCompositedBounds = compositedAncestor ? compositedAncestor->backing()->compositedBounds() : LayoutRect();
    setRequiresOwnBackingStore(compositor().requiresOwnBackingStore(m_owningLayer, compositedAncestor,
        LayoutRect(toLayoutPoint(compositedBoundsOffset.fromParentGraphicsLayer()), compositedBounds().size()), ancestorCompositedBounds));
#if ENABLE(FILTERS_LEVEL_2)
    updateBackdropFiltersGeometry();
#endif
    updateAfterWidgetResize();

    if (subpixelOffsetFromRendererChanged(oldSubpixelOffsetFromRenderer, m_subpixelOffsetFromRenderer, deviceScaleFactor) && canIssueSetNeedsDisplay())
        setContentsNeedDisplay();

    registerScrollingLayers();
    //compositor().updateScrollCoordinatedStatus(m_owningLayer);
}

void RenderLayerBacking::updateAfterDescendants()
{
    bool isSimpleContainer = false;
    if (!m_owningLayer.isRenderViewLayer()) {
        bool didUpdateContentsRect = false;
        // FIXME: this duplicates work we did in updateConfiguration().
        isSimpleContainer = isSimpleContainerCompositingLayer();
        updateDirectlyCompositedBoxDecorations(isSimpleContainer, didUpdateContentsRect);
	    if (!didUpdateContentsRect && m_graphicsLayer->usesContentsLayer())
			resetContentsRect();
    }

    updateDrawsContent(isSimpleContainer);

    if (!m_isMainFrameRenderViewLayer && !m_isFrameLayerWithTiledBacking && !m_requiresBackgroundLayer) {
        // For non-root layers, background is always painted by the primary graphics layer.
        ASSERT(!m_backgroundLayer);
        m_graphicsLayer->setContentsOpaque(!m_hasSubpixelRounding && m_owningLayer.backgroundIsKnownToBeOpaqueInRect(compositedBounds()));
    }

    m_graphicsLayer->setContentsVisible(m_owningLayer.hasVisibleContent() || hasVisibleNonCompositedDescendants());
}

// FIXME: Avoid repaints when clip path changes.
void RenderLayerBacking::updateMaskingLayerGeometry()
{
    m_maskLayer->setSize(m_graphicsLayer->size());
    m_maskLayer->setPosition(FloatPoint());
    m_maskLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());

    if (!m_maskLayer->drawsContent()) {
        if (renderer().hasClipPath()) {
            ASSERT(renderer().style().clipPath()->type() != ClipPathOperation::Reference);

            // FIXME: Use correct reference box for inlines: https://bugs.webkit.org/show_bug.cgi?id=129047, https://github.com/w3c/csswg-drafts/issues/6383
            LayoutRect boundingBox = m_owningLayer.boundingBox(&m_owningLayer);
            LayoutRect referenceBoxForClippedInline = LayoutRect(snapRectToDevicePixels(boundingBox, deviceScaleFactor()));
            LayoutSize offset = LayoutSize(snapSizeToDevicePixel(-m_subpixelOffsetFromRenderer, LayoutPoint(), deviceScaleFactor()));
            auto pairResult = m_owningLayer.computeClipPath(offset, referenceBoxForClippedInline);

            FloatSize pathOffset = m_maskLayer->offsetFromRenderer();
            if (!pathOffset.isZero())
            	pairResult.clipPath.translate(-pathOffset);

            m_maskLayer->setShapeLayerPath(pairResult.clipPath);
            m_maskLayer->setShapeLayerWindRule(pairResult.windRule);
        }
    }
}

void RenderLayerBacking::updateDirectlyCompositedBoxDecorations(bool isSimpleContainer, bool& didUpdateContentsRect)
{
    if (!m_owningLayer.hasVisibleContent())
        return;

    // The order of operations here matters, since the last valid type of contents needs
    // to also update the contentsRect.
    updateDirectlyCompositedBackgroundColor(isSimpleContainer, didUpdateContentsRect);
    updateDirectlyCompositedBackgroundImage(isSimpleContainer, didUpdateContentsRect);
}

void RenderLayerBacking::registerScrollingLayers()
{
#if PLATFORM(IOS)
    compositor().updateViewportConstraintStatus(m_owningLayer);
#else
    // Register fixed position layers and their containers with the scrolling coordinator.
    ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(&m_owningLayer);
    if (!scrollingCoordinator)
        return;

    compositor().updateViewportConstraintStatus(m_owningLayer);

    if (!scrollingCoordinator->supportsFixedPositionLayers())
        return;

    // Page scale is applied as a transform on the root render view layer. Because the scroll
    // layer is further up in the hierarchy, we need to avoid marking the root render view
    // layer as a container.
    bool isContainer = m_owningLayer.isTransformed() && !m_owningLayer.isRenderViewLayer();
    scrollingCoordinator->setLayerIsContainerForFixedPositionLayers(childForSuperlayers(), isContainer);
#endif
}

void RenderLayerBacking::updateInternalHierarchy()
{
    // m_foregroundLayer has to be inserted in the correct order with child layers,
    // so it's not inserted here.
    GraphicsLayer* lastClippingLayer = nullptr;
	if (m_ancestorClippingLayer) {
		m_ancestorClippingLayer->removeAllChildren();
        lastClippingLayer = m_ancestorClippingLayer.get();
    }

    constexpr size_t maxOrderedLayers = 6;
    Vector<GraphicsLayer*, maxOrderedLayers> orderedLayers;

    if (lastClippingLayer)
        orderedLayers.append(lastClippingLayer);

    if (m_contentsContainmentLayer) {
        m_contentsContainmentLayer->removeAllChildren();

        ASSERT(m_backgroundLayer);
        m_contentsContainmentLayer->addChild(m_backgroundLayer.get());

        // The loop below will add a second child to the m_contentsContainmentLayer.
        orderedLayers.append(m_contentsContainmentLayer.get());
    }

    orderedLayers.append(m_graphicsLayer.get());

    // The transform flattening layer is outside the clipping stack, so we need
    // to make sure we add the first layer in the clipping stack as its child.
    if (m_transformFlatteningLayer) {
        if (lastClippingLayer)
            m_transformFlatteningLayer->addChild(m_ancestorClippingLayer.get());
        else
            m_transformFlatteningLayer->addChild(orderedLayers[0]);
    }

    if (m_childContainmentLayer)
        orderedLayers.append(m_childContainmentLayer.get());

    if (m_scrollContainerLayer)
        orderedLayers.append(m_scrollContainerLayer.get());

    GraphicsLayer* previousLayer = nullptr;
    for (auto* layer : orderedLayers) {
        if (previousLayer)
            previousLayer->addChild(layer);

        previousLayer = layer;
    }

    // The clip for child layers does not include space for overflow controls, so they exist as
    // siblings of the clipping layer if we have one. Normal children of this layer are set as
    // children of the clipping layer.
    if (m_layerForHorizontalScrollbar) {
        m_layerForHorizontalScrollbar->removeFromParent();
        m_graphicsLayer->addChild(m_layerForHorizontalScrollbar.get());
    }
    if (m_layerForVerticalScrollbar) {
        m_layerForVerticalScrollbar->removeFromParent();
        m_graphicsLayer->addChild(m_layerForVerticalScrollbar.get());
    }
    if (m_layerForScrollCorner) {
        m_layerForScrollCorner->removeFromParent();
        m_graphicsLayer->addChild(m_layerForScrollCorner.get());
    }
}

void RenderLayerBacking::updateContentsRects()
{
    m_graphicsLayer->setContentsRect(snapRectToDevicePixels(contentsBox(), deviceScaleFactor()));

    if (renderer().isRenderReplaced()) {
        FloatRoundedRect contentsClippingRect = toRenderReplaced(renderer()).roundedContentBoxRect().pixelSnappedRoundedRectForPainting(deviceScaleFactor());
        contentsClippingRect.move(contentOffsetInCompositingLayer());
        m_graphicsLayer->setContentsClippingRect(contentsClippingRect);
    }
}

void RenderLayerBacking::resetContentsRect()
{
    updateContentsRects();
    m_graphicsLayer->setContentsTileSize(IntSize());
    m_graphicsLayer->setContentsTilePhase(IntSize());
}

void RenderLayerBacking::updateDrawsContent()
{
    updateDrawsContent(isSimpleContainerCompositingLayer());
}

void RenderLayerBacking::updateDrawsContent(bool isSimpleContainer)
{
    if (m_scrollContainerLayer) {
        // We don't have to consider overflow controls, because we know that the scrollbars are drawn elsewhere.
        // m_graphicsLayer only needs backing store if the non-scrolling parts (background, outlines, borders, shadows etc) need to paint.
        // m_scrollContainerLayer never has backing store.
        // m_scrolledContentsLayer only needs backing store if the scrolled contents need to paint.
        bool hasNonScrollingPaintedContent = m_owningLayer.hasVisibleContent() && m_owningLayer.hasVisibleBoxDecorationsOrBackground();
        m_graphicsLayer->setDrawsContent(hasNonScrollingPaintedContent);

        bool hasScrollingPaintedContent = m_owningLayer.hasVisibleContent() && (renderer().hasBackground() || paintsChildRenderers());
        m_scrolledContentsLayer->setDrawsContent(hasScrollingPaintedContent);
        return;
    }

    bool hasPaintedContent = containsPaintedContent(isSimpleContainer);

    // FIXME: we could refine this to only allocate backing for one of these layers if possible.
    m_graphicsLayer->setDrawsContent(hasPaintedContent);
    if (m_foregroundLayer)
        m_foregroundLayer->setDrawsContent(hasPaintedContent);

    if (m_backgroundLayer)
        m_backgroundLayer->setDrawsContent(hasPaintedContent);
}

// Return true if the layer changed.
bool RenderLayerBacking::updateAncestorClippingLayer(bool needsAncestorClip)
{
    bool layersChanged = false;

    if (needsAncestorClip) {
        if (!m_ancestorClippingLayer) {
            m_ancestorClippingLayer = createGraphicsLayer("Ancestor clipping Layer");
            m_ancestorClippingLayer->setMasksToBounds(true);
            layersChanged = true;
        }
    } else if (hasAncestorClippingLayer()) {
        willDestroyLayer(m_ancestorClippingLayer.get());
        m_ancestorClippingLayer->removeFromParent();
        m_ancestorClippingLayer = nullptr;
        layersChanged = true;
    }

    return layersChanged;
}

// Return true if the layer changed.
bool RenderLayerBacking::updateDescendantClippingLayer(bool needsDescendantClip)
{
    bool layersChanged = false;
    
    if (needsDescendantClip) {
        if (!m_childContainmentLayer && !m_usingTiledCacheLayer) {
            m_childContainmentLayer = createGraphicsLayer("Child clipping Layer");
            m_childContainmentLayer->setMasksToBounds(true);
            layersChanged = true;
        }
    } else if (hasClippingLayer()) {
        m_childContainmentLayer->removeFromParent();
        m_childContainmentLayer = nullptr;
        layersChanged = true;
    }
    
    return layersChanged;
}

void RenderLayerBacking::setBackgroundLayerPaintsFixedRootBackground(bool backgroundLayerPaintsFixedRootBackground)
{
    if (backgroundLayerPaintsFixedRootBackground == m_backgroundLayerPaintsFixedRootBackground)
        return;

    m_backgroundLayerPaintsFixedRootBackground = backgroundLayerPaintsFixedRootBackground;

    if (m_backgroundLayerPaintsFixedRootBackground) {
        ASSERT(m_isFrameLayerWithTiledBacking);
        renderer().view().frameView().removeSlowRepaintObject(renderer().view().rendererForRootBackground());
    }
}

void RenderLayerBacking::setRequiresBackgroundLayer(bool requiresBackgroundLayer)
{
    if (requiresBackgroundLayer == m_requiresBackgroundLayer)
        return;

    m_requiresBackgroundLayer = requiresBackgroundLayer;
    m_owningLayer.setNeedsCompositingConfigurationUpdate();
}

bool RenderLayerBacking::requiresHorizontalScrollbarLayer() const
{
#if !PLATFORM(CHROMIUM)
    if (!m_owningLayer.hasOverlayScrollbars())
        return false;
#endif
    return m_owningLayer.horizontalScrollbar();
}

bool RenderLayerBacking::requiresVerticalScrollbarLayer() const
{
#if !PLATFORM(CHROMIUM)
    if (!m_owningLayer.hasOverlayScrollbars())
        return false;
#endif
    return m_owningLayer.verticalScrollbar();
}

bool RenderLayerBacking::requiresScrollCornerLayer() const
{
#if !PLATFORM(CHROMIUM)
    if (!m_owningLayer.hasOverlayScrollbars())
        return false;
#endif
    return !m_owningLayer.scrollCornerAndResizerRect().isEmpty();
}

bool RenderLayerBacking::updateOverflowControlsLayers(bool needsHorizontalScrollbarLayer, bool needsVerticalScrollbarLayer, bool needsScrollCornerLayer)
{
    bool horizontalScrollbarLayerChanged = false;
    if (needsHorizontalScrollbarLayer) {
        if (!m_layerForHorizontalScrollbar) {
            m_layerForHorizontalScrollbar = createGraphicsLayer("horizontal scrollbar");
            horizontalScrollbarLayerChanged = true;
        }
    } else if (m_layerForHorizontalScrollbar) {
        willDestroyLayer(m_layerForHorizontalScrollbar.get());
        m_layerForHorizontalScrollbar = nullptr;
        horizontalScrollbarLayerChanged = true;
    }

    bool verticalScrollbarLayerChanged = false;
    if (needsVerticalScrollbarLayer) {
        if (!m_layerForVerticalScrollbar) {
            m_layerForVerticalScrollbar = createGraphicsLayer("vertical scrollbar");
            verticalScrollbarLayerChanged = true;
        }
    } else if (m_layerForVerticalScrollbar) {
        willDestroyLayer(m_layerForVerticalScrollbar.get());
        m_layerForVerticalScrollbar = nullptr;
        verticalScrollbarLayerChanged = true;
    }

    bool scrollCornerLayerChanged = false;
    if (needsScrollCornerLayer) {
        if (!m_layerForScrollCorner) {
            m_layerForScrollCorner = createGraphicsLayer("scroll corner");
            scrollCornerLayerChanged = true;
        }
    } else if (m_layerForScrollCorner) {
        willDestroyLayer(m_layerForScrollCorner.get());
        m_layerForScrollCorner = nullptr;
        scrollCornerLayerChanged = true;
    }

    if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(&m_owningLayer)) {
        if (horizontalScrollbarLayerChanged)
            scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_owningLayer, HorizontalScrollbar);
        if (verticalScrollbarLayerChanged)
            scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_owningLayer, VerticalScrollbar);
    }

    return horizontalScrollbarLayerChanged || verticalScrollbarLayerChanged || scrollCornerLayerChanged;
}

void RenderLayerBacking::positionOverflowControlsLayers()
{
    if (!m_owningLayer.hasScrollbars())
        return;

    const IntRect borderBox = snappedIntRect(renderBox()->borderBoxRect());

	FloatSize offsetFromRenderer = m_graphicsLayer->offsetFromRenderer();
    if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
        IntRect hBarRect = m_owningLayer.rectForHorizontalScrollbar(borderBox);
        layer->setPosition(hBarRect.location() - offsetFromRenderer);
        layer->setSize(hBarRect.size());

        if (layer->usesContentsLayer()) {
            IntRect barRect = IntRect(IntPoint(), hBarRect.size());
            layer->setContentsRect(barRect);
            layer->setContentsClippingRect(FloatRoundedRect(barRect));
        }
        layer->setDrawsContent(m_owningLayer.horizontalScrollbar() && !layer->usesContentsLayer());
    }

    if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
        IntRect vBarRect = m_owningLayer.rectForVerticalScrollbar(borderBox);
        layer->setPosition(vBarRect.location() - offsetFromRenderer);
        layer->setSize(vBarRect.size());
        if (layer->usesContentsLayer()) {
            IntRect barRect = IntRect(IntPoint(), vBarRect.size());
            layer->setContentsRect(barRect);
            layer->setContentsClippingRect(FloatRoundedRect(barRect));
        }
        layer->setDrawsContent(m_owningLayer.verticalScrollbar() && !layer->usesContentsLayer());
    }

    if (GraphicsLayer* layer = layerForScrollCorner()) {
        const LayoutRect& scrollCornerAndResizer = m_owningLayer.scrollCornerAndResizerRect();
        layer->setPosition(scrollCornerAndResizer.location() - offsetFromRenderer);
        layer->setSize(scrollCornerAndResizer.size());
        layer->setDrawsContent(!scrollCornerAndResizer.isEmpty());
    }
}

static bool ancestorLayerIsDOMParent(RenderLayer& layer, const RenderLayer* compositingAncestor)
{
    if (!compositingAncestor)
        return false;
    if (!layer.renderer().element() || !layer.renderer().element()->parentElement())
        return false;
    return compositingAncestor->renderer().element() == layer.renderer().element()->parentElement();
}

static bool ancestorLayerWillCombineTransform(const RenderLayer* compositingAncestor)
{
    if (!compositingAncestor)
        return false;
    return compositingAncestor->preserves3D() || compositingAncestor->hasPerspective();
}

bool RenderLayerBacking::updateTransformFlatteningLayer(const RenderLayer* compositingAncestor)
{
    bool needsFlatteningLayer = false;
    // If our parent layer has preserve-3d or perspective, and it's not our DOM parent, then we need a flattening layer to block that from being applied in 3d.
    if (useCSS3DTransformInteroperability() && ancestorLayerWillCombineTransform(compositingAncestor) && !ancestorLayerIsDOMParent(m_owningLayer, compositingAncestor))
        needsFlatteningLayer = true;

    bool layerChanged = false;
    if (needsFlatteningLayer) {
        if (!m_transformFlatteningLayer) {
            String layerName;
#ifndef NDEBUG
            layerName = makeString(m_owningLayer.name(), " (3d flattening)");
#endif
            m_transformFlatteningLayer = createGraphicsLayer(layerName);
            layerChanged = true;
        }
    } else if (m_transformFlatteningLayer) {
        willDestroyLayer(m_transformFlatteningLayer.get());
        m_transformFlatteningLayer->removeFromParent();
        m_transformFlatteningLayer = nullptr;
        layerChanged = true;
    }

    return layerChanged;
}

bool RenderLayerBacking::updateForegroundLayer(bool needsForegroundLayer)
{
    bool layerChanged = false;
    if (needsForegroundLayer) {
        if (!m_foregroundLayer) {
            String layerName;
#ifndef NDEBUG
            layerName = nameForLayer() + " (foreground)";
#endif
            m_foregroundLayer = createGraphicsLayer(layerName);
            m_foregroundLayer->setDrawsContent(true);
            layerChanged = true;
        }
    } else if (m_foregroundLayer) {
        willDestroyLayer(m_foregroundLayer.get());
        m_foregroundLayer->removeFromParent();
        m_foregroundLayer = nullptr;
        layerChanged = true;
    }

    return layerChanged;
}

bool RenderLayerBacking::updateBackgroundLayer(bool needsBackgroundLayer)
{
    bool layerChanged = false;
    if (needsBackgroundLayer) {
        if (!m_backgroundLayer) {
            String layerName;
#ifndef NDEBUG
            layerName = m_owningLayer.name() + " (background)";
#endif
            m_backgroundLayer = createGraphicsLayer(layerName);
            m_backgroundLayer->setDrawsContent(true);
            m_backgroundLayer->setAnchorPoint(FloatPoint3D());
            layerChanged = true;
        }

        if (!m_contentsContainmentLayer) {
            String layerName;
#ifndef NDEBUG
            layerName = m_owningLayer.name() + " (contents containment)";
#endif
            m_contentsContainmentLayer = createGraphicsLayer(layerName);
            m_contentsContainmentLayer->setAppliesPageScale(true);
            m_graphicsLayer->setAppliesPageScale(false);
            layerChanged = true;
        }
    } else {
        if (m_backgroundLayer) {
            willDestroyLayer(m_backgroundLayer.get());
            m_backgroundLayer->removeFromParent();
            m_backgroundLayer = nullptr;
            layerChanged = true;
        }
        if (m_contentsContainmentLayer) {
            willDestroyLayer(m_contentsContainmentLayer.get());
            m_contentsContainmentLayer->removeFromParent();
            m_contentsContainmentLayer = nullptr;
            layerChanged = true;
            m_graphicsLayer->setAppliesPageScale(true);
        }
    }

    if (layerChanged) {
        // This assumes that the background layer is only used for fixed backgrounds, which is currently a correct assumption.
        compositor().fixedRootBackgroundLayerChanged();
    }

    return layerChanged;
}

// Masking layer is used for masks or clip-path.
bool RenderLayerBacking::updateMaskingLayer(bool hasMask, bool hasClipPath)
{
    bool layerChanged = false;
    if (hasMask || hasClipPath) {
    	OptionSet<GraphicsLayerPaintingPhase> maskPhases;
        if (hasMask)
            maskPhases = GraphicsLayerPaintingPhase::Mask;

        if (hasClipPath) {
            // If we have a mask, we need to paint the combined clip-path and mask into the mask layer.
            if (hasMask || renderer().style()->clipPath()->type() == ClipPathOperation::Reference || !GraphicsLayer::supportsLayerType(GraphicsLayer::Type::Shape))
            	maskPhases.add(GraphicsLayerPaintingPhase::ClipPath);
        }

        bool paintsContent = !maskPhases.isEmpty();
        GraphicsLayer::Type requiredLayerType = paintsContent ? GraphicsLayer::Type::Normal : GraphicsLayer::Type::Shape;
        if (m_maskLayer && m_maskLayer->type() != requiredLayerType) {
            m_graphicsLayer->setMaskLayer(nullptr);
            willDestroyLayer(m_maskLayer.get());
            m_maskLayer = nullptr;
        }

        if (!m_maskLayer) {
            m_maskLayer = createGraphicsLayer("Mask", requiredLayerType);
            layerChanged = true;
            m_graphicsLayer->setMaskLayer(m_maskLayer.get());
            // We need a geometry update to size the new mask layer.
            m_owningLayer.setNeedsCompositingGeometryUpdate();
        }
        m_maskLayer->setDrawsContent(paintsContent);
        m_maskLayer->setPaintingPhase(maskPhases);
    } else if (m_maskLayer) {
        willDestroyLayer(m_maskLayer.get());
        m_maskLayer = nullptr;
        layerChanged = true;
    }

    return layerChanged;
}

void RenderLayerBacking::updateChildClippingStrategy(bool needsDescendantsClippingLayer)
{
    auto needsClipMaskLayer = [&] {
        return needsDescendantsClippingLayer && !GraphicsLayer::supportsRoundedClip() && renderer().isBox() && (renderer().style()->hasBorderRadius() || renderer().style()->clipPath());
    };

    auto* clippingLayer = this->clippingLayer();
    if (needsClipMaskLayer()) {
		m_childClippingMaskLayer = createGraphicsLayer("Child Clipping Mask Layer");
		m_childClippingMaskLayer->setDrawsContent(true);
		m_childClippingMaskLayer->setPaintingPhase(OptionSet<GraphicsLayerPaintingPhase>(GraphicsLayerPaintingPhase::ChildClippingMask));
		if (clippingLayer)
			clippingLayer->setMaskLayer(m_childClippingMaskLayer.get());
	} else if (m_childClippingMaskLayer) {
		if (clippingLayer)
			clippingLayer->setMaskLayer(nullptr);
		m_childClippingMaskLayer = nullptr;
	}
}

bool RenderLayerBacking::updateScrollingLayers(bool needsScrollingLayers)
{
    ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(&m_owningLayer);

    bool layerChanged = false;
    if (needsScrollingLayers) {
        if (!m_scrollContainerLayer) {
        	// Outer layer which corresponds with the scroll view. This never paints content.
			m_scrollContainerLayer = createGraphicsLayer("Scrolling container", GraphicsLayer::Type::Scrolling);
			m_scrollContainerLayer->setPaintingPhase(OptionSet<GraphicsLayerPaintingPhase>());
			m_scrollContainerLayer->setDrawsContent(false);
            m_scrollContainerLayer->setMasksToBounds(true);

            // Inner layer which renders the content that scrolls.
            m_scrolledContentsLayer = createGraphicsLayer("Scrolled Contents");
            m_scrolledContentsLayer->setDrawsContent(true);
            m_scrollContainerLayer->addChild(m_scrolledContentsLayer.get());

            layerChanged = true;
#if PLATFORM(IOS)
            if (m_owningLayer.parent())
                compositor().scrollingLayerAddedOrUpdated(&m_owningLayer);
#endif
            if (scrollingCoordinator)
                scrollingCoordinator->scrollableAreaScrollLayerDidChange(&m_owningLayer);
        }
    } else if (m_scrollContainerLayer) {
#if PLATFORM(IOS)
        if (!renderer().renderTreeBeingDestroyed())
            compositor().scrollingLayerRemoved(&m_owningLayer, m_scrollContainerLayer->platformLayer(), m_scrolledContentsLayer->platformLayer());
#endif
        willDestroyLayer(m_scrollContainerLayer.get());
        willDestroyLayer(m_scrolledContentsLayer.get());
        m_scrollContainerLayer = nullptr;
        m_scrolledContentsLayer = nullptr;
        layerChanged = true;
        if (scrollingCoordinator)
            scrollingCoordinator->scrollableAreaScrollLayerDidChange(&m_owningLayer);
    }

    if (layerChanged) {
        updateInternalHierarchy();
        compositor().scrollingLayerDidChange(m_owningLayer);
    }

    return layerChanged;
}

void RenderLayerBacking::attachToScrollingCoordinator(RenderLayerBacking* parent)
{
#if ENABLE(THREADED_SCROLLING)
    // If m_scrollLayerID non-zero, then this backing is already attached to the ScrollingCoordinator.
    if (m_scrollLayerID)
        return;

    Page* page = renderer().frame().page();
    if (!page)
        return;

    ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator();
    if (!scrollingCoordinator)
        return;

    // FIXME: When we support overflow areas, we will have to refine this for overflow areas that are also
    // positon:fixed.
    ScrollingNodeType nodeType;
    if (renderer().style()->position() == PositionType::Fixed)
        nodeType = FixedNode;
    else if (renderer().style()->position() == PositionType::Sticky)
        nodeType = StickyNode;
    else
        nodeType = ScrollingNode;

    m_scrollLayerID = scrollingCoordinator->attachToStateTree(scrollingCoordinator->uniqueScrollLayerID());
#endif
}

void RenderLayerBacking::detachFromScrollingCoordinator()
{
#if ENABLE(THREADED_SCROLLING)
    // If m_scrollLayerID is 0, then this backing is not attached to the ScrollingCoordinator.
    if (!m_scrollLayerID)
        return;

    Page* page = renderer().frame().page();
    if (!page)
        return;

    ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator();
    if (!scrollingCoordinator)
        return;

    scrollingCoordinator->detachFromStateTree(m_scrollLayerID);
    m_scrollLayerID = 0;
#endif
}

float RenderLayerBacking::compositingOpacity(float rendererOpacity) const
{
    float finalOpacity = rendererOpacity;

    for (auto* curr = m_owningLayer.stackingContext(); curr; curr = curr->stackingContext()) {
        // If we found a compositing layer, we want to compute opacity
        // relative to it. So we can break here.
        if (curr->isComposited())
            break;
        
        finalOpacity *= curr->renderer().opacity();
    }

    return finalOpacity;
}

// FIXME: Code is duplicated in RenderLayer. Also, we should probably not consider filters a box decoration here.
static bool hasVisibleBoxDecorations(const RenderStyle& style)
{
    return style.hasVisibleBorder() || style.hasBorderRadius() || style.hasOutline() || style.hasEffectiveAppearance() || style.boxShadow() || style.hasFilter();
}

static bool hasPaintedBoxDecorationsOrBackgroundImage(const RenderElement& renderer)
{
    const RenderStyle& style = *renderer.style();

    if (hasVisibleBoxDecorations(style))
        return true;

    if (!style.hasBackgroundImage())
        return false;

    return !canDirectlyCompositeBackgroundBackgroundImage(renderer);
}

static bool hasPerspectiveOrPreserves3D(const RenderStyle* style)
{
    return style->hasPerspective() || style->preserves3D();
}

Color RenderLayerBacking::rendererBackgroundColor() const
{
	RenderElement* backgroundRenderer = &renderer();
    if (backgroundRenderer->isDocumentElementRenderer())
        backgroundRenderer = &backgroundRenderer->rendererForRootBackground();

    return backgroundRenderer->style()->visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor);
}

void RenderLayerBacking::updateDirectlyCompositedBackgroundColor(bool isSimpleContainer, bool& didUpdateContentsRect)
{
	if (!isSimpleContainer || (renderer().isBox() && !toRenderBox(renderer()).paintsOwnBackground())) {
		m_graphicsLayer->setContentsToSolidColor(Color());
        return;
    }

    Color backgroundColor = rendererBackgroundColor();

    // An unset (invalid) color will remove the solid color.
    m_graphicsLayer->setContentsToSolidColor(backgroundColor);
    FloatRect contentsRect = backgroundBoxForSimpleContainerPainting();
    m_graphicsLayer->setContentsRect(contentsRect);
    m_graphicsLayer->setContentsClippingRect(FloatRoundedRect(contentsRect));
    didUpdateContentsRect = true;
}

static bool canDirectlyCompositeBackgroundBackgroundImage(const RenderElement& renderer)
{
    const RenderStyle& style = *renderer.style();

    if (!GraphicsLayer::supportsContentsTiling())
        return false;

    const FillLayer& fillLayer = style.backgroundLayers();
    if (fillLayer.next())
        return false;

    if (!fillLayer.imagesAreLoaded(&renderer))
        return false;

    if (fillLayer.attachment() != ScrollBackgroundAttachment)
        return false;

    Color color = style.visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor);

    // FIXME: Allow color+image compositing when it makes sense.
    // For now bailing out.
    if (color.isValid() && color.alpha())
        return false;

    // FIXME: support gradients with isGeneratedImage.
    auto* styleImage = fillLayer.image();
    if (!styleImage->hasCachedImage())
        return false;

    Image* image = styleImage->cachedImage()->image();
    if (!image->isBitmapImage())
        return false;

    return true;
}

void RenderLayerBacking::updateDirectlyCompositedBackgroundImage(bool isSimpleContainer, bool& didUpdateContentsRect)
{
    if (!GraphicsLayer::supportsContentsTiling())
        return;

    const RenderStyle* style = renderer().style();

    if (!isSimpleContainer || !style->hasBackgroundImage()) {
        m_graphicsLayer->setContentsToImage(nullptr);
        return;
    }

    FloatRect destRect = backgroundBoxForSimpleContainerPainting();
    FloatSize phase;
    FloatSize tileSize;

    RefPtr<Image> image = style->backgroundLayers().image()->cachedImage()->image();
    // FIXME: absolute paint location is required here.
	toRenderBox(renderer()).getGeometryForBackgroundImage(&renderer(), LayoutPoint(), destRect, phase, tileSize);
    m_graphicsLayer->setContentsTileSize(tileSize);
    m_graphicsLayer->setContentsTilePhase(phase);
    m_graphicsLayer->setContentsRect(destRect);
    m_graphicsLayer->setContentsClippingRect(FloatRoundedRect(destRect));
    m_graphicsLayer->setContentsToImage(image.get());
    didUpdateContentsRect = true;
}

void RenderLayerBacking::updateRootLayerConfiguration()
{
    if (!m_usingTiledCacheLayer)
        return;

    Color backgroundColor;
    bool viewIsTransparent = compositor().viewHasTransparentBackground(&backgroundColor);

    if (m_backgroundLayerPaintsFixedRootBackground && m_backgroundLayer) {
        if (m_isMainFrameRenderViewLayer) {
        	m_backgroundLayer->setBackgroundColor(backgroundColor);
        	m_backgroundLayer->setContentsOpaque(!viewIsTransparent);
        }

        m_graphicsLayer->setBackgroundColor(Color());
        m_graphicsLayer->setContentsOpaque(false);
    } else if (m_isMainFrameRenderViewLayer) {
        m_graphicsLayer->setBackgroundColor(backgroundColor);
        m_graphicsLayer->setContentsOpaque(!viewIsTransparent);
    }
}

void RenderLayerBacking::updatePaintingPhases()
{
    // Phases for m_childClippingMaskLayer and m_maskLayer are set elsewhere.
    OptionSet<GraphicsLayerPaintingPhase> primaryLayerPhases(GraphicsLayerPaintingPhase::Background, GraphicsLayerPaintingPhase::Foreground);

    if (m_foregroundLayer) {
        OptionSet<GraphicsLayerPaintingPhase> foregroundLayerPhases(GraphicsLayerPaintingPhase::Foreground);
        m_foregroundLayer->setPaintingPhase(foregroundLayerPhases);
        primaryLayerPhases.remove(GraphicsLayerPaintingPhase::Foreground);
    }

    if (m_backgroundLayer) {
        m_backgroundLayer->setPaintingPhase(GraphicsLayerPaintingPhase::Background);
        primaryLayerPhases.remove(GraphicsLayerPaintingPhase::Background);
    }

    if (m_scrollContainerLayer) {
        OptionSet<GraphicsLayerPaintingPhase> scrolledContentLayerPhases(GraphicsLayerPaintingPhase::OverflowContents, GraphicsLayerPaintingPhase::CompositedScroll);
        if (!m_foregroundLayer)
            scrolledContentLayerPhases.add(GraphicsLayerPaintingPhase::Foreground);
        m_scrollContainerLayer->setPaintingPhase(scrolledContentLayerPhases);

        primaryLayerPhases.remove(GraphicsLayerPaintingPhase::Foreground);
        primaryLayerPhases.add(GraphicsLayerPaintingPhase::CompositedScroll);
    }

    m_graphicsLayer->setPaintingPhase(primaryLayerPhases);
}

static bool supportsDirectlyCompositedBoxDecorations(const RenderLayerModelObject& renderer)
{
    if (!GraphicsLayer::supportsBackgroundColorContent())
        return false;

    if (renderer.hasClip())
        return false;

    if (hasPaintedBoxDecorationsOrBackgroundImage(renderer))
        return false;

    // FIXME: We can't create a directly composited background if this
    // layer will have children that intersect with the background layer.
    // A better solution might be to introduce a flattening layer if
    // we do direct box decoration composition.
    // https://bugs.webkit.org/show_bug.cgi?id=119461
    if (hasPerspectiveOrPreserves3D(renderer.style()))
        return false;

    // FIXME: we should be able to allow backgroundComposite; However since this is not a common use case it has been deferred for now.
    if (renderer.style()->backgroundComposite() != CompositeSourceOver)
        return false;

    return true;
}

bool RenderLayerBacking::paintsBoxDecorations() const
{
    if (!m_owningLayer.hasVisibleBoxDecorations())
        return false;

    return !supportsDirectlyCompositedBoxDecorations(renderer());
}

#if 0
bool RenderLayerBacking::paintsContent(RenderLayer::PaintedContentRequest& request) const
{
    m_owningLayer.updateDescendantDependentFlags();

    bool paintsContent = false;

    if (m_owningLayer.hasVisibleContent() && m_owningLayer.hasNonEmptyChildRenderers(request))
        paintsContent = true;

    if (request.isSatisfied())
        return paintsContent;

    if (isPaintDestinationForDescendantLayers(request))
        paintsContent = true;

    if (request.isSatisfied())
        return paintsContent;

    if (request.hasPaintedContent == RequestState::Unknown)
        request.hasPaintedContent = RequestState::False;

    if (request.hasSubpixelAntialiasedText == RequestState::Unknown)
        request.hasSubpixelAntialiasedText = RequestState::False;

    return paintsContent;
}
#endif

bool RenderLayerBacking::paintsChildRenderers() const
{
    m_owningLayer.updateDescendantDependentFlags();

    if (m_owningLayer.hasVisibleContent() && m_owningLayer.hasNonEmptyChildRenderers())
        return true;
        
    if (isPaintDestinationForDescendantLayers())
        return true;

    return false;
}

static bool isCompositedPlugin(RenderElement& renderer)
{
    return renderer.isRenderEmbeddedObject() && toRenderEmbeddedObject(renderer).allowsAcceleratedCompositing();
}

// A "simple container layer" is a RenderLayer which has no visible content to render.
// It may have no children, or all its children may be themselves composited.
// This is a useful optimization, because it allows us to avoid allocating backing store.
bool RenderLayerBacking::isSimpleContainerCompositingLayer() const
{
    if (m_owningLayer.isRenderViewLayer())
        return false;

	auto& renderObject = renderer();
    if (renderObject.isRenderReplaced() && !isCompositedPlugin(renderObject))
		return false;

    if (renderer().isTextControl())
        return false;

    if (paintsBoxDecorations() || paintsChildRenderers())
        return false;

    if (renderer().style()->backgroundClip() == TextFillBox)
        return false;

    if (renderer().isDocumentElementRenderer() && m_owningLayer.isolatesCompositedBlending())
        return false;

    return true;
}

enum class LayerTraversal { Continue, Stop };

static LayerTraversal traverseVisibleNonCompositedDescendantLayers(RenderLayer& parent, std::function<LayerTraversal (const RenderLayer&)> layerFunc)
{
    // FIXME: We shouldn't be called with a stale z-order lists. See bug 85512.
    parent.updateLayerListsIfNeeded();

#if !ASSERT_DISABLED
    LayerListMutationDetector mutationChecker(parent);
#endif

    for (auto* childLayer : parent.normalFlowLayers()) {
        if (compositedWithOwnBackingStore(*childLayer))
            continue;

        if (layerFunc(*childLayer) == LayerTraversal::Stop)
            return LayerTraversal::Stop;

        if (traverseVisibleNonCompositedDescendantLayers(*childLayer, layerFunc) == LayerTraversal::Stop)
            return LayerTraversal::Stop;
    }

    if (parent.isStackingContext() && !parent.hasVisibleDescendant())
        return LayerTraversal::Continue;

	// Use the m_hasCompositingDescendant bit to optimize?
    for (auto* childLayer : parent.negativeZOrderLayers()) {
        if (compositedWithOwnBackingStore(*childLayer))
            continue;

        if (layerFunc(*childLayer) == LayerTraversal::Stop)
            return LayerTraversal::Stop;

        if (traverseVisibleNonCompositedDescendantLayers(*childLayer, layerFunc) == LayerTraversal::Stop)
            return LayerTraversal::Stop;
	}

    for (auto* childLayer : parent.positiveZOrderLayers()) {
        if (compositedWithOwnBackingStore(*childLayer))
            continue;

        if (layerFunc(*childLayer) == LayerTraversal::Stop)
            return LayerTraversal::Stop;

        if (traverseVisibleNonCompositedDescendantLayers(*childLayer, layerFunc) == LayerTraversal::Stop)
            return LayerTraversal::Stop;
	}

    return LayerTraversal::Continue;
}

#if 0
static Optional<bool> intersectsWithAncestor(const RenderLayer& child, const RenderLayer& ancestor, const LayoutRect& ancestorCompositedBounds)
{
    // If any layers between child and ancestor are transformed, then adjusting the offset is
    // insufficient to convert coordinates into ancestor's coordinate space.
    if (!child.canUseOffsetFromAncestor(ancestor))
		return Nullopt;

    auto overlap = child.boundingBox(&ancestor, child.offsetFromAncestor(&ancestor), RenderLayer::UseFragmentBoxesExcludingCompositing);
    return overlap.intersects(ancestorCompositedBounds);
}
#endif

// Conservative test for having no rendered children.
bool RenderLayerBacking::isPaintDestinationForDescendantLayers() const
{
    bool hasPaintingDescendant = false;
    traverseVisibleNonCompositedDescendantLayers(m_owningLayer, [&hasPaintingDescendant](const RenderLayer& layer) {
        hasPaintingDescendant = layer.isVisuallyNonEmpty();
        return hasPaintingDescendant ? LayerTraversal::Stop : LayerTraversal::Continue;
    });

    return hasPaintingDescendant;
}

bool RenderLayerBacking::hasVisibleNonCompositedDescendants() const
{
    bool hasVisibleDescendant = false;
    traverseVisibleNonCompositedDescendantLayers(m_owningLayer, [&hasVisibleDescendant](const RenderLayer& layer) {
        hasVisibleDescendant = layer.hasVisibleContent();
        return hasVisibleDescendant ? LayerTraversal::Stop : LayerTraversal::Continue;
    });

    return hasVisibleDescendant;
}

bool RenderLayerBacking::containsPaintedContent(bool isSimpleContainer) const
{
    if (isSimpleContainer || paintsIntoWindow() || paintsIntoCompositedAncestor() || m_artificiallyInflatedBounds || m_owningLayer.isReflection())
        return false;

    if (isDirectlyCompositedImage())
        return false;

    // FIXME: we could optimize cases where the image, video or canvas is known to fill the border box entirely,
    // and set background color on the layer in that case, instead of allocating backing store and painting.
#if ENABLE(VIDEO)
    if (renderer().isVideo() && toRenderVideo(renderer()).shouldDisplayVideo()) {
#if USE(VIDEO_AS_TEXTURE)
    	return true;
#else
    	return m_owningLayer.hasVisibleBoxDecorationsOrBackground() || (!(toRenderVideo(renderer()).supportsAcceleratedRendering()) && m_requiresOwnBackingStore);
#endif
    }
#endif
#if PLATFORM(MAC) && !PLATFORM(IOS) && USE(CA)
#elif ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS) || PLATFORM(IOS_SIMULATOR)
    if (isAcceleratedCanvas(renderer()))
        return m_owningLayer.hasVisibleBoxDecorationsOrBackground();
#endif

    return true;
}

// An image can be directly compositing if it's the sole content of the layer, and has no box decorations
// that require painting. Direct compositing saves backing store.
bool RenderLayerBacking::isDirectlyCompositedImage() const
{
	auto& renderObject = renderer();
    
    if (!renderObject.isRenderImage() || renderObject.isMedia() || m_owningLayer.hasVisibleBoxDecorationsOrBackground() || m_owningLayer.paintsWithFilters() || renderObject.hasClip())
        return false;

    RenderImage& imageRenderer = toRenderImage(renderObject);
    if (CachedImage* cachedImage = imageRenderer.cachedImage()) {
        if (!cachedImage->hasImage())
            return false;

        Image* image = cachedImage->imageForRenderer(&imageRenderer);
        if (!image->isBitmapImage())
            return false;

        if (image->orientationForCurrentFrame() != ImageOrientation::OriginTopLeft)
            return false;

#if (PLATFORM(GTK) || PLATFORM(WPE) || PLATFORM(ESPIAL))
        // GTK and WPE ports don't support rounded rect clipping at TextureMapper level, so they cannot
        // directly composite images that have border-radius propery. Draw them as non directly composited
        // content instead. See https://bugs.webkit.org/show_bug.cgi?id=174157.
        if (imageRenderer.style()->hasBorderRadius())
            return false;
#endif

        return m_graphicsLayer->shouldDirectlyCompositeImage(image);
    }
    return false;
}

#if 0
bool RenderLayerBacking::isUnscaledBitmapOnly() const
{
    if (!is<RenderImage>(renderer()) && !is<RenderHTMLCanvas>(renderer()))
        return false;
    if (m_owningLayer.hasVisibleBoxDecorationsOrBackground())
        return false;
    if (pageScaleFactor() < 1.0f)
        return false;
    auto contents = contentsBox();
    if (contents.location() != LayoutPoint(0, 0))
        return false;
    if (is<RenderImage>(renderer())) {
        auto& imageRenderer = downcast<RenderImage>(renderer());
        if (auto* cachedImage = imageRenderer.cachedImage()) {
            if (!cachedImage->hasImage())
                return false;
            auto* image = cachedImage->imageForRenderer(&imageRenderer);
            if (!is<BitmapImage>(image))
                return false;
            if (downcast<BitmapImage>(*image).orientationForCurrentFrame() != ImageOrientation::None)
                return false;
            return contents.size() == image->size();
        }
        return false;
    }

    if (renderer().style().imageRendering() == ImageRendering::CrispEdges || renderer().style().imageRendering() == ImageRendering::Pixelated)
        return false;

    auto& canvasRenderer = downcast<RenderHTMLCanvas>(renderer());
    if (snappedIntRect(contents).size() == canvasRenderer.canvasElement().size())
        return true;
    return false;
}
#endif

void RenderLayerBacking::contentChanged(ContentChangeType changeType)
{
    if ((changeType == ImageChanged) && isDirectlyCompositedImage()) {
        updateImageContents();
        return;
    }

    if (changeType == VideoChanged) {
        compositor().scheduleCompositingLayerUpdate();
        return;
    }

    if ((changeType == BackgroundImageChanged) && canDirectlyCompositeBackgroundBackgroundImage(renderer()))
    	m_owningLayer.setNeedsCompositingConfigurationUpdate();

    if ((changeType == MaskImageChanged) && m_maskLayer)
        m_owningLayer.setNeedsCompositingConfigurationUpdate();

#if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
    if ((changeType == CanvasChanged || changeType == CanvasPixelsChanged) && isAcceleratedCanvas(renderer())) {
        m_graphicsLayer->setContentsNeedsDisplay();
        return;
    }
#endif
}

void RenderLayerBacking::updateImageContents()
{
    ASSERT(renderer().isRenderImage());
    RenderImage& imageRenderer = toRenderImage(renderer());

    CachedImage* cachedImage = imageRenderer.cachedImage();
    if (!cachedImage)
        return;

    Image* image = cachedImage->imageForRenderer(&imageRenderer);
    if (!image)
        return;

    // We have to wait until the image is fully loaded before setting it on the layer.
    if (!cachedImage->isLoaded())
        return;

    updateContentsRects();
    m_graphicsLayer->setContentsToImage(image);

    bool isSimpleContainer = false;
    updateDrawsContent(isSimpleContainer);
    
    // Image animation is "lazy", in that it automatically stops unless someone is drawing
    // the image. So we have to kick the animation each time; this has the downside that the
    // image will keep animating, even if its layer is not visible.
    image->startAnimation();
}

// Return the offset from the top-left of this compositing layer at which the renderer's contents are painted.
LayoutSize RenderLayerBacking::contentOffsetInCompositingLayer() const
{
    return LayoutSize(-m_compositedBounds.x() + m_compositedBoundsOffsetFromGraphicsLayer.width(), -m_compositedBounds.y() + m_compositedBoundsOffsetFromGraphicsLayer.height());
}

LayoutRect RenderLayerBacking::contentsBox() const
{
    if (!renderer().isBox())
        return LayoutRect();

    RenderBox& renderBox = toRenderBox(renderer());
    LayoutRect contentsRect;
#if ENABLE(VIDEO)
    if (renderBox.isVideo()) {
        RenderVideo& videoRenderer = toRenderVideo(renderBox);
        contentsRect = videoRenderer.videoBox();
    } else
#endif
	if (renderBox.isRenderReplaced() && !renderBox.isWidget()) {
		RenderReplaced& renderReplaced = toRenderReplaced(renderBox);
		contentsRect = renderReplaced.replacedContentRect();
	} else
		contentsRect = renderBox.contentBoxRect();

    contentsRect.move(contentOffsetInCompositingLayer());
    return contentsRect;
}

static LayoutRect backgroundRectForBox(const RenderBox& box)
{
    switch (box.style()->backgroundClip()) {
    case BorderFillBox:
        return box.borderBoxRect();
    case PaddingFillBox:
        return box.paddingBoxRect();
    case ContentFillBox:
        return box.contentBoxRect();
    default:
        break;
    }

    ASSERT_NOT_REACHED();
    return LayoutRect();
}

FloatRect RenderLayerBacking::backgroundBoxForSimpleContainerPainting() const
{
    if (!renderer().isBox())
        return FloatRect();

    LayoutRect backgroundBox = backgroundRectForBox(toRenderBox(renderer()));
    backgroundBox.move(contentOffsetInCompositingLayer());
    return snapRectToDevicePixels(backgroundBox, deviceScaleFactor());
}

GraphicsLayer* RenderLayerBacking::parentForSublayers() const
{
    if (m_scrolledContentsLayer)
        return m_scrolledContentsLayer.get();

    return m_childContainmentLayer ? m_childContainmentLayer.get() : m_graphicsLayer.get();
}

GraphicsLayer* RenderLayerBacking::childForSuperlayers() const
{
    if (m_transformFlatteningLayer)
        return m_transformFlatteningLayer.get();

    if (m_ancestorClippingLayer)
        return m_ancestorClippingLayer.get();

    if (m_contentsContainmentLayer)
        return m_contentsContainmentLayer.get();

    return m_graphicsLayer.get();
}

bool RenderLayerBacking::paintsIntoWindow() const
{
    if (m_usingTiledCacheLayer)
        return false;

    if (m_owningLayer.isRenderViewLayer()) {
#if PLATFORM(BLACKBERRY) || PLATFORM(IOS) || PLATFORM(ESPIAL)
        if (compositor().inForcedCompositingMode())
            return false;
#endif

        return compositor().rootLayerAttachment() != RenderLayerCompositor::RootLayerAttachedViaEnclosingFrame;
    }
    
    return false;
}

void RenderLayerBacking::setRequiresOwnBackingStore(bool requiresOwnBacking)
{
    if (requiresOwnBacking == m_requiresOwnBackingStore)
        return;

    m_requiresOwnBackingStore = requiresOwnBacking;

    // This affects the answer to paintsIntoCompositedAncestor(), which in turn affects
    // cached clip rects, so when it changes we have to clear clip rects on descendants.
    m_owningLayer.clearClipRectsIncludingDescendants(PaintingClipRects);
    m_owningLayer.computeRepaintRectsIncludingDescendants();
    
    compositor().repaintInCompositedAncestor(m_owningLayer, compositedBounds());
}

void RenderLayerBacking::setContentsNeedDisplay(GraphicsLayer::ShouldClipToLayer shouldClip)
{
    ASSERT(!paintsIntoCompositedAncestor());

    // Use the repaint as a trigger to re-evaluate direct compositing (which is never used on the root layer).
    if (!m_owningLayer.isRenderViewLayer())
        m_owningLayer.setNeedsCompositingConfigurationUpdate();

    FrameView& frameView = owningLayer().renderer().view().frameView();
    if (m_isMainFrameRenderViewLayer && frameView.isTrackingRepaints())
        frameView.addTrackedRepaintRect(owningLayer().absoluteBoundingBoxForPainting());
    
    if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
        // By default, setNeedsDisplay will clip to the size of the GraphicsLayer, which does not include margin tiles.
        // So if the TiledBacking has a margin that needs to be invalidated, we need to send in a rect to setNeedsDisplayInRect
        // that is large enough to include the margin. TiledBacking::bounds() includes the margin.
#if 0
        TiledBacking* tiledBacking = this->tiledBacking();
        FloatRect rectToRepaint = tiledBacking ? tiledBacking->bounds() : FloatRect(FloatPoint(0, 0), m_graphicsLayer->size());
        m_graphicsLayer->setNeedsDisplayInRect(rectToRepaint, shouldClip);
#else
        m_graphicsLayer->setNeedsDisplayInRect(FloatRect(FloatPoint(0, 0), m_graphicsLayer->size()), shouldClip);
#endif
    }
    
    if (m_foregroundLayer && m_foregroundLayer->drawsContent())
        m_foregroundLayer->setNeedsDisplay();

    if (m_backgroundLayer && m_backgroundLayer->drawsContent())
        m_backgroundLayer->setNeedsDisplay();

    if (m_maskLayer && m_maskLayer->drawsContent())
        m_maskLayer->setNeedsDisplay();

    if (m_childClippingMaskLayer && m_childClippingMaskLayer->drawsContent())
        m_childClippingMaskLayer->setNeedsDisplay();

    if (m_scrolledContentsLayer && m_scrolledContentsLayer->drawsContent())
        m_scrolledContentsLayer->setNeedsDisplay();
}

// r is in the coordinate space of the layer's render object
void RenderLayerBacking::setContentsNeedDisplayInRect(const LayoutRect& r, GraphicsLayer::ShouldClipToLayer shouldClip)
{
    ASSERT(!paintsIntoCompositedAncestor());

    // Use the repaint as a trigger to re-evaluate direct compositing (which is never used on the root layer).
    if (!m_owningLayer.isRenderViewLayer())
        m_owningLayer.setNeedsCompositingConfigurationUpdate();

    FloatRect pixelSnappedRectForPainting = snapRectToDevicePixels(r, deviceScaleFactor());
    FrameView& frameView = renderer().view().frameView();
	if (m_isMainFrameRenderViewLayer && frameView.isTrackingRepaints())
		frameView.addTrackedRepaintRect(pixelSnappedRectForPainting);

    if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
        FloatRect layerDirtyRect = pixelSnappedRectForPainting;
        layerDirtyRect.move(-m_graphicsLayer->offsetFromRenderer() - m_subpixelOffsetFromRenderer);
        m_graphicsLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
    }

    if (m_foregroundLayer && m_foregroundLayer->drawsContent()) {
        FloatRect layerDirtyRect = pixelSnappedRectForPainting;
        layerDirtyRect.move(-m_foregroundLayer->offsetFromRenderer() - m_subpixelOffsetFromRenderer);
        m_foregroundLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
    }

    // FIXME: need to split out repaints for the background.
    if (m_backgroundLayer && m_backgroundLayer->drawsContent()) {
        FloatRect layerDirtyRect = pixelSnappedRectForPainting;
        layerDirtyRect.move(-m_backgroundLayer->offsetFromRenderer() - m_subpixelOffsetFromRenderer);
        m_backgroundLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
    }

    if (m_maskLayer && m_maskLayer->drawsContent()) {
        FloatRect layerDirtyRect = pixelSnappedRectForPainting;
        layerDirtyRect.move(-m_maskLayer->offsetFromRenderer() - m_subpixelOffsetFromRenderer);
        m_maskLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
    }

    if (m_childClippingMaskLayer && m_childClippingMaskLayer->drawsContent()) {
        FloatRect layerDirtyRect = r;
        layerDirtyRect.move(-m_childClippingMaskLayer->offsetFromRenderer());
        m_childClippingMaskLayer->setNeedsDisplayInRect(layerDirtyRect);
    }

    if (m_scrolledContentsLayer && m_scrolledContentsLayer->drawsContent()) {
        FloatRect layerDirtyRect = pixelSnappedRectForPainting;
        layerDirtyRect.move(-m_scrolledContentsLayer->offsetFromRenderer() + toLayoutSize(m_owningLayer.scrollOffset()) - m_subpixelOffsetFromRenderer);
        m_scrolledContentsLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
    }
}

void RenderLayerBacking::paintIntoLayer(const GraphicsLayer* graphicsLayer, GraphicsContext* context,
	const IntRect& paintDirtyRect, // In the coords of rootLayer.
	PaintBehavior paintBehavior)
{
    if ((paintsIntoWindow() || paintsIntoCompositedAncestor()) && graphicsLayer->paintingPhase() != OptionSet<GraphicsLayerPaintingPhase>(GraphicsLayerPaintingPhase::ChildClippingMask)) {
#if !PLATFORM(IOS)
        // FIXME: Looks like the CALayer tree is out of sync with the GraphicsLayer heirarchy
        // when pages are restored from the PageCache.
        // <rdar://problem/8712587> ASSERT: When Going Back to Page with Plugins in PageCache
        ASSERT_NOT_REACHED();
#endif
        return;
    }

    FontCachePurgePreventer fontCachePurgePreventer;

    auto paintFlags = paintFlagsForLayer(*graphicsLayer);

#ifndef NDEBUG
    RenderElement::SetLayoutNeededForbiddenScope forbidSetNeedsLayout(&renderer());
#endif

    InspectorInstrumentationCookie cookie;
    if (!context->paintingDisabled())
        cookie = InspectorInstrumentation::willPaint(&renderer().view().frame(), context, paintDirtyRect);

    FrameView::PaintingState paintingState;
    if (m_owningLayer.isRenderViewLayer())
        renderer().view().frameView().willPaintContents(context, paintDirtyRect, paintingState, cookie);

    // FIXME: GraphicsLayers need a way to split for RenderRegions.
    RenderLayer::LayerPaintingInfo paintingInfo(&m_owningLayer, paintDirtyRect, paintBehavior, -m_subpixelOffsetFromRenderer);
	m_owningLayer.paintLayerContents(context, paintingInfo, paintFlags);

    if (m_owningLayer.containsDirtyOverlayScrollbars())
        m_owningLayer.paintLayerContents(context, paintingInfo, paintFlags | RenderLayer::PaintLayerPaintingOverlayScrollbars);

    if (m_owningLayer.isRenderViewLayer())
        renderer().view().frameView().didPaintContents(context, paintDirtyRect, paintingState, cookie);

    ASSERT(!m_owningLayer.m_usedTransparency);
}

OptionSet<RenderLayer::PaintLayerFlag> RenderLayerBacking::paintFlagsForLayer(const GraphicsLayer& graphicsLayer) const
{
    OptionSet<RenderLayer::PaintLayerFlag> paintFlags;

    auto paintingPhase = graphicsLayer.paintingPhase();
    if (paintingPhase.contains(GraphicsLayerPaintingPhase::Background))
        paintFlags.add(RenderLayer::PaintLayerPaintingCompositingBackgroundPhase);
    if (paintingPhase.contains(GraphicsLayerPaintingPhase::Foreground))
        paintFlags.add(RenderLayer::PaintLayerPaintingCompositingForegroundPhase);
    if (paintingPhase.contains(GraphicsLayerPaintingPhase::Mask))
        paintFlags.add(RenderLayer::PaintLayerPaintingCompositingMaskPhase);
    if (paintingPhase.contains(GraphicsLayerPaintingPhase::ClipPath))
        paintFlags.add(RenderLayer::PaintLayerPaintingCompositingClipPathPhase);
    if (paintingPhase.contains(GraphicsLayerPaintingPhase::ChildClippingMask))
        paintFlags.add(RenderLayer::PaintLayerPaintingChildClippingMaskPhase);
    if (paintingPhase.contains(GraphicsLayerPaintingPhase::OverflowContents))
        paintFlags.add(RenderLayer::PaintLayerPaintingOverflowContents);
    if (paintingPhase.contains(GraphicsLayerPaintingPhase::CompositedScroll))
        paintFlags.add(RenderLayer::PaintLayerPaintingCompositingScrollingPhase);

    if (&graphicsLayer == m_backgroundLayer.get() && m_backgroundLayerPaintsFixedRootBackground)
        paintFlags.add({ RenderLayer::PaintLayerPaintingRootBackgroundOnly, RenderLayer::PaintLayerPaintingCompositingForegroundPhase }); // Need PaintLayerPaintingCompositingForegroundPhase to walk child layers.
    else if (compositor().fixedRootBackgroundLayer())
        paintFlags.add(RenderLayer::PaintLayerPaintingSkipRootBackground);

    return paintFlags;
}

// Up-call from compositing layer drawing callback.
void RenderLayerBacking::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, const FloatRect& clip)
{
#ifndef NDEBUG
    if (Page* page = renderer().frame().page())
        page->setIsPainting(true);
#endif

    auto paintScrollbar = [&] (Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip) -> void
    {
        if (!scrollbar)
            return;

        context.save();
        const IntRect& scrollbarRect = scrollbar->frameRect();
        context.translate(-scrollbarRect.x(), -scrollbarRect.y());
        IntRect transformedClip = clip;
        transformedClip.moveBy(scrollbarRect.location());
        scrollbar->paint(&context, transformedClip);
        context.restore();
    };

    // The dirtyRect is in the coords of the painting root.
    FloatRect adjustedClipRect = clip;
    adjustedClipRect.move(m_subpixelOffsetFromRenderer);
    IntRect dirtyRect = enclosingIntRect(adjustedClipRect);

	if (graphicsLayer == m_graphicsLayer.get()
		|| graphicsLayer == m_foregroundLayer.get()
		|| graphicsLayer == m_backgroundLayer.get()
		|| graphicsLayer == m_maskLayer.get()
        || graphicsLayer == m_childClippingMaskLayer.get()
		|| graphicsLayer == m_scrolledContentsLayer.get()) {
        InspectorInstrumentationCookie cookie = InspectorInstrumentation::willPaint(&renderer().frame(), &context, dirtyRect);

        if (!graphicsLayer->paintingPhase().contains(GraphicsLayerPaintingPhase::OverflowContents))
			dirtyRect.intersect(enclosingIntRect(compositedBounds()));

        // We have to use the same root as for hit testing, because both methods can compute and cache clipRects.
        paintIntoLayer(graphicsLayer, &context, dirtyRect, PaintBehaviorNormal);

        if (m_usingTiledCacheLayer)
            renderer().view().frameView().setLastPaintTime(monotonicallyIncreasingTime());

        InspectorInstrumentation::didPaint(cookie);
    } else if (graphicsLayer == layerForHorizontalScrollbar()) {
        if (m_owningLayer.hasVisibleContent()) {
        	paintScrollbar(m_owningLayer.horizontalScrollbar(), context, dirtyRect);
        }
    } else if (graphicsLayer == layerForVerticalScrollbar()) {
        if (m_owningLayer.hasVisibleContent()) {
        	paintScrollbar(m_owningLayer.verticalScrollbar(), context, dirtyRect);
        }
    } else if (graphicsLayer == layerForScrollCorner()) {
        LayoutRect scrollCornerAndResizer = m_owningLayer.scrollCornerAndResizerRect();
        context.save();
        context.translate(-scrollCornerAndResizer.x(), -scrollCornerAndResizer.y());
        LayoutRect transformedClip = LayoutRect(clip);
        transformedClip.moveBy(scrollCornerAndResizer.location());
        m_owningLayer.paintScrollCorner(&context, IntPoint(), snappedIntRect(transformedClip));
        m_owningLayer.paintResizer(&context, IntPoint(), transformedClip);
        context.restore();
    }
#ifndef NDEBUG
    if (Page* page = renderer().frame().page())
        page->setIsPainting(false);
#endif
}

float RenderLayerBacking::pageScaleFactor() const
{
    return compositor().pageScaleFactor();
}

float RenderLayerBacking::deviceScaleFactor() const
{
    return compositor().deviceScaleFactor();
}

bool RenderLayerBacking::paintsOpaquelyAtNonIntegralScales(const GraphicsLayer*) const
{
    return m_isMainFrameRenderViewLayer;
}

void RenderLayerBacking::didCommitChangesForLayer(const GraphicsLayer* layer) const
{
    compositor().didFlushChangesForLayer(&m_owningLayer, layer);
}

bool RenderLayerBacking::getCurrentTransform(const GraphicsLayer* graphicsLayer, TransformationMatrix& transform) const
{
    GraphicsLayer* transformedLayer = m_contentsContainmentLayer.get() ? m_contentsContainmentLayer.get() : m_graphicsLayer.get();
    if (graphicsLayer != transformedLayer)
        return false;

    if (m_owningLayer.isTransformed()) {
        transform = m_owningLayer.currentTransform(RenderStyle::individualTransformOperations());
        return true;
    }
    return false;
}

#if 0
bool RenderLayerBacking::isTrackingRepaints() const
{
    return static_cast<GraphicsLayerClient&>(compositor()).isTrackingRepaints();
}

bool RenderLayerBacking::shouldSkipLayerInDump(const GraphicsLayer* layer) const
{
    // Skip the root tile cache's flattening layer.
    return m_isMainFrameRenderViewLayer && layer && layer == m_childContainmentLayer.get();
}

bool RenderLayerBacking::shouldDumpPropertyForLayer(const GraphicsLayer* layer, const char* propertyName, LayerTreeAsTextBehavior flags) const
{
    // For backwards compatibility with WebKit1 and other platforms,
    // skip some properties on the root tile cache.
    if (m_isMainFrameRenderViewLayer && layer == m_graphicsLayer.get() && !(flags & LayerTreeAsTextIncludeRootLayerProperties)) {
        if (!strcmp(propertyName, "drawsContent"))
            return false;

        // Background color could be of interest to tests or other dumpers if it's non-white.
        if (!strcmp(propertyName, "backgroundColor") && layer->backgroundColor() == Color::white)
            return false;

        // The root tile cache's repaints will show up at the top with FrameView's,
        // so don't dump them twice.
        if (!strcmp(propertyName, "repaintRects"))
            return false;
    }

    return true;
}
#endif

bool RenderLayerBacking::useCSS3DTransformInteroperability() const
{
    return renderer().document().settings().css3DTransformInteroperabilityEnabled();
}

#ifndef NDEBUG
void RenderLayerBacking::verifyNotPainting()
{
    ASSERT(!renderer().frame().page() || !renderer().frame().page()->isPainting());
}
#endif

bool RenderLayerBacking::startAnimation(double timeOffset, const Animation& anim, const KeyframeList& keyframes)
{
#if PLATFORM(ESPIAL)
	return false;
#else
    bool hasOpacity = keyframes.containsProperty(CSSPropertyOpacity);
    bool hasRotate = renderer().isBox() && keyframes.containsProperty(CSSPropertyRotate);
	bool hasScale = renderer().isBox() && keyframes.containsProperty(CSSPropertyScale);
	bool hasTranslate = renderer().isBox() && keyframes.containsProperty(CSSPropertyTranslate);
    bool hasTransform = renderer().isBox() && keyframes.containsProperty(CSSPropertyTransform);
#if ENABLE(CSS_FILTERS)
    bool hasFilter = keyframes.containsProperty(CSSPropertyFilter);
#else
    bool hasFilter = false;
#endif

    if (!hasOpacity && !hasRotate && !hasScale && !hasTranslate && !hasTransform && !hasFilter && !hasBackdropFilter)
        return false;

    KeyframeValueList rotateVector(AnimatedPropertyRotate);
    KeyframeValueList scaleVector(AnimatedPropertyScale);
    KeyframeValueList translateVector(AnimatedPropertyTranslate);
    KeyframeValueList transformVector(AnimatedPropertyTransform);
    KeyframeValueList opacityVector(AnimatedPropertyOpacity);
#if ENABLE(CSS_FILTERS)
    KeyframeValueList filterVector(AnimatedPropertyFilter);
#endif

    size_t numKeyframes = keyframes.size();
    for (size_t i = 0; i < numKeyframes; ++i) {
        const KeyframeValue& currentKeyframe = keyframes[i];
        const RenderStyle* keyframeStyle = currentKeyframe.style();
        double key = currentKeyframe.key();

        if (!keyframeStyle)
            continue;

        TimingFunction* tf = currentKeyframe.timingFunction();

        if (currentKeyframe.containsProperty(CSSPropertyRotate))
            rotateVector.insert(makeUnique<TransformAnimationValue>(key, keyframeStyle->rotate(), tf));

        if (currentKeyframe.containsProperty(CSSPropertyScale))
            scaleVector.insert(makeUnique<TransformAnimationValue>(key, keyframeStyle->scale(), tf));

        if (currentKeyframe.containsProperty(CSSPropertyTranslate))
            translateVector.insert(makeUnique<TransformAnimationValue>(key, keyframeStyle->translate(), tf));

        if (currentKeyframe.containsProperty(CSSPropertyTransform))
            transformVector.insert(makeUnique<TransformAnimationValue>(key, keyframeStyle->transform(), tf));

        if (currentKeyframe.containsProperty(CSSPropertyOpacity))
            opacityVector.insert(makeUnique<FloatAnimationValue>(key, keyframeStyle->opacity(), tf));

        if (currentKeyframe.containsProperty(CSSPropertyFilter))
            filterVector.insert(makeUnique<FilterAnimationValue>(key, keyframeStyle->filter(), tf));

#if ENABLE(FILTERS_LEVEL_2)
        if (currentKeyframe.containsProperty(CSSPropertyWebkitBackdropFilter))
            backdropFilterVector.insert(makeUnique<FilterAnimationValue>(key, keyframeStyle->backdropFilter(), tf));
#endif
    }

    if (!renderer().settings().acceleratedCompositedAnimationsEnabled())
        return false;

    bool didAnimate = false;

    if (hasRotate && m_graphicsLayer->addAnimation(rotateVector, snappedIntRect(renderBox()->borderBoxRect()).size(), &animation, keyframes.animationName(), timeOffset))
        didAnimate = true;

    if (hasScale && m_graphicsLayer->addAnimation(scaleVector, snappedIntRect(renderBox()->borderBoxRect()).size(), &animation, keyframes.animationName(), timeOffset))
        didAnimate = true;

    if (hasTranslate && m_graphicsLayer->addAnimation(translateVector, snappedIntRect(renderBox()->borderBoxRect()).size(), &animation, keyframes.animationName(), timeOffset))
        didAnimate = true;

    if (hasTransform && m_graphicsLayer->addAnimation(transformVector, snappedIntRect(renderBox()->borderBoxRect()).size(), anim, keyframes.animationName(), timeOffset))
    	didAnimate = true;

    if (hasOpacity && m_graphicsLayer->addAnimation(opacityVector, IntSize(), anim, keyframes.animationName(), timeOffset))
    	didAnimate = true;

#if ENABLE(CSS_FILTERS)
    if (hasFilter && m_graphicsLayer->addAnimation(filterVector, IntSize(), anim, keyframes.animationName(), timeOffset))
    	didAnimate = true;
#endif

    if (didAnimate) {
        m_owningLayer.setNeedsPostLayoutCompositingUpdate();
        m_owningLayer.setNeedsCompositingGeometryUpdate();
    }

    return didAnimate;
#endif
}

void RenderLayerBacking::animationPaused(double timeOffset, const String& animationName)
{
    m_graphicsLayer->pauseAnimation(animationName, timeOffset);
}

void RenderLayerBacking::animationFinished(const String& animationName)
{
    m_graphicsLayer->removeAnimation(animationName);
    m_owningLayer.setNeedsPostLayoutCompositingUpdate();
    m_owningLayer.setNeedsCompositingGeometryUpdate();
}

void RenderLayerBacking::transformRelatedPropertyDidChange()
{
    m_graphicsLayer->transformRelatedPropertyDidChange();
}

void RenderLayerBacking::notifyAnimationStarted(const GraphicsLayer*, double time)
{
}

void RenderLayerBacking::notifySyncRequired(const GraphicsLayer* layer)
{
    if (renderer().renderTreeBeingDestroyed())
        return;
    compositor().scheduleLayerFlush(layer->canThrottleLayerFlush());
}

// This is used for the 'freeze' API, for testing only.
void RenderLayerBacking::suspendAnimations(double time)
{
    m_graphicsLayer->suspendAnimations(time);
}

void RenderLayerBacking::resumeAnimations()
{
    m_graphicsLayer->resumeAnimations();
}

const LayoutRect& RenderLayerBacking::compositedBounds() const
{
    return m_compositedBounds;
}

bool RenderLayerBacking::setCompositedBounds(const LayoutRect& bounds)
{
    if (bounds == m_compositedBounds)
        return false;

    m_compositedBounds = bounds;
    return true;
}

#if 0
LayoutRect RenderLayerBacking::compositedBoundsIncludingMargin() const
{
    TiledBacking* tiledBacking = this->tiledBacking();
    if (!tiledBacking || !tiledBacking->hasMargins())
        return compositedBounds();

    LayoutRect boundsIncludingMargin = compositedBounds();
    LayoutUnit leftMarginWidth = tiledBacking->leftMarginWidth();
    LayoutUnit topMarginHeight = tiledBacking->topMarginHeight();

    boundsIncludingMargin.moveBy(LayoutPoint(-leftMarginWidth, -topMarginHeight));
    boundsIncludingMargin.expand(leftMarginWidth + tiledBacking->rightMarginWidth(), topMarginHeight + tiledBacking->bottomMarginHeight());

    return boundsIncludingMargin;
}
#endif

CSSPropertyID RenderLayerBacking::graphicsLayerToCSSProperty(AnimatedPropertyID property)
{
    CSSPropertyID cssProperty = CSSPropertyInvalid;
    switch (property) {
    case AnimatedPropertyTranslate:
        cssProperty = CSSPropertyTranslate;
        break;
    case AnimatedPropertyScale:
        cssProperty = CSSPropertyScale;
        break;
    case AnimatedPropertyRotate:
        cssProperty = CSSPropertyRotate;
        break;
	case AnimatedPropertyTransform:
		cssProperty = CSSPropertyTransform;
		break;
	case AnimatedPropertyOpacity:
		cssProperty = CSSPropertyOpacity;
		break;
	case AnimatedPropertyBackgroundColor:
		cssProperty = CSSPropertyBackgroundColor;
		break;
	case AnimatedPropertyFilter:
#if ENABLE(CSS_FILTERS)
		cssProperty = CSSPropertyFilter;
#else
		ASSERT_NOT_REACHED();
#endif
		break;
	case AnimatedPropertyInvalid:
		ASSERT_NOT_REACHED();
    }
    return cssProperty;
}

AnimatedPropertyID RenderLayerBacking::cssToGraphicsLayerProperty(CSSPropertyID cssProperty)
{
    switch (cssProperty) {
    case CSSPropertyTranslate:
        return AnimatedPropertyTranslate;
    case CSSPropertyScale:
        return AnimatedPropertyScale;
    case CSSPropertyRotate:
        return AnimatedPropertyRotate;
	case CSSPropertyTransform:
		return AnimatedPropertyTransform;
	case CSSPropertyOpacity:
		return AnimatedPropertyOpacity;
	case CSSPropertyBackgroundColor:
		return AnimatedPropertyBackgroundColor;
#if ENABLE(CSS_FILTERS)
	case CSSPropertyFilter:
		return AnimatedPropertyFilter;
#endif
	default:
		// It's fine if we see other css properties here; they are just not accelerated.
		break;
    }
    return AnimatedPropertyInvalid;
}

String RenderLayerBacking::nameForLayer() const
{
    StringBuilder name;
    name.append(renderer().renderName());
    if (Element* node = renderer().element()) {
        if (node->isElementNode()) {
            name.append(' ');
            name.append(static_cast<Element*>(node)->tagName());
        }
        if (node->hasID()) {
            name.appendLiteral(" id=\'");
            name.append(static_cast<Element*>(node)->getIdAttribute());
            name.append('\'');
        }

        if (node->hasClass()) {
            name.appendLiteral(" class=\'");
            StyledElement* styledElement = static_cast<StyledElement*>(node);
            String classes;
            for (size_t i = 0; i < styledElement->classNames().size(); ++i) {
                if (i > 0)
                    name.append(' ');
                name.append(styledElement->classNames()[i]);
            }
            name.append('\'');
        }
    }

    if (m_owningLayer.isReflection())
        name.appendLiteral(" (reflection)");

    return name.toString();
}

CompositingLayerType RenderLayerBacking::compositingLayerType() const
{
    if (m_graphicsLayer->usesContentsLayer())
        return MediaCompositingLayer;

    if (m_graphicsLayer->drawsContent())
        return m_graphicsLayer->tiledBacking() ? TiledCompositingLayer : NormalCompositingLayer;
    
    return ContainerCompositingLayer;
}

double RenderLayerBacking::backingStoreMemoryEstimate() const
{
    double backingMemory;
    
    // m_ancestorClippingLayer, m_contentsContainmentLayer and m_childContainmentLayer are just used for masking or containment, so have no backing.
    backingMemory = m_graphicsLayer->backingStoreMemoryEstimate();
    if (m_foregroundLayer)
        backingMemory += m_foregroundLayer->backingStoreMemoryEstimate();
    if (m_backgroundLayer)
        backingMemory += m_backgroundLayer->backingStoreMemoryEstimate();
    if (m_maskLayer)
        backingMemory += m_maskLayer->backingStoreMemoryEstimate();
    if (m_childClippingMaskLayer)
        backingMemory += m_childClippingMaskLayer->backingStoreMemoryEstimate();

    if (m_scrolledContentsLayer)
        backingMemory += m_scrolledContentsLayer->backingStoreMemoryEstimate();

    if (m_layerForHorizontalScrollbar)
        backingMemory += m_layerForHorizontalScrollbar->backingStoreMemoryEstimate();

    if (m_layerForVerticalScrollbar)
        backingMemory += m_layerForVerticalScrollbar->backingStoreMemoryEstimate();

    if (m_layerForScrollCorner)
        backingMemory += m_layerForScrollCorner->backingStoreMemoryEstimate();
    
    return backingMemory;
}

TransformationMatrix RenderLayerBacking::transformMatrixForProperty(AnimatedPropertyID property) const
{
    TransformationMatrix matrix;

    auto applyTransformOperation = [&](TransformOperation* operation) {
        if (operation)
            operation->apply(matrix, snappedIntRect(m_owningLayer.rendererBorderBoxRect()).size());
    };

    if (property == AnimatedPropertyTranslate)
        applyTransformOperation(renderer().style()->translate());
    else if (property == AnimatedPropertyScale)
        applyTransformOperation(renderer().style()->scale());
    else if (property == AnimatedPropertyRotate)
        applyTransformOperation(renderer().style()->rotate());
    else if (property == AnimatedPropertyTransform)
        renderer().style()->transform().apply(snappedIntRect(m_owningLayer.rendererBorderBoxRect()).size(), matrix);
    else
        ASSERT_NOT_REACHED();

    return matrix;
}

} // namespace WebCore

#endif // USE(ACCELERATED_COMPOSITING)
