Unreviewed, fix -Wmisleading-indentation warning introduced in r246764
[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().touchActionElements();
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 == BackgroundImageChanged) && canDirectlyCompositeBackgroundBackgroundImage(renderer().style()))
2458         m_owningLayer.setNeedsCompositingConfigurationUpdate();
2459
2460     if ((changeType == MaskImageChanged) && m_maskLayer)
2461         m_owningLayer.setNeedsCompositingConfigurationUpdate();
2462
2463 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
2464     if ((changeType == CanvasChanged || changeType == CanvasPixelsChanged) && renderer().isCanvas() && canvasCompositingStrategy(renderer()) == CanvasAsLayerContents) {
2465         m_graphicsLayer->setContentsNeedsDisplay();
2466         return;
2467     }
2468 #endif
2469 }
2470
2471 void RenderLayerBacking::updateImageContents(PaintedContentsInfo& contentsInfo)
2472 {
2473     auto& imageRenderer = downcast<RenderImage>(renderer());
2474
2475     auto* cachedImage = imageRenderer.cachedImage();
2476     if (!cachedImage)
2477         return;
2478
2479     auto* image = cachedImage->imageForRenderer(&imageRenderer);
2480     if (!image)
2481         return;
2482
2483     // We have to wait until the image is fully loaded before setting it on the layer.
2484     if (!cachedImage->isLoaded())
2485         return;
2486
2487     // This is a no-op if the layer doesn't have an inner layer for the image.
2488     m_graphicsLayer->setContentsRect(snapRectToDevicePixels(contentsBox(), deviceScaleFactor()));
2489
2490     LayoutRect boxRect(LayoutPoint(), imageRenderer.size());
2491     boxRect.move(contentOffsetInCompositingLayer());
2492     FloatRoundedRect contentsClippingRect = renderer().style().getRoundedInnerBorderFor(boxRect).pixelSnappedRoundedRectForPainting(deviceScaleFactor());
2493     m_graphicsLayer->setContentsClippingRect(contentsClippingRect);
2494
2495     m_graphicsLayer->setContentsToImage(image);
2496     
2497     updateDrawsContent(contentsInfo);
2498     
2499     // Image animation is "lazy", in that it automatically stops unless someone is drawing
2500     // the image. So we have to kick the animation each time; this has the downside that the
2501     // image will keep animating, even if its layer is not visible.
2502     image->startAnimation();
2503 }
2504
2505 FloatPoint3D RenderLayerBacking::computeTransformOriginForPainting(const LayoutRect& borderBox) const
2506 {
2507     const RenderStyle& style = renderer().style();
2508     float deviceScaleFactor = this->deviceScaleFactor();
2509
2510     FloatPoint3D origin;
2511     origin.setX(roundToDevicePixel(floatValueForLength(style.transformOriginX(), borderBox.width()), deviceScaleFactor));
2512     origin.setY(roundToDevicePixel(floatValueForLength(style.transformOriginY(), borderBox.height()), deviceScaleFactor));
2513     origin.setZ(style.transformOriginZ());
2514
2515     return origin;
2516 }
2517
2518 // Return the offset from the top-left of this compositing layer at which the renderer's contents are painted.
2519 LayoutSize RenderLayerBacking::contentOffsetInCompositingLayer() const
2520 {
2521     return LayoutSize(-m_compositedBounds.x() + m_compositedBoundsOffsetFromGraphicsLayer.width(), -m_compositedBounds.y() + m_compositedBoundsOffsetFromGraphicsLayer.height());
2522 }
2523
2524 LayoutRect RenderLayerBacking::contentsBox() const
2525 {
2526     if (!is<RenderBox>(renderer()))
2527         return LayoutRect();
2528
2529     auto& renderBox = downcast<RenderBox>(renderer());
2530     LayoutRect contentsRect;
2531 #if ENABLE(VIDEO)
2532     if (is<RenderVideo>(renderBox))
2533         contentsRect = downcast<RenderVideo>(renderBox).videoBox();
2534     else
2535 #endif
2536     if (is<RenderReplaced>(renderBox)) {
2537         RenderReplaced& renderReplaced = downcast<RenderReplaced>(renderBox);
2538         contentsRect = renderReplaced.replacedContentRect();
2539     } else
2540         contentsRect = renderBox.contentBoxRect();
2541
2542     contentsRect.move(contentOffsetInCompositingLayer());
2543     return contentsRect;
2544 }
2545
2546 static LayoutRect backgroundRectForBox(const RenderBox& box)
2547 {
2548     switch (box.style().backgroundClip()) {
2549     case FillBox::Border:
2550         return box.borderBoxRect();
2551     case FillBox::Padding:
2552         return box.paddingBoxRect();
2553     case FillBox::Content:
2554         return box.contentBoxRect();
2555     default:
2556         break;
2557     }
2558
2559     ASSERT_NOT_REACHED();
2560     return LayoutRect();
2561 }
2562
2563 FloatRect RenderLayerBacking::backgroundBoxForSimpleContainerPainting() const
2564 {
2565     if (!is<RenderBox>(renderer()))
2566         return FloatRect();
2567
2568     LayoutRect backgroundBox = backgroundRectForBox(downcast<RenderBox>(renderer()));
2569     backgroundBox.move(contentOffsetInCompositingLayer());
2570     return snapRectToDevicePixels(backgroundBox, deviceScaleFactor());
2571 }
2572
2573 GraphicsLayer* RenderLayerBacking::parentForSublayers() const
2574 {
2575     if (m_scrolledContentsLayer)
2576         return m_scrolledContentsLayer.get();
2577
2578     return m_childContainmentLayer ? m_childContainmentLayer.get() : m_graphicsLayer.get();
2579 }
2580
2581 GraphicsLayer* RenderLayerBacking::childForSuperlayers() const
2582 {
2583     if (m_ancestorClippingStack)
2584         return m_ancestorClippingStack->firstClippingLayer();
2585
2586     if (m_contentsContainmentLayer)
2587         return m_contentsContainmentLayer.get();
2588     
2589     return m_graphicsLayer.get();
2590 }
2591
2592 bool RenderLayerBacking::paintsIntoWindow() const
2593 {
2594 #if USE(COORDINATED_GRAPHICS)
2595         return false;
2596 #endif
2597
2598     if (m_isFrameLayerWithTiledBacking)
2599         return false;
2600
2601     if (m_owningLayer.isRenderViewLayer()) {
2602 #if PLATFORM(IOS_FAMILY) || USE(COORDINATED_GRAPHICS)
2603         if (compositor().inForcedCompositingMode())
2604             return false;
2605 #endif
2606
2607         return compositor().rootLayerAttachment() != RenderLayerCompositor::RootLayerAttachedViaEnclosingFrame;
2608     }
2609     
2610     return false;
2611 }
2612
2613 void RenderLayerBacking::setRequiresOwnBackingStore(bool requiresOwnBacking)
2614 {
2615     if (requiresOwnBacking == m_requiresOwnBackingStore)
2616         return;
2617     
2618     m_requiresOwnBackingStore = requiresOwnBacking;
2619
2620     // This affects the answer to paintsIntoCompositedAncestor(), which in turn affects
2621     // cached clip rects, so when it changes we have to clear clip rects on descendants.
2622     m_owningLayer.clearClipRectsIncludingDescendants(PaintingClipRects);
2623     m_owningLayer.computeRepaintRectsIncludingDescendants();
2624     
2625     compositor().repaintInCompositedAncestor(m_owningLayer, compositedBounds());
2626 }
2627
2628 void RenderLayerBacking::setContentsNeedDisplay(GraphicsLayer::ShouldClipToLayer shouldClip)
2629 {
2630     ASSERT(!paintsIntoCompositedAncestor());
2631
2632     // Use the repaint as a trigger to re-evaluate direct compositing (which is never used on the root layer).
2633     if (!m_owningLayer.isRenderViewLayer())
2634         m_owningLayer.setNeedsCompositingConfigurationUpdate();
2635
2636     m_owningLayer.invalidateEventRegion();
2637
2638     auto& frameView = renderer().view().frameView();
2639     if (m_isMainFrameRenderViewLayer && frameView.isTrackingRepaints())
2640         frameView.addTrackedRepaintRect(owningLayer().absoluteBoundingBoxForPainting());
2641     
2642     if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
2643         // By default, setNeedsDisplay will clip to the size of the GraphicsLayer, which does not include margin tiles.
2644         // So if the TiledBacking has a margin that needs to be invalidated, we need to send in a rect to setNeedsDisplayInRect
2645         // that is large enough to include the margin. TiledBacking::bounds() includes the margin.
2646         auto* tiledBacking = this->tiledBacking();
2647         FloatRect rectToRepaint = tiledBacking ? tiledBacking->bounds() : FloatRect(FloatPoint(0, 0), m_graphicsLayer->size());
2648         m_graphicsLayer->setNeedsDisplayInRect(rectToRepaint, shouldClip);
2649     }
2650     
2651     if (m_foregroundLayer && m_foregroundLayer->drawsContent())
2652         m_foregroundLayer->setNeedsDisplay();
2653
2654     if (m_backgroundLayer && m_backgroundLayer->drawsContent())
2655         m_backgroundLayer->setNeedsDisplay();
2656
2657     if (m_maskLayer && m_maskLayer->drawsContent())
2658         m_maskLayer->setNeedsDisplay();
2659
2660     if (m_childClippingMaskLayer && m_childClippingMaskLayer->drawsContent())
2661         m_childClippingMaskLayer->setNeedsDisplay();
2662
2663     if (m_scrolledContentsLayer && m_scrolledContentsLayer->drawsContent())
2664         m_scrolledContentsLayer->setNeedsDisplay();
2665 }
2666
2667 // r is in the coordinate space of the layer's render object
2668 void RenderLayerBacking::setContentsNeedDisplayInRect(const LayoutRect& r, GraphicsLayer::ShouldClipToLayer shouldClip)
2669 {
2670     ASSERT(!paintsIntoCompositedAncestor());
2671     
2672     // Use the repaint as a trigger to re-evaluate direct compositing (which is never used on the root layer).
2673     if (!m_owningLayer.isRenderViewLayer())
2674         m_owningLayer.setNeedsCompositingConfigurationUpdate();
2675
2676     m_owningLayer.invalidateEventRegion();
2677
2678     FloatRect pixelSnappedRectForPainting = snapRectToDevicePixels(r, deviceScaleFactor());
2679     auto& frameView = renderer().view().frameView();
2680     if (m_isMainFrameRenderViewLayer && frameView.isTrackingRepaints())
2681         frameView.addTrackedRepaintRect(pixelSnappedRectForPainting);
2682
2683     if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
2684         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2685         layerDirtyRect.move(-m_graphicsLayer->offsetFromRenderer() - m_subpixelOffsetFromRenderer);
2686         m_graphicsLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2687     }
2688
2689     if (m_foregroundLayer && m_foregroundLayer->drawsContent()) {
2690         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2691         layerDirtyRect.move(-m_foregroundLayer->offsetFromRenderer() - m_subpixelOffsetFromRenderer);
2692         m_foregroundLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2693     }
2694
2695     // FIXME: need to split out repaints for the background.
2696     if (m_backgroundLayer && m_backgroundLayer->drawsContent()) {
2697         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2698         layerDirtyRect.move(-m_backgroundLayer->offsetFromRenderer() - m_subpixelOffsetFromRenderer);
2699         m_backgroundLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2700     }
2701
2702     if (m_maskLayer && m_maskLayer->drawsContent()) {
2703         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2704         layerDirtyRect.move(-m_maskLayer->offsetFromRenderer() - m_subpixelOffsetFromRenderer);
2705         m_maskLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2706     }
2707
2708     if (m_childClippingMaskLayer && m_childClippingMaskLayer->drawsContent()) {
2709         FloatRect layerDirtyRect = r;
2710         layerDirtyRect.move(-m_childClippingMaskLayer->offsetFromRenderer());
2711         m_childClippingMaskLayer->setNeedsDisplayInRect(layerDirtyRect);
2712     }
2713
2714     if (m_scrolledContentsLayer && m_scrolledContentsLayer->drawsContent()) {
2715         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2716         layerDirtyRect.move(-m_scrolledContentsLayer->offsetFromRenderer() + toLayoutSize(m_scrolledContentsLayer->scrollOffset()) - m_subpixelOffsetFromRenderer);
2717         m_scrolledContentsLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2718     }
2719 }
2720
2721 void RenderLayerBacking::paintIntoLayer(const GraphicsLayer* graphicsLayer, GraphicsContext& context,
2722     const IntRect& paintDirtyRect, // In the coords of rootLayer.
2723     OptionSet<PaintBehavior> paintBehavior, OptionSet<GraphicsLayerPaintingPhase> paintingPhase)
2724 {
2725     if ((paintsIntoWindow() || paintsIntoCompositedAncestor()) && paintingPhase != OptionSet<GraphicsLayerPaintingPhase>(GraphicsLayerPaintingPhase::ChildClippingMask)) {
2726 #if !PLATFORM(IOS_FAMILY) && !OS(WINDOWS)
2727         // FIXME: Looks like the CALayer tree is out of sync with the GraphicsLayer heirarchy
2728         // when pages are restored from the PageCache.
2729         // <rdar://problem/8712587> ASSERT: When Going Back to Page with Plugins in PageCache
2730         ASSERT_NOT_REACHED();
2731 #endif
2732         return;
2733     }
2734
2735     GraphicsContextStateStackChecker checker(context);
2736
2737     OptionSet<RenderLayer::PaintLayerFlag> paintFlags;
2738     if (paintingPhase.contains(GraphicsLayerPaintingPhase::Background))
2739         paintFlags.add(RenderLayer::PaintLayerPaintingCompositingBackgroundPhase);
2740     if (paintingPhase.contains(GraphicsLayerPaintingPhase::Foreground))
2741         paintFlags.add(RenderLayer::PaintLayerPaintingCompositingForegroundPhase);
2742     if (paintingPhase.contains(GraphicsLayerPaintingPhase::Mask))
2743         paintFlags.add(RenderLayer::PaintLayerPaintingCompositingMaskPhase);
2744     if (paintingPhase.contains(GraphicsLayerPaintingPhase::ClipPath))
2745         paintFlags.add(RenderLayer::PaintLayerPaintingCompositingClipPathPhase);
2746     if (paintingPhase.contains(GraphicsLayerPaintingPhase::ChildClippingMask))
2747         paintFlags.add(RenderLayer::PaintLayerPaintingChildClippingMaskPhase);
2748     if (paintingPhase.contains(GraphicsLayerPaintingPhase::OverflowContents))
2749         paintFlags.add(RenderLayer::PaintLayerPaintingOverflowContents);
2750     if (paintingPhase.contains(GraphicsLayerPaintingPhase::CompositedScroll))
2751         paintFlags.add(RenderLayer::PaintLayerPaintingCompositingScrollingPhase);
2752
2753     if (graphicsLayer == m_backgroundLayer.get() && m_backgroundLayerPaintsFixedRootBackground)
2754         paintFlags.add({ RenderLayer::PaintLayerPaintingRootBackgroundOnly, RenderLayer::PaintLayerPaintingCompositingForegroundPhase }); // Need PaintLayerPaintingCompositingForegroundPhase to walk child layers.
2755     else if (compositor().fixedRootBackgroundLayer())
2756         paintFlags.add(RenderLayer::PaintLayerPaintingSkipRootBackground);
2757
2758 #ifndef NDEBUG
2759     RenderElement::SetLayoutNeededForbiddenScope forbidSetNeedsLayout(&renderer());
2760 #endif
2761
2762     auto paintOneLayer = [&](RenderLayer& layer, OptionSet<RenderLayer::PaintLayerFlag> paintFlags) {
2763         InspectorInstrumentation::willPaint(layer.renderer());
2764
2765         FrameView::PaintingState paintingState;
2766         if (layer.isRenderViewLayer())
2767             renderer().view().frameView().willPaintContents(context, paintDirtyRect, paintingState);
2768
2769         RenderLayer::LayerPaintingInfo paintingInfo(&m_owningLayer, paintDirtyRect, paintBehavior, -m_subpixelOffsetFromRenderer);
2770
2771         if (&layer == &m_owningLayer) {
2772             layer.paintLayerContents(context, paintingInfo, paintFlags);
2773
2774             if (layer.containsDirtyOverlayScrollbars())
2775                 layer.paintLayerContents(context, paintingInfo, paintFlags | RenderLayer::PaintLayerPaintingOverlayScrollbars);
2776         } else
2777             layer.paintLayerWithEffects(context, paintingInfo, paintFlags);
2778
2779         if (layer.isRenderViewLayer())
2780             renderer().view().frameView().didPaintContents(context, paintDirtyRect, paintingState);
2781
2782         ASSERT(!m_owningLayer.m_usedTransparency);
2783
2784         InspectorInstrumentation::didPaint(layer.renderer(), paintDirtyRect);
2785     };
2786
2787     paintOneLayer(m_owningLayer, paintFlags);
2788     
2789     // FIXME: Need to check m_foregroundLayer, masking etc. webkit.org/b/197565.
2790     GraphicsLayer* destinationForSharingLayers = m_scrolledContentsLayer ? m_scrolledContentsLayer.get() : m_graphicsLayer.get();
2791
2792     if (graphicsLayer == destinationForSharingLayers) {
2793         OptionSet<RenderLayer::PaintLayerFlag> sharingLayerPaintFlags = {
2794             RenderLayer::PaintLayerPaintingCompositingBackgroundPhase,
2795             RenderLayer::PaintLayerPaintingCompositingForegroundPhase };
2796
2797         if (paintingPhase.contains(GraphicsLayerPaintingPhase::OverflowContents))
2798             sharingLayerPaintFlags.add(RenderLayer::PaintLayerPaintingOverflowContents);
2799
2800         for (auto& layerWeakPtr : m_backingSharingLayers)
2801             paintOneLayer(*layerWeakPtr, sharingLayerPaintFlags);
2802     }
2803
2804     compositor().didPaintBacking(this);
2805 }
2806
2807 #if ENABLE(POINTER_EVENTS)
2808 static RefPtr<Pattern> patternForTouchAction(TouchAction touchAction, FloatSize contentOffset, GraphicsContext& destContext)
2809 {
2810     auto toIndex = [](TouchAction touchAction) -> unsigned {
2811         switch (touchAction) {
2812         case TouchAction::Manipulation:
2813             return 1;
2814         case TouchAction::PanX:
2815             return 2;
2816         case TouchAction::PanY:
2817             return 3;
2818         case TouchAction::PinchZoom:
2819             return 4;
2820         case TouchAction::None:
2821         case TouchAction::Auto:
2822             break;
2823         }
2824         return 0;
2825     };
2826
2827     struct TouchActionAndRGB {
2828         TouchAction action;
2829         ASCIILiteral name;
2830         FloatSize phase;
2831     };
2832     static const TouchActionAndRGB actionsAndColors[] = {
2833         { TouchAction::None, "none"_s, { } },
2834         { TouchAction::Manipulation, "manip"_s, { } },
2835         { TouchAction::PanX, "pan-x"_s, { } },
2836         { TouchAction::PanY, "pan-y"_s, { 0, 9 } },
2837         { TouchAction::PinchZoom, "p-z"_s, { 16, 4.5 } },
2838     };
2839     
2840     auto actionIndex = toIndex(touchAction);
2841     if (!actionIndex || actionIndex >= ARRAY_SIZE(actionsAndColors))
2842         return nullptr;
2843
2844     const FloatSize tileSize { 32, 18 };
2845
2846     auto imageBuffer = ImageBuffer::createCompatibleBuffer(tileSize, ColorSpaceSRGB, destContext);
2847     if (!imageBuffer)
2848         return nullptr;
2849
2850     const auto& touchActionData = actionsAndColors[actionIndex];
2851     {
2852         GraphicsContext& imageContext = imageBuffer->context();
2853
2854         FontCascadeDescription fontDescription;
2855         fontDescription.setOneFamily("Helvetica");
2856         fontDescription.setSpecifiedSize(10);
2857         fontDescription.setComputedSize(10);
2858         fontDescription.setWeight(FontSelectionValue(500));
2859         FontCascade font(WTFMove(fontDescription), 0, 0);
2860         font.update(nullptr);
2861
2862         TextRun textRun = TextRun(touchActionData.name);
2863         imageContext.setFillColor(Color(0, 0, 0, 128));
2864
2865         constexpr float textGap = 4;
2866         constexpr float yOffset = 12;
2867         imageContext.drawText(font, textRun, { textGap, yOffset }, 0);
2868     }
2869
2870     auto tileImage = ImageBuffer::sinkIntoImage(WTFMove(imageBuffer));
2871     auto fillPattern = Pattern::create(tileImage.releaseNonNull(), true, true);
2872     AffineTransform patternOffsetTransform;
2873     patternOffsetTransform.translate(contentOffset + touchActionData.phase);
2874     patternOffsetTransform.scale(1 / destContext.scaleFactor());
2875     fillPattern->setPatternSpaceTransform(patternOffsetTransform);
2876
2877     return fillPattern;
2878 }
2879 #endif // ENABLE(POINTER_EVENTS)
2880
2881 void RenderLayerBacking::paintDebugOverlays(const GraphicsLayer* graphicsLayer, GraphicsContext& context)
2882 {
2883     if (graphicsLayer->eventRegion().isEmpty())
2884         return;
2885
2886     GraphicsContextStateSaver stateSaver(context);
2887
2888     // The region is offset by contentOffsetInCompositingLayer() so undo that.
2889     auto contentOffset = roundedIntSize(contentOffsetInCompositingLayer());
2890     context.translate(-contentOffset);
2891
2892     // The interactive part.
2893     auto& eventRegion = graphicsLayer->eventRegion();
2894     Color regionColor(0, 0, 0, 5);
2895     context.setFillColor(regionColor);
2896     for (auto rect : eventRegion.region().rects())
2897         context.fillRect(rect);
2898
2899 #if ENABLE(POINTER_EVENTS)
2900     const TouchAction touchActionList[] = {
2901         TouchAction::None,
2902         TouchAction::Manipulation,
2903         TouchAction::PanX,
2904         TouchAction::PanY,
2905         TouchAction::PinchZoom,
2906     };
2907
2908     for (auto action : touchActionList) {
2909         auto* actionRegion = graphicsLayer->eventRegion().regionForTouchAction(action);
2910         if (!actionRegion)
2911             continue;
2912
2913         auto fillPattern = patternForTouchAction(action, contentOffsetInCompositingLayer(), context);
2914         if (!fillPattern)
2915             continue;
2916
2917         context.setFillPattern(fillPattern.releaseNonNull());
2918         for (auto rect : actionRegion->rects())
2919             context.fillRect(rect);
2920     }
2921 #endif // ENABLE(POINTER_EVENTS)
2922 }
2923
2924 // Up-call from compositing layer drawing callback.
2925 void RenderLayerBacking::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, OptionSet<GraphicsLayerPaintingPhase> paintingPhase, const FloatRect& clip, GraphicsLayerPaintBehavior layerPaintBehavior)
2926 {
2927 #ifndef NDEBUG
2928     renderer().page().setIsPainting(true);
2929 #endif
2930
2931 #if PLATFORM(MAC)
2932     LocalDefaultSystemAppearance localAppearance(renderer().useDarkAppearance());
2933 #endif
2934
2935     // The dirtyRect is in the coords of the painting root.
2936     FloatRect adjustedClipRect = clip;
2937     adjustedClipRect.move(m_subpixelOffsetFromRenderer);
2938     IntRect dirtyRect = enclosingIntRect(adjustedClipRect);
2939
2940     if (!graphicsLayer->repaintCount())
2941         layerPaintBehavior |= GraphicsLayerPaintFirstTilePaint;
2942
2943     if (graphicsLayer == m_graphicsLayer.get()
2944         || graphicsLayer == m_foregroundLayer.get()
2945         || graphicsLayer == m_backgroundLayer.get()
2946         || graphicsLayer == m_maskLayer.get()
2947         || graphicsLayer == m_childClippingMaskLayer.get()
2948         || graphicsLayer == m_scrolledContentsLayer.get()) {
2949
2950         if (!paintingPhase.contains(GraphicsLayerPaintingPhase::OverflowContents))
2951             dirtyRect.intersect(enclosingIntRect(compositedBoundsIncludingMargin()));
2952
2953         // We have to use the same root as for hit testing, because both methods can compute and cache clipRects.
2954         OptionSet<PaintBehavior> behavior = PaintBehavior::Normal;
2955         if (layerPaintBehavior == GraphicsLayerPaintSnapshotting)
2956             behavior.add(PaintBehavior::Snapshotting);
2957         
2958         if (layerPaintBehavior == GraphicsLayerPaintFirstTilePaint)
2959             behavior.add(PaintBehavior::TileFirstPaint);
2960
2961         paintIntoLayer(graphicsLayer, context, dirtyRect, behavior, paintingPhase);
2962
2963         if (renderer().settings().visibleDebugOverlayRegions() & NonFastScrollableRegion) // Piggy-back off the setting that shows touch handler regions.
2964             paintDebugOverlays(graphicsLayer, context);
2965
2966     } else if (graphicsLayer == layerForHorizontalScrollbar()) {
2967         paintScrollbar(m_owningLayer.horizontalScrollbar(), context, dirtyRect);
2968     } else if (graphicsLayer == layerForVerticalScrollbar()) {
2969         paintScrollbar(m_owningLayer.verticalScrollbar(), context, dirtyRect);
2970     } else if (graphicsLayer == layerForScrollCorner()) {
2971         const LayoutRect& scrollCornerAndResizer = m_owningLayer.scrollCornerAndResizerRect();
2972         GraphicsContextStateSaver stateSaver(context);
2973         context.translate(-scrollCornerAndResizer.location());
2974         LayoutRect transformedClip = LayoutRect(clip);
2975         transformedClip.moveBy(scrollCornerAndResizer.location());
2976         m_owningLayer.paintScrollCorner(context, IntPoint(), snappedIntRect(transformedClip));
2977         m_owningLayer.paintResizer(context, IntPoint(), transformedClip);
2978     }
2979 #ifndef NDEBUG
2980     renderer().page().setIsPainting(false);
2981 #endif
2982 }
2983
2984 float RenderLayerBacking::pageScaleFactor() const
2985 {
2986     return compositor().pageScaleFactor();
2987 }
2988
2989 float RenderLayerBacking::zoomedOutPageScaleFactor() const
2990 {
2991     return compositor().zoomedOutPageScaleFactor();
2992 }
2993
2994 float RenderLayerBacking::deviceScaleFactor() const
2995 {
2996     return compositor().deviceScaleFactor();
2997 }
2998
2999 float RenderLayerBacking::contentsScaleMultiplierForNewTiles(const GraphicsLayer* layer) const
3000 {
3001     return compositor().contentsScaleMultiplierForNewTiles(layer);
3002 }
3003
3004 bool RenderLayerBacking::paintsOpaquelyAtNonIntegralScales(const GraphicsLayer*) const
3005 {
3006     return m_isMainFrameRenderViewLayer;
3007 }
3008
3009 void RenderLayerBacking::didChangePlatformLayerForLayer(const GraphicsLayer* layer)
3010 {
3011     compositor().didChangePlatformLayerForLayer(m_owningLayer, layer);
3012 }
3013
3014 bool RenderLayerBacking::getCurrentTransform(const GraphicsLayer* graphicsLayer, TransformationMatrix& transform) const
3015 {
3016     auto* transformedLayer = m_contentsContainmentLayer.get() ? m_contentsContainmentLayer.get() : m_graphicsLayer.get();
3017     if (graphicsLayer != transformedLayer)
3018         return false;
3019
3020     if (m_owningLayer.hasTransform()) {
3021         transform = m_owningLayer.currentTransform(RenderStyle::ExcludeTransformOrigin);
3022         return true;
3023     }
3024     return false;
3025 }
3026
3027 bool RenderLayerBacking::isTrackingRepaints() const
3028 {
3029     return static_cast<GraphicsLayerClient&>(compositor()).isTrackingRepaints();
3030 }
3031
3032 bool RenderLayerBacking::shouldSkipLayerInDump(const GraphicsLayer* layer, LayerTreeAsTextBehavior behavior) const
3033 {
3034     if (behavior & LayerTreeAsTextDebug)
3035         return false;
3036
3037     // Skip the root tile cache's flattening layer.
3038     return m_isMainFrameRenderViewLayer && layer && layer == m_childContainmentLayer.get();
3039 }
3040
3041 bool RenderLayerBacking::shouldDumpPropertyForLayer(const GraphicsLayer* layer, const char* propertyName, LayerTreeAsTextBehavior flags) const
3042 {
3043     // For backwards compatibility with WebKit1 and other platforms,
3044     // skip some properties on the root tile cache.
3045     if (m_isMainFrameRenderViewLayer && layer == m_graphicsLayer.get() && !(flags & LayerTreeAsTextIncludeRootLayerProperties)) {
3046         if (!strcmp(propertyName, "drawsContent"))
3047             return false;
3048
3049         // Background color could be of interest to tests or other dumpers if it's non-white.
3050         if (!strcmp(propertyName, "backgroundColor") && Color::isWhiteColor(layer->backgroundColor()))
3051             return false;
3052
3053         // The root tile cache's repaints will show up at the top with FrameView's,
3054         // so don't dump them twice.
3055         if (!strcmp(propertyName, "repaintRects"))
3056             return false;
3057     }
3058
3059     return true;
3060 }
3061
3062 bool RenderLayerBacking::shouldAggressivelyRetainTiles(const GraphicsLayer*) const
3063 {
3064     // Only the main frame TileController has enough information about in-window state to
3065     // correctly implement aggressive tile retention.
3066     if (!m_isMainFrameRenderViewLayer)
3067         return false;
3068
3069     return renderer().settings().aggressiveTileRetentionEnabled();
3070 }
3071
3072 bool RenderLayerBacking::shouldTemporarilyRetainTileCohorts(const GraphicsLayer*) const
3073 {
3074     return renderer().settings().temporaryTileCohortRetentionEnabled();
3075 }
3076
3077 bool RenderLayerBacking::useGiantTiles() const
3078 {
3079     return renderer().settings().useGiantTiles();
3080 }
3081
3082 void RenderLayerBacking::logFilledVisibleFreshTile(unsigned blankPixelCount)
3083 {
3084     if (auto* loggingClient = renderer().page().performanceLoggingClient())
3085         loggingClient->logScrollingEvent(PerformanceLoggingClient::ScrollingEvent::FilledTile, MonotonicTime::now(), blankPixelCount);
3086 }
3087
3088 #ifndef NDEBUG
3089 void RenderLayerBacking::verifyNotPainting()
3090 {
3091     ASSERT(!renderer().page().isPainting());
3092 }
3093 #endif
3094
3095 bool RenderLayerBacking::startAnimation(double timeOffset, const Animation& animation, const KeyframeList& keyframes)
3096 {
3097     bool hasOpacity = keyframes.containsProperty(CSSPropertyOpacity);
3098     bool hasTransform = renderer().isBox() && keyframes.containsProperty(CSSPropertyTransform);
3099     bool hasFilter = keyframes.containsProperty(CSSPropertyFilter);
3100
3101     bool hasBackdropFilter = false;
3102 #if ENABLE(FILTERS_LEVEL_2)
3103     hasBackdropFilter = keyframes.containsProperty(CSSPropertyWebkitBackdropFilter);
3104 #endif
3105
3106     if (!hasOpacity && !hasTransform && !hasFilter && !hasBackdropFilter)
3107         return false;
3108
3109     KeyframeValueList transformVector(AnimatedPropertyTransform);
3110     KeyframeValueList opacityVector(AnimatedPropertyOpacity);
3111     KeyframeValueList filterVector(AnimatedPropertyFilter);
3112 #if ENABLE(FILTERS_LEVEL_2)
3113     KeyframeValueList backdropFilterVector(AnimatedPropertyWebkitBackdropFilter);
3114 #endif
3115
3116     size_t numKeyframes = keyframes.size();
3117     for (size_t i = 0; i < numKeyframes; ++i) {
3118         const KeyframeValue& currentKeyframe = keyframes[i];
3119         const RenderStyle* keyframeStyle = currentKeyframe.style();
3120         double key = currentKeyframe.key();
3121
3122         if (!keyframeStyle)
3123             continue;
3124             
3125         auto* tf = currentKeyframe.timingFunction();
3126         
3127         bool isFirstOrLastKeyframe = key == 0 || key == 1;
3128         if ((hasTransform && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyTransform))
3129             transformVector.insert(std::make_unique<TransformAnimationValue>(key, keyframeStyle->transform(), tf));
3130
3131         if ((hasOpacity && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyOpacity))
3132             opacityVector.insert(std::make_unique<FloatAnimationValue>(key, keyframeStyle->opacity(), tf));
3133
3134         if ((hasFilter && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyFilter))
3135             filterVector.insert(std::make_unique<FilterAnimationValue>(key, keyframeStyle->filter(), tf));
3136
3137 #if ENABLE(FILTERS_LEVEL_2)
3138         if ((hasBackdropFilter && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitBackdropFilter))
3139             backdropFilterVector.insert(std::make_unique<FilterAnimationValue>(key, keyframeStyle->backdropFilter(), tf));
3140 #endif
3141     }
3142
3143     if (!renderer().settings().acceleratedCompositedAnimationsEnabled())
3144         return false;
3145
3146     bool didAnimate = false;
3147
3148     if (hasTransform && m_graphicsLayer->addAnimation(transformVector, snappedIntRect(renderBox()->borderBoxRect()).size(), &animation, keyframes.animationName(), timeOffset))
3149         didAnimate = true;
3150
3151     if (hasOpacity && m_graphicsLayer->addAnimation(opacityVector, IntSize { }, &animation, keyframes.animationName(), timeOffset))
3152         didAnimate = true;
3153
3154     if (hasFilter && m_graphicsLayer->addAnimation(filterVector, IntSize { }, &animation, keyframes.animationName(), timeOffset))
3155         didAnimate = true;
3156
3157 #if ENABLE(FILTERS_LEVEL_2)
3158     if (hasBackdropFilter && m_graphicsLayer->addAnimation(backdropFilterVector, IntSize { }, &animation, keyframes.animationName(), timeOffset))
3159         didAnimate = true;
3160 #endif
3161
3162     if (didAnimate)
3163         m_owningLayer.setNeedsPostLayoutCompositingUpdate();
3164
3165     return didAnimate;
3166 }
3167
3168 void RenderLayerBacking::animationPaused(double timeOffset, const String& animationName)
3169 {
3170     m_graphicsLayer->pauseAnimation(animationName, timeOffset);
3171 }
3172
3173 void RenderLayerBacking::animationSeeked(double timeOffset, const String& animationName)
3174 {
3175     m_graphicsLayer->seekAnimation(animationName, timeOffset);
3176 }
3177
3178 void RenderLayerBacking::animationFinished(const String& animationName)
3179 {
3180     m_graphicsLayer->removeAnimation(animationName);
3181     m_owningLayer.setNeedsPostLayoutCompositingUpdate();
3182 }
3183
3184 bool RenderLayerBacking::startTransition(double timeOffset, CSSPropertyID property, const RenderStyle* fromStyle, const RenderStyle* toStyle)
3185 {
3186     bool didAnimate = false;
3187
3188     ASSERT(property != CSSPropertyInvalid);
3189
3190     if (property == CSSPropertyOpacity) {
3191         const Animation* opacityAnim = toStyle->transitionForProperty(CSSPropertyOpacity);
3192         if (opacityAnim && !opacityAnim->isEmptyOrZeroDuration()) {
3193             KeyframeValueList opacityVector(AnimatedPropertyOpacity);
3194             opacityVector.insert(std::make_unique<FloatAnimationValue>(0, compositingOpacity(fromStyle->opacity())));
3195             opacityVector.insert(std::make_unique<FloatAnimationValue>(1, compositingOpacity(toStyle->opacity())));
3196             // The boxSize param is only used for transform animations (which can only run on RenderBoxes), so we pass an empty size here.
3197             if (m_graphicsLayer->addAnimation(opacityVector, FloatSize(), opacityAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyOpacity), timeOffset)) {
3198                 // To ensure that the correct opacity is visible when the animation ends, also set the final opacity.
3199                 updateOpacity(*toStyle);
3200                 didAnimate = true;
3201             }
3202         }
3203     }
3204
3205     if (property == CSSPropertyTransform && m_owningLayer.hasTransform()) {
3206         const Animation* transformAnim = toStyle->transitionForProperty(CSSPropertyTransform);
3207         if (transformAnim && !transformAnim->isEmptyOrZeroDuration()) {
3208             KeyframeValueList transformVector(AnimatedPropertyTransform);
3209             transformVector.insert(std::make_unique<TransformAnimationValue>(0, fromStyle->transform()));
3210             transformVector.insert(std::make_unique<TransformAnimationValue>(1, toStyle->transform()));
3211             if (m_graphicsLayer->addAnimation(transformVector, snappedIntRect(renderBox()->borderBoxRect()).size(), transformAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyTransform), timeOffset)) {
3212                 // To ensure that the correct transform is visible when the animation ends, also set the final transform.
3213                 updateTransform(*toStyle);
3214                 didAnimate = true;
3215             }
3216         }
3217     }
3218
3219     if (property == CSSPropertyFilter && m_owningLayer.hasFilter()) {
3220         const Animation* filterAnim = toStyle->transitionForProperty(CSSPropertyFilter);
3221         if (filterAnim && !filterAnim->isEmptyOrZeroDuration()) {
3222             KeyframeValueList filterVector(AnimatedPropertyFilter);
3223             filterVector.insert(std::make_unique<FilterAnimationValue>(0, fromStyle->filter()));
3224             filterVector.insert(std::make_unique<FilterAnimationValue>(1, toStyle->filter()));
3225             if (m_graphicsLayer->addAnimation(filterVector, FloatSize(), filterAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyFilter), timeOffset)) {
3226                 // To ensure that the correct filter is visible when the animation ends, also set the final filter.
3227                 updateFilters(*toStyle);
3228                 didAnimate = true;
3229             }
3230         }
3231     }
3232
3233 #if ENABLE(FILTERS_LEVEL_2)
3234     if (property == CSSPropertyWebkitBackdropFilter && m_owningLayer.hasBackdropFilter()) {
3235         const Animation* backdropFilterAnim = toStyle->transitionForProperty(CSSPropertyWebkitBackdropFilter);
3236         if (backdropFilterAnim && !backdropFilterAnim->isEmptyOrZeroDuration()) {
3237             KeyframeValueList backdropFilterVector(AnimatedPropertyWebkitBackdropFilter);
3238             backdropFilterVector.insert(std::make_unique<FilterAnimationValue>(0, fromStyle->backdropFilter()));
3239             backdropFilterVector.insert(std::make_unique<FilterAnimationValue>(1, toStyle->backdropFilter()));
3240             if (m_graphicsLayer->addAnimation(backdropFilterVector, FloatSize(), backdropFilterAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyWebkitBackdropFilter), timeOffset)) {
3241                 // To ensure that the correct backdrop filter is visible when the animation ends, also set the final backdrop filter.
3242                 updateBackdropFilters(*toStyle);
3243                 didAnimate = true;
3244             }
3245         }
3246     }
3247 #endif
3248
3249     if (didAnimate)
3250         m_owningLayer.setNeedsPostLayoutCompositingUpdate();
3251
3252     return didAnimate;
3253 }
3254
3255 void RenderLayerBacking::transitionPaused(double timeOffset, CSSPropertyID property)
3256 {
3257     AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
3258     if (animatedProperty != AnimatedPropertyInvalid)
3259         m_graphicsLayer->pauseAnimation(GraphicsLayer::animationNameForTransition(animatedProperty), timeOffset);
3260 }
3261
3262 void RenderLayerBacking::transitionFinished(CSSPropertyID property)
3263 {
3264     AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
3265     if (animatedProperty != AnimatedPropertyInvalid) {
3266         m_graphicsLayer->removeAnimation(GraphicsLayer::animationNameForTransition(animatedProperty));
3267         m_owningLayer.setNeedsPostLayoutCompositingUpdate();
3268     }
3269 }
3270
3271 void RenderLayerBacking::notifyAnimationStarted(const GraphicsLayer*, const String&, MonotonicTime time)
3272 {
3273     renderer().animation().notifyAnimationStarted(renderer(), time);
3274 }
3275
3276 void RenderLayerBacking::notifyFlushRequired(const GraphicsLayer* layer)
3277 {
3278     if (renderer().renderTreeBeingDestroyed())
3279         return;
3280     compositor().scheduleLayerFlush(layer->canThrottleLayerFlush());
3281 }
3282
3283 void RenderLayerBacking::notifyFlushBeforeDisplayRefresh(const GraphicsLayer* layer)
3284 {
3285     compositor().notifyFlushBeforeDisplayRefresh(layer);
3286 }
3287
3288 // This is used for the 'freeze' API, for testing only.
3289 void RenderLayerBacking::suspendAnimations(MonotonicTime time)
3290 {
3291     m_graphicsLayer->suspendAnimations(time);
3292 }
3293
3294 void RenderLayerBacking::resumeAnimations()
3295 {
3296     m_graphicsLayer->resumeAnimations();
3297 }
3298
3299 LayoutRect RenderLayerBacking::compositedBounds() const
3300 {
3301     return m_compositedBounds;
3302 }
3303
3304 bool RenderLayerBacking::setCompositedBounds(const LayoutRect& bounds)
3305 {
3306     if (bounds == m_compositedBounds)
3307         return false;
3308
3309     m_compositedBounds = bounds;
3310     return true;
3311 }
3312
3313 LayoutRect RenderLayerBacking::compositedBoundsIncludingMargin() const
3314 {
3315     auto* tiledBacking = this->tiledBacking();
3316     if (!tiledBacking || !tiledBacking->hasMargins())
3317         return compositedBounds();
3318
3319     LayoutRect boundsIncludingMargin = compositedBounds();
3320     LayoutUnit leftMarginWidth = tiledBacking->leftMarginWidth();
3321     LayoutUnit topMarginHeight = tiledBacking->topMarginHeight();
3322
3323     boundsIncludingMargin.moveBy(LayoutPoint(-leftMarginWidth, -topMarginHeight));
3324     boundsIncludingMargin.expand(leftMarginWidth + tiledBacking->rightMarginWidth(), topMarginHeight + tiledBacking->bottomMarginHeight());
3325
3326     return boundsIncludingMargin;
3327 }
3328
3329 CSSPropertyID RenderLayerBacking::graphicsLayerToCSSProperty(AnimatedPropertyID property)
3330 {
3331     CSSPropertyID cssProperty = CSSPropertyInvalid;
3332     switch (property) {
3333     case AnimatedPropertyTransform:
3334         cssProperty = CSSPropertyTransform;
3335         break;
3336     case AnimatedPropertyOpacity:
3337         cssProperty = CSSPropertyOpacity;
3338         break;
3339     case AnimatedPropertyBackgroundColor:
3340         cssProperty = CSSPropertyBackgroundColor;
3341         break;
3342     case AnimatedPropertyFilter:
3343         cssProperty = CSSPropertyFilter;
3344         break;
3345 #if ENABLE(FILTERS_LEVEL_2)
3346     case AnimatedPropertyWebkitBackdropFilter:
3347         cssProperty = CSSPropertyWebkitBackdropFilter;
3348         break;
3349 #endif
3350     case AnimatedPropertyInvalid: