a78a74e7b3306976e446cb530fac7fd07a69ac13
[WebKit-https.git] / Source / WebCore / rendering / RenderLayerBacking.cpp
1 /*
2  * Copyright (C) 2009, 2010, 2011 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27
28 #include "RenderLayerBacking.h"
29
30 #include "BitmapImage.h"
31 #include "CSSAnimationController.h"
32 #include "CanvasRenderingContext.h"
33 #include "CSSPropertyNames.h"
34 #include "CachedImage.h"
35 #include "Chrome.h"
36 #include "DocumentTimeline.h"
37 #include "EventRegion.h"
38 #include "Frame.h"
39 #include "FrameView.h"
40 #include "GraphicsContext.h"
41 #include "GraphicsLayer.h"
42 #include "HTMLBodyElement.h"
43 #include "HTMLCanvasElement.h"
44 #include "HTMLIFrameElement.h"
45 #include "HTMLMediaElement.h"
46 #include "HTMLNames.h"
47 #include "HTMLPlugInElement.h"
48 #include "InspectorInstrumentation.h"
49 #include "KeyframeList.h"
50 #include "LayerAncestorClippingStack.h"
51 #include "Logging.h"
52 #include "Page.h"
53 #include "PerformanceLoggingClient.h"
54 #include "PluginViewBase.h"
55 #include "ProgressTracker.h"
56 #include "RenderFragmentContainer.h"
57 #include "RenderFragmentedFlow.h"
58 #include "RenderHTMLCanvas.h"
59 #include "RenderIFrame.h"
60 #include "RenderImage.h"
61 #include "RenderLayerCompositor.h"
62 #include "RenderEmbeddedObject.h"
63 #include "RenderMedia.h"
64 #include "RenderVideo.h"
65 #include "RenderView.h"
66 #include "RuntimeEnabledFeatures.h"
67 #include "ScrollingCoordinator.h"
68 #include "Settings.h"
69 #include "StyleResolver.h"
70 #include "TiledBacking.h"
71 #include <wtf/text/TextStream.h>
72
73 #if PLATFORM(IOS_FAMILY)
74 #include "RuntimeApplicationChecks.h"
75 #endif
76
77 #if PLATFORM(MAC)
78 #include "LocalDefaultSystemAppearance.h"
79 #endif
80
81 namespace WebCore {
82
83 using namespace HTMLNames;
84
85 CanvasCompositingStrategy canvasCompositingStrategy(const RenderObject& renderer)
86 {
87     ASSERT(renderer.isCanvas());
88     
89     const HTMLCanvasElement* canvas = downcast<HTMLCanvasElement>(renderer.node());
90     auto* context = canvas->renderingContext();
91     if (!context || !context->isAccelerated())
92         return UnacceleratedCanvas;
93     
94     if (context->isGPUBased())
95         return CanvasAsLayerContents;
96
97 #if ENABLE(ACCELERATED_2D_CANVAS)
98     return CanvasAsLayerContents;
99 #else
100     return CanvasPaintedToLayer; // On Mac and iOS we paint accelerated canvases into their layers.
101 #endif
102 }
103
104 // This acts as a cache of what we know about what is painting into this RenderLayerBacking.
105 class PaintedContentsInfo {
106 public:
107     enum class ContentsTypeDetermination {
108         Unknown,
109         SimpleContainer,
110         DirectlyCompositedImage,
111         Painted
112     };
113
114     PaintedContentsInfo(RenderLayerBacking& inBacking)
115         : m_backing(inBacking)
116     {
117     }
118     
119     void setWantsSubpixelAntialiasedTextState(bool wantsSubpixelAntialiasedTextState)
120     {
121         m_subpixelAntialiasedText = wantsSubpixelAntialiasedTextState ? RequestState::Unknown : RequestState::DontCare;
122     }
123
124     RequestState paintsBoxDecorationsDetermination();
125     bool paintsBoxDecorations()
126     {
127         RequestState state = paintsBoxDecorationsDetermination();
128         return state == RequestState::True || state == RequestState::Undetermined;
129     }
130
131     RequestState paintsContentDetermination();
132     bool paintsContent()
133     {
134         RequestState state = paintsContentDetermination();
135         return state == RequestState::True || state == RequestState::Undetermined;
136     }
137
138     RequestState paintsSubpixelAntialiasedTextDetermination();
139     bool paintsSubpixelAntialiasedText()
140     {
141         RequestState state = paintsSubpixelAntialiasedTextDetermination();
142         return state == RequestState::True || state == RequestState::Undetermined;
143     }
144
145     ContentsTypeDetermination contentsTypeDetermination();
146     bool isSimpleContainer()
147     {
148         return contentsTypeDetermination() == ContentsTypeDetermination::SimpleContainer;
149     }
150
151     bool isDirectlyCompositedImage()
152     {
153         return contentsTypeDetermination() == ContentsTypeDetermination::DirectlyCompositedImage;
154     }
155
156     RenderLayerBacking& m_backing;
157     RequestState m_boxDecorations { RequestState::Unknown };
158     RequestState m_content { RequestState::Unknown };
159     RequestState m_subpixelAntialiasedText { RequestState::DontCare };
160
161     ContentsTypeDetermination m_contentsType { ContentsTypeDetermination::Unknown };
162 };
163
164 RequestState PaintedContentsInfo::paintsBoxDecorationsDetermination()
165 {
166     if (m_boxDecorations != RequestState::Unknown)
167         return m_boxDecorations;
168
169     m_boxDecorations = m_backing.paintsBoxDecorations() ? RequestState::True : RequestState::False;
170     return m_boxDecorations;
171 }
172
173 RequestState PaintedContentsInfo::paintsContentDetermination()
174 {
175     if (m_content != RequestState::Unknown && m_subpixelAntialiasedText != RequestState::Unknown)
176         return m_content;
177
178     RenderLayer::PaintedContentRequest contentRequest;
179     if (m_subpixelAntialiasedText == RequestState::Unknown)
180         contentRequest.hasSubpixelAntialiasedText = RequestState::Unknown;
181
182     m_content = m_backing.paintsContent(contentRequest) ? RequestState::True : RequestState::False;
183
184     if (m_subpixelAntialiasedText == RequestState::Unknown)
185         m_subpixelAntialiasedText = contentRequest.hasSubpixelAntialiasedText;
186
187     return m_content;
188 }
189
190 RequestState PaintedContentsInfo::paintsSubpixelAntialiasedTextDetermination()
191 {
192     if (m_subpixelAntialiasedText != RequestState::Unknown)
193         return m_subpixelAntialiasedText;
194
195     paintsContentDetermination();
196
197     return m_subpixelAntialiasedText;
198 }
199
200 PaintedContentsInfo::ContentsTypeDetermination PaintedContentsInfo::contentsTypeDetermination()
201 {
202     if (m_contentsType != ContentsTypeDetermination::Unknown)
203         return m_contentsType;
204
205     if (m_backing.isSimpleContainerCompositingLayer(*this))
206         m_contentsType = ContentsTypeDetermination::SimpleContainer;
207     else if (m_backing.isDirectlyCompositedImage())
208         m_contentsType = ContentsTypeDetermination::DirectlyCompositedImage;
209     else
210         m_contentsType = ContentsTypeDetermination::Painted;
211
212     return m_contentsType;
213 }
214
215
216 RenderLayerBacking::RenderLayerBacking(RenderLayer& layer)
217     : m_owningLayer(layer)
218 {
219     if (layer.isRenderViewLayer()) {
220         m_isMainFrameRenderViewLayer = renderer().frame().isMainFrame();
221         m_isFrameLayerWithTiledBacking = renderer().page().chrome().client().shouldUseTiledBackingForFrameView(renderer().view().frameView());
222     }
223     
224     createPrimaryGraphicsLayer();
225 #if ENABLE(FULLSCREEN_API)
226     setRequiresBackgroundLayer(layer.renderer().isRenderFullScreen());
227 #endif
228
229     if (auto* tiledBacking = this->tiledBacking()) {
230         tiledBacking->setIsInWindow(renderer().page().isInWindow());
231
232         if (m_isFrameLayerWithTiledBacking) {
233             tiledBacking->setScrollingPerformanceLoggingEnabled(renderer().settings().scrollingPerformanceLoggingEnabled());
234             adjustTiledBackingCoverage();
235         }
236     }
237 }
238
239 RenderLayerBacking::~RenderLayerBacking()
240 {
241     // Note that m_owningLayer->backing() is null here.
242     updateAncestorClipping(false, nullptr);
243     updateChildClippingStrategy(false);
244     updateDescendantClippingLayer(false);
245     updateOverflowControlsLayers(false, false, false);
246     updateForegroundLayer(false);
247     updateBackgroundLayer(false);
248     updateMaskingLayer(false, false);
249     updateScrollingLayers(false);
250     
251     ASSERT(!m_viewportConstrainedNodeID);
252     ASSERT(!m_scrollingNodeID);
253     ASSERT(!m_frameHostingNodeID);
254     ASSERT(!m_positioningNodeID);
255
256     destroyGraphicsLayers();
257 }
258
259 void RenderLayerBacking::willBeDestroyed()
260 {
261     ASSERT(m_owningLayer.backing() == this);
262     compositor().removeFromScrollCoordinatedLayers(m_owningLayer);
263
264     clearBackingSharingLayers();
265 }
266
267 void RenderLayerBacking::willDestroyLayer(const GraphicsLayer* layer)
268 {
269     if (layer && layer->type() == GraphicsLayer::Type::Normal && layer->tiledBacking())
270         compositor().layerTiledBackingUsageChanged(layer, false);
271 }
272
273 static void clearBackingSharingLayerProviders(Vector<WeakPtr<RenderLayer>>& sharingLayers)
274 {
275     for (auto& layerWeakPtr : sharingLayers) {
276         if (!layerWeakPtr)
277             continue;
278         layerWeakPtr->setBackingProviderLayer(nullptr);
279     }
280 }
281
282 void RenderLayerBacking::setBackingSharingLayers(Vector<WeakPtr<RenderLayer>>&& sharingLayers)
283 {
284     clearBackingSharingLayerProviders(m_backingSharingLayers);
285
286     if (sharingLayers != m_backingSharingLayers)
287         setContentsNeedDisplay(); // This could be optimize to only repaint rects for changed layers.
288
289     m_backingSharingLayers = WTFMove(sharingLayers);
290
291     for (auto& layerWeakPtr : m_backingSharingLayers)
292         layerWeakPtr->setBackingProviderLayer(&m_owningLayer);
293 }
294
295 void RenderLayerBacking::removeBackingSharingLayer(RenderLayer& layer)
296 {
297     layer.setBackingProviderLayer(nullptr);
298     m_backingSharingLayers.removeAll(&layer);
299 }
300
301 void RenderLayerBacking::clearBackingSharingLayers()
302 {
303     clearBackingSharingLayerProviders(m_backingSharingLayers);
304     m_backingSharingLayers.clear();
305 }
306
307 Ref<GraphicsLayer> RenderLayerBacking::createGraphicsLayer(const String& name, GraphicsLayer::Type layerType)
308 {
309     auto* graphicsLayerFactory = renderer().page().chrome().client().graphicsLayerFactory();
310
311     auto graphicsLayer = GraphicsLayer::create(graphicsLayerFactory, *this, layerType);
312
313     graphicsLayer->setName(name);
314
315 #if PLATFORM(COCOA) && USE(CA)
316     graphicsLayer->setAcceleratesDrawing(compositor().acceleratedDrawingEnabled());
317     graphicsLayer->setUsesDisplayListDrawing(compositor().displayListDrawingEnabled());
318 #endif
319     
320     return graphicsLayer;
321 }
322
323 void RenderLayerBacking::setUsesDisplayListDrawing(bool usesDisplayListDrawing)
324 {
325     // Note that this only affects the primary layer.
326     if (usesDisplayListDrawing == m_graphicsLayer->usesDisplayListDrawing())
327         return;
328
329     m_graphicsLayer->setUsesDisplayListDrawing(usesDisplayListDrawing);
330     if (m_graphicsLayer->drawsContent())
331         m_graphicsLayer->setNeedsDisplay();
332 }
333
334 String RenderLayerBacking::displayListAsText(DisplayList::AsTextFlags flags) const
335 {
336     return m_graphicsLayer->displayListAsText(flags);
337 }
338
339 void RenderLayerBacking::setIsTrackingDisplayListReplay(bool isTrackingReplay)
340 {
341     m_graphicsLayer->setIsTrackingDisplayListReplay(isTrackingReplay);
342 }
343
344 String RenderLayerBacking::replayDisplayListAsText(DisplayList::AsTextFlags flags) const
345 {
346     return m_graphicsLayer->replayDisplayListAsText(flags);
347 }
348
349 void RenderLayerBacking::tiledBackingUsageChanged(const GraphicsLayer* layer, bool usingTiledBacking)
350 {
351     compositor().layerTiledBackingUsageChanged(layer, usingTiledBacking);
352 }
353
354 TiledBacking* RenderLayerBacking::tiledBacking() const
355 {
356     return m_graphicsLayer->tiledBacking();
357 }
358
359 static TiledBacking::TileCoverage computePageTiledBackingCoverage(const RenderLayer& layer)
360 {
361     // If the page is non-visible, don't incur the cost of keeping extra tiles for scrolling.
362     if (!layer.page().isVisible())
363         return TiledBacking::CoverageForVisibleArea;
364
365     auto& frameView = layer.renderer().view().frameView();
366
367     TiledBacking::TileCoverage tileCoverage = TiledBacking::CoverageForVisibleArea;
368     bool useMinimalTilesDuringLiveResize = frameView.inLiveResize();
369     if (frameView.speculativeTilingEnabled() && !useMinimalTilesDuringLiveResize) {
370         bool clipsToExposedRect = static_cast<bool>(frameView.viewExposedRect());
371         if (frameView.horizontalScrollbarMode() != ScrollbarAlwaysOff || clipsToExposedRect)
372             tileCoverage |= TiledBacking::CoverageForHorizontalScrolling;
373
374         if (frameView.verticalScrollbarMode() != ScrollbarAlwaysOff || clipsToExposedRect)
375             tileCoverage |= TiledBacking::CoverageForVerticalScrolling;
376     }
377     return tileCoverage;
378 }
379
380 static TiledBacking::TileCoverage computeOverflowTiledBackingCoverage(const RenderLayer& layer)
381 {
382     // If the page is non-visible, don't incur the cost of keeping extra tiles for scrolling.
383     if (!layer.page().isVisible())
384         return TiledBacking::CoverageForVisibleArea;
385     
386     auto& frameView = layer.renderer().view().frameView();
387
388     TiledBacking::TileCoverage tileCoverage = TiledBacking::CoverageForVisibleArea;
389     bool useMinimalTilesDuringLiveResize = frameView.inLiveResize();
390     if (!useMinimalTilesDuringLiveResize) {
391         if (layer.hasScrollableHorizontalOverflow())
392             tileCoverage |= TiledBacking::CoverageForHorizontalScrolling;
393
394         if (layer.hasScrollableVerticalOverflow())
395             tileCoverage |= TiledBacking::CoverageForVerticalScrolling;
396     }
397     return tileCoverage;
398 }
399
400 void RenderLayerBacking::adjustTiledBackingCoverage()
401 {
402     if (m_isFrameLayerWithTiledBacking) {
403         auto tileCoverage = computePageTiledBackingCoverage(m_owningLayer);
404         tiledBacking()->setTileCoverage(tileCoverage);
405     }
406
407     if (m_owningLayer.hasCompositedScrollableOverflow() && m_scrolledContentsLayer) {
408         if (auto* tiledBacking = m_scrolledContentsLayer->tiledBacking()) {
409             auto tileCoverage = computeOverflowTiledBackingCoverage(m_owningLayer);
410             tiledBacking->setTileCoverage(tileCoverage);
411         }
412     }
413 }
414
415 void RenderLayerBacking::setTiledBackingHasMargins(bool hasExtendedBackgroundOnLeftAndRight, bool hasExtendedBackgroundOnTopAndBottom)
416 {
417     if (!m_isFrameLayerWithTiledBacking)
418         return;
419
420     tiledBacking()->setHasMargins(hasExtendedBackgroundOnTopAndBottom, hasExtendedBackgroundOnTopAndBottom, hasExtendedBackgroundOnLeftAndRight, hasExtendedBackgroundOnLeftAndRight);
421 }
422
423 void RenderLayerBacking::updateDebugIndicators(bool showBorder, bool showRepaintCounter)
424 {
425     m_graphicsLayer->setShowDebugBorder(showBorder);
426     m_graphicsLayer->setShowRepaintCounter(showRepaintCounter);
427     
428     if (m_ancestorClippingStack) {
429         for (auto& entry : m_ancestorClippingStack->stack())
430             entry.clippingLayer->setShowDebugBorder(showBorder);
431     }
432
433     if (m_foregroundLayer) {
434         m_foregroundLayer->setShowDebugBorder(showBorder);
435         m_foregroundLayer->setShowRepaintCounter(showRepaintCounter);
436     }
437     
438     if (m_contentsContainmentLayer)
439         m_contentsContainmentLayer->setShowDebugBorder(showBorder);
440     
441     if (m_backgroundLayer) {
442         m_backgroundLayer->setShowDebugBorder(showBorder);
443         m_backgroundLayer->setShowRepaintCounter(showRepaintCounter);
444     }
445
446     if (m_maskLayer) {
447         m_maskLayer->setShowDebugBorder(showBorder);
448         m_maskLayer->setShowRepaintCounter(showRepaintCounter);
449     }
450
451     if (m_layerForHorizontalScrollbar)
452         m_layerForHorizontalScrollbar->setShowDebugBorder(showBorder);
453
454     if (m_layerForVerticalScrollbar)
455         m_layerForVerticalScrollbar->setShowDebugBorder(showBorder);
456
457     if (m_layerForScrollCorner)
458         m_layerForScrollCorner->setShowDebugBorder(showBorder);
459
460     if (m_scrollContainerLayer)
461         m_scrollContainerLayer->setShowDebugBorder(showBorder);
462
463     if (m_scrolledContentsLayer) {
464         m_scrolledContentsLayer->setShowDebugBorder(showBorder);
465         m_scrolledContentsLayer->setShowRepaintCounter(showRepaintCounter);
466     }
467 }
468
469 void RenderLayerBacking::createPrimaryGraphicsLayer()
470 {
471     String layerName = m_owningLayer.name();
472     const unsigned maxLayerNameLength = 100;
473     if (layerName.length() > maxLayerNameLength) {
474         layerName.truncate(maxLayerNameLength);
475         layerName.append("...");
476     }
477     m_graphicsLayer = createGraphicsLayer(layerName, m_isFrameLayerWithTiledBacking ? GraphicsLayer::Type::PageTiledBacking : GraphicsLayer::Type::Normal);
478
479     if (m_isFrameLayerWithTiledBacking) {
480         m_childContainmentLayer = createGraphicsLayer("Page TiledBacking containment");
481         m_graphicsLayer->addChild(*m_childContainmentLayer);
482     }
483
484 #if !PLATFORM(IOS_FAMILY)
485     if (m_isMainFrameRenderViewLayer) {
486         // Page scale is applied above the RenderView on iOS.
487         m_graphicsLayer->setContentsOpaque(!compositor().viewHasTransparentBackground());
488         m_graphicsLayer->setAppliesPageScale();
489     }
490 #endif
491
492 #if PLATFORM(COCOA) && USE(CA)
493     if (!compositor().acceleratedDrawingEnabled() && renderer().isCanvas()) {
494         const HTMLCanvasElement* canvas = downcast<HTMLCanvasElement>(renderer().element());
495         if (canvas->shouldAccelerate(canvas->size()))
496             m_graphicsLayer->setAcceleratesDrawing(true);
497     }
498 #endif    
499     
500     updateOpacity(renderer().style());
501     updateTransform(renderer().style());
502     updateFilters(renderer().style());
503 #if ENABLE(FILTERS_LEVEL_2)
504     updateBackdropFilters(renderer().style());
505 #endif
506 #if ENABLE(CSS_COMPOSITING)
507     updateBlendMode(renderer().style());
508 #endif
509     updateCustomAppearance(renderer().style());
510 }
511
512 #if PLATFORM(IOS_FAMILY)
513 void RenderLayerBacking::layerWillBeDestroyed()
514 {
515     auto& renderer = this->renderer();
516     if (is<RenderEmbeddedObject>(renderer) && downcast<RenderEmbeddedObject>(renderer).allowsAcceleratedCompositing()) {
517         auto* pluginViewBase = downcast<PluginViewBase>(downcast<RenderWidget>(renderer).widget());
518         if (pluginViewBase && m_graphicsLayer->contentsLayerForMedia())
519             pluginViewBase->detachPluginLayer();
520     }
521 }
522
523 bool RenderLayerBacking::needsIOSDumpRenderTreeMainFrameRenderViewLayerIsAlwaysOpaqueHack(const GraphicsLayer& layer) const
524 {
525     if (m_isMainFrameRenderViewLayer && IOSApplication::isDumpRenderTree()) {
526         // In iOS WebKit1 the main frame's RenderView layer is always transparent. We lie that it is opaque so that
527         // internals.layerTreeAsText() tests succeed.
528         ASSERT_UNUSED(layer, !layer.contentsOpaque());
529         return true;
530     }
531     return false;
532 }
533 #endif
534
535 void RenderLayerBacking::destroyGraphicsLayers()
536 {
537     if (m_graphicsLayer) {
538         m_graphicsLayer->setMaskLayer(nullptr);
539         m_graphicsLayer->setReplicatedByLayer(nullptr);
540         willDestroyLayer(m_graphicsLayer.get());
541     }
542
543     GraphicsLayer::clear(m_maskLayer);
544
545     if (m_ancestorClippingStack) {
546         for (auto& entry : m_ancestorClippingStack->stack())
547             GraphicsLayer::unparentAndClear(entry.clippingLayer);
548     }
549
550     GraphicsLayer::unparentAndClear(m_contentsContainmentLayer);
551     GraphicsLayer::unparentAndClear(m_foregroundLayer);
552     GraphicsLayer::unparentAndClear(m_backgroundLayer);
553     GraphicsLayer::unparentAndClear(m_childContainmentLayer);
554     GraphicsLayer::unparentAndClear(m_childClippingMaskLayer);
555     GraphicsLayer::unparentAndClear(m_scrollContainerLayer);
556     GraphicsLayer::unparentAndClear(m_scrolledContentsLayer);
557     GraphicsLayer::unparentAndClear(m_graphicsLayer);
558 }
559
560 void RenderLayerBacking::updateOpacity(const RenderStyle& style)
561 {
562     m_graphicsLayer->setOpacity(compositingOpacity(style.opacity()));
563 }
564
565 void RenderLayerBacking::updateTransform(const RenderStyle& style)
566 {
567     // FIXME: This could use m_owningLayer.transform(), but that currently has transform-origin
568     // baked into it, and we don't want that.
569     TransformationMatrix t;
570     if (m_owningLayer.hasTransform()) {
571         auto& renderBox = downcast<RenderBox>(renderer());
572         style.applyTransform(t, snapRectToDevicePixels(renderBox.borderBoxRect(), deviceScaleFactor()), RenderStyle::ExcludeTransformOrigin);
573         makeMatrixRenderable(t, compositor().canRender3DTransforms());
574     }
575     
576     if (m_contentsContainmentLayer) {
577         m_contentsContainmentLayer->setTransform(t);
578         m_graphicsLayer->setTransform({ });
579     } else
580         m_graphicsLayer->setTransform(t);
581 }
582
583 void RenderLayerBacking::updateFilters(const RenderStyle& style)
584 {
585     m_canCompositeFilters = m_graphicsLayer->setFilters(style.filter());
586 }
587
588 #if ENABLE(FILTERS_LEVEL_2)
589 void RenderLayerBacking::updateBackdropFilters(const RenderStyle& style)
590 {
591     m_canCompositeBackdropFilters = m_graphicsLayer->setBackdropFilters(style.backdropFilter());
592 }
593
594 void RenderLayerBacking::updateBackdropFiltersGeometry()
595 {
596     if (!m_canCompositeBackdropFilters)
597         return;
598
599     if (!is<RenderBox>(renderer()))
600         return;
601
602     auto& renderer = downcast<RenderBox>(this->renderer());
603     LayoutRect boxRect = renderer.borderBoxRect();
604     if (renderer.hasClip())
605         boxRect.intersect(renderer.clipRect(LayoutPoint(), nullptr));
606     boxRect.move(contentOffsetInCompositingLayer());
607
608     FloatRoundedRect backdropFiltersRect;
609     if (renderer.style().hasBorderRadius() && !renderer.hasClip())
610         backdropFiltersRect = renderer.style().getRoundedInnerBorderFor(boxRect).pixelSnappedRoundedRectForPainting(deviceScaleFactor());
611     else
612         backdropFiltersRect = FloatRoundedRect(snapRectToDevicePixels(boxRect, deviceScaleFactor()));
613
614     m_graphicsLayer->setBackdropFiltersRect(backdropFiltersRect);
615 }
616 #endif
617
618 #if ENABLE(CSS_COMPOSITING)
619 void RenderLayerBacking::updateBlendMode(const RenderStyle& style)
620 {
621     // FIXME: where is the blend mode updated when m_ancestorClippingStacks come and go?
622     if (m_ancestorClippingStack) {
623         m_ancestorClippingStack->stack().first().clippingLayer->setBlendMode(style.blendMode());
624         m_graphicsLayer->setBlendMode(BlendMode::Normal);
625     } else
626         m_graphicsLayer->setBlendMode(style.blendMode());
627 }
628 #endif
629
630 void RenderLayerBacking::updateCustomAppearance(const RenderStyle& style)
631 {
632     ControlPart appearance = style.appearance();
633     if (appearance == MediaControlsLightBarBackgroundPart)
634         m_graphicsLayer->setCustomAppearance(GraphicsLayer::CustomAppearance::LightBackdrop);
635     else if (appearance == MediaControlsDarkBarBackgroundPart)
636         m_graphicsLayer->setCustomAppearance(GraphicsLayer::CustomAppearance::DarkBackdrop);
637     else
638         m_graphicsLayer->setCustomAppearance(GraphicsLayer::CustomAppearance::None);
639 }
640
641 static bool layerOrAncestorIsTransformedOrUsingCompositedScrolling(RenderLayer& layer)
642 {
643     for (auto* curr = &layer; curr; curr = curr->parent()) {
644         if (curr->hasTransform() || curr->hasCompositedScrollableOverflow())
645             return true;
646     }
647
648     return false;
649 }
650
651 bool RenderLayerBacking::shouldClipCompositedBounds() const
652 {
653 #if !PLATFORM(IOS_FAMILY)
654     // Scrollbar layers use this layer for relative positioning, so don't clip.
655     if (layerForHorizontalScrollbar() || layerForVerticalScrollbar())
656         return false;
657 #endif
658
659     if (m_isFrameLayerWithTiledBacking)
660         return false;
661
662     if (layerOrAncestorIsTransformedOrUsingCompositedScrolling(m_owningLayer))
663         return false;
664
665     return true;
666 }
667
668 static bool hasNonZeroTransformOrigin(const RenderObject& renderer)
669 {
670     const RenderStyle& style = renderer.style();
671     return (style.transformOriginX().type() == Fixed && style.transformOriginX().value())
672         || (style.transformOriginY().type() == Fixed && style.transformOriginY().value());
673 }
674
675 bool RenderLayerBacking::updateCompositedBounds()
676 {
677     LayoutRect layerBounds = m_owningLayer.calculateLayerBounds(&m_owningLayer, { }, RenderLayer::defaultCalculateLayerBoundsFlags() | RenderLayer::ExcludeHiddenDescendants | RenderLayer::DontConstrainForMask);
678     // Clip to the size of the document or enclosing overflow-scroll layer.
679     // If this or an ancestor is transformed, we can't currently compute the correct rect to intersect with.
680     // We'd need RenderObject::convertContainerToLocalQuad(), which doesn't yet exist.
681     if (shouldClipCompositedBounds()) {
682         auto& view = renderer().view();
683         auto* rootLayer = view.layer();
684
685         LayoutRect clippingBounds;
686         if (renderer().isFixedPositioned() && renderer().container() == &view)
687             clippingBounds = view.frameView().rectForFixedPositionLayout();
688         else
689             clippingBounds = view.unscaledDocumentRect();
690
691         if (&m_owningLayer != rootLayer)
692             clippingBounds.intersect(m_owningLayer.backgroundClipRect(RenderLayer::ClipRectsContext(rootLayer, AbsoluteClipRects)).rect()); // FIXME: Incorrect for CSS regions.
693
694         LayoutPoint delta = m_owningLayer.convertToLayerCoords(rootLayer, LayoutPoint(), RenderLayer::AdjustForColumns);
695         clippingBounds.move(-delta.x(), -delta.y());
696
697         layerBounds.intersect(clippingBounds);
698     }
699
700     // If the backing provider has overflow:clip, we know all sharing layers are affected by the clip because they are containing-block descendants.
701     if (!renderer().hasOverflowClip()) {
702         for (auto& layerWeakPtr : m_backingSharingLayers) {
703             auto* boundsRootLayer = &m_owningLayer;
704             ASSERT(layerWeakPtr->isDescendantOf(m_owningLayer));
705             auto offset = layerWeakPtr->offsetFromAncestor(&m_owningLayer);
706             auto bounds = layerWeakPtr->calculateLayerBounds(boundsRootLayer, offset, RenderLayer::defaultCalculateLayerBoundsFlags() | RenderLayer::ExcludeHiddenDescendants | RenderLayer::DontConstrainForMask);
707             layerBounds.unite(bounds);
708         }
709     }
710
711     // If the element has a transform-origin that has fixed lengths, and the renderer has zero size,
712     // then we need to ensure that the compositing layer has non-zero size so that we can apply
713     // the transform-origin via the GraphicsLayer anchorPoint (which is expressed as a fractional value).
714     if (layerBounds.isEmpty() && (hasNonZeroTransformOrigin(renderer()) || renderer().style().hasPerspective())) {
715         layerBounds.setWidth(1);
716         layerBounds.setHeight(1);
717         m_artificiallyInflatedBounds = true;
718     } else
719         m_artificiallyInflatedBounds = false;
720
721     return setCompositedBounds(layerBounds);
722 }
723
724 void RenderLayerBacking::updateAfterWidgetResize()
725 {
726     if (!is<RenderWidget>(renderer()))
727         return;
728
729     if (auto* innerCompositor = RenderLayerCompositor::frameContentsCompositor(downcast<RenderWidget>(renderer()))) {
730         innerCompositor->frameViewDidChangeSize();
731         innerCompositor->frameViewDidChangeLocation(flooredIntPoint(contentsBox().location()));
732     }
733 }
734
735 void RenderLayerBacking::updateAfterLayout(bool needsClippingUpdate, bool needsFullRepaint)
736 {
737     LOG(Compositing, "RenderLayerBacking %p updateAfterLayout (layer %p)", this, &m_owningLayer);
738
739     // This is the main trigger for layout changing layer geometry, but we have to do the work again in updateBackingAndHierarchy()
740     // when we know the final compositing hierarchy. We can't just set dirty bits from RenderLayer::setSize() because that doesn't
741     // take overflow into account.
742     if (updateCompositedBounds()) {
743         m_owningLayer.setNeedsCompositingGeometryUpdate();
744         // This layer's geometry affects those of its children.
745         m_owningLayer.setChildrenNeedCompositingGeometryUpdate();
746     } else if (needsClippingUpdate) {
747         m_owningLayer.setNeedsCompositingConfigurationUpdate();
748         m_owningLayer.setNeedsCompositingGeometryUpdate();
749     }
750     
751     if (needsFullRepaint && canIssueSetNeedsDisplay())
752         setContentsNeedDisplay();
753 }
754
755 // This can only update things that don't require up-to-date layout.
756 void RenderLayerBacking::updateConfigurationAfterStyleChange()
757 {
758     updateMaskingLayer(renderer().hasMask(), renderer().hasClipPath());
759
760     if (m_owningLayer.hasReflection()) {
761         if (m_owningLayer.reflectionLayer()->backing()) {
762             auto* reflectionLayer = m_owningLayer.reflectionLayer()->backing()->graphicsLayer();
763             m_graphicsLayer->setReplicatedByLayer(reflectionLayer);
764         }
765     } else
766         m_graphicsLayer->setReplicatedByLayer(nullptr);
767
768     // FIXME: do we care if opacity is animating?
769     auto& style = renderer().style();
770     updateOpacity(style);
771     updateFilters(style);
772
773 #if ENABLE(FILTERS_LEVEL_2)
774     updateBackdropFilters(style);
775 #endif
776 #if ENABLE(CSS_COMPOSITING)
777     updateBlendMode(style);
778 #endif
779     updateCustomAppearance(style);
780 }
781
782 bool RenderLayerBacking::updateConfiguration()
783 {
784     ASSERT(!m_owningLayer.normalFlowListDirty());
785     ASSERT(!m_owningLayer.zOrderListsDirty());
786     ASSERT(!renderer().view().needsLayout());
787
788     bool layerConfigChanged = false;
789     auto& compositor = this->compositor();
790
791     setBackgroundLayerPaintsFixedRootBackground(compositor.needsFixedRootBackgroundLayer(m_owningLayer));
792
793     if (updateBackgroundLayer(m_backgroundLayerPaintsFixedRootBackground || m_requiresBackgroundLayer))
794         layerConfigChanged = true;
795
796     if (updateForegroundLayer(compositor.needsContentsCompositingLayer(m_owningLayer)))
797         layerConfigChanged = true;
798     
799     bool needsDescendantsClippingLayer = false;
800     bool usesCompositedScrolling = m_owningLayer.hasCompositedScrollableOverflow();
801
802     if (usesCompositedScrolling) {
803         // If it's scrollable, it has to be a box.
804         auto& renderBox = downcast<RenderBox>(renderer());
805         FloatRoundedRect contentsClippingRect = renderer().style().getRoundedInnerBorderFor(renderBox.borderBoxRect()).pixelSnappedRoundedRectForPainting(deviceScaleFactor());
806         needsDescendantsClippingLayer = contentsClippingRect.isRounded();
807     } else
808         needsDescendantsClippingLayer = RenderLayerCompositor::clipsCompositingDescendants(m_owningLayer);
809
810     if (updateScrollingLayers(usesCompositedScrolling))
811         layerConfigChanged = true;
812
813     if (updateDescendantClippingLayer(needsDescendantsClippingLayer))
814         layerConfigChanged = true;
815
816     auto* compositingAncestor = m_owningLayer.ancestorCompositingLayer();
817     if (updateAncestorClipping(compositor.clippedByAncestor(m_owningLayer, compositingAncestor), compositingAncestor))
818         layerConfigChanged = true;
819
820     if (updateOverflowControlsLayers(requiresHorizontalScrollbarLayer(), requiresVerticalScrollbarLayer(), requiresScrollCornerLayer()))
821         layerConfigChanged = true;
822
823     if (layerConfigChanged)
824         updateInternalHierarchy();
825
826     if (auto* flatteningLayer = tileCacheFlatteningLayer()) {
827         if (layerConfigChanged || flatteningLayer->parent() != m_graphicsLayer.get())
828             m_graphicsLayer->addChild(*flatteningLayer);
829     }
830
831     if (updateMaskingLayer(renderer().hasMask(), renderer().hasClipPath()))
832         layerConfigChanged = true;
833
834     updateChildClippingStrategy(needsDescendantsClippingLayer);
835
836     if (m_owningLayer.hasReflection()) {
837         if (m_owningLayer.reflectionLayer()->backing()) {
838             auto* reflectionLayer = m_owningLayer.reflectionLayer()->backing()->graphicsLayer();
839             m_graphicsLayer->setReplicatedByLayer(reflectionLayer);
840         }
841     } else
842         m_graphicsLayer->setReplicatedByLayer(nullptr);
843
844     PaintedContentsInfo contentsInfo(*this);
845
846     // Requires layout.
847     if (!m_owningLayer.isRenderViewLayer()) {
848         bool didUpdateContentsRect = false;
849         updateDirectlyCompositedBoxDecorations(contentsInfo, didUpdateContentsRect);
850     } else
851         updateRootLayerConfiguration();
852
853     // Requires layout.
854     if (contentsInfo.isDirectlyCompositedImage())
855         updateImageContents(contentsInfo);
856
857     if (is<RenderEmbeddedObject>(renderer()) && downcast<RenderEmbeddedObject>(renderer()).allowsAcceleratedCompositing()) {
858         auto* pluginViewBase = downcast<PluginViewBase>(downcast<RenderWidget>(renderer()).widget());
859 #if PLATFORM(IOS_FAMILY)
860         if (pluginViewBase && !m_graphicsLayer->contentsLayerForMedia()) {
861             pluginViewBase->detachPluginLayer();
862             pluginViewBase->attachPluginLayer();
863         }
864 #else
865         if (!pluginViewBase->shouldNotAddLayer())
866             m_graphicsLayer->setContentsToPlatformLayer(pluginViewBase->platformLayer(), GraphicsLayer::ContentsLayerPurpose::Plugin);
867 #endif
868     }
869 #if ENABLE(VIDEO)
870     else if (is<RenderVideo>(renderer()) && downcast<RenderVideo>(renderer()).shouldDisplayVideo()) {
871         auto* mediaElement = downcast<HTMLMediaElement>(renderer().element());
872         m_graphicsLayer->setContentsToPlatformLayer(mediaElement->platformLayer(), GraphicsLayer::ContentsLayerPurpose::Media);
873         // Requires layout.
874         resetContentsRect();
875     }
876 #endif
877 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
878     else if (renderer().isCanvas() && canvasCompositingStrategy(renderer()) == CanvasAsLayerContents) {
879         const HTMLCanvasElement* canvas = downcast<HTMLCanvasElement>(renderer().element());
880         if (auto* context = canvas->renderingContext())
881             m_graphicsLayer->setContentsToPlatformLayer(context->platformLayer(), GraphicsLayer::ContentsLayerPurpose::Canvas);
882
883         layerConfigChanged = true;
884     }
885 #endif
886     if (is<RenderWidget>(renderer()) && compositor.parentFrameContentLayers(downcast<RenderWidget>(renderer()))) {
887         m_owningLayer.setNeedsCompositingGeometryUpdate();
888         layerConfigChanged = true;
889     }
890
891     if (is<RenderImage>(renderer()) && downcast<RenderImage>(renderer()).isEditableImage()) {
892         auto element = renderer().element();
893         if (is<HTMLImageElement>(element)) {
894             m_graphicsLayer->setContentsToEmbeddedView(GraphicsLayer::ContentsLayerEmbeddedViewType::EditableImage, downcast<HTMLImageElement>(element)->editableImageViewID());
895             layerConfigChanged = true;
896         }
897     }
898
899     if (layerConfigChanged)
900         updatePaintingPhases();
901
902     return layerConfigChanged;
903 }
904
905 static LayoutRect clipBox(RenderBox& renderer)
906 {
907     LayoutRect result = LayoutRect::infiniteRect();
908     if (renderer.hasOverflowClip())
909         result = renderer.overflowClipRect(LayoutPoint(), 0); // FIXME: Incorrect for CSS regions.
910
911     if (renderer.hasClip())
912         result.intersect(renderer.clipRect(LayoutPoint(), 0)); // FIXME: Incorrect for CSS regions.
913
914     return result;
915 }
916
917 static bool subpixelOffsetFromRendererChanged(const LayoutSize& oldSubpixelOffsetFromRenderer, const LayoutSize& newSubpixelOffsetFromRenderer, float deviceScaleFactor)
918 {
919     FloatSize previous = snapSizeToDevicePixel(oldSubpixelOffsetFromRenderer, LayoutPoint(), deviceScaleFactor);
920     FloatSize current = snapSizeToDevicePixel(newSubpixelOffsetFromRenderer, LayoutPoint(), deviceScaleFactor);
921     return previous != current;
922 }
923     
924 static FloatSize subpixelForLayerPainting(const LayoutPoint& point, float pixelSnappingFactor)
925 {
926     LayoutUnit x = point.x();
927     LayoutUnit y = point.y();
928     x = x >= 0 ? floorToDevicePixel(x, pixelSnappingFactor) : ceilToDevicePixel(x, pixelSnappingFactor);
929     y = y >= 0 ? floorToDevicePixel(y, pixelSnappingFactor) : ceilToDevicePixel(y, pixelSnappingFactor);
930     return point - LayoutPoint(x, y);
931 }
932
933 struct OffsetFromRenderer {
934     // 1.2px - > { m_devicePixelOffset = 1px m_subpixelOffset = 0.2px }
935     LayoutSize m_devicePixelOffset;
936     LayoutSize m_subpixelOffset;
937 };
938
939 static OffsetFromRenderer computeOffsetFromRenderer(const LayoutSize& offset, float deviceScaleFactor)
940 {
941     OffsetFromRenderer offsetFromRenderer;
942     offsetFromRenderer.m_subpixelOffset = LayoutSize(subpixelForLayerPainting(toLayoutPoint(offset), deviceScaleFactor));
943     offsetFromRenderer.m_devicePixelOffset = offset - offsetFromRenderer.m_subpixelOffset;
944     return offsetFromRenderer;
945 }
946     
947 struct SnappedRectInfo {
948     LayoutRect m_snappedRect;
949     LayoutSize m_snapDelta;
950 };
951     
952 static SnappedRectInfo snappedGraphicsLayer(const LayoutSize& offset, const LayoutSize& size, float deviceScaleFactor)
953 {
954     SnappedRectInfo snappedGraphicsLayer;
955     LayoutRect graphicsLayerRect = LayoutRect(toLayoutPoint(offset), size);
956     snappedGraphicsLayer.m_snappedRect = LayoutRect(snapRectToDevicePixels(graphicsLayerRect, deviceScaleFactor));
957     snappedGraphicsLayer.m_snapDelta = snappedGraphicsLayer.m_snappedRect.location() - toLayoutPoint(offset);
958     return snappedGraphicsLayer;
959 }
960
961 static LayoutSize computeOffsetFromAncestorGraphicsLayer(const RenderLayer* compositedAncestor, const LayoutPoint& location, float deviceScaleFactor)
962 {
963     if (!compositedAncestor)
964         return toLayoutSize(location);
965
966     // FIXME: This is a workaround until after webkit.org/162634 gets fixed. ancestorSubpixelOffsetFromRenderer
967     // could be stale when a dynamic composited state change triggers a pre-order updateGeometry() traversal.
968     LayoutSize ancestorSubpixelOffsetFromRenderer = compositedAncestor->backing()->subpixelOffsetFromRenderer();
969     LayoutRect ancestorCompositedBounds = compositedAncestor->backing()->compositedBounds();
970     LayoutSize floored = toLayoutSize(LayoutPoint(floorPointToDevicePixels(ancestorCompositedBounds.location() - ancestorSubpixelOffsetFromRenderer, deviceScaleFactor)));
971     LayoutSize ancestorRendererOffsetFromAncestorGraphicsLayer = -(floored + ancestorSubpixelOffsetFromRenderer);
972     return ancestorRendererOffsetFromAncestorGraphicsLayer + toLayoutSize(location);
973 }
974
975 class ComputedOffsets {
976 public:
977     ComputedOffsets(const RenderLayer& renderLayer, const LayoutRect& localRect, const LayoutRect& parentGraphicsLayerRect, const LayoutRect& primaryGraphicsLayerRect)
978         : m_renderLayer(renderLayer)
979         , m_location(localRect.location())
980         , m_parentGraphicsLayerOffset(toLayoutSize(parentGraphicsLayerRect.location()))
981         , m_primaryGraphicsLayerOffset(toLayoutSize(primaryGraphicsLayerRect.location()))
982         , m_deviceScaleFactor(renderLayer.renderer().document().deviceScaleFactor())
983     {
984     }
985
986     LayoutSize fromParentGraphicsLayer()
987     {
988         if (!m_fromParentGraphicsLayer)
989             m_fromParentGraphicsLayer = fromAncestorGraphicsLayer() - m_parentGraphicsLayerOffset;
990         return m_fromParentGraphicsLayer.value();
991     }
992     
993     LayoutSize fromPrimaryGraphicsLayer()
994     {
995         if (!m_fromPrimaryGraphicsLayer)
996             m_fromPrimaryGraphicsLayer = fromAncestorGraphicsLayer() - m_parentGraphicsLayerOffset - m_primaryGraphicsLayerOffset;
997         return m_fromPrimaryGraphicsLayer.value();
998     }
999     
1000 private:
1001     LayoutSize fromAncestorGraphicsLayer()
1002     {
1003         if (!m_fromAncestorGraphicsLayer) {
1004             auto* compositedAncestor = m_renderLayer.ancestorCompositingLayer();
1005             LayoutPoint localPointInAncestorRenderLayerCoords = m_renderLayer.convertToLayerCoords(compositedAncestor, m_location, RenderLayer::AdjustForColumns);
1006             m_fromAncestorGraphicsLayer = computeOffsetFromAncestorGraphicsLayer(compositedAncestor, localPointInAncestorRenderLayerCoords, m_deviceScaleFactor);
1007         }
1008         return m_fromAncestorGraphicsLayer.value();
1009     }
1010
1011     Optional<LayoutSize> m_fromAncestorGraphicsLayer;
1012     Optional<LayoutSize> m_fromParentGraphicsLayer;
1013     Optional<LayoutSize> m_fromPrimaryGraphicsLayer;
1014     
1015     const RenderLayer& m_renderLayer;
1016     // Location is relative to the renderer.
1017     const LayoutPoint m_location;
1018     const LayoutSize m_parentGraphicsLayerOffset;
1019     const LayoutSize m_primaryGraphicsLayerOffset;
1020     float m_deviceScaleFactor;
1021 };
1022
1023 LayoutRect RenderLayerBacking::computePrimaryGraphicsLayerRect(const LayoutRect& parentGraphicsLayerRect) const
1024 {
1025     ComputedOffsets compositedBoundsOffset(m_owningLayer, compositedBounds(), parentGraphicsLayerRect, { });
1026     return LayoutRect(encloseRectToDevicePixels(LayoutRect(toLayoutPoint(compositedBoundsOffset.fromParentGraphicsLayer()), compositedBounds().size()),
1027         deviceScaleFactor()));
1028 }
1029
1030 // FIXME: See if we need this now that updateGeometry() is always called in post-order traversal.
1031 LayoutRect RenderLayerBacking::computeParentGraphicsLayerRect(const RenderLayer* compositedAncestor) const
1032 {
1033     if (!compositedAncestor || !compositedAncestor->backing())
1034         return renderer().view().documentRect();
1035
1036     auto* ancestorBackingLayer = compositedAncestor->backing();
1037     LayoutRect parentGraphicsLayerRect;
1038     if (m_owningLayer.isInsideFragmentedFlow()) {
1039         // FIXME: flows/columns need work.
1040         LayoutRect ancestorCompositedBounds = ancestorBackingLayer->compositedBounds();
1041         ancestorCompositedBounds.setLocation(LayoutPoint());
1042         parentGraphicsLayerRect = ancestorCompositedBounds;
1043     }
1044
1045     if (ancestorBackingLayer->hasClippingLayer()) {
1046         // If the compositing ancestor has a layer to clip children, we parent in that, and therefore position relative to it.
1047         LayoutRect clippingBox = clipBox(downcast<RenderBox>(compositedAncestor->renderer()));
1048         LayoutSize clippingBoxOffset = computeOffsetFromAncestorGraphicsLayer(compositedAncestor, clippingBox.location(), deviceScaleFactor());
1049         parentGraphicsLayerRect = snappedGraphicsLayer(clippingBoxOffset, clippingBox.size(), deviceScaleFactor()).m_snappedRect;
1050     }
1051
1052     if (compositedAncestor->hasCompositedScrollableOverflow()) {
1053         LayoutRect ancestorCompositedBounds = ancestorBackingLayer->compositedBounds();
1054         auto& renderBox = downcast<RenderBox>(compositedAncestor->renderer());
1055         LayoutRect paddingBoxIncludingScrollbar = renderBox.paddingBoxRectIncludingScrollbar();
1056         ScrollOffset scrollOffset = compositedAncestor->scrollOffset();
1057         parentGraphicsLayerRect = LayoutRect((paddingBoxIncludingScrollbar.location() - toLayoutSize(ancestorCompositedBounds.location()) - toLayoutSize(scrollOffset)), paddingBoxIncludingScrollbar.size());
1058     }
1059
1060     return parentGraphicsLayerRect;
1061 }
1062
1063 void RenderLayerBacking::updateGeometry()
1064 {
1065     ASSERT(!m_owningLayer.normalFlowListDirty());
1066     ASSERT(!m_owningLayer.zOrderListsDirty());
1067     ASSERT(!m_owningLayer.descendantDependentFlagsAreDirty());
1068     ASSERT(!renderer().view().needsLayout());
1069
1070     const RenderStyle& style = renderer().style();
1071
1072     bool isRunningAcceleratedTransformAnimation = false;
1073     if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled()) {
1074         if (auto* timeline = renderer().documentTimeline())
1075             isRunningAcceleratedTransformAnimation = timeline->isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyTransform);
1076     } else
1077         isRunningAcceleratedTransformAnimation = renderer().animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyTransform);
1078
1079     updateTransform(style);
1080     updateOpacity(style);
1081     updateFilters(style);
1082 #if ENABLE(FILTERS_LEVEL_2)
1083     updateBackdropFilters(style);
1084 #endif
1085 #if ENABLE(CSS_COMPOSITING)
1086     updateBlendMode(style);
1087 #endif
1088
1089     auto* compositedAncestor = m_owningLayer.ancestorCompositingLayer();
1090     LayoutRect parentGraphicsLayerRect = computeParentGraphicsLayerRect(compositedAncestor);
1091
1092     if (m_ancestorClippingStack) {
1093         // All clipRects in the stack are computed relative to m_owningLayer, so convert them back to compositedAncestor.
1094         auto offsetFromCompositedAncestor = toLayoutSize(m_owningLayer.convertToLayerCoords(compositedAncestor, { }, RenderLayer::AdjustForColumns));
1095         LayoutRect lastClipLayerRect = parentGraphicsLayerRect;
1096
1097         for (auto& entry : m_ancestorClippingStack->stack()) {
1098             auto clipRect = entry.clipData.clipRect;
1099             LayoutSize clippingOffset = computeOffsetFromAncestorGraphicsLayer(compositedAncestor, clipRect.location() + offsetFromCompositedAncestor, deviceScaleFactor());
1100             LayoutRect snappedClippingLayerRect = snappedGraphicsLayer(clippingOffset, clipRect.size(), deviceScaleFactor()).m_snappedRect;
1101
1102             entry.clippingLayer->setPosition(toLayoutPoint(snappedClippingLayerRect.location() - lastClipLayerRect.location()));
1103             lastClipLayerRect = snappedClippingLayerRect;
1104
1105             entry.clippingLayer->setSize(snappedClippingLayerRect.size());
1106
1107             if (entry.clipData.isOverflowScroll) {
1108                 ScrollOffset scrollOffset = entry.clipData.clippingLayer->scrollOffset();
1109
1110                 entry.clippingLayer->setBoundsOrigin(scrollOffset);
1111                 lastClipLayerRect.moveBy(-scrollOffset);
1112             } else
1113                 entry.clippingLayer->setBoundsOrigin({ });
1114         }
1115
1116         parentGraphicsLayerRect = lastClipLayerRect;
1117     }
1118
1119     LayoutRect primaryGraphicsLayerRect = computePrimaryGraphicsLayerRect(parentGraphicsLayerRect);
1120
1121     ComputedOffsets compositedBoundsOffset(m_owningLayer, compositedBounds(), parentGraphicsLayerRect, primaryGraphicsLayerRect);
1122     ComputedOffsets rendererOffset(m_owningLayer, { }, parentGraphicsLayerRect, primaryGraphicsLayerRect);
1123
1124     m_compositedBoundsOffsetFromGraphicsLayer = compositedBoundsOffset.fromPrimaryGraphicsLayer();
1125
1126     auto primaryLayerPosition = primaryGraphicsLayerRect.location();
1127
1128     // FIXME: reflections should force transform-style to be flat in the style: https://bugs.webkit.org/show_bug.cgi?id=106959
1129     bool preserves3D = style.transformStyle3D() == TransformStyle3D::Preserve3D && !renderer().hasReflection();
1130     if (m_contentsContainmentLayer) {
1131         m_contentsContainmentLayer->setPreserves3D(preserves3D);
1132         m_contentsContainmentLayer->setPosition(primaryLayerPosition);
1133         primaryLayerPosition = { };
1134         // Use the same size as m_graphicsLayer so transforms behave correctly.
1135         m_contentsContainmentLayer->setSize(primaryGraphicsLayerRect.size());
1136     }
1137
1138     auto computeAnimationExtent = [&] () -> Optional<FloatRect> {
1139         LayoutRect animatedBounds;
1140         if (isRunningAcceleratedTransformAnimation && m_owningLayer.getOverlapBoundsIncludingChildrenAccountingForTransformAnimations(animatedBounds, RenderLayer::IncludeCompositedDescendants))
1141             return FloatRect(animatedBounds);
1142         return { };
1143     };
1144     m_graphicsLayer->setAnimationExtent(computeAnimationExtent());
1145     m_graphicsLayer->setPreserves3D(preserves3D);
1146     m_graphicsLayer->setBackfaceVisibility(style.backfaceVisibility() == BackfaceVisibility::Visible);
1147
1148     m_graphicsLayer->setPosition(primaryLayerPosition);
1149     m_graphicsLayer->setSize(primaryGraphicsLayerRect.size());
1150
1151     // Compute renderer offset from primary graphics layer. Note that primaryGraphicsLayerRect is in parentGraphicsLayer's coordinate system which is not necessarily
1152     // the same as the ancestor graphics layer.
1153     OffsetFromRenderer primaryGraphicsLayerOffsetFromRenderer;
1154     LayoutSize oldSubpixelOffsetFromRenderer = m_subpixelOffsetFromRenderer;
1155     primaryGraphicsLayerOffsetFromRenderer = computeOffsetFromRenderer(-rendererOffset.fromPrimaryGraphicsLayer(), deviceScaleFactor());
1156     m_subpixelOffsetFromRenderer = primaryGraphicsLayerOffsetFromRenderer.m_subpixelOffset;
1157     m_hasSubpixelRounding = !m_subpixelOffsetFromRenderer.isZero() || compositedBounds().size() != primaryGraphicsLayerRect.size();
1158
1159     if (primaryGraphicsLayerOffsetFromRenderer.m_devicePixelOffset != m_graphicsLayer->offsetFromRenderer()) {
1160         m_graphicsLayer->setOffsetFromRenderer(primaryGraphicsLayerOffsetFromRenderer.m_devicePixelOffset);
1161         positionOverflowControlsLayers();
1162     }
1163
1164     // If we have a layer that clips children, position it.
1165     LayoutRect clippingBox;
1166     if (auto* clipLayer = clippingLayer()) {
1167         // clipLayer is the m_childContainmentLayer.
1168         clippingBox = clipBox(downcast<RenderBox>(renderer()));
1169         // Clipping layer is parented in the primary graphics layer.
1170         LayoutSize clipBoxOffsetFromGraphicsLayer = toLayoutSize(clippingBox.location()) + rendererOffset.fromPrimaryGraphicsLayer();
1171         SnappedRectInfo snappedClippingGraphicsLayer = snappedGraphicsLayer(clipBoxOffsetFromGraphicsLayer, clippingBox.size(), deviceScaleFactor());
1172         clipLayer->setPosition(snappedClippingGraphicsLayer.m_snappedRect.location());
1173         clipLayer->setSize(snappedClippingGraphicsLayer.m_snappedRect.size());
1174         clipLayer->setOffsetFromRenderer(toLayoutSize(clippingBox.location() - snappedClippingGraphicsLayer.m_snapDelta));
1175
1176         if ((renderer().style().clipPath() || renderer().style().hasBorderRadius()) && !m_childClippingMaskLayer) {
1177             LayoutRect boxRect(LayoutPoint(), downcast<RenderBox>(renderer()).size());
1178             FloatRoundedRect contentsClippingRect = renderer().style().getRoundedInnerBorderFor(boxRect).pixelSnappedRoundedRectForPainting(deviceScaleFactor());
1179             contentsClippingRect.move(LayoutSize(-clipLayer->offsetFromRenderer()));
1180             clipLayer->setMasksToBoundsRect(contentsClippingRect);
1181         }
1182
1183         if (m_childClippingMaskLayer && !m_scrollContainerLayer) {
1184             m_childClippingMaskLayer->setSize(clipLayer->size());
1185             m_childClippingMaskLayer->setPosition(FloatPoint());
1186             m_childClippingMaskLayer->setOffsetFromRenderer(clipLayer->offsetFromRenderer());
1187         }
1188     }
1189     
1190     if (m_maskLayer)
1191         updateMaskingLayerGeometry();
1192     
1193     if (renderer().hasTransformRelatedProperty()) {
1194         // Update properties that depend on layer dimensions.
1195         FloatPoint3D transformOrigin = computeTransformOriginForPainting(downcast<RenderBox>(renderer()).borderBoxRect());
1196         FloatPoint layerOffset = roundPointToDevicePixels(toLayoutPoint(rendererOffset.fromParentGraphicsLayer()), deviceScaleFactor());
1197         // Compute the anchor point, which is in the center of the renderer box unless transform-origin is set.
1198         FloatPoint3D anchor(
1199             primaryGraphicsLayerRect.width() ? ((layerOffset.x() - primaryGraphicsLayerRect.x()) + transformOrigin.x()) / primaryGraphicsLayerRect.width() : 0.5,
1200             primaryGraphicsLayerRect.height() ? ((layerOffset.y() - primaryGraphicsLayerRect.y())+ transformOrigin.y()) / primaryGraphicsLayerRect.height() : 0.5,
1201             transformOrigin.z());
1202
1203         if (m_contentsContainmentLayer)
1204             m_contentsContainmentLayer->setAnchorPoint(anchor);
1205         else
1206             m_graphicsLayer->setAnchorPoint(anchor);
1207
1208         auto* clipLayer = clippingLayer();
1209         if (style.hasPerspective()) {
1210             TransformationMatrix t = owningLayer().perspectiveTransform();
1211             
1212             if (clipLayer) {
1213                 clipLayer->setChildrenTransform(t);
1214                 m_graphicsLayer->setChildrenTransform(TransformationMatrix());
1215             }
1216             else
1217                 m_graphicsLayer->setChildrenTransform(t);
1218         } else {
1219             if (clipLayer)
1220                 clipLayer->setChildrenTransform(TransformationMatrix());
1221             else
1222                 m_graphicsLayer->setChildrenTransform(TransformationMatrix());
1223         }
1224     } else {
1225         m_graphicsLayer->setAnchorPoint(FloatPoint3D(0.5, 0.5, 0));
1226         if (m_contentsContainmentLayer)
1227             m_contentsContainmentLayer->setAnchorPoint(FloatPoint3D(0.5, 0.5, 0));
1228     }
1229
1230     if (m_owningLayer.reflectionLayer() && m_owningLayer.reflectionLayer()->isComposited()) {
1231         auto* reflectionBacking = m_owningLayer.reflectionLayer()->backing();
1232         reflectionBacking->updateGeometry();
1233         
1234         // The reflection layer has the bounds of m_owningLayer.reflectionLayer(),
1235         // but the reflected layer is the bounds of this layer, so we need to position it appropriately.
1236         FloatRect layerBounds = this->compositedBounds();
1237         FloatRect reflectionLayerBounds = reflectionBacking->compositedBounds();
1238         reflectionBacking->graphicsLayer()->setReplicatedLayerPosition(FloatPoint(layerBounds.location() - reflectionLayerBounds.location()));
1239     }
1240
1241     if (m_scrollContainerLayer) {
1242         ASSERT(m_scrolledContentsLayer);
1243         auto& renderBox = downcast<RenderBox>(renderer());
1244         LayoutRect paddingBox = renderBox.paddingBoxRect();
1245         LayoutRect parentLayerBounds = clippingLayer() ? clippingBox : compositedBounds();
1246
1247         // FIXME: need to do some pixel snapping here.
1248         m_scrollContainerLayer->setPosition(FloatPoint(paddingBox.location() - parentLayerBounds.location()));
1249         m_scrollContainerLayer->setSize(roundedIntSize(LayoutSize(renderBox.paddingBoxWidth(), renderBox.paddingBoxHeight())));
1250
1251         ScrollOffset scrollOffset = m_owningLayer.scrollOffset();
1252         updateScrollOffset(scrollOffset);
1253
1254         FloatSize oldScrollingLayerOffset = m_scrollContainerLayer->offsetFromRenderer();
1255         m_scrollContainerLayer->setOffsetFromRenderer(toFloatSize(paddingBox.location()));
1256
1257         if (m_childClippingMaskLayer) {
1258             m_childClippingMaskLayer->setPosition(m_scrollContainerLayer->position());
1259             m_childClippingMaskLayer->setSize(m_scrollContainerLayer->size());
1260             m_childClippingMaskLayer->setOffsetFromRenderer(toFloatSize(paddingBox.location()));
1261         }
1262
1263         bool paddingBoxOffsetChanged = oldScrollingLayerOffset != m_scrollContainerLayer->offsetFromRenderer();
1264
1265         IntSize scrollSize(m_owningLayer.scrollWidth(), m_owningLayer.scrollHeight());
1266         if (scrollSize != m_scrolledContentsLayer->size() || paddingBoxOffsetChanged)
1267             m_scrolledContentsLayer->setNeedsDisplay();
1268
1269         m_scrolledContentsLayer->setSize(scrollSize);
1270         m_scrolledContentsLayer->setScrollOffset(scrollOffset, GraphicsLayer::DontSetNeedsDisplay);
1271         m_scrolledContentsLayer->setOffsetFromRenderer(toLayoutSize(paddingBox.location()), GraphicsLayer::DontSetNeedsDisplay);
1272         
1273         adjustTiledBackingCoverage();
1274     }
1275
1276     if (m_foregroundLayer) {
1277         FloatSize foregroundSize;
1278         FloatSize foregroundOffset;
1279         GraphicsLayer::ShouldSetNeedsDisplay needsDisplayOnOffsetChange = GraphicsLayer::SetNeedsDisplay;
1280         if (m_scrolledContentsLayer) {
1281             foregroundSize = m_scrolledContentsLayer->size();
1282             foregroundOffset = m_scrolledContentsLayer->offsetFromRenderer() - toLayoutSize(m_scrolledContentsLayer->scrollOffset());
1283             needsDisplayOnOffsetChange = GraphicsLayer::DontSetNeedsDisplay;
1284         } else if (hasClippingLayer()) {
1285             // If we have a clipping layer (which clips descendants), then the foreground layer is a child of it,
1286             // so that it gets correctly sorted with children. In that case, position relative to the clipping layer.
1287             foregroundSize = FloatSize(clippingBox.size());
1288             foregroundOffset = toFloatSize(clippingBox.location());
1289         } else {
1290             foregroundSize = primaryGraphicsLayerRect.size();
1291             foregroundOffset = m_graphicsLayer->offsetFromRenderer();
1292         }
1293
1294         m_foregroundLayer->setPosition({ });
1295         m_foregroundLayer->setSize(foregroundSize);
1296         m_foregroundLayer->setOffsetFromRenderer(foregroundOffset, needsDisplayOnOffsetChange);
1297     }
1298
1299     if (m_backgroundLayer) {
1300         FloatPoint backgroundPosition;
1301         FloatSize backgroundSize = primaryGraphicsLayerRect.size();
1302         if (backgroundLayerPaintsFixedRootBackground()) {
1303             const FrameView& frameView = renderer().view().frameView();
1304             backgroundPosition = frameView.scrollPositionForFixedPosition();
1305             backgroundSize = frameView.layoutSize();
1306         } else {
1307             auto boundingBox = renderer().objectBoundingBox();
1308             backgroundPosition = boundingBox.location();
1309             backgroundSize = boundingBox.size();
1310         }
1311         m_backgroundLayer->setPosition(backgroundPosition);
1312         m_backgroundLayer->setSize(backgroundSize);
1313         m_backgroundLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
1314     }
1315
1316     // If this layer was created just for clipping or to apply perspective, it doesn't need its own backing store.
1317     LayoutRect ancestorCompositedBounds = compositedAncestor ? compositedAncestor->backing()->compositedBounds() : LayoutRect();
1318     setRequiresOwnBackingStore(compositor().requiresOwnBackingStore(m_owningLayer, compositedAncestor,
1319         LayoutRect(toLayoutPoint(compositedBoundsOffset.fromParentGraphicsLayer()), compositedBounds().size()), ancestorCompositedBounds));
1320 #if ENABLE(FILTERS_LEVEL_2)
1321     updateBackdropFiltersGeometry();
1322 #endif
1323     updateAfterWidgetResize();
1324
1325     if (subpixelOffsetFromRendererChanged(oldSubpixelOffsetFromRenderer, m_subpixelOffsetFromRenderer, deviceScaleFactor()) && canIssueSetNeedsDisplay())
1326         setContentsNeedDisplay();
1327 }
1328
1329 void RenderLayerBacking::setLocationOfScrolledContents(ScrollOffset scrollOffset, ScrollingLayerPositionAction setOrSync)
1330 {
1331     if (setOrSync == ScrollingLayerPositionAction::Sync)
1332         m_scrollContainerLayer->syncBoundsOrigin(scrollOffset);
1333     else
1334         m_scrollContainerLayer->setBoundsOrigin(scrollOffset);
1335 }
1336
1337 void RenderLayerBacking::updateScrollOffset(ScrollOffset scrollOffset)
1338 {
1339     if (m_owningLayer.currentScrollType() == ScrollType::User) {
1340         // If scrolling is happening externally, we don't want to touch the layer bounds origin here because that will cause jitter.
1341         setLocationOfScrolledContents(scrollOffset, ScrollingLayerPositionAction::Sync);
1342         m_owningLayer.setRequiresScrollPositionReconciliation(true);
1343     } else {
1344         // Note that we implement the contents offset via the bounds origin on this layer, rather than a position on the sublayer.
1345         setLocationOfScrolledContents(scrollOffset, ScrollingLayerPositionAction::Set);
1346         m_owningLayer.setRequiresScrollPositionReconciliation(false);
1347     }
1348
1349     ASSERT(m_scrolledContentsLayer->position().isZero());
1350 }
1351
1352 void RenderLayerBacking::updateAfterDescendants()
1353 {
1354     // FIXME: this potentially duplicates work we did in updateConfiguration().
1355     PaintedContentsInfo contentsInfo(*this);
1356     contentsInfo.setWantsSubpixelAntialiasedTextState(GraphicsLayer::supportsSubpixelAntialiasedLayerText() && FontCascade::isSubpixelAntialiasingAvailable());
1357
1358     if (!m_owningLayer.isRenderViewLayer()) {
1359         bool didUpdateContentsRect = false;
1360         updateDirectlyCompositedBoxDecorations(contentsInfo, didUpdateContentsRect);
1361         if (!didUpdateContentsRect && m_graphicsLayer->usesContentsLayer())
1362             resetContentsRect();
1363     }
1364
1365     updateDrawsContent(contentsInfo);
1366
1367     if (!m_isMainFrameRenderViewLayer && !m_isFrameLayerWithTiledBacking && !m_requiresBackgroundLayer) {
1368         // For non-root layers, background is always painted by the primary graphics layer.
1369         ASSERT(!m_backgroundLayer);
1370         m_graphicsLayer->setContentsOpaque(!m_hasSubpixelRounding && m_owningLayer.backgroundIsKnownToBeOpaqueInRect(compositedBounds()));
1371     }
1372
1373     m_graphicsLayer->setContentsVisible(m_owningLayer.hasVisibleContent() || hasVisibleNonCompositedDescendants());
1374     if (m_scrollContainerLayer) {
1375         m_scrollContainerLayer->setContentsVisible(renderer().style().visibility() == Visibility::Visible);
1376         m_scrollContainerLayer->setUserInteractionEnabled(renderer().style().pointerEvents() != PointerEvents::None);
1377     }
1378 }
1379
1380 // FIXME: Avoid repaints when clip path changes.
1381 void RenderLayerBacking::updateMaskingLayerGeometry()
1382 {
1383     m_maskLayer->setSize(m_graphicsLayer->size());
1384     m_maskLayer->setPosition(FloatPoint());
1385     m_maskLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
1386     
1387     if (!m_maskLayer->drawsContent()) {
1388         if (renderer().hasClipPath()) {
1389             ASSERT(renderer().style().clipPath()->type() != ClipPathOperation::Reference);
1390
1391             WindRule windRule;
1392             // FIXME: Use correct reference box for inlines: https://bugs.webkit.org/show_bug.cgi?id=129047
1393             LayoutRect boundingBox = m_owningLayer.boundingBox(&m_owningLayer);
1394             LayoutRect referenceBoxForClippedInline = LayoutRect(snapRectToDevicePixels(boundingBox, deviceScaleFactor()));
1395             LayoutSize offset = LayoutSize(snapSizeToDevicePixel(-m_subpixelOffsetFromRenderer, LayoutPoint(), deviceScaleFactor()));
1396             Path clipPath = m_owningLayer.computeClipPath(offset, referenceBoxForClippedInline, windRule);
1397
1398             FloatSize pathOffset = m_maskLayer->offsetFromRenderer();
1399             if (!pathOffset.isZero())
1400                 clipPath.translate(-pathOffset);
1401             
1402             m_maskLayer->setShapeLayerPath(clipPath);
1403             m_maskLayer->setShapeLayerWindRule(windRule);
1404         }
1405     }
1406 }
1407
1408 void RenderLayerBacking::updateDirectlyCompositedBoxDecorations(PaintedContentsInfo& contentsInfo, bool& didUpdateContentsRect)
1409 {
1410     if (!m_owningLayer.hasVisibleContent())
1411         return;
1412
1413     // The order of operations here matters, since the last valid type of contents needs
1414     // to also update the contentsRect.
1415     updateDirectlyCompositedBackgroundColor(contentsInfo, didUpdateContentsRect);
1416     updateDirectlyCompositedBackgroundImage(contentsInfo, didUpdateContentsRect);
1417 }
1418
1419 void RenderLayerBacking::updateInternalHierarchy()
1420 {
1421     // m_foregroundLayer has to be inserted in the correct order with child layers,
1422     // so it's not inserted here.
1423     GraphicsLayer* lastClippingLayer = nullptr;
1424     if (m_ancestorClippingStack) {
1425         auto& clippingStack = m_ancestorClippingStack->stack();
1426         for (unsigned i = 0; i < clippingStack.size() - 1; ++i) {
1427             auto& entry = clippingStack.at(i);
1428             Vector<Ref<GraphicsLayer>> children;
1429             children.append(*clippingStack.at(i + 1).clippingLayer);
1430             entry.clippingLayer->setChildren(WTFMove(children));
1431         }
1432         
1433         lastClippingLayer = clippingStack.last().clippingLayer.get();
1434         lastClippingLayer->removeAllChildren();
1435     }
1436     
1437     if (m_contentsContainmentLayer) {
1438         m_contentsContainmentLayer->removeAllChildren();
1439         if (lastClippingLayer)
1440             lastClippingLayer->addChild(*m_contentsContainmentLayer);
1441     }
1442     
1443     if (m_backgroundLayer)
1444         m_contentsContainmentLayer->addChild(*m_backgroundLayer);
1445
1446     if (m_contentsContainmentLayer)
1447         m_contentsContainmentLayer->addChild(*m_graphicsLayer);
1448     else if (lastClippingLayer)
1449         lastClippingLayer->addChild(*m_graphicsLayer);
1450
1451     if (m_childContainmentLayer)
1452         m_graphicsLayer->addChild(*m_childContainmentLayer);
1453
1454     if (m_scrollContainerLayer) {
1455         auto* superlayer = m_childContainmentLayer ? m_childContainmentLayer.get() : m_graphicsLayer.get();
1456         superlayer->addChild(*m_scrollContainerLayer);
1457     }
1458
1459     // The clip for child layers does not include space for overflow controls, so they exist as
1460     // siblings of the clipping layer if we have one. Normal children of this layer are set as
1461     // children of the clipping layer.
1462     if (m_layerForHorizontalScrollbar)
1463         m_graphicsLayer->addChild(*m_layerForHorizontalScrollbar);
1464
1465     if (m_layerForVerticalScrollbar)
1466         m_graphicsLayer->addChild(*m_layerForVerticalScrollbar);
1467
1468     if (m_layerForScrollCorner)
1469         m_graphicsLayer->addChild(*m_layerForScrollCorner);
1470 }
1471
1472 void RenderLayerBacking::resetContentsRect()
1473 {
1474     m_graphicsLayer->setContentsRect(snapRectToDevicePixels(contentsBox(), deviceScaleFactor()));
1475     
1476     if (is<RenderBox>(renderer())) {
1477         LayoutRect boxRect(LayoutPoint(), downcast<RenderBox>(renderer()).size());
1478         boxRect.move(contentOffsetInCompositingLayer());
1479         FloatRoundedRect contentsClippingRect = renderer().style().getRoundedInnerBorderFor(boxRect).pixelSnappedRoundedRectForPainting(deviceScaleFactor());
1480         m_graphicsLayer->setContentsClippingRect(contentsClippingRect);
1481     }
1482
1483     m_graphicsLayer->setContentsTileSize(IntSize());
1484     m_graphicsLayer->setContentsTilePhase(IntSize());
1485 }
1486
1487 void RenderLayerBacking::updateDrawsContent()
1488 {
1489     PaintedContentsInfo contentsInfo(*this);
1490     contentsInfo.setWantsSubpixelAntialiasedTextState(GraphicsLayer::supportsSubpixelAntialiasedLayerText());
1491
1492     updateDrawsContent(contentsInfo);
1493 }
1494
1495 void RenderLayerBacking::updateDrawsContent(PaintedContentsInfo& contentsInfo)
1496 {
1497     if (m_scrollContainerLayer) {
1498         // We don't have to consider overflow controls, because we know that the scrollbars are drawn elsewhere.
1499         // m_graphicsLayer only needs backing store if the non-scrolling parts (background, outlines, borders, shadows etc) need to paint.
1500         // m_scrollContainerLayer never has backing store.
1501         // m_scrolledContentsLayer only needs backing store if the scrolled contents need to paint.
1502         bool hasNonScrollingPaintedContent = m_owningLayer.hasVisibleContent() && m_owningLayer.hasVisibleBoxDecorationsOrBackground();
1503         m_graphicsLayer->setDrawsContent(hasNonScrollingPaintedContent);
1504
1505         bool hasScrollingPaintedContent = hasBackingSharingLayers() || (m_owningLayer.hasVisibleContent() && (renderer().hasBackground() || contentsInfo.paintsContent()));
1506         m_scrolledContentsLayer->setDrawsContent(hasScrollingPaintedContent);
1507         return;
1508     }
1509
1510     bool hasPaintedContent = containsPaintedContent(contentsInfo);
1511
1512     m_paintsSubpixelAntialiasedText = renderer().settings().subpixelAntialiasedLayerTextEnabled() && contentsInfo.paintsSubpixelAntialiasedText();
1513
1514     // FIXME: we could refine this to only allocate backing for one of these layers if possible.
1515     m_graphicsLayer->setDrawsContent(hasPaintedContent);
1516     if (m_foregroundLayer) {
1517         m_foregroundLayer->setDrawsContent(hasPaintedContent);
1518         m_foregroundLayer->setSupportsSubpixelAntialiasedText(m_paintsSubpixelAntialiasedText);
1519         // The text content is painted into the foreground layer.
1520         // FIXME: this ignores SVG background images which may contain text.
1521         m_graphicsLayer->setSupportsSubpixelAntialiasedText(false);
1522     } else
1523         m_graphicsLayer->setSupportsSubpixelAntialiasedText(m_paintsSubpixelAntialiasedText);
1524
1525     if (m_backgroundLayer)
1526         m_backgroundLayer->setDrawsContent(m_backgroundLayerPaintsFixedRootBackground ? hasPaintedContent : contentsInfo.paintsBoxDecorations());
1527 }
1528
1529 void RenderLayerBacking::updateEventRegion()
1530 {
1531 #if PLATFORM(IOS_FAMILY)
1532     if (paintsIntoCompositedAncestor())
1533         return;
1534
1535     bool hasTouchActionElements = false;
1536 #if ENABLE(POINTER_EVENTS)
1537     hasTouchActionElements = renderer().document().mayHaveElementsWithNonAutoTouchAction();
1538 #endif
1539     if (m_owningLayer.isRenderViewLayer() && !hasTouchActionElements)
1540         return;
1541
1542     GraphicsContext nullContext(nullptr);
1543     RenderLayer::LayerPaintingInfo paintingInfo(&m_owningLayer, compositedBounds(), { }, LayoutSize());
1544
1545     EventRegion eventRegion;
1546     auto eventRegionContext = eventRegion.makeContext();
1547     paintingInfo.eventRegionContext = &eventRegionContext;
1548
1549     auto paintFlags = RenderLayer::paintLayerPaintingCompositingAllPhasesFlags() | RenderLayer::PaintLayerCollectingEventRegion;
1550     m_owningLayer.paintLayerContents(nullContext, paintingInfo, paintFlags);
1551
1552     for (auto& layer : m_backingSharingLayers)
1553         layer->paintLayerWithEffects(nullContext, paintingInfo, paintFlags);
1554
1555     GraphicsLayer& layerForEventRegion = m_scrolledContentsLayer ? *m_scrolledContentsLayer : *m_graphicsLayer;
1556
1557     auto layerOffset = toIntSize(layerForEventRegion.scrollOffset()) - roundedIntSize(layerForEventRegion.offsetFromRenderer());
1558     eventRegion.translate(layerOffset);
1559
1560     layerForEventRegion.setEventRegion(WTFMove(eventRegion));
1561 #endif
1562 }
1563
1564 bool RenderLayerBacking::updateAncestorClippingStack(Vector<CompositedClipData>&& clippingData)
1565 {
1566     if (!m_ancestorClippingStack && clippingData.isEmpty())
1567         return false;
1568
1569     auto* scrollingCoordinator = m_owningLayer.page().scrollingCoordinator();
1570
1571     if (m_ancestorClippingStack && clippingData.isEmpty()) {
1572         m_ancestorClippingStack->clear(scrollingCoordinator);
1573         m_ancestorClippingStack = nullptr;
1574         return true;
1575     }
1576     
1577     if (!m_ancestorClippingStack) {
1578         m_ancestorClippingStack = std::make_unique<LayerAncestorClippingStack>(WTFMove(clippingData));
1579         LOG_WITH_STREAM(Compositing, stream << "layer " << &m_owningLayer << " ancestorClippingStack " << *m_ancestorClippingStack);
1580         return true;
1581     }
1582     
1583     if (m_ancestorClippingStack->equalToClipData(clippingData)) {
1584         LOG_WITH_STREAM(Compositing, stream << "layer " << &m_owningLayer << " ancestorClippingStack " << *m_ancestorClippingStack);
1585         return false;
1586     }
1587     
1588     m_ancestorClippingStack->updateWithClipData(scrollingCoordinator, WTFMove(clippingData));
1589     LOG_WITH_STREAM(Compositing, stream << "layer " << &m_owningLayer << " ancestorClippingStack " << *m_ancestorClippingStack);
1590     return true;
1591 }
1592
1593 // Return true if the layer changed.
1594 bool RenderLayerBacking::updateAncestorClipping(bool needsAncestorClip, const RenderLayer* compositingAncestor)
1595 {
1596     bool layersChanged = false;
1597
1598     if (needsAncestorClip) {
1599         if (compositor().updateAncestorClippingStack(m_owningLayer, compositingAncestor)) {
1600             // Make any layers we don't have.
1601             if (m_ancestorClippingStack) {
1602                 for (auto& entry : m_ancestorClippingStack->stack()) {
1603                     if (!entry.clippingLayer) {
1604                         entry.clippingLayer = createGraphicsLayer(entry.clipData.isOverflowScroll ? "clip for scroller" : "ancestor clipping");
1605                         entry.clippingLayer->setMasksToBounds(true);
1606                         entry.clippingLayer->setPaintingPhase({ });
1607                     }
1608                 }
1609             }
1610
1611             layersChanged = true;
1612         }
1613     } else if (m_ancestorClippingStack) {
1614         for (auto& entry : m_ancestorClippingStack->stack())
1615             GraphicsLayer::unparentAndClear(entry.clippingLayer);
1616
1617         m_ancestorClippingStack = nullptr;
1618         layersChanged = true;
1619     }
1620     
1621     return layersChanged;
1622 }
1623
1624 // Return true if the layer changed.
1625 bool RenderLayerBacking::updateDescendantClippingLayer(bool needsDescendantClip)
1626 {
1627     bool layersChanged = false;
1628
1629     if (needsDescendantClip) {
1630         if (!m_childContainmentLayer && !m_isFrameLayerWithTiledBacking) {
1631             m_childContainmentLayer = createGraphicsLayer("child clipping");
1632             m_childContainmentLayer->setMasksToBounds(true);
1633             layersChanged = true;
1634         }
1635     } else if (hasClippingLayer()) {
1636         willDestroyLayer(m_childContainmentLayer.get());
1637         GraphicsLayer::unparentAndClear(m_childContainmentLayer);
1638         layersChanged = true;
1639     }
1640     
1641     return layersChanged;
1642 }
1643
1644 void RenderLayerBacking::setBackgroundLayerPaintsFixedRootBackground(bool backgroundLayerPaintsFixedRootBackground)
1645 {
1646     if (backgroundLayerPaintsFixedRootBackground == m_backgroundLayerPaintsFixedRootBackground)
1647         return;
1648
1649     m_backgroundLayerPaintsFixedRootBackground = backgroundLayerPaintsFixedRootBackground;
1650
1651     if (m_backgroundLayerPaintsFixedRootBackground) {
1652         ASSERT(m_isFrameLayerWithTiledBacking);
1653         renderer().view().frameView().removeSlowRepaintObject(*renderer().view().rendererForRootBackground());
1654     }
1655 }
1656
1657 void RenderLayerBacking::setRequiresBackgroundLayer(bool requiresBackgroundLayer)
1658 {
1659     if (requiresBackgroundLayer == m_requiresBackgroundLayer)
1660         return;
1661
1662     m_requiresBackgroundLayer = requiresBackgroundLayer;
1663     m_owningLayer.setNeedsCompositingConfigurationUpdate();
1664 }
1665
1666 bool RenderLayerBacking::requiresHorizontalScrollbarLayer() const
1667 {
1668     if (!m_owningLayer.hasOverlayScrollbars())
1669         return false;
1670     return m_owningLayer.horizontalScrollbar();
1671 }
1672
1673 bool RenderLayerBacking::requiresVerticalScrollbarLayer() const
1674 {
1675     if (!m_owningLayer.hasOverlayScrollbars())
1676         return false;
1677     return m_owningLayer.verticalScrollbar();
1678 }
1679
1680 bool RenderLayerBacking::requiresScrollCornerLayer() const
1681 {
1682     if (!m_owningLayer.hasOverlayScrollbars())
1683         return false;
1684     return !m_owningLayer.scrollCornerAndResizerRect().isEmpty();
1685 }
1686
1687 bool RenderLayerBacking::updateOverflowControlsLayers(bool needsHorizontalScrollbarLayer, bool needsVerticalScrollbarLayer, bool needsScrollCornerLayer)
1688 {
1689     bool horizontalScrollbarLayerChanged = false;
1690     if (needsHorizontalScrollbarLayer) {
1691         if (!m_layerForHorizontalScrollbar) {
1692             m_layerForHorizontalScrollbar = createGraphicsLayer("horizontal scrollbar");
1693             m_layerForHorizontalScrollbar->setCanDetachBackingStore(false);
1694             horizontalScrollbarLayerChanged = true;
1695         }
1696     } else if (m_layerForHorizontalScrollbar) {
1697         willDestroyLayer(m_layerForHorizontalScrollbar.get());
1698         GraphicsLayer::unparentAndClear(m_layerForHorizontalScrollbar);
1699         horizontalScrollbarLayerChanged = true;
1700     }
1701
1702     bool verticalScrollbarLayerChanged = false;
1703     if (needsVerticalScrollbarLayer) {
1704         if (!m_layerForVerticalScrollbar) {
1705             m_layerForVerticalScrollbar = createGraphicsLayer("vertical scrollbar");
1706             m_layerForVerticalScrollbar->setCanDetachBackingStore(false);
1707             verticalScrollbarLayerChanged = true;
1708         }
1709     } else if (m_layerForVerticalScrollbar) {
1710         willDestroyLayer(m_layerForVerticalScrollbar.get());
1711         GraphicsLayer::unparentAndClear(m_layerForVerticalScrollbar);
1712         verticalScrollbarLayerChanged = true;
1713     }
1714
1715     bool scrollCornerLayerChanged = false;
1716     if (needsScrollCornerLayer) {
1717         if (!m_layerForScrollCorner) {
1718             m_layerForScrollCorner = createGraphicsLayer("scroll corner");
1719             m_layerForScrollCorner->setCanDetachBackingStore(false);
1720             scrollCornerLayerChanged = true;
1721         }
1722     } else if (m_layerForScrollCorner) {
1723         willDestroyLayer(m_layerForScrollCorner.get());
1724         GraphicsLayer::unparentAndClear(m_layerForScrollCorner);
1725         scrollCornerLayerChanged = true;
1726     }
1727
1728     if (auto* scrollingCoordinator = m_owningLayer.page().scrollingCoordinator()) {
1729         if (horizontalScrollbarLayerChanged)
1730             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_owningLayer, HorizontalScrollbar);
1731         if (verticalScrollbarLayerChanged)
1732             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_owningLayer, VerticalScrollbar);
1733     }
1734
1735     return horizontalScrollbarLayerChanged || verticalScrollbarLayerChanged || scrollCornerLayerChanged;
1736 }
1737
1738 void RenderLayerBacking::positionOverflowControlsLayers()
1739 {
1740     if (!m_owningLayer.hasScrollbars())
1741         return;
1742
1743     const IntRect borderBox = snappedIntRect(renderBox()->borderBoxRect());
1744
1745     FloatSize offsetFromRenderer = m_graphicsLayer->offsetFromRenderer();
1746     if (auto* layer = layerForHorizontalScrollbar()) {
1747         IntRect hBarRect = m_owningLayer.rectForHorizontalScrollbar(borderBox);
1748         layer->setPosition(hBarRect.location() - offsetFromRenderer);
1749         layer->setSize(hBarRect.size());
1750         if (layer->usesContentsLayer()) {
1751             IntRect barRect = IntRect(IntPoint(), hBarRect.size());
1752             layer->setContentsRect(barRect);
1753             layer->setContentsClippingRect(FloatRoundedRect(barRect));
1754         }
1755         layer->setDrawsContent(m_owningLayer.horizontalScrollbar() && !layer->usesContentsLayer());
1756     }
1757     
1758     if (auto* layer = layerForVerticalScrollbar()) {
1759         IntRect vBarRect = m_owningLayer.rectForVerticalScrollbar(borderBox);
1760         layer->setPosition(vBarRect.location() - offsetFromRenderer);
1761         layer->setSize(vBarRect.size());
1762         if (layer->usesContentsLayer()) {
1763             IntRect barRect = IntRect(IntPoint(), vBarRect.size());
1764             layer->setContentsRect(barRect);
1765             layer->setContentsClippingRect(FloatRoundedRect(barRect));
1766         }
1767         layer->setDrawsContent(m_owningLayer.verticalScrollbar() && !layer->usesContentsLayer());
1768     }
1769
1770     if (auto* layer = layerForScrollCorner()) {
1771         const LayoutRect& scrollCornerAndResizer = m_owningLayer.scrollCornerAndResizerRect();
1772         layer->setPosition(scrollCornerAndResizer.location() - offsetFromRenderer);
1773         layer->setSize(scrollCornerAndResizer.size());
1774         layer->setDrawsContent(!scrollCornerAndResizer.isEmpty());
1775     }
1776 }
1777
1778 bool RenderLayerBacking::updateForegroundLayer(bool needsForegroundLayer)
1779 {
1780     bool layerChanged = false;
1781     if (needsForegroundLayer) {
1782         if (!m_foregroundLayer) {
1783             String layerName = m_owningLayer.name() + " (foreground)";
1784             m_foregroundLayer = createGraphicsLayer(layerName);
1785             m_foregroundLayer->setDrawsContent(true);
1786             layerChanged = true;
1787         }
1788     } else if (m_foregroundLayer) {
1789         willDestroyLayer(m_foregroundLayer.get());
1790         GraphicsLayer::unparentAndClear(m_foregroundLayer);
1791         layerChanged = true;
1792     }
1793
1794     return layerChanged;
1795 }
1796
1797 bool RenderLayerBacking::updateBackgroundLayer(bool needsBackgroundLayer)
1798 {
1799     bool layerChanged = false;
1800     if (needsBackgroundLayer) {
1801         if (!m_backgroundLayer) {
1802             String layerName = m_owningLayer.name() + " (background)";
1803             m_backgroundLayer = createGraphicsLayer(layerName);
1804             m_backgroundLayer->setDrawsContent(true);
1805             m_backgroundLayer->setAnchorPoint(FloatPoint3D());
1806             layerChanged = true;
1807         }
1808         
1809         if (!m_contentsContainmentLayer) {
1810             String layerName = m_owningLayer.name() + " (contents containment)";
1811             m_contentsContainmentLayer = createGraphicsLayer(layerName);
1812             m_contentsContainmentLayer->setAppliesPageScale(true);
1813             m_graphicsLayer->setAppliesPageScale(false);
1814             layerChanged = true;
1815         }
1816     } else {
1817         if (m_backgroundLayer) {
1818             willDestroyLayer(m_backgroundLayer.get());
1819             GraphicsLayer::unparentAndClear(m_backgroundLayer);
1820             layerChanged = true;
1821         }
1822         if (m_contentsContainmentLayer) {
1823             willDestroyLayer(m_contentsContainmentLayer.get());
1824             GraphicsLayer::unparentAndClear(m_contentsContainmentLayer);
1825             layerChanged = true;
1826             m_graphicsLayer->setAppliesPageScale(true);
1827         }
1828     }
1829
1830     return layerChanged;
1831 }
1832
1833 // Masking layer is used for masks or clip-path.
1834 bool RenderLayerBacking::updateMaskingLayer(bool hasMask, bool hasClipPath)
1835 {
1836     bool layerChanged = false;
1837     if (hasMask || hasClipPath) {
1838         OptionSet<GraphicsLayerPaintingPhase> maskPhases;
1839         if (hasMask)
1840             maskPhases = GraphicsLayerPaintingPhase::Mask;
1841         
1842         if (hasClipPath) {
1843             // If we have a mask, we need to paint the combined clip-path and mask into the mask layer.
1844             if (hasMask || renderer().style().clipPath()->type() == ClipPathOperation::Reference || !GraphicsLayer::supportsLayerType(GraphicsLayer::Type::Shape))
1845                 maskPhases.add(GraphicsLayerPaintingPhase::ClipPath);
1846         }
1847
1848         bool paintsContent = !maskPhases.isEmpty();
1849         GraphicsLayer::Type requiredLayerType = paintsContent ? GraphicsLayer::Type::Normal : GraphicsLayer::Type::Shape;
1850         if (m_maskLayer && m_maskLayer->type() != requiredLayerType) {
1851             m_graphicsLayer->setMaskLayer(nullptr);
1852             willDestroyLayer(m_maskLayer.get());
1853             GraphicsLayer::clear(m_maskLayer);
1854         }
1855
1856         if (!m_maskLayer) {
1857             m_maskLayer = createGraphicsLayer("mask", requiredLayerType);
1858             m_maskLayer->setDrawsContent(paintsContent);
1859             m_maskLayer->setPaintingPhase(maskPhases);
1860             layerChanged = true;
1861             m_graphicsLayer->setMaskLayer(m_maskLayer.copyRef());
1862             // We need a geometry update to size the new mask layer.
1863             m_owningLayer.setNeedsCompositingGeometryUpdate();
1864         }
1865     } else if (m_maskLayer) {
1866         m_graphicsLayer->setMaskLayer(nullptr);
1867         willDestroyLayer(m_maskLayer.get());
1868         GraphicsLayer::clear(m_maskLayer);
1869         layerChanged = true;
1870     }
1871
1872     return layerChanged;
1873 }
1874
1875 void RenderLayerBacking::updateChildClippingStrategy(bool needsDescendantsClippingLayer)
1876 {
1877     if (hasClippingLayer() && needsDescendantsClippingLayer) {
1878         if (is<RenderBox>(renderer()) && (renderer().style().clipPath() || renderer().style().hasBorderRadius())) {
1879             auto* clipLayer = clippingLayer();
1880             LayoutRect boxRect(LayoutPoint(), downcast<RenderBox>(renderer()).size());
1881             FloatRoundedRect contentsClippingRect = renderer().style().getRoundedInnerBorderFor(boxRect).pixelSnappedRoundedRectForPainting(deviceScaleFactor());
1882             contentsClippingRect.move(LayoutSize(clipLayer->offsetFromRenderer()));
1883             // Note that we have to set this rounded rect again during the geometry update (clipLayer->offsetFromRenderer() may be stale here).
1884             if (clipLayer->setMasksToBoundsRect(contentsClippingRect)) {
1885                 clipLayer->setMaskLayer(nullptr);
1886                 GraphicsLayer::clear(m_childClippingMaskLayer);
1887                 return;
1888             }
1889
1890             if (!m_childClippingMaskLayer) {
1891                 m_childClippingMaskLayer = createGraphicsLayer("child clipping mask");
1892                 m_childClippingMaskLayer->setDrawsContent(true);
1893                 m_childClippingMaskLayer->setPaintingPhase({ GraphicsLayerPaintingPhase::ChildClippingMask });
1894                 clippingLayer()->setMaskLayer(m_childClippingMaskLayer.copyRef());
1895             }
1896         }
1897     } else {
1898         if (m_childClippingMaskLayer) {
1899             if (hasClippingLayer())
1900                 clippingLayer()->setMaskLayer(nullptr);
1901             GraphicsLayer::clear(m_childClippingMaskLayer);
1902         } else 
1903             if (hasClippingLayer())
1904                 clippingLayer()->setMasksToBoundsRect(FloatRoundedRect(FloatRect({ }, clippingLayer()->size())));
1905     }
1906 }
1907
1908 bool RenderLayerBacking::updateScrollingLayers(bool needsScrollingLayers)
1909 {
1910     if (needsScrollingLayers == !!m_scrollContainerLayer)
1911         return false;
1912
1913     if (!m_scrollContainerLayer) {
1914         // Outer layer which corresponds with the scroll view. This never paints content.
1915         m_scrollContainerLayer = createGraphicsLayer("scroll container", GraphicsLayer::Type::ScrollContainer);
1916         m_scrollContainerLayer->setPaintingPhase({ });
1917         m_scrollContainerLayer->setDrawsContent(false);
1918         m_scrollContainerLayer->setMasksToBounds(true);
1919
1920         // Inner layer which renders the content that scrolls.
1921         m_scrolledContentsLayer = createGraphicsLayer("scrolled contents", GraphicsLayer::Type::ScrolledContents);
1922         m_scrolledContentsLayer->setDrawsContent(true);
1923         m_scrolledContentsLayer->setAnchorPoint({ });
1924         m_scrollContainerLayer->addChild(*m_scrolledContentsLayer);
1925     } else {
1926         compositor().willRemoveScrollingLayerWithBacking(m_owningLayer, *this);
1927
1928         willDestroyLayer(m_scrollContainerLayer.get());
1929         willDestroyLayer(m_scrolledContentsLayer.get());
1930         
1931         GraphicsLayer::unparentAndClear(m_scrollContainerLayer);
1932         GraphicsLayer::unparentAndClear(m_scrolledContentsLayer);
1933     }
1934
1935     if (m_scrollContainerLayer)
1936         compositor().didAddScrollingLayer(m_owningLayer);
1937     
1938     return true;
1939 }
1940
1941 void RenderLayerBacking::detachFromScrollingCoordinator(OptionSet<ScrollCoordinationRole> roles)
1942 {
1943     if (!m_scrollingNodeID && !m_ancestorClippingStack && !m_frameHostingNodeID && !m_viewportConstrainedNodeID && !m_positioningNodeID)
1944         return;
1945
1946     auto* scrollingCoordinator = m_owningLayer.page().scrollingCoordinator();
1947     if (!scrollingCoordinator)
1948         return;
1949
1950     if (roles.contains(ScrollCoordinationRole::Scrolling) && m_scrollingNodeID) {
1951         LOG_WITH_STREAM(Compositing, stream << "Detaching Scrolling node " << m_scrollingNodeID);
1952         scrollingCoordinator->unparentChildrenAndDestroyNode(m_scrollingNodeID);
1953         m_scrollingNodeID = 0;
1954     }
1955
1956     if (roles.contains(ScrollCoordinationRole::ScrollingProxy) && m_ancestorClippingStack) {
1957         m_ancestorClippingStack->detachFromScrollingCoordinator(*scrollingCoordinator);
1958         LOG_WITH_STREAM(Compositing, stream << "Detaching nodes in ancestor clipping stack");
1959     }
1960
1961     if (roles.contains(ScrollCoordinationRole::FrameHosting) && m_frameHostingNodeID) {
1962         LOG_WITH_STREAM(Compositing, stream << "Detaching FrameHosting node " << m_frameHostingNodeID);
1963         scrollingCoordinator->unparentChildrenAndDestroyNode(m_frameHostingNodeID);
1964         m_frameHostingNodeID = 0;
1965     }
1966
1967     if (roles.contains(ScrollCoordinationRole::ViewportConstrained) && m_viewportConstrainedNodeID) {
1968         LOG_WITH_STREAM(Compositing, stream << "Detaching ViewportConstrained node " << m_viewportConstrainedNodeID);
1969         scrollingCoordinator->unparentChildrenAndDestroyNode(m_viewportConstrainedNodeID);
1970         m_viewportConstrainedNodeID = 0;
1971     }
1972
1973     if (roles.contains(ScrollCoordinationRole::Positioning) && m_positioningNodeID) {
1974         LOG_WITH_STREAM(Compositing, stream << "Detaching Positioned node " << m_positioningNodeID);
1975         scrollingCoordinator->unparentChildrenAndDestroyNode(m_positioningNodeID);
1976         m_positioningNodeID = 0;
1977     }
1978 }
1979
1980 ScrollingNodeID RenderLayerBacking::scrollingNodeIDForChildren() const
1981 {
1982     if (m_frameHostingNodeID)
1983         return m_frameHostingNodeID;
1984
1985     if (m_scrollingNodeID)
1986         return m_scrollingNodeID;
1987
1988     if (m_viewportConstrainedNodeID)
1989         return m_viewportConstrainedNodeID;
1990
1991     if (m_ancestorClippingStack) {
1992         if (auto lastOverflowScrollProxyNode = m_ancestorClippingStack->lastOverflowScrollProxyNodeID())
1993             return lastOverflowScrollProxyNode;
1994     }
1995
1996     return m_positioningNodeID;
1997 }
1998
1999 void RenderLayerBacking::setIsScrollCoordinatedWithViewportConstrainedRole(bool viewportCoordinated)
2000 {
2001     m_graphicsLayer->setIsViewportConstrained(viewportCoordinated);
2002 }
2003
2004 float RenderLayerBacking::compositingOpacity(float rendererOpacity) const
2005 {
2006     float finalOpacity = rendererOpacity;
2007     
2008     for (auto* curr = m_owningLayer.parent(); curr; curr = curr->parent()) {
2009         // We only care about parents that are stacking contexts.
2010         // Recall that opacity creates stacking context.
2011         if (!curr->isCSSStackingContext())
2012             continue;
2013         
2014         // If we found a compositing layer, we want to compute opacity
2015         // relative to it. So we can break here.
2016         if (curr->isComposited())
2017             break;
2018         
2019         finalOpacity *= curr->renderer().opacity();
2020     }
2021
2022     return finalOpacity;
2023 }
2024
2025 // FIXME: Code is duplicated in RenderLayer. Also, we should probably not consider filters a box decoration here.
2026 static inline bool hasVisibleBoxDecorations(const RenderStyle& style)
2027 {
2028     return style.hasVisibleBorder() || style.hasBorderRadius() || style.hasOutline() || style.hasAppearance() || style.boxShadow() || style.hasFilter();
2029 }
2030
2031 static bool canDirectlyCompositeBackgroundBackgroundImage(const RenderStyle& style)
2032 {
2033     if (!GraphicsLayer::supportsContentsTiling())
2034         return false;
2035
2036     auto& fillLayer = style.backgroundLayers();
2037     if (fillLayer.next())
2038         return false;
2039
2040     if (!fillLayer.imagesAreLoaded())
2041         return false;
2042
2043     if (fillLayer.attachment() != FillAttachment::ScrollBackground)
2044         return false;
2045
2046     // FIXME: Allow color+image compositing when it makes sense.
2047     // For now bailing out.
2048     if (style.visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor).isVisible())
2049         return false;
2050
2051     // FIXME: support gradients with isGeneratedImage.
2052     auto* styleImage = fillLayer.image();
2053     if (!styleImage->isCachedImage())
2054         return false;
2055
2056     auto* image = styleImage->cachedImage()->image();
2057     if (!image->isBitmapImage())
2058         return false;
2059
2060     return true;
2061 }
2062
2063 static bool hasPaintedBoxDecorationsOrBackgroundImage(const RenderStyle& style)
2064 {
2065     if (hasVisibleBoxDecorations(style))
2066         return true;
2067
2068     if (!style.hasBackgroundImage())
2069         return false;
2070
2071     return !canDirectlyCompositeBackgroundBackgroundImage(style);
2072 }
2073
2074 static inline bool hasPerspectiveOrPreserves3D(const RenderStyle& style)
2075 {
2076     return style.hasPerspective() || style.preserves3D();
2077 }
2078
2079 Color RenderLayerBacking::rendererBackgroundColor() const
2080 {
2081     RenderElement* backgroundRenderer = nullptr;
2082     if (renderer().isDocumentElementRenderer())
2083         backgroundRenderer = renderer().view().rendererForRootBackground();
2084     
2085     if (!backgroundRenderer)
2086         backgroundRenderer = &renderer();
2087
2088     return backgroundRenderer->style().visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor);
2089 }
2090
2091 void RenderLayerBacking::updateDirectlyCompositedBackgroundColor(PaintedContentsInfo& contentsInfo, bool& didUpdateContentsRect)
2092 {
2093     if (m_backgroundLayer && !m_backgroundLayerPaintsFixedRootBackground && !contentsInfo.paintsBoxDecorations()) {
2094         m_graphicsLayer->setContentsToSolidColor(Color());
2095         m_backgroundLayer->setContentsToSolidColor(rendererBackgroundColor());
2096
2097         FloatRect contentsRect = backgroundBoxForSimpleContainerPainting();
2098         // NOTE: This is currently only used by RenderFullScreen, which we want to be
2099         // big enough to hide overflow areas of the root.
2100         contentsRect.inflate(contentsRect.size());
2101         m_backgroundLayer->setContentsRect(contentsRect);
2102         m_backgroundLayer->setContentsClippingRect(FloatRoundedRect(contentsRect));
2103         return;
2104     }
2105
2106     if (!contentsInfo.isSimpleContainer() || (is<RenderBox>(renderer()) && !downcast<RenderBox>(renderer()).paintsOwnBackground())) {
2107         m_graphicsLayer->setContentsToSolidColor(Color());
2108         return;
2109     }
2110
2111     Color backgroundColor = rendererBackgroundColor();
2112
2113     // An unset (invalid) color will remove the solid color.
2114     m_graphicsLayer->setContentsToSolidColor(backgroundColor);
2115     FloatRect contentsRect = backgroundBoxForSimpleContainerPainting();
2116     m_graphicsLayer->setContentsRect(contentsRect);
2117     m_graphicsLayer->setContentsClippingRect(FloatRoundedRect(contentsRect));
2118     didUpdateContentsRect = true;
2119 }
2120
2121 void RenderLayerBacking::updateDirectlyCompositedBackgroundImage(PaintedContentsInfo& contentsInfo, bool& didUpdateContentsRect)
2122 {
2123     if (!GraphicsLayer::supportsContentsTiling())
2124         return;
2125
2126     if (contentsInfo.isDirectlyCompositedImage())
2127         return;
2128
2129     auto& style = renderer().style();
2130     if (!contentsInfo.isSimpleContainer() || !style.hasBackgroundImage()) {
2131         m_graphicsLayer->setContentsToImage(0);
2132         return;
2133     }
2134
2135     auto destRect = backgroundBoxForSimpleContainerPainting();
2136     FloatSize phase;
2137     FloatSize tileSize;
2138     // FIXME: Absolute paint location is required here.
2139     downcast<RenderBox>(renderer()).getGeometryForBackgroundImage(&renderer(), LayoutPoint(), destRect, phase, tileSize);
2140
2141     m_graphicsLayer->setContentsTileSize(tileSize);
2142     m_graphicsLayer->setContentsTilePhase(phase);
2143     m_graphicsLayer->setContentsRect(destRect);
2144     m_graphicsLayer->setContentsClippingRect(FloatRoundedRect(destRect));
2145     m_graphicsLayer->setContentsToImage(style.backgroundLayers().image()->cachedImage()->image());
2146
2147     didUpdateContentsRect = true;
2148 }
2149
2150 void RenderLayerBacking::updateRootLayerConfiguration()
2151 {
2152     if (!m_isFrameLayerWithTiledBacking)
2153         return;
2154
2155     Color backgroundColor;
2156     bool viewIsTransparent = compositor().viewHasTransparentBackground(&backgroundColor);
2157
2158     if (m_backgroundLayerPaintsFixedRootBackground && m_backgroundLayer) {
2159         if (m_isMainFrameRenderViewLayer) {
2160             m_backgroundLayer->setBackgroundColor(backgroundColor);
2161             m_backgroundLayer->setContentsOpaque(!viewIsTransparent);
2162         }
2163
2164         m_graphicsLayer->setBackgroundColor(Color());
2165         m_graphicsLayer->setContentsOpaque(false);
2166     } else if (m_isMainFrameRenderViewLayer) {
2167         m_graphicsLayer->setBackgroundColor(backgroundColor);
2168         m_graphicsLayer->setContentsOpaque(!viewIsTransparent);
2169     }
2170 }
2171
2172 void RenderLayerBacking::updatePaintingPhases()
2173 {
2174     // Phases for m_childClippingMaskLayer and m_maskLayer are set elsewhere.
2175     OptionSet<GraphicsLayerPaintingPhase> primaryLayerPhases = { GraphicsLayerPaintingPhase::Background, GraphicsLayerPaintingPhase::Foreground };
2176     
2177     if (m_foregroundLayer) {
2178         OptionSet<GraphicsLayerPaintingPhase> foregroundLayerPhases { GraphicsLayerPaintingPhase::Foreground };
2179         
2180         if (m_scrolledContentsLayer)
2181             foregroundLayerPhases.add(GraphicsLayerPaintingPhase::OverflowContents);
2182
2183         m_foregroundLayer->setPaintingPhase(foregroundLayerPhases);
2184         primaryLayerPhases.remove(GraphicsLayerPaintingPhase::Foreground);
2185     }
2186
2187     if (m_backgroundLayer) {
2188         m_backgroundLayer->setPaintingPhase(GraphicsLayerPaintingPhase::Background);
2189         primaryLayerPhases.remove(GraphicsLayerPaintingPhase::Background);
2190     }
2191
2192     if (m_scrolledContentsLayer) {
2193         OptionSet<GraphicsLayerPaintingPhase> scrolledContentLayerPhases = { GraphicsLayerPaintingPhase::OverflowContents, GraphicsLayerPaintingPhase::CompositedScroll };
2194         if (!m_foregroundLayer)
2195             scrolledContentLayerPhases.add(GraphicsLayerPaintingPhase::Foreground);
2196         m_scrolledContentsLayer->setPaintingPhase(scrolledContentLayerPhases);
2197
2198         primaryLayerPhases.remove(GraphicsLayerPaintingPhase::Foreground);
2199         primaryLayerPhases.add(GraphicsLayerPaintingPhase::CompositedScroll);
2200     }
2201
2202     m_graphicsLayer->setPaintingPhase(primaryLayerPhases);
2203 }
2204
2205 static bool supportsDirectlyCompositedBoxDecorations(const RenderLayerModelObject& renderer)
2206 {
2207     if (!GraphicsLayer::supportsBackgroundColorContent())
2208         return false;
2209
2210     const RenderStyle& style = renderer.style();
2211     if (renderer.hasClip())
2212         return false;
2213
2214     if (hasPaintedBoxDecorationsOrBackgroundImage(style))
2215         return false;
2216
2217     // FIXME: We can't create a directly composited background if this
2218     // layer will have children that intersect with the background layer.
2219     // A better solution might be to introduce a flattening layer if
2220     // we do direct box decoration composition.
2221     // https://bugs.webkit.org/show_bug.cgi?id=119461
2222     if (hasPerspectiveOrPreserves3D(style))
2223         return false;
2224
2225     // FIXME: we should be able to allow backgroundComposite; However since this is not a common use case it has been deferred for now.
2226     if (style.backgroundComposite() != CompositeSourceOver)
2227         return false;
2228
2229     return true;
2230 }
2231
2232 bool RenderLayerBacking::paintsBoxDecorations() const
2233 {
2234     if (!m_owningLayer.hasVisibleBoxDecorations())
2235         return false;
2236
2237     return !supportsDirectlyCompositedBoxDecorations(renderer());
2238 }
2239
2240 bool RenderLayerBacking::paintsContent(RenderLayer::PaintedContentRequest& request) const
2241 {
2242     m_owningLayer.updateDescendantDependentFlags();
2243
2244     bool paintsContent = false;
2245
2246     if (m_owningLayer.hasVisibleContent() && m_owningLayer.hasNonEmptyChildRenderers(request))
2247         paintsContent = true;
2248
2249     if (request.isSatisfied())
2250         return paintsContent;
2251
2252     if (isPaintDestinationForDescendantLayers(request))
2253         paintsContent = true;
2254
2255     if (request.isSatisfied())
2256         return paintsContent;
2257
2258     if (request.hasPaintedContent == RequestState::Unknown)
2259         request.hasPaintedContent = RequestState::False;
2260
2261     if (request.hasSubpixelAntialiasedText == RequestState::Unknown)
2262         request.hasSubpixelAntialiasedText = RequestState::False;
2263
2264     return paintsContent;
2265 }
2266
2267 static bool isRestartedPlugin(RenderObject& renderer)
2268 {
2269     if (!is<RenderEmbeddedObject>(renderer))
2270         return false;
2271
2272     auto& element = downcast<RenderEmbeddedObject>(renderer).frameOwnerElement();
2273     if (!is<HTMLPlugInElement>(element))
2274         return false;
2275
2276     return downcast<HTMLPlugInElement>(element).isRestartedPlugin();
2277 }
2278
2279 static bool isCompositedPlugin(RenderObject& renderer)
2280 {
2281     return is<RenderEmbeddedObject>(renderer) && downcast<RenderEmbeddedObject>(renderer).allowsAcceleratedCompositing();
2282 }
2283
2284 // A "simple container layer" is a RenderLayer which has no visible content to render.
2285 // It may have no children, or all its children may be themselves composited.
2286 // This is a useful optimization, because it allows us to avoid allocating backing store.
2287 bool RenderLayerBacking::isSimpleContainerCompositingLayer(PaintedContentsInfo& contentsInfo) const
2288 {
2289     if (m_owningLayer.isRenderViewLayer())
2290         return false;
2291
2292     if (hasBackingSharingLayers())
2293         return false;
2294
2295     if (renderer().isRenderReplaced() && (!isCompositedPlugin(renderer()) || isRestartedPlugin(renderer())))
2296         return false;
2297
2298     if (renderer().isTextControl())
2299         return false;
2300
2301     if (contentsInfo.paintsBoxDecorations() || contentsInfo.paintsContent())
2302         return false;
2303
2304     if (renderer().style().backgroundClip() == FillBox::Text)
2305         return false;
2306     
2307     if (renderer().isDocumentElementRenderer() && m_owningLayer.isolatesCompositedBlending())
2308         return false;
2309
2310     return true;
2311 }
2312
2313 // Returning true stops the traversal.
2314 enum class LayerTraversal { Continue, Stop };
2315
2316 static LayerTraversal traverseVisibleNonCompositedDescendantLayers(RenderLayer& parent, const WTF::Function<LayerTraversal (const RenderLayer&)>& layerFunc)
2317 {
2318     // FIXME: We shouldn't be called with a stale z-order lists. See bug 85512.
2319     parent.updateLayerListsIfNeeded();
2320
2321 #if !ASSERT_DISABLED
2322     LayerListMutationDetector mutationChecker(parent);
2323 #endif
2324
2325     for (auto* childLayer : parent.normalFlowLayers()) {
2326         if (compositedWithOwnBackingStore(*childLayer))
2327             continue;
2328
2329         if (layerFunc(*childLayer) == LayerTraversal::Stop)
2330             return LayerTraversal::Stop;
2331         
2332         if (traverseVisibleNonCompositedDescendantLayers(*childLayer, layerFunc) == LayerTraversal::Stop)
2333             return LayerTraversal::Stop;
2334     }
2335
2336     if (parent.isStackingContext() && !parent.hasVisibleDescendant())
2337         return LayerTraversal::Continue;
2338
2339     // Use the m_hasCompositingDescendant bit to optimize?
2340     for (auto* childLayer : parent.negativeZOrderLayers()) {
2341         if (compositedWithOwnBackingStore(*childLayer))
2342             continue;
2343
2344         if (layerFunc(*childLayer) == LayerTraversal::Stop)
2345             return LayerTraversal::Stop;
2346
2347         if (traverseVisibleNonCompositedDescendantLayers(*childLayer, layerFunc) == LayerTraversal::Stop)
2348             return LayerTraversal::Stop;
2349     }
2350
2351     for (auto* childLayer : parent.positiveZOrderLayers()) {
2352         if (compositedWithOwnBackingStore(*childLayer))
2353             continue;
2354
2355         if (layerFunc(*childLayer) == LayerTraversal::Stop)
2356             return LayerTraversal::Stop;
2357
2358         if (traverseVisibleNonCompositedDescendantLayers(*childLayer, layerFunc) == LayerTraversal::Stop)
2359             return LayerTraversal::Stop;
2360     }
2361
2362     return LayerTraversal::Continue;
2363 }
2364
2365 // Conservative test for having no rendered children.
2366 bool RenderLayerBacking::isPaintDestinationForDescendantLayers(RenderLayer::PaintedContentRequest& request) const
2367 {
2368     bool hasPaintingDescendant = false;
2369     traverseVisibleNonCompositedDescendantLayers(m_owningLayer, [&hasPaintingDescendant, &request](const RenderLayer& layer) {
2370         hasPaintingDescendant |= layer.isVisuallyNonEmpty(&request);
2371         return (hasPaintingDescendant && request.isSatisfied()) ? LayerTraversal::Stop : LayerTraversal::Continue;
2372     });
2373
2374     return hasPaintingDescendant;
2375 }
2376
2377 bool RenderLayerBacking::hasVisibleNonCompositedDescendants() const
2378 {
2379     bool hasVisibleDescendant = false;
2380     traverseVisibleNonCompositedDescendantLayers(m_owningLayer, [&hasVisibleDescendant](const RenderLayer& layer) {
2381         hasVisibleDescendant |= layer.hasVisibleContent();
2382         return hasVisibleDescendant ? LayerTraversal::Stop : LayerTraversal::Continue;
2383     });
2384
2385     return hasVisibleDescendant;
2386 }
2387
2388 bool RenderLayerBacking::containsPaintedContent(PaintedContentsInfo& contentsInfo) const
2389 {
2390     if (contentsInfo.isSimpleContainer() || paintsIntoWindow() || paintsIntoCompositedAncestor() || m_artificiallyInflatedBounds || m_owningLayer.isReflection())
2391         return false;
2392
2393     if (contentsInfo.isDirectlyCompositedImage())
2394         return false;
2395
2396     // FIXME: we could optimize cases where the image, video or canvas is known to fill the border box entirely,
2397     // and set background color on the layer in that case, instead of allocating backing store and painting.
2398 #if ENABLE(VIDEO)
2399     if (is<RenderVideo>(renderer()) && downcast<RenderVideo>(renderer()).shouldDisplayVideo())
2400         return m_owningLayer.hasVisibleBoxDecorationsOrBackground() || (!(downcast<RenderVideo>(renderer()).supportsAcceleratedRendering()) && m_requiresOwnBackingStore);
2401 #endif
2402
2403 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
2404     if (is<RenderHTMLCanvas>(renderer()) && canvasCompositingStrategy(renderer()) == CanvasAsLayerContents)
2405         return m_owningLayer.hasVisibleBoxDecorationsOrBackground();
2406 #endif
2407
2408     return true;
2409 }
2410
2411 // An image can be directly compositing if it's the sole content of the layer, and has no box decorations
2412 // that require painting. Direct compositing saves backing store.
2413 bool RenderLayerBacking::isDirectlyCompositedImage() const
2414 {
2415     if (!is<RenderImage>(renderer()) || m_owningLayer.hasVisibleBoxDecorationsOrBackground() || m_owningLayer.paintsWithFilters() || renderer().hasClip())
2416         return false;
2417
2418 #if ENABLE(VIDEO)
2419     if (is<RenderMedia>(renderer()))
2420         return false;
2421 #endif
2422
2423     auto& imageRenderer = downcast<RenderImage>(renderer());
2424     if (auto* cachedImage = imageRenderer.cachedImage()) {
2425         if (!cachedImage->hasImage())
2426             return false;
2427
2428         auto* image = cachedImage->imageForRenderer(&imageRenderer);
2429         if (!is<BitmapImage>(image))
2430             return false;
2431
2432         if (downcast<BitmapImage>(*image).orientationForCurrentFrame() != DefaultImageOrientation)
2433             return false;
2434
2435 #if (PLATFORM(GTK) || PLATFORM(WPE))
2436         // GTK and WPE ports don't support rounded rect clipping at TextureMapper level, so they cannot
2437         // directly composite images that have border-radius propery. Draw them as non directly composited
2438         // content instead. See https://bugs.webkit.org/show_bug.cgi?id=174157.
2439         if (imageRenderer.style().hasBorderRadius())
2440             return false;
2441 #endif
2442
2443         return m_graphicsLayer->shouldDirectlyCompositeImage(image);
2444     }
2445
2446     return false;
2447 }
2448
2449 void RenderLayerBacking::contentChanged(ContentChangeType changeType)
2450 {
2451     PaintedContentsInfo contentsInfo(*this);
2452     if ((changeType == ImageChanged) && contentsInfo.isDirectlyCompositedImage()) {
2453         updateImageContents(contentsInfo);
2454         return;
2455     }
2456
2457     if (changeType == VideoChanged) {
2458         compositor().scheduleCompositingLayerUpdate();
2459         return;
2460     }
2461
2462     if ((changeType == BackgroundImageChanged) && canDirectlyCompositeBackgroundBackgroundImage(renderer().style()))
2463         m_owningLayer.setNeedsCompositingConfigurationUpdate();
2464
2465     if ((changeType == MaskImageChanged) && m_maskLayer)
2466         m_owningLayer.setNeedsCompositingConfigurationUpdate();
2467
2468 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
2469     if ((changeType == CanvasChanged || changeType == CanvasPixelsChanged) && renderer().isCanvas() && canvasCompositingStrategy(renderer()) == CanvasAsLayerContents) {
2470         m_graphicsLayer->setContentsNeedsDisplay();
2471         return;
2472     }
2473 #endif
2474 }
2475
2476 void RenderLayerBacking::updateImageContents(PaintedContentsInfo& contentsInfo)
2477 {
2478     auto& imageRenderer = downcast<RenderImage>(renderer());
2479
2480     auto* cachedImage = imageRenderer.cachedImage();
2481     if (!cachedImage)
2482         return;
2483
2484     auto* image = cachedImage->imageForRenderer(&imageRenderer);
2485     if (!image)
2486         return;
2487
2488     // We have to wait until the image is fully loaded before setting it on the layer.
2489     if (!cachedImage->isLoaded())
2490         return;
2491
2492     // This is a no-op if the layer doesn't have an inner layer for the image.
2493     m_graphicsLayer->setContentsRect(snapRectToDevicePixels(contentsBox(), deviceScaleFactor()));
2494
2495     LayoutRect boxRect(LayoutPoint(), imageRenderer.size());
2496     boxRect.move(contentOffsetInCompositingLayer());
2497     FloatRoundedRect contentsClippingRect = renderer().style().getRoundedInnerBorderFor(boxRect).pixelSnappedRoundedRectForPainting(deviceScaleFactor());
2498     m_graphicsLayer->setContentsClippingRect(contentsClippingRect);
2499
2500     m_graphicsLayer->setContentsToImage(image);
2501     
2502     updateDrawsContent(contentsInfo);
2503     
2504     // Image animation is "lazy", in that it automatically stops unless someone is drawing
2505     // the image. So we have to kick the animation each time; this has the downside that the
2506     // image will keep animating, even if its layer is not visible.
2507     image->startAnimation();
2508 }
2509
2510 FloatPoint3D RenderLayerBacking::computeTransformOriginForPainting(const LayoutRect& borderBox) const
2511 {
2512     const RenderStyle& style = renderer().style();
2513     float deviceScaleFactor = this->deviceScaleFactor();
2514
2515     FloatPoint3D origin;
2516     origin.setX(roundToDevicePixel(floatValueForLength(style.transformOriginX(), borderBox.width()), deviceScaleFactor));
2517     origin.setY(roundToDevicePixel(floatValueForLength(style.transformOriginY(), borderBox.height()), deviceScaleFactor));
2518     origin.setZ(style.transformOriginZ());
2519
2520     return origin;
2521 }
2522
2523 // Return the offset from the top-left of this compositing layer at which the renderer's contents are painted.
2524 LayoutSize RenderLayerBacking::contentOffsetInCompositingLayer() const
2525 {
2526     return LayoutSize(-m_compositedBounds.x() + m_compositedBoundsOffsetFromGraphicsLayer.width(), -m_compositedBounds.y() + m_compositedBoundsOffsetFromGraphicsLayer.height());
2527 }
2528
2529 LayoutRect RenderLayerBacking::contentsBox() const
2530 {
2531     if (!is<RenderBox>(renderer()))
2532         return LayoutRect();
2533
2534     auto& renderBox = downcast<RenderBox>(renderer());
2535     LayoutRect contentsRect;
2536 #if ENABLE(VIDEO)
2537     if (is<RenderVideo>(renderBox))
2538         contentsRect = downcast<RenderVideo>(renderBox).videoBox();
2539     else
2540 #endif
2541     if (is<RenderReplaced>(renderBox)) {
2542         RenderReplaced& renderReplaced = downcast<RenderReplaced>(renderBox);
2543         contentsRect = renderReplaced.replacedContentRect();
2544     } else
2545         contentsRect = renderBox.contentBoxRect();
2546
2547     contentsRect.move(contentOffsetInCompositingLayer());
2548     return contentsRect;
2549 }
2550
2551 static LayoutRect backgroundRectForBox(const RenderBox& box)
2552 {
2553     switch (box.style().backgroundClip()) {
2554     case FillBox::Border:
2555         return box.borderBoxRect();
2556     case FillBox::Padding:
2557         return box.paddingBoxRect();
2558     case FillBox::Content:
2559         return box.contentBoxRect();
2560     default:
2561         break;
2562     }
2563
2564     ASSERT_NOT_REACHED();
2565     return LayoutRect();
2566 }
2567
2568 FloatRect RenderLayerBacking::backgroundBoxForSimpleContainerPainting() const
2569 {
2570     if (!is<RenderBox>(renderer()))
2571         return FloatRect();
2572
2573     LayoutRect backgroundBox = backgroundRectForBox(downcast<RenderBox>(renderer()));
2574     backgroundBox.move(contentOffsetInCompositingLayer());
2575     return snapRectToDevicePixels(backgroundBox, deviceScaleFactor());
2576 }
2577
2578 GraphicsLayer* RenderLayerBacking::parentForSublayers() const
2579 {
2580     if (m_scrolledContentsLayer)
2581         return m_scrolledContentsLayer.get();
2582
2583     return m_childContainmentLayer ? m_childContainmentLayer.get() : m_graphicsLayer.get();
2584 }
2585
2586 GraphicsLayer* RenderLayerBacking::childForSuperlayers() const
2587 {
2588     if (m_ancestorClippingStack)
2589         return m_ancestorClippingStack->firstClippingLayer();
2590
2591     if (m_contentsContainmentLayer)
2592         return m_contentsContainmentLayer.get();
2593     
2594     return m_graphicsLayer.get();
2595 }
2596
2597 bool RenderLayerBacking::paintsIntoWindow() const
2598 {
2599 #if USE(COORDINATED_GRAPHICS)
2600         return false;
2601 #endif
2602
2603     if (m_isFrameLayerWithTiledBacking)
2604         return false;
2605
2606     if (m_owningLayer.isRenderViewLayer()) {
2607 #if PLATFORM(IOS_FAMILY) || USE(COORDINATED_GRAPHICS)
2608         if (compositor().inForcedCompositingMode())
2609             return false;
2610 #endif
2611
2612         return compositor().rootLayerAttachment() != RenderLayerCompositor::RootLayerAttachedViaEnclosingFrame;
2613     }
2614     
2615     return false;
2616 }
2617
2618 void RenderLayerBacking::setRequiresOwnBackingStore(bool requiresOwnBacking)
2619 {
2620     if (requiresOwnBacking == m_requiresOwnBackingStore)
2621         return;
2622     
2623     m_requiresOwnBackingStore = requiresOwnBacking;
2624
2625     // This affects the answer to paintsIntoCompositedAncestor(), which in turn affects
2626     // cached clip rects, so when it changes we have to clear clip rects on descendants.
2627     m_owningLayer.clearClipRectsIncludingDescendants(PaintingClipRects);
2628     m_owningLayer.computeRepaintRectsIncludingDescendants();
2629     
2630     compositor().repaintInCompositedAncestor(m_owningLayer, compositedBounds());
2631 }
2632
2633 void RenderLayerBacking::setContentsNeedDisplay(GraphicsLayer::ShouldClipToLayer shouldClip)
2634 {
2635     ASSERT(!paintsIntoCompositedAncestor());
2636
2637     // Use the repaint as a trigger to re-evaluate direct compositing (which is never used on the root layer).
2638     if (!m_owningLayer.isRenderViewLayer())
2639         m_owningLayer.setNeedsCompositingConfigurationUpdate();
2640
2641     m_owningLayer.invalidateEventRegion();
2642
2643     auto& frameView = renderer().view().frameView();
2644     if (m_isMainFrameRenderViewLayer && frameView.isTrackingRepaints())
2645         frameView.addTrackedRepaintRect(owningLayer().absoluteBoundingBoxForPainting());
2646     
2647     if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
2648         // By default, setNeedsDisplay will clip to the size of the GraphicsLayer, which does not include margin tiles.
2649         // So if the TiledBacking has a margin that needs to be invalidated, we need to send in a rect to setNeedsDisplayInRect
2650         // that is large enough to include the margin. TiledBacking::bounds() includes the margin.
2651         auto* tiledBacking = this->tiledBacking();
2652         FloatRect rectToRepaint = tiledBacking ? tiledBacking->bounds() : FloatRect(FloatPoint(0, 0), m_graphicsLayer->size());
2653         m_graphicsLayer->setNeedsDisplayInRect(rectToRepaint, shouldClip);
2654     }
2655     
2656     if (m_foregroundLayer && m_foregroundLayer->drawsContent())
2657         m_foregroundLayer->setNeedsDisplay();
2658
2659     if (m_backgroundLayer && m_backgroundLayer->drawsContent())
2660         m_backgroundLayer->setNeedsDisplay();
2661
2662     if (m_maskLayer && m_maskLayer->drawsContent())
2663         m_maskLayer->setNeedsDisplay();
2664
2665     if (m_childClippingMaskLayer && m_childClippingMaskLayer->drawsContent())
2666         m_childClippingMaskLayer->setNeedsDisplay();
2667
2668     if (m_scrolledContentsLayer && m_scrolledContentsLayer->drawsContent())
2669         m_scrolledContentsLayer->setNeedsDisplay();
2670 }
2671
2672 // r is in the coordinate space of the layer's render object
2673 void RenderLayerBacking::setContentsNeedDisplayInRect(const LayoutRect& r, GraphicsLayer::ShouldClipToLayer shouldClip)
2674 {
2675     ASSERT(!paintsIntoCompositedAncestor());
2676     
2677     // Use the repaint as a trigger to re-evaluate direct compositing (which is never used on the root layer).
2678     if (!m_owningLayer.isRenderViewLayer())
2679         m_owningLayer.setNeedsCompositingConfigurationUpdate();
2680
2681     m_owningLayer.invalidateEventRegion();
2682
2683     FloatRect pixelSnappedRectForPainting = snapRectToDevicePixels(r, deviceScaleFactor());
2684     auto& frameView = renderer().view().frameView();
2685     if (m_isMainFrameRenderViewLayer && frameView.isTrackingRepaints())
2686         frameView.addTrackedRepaintRect(pixelSnappedRectForPainting);
2687
2688     if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
2689         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2690         layerDirtyRect.move(-m_graphicsLayer->offsetFromRenderer() - m_subpixelOffsetFromRenderer);
2691         m_graphicsLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2692     }
2693
2694     if (m_foregroundLayer && m_foregroundLayer->drawsContent()) {
2695         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2696         layerDirtyRect.move(-m_foregroundLayer->offsetFromRenderer() - m_subpixelOffsetFromRenderer);
2697         m_foregroundLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2698     }
2699
2700     // FIXME: need to split out repaints for the background.
2701     if (m_backgroundLayer && m_backgroundLayer->drawsContent()) {
2702         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2703         layerDirtyRect.move(-m_backgroundLayer->offsetFromRenderer() - m_subpixelOffsetFromRenderer);
2704         m_backgroundLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2705     }
2706
2707     if (m_maskLayer && m_maskLayer->drawsContent()) {
2708         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2709         layerDirtyRect.move(-m_maskLayer->offsetFromRenderer() - m_subpixelOffsetFromRenderer);
2710         m_maskLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2711     }
2712
2713     if (m_childClippingMaskLayer && m_childClippingMaskLayer->drawsContent()) {
2714         FloatRect layerDirtyRect = r;
2715         layerDirtyRect.move(-m_childClippingMaskLayer->offsetFromRenderer());
2716         m_childClippingMaskLayer->setNeedsDisplayInRect(layerDirtyRect);
2717     }
2718
2719     if (m_scrolledContentsLayer && m_scrolledContentsLayer->drawsContent()) {
2720         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2721         layerDirtyRect.move(-m_scrolledContentsLayer->offsetFromRenderer() + toLayoutSize(m_scrolledContentsLayer->scrollOffset()) - m_subpixelOffsetFromRenderer);
2722         m_scrolledContentsLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2723     }
2724 }
2725
2726 void RenderLayerBacking::paintIntoLayer(const GraphicsLayer* graphicsLayer, GraphicsContext& context,
2727     const IntRect& paintDirtyRect, // In the coords of rootLayer.
2728     OptionSet<PaintBehavior> paintBehavior, OptionSet<GraphicsLayerPaintingPhase> paintingPhase)
2729 {
2730     if ((paintsIntoWindow() || paintsIntoCompositedAncestor()) && paintingPhase != OptionSet<GraphicsLayerPaintingPhase>(GraphicsLayerPaintingPhase::ChildClippingMask)) {
2731 #if !PLATFORM(IOS_FAMILY) && !OS(WINDOWS)
2732         // FIXME: Looks like the CALayer tree is out of sync with the GraphicsLayer heirarchy
2733         // when pages are restored from the PageCache.
2734         // <rdar://problem/8712587> ASSERT: When Going Back to Page with Plugins in PageCache
2735         ASSERT_NOT_REACHED();
2736 #endif
2737         return;
2738     }
2739
2740     OptionSet<RenderLayer::PaintLayerFlag> paintFlags;
2741     if (paintingPhase.contains(GraphicsLayerPaintingPhase::Background))
2742         paintFlags.add(RenderLayer::PaintLayerPaintingCompositingBackgroundPhase);
2743     if (paintingPhase.contains(GraphicsLayerPaintingPhase::Foreground))
2744         paintFlags.add(RenderLayer::PaintLayerPaintingCompositingForegroundPhase);
2745     if (paintingPhase.contains(GraphicsLayerPaintingPhase::Mask))
2746         paintFlags.add(RenderLayer::PaintLayerPaintingCompositingMaskPhase);
2747     if (paintingPhase.contains(GraphicsLayerPaintingPhase::ClipPath))
2748         paintFlags.add(RenderLayer::PaintLayerPaintingCompositingClipPathPhase);
2749     if (paintingPhase.contains(GraphicsLayerPaintingPhase::ChildClippingMask))
2750         paintFlags.add(RenderLayer::PaintLayerPaintingChildClippingMaskPhase);
2751     if (paintingPhase.contains(GraphicsLayerPaintingPhase::OverflowContents))
2752         paintFlags.add(RenderLayer::PaintLayerPaintingOverflowContents);
2753     if (paintingPhase.contains(GraphicsLayerPaintingPhase::CompositedScroll))
2754         paintFlags.add(RenderLayer::PaintLayerPaintingCompositingScrollingPhase);
2755
2756     if (graphicsLayer == m_backgroundLayer.get() && m_backgroundLayerPaintsFixedRootBackground)
2757         paintFlags.add({ RenderLayer::PaintLayerPaintingRootBackgroundOnly, RenderLayer::PaintLayerPaintingCompositingForegroundPhase }); // Need PaintLayerPaintingCompositingForegroundPhase to walk child layers.
2758     else if (compositor().fixedRootBackgroundLayer())
2759         paintFlags.add(RenderLayer::PaintLayerPaintingSkipRootBackground);
2760
2761 #ifndef NDEBUG
2762     RenderElement::SetLayoutNeededForbiddenScope forbidSetNeedsLayout(&renderer());
2763 #endif
2764
2765     auto paintOneLayer = [&](RenderLayer& layer, OptionSet<RenderLayer::PaintLayerFlag> paintFlags) {
2766         InspectorInstrumentation::willPaint(layer.renderer());
2767
2768         FrameView::PaintingState paintingState;
2769         if (layer.isRenderViewLayer())
2770             renderer().view().frameView().willPaintContents(context, paintDirtyRect, paintingState);
2771
2772         RenderLayer::LayerPaintingInfo paintingInfo(&m_owningLayer, paintDirtyRect, paintBehavior, -m_subpixelOffsetFromRenderer);
2773
2774         if (&layer == &m_owningLayer) {
2775             layer.paintLayerContents(context, paintingInfo, paintFlags);
2776
2777             if (layer.containsDirtyOverlayScrollbars())
2778                 layer.paintLayerContents(context, paintingInfo, paintFlags | RenderLayer::PaintLayerPaintingOverlayScrollbars);
2779         } else
2780             layer.paintLayerWithEffects(context, paintingInfo, paintFlags);
2781
2782         if (layer.isRenderViewLayer())
2783             renderer().view().frameView().didPaintContents(context, paintDirtyRect, paintingState);
2784
2785         ASSERT(!m_owningLayer.m_usedTransparency);
2786
2787         InspectorInstrumentation::didPaint(layer.renderer(), paintDirtyRect);
2788     };
2789
2790     paintOneLayer(m_owningLayer, paintFlags);
2791     
2792     // FIXME: Need to check m_foregroundLayer, masking etc. webkit.org/b/197565.
2793     GraphicsLayer* destinationForSharingLayers = m_scrolledContentsLayer ? m_scrolledContentsLayer.get() : m_graphicsLayer.get();
2794
2795     if (graphicsLayer == destinationForSharingLayers) {
2796         OptionSet<RenderLayer::PaintLayerFlag> sharingLayerPaintFlags = {
2797             RenderLayer::PaintLayerPaintingCompositingBackgroundPhase,
2798             RenderLayer::PaintLayerPaintingCompositingForegroundPhase };
2799
2800         if (paintingPhase.contains(GraphicsLayerPaintingPhase::OverflowContents))
2801             sharingLayerPaintFlags.add(RenderLayer::PaintLayerPaintingOverflowContents);
2802
2803         for (auto& layerWeakPtr : m_backingSharingLayers)
2804             paintOneLayer(*layerWeakPtr, sharingLayerPaintFlags);
2805     }
2806
2807     compositor().didPaintBacking(this);
2808 }
2809
2810 #if ENABLE(POINTER_EVENTS)
2811 static RefPtr<Pattern> patternForTouchAction(TouchAction touchAction, FloatSize contentOffset, GraphicsContext& destContext)
2812 {
2813     auto toIndex = [](TouchAction touchAction) -> unsigned {
2814         switch (touchAction) {
2815         case TouchAction::Manipulation:
2816             return 1;
2817         case TouchAction::PanX:
2818             return 2;
2819         case TouchAction::PanY:
2820             return 3;
2821         case TouchAction::PinchZoom:
2822             return 4;
2823         case TouchAction::None:
2824         case TouchAction::Auto:
2825             break;
2826         }
2827         return 0;
2828     };
2829
2830     struct TouchActionAndRGB {
2831         TouchAction action;
2832         ASCIILiteral name;
2833         FloatSize phase;
2834     };
2835     static const TouchActionAndRGB actionsAndColors[] = {
2836         { TouchAction::None, "none"_s, { } },
2837         { TouchAction::Manipulation, "manip"_s, { } },
2838         { TouchAction::PanX, "pan-x"_s, { } },
2839         { TouchAction::PanY, "pan-y"_s, { 0, 9 } },
2840         { TouchAction::PinchZoom, "p-z"_s, { 16, 4.5 } },
2841     };
2842     
2843     auto actionIndex = toIndex(touchAction);
2844     if (!actionIndex || actionIndex >= ARRAY_SIZE(actionsAndColors))
2845         return nullptr;
2846
2847     const FloatSize tileSize { 32, 18 };
2848
2849     auto imageBuffer = ImageBuffer::createCompatibleBuffer(tileSize, ColorSpaceSRGB, destContext);
2850     if (!imageBuffer)
2851         return nullptr;
2852
2853     const auto& touchActionData = actionsAndColors[actionIndex];
2854     {
2855         GraphicsContext& imageContext = imageBuffer->context();
2856
2857         FontCascadeDescription fontDescription;
2858         fontDescription.setOneFamily("Helvetica");
2859         fontDescription.setSpecifiedSize(10);
2860         fontDescription.setComputedSize(10);
2861         fontDescription.setWeight(FontSelectionValue(500));
2862         FontCascade font(WTFMove(fontDescription), 0, 0);
2863         font.update(nullptr);
2864
2865         TextRun textRun = TextRun(touchActionData.name);
2866         imageContext.setFillColor(Color(0, 0, 0, 128));
2867
2868         constexpr float textGap = 4;
2869         constexpr float yOffset = 12;
2870         imageContext.drawText(font, textRun, { textGap, yOffset }, 0);
2871     }
2872
2873     auto tileImage = ImageBuffer::sinkIntoImage(WTFMove(imageBuffer));
2874     auto fillPattern = Pattern::create(tileImage.releaseNonNull(), true, true);
2875     AffineTransform patternOffsetTransform;
2876     patternOffsetTransform.translate(contentOffset + touchActionData.phase);
2877     patternOffsetTransform.scale(1 / destContext.scaleFactor());
2878     fillPattern->setPatternSpaceTransform(patternOffsetTransform);
2879
2880     return fillPattern;
2881 }
2882 #endif // ENABLE(POINTER_EVENTS)
2883
2884 void RenderLayerBacking::paintDebugOverlays(const GraphicsLayer* graphicsLayer, GraphicsContext& context)
2885 {
2886     if (graphicsLayer->eventRegion().isEmpty())
2887         return;
2888
2889     GraphicsContextStateSaver stateSaver(context);
2890
2891     // The region is offset by contentOffsetInCompositingLayer() so undo that.
2892     auto contentOffset = roundedIntSize(contentOffsetInCompositingLayer());
2893     context.translate(-contentOffset);
2894
2895     // The interactive part.
2896     auto& eventRegion = graphicsLayer->eventRegion();
2897     Color regionColor(0, 0, 0, 5);
2898     context.setFillColor(regionColor);
2899     for (auto rect : eventRegion.region().rects())
2900         context.fillRect(rect);
2901
2902 #if ENABLE(POINTER_EVENTS)
2903     const TouchAction touchActionList[] = {
2904         TouchAction::None,
2905         TouchAction::Manipulation,
2906         TouchAction::PanX,
2907         TouchAction::PanY,
2908         TouchAction::PinchZoom,
2909     };
2910
2911     for (auto action : touchActionList) {
2912         auto* actionRegion = graphicsLayer->eventRegion().regionForTouchAction(action);
2913         if (!actionRegion)
2914             continue;
2915
2916         auto fillPattern = patternForTouchAction(action, contentOffsetInCompositingLayer(), context);
2917         if (!fillPattern)
2918             continue;
2919
2920         context.setFillPattern(fillPattern.releaseNonNull());
2921         for (auto rect : actionRegion->rects())
2922             context.fillRect(rect);
2923     }
2924 #endif // ENABLE(POINTER_EVENTS)
2925 }
2926
2927 // Up-call from compositing layer drawing callback.
2928 void RenderLayerBacking::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, OptionSet<GraphicsLayerPaintingPhase> paintingPhase, const FloatRect& clip, GraphicsLayerPaintBehavior layerPaintBehavior)
2929 {
2930 #ifndef NDEBUG
2931     renderer().page().setIsPainting(true);
2932 #endif
2933
2934 #if PLATFORM(MAC)
2935     LocalDefaultSystemAppearance localAppearance(renderer().useDarkAppearance());
2936 #endif
2937
2938     // The dirtyRect is in the coords of the painting root.
2939     FloatRect adjustedClipRect = clip;
2940     adjustedClipRect.move(m_subpixelOffsetFromRenderer);
2941     IntRect dirtyRect = enclosingIntRect(adjustedClipRect);
2942
2943     if (!graphicsLayer->repaintCount())
2944         layerPaintBehavior |= GraphicsLayerPaintFirstTilePaint;
2945
2946     if (graphicsLayer == m_graphicsLayer.get()
2947         || graphicsLayer == m_foregroundLayer.get()
2948         || graphicsLayer == m_backgroundLayer.get()
2949         || graphicsLayer == m_maskLayer.get()
2950         || graphicsLayer == m_childClippingMaskLayer.get()
2951         || graphicsLayer == m_scrolledContentsLayer.get()) {
2952
2953         if (!paintingPhase.contains(GraphicsLayerPaintingPhase::OverflowContents))
2954             dirtyRect.intersect(enclosingIntRect(compositedBoundsIncludingMargin()));
2955
2956         // We have to use the same root as for hit testing, because both methods can compute and cache clipRects.
2957         OptionSet<PaintBehavior> behavior = PaintBehavior::Normal;
2958         if (layerPaintBehavior == GraphicsLayerPaintSnapshotting)
2959             behavior.add(PaintBehavior::Snapshotting);
2960         
2961         if (layerPaintBehavior == GraphicsLayerPaintFirstTilePaint)
2962             behavior.add(PaintBehavior::TileFirstPaint);
2963
2964         paintIntoLayer(graphicsLayer, context, dirtyRect, behavior, paintingPhase);
2965
2966         if (renderer().settings().visibleDebugOverlayRegions() & NonFastScrollableRegion) // Piggy-back off the setting that shows touch handler regions.
2967             paintDebugOverlays(graphicsLayer, context);
2968
2969     } else if (graphicsLayer == layerForHorizontalScrollbar()) {
2970         paintScrollbar(m_owningLayer.horizontalScrollbar(), context, dirtyRect);
2971     } else if (graphicsLayer == layerForVerticalScrollbar()) {
2972         paintScrollbar(m_owningLayer.verticalScrollbar(), context, dirtyRect);
2973     } else if (graphicsLayer == layerForScrollCorner()) {
2974         const LayoutRect& scrollCornerAndResizer = m_owningLayer.scrollCornerAndResizerRect();
2975         GraphicsContextStateSaver stateSaver(context);
2976         context.translate(-scrollCornerAndResizer.location());
2977         LayoutRect transformedClip = LayoutRect(clip);
2978         transformedClip.moveBy(scrollCornerAndResizer.location());
2979         m_owningLayer.paintScrollCorner(context, IntPoint(), snappedIntRect(transformedClip));
2980         m_owningLayer.paintResizer(context, IntPoint(), transformedClip);
2981     }
2982 #ifndef NDEBUG
2983     renderer().page().setIsPainting(false);
2984 #endif
2985 }
2986
2987 float RenderLayerBacking::pageScaleFactor() const
2988 {
2989     return compositor().pageScaleFactor();
2990 }
2991
2992 float RenderLayerBacking::zoomedOutPageScaleFactor() const
2993 {
2994     return compositor().zoomedOutPageScaleFactor();
2995 }
2996
2997 float RenderLayerBacking::deviceScaleFactor() const
2998 {
2999     return compositor().deviceScaleFactor();
3000 }
3001
3002 float RenderLayerBacking::contentsScaleMultiplierForNewTiles(const GraphicsLayer* layer) const
3003 {
3004     return compositor().contentsScaleMultiplierForNewTiles(layer);
3005 }
3006
3007 bool RenderLayerBacking::paintsOpaquelyAtNonIntegralScales(const GraphicsLayer*) const
3008 {
3009     return m_isMainFrameRenderViewLayer;
3010 }
3011
3012 void RenderLayerBacking::didChangePlatformLayerForLayer(const GraphicsLayer* layer)
3013 {
3014     compositor().didChangePlatformLayerForLayer(m_owningLayer, layer);
3015 }
3016
3017 bool RenderLayerBacking::getCurrentTransform(const GraphicsLayer* graphicsLayer, TransformationMatrix& transform) const
3018 {
3019     auto* transformedLayer = m_contentsContainmentLayer.get() ? m_contentsContainmentLayer.get() : m_graphicsLayer.get();
3020     if (graphicsLayer != transformedLayer)
3021         return false;
3022
3023     if (m_owningLayer.hasTransform()) {
3024         transform = m_owningLayer.currentTransform(RenderStyle::ExcludeTransformOrigin);
3025         return true;
3026     }
3027     return false;
3028 }
3029
3030 bool RenderLayerBacking::isTrackingRepaints() const
3031 {
3032     return static_cast<GraphicsLayerClient&>(compositor()).isTrackingRepaints();
3033 }
3034
3035 bool RenderLayerBacking::shouldSkipLayerInDump(const GraphicsLayer* layer, LayerTreeAsTextBehavior behavior) const
3036 {
3037     if (behavior & LayerTreeAsTextDebug)
3038         return false;
3039
3040     // Skip the root tile cache's flattening layer.
3041     return m_isMainFrameRenderViewLayer && layer && layer == m_childContainmentLayer.get();
3042 }
3043
3044 bool RenderLayerBacking::shouldDumpPropertyForLayer(const GraphicsLayer* layer, const char* propertyName, LayerTreeAsTextBehavior flags) const
3045 {
3046     // For backwards compatibility with WebKit1 and other platforms,
3047     // skip some properties on the root tile cache.
3048     if (m_isMainFrameRenderViewLayer && layer == m_graphicsLayer.get() && !(flags & LayerTreeAsTextIncludeRootLayerProperties)) {
3049         if (!strcmp(propertyName, "drawsContent"))
3050             return false;
3051
3052         // Background color could be of interest to tests or other dumpers if it's non-white.
3053         if (!strcmp(propertyName, "backgroundColor") && Color::isWhiteColor(layer->backgroundColor()))
3054             return false;
3055
3056         // The root tile cache's repaints will show up at the top with FrameView's,
3057         // so don't dump them twice.
3058         if (!strcmp(propertyName, "repaintRects"))
3059             return false;
3060     }
3061
3062     return true;
3063 }
3064
3065 bool RenderLayerBacking::shouldAggressivelyRetainTiles(const GraphicsLayer*) const
3066 {
3067     // Only the main frame TileController has enough information about in-window state to
3068     // correctly implement aggressive tile retention.
3069     if (!m_isMainFrameRenderViewLayer)
3070         return false;
3071
3072     return renderer().settings().aggressiveTileRetentionEnabled();
3073 }
3074
3075 bool RenderLayerBacking::shouldTemporarilyRetainTileCohorts(const GraphicsLayer*) const
3076 {
3077     return renderer().settings().temporaryTileCohortRetentionEnabled();
3078 }
3079
3080 bool RenderLayerBacking::useGiantTiles() const
3081 {
3082     return renderer().settings().useGiantTiles();
3083 }
3084
3085 void RenderLayerBacking::logFilledVisibleFreshTile(unsigned blankPixelCount)
3086 {
3087     if (auto* loggingClient = renderer().page().performanceLoggingClient())
3088         loggingClient->logScrollingEvent(PerformanceLoggingClient::ScrollingEvent::FilledTile, MonotonicTime::now(), blankPixelCount);
3089 }
3090
3091 #ifndef NDEBUG
3092 void RenderLayerBacking::verifyNotPainting()
3093 {
3094     ASSERT(!renderer().page().isPainting());
3095 }
3096 #endif
3097
3098 bool RenderLayerBacking::startAnimation(double timeOffset, const Animation& animation, const KeyframeList& keyframes)
3099 {
3100     bool hasOpacity = keyframes.containsProperty(CSSPropertyOpacity);
3101     bool hasTransform = renderer().isBox() && keyframes.containsProperty(CSSPropertyTransform);
3102     bool hasFilter = keyframes.containsProperty(CSSPropertyFilter);
3103
3104     bool hasBackdropFilter = false;
3105 #if ENABLE(FILTERS_LEVEL_2)
3106     hasBackdropFilter = keyframes.containsProperty(CSSPropertyWebkitBackdropFilter);
3107 #endif
3108
3109     if (!hasOpacity && !hasTransform && !hasFilter && !hasBackdropFilter)
3110         return false;
3111
3112     KeyframeValueList transformVector(AnimatedPropertyTransform);
3113     KeyframeValueList opacityVector(AnimatedPropertyOpacity);
3114     KeyframeValueList filterVector(AnimatedPropertyFilter);
3115 #if ENABLE(FILTERS_LEVEL_2)
3116     KeyframeValueList backdropFilterVector(AnimatedPropertyWebkitBackdropFilter);
3117 #endif
3118
3119     size_t numKeyframes = keyframes.size();
3120     for (size_t i = 0; i < numKeyframes; ++i) {
3121         const KeyframeValue& currentKeyframe = keyframes[i];
3122         const RenderStyle* keyframeStyle = currentKeyframe.style();
3123         double key = currentKeyframe.key();
3124
3125         if (!keyframeStyle)
3126             continue;
3127             
3128         auto* tf = currentKeyframe.timingFunction();
3129         
3130         bool isFirstOrLastKeyframe = key == 0 || key == 1;
3131         if ((hasTransform && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyTransform))
3132             transformVector.insert(std::make_unique<TransformAnimationValue>(key, keyframeStyle->transform(), tf));
3133
3134         if ((hasOpacity && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyOpacity))
3135             opacityVector.insert(std::make_unique<FloatAnimationValue>(key, keyframeStyle->opacity(), tf));
3136
3137         if ((hasFilter && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyFilter))
3138             filterVector.insert(std::make_unique<FilterAnimationValue>(key, keyframeStyle->filter(), tf));
3139
3140 #if ENABLE(FILTERS_LEVEL_2)
3141         if ((hasBackdropFilter && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitBackdropFilter))
3142             backdropFilterVector.insert(std::make_unique<FilterAnimationValue>(key, keyframeStyle->backdropFilter(), tf));
3143 #endif
3144     }
3145
3146     if (!renderer().settings().acceleratedCompositedAnimationsEnabled())
3147         return false;
3148
3149     bool didAnimate = false;
3150
3151     if (hasTransform && m_graphicsLayer->addAnimation(transformVector, snappedIntRect(renderBox()->borderBoxRect()).size(), &animation, keyframes.animationName(), timeOffset))
3152         didAnimate = true;
3153
3154     if (hasOpacity && m_graphicsLayer->addAnimation(opacityVector, IntSize { }, &animation, keyframes.animationName(), timeOffset))
3155         didAnimate = true;
3156
3157     if (hasFilter && m_graphicsLayer->addAnimation(filterVector, IntSize { }, &animation, keyframes.animationName(), timeOffset))
3158         didAnimate = true;
3159
3160 #if ENABLE(FILTERS_LEVEL_2)
3161     if (hasBackdropFilter && m_graphicsLayer->addAnimation(backdropFilterVector, IntSize { }, &animation, keyframes.animationName(), timeOffset))
3162         didAnimate = true;
3163 #endif
3164
3165     if (didAnimate)
3166         m_owningLayer.setNeedsPostLayoutCompositingUpdate();
3167
3168     return didAnimate;
3169 }
3170
3171 void RenderLayerBacking::animationPaused(double timeOffset, const String& animationName)
3172 {
3173     m_graphicsLayer->pauseAnimation(animationName, timeOffset);
3174 }
3175
3176 void RenderLayerBacking::animationSeeked(double timeOffset, const String& animationName)
3177 {
3178     m_graphicsLayer->seekAnimation(animationName, timeOffset);
3179 }
3180
3181 void RenderLayerBacking::animationFinished(const String& animationName)
3182 {
3183     m_graphicsLayer->removeAnimation(animationName);
3184     m_owningLayer.setNeedsPostLayoutCompositingUpdate();
3185 }
3186
3187 bool RenderLayerBacking::startTransition(double timeOffset, CSSPropertyID property, const RenderStyle* fromStyle, const RenderStyle* toStyle)
3188 {
3189     bool didAnimate = false;
3190
3191     ASSERT(property != CSSPropertyInvalid);
3192
3193     if (property == CSSPropertyOpacity) {
3194         const Animation* opacityAnim = toStyle->transitionForProperty(CSSPropertyOpacity);
3195         if (opacityAnim && !opacityAnim->isEmptyOrZeroDuration()) {
3196             KeyframeValueList opacityVector(AnimatedPropertyOpacity);
3197             opacityVector.insert(std::make_unique<FloatAnimationValue>(0, compositingOpacity(fromStyle->opacity())));
3198             opacityVector.insert(std::make_unique<FloatAnimationValue>(1, compositingOpacity(toStyle->opacity())));
3199             // The boxSize param is only used for transform animations (which can only run on RenderBoxes), so we pass an empty size here.
3200             if (m_graphicsLayer->addAnimation(opacityVector, FloatSize(), opacityAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyOpacity), timeOffset)) {
3201                 // To ensure that the correct opacity is visible when the animation ends, also set the final opacity.
3202                 updateOpacity(*toStyle);
3203                 didAnimate = true;
3204             }
3205         }
3206     }
3207
3208     if (property == CSSPropertyTransform && m_owningLayer.hasTransform()) {
3209         const Animation* transformAnim = toStyle->transitionForProperty(CSSPropertyTransform);
3210         if (transformAnim && !transformAnim->isEmptyOrZeroDuration()) {
3211             KeyframeValueList transformVector(AnimatedPropertyTransform);
3212             transformVector.insert(std::make_unique<TransformAnimationValue>(0, fromStyle->transform()));
3213             transformVector.insert(std::make_unique<TransformAnimationValue>(1, toStyle->transform()));
3214             if (m_graphicsLayer->addAnimation(transformVector, snappedIntRect(renderBox()->borderBoxRect()).size(), transformAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyTransform), timeOffset)) {
3215                 // To ensure that the correct transform is visible when the animation ends, also set the final transform.
3216                 updateTransform(*toStyle);
3217                 didAnimate = true;
3218             }
3219         }
3220     }
3221
3222     if (property == CSSPropertyFilter && m_owningLayer.hasFilter()) {
3223         const Animation* filterAnim = toStyle->transitionForProperty(CSSPropertyFilter);
3224         if (filterAnim && !filterAnim->isEmptyOrZeroDuration()) {
3225             KeyframeValueList filterVector(AnimatedPropertyFilter);
3226             filterVector.insert(std::make_unique<FilterAnimationValue>(0, fromStyle->filter()));
3227             filterVector.insert(std::make_unique<FilterAnimationValue>(1, toStyle->filter()));
3228             if (m_graphicsLayer->addAnimation(filterVector, FloatSize(), filterAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyFilter), timeOffset)) {
3229                 // To ensure that the correct filter is visible when the animation ends, also set the final filter.
3230                 updateFilters(*toStyle);
3231                 didAnimate = true;
3232             }
3233         }
3234     }
3235
3236 #if ENABLE(FILTERS_LEVEL_2)
3237     if (property == CSSPropertyWebkitBackdropFilter && m_owningLayer.hasBackdropFilter()) {
3238         const Animation* backdropFilterAnim = toStyle->transitionForProperty(CSSPropertyWebkitBackdropFilter);
3239         if (backdropFilterAnim && !backdropFilterAnim->isEmptyOrZeroDuration()) {
3240             KeyframeValueList backdropFilterVector(AnimatedPropertyWebkitBackdropFilter);
3241             backdropFilterVector.insert(std::make_unique<FilterAnimationValue>(0, fromStyle->backdropFilter()));
3242             backdropFilterVector.insert(std::make_unique<FilterAnimationValue>(1, toStyle->backdropFilter()));
3243             if (m_graphicsLayer->addAnimation(backdropFilterVector, FloatSize(), backdropFilterAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyWebkitBackdropFilter), timeOffset)) {
3244                 // To ensure that the correct backdrop filter is visible when the animation ends, also set the final backdrop filter.
3245                 updateBackdropFilters(*toStyle);
3246                 didAnimate = true;
3247             }
3248         }
3249     }
3250 #endif
3251
3252     if (didAnimate)
3253         m_owningLayer.setNeedsPostLayoutCompositingUpdate();
3254
3255     return didAnimate;
3256 }
3257
3258 void RenderLayerBacking::transitionPaused(double timeOffset, CSSPropertyID property)
3259 {
3260     AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
3261     if (animatedProperty != AnimatedPropertyInvalid)
3262         m_graphicsLayer->pauseAnimation(GraphicsLayer::animationNameForTransition(animatedProperty), timeOffset);
3263 }
3264
3265 void RenderLayerBacking::transitionFinished(CSSPropertyID property)
3266 {
3267     AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
3268     if (animatedProperty != AnimatedPropertyInvalid) {
3269         m_graphicsLayer->removeAnimation(GraphicsLayer::animationNameForTransition(animatedProperty));
3270         m_owningLayer.setNeedsPostLayoutCompositingUpdate();
3271     }
3272 }
3273
3274 void RenderLayerBacking::notifyAnimationStarted(const GraphicsLayer*, const String&, MonotonicTime time)
3275 {
3276     renderer().animation().notifyAnimationStarted(renderer(), time);
3277 }
3278
3279 void RenderLayerBacking::notifyFlushRequired(const GraphicsLayer* layer)
3280 {
3281     if (renderer().renderTreeBeingDestroyed())
3282         return;
3283     compositor().scheduleLayerFlush(layer->canThrottleLayerFlush());
3284 }
3285
3286 void RenderLayerBacking::notifyFlushBeforeDisplayRefresh(const GraphicsLayer* layer)
3287 {
3288     compositor().notifyFlushBeforeDisplayRefresh(layer);
3289 }
3290
3291 // This is used for the 'freeze' API, for testing only.
3292 void RenderLayerBacking::suspendAnimations(MonotonicTime time)
3293 {
3294     m_graphicsLayer->suspendAnimations(time);
3295 }
3296
3297 void RenderLayerBacking::resumeAnimations()
3298 {
3299     m_graphicsLayer->resumeAnimations();
3300 }
3301
3302 LayoutRect RenderLayerBacking::compositedBounds() const
3303 {
3304     return m_compositedBounds;
3305 }
3306
3307 bool RenderLayerBacking::setCompositedBounds(const LayoutRect& bounds)
3308 {
3309     if (bounds == m_compositedBounds)
3310         return false;
3311
3312     m_compositedBounds = bounds;
3313     return true;
3314 }
3315
3316 LayoutRect RenderLayerBacking::compositedBoundsIncludingMargin() const
3317 {
3318     auto* tiledBacking = this->tiledBacking();
3319     if (!tiledBacking || !tiledBacking->hasMargins())
3320         return compositedBounds();
3321
3322     LayoutRect boundsIncludingMargin = compositedBounds();
3323     LayoutUnit leftMarginWidth = tiledBacking->leftMarginWidth();
3324     LayoutUnit topMarginHeight = tiledBacking->topMarginHeight();
3325
3326     boundsIncludingMargin.moveBy(LayoutPoint(-leftMarginWidth, -topMarginHeight));
3327     boundsIncludingMargin.expand(leftMarginWidth + tiledBacking->rightMarginWidth(), topMarginHeight + tiledBacking->bottomMarginHeight());
3328
3329     return boundsIncludingMargin;
3330 }
3331
3332 CSSPropertyID RenderLayerBacking::graphicsLayerToCSSProperty(AnimatedPropertyID property)
3333 {
3334     CSSPropertyID cssProperty = CSSPropertyInvalid;
3335     switch (property) {
3336     case AnimatedPropertyTransform:
3337         cssProperty = CSSPropertyTransform;
3338         break;
3339     case AnimatedPropertyOpacity:
3340         cssProperty = CSSPropertyOpacity;
3341         break;
3342     case AnimatedPropertyBackgroundColor:
3343         cssProperty = CSSPropertyBackgroundColor;
3344         break;
3345     case AnimatedPropertyFilter:
3346         cssProperty = CSSPropertyFilter;
3347         break;
3348 #if ENABLE(FILTERS_LEVEL_2)
3349     case AnimatedPropertyWebkitBackdropFilter:
3350         cssProperty = CSSPropertyWebkitBackdropFilter;
3351         break;
3352 #endif
3353     case AnimatedPropertyInvalid:
3354         ASSERT_NOT_REACHED();
3355     }
3356     return cssProperty;
3357 }
3358
3359 AnimatedPropertyID RenderLayerBacking::cssToGraphicsLayerProperty(CSSPropertyID cssProperty)
3360 {
3361     switch (cssProperty) {
3362     case CSSPropertyTransform:
3363         return AnimatedPropertyTransform;
3364     case CSSPropertyOpacity:
3365         return AnimatedPropertyOpacity;
3366     case CSSPropertyBackgroundColor:
3367         return AnimatedPropertyBackgroundColor;
3368     case CSSPropertyFilter:
3369         return AnimatedPropertyFilter;
3370 #if ENABLE(FILTERS_LEVEL_2)
3371     case CSSPropertyWebkitBackdropFilter:
3372         return AnimatedPropertyWebkitBackdropFilter;
3373 #endif
3374     default:
3375         // It's fine if we see other css properties here; they are just not accelerated.
3376         break;
3377     }
3378     return AnimatedPropertyInvalid;
3379 }
3380
3381 CompositingLayerType RenderLayerBacking::compositingLayerType() const
3382 {
3383     if (m_graphicsLayer->usesContentsLayer())
3384         return MediaCompositingLayer;
3385
3386     if (m_graphicsLayer->drawsContent())
3387         return m_graphicsLayer->tiledBacking() ? TiledCompositingLayer : NormalCompositingLayer;
3388     
3389     return ContainerCompositingLayer;
3390 }
3391
3392 double RenderLayerBacking::backingStoreMemoryEstimate() const
3393 {
3394     double backingMemory;
3395     
3396     // Layers in m_ancestorClippingStack, m_contentsContainmentLayer and m_childContainmentLayer are just used for masking or containment, so have no backing.
3397     backingMemory = m_graphicsLayer->backingStoreMemoryEstimate();
3398     if (m_foregroundLayer)
3399         backingMemory += m_foregroundLayer->backingStoreMemoryEstimate();
3400     if (m_backgroundLayer)
3401         backingMemory += m_backgroundLayer->backingStoreMemoryEstimate();
3402     if (m_maskLayer)
3403         backingMemory += m_maskLayer->backingStoreMemoryEstimate();
3404     if (m_childClippingMaskLayer)
3405         backingMemory += m_childClippingMaskLayer->backingStoreMemoryEstimate();
3406
3407     if (m_scrolledContentsLayer)
3408         backingMemory += m_scrolledContentsLayer->backingStoreMemoryEstimate();
3409
3410     if (m_layerForHorizontalScrollbar)
3411         backingMemory += m_layerForHorizontalScrollbar->backingStoreMemoryEstimate();
3412
3413     if (m_layerForVerticalScrollbar)
3414         backingMemory += m_layerForVerticalScrollbar->backingStoreMemoryEstimate();
3415
3416     if (m_layerForScrollCorner)
3417         backingMemory += m_layerForScrollCorner->backingStoreMemoryEstimate();
3418     
3419     return backingMemory;
3420 }
3421
3422 TextStream& operator<<(TextStream& ts, const RenderLayerBacking& backing)
3423 {
3424     ts << "RenderLayerBacking " << &backing << " bounds " << backing.compositedBounds();
3425
3426     if (backing.isFrameLayerWithTiledBacking())
3427         ts << " frame layer tiled backing";
3428     if (backing.paintsIntoWindow())
3429         ts << " paintsIntoWindow";
3430     if (backing.paintsIntoCompositedAncestor())
3431         ts << " paintsIntoCompositedAncestor";
3432
3433     ts << " primary layer ID " << backing.graphicsLayer()->primaryLayerID();
3434     if (auto nodeID = backing.scrollingNodeIDForRole(ScrollCoordinationRole::ViewportConstrained))
3435         ts << " viewport constrained scrolling node " << nodeID;
3436     if (auto nodeID = backing.scrollingNodeIDForRole(ScrollCoordinationRole::Scrolling))
3437         ts << " scrolling node " << nodeID;
3438
3439     if (backing.ancestorClippingStack())
3440         ts << " ancestor clip stack " << *backing.ancestorClippingStack();
3441
3442     if (auto nodeID = backing.scrollingNodeIDForRole(ScrollCoordinationRole::FrameHosting))
3443         ts << " frame hosting node " << nodeID;
3444     if (auto nodeID = backing.scrollingNodeIDForRole(ScrollCoordinationRole::Positioning))
3445         ts << " positioning node " << nodeID;
3446     return ts;
3447 }
3448
3449 } // namespace WebCore