[iOS WK2] Avoid lots of compositing backing store for offscreen position:fixed descen...
[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::updateAllowsBackingStoreDetaching(const LayoutRect& absoluteBounds)
725 {
726     auto setAllowsBackingStoreDetaching = [&](bool allowDetaching) {
727         m_graphicsLayer->setAllowsBackingStoreDetaching(allowDetaching);
728         if (m_foregroundLayer)
729             m_foregroundLayer->setAllowsBackingStoreDetaching(allowDetaching);
730         if (m_backgroundLayer)
731             m_backgroundLayer->setAllowsBackingStoreDetaching(allowDetaching);
732         if (m_scrolledContentsLayer)
733             m_scrolledContentsLayer->setAllowsBackingStoreDetaching(allowDetaching);
734     };
735
736     if (!m_owningLayer.behavesAsFixed()) {
737         setAllowsBackingStoreDetaching(true);
738         return;
739     }
740
741     // We'll allow detaching if the layer is outside the layout viewport. Fixed layers inside
742     // the layout viewport can be revealed by async scrolling, so we want to pin their backing store.
743     FrameView& frameView = renderer().view().frameView();
744     LayoutRect fixedLayoutRect;
745     if (frameView.useFixedLayout())
746         fixedLayoutRect = renderer().view().unscaledDocumentRect();
747     else
748         fixedLayoutRect = frameView.rectForFixedPositionLayout();
749
750     bool allowDetaching = !fixedLayoutRect.intersects(absoluteBounds);
751     LOG_WITH_STREAM(Compositing, stream << "RenderLayerBacking (layer " << &m_owningLayer << ") updateAllowsBackingStoreDetaching - absoluteBounds " << absoluteBounds << " layoutViewportRect " << fixedLayoutRect << ", allowDetaching " << allowDetaching);
752     setAllowsBackingStoreDetaching(allowDetaching);
753 }
754
755 void RenderLayerBacking::updateAfterWidgetResize()
756 {
757     if (!is<RenderWidget>(renderer()))
758         return;
759
760     if (auto* innerCompositor = RenderLayerCompositor::frameContentsCompositor(downcast<RenderWidget>(renderer()))) {
761         innerCompositor->frameViewDidChangeSize();
762         innerCompositor->frameViewDidChangeLocation(flooredIntPoint(contentsBox().location()));
763     }
764 }
765
766 void RenderLayerBacking::updateAfterLayout(bool needsClippingUpdate, bool needsFullRepaint)
767 {
768     LOG(Compositing, "RenderLayerBacking %p updateAfterLayout (layer %p)", this, &m_owningLayer);
769
770     // This is the main trigger for layout changing layer geometry, but we have to do the work again in updateBackingAndHierarchy()
771     // when we know the final compositing hierarchy. We can't just set dirty bits from RenderLayer::setSize() because that doesn't
772     // take overflow into account.
773     if (updateCompositedBounds()) {
774         m_owningLayer.setNeedsCompositingGeometryUpdate();
775         // This layer's geometry affects those of its children.
776         m_owningLayer.setChildrenNeedCompositingGeometryUpdate();
777     } else if (needsClippingUpdate) {
778         m_owningLayer.setNeedsCompositingConfigurationUpdate();
779         m_owningLayer.setNeedsCompositingGeometryUpdate();
780     }
781     
782     if (needsFullRepaint && canIssueSetNeedsDisplay())
783         setContentsNeedDisplay();
784 }
785
786 // This can only update things that don't require up-to-date layout.
787 void RenderLayerBacking::updateConfigurationAfterStyleChange()
788 {
789     updateMaskingLayer(renderer().hasMask(), renderer().hasClipPath());
790
791     if (m_owningLayer.hasReflection()) {
792         if (m_owningLayer.reflectionLayer()->backing()) {
793             auto* reflectionLayer = m_owningLayer.reflectionLayer()->backing()->graphicsLayer();
794             m_graphicsLayer->setReplicatedByLayer(reflectionLayer);
795         }
796     } else
797         m_graphicsLayer->setReplicatedByLayer(nullptr);
798
799     // FIXME: do we care if opacity is animating?
800     auto& style = renderer().style();
801     updateOpacity(style);
802     updateFilters(style);
803
804 #if ENABLE(FILTERS_LEVEL_2)
805     updateBackdropFilters(style);
806 #endif
807 #if ENABLE(CSS_COMPOSITING)
808     updateBlendMode(style);
809 #endif
810     updateCustomAppearance(style);
811 }
812
813 bool RenderLayerBacking::updateConfiguration()
814 {
815     ASSERT(!m_owningLayer.normalFlowListDirty());
816     ASSERT(!m_owningLayer.zOrderListsDirty());
817     ASSERT(!renderer().view().needsLayout());
818
819     bool layerConfigChanged = false;
820     auto& compositor = this->compositor();
821
822     setBackgroundLayerPaintsFixedRootBackground(compositor.needsFixedRootBackgroundLayer(m_owningLayer));
823
824     if (updateBackgroundLayer(m_backgroundLayerPaintsFixedRootBackground || m_requiresBackgroundLayer))
825         layerConfigChanged = true;
826
827     if (updateForegroundLayer(compositor.needsContentsCompositingLayer(m_owningLayer)))
828         layerConfigChanged = true;
829     
830     bool needsDescendantsClippingLayer = false;
831     bool usesCompositedScrolling = m_owningLayer.hasCompositedScrollableOverflow();
832
833     if (usesCompositedScrolling) {
834         // If it's scrollable, it has to be a box.
835         auto& renderBox = downcast<RenderBox>(renderer());
836         FloatRoundedRect contentsClippingRect = renderer().style().getRoundedInnerBorderFor(renderBox.borderBoxRect()).pixelSnappedRoundedRectForPainting(deviceScaleFactor());
837         needsDescendantsClippingLayer = contentsClippingRect.isRounded();
838     } else
839         needsDescendantsClippingLayer = RenderLayerCompositor::clipsCompositingDescendants(m_owningLayer);
840
841     if (updateScrollingLayers(usesCompositedScrolling))
842         layerConfigChanged = true;
843
844     if (updateDescendantClippingLayer(needsDescendantsClippingLayer))
845         layerConfigChanged = true;
846
847     auto* compositingAncestor = m_owningLayer.ancestorCompositingLayer();
848     if (updateAncestorClipping(compositor.clippedByAncestor(m_owningLayer, compositingAncestor), compositingAncestor))
849         layerConfigChanged = true;
850
851     if (updateOverflowControlsLayers(requiresHorizontalScrollbarLayer(), requiresVerticalScrollbarLayer(), requiresScrollCornerLayer()))
852         layerConfigChanged = true;
853
854     if (layerConfigChanged)
855         updateInternalHierarchy();
856
857     if (auto* flatteningLayer = tileCacheFlatteningLayer()) {
858         if (layerConfigChanged || flatteningLayer->parent() != m_graphicsLayer.get())
859             m_graphicsLayer->addChild(*flatteningLayer);
860     }
861
862     if (updateMaskingLayer(renderer().hasMask(), renderer().hasClipPath()))
863         layerConfigChanged = true;
864
865     updateChildClippingStrategy(needsDescendantsClippingLayer);
866
867     if (m_owningLayer.hasReflection()) {
868         if (m_owningLayer.reflectionLayer()->backing()) {
869             auto* reflectionLayer = m_owningLayer.reflectionLayer()->backing()->graphicsLayer();
870             m_graphicsLayer->setReplicatedByLayer(reflectionLayer);
871         }
872     } else
873         m_graphicsLayer->setReplicatedByLayer(nullptr);
874
875     PaintedContentsInfo contentsInfo(*this);
876
877     // Requires layout.
878     if (!m_owningLayer.isRenderViewLayer()) {
879         bool didUpdateContentsRect = false;
880         updateDirectlyCompositedBoxDecorations(contentsInfo, didUpdateContentsRect);
881     } else
882         updateRootLayerConfiguration();
883
884     // Requires layout.
885     if (contentsInfo.isDirectlyCompositedImage())
886         updateImageContents(contentsInfo);
887
888     if (is<RenderEmbeddedObject>(renderer()) && downcast<RenderEmbeddedObject>(renderer()).allowsAcceleratedCompositing()) {
889         auto* pluginViewBase = downcast<PluginViewBase>(downcast<RenderWidget>(renderer()).widget());
890 #if PLATFORM(IOS_FAMILY)
891         if (pluginViewBase && !m_graphicsLayer->contentsLayerForMedia()) {
892             pluginViewBase->detachPluginLayer();
893             pluginViewBase->attachPluginLayer();
894         }
895 #else
896         if (!pluginViewBase->shouldNotAddLayer())
897             m_graphicsLayer->setContentsToPlatformLayer(pluginViewBase->platformLayer(), GraphicsLayer::ContentsLayerPurpose::Plugin);
898 #endif
899     }
900 #if ENABLE(VIDEO)
901     else if (is<RenderVideo>(renderer()) && downcast<RenderVideo>(renderer()).shouldDisplayVideo()) {
902         auto* mediaElement = downcast<HTMLMediaElement>(renderer().element());
903         m_graphicsLayer->setContentsToPlatformLayer(mediaElement->platformLayer(), GraphicsLayer::ContentsLayerPurpose::Media);
904         // Requires layout.
905         resetContentsRect();
906     }
907 #endif
908 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
909     else if (renderer().isCanvas() && canvasCompositingStrategy(renderer()) == CanvasAsLayerContents) {
910         const HTMLCanvasElement* canvas = downcast<HTMLCanvasElement>(renderer().element());
911         if (auto* context = canvas->renderingContext())
912             m_graphicsLayer->setContentsToPlatformLayer(context->platformLayer(), GraphicsLayer::ContentsLayerPurpose::Canvas);
913
914         layerConfigChanged = true;
915     }
916 #endif
917     if (is<RenderWidget>(renderer()) && compositor.parentFrameContentLayers(downcast<RenderWidget>(renderer()))) {
918         m_owningLayer.setNeedsCompositingGeometryUpdate();
919         layerConfigChanged = true;
920     }
921
922     if (is<RenderImage>(renderer()) && downcast<RenderImage>(renderer()).isEditableImage()) {
923         auto element = renderer().element();
924         if (is<HTMLImageElement>(element)) {
925             m_graphicsLayer->setContentsToEmbeddedView(GraphicsLayer::ContentsLayerEmbeddedViewType::EditableImage, downcast<HTMLImageElement>(element)->editableImageViewID());
926             layerConfigChanged = true;
927         }
928     }
929
930     if (layerConfigChanged)
931         updatePaintingPhases();
932
933     return layerConfigChanged;
934 }
935
936 static LayoutRect clipBox(RenderBox& renderer)
937 {
938     LayoutRect result = LayoutRect::infiniteRect();
939     if (renderer.hasOverflowClip())
940         result = renderer.overflowClipRect(LayoutPoint(), 0); // FIXME: Incorrect for CSS regions.
941
942     if (renderer.hasClip())
943         result.intersect(renderer.clipRect(LayoutPoint(), 0)); // FIXME: Incorrect for CSS regions.
944
945     return result;
946 }
947
948 static bool subpixelOffsetFromRendererChanged(const LayoutSize& oldSubpixelOffsetFromRenderer, const LayoutSize& newSubpixelOffsetFromRenderer, float deviceScaleFactor)
949 {
950     FloatSize previous = snapSizeToDevicePixel(oldSubpixelOffsetFromRenderer, LayoutPoint(), deviceScaleFactor);
951     FloatSize current = snapSizeToDevicePixel(newSubpixelOffsetFromRenderer, LayoutPoint(), deviceScaleFactor);
952     return previous != current;
953 }
954     
955 static FloatSize subpixelForLayerPainting(const LayoutPoint& point, float pixelSnappingFactor)
956 {
957     LayoutUnit x = point.x();
958     LayoutUnit y = point.y();
959     x = x >= 0 ? floorToDevicePixel(x, pixelSnappingFactor) : ceilToDevicePixel(x, pixelSnappingFactor);
960     y = y >= 0 ? floorToDevicePixel(y, pixelSnappingFactor) : ceilToDevicePixel(y, pixelSnappingFactor);
961     return point - LayoutPoint(x, y);
962 }
963
964 struct OffsetFromRenderer {
965     // 1.2px - > { m_devicePixelOffset = 1px m_subpixelOffset = 0.2px }
966     LayoutSize m_devicePixelOffset;
967     LayoutSize m_subpixelOffset;
968 };
969
970 static OffsetFromRenderer computeOffsetFromRenderer(const LayoutSize& offset, float deviceScaleFactor)
971 {
972     OffsetFromRenderer offsetFromRenderer;
973     offsetFromRenderer.m_subpixelOffset = LayoutSize(subpixelForLayerPainting(toLayoutPoint(offset), deviceScaleFactor));
974     offsetFromRenderer.m_devicePixelOffset = offset - offsetFromRenderer.m_subpixelOffset;
975     return offsetFromRenderer;
976 }
977     
978 struct SnappedRectInfo {
979     LayoutRect m_snappedRect;
980     LayoutSize m_snapDelta;
981 };
982     
983 static SnappedRectInfo snappedGraphicsLayer(const LayoutSize& offset, const LayoutSize& size, float deviceScaleFactor)
984 {
985     SnappedRectInfo snappedGraphicsLayer;
986     LayoutRect graphicsLayerRect = LayoutRect(toLayoutPoint(offset), size);
987     snappedGraphicsLayer.m_snappedRect = LayoutRect(snapRectToDevicePixels(graphicsLayerRect, deviceScaleFactor));
988     snappedGraphicsLayer.m_snapDelta = snappedGraphicsLayer.m_snappedRect.location() - toLayoutPoint(offset);
989     return snappedGraphicsLayer;
990 }
991
992 static LayoutSize computeOffsetFromAncestorGraphicsLayer(const RenderLayer* compositedAncestor, const LayoutPoint& location, float deviceScaleFactor)
993 {
994     if (!compositedAncestor)
995         return toLayoutSize(location);
996
997     // FIXME: This is a workaround until after webkit.org/162634 gets fixed. ancestorSubpixelOffsetFromRenderer
998     // could be stale when a dynamic composited state change triggers a pre-order updateGeometry() traversal.
999     LayoutSize ancestorSubpixelOffsetFromRenderer = compositedAncestor->backing()->subpixelOffsetFromRenderer();
1000     LayoutRect ancestorCompositedBounds = compositedAncestor->backing()->compositedBounds();
1001     LayoutSize floored = toLayoutSize(LayoutPoint(floorPointToDevicePixels(ancestorCompositedBounds.location() - ancestorSubpixelOffsetFromRenderer, deviceScaleFactor)));
1002     LayoutSize ancestorRendererOffsetFromAncestorGraphicsLayer = -(floored + ancestorSubpixelOffsetFromRenderer);
1003     return ancestorRendererOffsetFromAncestorGraphicsLayer + toLayoutSize(location);
1004 }
1005
1006 class ComputedOffsets {
1007 public:
1008     ComputedOffsets(const RenderLayer& renderLayer, const LayoutRect& localRect, const LayoutRect& parentGraphicsLayerRect, const LayoutRect& primaryGraphicsLayerRect)
1009         : m_renderLayer(renderLayer)
1010         , m_location(localRect.location())
1011         , m_parentGraphicsLayerOffset(toLayoutSize(parentGraphicsLayerRect.location()))
1012         , m_primaryGraphicsLayerOffset(toLayoutSize(primaryGraphicsLayerRect.location()))
1013         , m_deviceScaleFactor(renderLayer.renderer().document().deviceScaleFactor())
1014     {
1015     }
1016
1017     LayoutSize fromParentGraphicsLayer()
1018     {
1019         if (!m_fromParentGraphicsLayer)
1020             m_fromParentGraphicsLayer = fromAncestorGraphicsLayer() - m_parentGraphicsLayerOffset;
1021         return m_fromParentGraphicsLayer.value();
1022     }
1023     
1024     LayoutSize fromPrimaryGraphicsLayer()
1025     {
1026         if (!m_fromPrimaryGraphicsLayer)
1027             m_fromPrimaryGraphicsLayer = fromAncestorGraphicsLayer() - m_parentGraphicsLayerOffset - m_primaryGraphicsLayerOffset;
1028         return m_fromPrimaryGraphicsLayer.value();
1029     }
1030     
1031 private:
1032     LayoutSize fromAncestorGraphicsLayer()
1033     {
1034         if (!m_fromAncestorGraphicsLayer) {
1035             auto* compositedAncestor = m_renderLayer.ancestorCompositingLayer();
1036             LayoutPoint localPointInAncestorRenderLayerCoords = m_renderLayer.convertToLayerCoords(compositedAncestor, m_location, RenderLayer::AdjustForColumns);
1037             m_fromAncestorGraphicsLayer = computeOffsetFromAncestorGraphicsLayer(compositedAncestor, localPointInAncestorRenderLayerCoords, m_deviceScaleFactor);
1038         }
1039         return m_fromAncestorGraphicsLayer.value();
1040     }
1041
1042     Optional<LayoutSize> m_fromAncestorGraphicsLayer;
1043     Optional<LayoutSize> m_fromParentGraphicsLayer;
1044     Optional<LayoutSize> m_fromPrimaryGraphicsLayer;
1045     
1046     const RenderLayer& m_renderLayer;
1047     // Location is relative to the renderer.
1048     const LayoutPoint m_location;
1049     const LayoutSize m_parentGraphicsLayerOffset;
1050     const LayoutSize m_primaryGraphicsLayerOffset;
1051     float m_deviceScaleFactor;
1052 };
1053
1054 LayoutRect RenderLayerBacking::computePrimaryGraphicsLayerRect(const LayoutRect& parentGraphicsLayerRect) const
1055 {
1056     ComputedOffsets compositedBoundsOffset(m_owningLayer, compositedBounds(), parentGraphicsLayerRect, { });
1057     return LayoutRect(encloseRectToDevicePixels(LayoutRect(toLayoutPoint(compositedBoundsOffset.fromParentGraphicsLayer()), compositedBounds().size()),
1058         deviceScaleFactor()));
1059 }
1060
1061 // FIXME: See if we need this now that updateGeometry() is always called in post-order traversal.
1062 LayoutRect RenderLayerBacking::computeParentGraphicsLayerRect(const RenderLayer* compositedAncestor) const
1063 {
1064     if (!compositedAncestor || !compositedAncestor->backing())
1065         return renderer().view().documentRect();
1066
1067     auto* ancestorBackingLayer = compositedAncestor->backing();
1068     LayoutRect parentGraphicsLayerRect;
1069     if (m_owningLayer.isInsideFragmentedFlow()) {
1070         // FIXME: flows/columns need work.
1071         LayoutRect ancestorCompositedBounds = ancestorBackingLayer->compositedBounds();
1072         ancestorCompositedBounds.setLocation(LayoutPoint());
1073         parentGraphicsLayerRect = ancestorCompositedBounds;
1074     }
1075
1076     if (ancestorBackingLayer->hasClippingLayer()) {
1077         // If the compositing ancestor has a layer to clip children, we parent in that, and therefore position relative to it.
1078         LayoutRect clippingBox = clipBox(downcast<RenderBox>(compositedAncestor->renderer()));
1079         LayoutSize clippingBoxOffset = computeOffsetFromAncestorGraphicsLayer(compositedAncestor, clippingBox.location(), deviceScaleFactor());
1080         parentGraphicsLayerRect = snappedGraphicsLayer(clippingBoxOffset, clippingBox.size(), deviceScaleFactor()).m_snappedRect;
1081     }
1082
1083     if (compositedAncestor->hasCompositedScrollableOverflow()) {
1084         LayoutRect ancestorCompositedBounds = ancestorBackingLayer->compositedBounds();
1085         auto& renderBox = downcast<RenderBox>(compositedAncestor->renderer());
1086         LayoutRect paddingBoxIncludingScrollbar = renderBox.paddingBoxRectIncludingScrollbar();
1087         ScrollOffset scrollOffset = compositedAncestor->scrollOffset();
1088         parentGraphicsLayerRect = LayoutRect((paddingBoxIncludingScrollbar.location() - toLayoutSize(ancestorCompositedBounds.location()) - toLayoutSize(scrollOffset)), paddingBoxIncludingScrollbar.size());
1089     }
1090
1091     return parentGraphicsLayerRect;
1092 }
1093
1094 void RenderLayerBacking::updateGeometry()
1095 {
1096     ASSERT(!m_owningLayer.normalFlowListDirty());
1097     ASSERT(!m_owningLayer.zOrderListsDirty());
1098     ASSERT(!m_owningLayer.descendantDependentFlagsAreDirty());
1099     ASSERT(!renderer().view().needsLayout());
1100
1101     const RenderStyle& style = renderer().style();
1102
1103     bool isRunningAcceleratedTransformAnimation = false;
1104     if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled()) {
1105         if (auto* timeline = renderer().documentTimeline())
1106             isRunningAcceleratedTransformAnimation = timeline->isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyTransform);
1107     } else
1108         isRunningAcceleratedTransformAnimation = renderer().animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyTransform);
1109
1110     updateTransform(style);
1111     updateOpacity(style);
1112     updateFilters(style);
1113 #if ENABLE(FILTERS_LEVEL_2)
1114     updateBackdropFilters(style);
1115 #endif
1116 #if ENABLE(CSS_COMPOSITING)
1117     updateBlendMode(style);
1118 #endif
1119
1120     auto* compositedAncestor = m_owningLayer.ancestorCompositingLayer();
1121     LayoutRect parentGraphicsLayerRect = computeParentGraphicsLayerRect(compositedAncestor);
1122
1123     if (m_ancestorClippingStack) {
1124         // All clipRects in the stack are computed relative to m_owningLayer, so convert them back to compositedAncestor.
1125         auto offsetFromCompositedAncestor = toLayoutSize(m_owningLayer.convertToLayerCoords(compositedAncestor, { }, RenderLayer::AdjustForColumns));
1126         LayoutRect lastClipLayerRect = parentGraphicsLayerRect;
1127
1128         for (auto& entry : m_ancestorClippingStack->stack()) {
1129             auto clipRect = entry.clipData.clipRect;
1130             LayoutSize clippingOffset = computeOffsetFromAncestorGraphicsLayer(compositedAncestor, clipRect.location() + offsetFromCompositedAncestor, deviceScaleFactor());
1131             LayoutRect snappedClippingLayerRect = snappedGraphicsLayer(clippingOffset, clipRect.size(), deviceScaleFactor()).m_snappedRect;
1132
1133             entry.clippingLayer->setPosition(toLayoutPoint(snappedClippingLayerRect.location() - lastClipLayerRect.location()));
1134             lastClipLayerRect = snappedClippingLayerRect;
1135
1136             entry.clippingLayer->setSize(snappedClippingLayerRect.size());
1137
1138             if (entry.clipData.isOverflowScroll) {
1139                 ScrollOffset scrollOffset = entry.clipData.clippingLayer->scrollOffset();
1140
1141                 entry.clippingLayer->setBoundsOrigin(scrollOffset);
1142                 lastClipLayerRect.moveBy(-scrollOffset);
1143             } else
1144                 entry.clippingLayer->setBoundsOrigin({ });
1145         }
1146
1147         parentGraphicsLayerRect = lastClipLayerRect;
1148     }
1149
1150     LayoutRect primaryGraphicsLayerRect = computePrimaryGraphicsLayerRect(parentGraphicsLayerRect);
1151
1152     ComputedOffsets compositedBoundsOffset(m_owningLayer, compositedBounds(), parentGraphicsLayerRect, primaryGraphicsLayerRect);
1153     ComputedOffsets rendererOffset(m_owningLayer, { }, parentGraphicsLayerRect, primaryGraphicsLayerRect);
1154
1155     m_compositedBoundsOffsetFromGraphicsLayer = compositedBoundsOffset.fromPrimaryGraphicsLayer();
1156
1157     auto primaryLayerPosition = primaryGraphicsLayerRect.location();
1158
1159     // FIXME: reflections should force transform-style to be flat in the style: https://bugs.webkit.org/show_bug.cgi?id=106959
1160     bool preserves3D = style.transformStyle3D() == TransformStyle3D::Preserve3D && !renderer().hasReflection();
1161     if (m_contentsContainmentLayer) {
1162         m_contentsContainmentLayer->setPreserves3D(preserves3D);
1163         m_contentsContainmentLayer->setPosition(primaryLayerPosition);
1164         primaryLayerPosition = { };
1165         // Use the same size as m_graphicsLayer so transforms behave correctly.
1166         m_contentsContainmentLayer->setSize(primaryGraphicsLayerRect.size());
1167     }
1168
1169     auto computeAnimationExtent = [&] () -> Optional<FloatRect> {
1170         LayoutRect animatedBounds;
1171         if (isRunningAcceleratedTransformAnimation && m_owningLayer.getOverlapBoundsIncludingChildrenAccountingForTransformAnimations(animatedBounds, RenderLayer::IncludeCompositedDescendants))
1172             return FloatRect(animatedBounds);
1173         return { };
1174     };
1175     m_graphicsLayer->setAnimationExtent(computeAnimationExtent());
1176     m_graphicsLayer->setPreserves3D(preserves3D);
1177     m_graphicsLayer->setBackfaceVisibility(style.backfaceVisibility() == BackfaceVisibility::Visible);
1178
1179     m_graphicsLayer->setPosition(primaryLayerPosition);
1180     m_graphicsLayer->setSize(primaryGraphicsLayerRect.size());
1181
1182     // Compute renderer offset from primary graphics layer. Note that primaryGraphicsLayerRect is in parentGraphicsLayer's coordinate system which is not necessarily
1183     // the same as the ancestor graphics layer.
1184     OffsetFromRenderer primaryGraphicsLayerOffsetFromRenderer;
1185     LayoutSize oldSubpixelOffsetFromRenderer = m_subpixelOffsetFromRenderer;
1186     primaryGraphicsLayerOffsetFromRenderer = computeOffsetFromRenderer(-rendererOffset.fromPrimaryGraphicsLayer(), deviceScaleFactor());
1187     m_subpixelOffsetFromRenderer = primaryGraphicsLayerOffsetFromRenderer.m_subpixelOffset;
1188     m_hasSubpixelRounding = !m_subpixelOffsetFromRenderer.isZero() || compositedBounds().size() != primaryGraphicsLayerRect.size();
1189
1190     if (primaryGraphicsLayerOffsetFromRenderer.m_devicePixelOffset != m_graphicsLayer->offsetFromRenderer()) {
1191         m_graphicsLayer->setOffsetFromRenderer(primaryGraphicsLayerOffsetFromRenderer.m_devicePixelOffset);
1192         positionOverflowControlsLayers();
1193     }
1194
1195     // If we have a layer that clips children, position it.
1196     LayoutRect clippingBox;
1197     if (auto* clipLayer = clippingLayer()) {
1198         // clipLayer is the m_childContainmentLayer.
1199         clippingBox = clipBox(downcast<RenderBox>(renderer()));
1200         // Clipping layer is parented in the primary graphics layer.
1201         LayoutSize clipBoxOffsetFromGraphicsLayer = toLayoutSize(clippingBox.location()) + rendererOffset.fromPrimaryGraphicsLayer();
1202         SnappedRectInfo snappedClippingGraphicsLayer = snappedGraphicsLayer(clipBoxOffsetFromGraphicsLayer, clippingBox.size(), deviceScaleFactor());
1203         clipLayer->setPosition(snappedClippingGraphicsLayer.m_snappedRect.location());
1204         clipLayer->setSize(snappedClippingGraphicsLayer.m_snappedRect.size());
1205         clipLayer->setOffsetFromRenderer(toLayoutSize(clippingBox.location() - snappedClippingGraphicsLayer.m_snapDelta));
1206
1207         if ((renderer().style().clipPath() || renderer().style().hasBorderRadius()) && !m_childClippingMaskLayer) {
1208             LayoutRect boxRect(LayoutPoint(), downcast<RenderBox>(renderer()).size());
1209             FloatRoundedRect contentsClippingRect = renderer().style().getRoundedInnerBorderFor(boxRect).pixelSnappedRoundedRectForPainting(deviceScaleFactor());
1210             contentsClippingRect.move(LayoutSize(-clipLayer->offsetFromRenderer()));
1211             clipLayer->setMasksToBoundsRect(contentsClippingRect);
1212         }
1213
1214         if (m_childClippingMaskLayer && !m_scrollContainerLayer) {
1215             m_childClippingMaskLayer->setSize(clipLayer->size());
1216             m_childClippingMaskLayer->setPosition(FloatPoint());
1217             m_childClippingMaskLayer->setOffsetFromRenderer(clipLayer->offsetFromRenderer());
1218         }
1219     }
1220     
1221     if (m_maskLayer)
1222         updateMaskingLayerGeometry();
1223     
1224     if (renderer().hasTransformRelatedProperty()) {
1225         // Update properties that depend on layer dimensions.
1226         FloatPoint3D transformOrigin = computeTransformOriginForPainting(downcast<RenderBox>(renderer()).borderBoxRect());
1227         FloatPoint layerOffset = roundPointToDevicePixels(toLayoutPoint(rendererOffset.fromParentGraphicsLayer()), deviceScaleFactor());
1228         // Compute the anchor point, which is in the center of the renderer box unless transform-origin is set.
1229         FloatPoint3D anchor(
1230             primaryGraphicsLayerRect.width() ? ((layerOffset.x() - primaryGraphicsLayerRect.x()) + transformOrigin.x()) / primaryGraphicsLayerRect.width() : 0.5,
1231             primaryGraphicsLayerRect.height() ? ((layerOffset.y() - primaryGraphicsLayerRect.y())+ transformOrigin.y()) / primaryGraphicsLayerRect.height() : 0.5,
1232             transformOrigin.z());
1233
1234         if (m_contentsContainmentLayer)
1235             m_contentsContainmentLayer->setAnchorPoint(anchor);
1236         else
1237             m_graphicsLayer->setAnchorPoint(anchor);
1238
1239         auto* clipLayer = clippingLayer();
1240         if (style.hasPerspective()) {
1241             TransformationMatrix t = owningLayer().perspectiveTransform();
1242             
1243             if (clipLayer) {
1244                 clipLayer->setChildrenTransform(t);
1245                 m_graphicsLayer->setChildrenTransform(TransformationMatrix());
1246             }
1247             else
1248                 m_graphicsLayer->setChildrenTransform(t);
1249         } else {
1250             if (clipLayer)
1251                 clipLayer->setChildrenTransform(TransformationMatrix());
1252             else
1253                 m_graphicsLayer->setChildrenTransform(TransformationMatrix());
1254         }
1255     } else {
1256         m_graphicsLayer->setAnchorPoint(FloatPoint3D(0.5, 0.5, 0));
1257         if (m_contentsContainmentLayer)
1258             m_contentsContainmentLayer->setAnchorPoint(FloatPoint3D(0.5, 0.5, 0));
1259     }
1260
1261     if (m_owningLayer.reflectionLayer() && m_owningLayer.reflectionLayer()->isComposited()) {
1262         auto* reflectionBacking = m_owningLayer.reflectionLayer()->backing();
1263         reflectionBacking->updateGeometry();
1264         
1265         // The reflection layer has the bounds of m_owningLayer.reflectionLayer(),
1266         // but the reflected layer is the bounds of this layer, so we need to position it appropriately.
1267         FloatRect layerBounds = this->compositedBounds();
1268         FloatRect reflectionLayerBounds = reflectionBacking->compositedBounds();
1269         reflectionBacking->graphicsLayer()->setReplicatedLayerPosition(FloatPoint(layerBounds.location() - reflectionLayerBounds.location()));
1270     }
1271
1272     if (m_scrollContainerLayer) {
1273         ASSERT(m_scrolledContentsLayer);
1274         auto& renderBox = downcast<RenderBox>(renderer());
1275         LayoutRect paddingBox = renderBox.paddingBoxRect();
1276         LayoutRect parentLayerBounds = clippingLayer() ? clippingBox : compositedBounds();
1277
1278         // FIXME: need to do some pixel snapping here.
1279         m_scrollContainerLayer->setPosition(FloatPoint(paddingBox.location() - parentLayerBounds.location()));
1280         m_scrollContainerLayer->setSize(roundedIntSize(LayoutSize(renderBox.paddingBoxWidth(), renderBox.paddingBoxHeight())));
1281
1282         ScrollOffset scrollOffset = m_owningLayer.scrollOffset();
1283         updateScrollOffset(scrollOffset);
1284
1285         FloatSize oldScrollingLayerOffset = m_scrollContainerLayer->offsetFromRenderer();
1286         m_scrollContainerLayer->setOffsetFromRenderer(toFloatSize(paddingBox.location()));
1287
1288         if (m_childClippingMaskLayer) {
1289             m_childClippingMaskLayer->setPosition(m_scrollContainerLayer->position());
1290             m_childClippingMaskLayer->setSize(m_scrollContainerLayer->size());
1291             m_childClippingMaskLayer->setOffsetFromRenderer(toFloatSize(paddingBox.location()));
1292         }
1293
1294         bool paddingBoxOffsetChanged = oldScrollingLayerOffset != m_scrollContainerLayer->offsetFromRenderer();
1295
1296         IntSize scrollSize(m_owningLayer.scrollWidth(), m_owningLayer.scrollHeight());
1297         if (scrollSize != m_scrolledContentsLayer->size() || paddingBoxOffsetChanged)
1298             m_scrolledContentsLayer->setNeedsDisplay();
1299
1300         m_scrolledContentsLayer->setSize(scrollSize);
1301         m_scrolledContentsLayer->setScrollOffset(scrollOffset, GraphicsLayer::DontSetNeedsDisplay);
1302         m_scrolledContentsLayer->setOffsetFromRenderer(toLayoutSize(paddingBox.location()), GraphicsLayer::DontSetNeedsDisplay);
1303         
1304         adjustTiledBackingCoverage();
1305     }
1306
1307     if (m_foregroundLayer) {
1308         FloatSize foregroundSize;
1309         FloatSize foregroundOffset;
1310         GraphicsLayer::ShouldSetNeedsDisplay needsDisplayOnOffsetChange = GraphicsLayer::SetNeedsDisplay;
1311         if (m_scrolledContentsLayer) {
1312             foregroundSize = m_scrolledContentsLayer->size();
1313             foregroundOffset = m_scrolledContentsLayer->offsetFromRenderer() - toLayoutSize(m_scrolledContentsLayer->scrollOffset());
1314             needsDisplayOnOffsetChange = GraphicsLayer::DontSetNeedsDisplay;
1315         } else if (hasClippingLayer()) {
1316             // If we have a clipping layer (which clips descendants), then the foreground layer is a child of it,
1317             // so that it gets correctly sorted with children. In that case, position relative to the clipping layer.
1318             foregroundSize = FloatSize(clippingBox.size());
1319             foregroundOffset = toFloatSize(clippingBox.location());
1320         } else {
1321             foregroundSize = primaryGraphicsLayerRect.size();
1322             foregroundOffset = m_graphicsLayer->offsetFromRenderer();
1323         }
1324
1325         m_foregroundLayer->setPosition({ });
1326         m_foregroundLayer->setSize(foregroundSize);
1327         m_foregroundLayer->setOffsetFromRenderer(foregroundOffset, needsDisplayOnOffsetChange);
1328     }
1329
1330     if (m_backgroundLayer) {
1331         FloatPoint backgroundPosition;
1332         FloatSize backgroundSize = primaryGraphicsLayerRect.size();
1333         if (backgroundLayerPaintsFixedRootBackground()) {
1334             const FrameView& frameView = renderer().view().frameView();
1335             backgroundPosition = frameView.scrollPositionForFixedPosition();
1336             backgroundSize = frameView.layoutSize();
1337         } else {
1338             auto boundingBox = renderer().objectBoundingBox();
1339             backgroundPosition = boundingBox.location();
1340             backgroundSize = boundingBox.size();
1341         }
1342         m_backgroundLayer->setPosition(backgroundPosition);
1343         m_backgroundLayer->setSize(backgroundSize);
1344         m_backgroundLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
1345     }
1346
1347     // If this layer was created just for clipping or to apply perspective, it doesn't need its own backing store.
1348     LayoutRect ancestorCompositedBounds = compositedAncestor ? compositedAncestor->backing()->compositedBounds() : LayoutRect();
1349     setRequiresOwnBackingStore(compositor().requiresOwnBackingStore(m_owningLayer, compositedAncestor,
1350         LayoutRect(toLayoutPoint(compositedBoundsOffset.fromParentGraphicsLayer()), compositedBounds().size()), ancestorCompositedBounds));
1351 #if ENABLE(FILTERS_LEVEL_2)
1352     updateBackdropFiltersGeometry();
1353 #endif
1354     updateAfterWidgetResize();
1355
1356     if (subpixelOffsetFromRendererChanged(oldSubpixelOffsetFromRenderer, m_subpixelOffsetFromRenderer, deviceScaleFactor()) && canIssueSetNeedsDisplay())
1357         setContentsNeedDisplay();
1358 }
1359
1360 void RenderLayerBacking::setLocationOfScrolledContents(ScrollOffset scrollOffset, ScrollingLayerPositionAction setOrSync)
1361 {
1362     if (setOrSync == ScrollingLayerPositionAction::Sync)
1363         m_scrollContainerLayer->syncBoundsOrigin(scrollOffset);
1364     else
1365         m_scrollContainerLayer->setBoundsOrigin(scrollOffset);
1366 }
1367
1368 void RenderLayerBacking::updateScrollOffset(ScrollOffset scrollOffset)
1369 {
1370     if (m_owningLayer.currentScrollType() == ScrollType::User) {
1371         // If scrolling is happening externally, we don't want to touch the layer bounds origin here because that will cause jitter.
1372         setLocationOfScrolledContents(scrollOffset, ScrollingLayerPositionAction::Sync);
1373         m_owningLayer.setRequiresScrollPositionReconciliation(true);
1374     } else {
1375         // Note that we implement the contents offset via the bounds origin on this layer, rather than a position on the sublayer.
1376         setLocationOfScrolledContents(scrollOffset, ScrollingLayerPositionAction::Set);
1377         m_owningLayer.setRequiresScrollPositionReconciliation(false);
1378     }
1379
1380     ASSERT(m_scrolledContentsLayer->position().isZero());
1381 }
1382
1383 void RenderLayerBacking::updateAfterDescendants()
1384 {
1385     // FIXME: this potentially duplicates work we did in updateConfiguration().
1386     PaintedContentsInfo contentsInfo(*this);
1387     contentsInfo.setWantsSubpixelAntialiasedTextState(GraphicsLayer::supportsSubpixelAntialiasedLayerText() && FontCascade::isSubpixelAntialiasingAvailable());
1388
1389     if (!m_owningLayer.isRenderViewLayer()) {
1390         bool didUpdateContentsRect = false;
1391         updateDirectlyCompositedBoxDecorations(contentsInfo, didUpdateContentsRect);
1392         if (!didUpdateContentsRect && m_graphicsLayer->usesContentsLayer())
1393             resetContentsRect();
1394     }
1395
1396     updateDrawsContent(contentsInfo);
1397
1398     if (!m_isMainFrameRenderViewLayer && !m_isFrameLayerWithTiledBacking && !m_requiresBackgroundLayer) {
1399         // For non-root layers, background is always painted by the primary graphics layer.
1400         ASSERT(!m_backgroundLayer);
1401         m_graphicsLayer->setContentsOpaque(!m_hasSubpixelRounding && m_owningLayer.backgroundIsKnownToBeOpaqueInRect(compositedBounds()));
1402     }
1403
1404     m_graphicsLayer->setContentsVisible(m_owningLayer.hasVisibleContent() || hasVisibleNonCompositedDescendants());
1405     if (m_scrollContainerLayer) {
1406         m_scrollContainerLayer->setContentsVisible(renderer().style().visibility() == Visibility::Visible);
1407         m_scrollContainerLayer->setUserInteractionEnabled(renderer().style().pointerEvents() != PointerEvents::None);
1408     }
1409 }
1410
1411 // FIXME: Avoid repaints when clip path changes.
1412 void RenderLayerBacking::updateMaskingLayerGeometry()
1413 {
1414     m_maskLayer->setSize(m_graphicsLayer->size());
1415     m_maskLayer->setPosition(FloatPoint());
1416     m_maskLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
1417     
1418     if (!m_maskLayer->drawsContent()) {
1419         if (renderer().hasClipPath()) {
1420             ASSERT(renderer().style().clipPath()->type() != ClipPathOperation::Reference);
1421
1422             WindRule windRule;
1423             // FIXME: Use correct reference box for inlines: https://bugs.webkit.org/show_bug.cgi?id=129047
1424             LayoutRect boundingBox = m_owningLayer.boundingBox(&m_owningLayer);
1425             LayoutRect referenceBoxForClippedInline = LayoutRect(snapRectToDevicePixels(boundingBox, deviceScaleFactor()));
1426             LayoutSize offset = LayoutSize(snapSizeToDevicePixel(-m_subpixelOffsetFromRenderer, LayoutPoint(), deviceScaleFactor()));
1427             Path clipPath = m_owningLayer.computeClipPath(offset, referenceBoxForClippedInline, windRule);
1428
1429             FloatSize pathOffset = m_maskLayer->offsetFromRenderer();
1430             if (!pathOffset.isZero())
1431                 clipPath.translate(-pathOffset);
1432             
1433             m_maskLayer->setShapeLayerPath(clipPath);
1434             m_maskLayer->setShapeLayerWindRule(windRule);
1435         }
1436     }
1437 }
1438
1439 void RenderLayerBacking::updateDirectlyCompositedBoxDecorations(PaintedContentsInfo& contentsInfo, bool& didUpdateContentsRect)
1440 {
1441     if (!m_owningLayer.hasVisibleContent())
1442         return;
1443
1444     // The order of operations here matters, since the last valid type of contents needs
1445     // to also update the contentsRect.
1446     updateDirectlyCompositedBackgroundColor(contentsInfo, didUpdateContentsRect);
1447     updateDirectlyCompositedBackgroundImage(contentsInfo, didUpdateContentsRect);
1448 }
1449
1450 void RenderLayerBacking::updateInternalHierarchy()
1451 {
1452     // m_foregroundLayer has to be inserted in the correct order with child layers,
1453     // so it's not inserted here.
1454     GraphicsLayer* lastClippingLayer = nullptr;
1455     if (m_ancestorClippingStack) {
1456         auto& clippingStack = m_ancestorClippingStack->stack();
1457         for (unsigned i = 0; i < clippingStack.size() - 1; ++i) {
1458             auto& entry = clippingStack.at(i);
1459             Vector<Ref<GraphicsLayer>> children;
1460             children.append(*clippingStack.at(i + 1).clippingLayer);
1461             entry.clippingLayer->setChildren(WTFMove(children));
1462         }
1463         
1464         lastClippingLayer = clippingStack.last().clippingLayer.get();
1465         lastClippingLayer->removeAllChildren();
1466     }
1467     
1468     if (m_contentsContainmentLayer) {
1469         m_contentsContainmentLayer->removeAllChildren();
1470         if (lastClippingLayer)
1471             lastClippingLayer->addChild(*m_contentsContainmentLayer);
1472     }
1473     
1474     if (m_backgroundLayer)
1475         m_contentsContainmentLayer->addChild(*m_backgroundLayer);
1476
1477     if (m_contentsContainmentLayer)
1478         m_contentsContainmentLayer->addChild(*m_graphicsLayer);
1479     else if (lastClippingLayer)
1480         lastClippingLayer->addChild(*m_graphicsLayer);
1481
1482     if (m_childContainmentLayer)
1483         m_graphicsLayer->addChild(*m_childContainmentLayer);
1484
1485     if (m_scrollContainerLayer) {
1486         auto* superlayer = m_childContainmentLayer ? m_childContainmentLayer.get() : m_graphicsLayer.get();
1487         superlayer->addChild(*m_scrollContainerLayer);
1488     }
1489
1490     // The clip for child layers does not include space for overflow controls, so they exist as
1491     // siblings of the clipping layer if we have one. Normal children of this layer are set as
1492     // children of the clipping layer.
1493     if (m_layerForHorizontalScrollbar)
1494         m_graphicsLayer->addChild(*m_layerForHorizontalScrollbar);
1495
1496     if (m_layerForVerticalScrollbar)
1497         m_graphicsLayer->addChild(*m_layerForVerticalScrollbar);
1498
1499     if (m_layerForScrollCorner)
1500         m_graphicsLayer->addChild(*m_layerForScrollCorner);
1501 }
1502
1503 void RenderLayerBacking::resetContentsRect()
1504 {
1505     m_graphicsLayer->setContentsRect(snapRectToDevicePixels(contentsBox(), deviceScaleFactor()));
1506     
1507     if (is<RenderBox>(renderer())) {
1508         LayoutRect boxRect(LayoutPoint(), downcast<RenderBox>(renderer()).size());
1509         boxRect.move(contentOffsetInCompositingLayer());
1510         FloatRoundedRect contentsClippingRect = renderer().style().getRoundedInnerBorderFor(boxRect).pixelSnappedRoundedRectForPainting(deviceScaleFactor());
1511         m_graphicsLayer->setContentsClippingRect(contentsClippingRect);
1512     }
1513
1514     m_graphicsLayer->setContentsTileSize(IntSize());
1515     m_graphicsLayer->setContentsTilePhase(IntSize());
1516 }
1517
1518 void RenderLayerBacking::updateDrawsContent()
1519 {
1520     PaintedContentsInfo contentsInfo(*this);
1521     contentsInfo.setWantsSubpixelAntialiasedTextState(GraphicsLayer::supportsSubpixelAntialiasedLayerText());
1522
1523     updateDrawsContent(contentsInfo);
1524 }
1525
1526 void RenderLayerBacking::updateDrawsContent(PaintedContentsInfo& contentsInfo)
1527 {
1528     if (m_scrollContainerLayer) {
1529         // We don't have to consider overflow controls, because we know that the scrollbars are drawn elsewhere.
1530         // m_graphicsLayer only needs backing store if the non-scrolling parts (background, outlines, borders, shadows etc) need to paint.
1531         // m_scrollContainerLayer never has backing store.
1532         // m_scrolledContentsLayer only needs backing store if the scrolled contents need to paint.
1533         bool hasNonScrollingPaintedContent = m_owningLayer.hasVisibleContent() && m_owningLayer.hasVisibleBoxDecorationsOrBackground();
1534         m_graphicsLayer->setDrawsContent(hasNonScrollingPaintedContent);
1535
1536         bool hasScrollingPaintedContent = hasBackingSharingLayers() || (m_owningLayer.hasVisibleContent() && (renderer().hasBackground() || contentsInfo.paintsContent()));
1537         m_scrolledContentsLayer->setDrawsContent(hasScrollingPaintedContent);
1538         return;
1539     }
1540
1541     bool hasPaintedContent = containsPaintedContent(contentsInfo);
1542
1543     m_paintsSubpixelAntialiasedText = renderer().settings().subpixelAntialiasedLayerTextEnabled() && contentsInfo.paintsSubpixelAntialiasedText();
1544
1545     // FIXME: we could refine this to only allocate backing for one of these layers if possible.
1546     m_graphicsLayer->setDrawsContent(hasPaintedContent);
1547     if (m_foregroundLayer) {
1548         m_foregroundLayer->setDrawsContent(hasPaintedContent);
1549         m_foregroundLayer->setSupportsSubpixelAntialiasedText(m_paintsSubpixelAntialiasedText);
1550         // The text content is painted into the foreground layer.
1551         // FIXME: this ignores SVG background images which may contain text.
1552         m_graphicsLayer->setSupportsSubpixelAntialiasedText(false);
1553     } else
1554         m_graphicsLayer->setSupportsSubpixelAntialiasedText(m_paintsSubpixelAntialiasedText);
1555
1556     if (m_backgroundLayer)
1557         m_backgroundLayer->setDrawsContent(m_backgroundLayerPaintsFixedRootBackground ? hasPaintedContent : contentsInfo.paintsBoxDecorations());
1558 }
1559
1560 void RenderLayerBacking::updateEventRegion()
1561 {
1562 #if PLATFORM(IOS_FAMILY)
1563     if (paintsIntoCompositedAncestor())
1564         return;
1565
1566     bool hasTouchActionElements = false;
1567 #if ENABLE(POINTER_EVENTS)
1568     hasTouchActionElements = renderer().document().mayHaveElementsWithNonAutoTouchAction();
1569 #endif
1570     if (m_owningLayer.isRenderViewLayer() && !hasTouchActionElements)
1571         return;
1572
1573     GraphicsContext nullContext(nullptr);
1574     RenderLayer::LayerPaintingInfo paintingInfo(&m_owningLayer, compositedBounds(), { }, LayoutSize());
1575
1576     EventRegion eventRegion;
1577     auto eventRegionContext = eventRegion.makeContext();
1578     paintingInfo.eventRegionContext = &eventRegionContext;
1579
1580     auto paintFlags = RenderLayer::paintLayerPaintingCompositingAllPhasesFlags() | RenderLayer::PaintLayerCollectingEventRegion;
1581     m_owningLayer.paintLayerContents(nullContext, paintingInfo, paintFlags);
1582
1583     for (auto& layer : m_backingSharingLayers)
1584         layer->paintLayerWithEffects(nullContext, paintingInfo, paintFlags);
1585
1586     GraphicsLayer& layerForEventRegion = m_scrolledContentsLayer ? *m_scrolledContentsLayer : *m_graphicsLayer;
1587
1588     auto layerOffset = toIntSize(layerForEventRegion.scrollOffset()) - roundedIntSize(layerForEventRegion.offsetFromRenderer());
1589     eventRegion.translate(layerOffset);
1590
1591     layerForEventRegion.setEventRegion(WTFMove(eventRegion));
1592 #endif
1593 }
1594
1595 bool RenderLayerBacking::updateAncestorClippingStack(Vector<CompositedClipData>&& clippingData)
1596 {
1597     if (!m_ancestorClippingStack && clippingData.isEmpty())
1598         return false;
1599
1600     auto* scrollingCoordinator = m_owningLayer.page().scrollingCoordinator();
1601
1602     if (m_ancestorClippingStack && clippingData.isEmpty()) {
1603         m_ancestorClippingStack->clear(scrollingCoordinator);
1604         m_ancestorClippingStack = nullptr;
1605         return true;
1606     }
1607     
1608     if (!m_ancestorClippingStack) {
1609         m_ancestorClippingStack = std::make_unique<LayerAncestorClippingStack>(WTFMove(clippingData));
1610         LOG_WITH_STREAM(Compositing, stream << "layer " << &m_owningLayer << " ancestorClippingStack " << *m_ancestorClippingStack);
1611         return true;
1612     }
1613     
1614     if (m_ancestorClippingStack->equalToClipData(clippingData)) {
1615         LOG_WITH_STREAM(Compositing, stream << "layer " << &m_owningLayer << " ancestorClippingStack " << *m_ancestorClippingStack);
1616         return false;
1617     }
1618     
1619     m_ancestorClippingStack->updateWithClipData(scrollingCoordinator, WTFMove(clippingData));
1620     LOG_WITH_STREAM(Compositing, stream << "layer " << &m_owningLayer << " ancestorClippingStack " << *m_ancestorClippingStack);
1621     return true;
1622 }
1623
1624 // Return true if the layer changed.
1625 bool RenderLayerBacking::updateAncestorClipping(bool needsAncestorClip, const RenderLayer* compositingAncestor)
1626 {
1627     bool layersChanged = false;
1628
1629     if (needsAncestorClip) {
1630         if (compositor().updateAncestorClippingStack(m_owningLayer, compositingAncestor)) {
1631             // Make any layers we don't have.
1632             if (m_ancestorClippingStack) {
1633                 for (auto& entry : m_ancestorClippingStack->stack()) {
1634                     if (!entry.clippingLayer) {
1635                         entry.clippingLayer = createGraphicsLayer(entry.clipData.isOverflowScroll ? "clip for scroller" : "ancestor clipping");
1636                         entry.clippingLayer->setMasksToBounds(true);
1637                         entry.clippingLayer->setPaintingPhase({ });
1638                     }
1639                 }
1640             }
1641
1642             layersChanged = true;
1643         }
1644     } else if (m_ancestorClippingStack) {
1645         for (auto& entry : m_ancestorClippingStack->stack())
1646             GraphicsLayer::unparentAndClear(entry.clippingLayer);
1647
1648         m_ancestorClippingStack = nullptr;
1649         layersChanged = true;
1650     }
1651     
1652     return layersChanged;
1653 }
1654
1655 // Return true if the layer changed.
1656 bool RenderLayerBacking::updateDescendantClippingLayer(bool needsDescendantClip)
1657 {
1658     bool layersChanged = false;
1659
1660     if (needsDescendantClip) {
1661         if (!m_childContainmentLayer && !m_isFrameLayerWithTiledBacking) {
1662             m_childContainmentLayer = createGraphicsLayer("child clipping");
1663             m_childContainmentLayer->setMasksToBounds(true);
1664             layersChanged = true;
1665         }
1666     } else if (hasClippingLayer()) {
1667         willDestroyLayer(m_childContainmentLayer.get());
1668         GraphicsLayer::unparentAndClear(m_childContainmentLayer);
1669         layersChanged = true;
1670     }
1671     
1672     return layersChanged;
1673 }
1674
1675 void RenderLayerBacking::setBackgroundLayerPaintsFixedRootBackground(bool backgroundLayerPaintsFixedRootBackground)
1676 {
1677     if (backgroundLayerPaintsFixedRootBackground == m_backgroundLayerPaintsFixedRootBackground)
1678         return;
1679
1680     m_backgroundLayerPaintsFixedRootBackground = backgroundLayerPaintsFixedRootBackground;
1681
1682     if (m_backgroundLayerPaintsFixedRootBackground) {
1683         ASSERT(m_isFrameLayerWithTiledBacking);
1684         renderer().view().frameView().removeSlowRepaintObject(*renderer().view().rendererForRootBackground());
1685     }
1686 }
1687
1688 void RenderLayerBacking::setRequiresBackgroundLayer(bool requiresBackgroundLayer)
1689 {
1690     if (requiresBackgroundLayer == m_requiresBackgroundLayer)
1691         return;
1692
1693     m_requiresBackgroundLayer = requiresBackgroundLayer;
1694     m_owningLayer.setNeedsCompositingConfigurationUpdate();
1695 }
1696
1697 bool RenderLayerBacking::requiresHorizontalScrollbarLayer() const
1698 {
1699     if (!m_owningLayer.hasOverlayScrollbars())
1700         return false;
1701     return m_owningLayer.horizontalScrollbar();
1702 }
1703
1704 bool RenderLayerBacking::requiresVerticalScrollbarLayer() const
1705 {
1706     if (!m_owningLayer.hasOverlayScrollbars())
1707         return false;
1708     return m_owningLayer.verticalScrollbar();
1709 }
1710
1711 bool RenderLayerBacking::requiresScrollCornerLayer() const
1712 {
1713     if (!m_owningLayer.hasOverlayScrollbars())
1714         return false;
1715     return !m_owningLayer.scrollCornerAndResizerRect().isEmpty();
1716 }
1717
1718 bool RenderLayerBacking::updateOverflowControlsLayers(bool needsHorizontalScrollbarLayer, bool needsVerticalScrollbarLayer, bool needsScrollCornerLayer)
1719 {
1720     bool horizontalScrollbarLayerChanged = false;
1721     if (needsHorizontalScrollbarLayer) {
1722         if (!m_layerForHorizontalScrollbar) {
1723             m_layerForHorizontalScrollbar = createGraphicsLayer("horizontal scrollbar");
1724             m_layerForHorizontalScrollbar->setAllowsBackingStoreDetaching(false);
1725             horizontalScrollbarLayerChanged = true;
1726         }
1727     } else if (m_layerForHorizontalScrollbar) {
1728         willDestroyLayer(m_layerForHorizontalScrollbar.get());
1729         GraphicsLayer::unparentAndClear(m_layerForHorizontalScrollbar);
1730         horizontalScrollbarLayerChanged = true;
1731     }
1732
1733     bool verticalScrollbarLayerChanged = false;
1734     if (needsVerticalScrollbarLayer) {
1735         if (!m_layerForVerticalScrollbar) {
1736             m_layerForVerticalScrollbar = createGraphicsLayer("vertical scrollbar");
1737             m_layerForVerticalScrollbar->setAllowsBackingStoreDetaching(false);
1738             verticalScrollbarLayerChanged = true;
1739         }
1740     } else if (m_layerForVerticalScrollbar) {
1741         willDestroyLayer(m_layerForVerticalScrollbar.get());
1742         GraphicsLayer::unparentAndClear(m_layerForVerticalScrollbar);
1743         verticalScrollbarLayerChanged = true;
1744     }
1745
1746     bool scrollCornerLayerChanged = false;
1747     if (needsScrollCornerLayer) {
1748         if (!m_layerForScrollCorner) {
1749             m_layerForScrollCorner = createGraphicsLayer("scroll corner");
1750             m_layerForScrollCorner->setAllowsBackingStoreDetaching(false);
1751             scrollCornerLayerChanged = true;
1752         }
1753     } else if (m_layerForScrollCorner) {
1754         willDestroyLayer(m_layerForScrollCorner.get());
1755         GraphicsLayer::unparentAndClear(m_layerForScrollCorner);
1756         scrollCornerLayerChanged = true;
1757     }
1758
1759     if (auto* scrollingCoordinator = m_owningLayer.page().scrollingCoordinator()) {
1760         if (horizontalScrollbarLayerChanged)
1761             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_owningLayer, HorizontalScrollbar);
1762         if (verticalScrollbarLayerChanged)
1763             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_owningLayer, VerticalScrollbar);
1764     }
1765
1766     return horizontalScrollbarLayerChanged || verticalScrollbarLayerChanged || scrollCornerLayerChanged;
1767 }
1768
1769 void RenderLayerBacking::positionOverflowControlsLayers()
1770 {
1771     if (!m_owningLayer.hasScrollbars())
1772         return;
1773
1774     const IntRect borderBox = snappedIntRect(renderBox()->borderBoxRect());
1775
1776     FloatSize offsetFromRenderer = m_graphicsLayer->offsetFromRenderer();
1777     if (auto* layer = layerForHorizontalScrollbar()) {
1778         IntRect hBarRect = m_owningLayer.rectForHorizontalScrollbar(borderBox);
1779         layer->setPosition(hBarRect.location() - offsetFromRenderer);
1780         layer->setSize(hBarRect.size());
1781         if (layer->usesContentsLayer()) {
1782             IntRect barRect = IntRect(IntPoint(), hBarRect.size());
1783             layer->setContentsRect(barRect);
1784             layer->setContentsClippingRect(FloatRoundedRect(barRect));
1785         }
1786         layer->setDrawsContent(m_owningLayer.horizontalScrollbar() && !layer->usesContentsLayer());
1787     }
1788     
1789     if (auto* layer = layerForVerticalScrollbar()) {
1790         IntRect vBarRect = m_owningLayer.rectForVerticalScrollbar(borderBox);
1791         layer->setPosition(vBarRect.location() - offsetFromRenderer);
1792         layer->setSize(vBarRect.size());
1793         if (layer->usesContentsLayer()) {
1794             IntRect barRect = IntRect(IntPoint(), vBarRect.size());
1795             layer->setContentsRect(barRect);
1796             layer->setContentsClippingRect(FloatRoundedRect(barRect));
1797         }
1798         layer->setDrawsContent(m_owningLayer.verticalScrollbar() && !layer->usesContentsLayer());
1799     }
1800
1801     if (auto* layer = layerForScrollCorner()) {
1802         const LayoutRect& scrollCornerAndResizer = m_owningLayer.scrollCornerAndResizerRect();
1803         layer->setPosition(scrollCornerAndResizer.location() - offsetFromRenderer);
1804         layer->setSize(scrollCornerAndResizer.size());
1805         layer->setDrawsContent(!scrollCornerAndResizer.isEmpty());
1806     }
1807 }
1808
1809 bool RenderLayerBacking::updateForegroundLayer(bool needsForegroundLayer)
1810 {
1811     bool layerChanged = false;
1812     if (needsForegroundLayer) {
1813         if (!m_foregroundLayer) {
1814             String layerName = m_owningLayer.name() + " (foreground)";
1815             m_foregroundLayer = createGraphicsLayer(layerName);
1816             m_foregroundLayer->setDrawsContent(true);
1817             layerChanged = true;
1818         }
1819     } else if (m_foregroundLayer) {
1820         willDestroyLayer(m_foregroundLayer.get());
1821         GraphicsLayer::unparentAndClear(m_foregroundLayer);
1822         layerChanged = true;
1823     }
1824
1825     return layerChanged;
1826 }
1827
1828 bool RenderLayerBacking::updateBackgroundLayer(bool needsBackgroundLayer)
1829 {
1830     bool layerChanged = false;
1831     if (needsBackgroundLayer) {
1832         if (!m_backgroundLayer) {
1833             String layerName = m_owningLayer.name() + " (background)";
1834             m_backgroundLayer = createGraphicsLayer(layerName);
1835             m_backgroundLayer->setDrawsContent(true);
1836             m_backgroundLayer->setAnchorPoint(FloatPoint3D());
1837             layerChanged = true;
1838         }
1839         
1840         if (!m_contentsContainmentLayer) {
1841             String layerName = m_owningLayer.name() + " (contents containment)";
1842             m_contentsContainmentLayer = createGraphicsLayer(layerName);
1843             m_contentsContainmentLayer->setAppliesPageScale(true);
1844             m_graphicsLayer->setAppliesPageScale(false);
1845             layerChanged = true;
1846         }
1847     } else {
1848         if (m_backgroundLayer) {
1849             willDestroyLayer(m_backgroundLayer.get());
1850             GraphicsLayer::unparentAndClear(m_backgroundLayer);
1851             layerChanged = true;
1852         }
1853         if (m_contentsContainmentLayer) {
1854             willDestroyLayer(m_contentsContainmentLayer.get());
1855             GraphicsLayer::unparentAndClear(m_contentsContainmentLayer);
1856             layerChanged = true;
1857             m_graphicsLayer->setAppliesPageScale(true);
1858         }
1859     }
1860
1861     return layerChanged;
1862 }
1863
1864 // Masking layer is used for masks or clip-path.
1865 bool RenderLayerBacking::updateMaskingLayer(bool hasMask, bool hasClipPath)
1866 {
1867     bool layerChanged = false;
1868     if (hasMask || hasClipPath) {
1869         OptionSet<GraphicsLayerPaintingPhase> maskPhases;
1870         if (hasMask)
1871             maskPhases = GraphicsLayerPaintingPhase::Mask;
1872         
1873         if (hasClipPath) {
1874             // If we have a mask, we need to paint the combined clip-path and mask into the mask layer.
1875             if (hasMask || renderer().style().clipPath()->type() == ClipPathOperation::Reference || !GraphicsLayer::supportsLayerType(GraphicsLayer::Type::Shape))
1876                 maskPhases.add(GraphicsLayerPaintingPhase::ClipPath);
1877         }
1878
1879         bool paintsContent = !maskPhases.isEmpty();
1880         GraphicsLayer::Type requiredLayerType = paintsContent ? GraphicsLayer::Type::Normal : GraphicsLayer::Type::Shape;
1881         if (m_maskLayer && m_maskLayer->type() != requiredLayerType) {
1882             m_graphicsLayer->setMaskLayer(nullptr);
1883             willDestroyLayer(m_maskLayer.get());
1884             GraphicsLayer::clear(m_maskLayer);
1885         }
1886
1887         if (!m_maskLayer) {
1888             m_maskLayer = createGraphicsLayer("mask", requiredLayerType);
1889             m_maskLayer->setDrawsContent(paintsContent);
1890             m_maskLayer->setPaintingPhase(maskPhases);
1891             layerChanged = true;
1892             m_graphicsLayer->setMaskLayer(m_maskLayer.copyRef());
1893             // We need a geometry update to size the new mask layer.
1894             m_owningLayer.setNeedsCompositingGeometryUpdate();
1895         }
1896     } else if (m_maskLayer) {
1897         m_graphicsLayer->setMaskLayer(nullptr);
1898         willDestroyLayer(m_maskLayer.get());
1899         GraphicsLayer::clear(m_maskLayer);
1900         layerChanged = true;
1901     }
1902
1903     return layerChanged;
1904 }
1905
1906 void RenderLayerBacking::updateChildClippingStrategy(bool needsDescendantsClippingLayer)
1907 {
1908     if (hasClippingLayer() && needsDescendantsClippingLayer) {
1909         if (is<RenderBox>(renderer()) && (renderer().style().clipPath() || renderer().style().hasBorderRadius())) {
1910             auto* clipLayer = clippingLayer();
1911             LayoutRect boxRect(LayoutPoint(), downcast<RenderBox>(renderer()).size());
1912             FloatRoundedRect contentsClippingRect = renderer().style().getRoundedInnerBorderFor(boxRect).pixelSnappedRoundedRectForPainting(deviceScaleFactor());
1913             contentsClippingRect.move(LayoutSize(clipLayer->offsetFromRenderer()));
1914             // Note that we have to set this rounded rect again during the geometry update (clipLayer->offsetFromRenderer() may be stale here).
1915             if (clipLayer->setMasksToBoundsRect(contentsClippingRect)) {
1916                 clipLayer->setMaskLayer(nullptr);
1917                 GraphicsLayer::clear(m_childClippingMaskLayer);
1918                 return;
1919             }
1920
1921             if (!m_childClippingMaskLayer) {
1922                 m_childClippingMaskLayer = createGraphicsLayer("child clipping mask");
1923                 m_childClippingMaskLayer->setDrawsContent(true);
1924                 m_childClippingMaskLayer->setPaintingPhase({ GraphicsLayerPaintingPhase::ChildClippingMask });
1925                 clippingLayer()->setMaskLayer(m_childClippingMaskLayer.copyRef());
1926             }
1927         }
1928     } else {
1929         if (m_childClippingMaskLayer) {
1930             if (hasClippingLayer())
1931                 clippingLayer()->setMaskLayer(nullptr);
1932             GraphicsLayer::clear(m_childClippingMaskLayer);
1933         } else 
1934             if (hasClippingLayer())
1935                 clippingLayer()->setMasksToBoundsRect(FloatRoundedRect(FloatRect({ }, clippingLayer()->size())));
1936     }
1937 }
1938
1939 bool RenderLayerBacking::updateScrollingLayers(bool needsScrollingLayers)
1940 {
1941     if (needsScrollingLayers == !!m_scrollContainerLayer)
1942         return false;
1943
1944     if (!m_scrollContainerLayer) {
1945         // Outer layer which corresponds with the scroll view. This never paints content.
1946         m_scrollContainerLayer = createGraphicsLayer("scroll container", GraphicsLayer::Type::ScrollContainer);
1947         m_scrollContainerLayer->setPaintingPhase({ });
1948         m_scrollContainerLayer->setDrawsContent(false);
1949         m_scrollContainerLayer->setMasksToBounds(true);
1950
1951         // Inner layer which renders the content that scrolls.
1952         m_scrolledContentsLayer = createGraphicsLayer("scrolled contents", GraphicsLayer::Type::ScrolledContents);
1953         m_scrolledContentsLayer->setDrawsContent(true);
1954         m_scrolledContentsLayer->setAnchorPoint({ });
1955         m_scrollContainerLayer->addChild(*m_scrolledContentsLayer);
1956     } else {
1957         compositor().willRemoveScrollingLayerWithBacking(m_owningLayer, *this);
1958
1959         willDestroyLayer(m_scrollContainerLayer.get());
1960         willDestroyLayer(m_scrolledContentsLayer.get());
1961         
1962         GraphicsLayer::unparentAndClear(m_scrollContainerLayer);
1963         GraphicsLayer::unparentAndClear(m_scrolledContentsLayer);
1964     }
1965
1966     if (m_scrollContainerLayer)
1967         compositor().didAddScrollingLayer(m_owningLayer);
1968     
1969     return true;
1970 }
1971
1972 void RenderLayerBacking::detachFromScrollingCoordinator(OptionSet<ScrollCoordinationRole> roles)
1973 {
1974     if (!m_scrollingNodeID && !m_ancestorClippingStack && !m_frameHostingNodeID && !m_viewportConstrainedNodeID && !m_positioningNodeID)
1975         return;
1976
1977     auto* scrollingCoordinator = m_owningLayer.page().scrollingCoordinator();
1978     if (!scrollingCoordinator)
1979         return;
1980
1981     if (roles.contains(ScrollCoordinationRole::Scrolling) && m_scrollingNodeID) {
1982         LOG_WITH_STREAM(Compositing, stream << "Detaching Scrolling node " << m_scrollingNodeID);
1983         scrollingCoordinator->unparentChildrenAndDestroyNode(m_scrollingNodeID);
1984         m_scrollingNodeID = 0;
1985     }
1986
1987     if (roles.contains(ScrollCoordinationRole::ScrollingProxy) && m_ancestorClippingStack) {
1988         m_ancestorClippingStack->detachFromScrollingCoordinator(*scrollingCoordinator);
1989         LOG_WITH_STREAM(Compositing, stream << "Detaching nodes in ancestor clipping stack");
1990     }
1991
1992     if (roles.contains(ScrollCoordinationRole::FrameHosting) && m_frameHostingNodeID) {
1993         LOG_WITH_STREAM(Compositing, stream << "Detaching FrameHosting node " << m_frameHostingNodeID);
1994         scrollingCoordinator->unparentChildrenAndDestroyNode(m_frameHostingNodeID);
1995         m_frameHostingNodeID = 0;
1996     }
1997
1998     if (roles.contains(ScrollCoordinationRole::ViewportConstrained) && m_viewportConstrainedNodeID) {
1999         LOG_WITH_STREAM(Compositing, stream << "Detaching ViewportConstrained node " << m_viewportConstrainedNodeID);
2000         scrollingCoordinator->unparentChildrenAndDestroyNode(m_viewportConstrainedNodeID);
2001         m_viewportConstrainedNodeID = 0;
2002     }
2003
2004     if (roles.contains(ScrollCoordinationRole::Positioning) && m_positioningNodeID) {
2005         LOG_WITH_STREAM(Compositing, stream << "Detaching Positioned node " << m_positioningNodeID);
2006         scrollingCoordinator->unparentChildrenAndDestroyNode(m_positioningNodeID);
2007         m_positioningNodeID = 0;
2008     }
2009 }
2010
2011 ScrollingNodeID RenderLayerBacking::scrollingNodeIDForChildren() const
2012 {
2013     if (m_frameHostingNodeID)
2014         return m_frameHostingNodeID;
2015
2016     if (m_scrollingNodeID)
2017         return m_scrollingNodeID;
2018
2019     if (m_viewportConstrainedNodeID)
2020         return m_viewportConstrainedNodeID;
2021
2022     if (m_ancestorClippingStack) {
2023         if (auto lastOverflowScrollProxyNode = m_ancestorClippingStack->lastOverflowScrollProxyNodeID())
2024             return lastOverflowScrollProxyNode;
2025     }
2026
2027     return m_positioningNodeID;
2028 }
2029
2030 float RenderLayerBacking::compositingOpacity(float rendererOpacity) const
2031 {
2032     float finalOpacity = rendererOpacity;
2033     
2034     for (auto* curr = m_owningLayer.parent(); curr; curr = curr->parent()) {
2035         // We only care about parents that are stacking contexts.
2036         // Recall that opacity creates stacking context.
2037         if (!curr->isCSSStackingContext())
2038             continue;
2039         
2040         // If we found a compositing layer, we want to compute opacity
2041         // relative to it. So we can break here.
2042         if (curr->isComposited())
2043             break;
2044         
2045         finalOpacity *= curr->renderer().opacity();
2046     }
2047
2048     return finalOpacity;
2049 }
2050
2051 // FIXME: Code is duplicated in RenderLayer. Also, we should probably not consider filters a box decoration here.
2052 static inline bool hasVisibleBoxDecorations(const RenderStyle& style)
2053 {
2054     return style.hasVisibleBorder() || style.hasBorderRadius() || style.hasOutline() || style.hasAppearance() || style.boxShadow() || style.hasFilter();
2055 }
2056
2057 static bool canDirectlyCompositeBackgroundBackgroundImage(const RenderStyle& style)
2058 {
2059     if (!GraphicsLayer::supportsContentsTiling())
2060         return false;
2061
2062     auto& fillLayer = style.backgroundLayers();
2063     if (fillLayer.next())
2064         return false;
2065
2066     if (!fillLayer.imagesAreLoaded())
2067         return false;
2068
2069     if (fillLayer.attachment() != FillAttachment::ScrollBackground)
2070         return false;
2071
2072     // FIXME: Allow color+image compositing when it makes sense.
2073     // For now bailing out.
2074     if (style.visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor).isVisible())
2075         return false;
2076
2077     // FIXME: support gradients with isGeneratedImage.
2078     auto* styleImage = fillLayer.image();
2079     if (!styleImage->isCachedImage())
2080         return false;
2081
2082     auto* image = styleImage->cachedImage()->image();
2083     if (!image->isBitmapImage())
2084         return false;
2085
2086     return true;
2087 }
2088
2089 static bool hasPaintedBoxDecorationsOrBackgroundImage(const RenderStyle& style)
2090 {
2091     if (hasVisibleBoxDecorations(style))
2092         return true;
2093
2094     if (!style.hasBackgroundImage())
2095         return false;
2096
2097     return !canDirectlyCompositeBackgroundBackgroundImage(style);
2098 }
2099
2100 static inline bool hasPerspectiveOrPreserves3D(const RenderStyle& style)
2101 {
2102     return style.hasPerspective() || style.preserves3D();
2103 }
2104
2105 Color RenderLayerBacking::rendererBackgroundColor() const
2106 {
2107     RenderElement* backgroundRenderer = nullptr;
2108     if (renderer().isDocumentElementRenderer())
2109         backgroundRenderer = renderer().view().rendererForRootBackground();
2110     
2111     if (!backgroundRenderer)
2112         backgroundRenderer = &renderer();
2113
2114     return backgroundRenderer->style().visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor);
2115 }
2116
2117 void RenderLayerBacking::updateDirectlyCompositedBackgroundColor(PaintedContentsInfo& contentsInfo, bool& didUpdateContentsRect)
2118 {
2119     if (m_backgroundLayer && !m_backgroundLayerPaintsFixedRootBackground && !contentsInfo.paintsBoxDecorations()) {
2120         m_graphicsLayer->setContentsToSolidColor(Color());
2121         m_backgroundLayer->setContentsToSolidColor(rendererBackgroundColor());
2122
2123         FloatRect contentsRect = backgroundBoxForSimpleContainerPainting();
2124         // NOTE: This is currently only used by RenderFullScreen, which we want to be
2125         // big enough to hide overflow areas of the root.
2126         contentsRect.inflate(contentsRect.size());
2127         m_backgroundLayer->setContentsRect(contentsRect);
2128         m_backgroundLayer->setContentsClippingRect(FloatRoundedRect(contentsRect));
2129         return;
2130     }
2131
2132     if (!contentsInfo.isSimpleContainer() || (is<RenderBox>(renderer()) && !downcast<RenderBox>(renderer()).paintsOwnBackground())) {
2133         m_graphicsLayer->setContentsToSolidColor(Color());
2134         return;
2135     }
2136
2137     Color backgroundColor = rendererBackgroundColor();
2138
2139     // An unset (invalid) color will remove the solid color.
2140     m_graphicsLayer->setContentsToSolidColor(backgroundColor);
2141     FloatRect contentsRect = backgroundBoxForSimpleContainerPainting();
2142     m_graphicsLayer->setContentsRect(contentsRect);
2143     m_graphicsLayer->setContentsClippingRect(FloatRoundedRect(contentsRect));
2144     didUpdateContentsRect = true;
2145 }
2146
2147 void RenderLayerBacking::updateDirectlyCompositedBackgroundImage(PaintedContentsInfo& contentsInfo, bool& didUpdateContentsRect)
2148 {
2149     if (!GraphicsLayer::supportsContentsTiling())
2150         return;
2151
2152     if (contentsInfo.isDirectlyCompositedImage())
2153         return;
2154
2155     auto& style = renderer().style();
2156     if (!contentsInfo.isSimpleContainer() || !style.hasBackgroundImage()) {
2157         m_graphicsLayer->setContentsToImage(0);
2158         return;
2159     }
2160
2161     auto destRect = backgroundBoxForSimpleContainerPainting();
2162     FloatSize phase;
2163     FloatSize tileSize;
2164     // FIXME: Absolute paint location is required here.
2165     downcast<RenderBox>(renderer()).getGeometryForBackgroundImage(&renderer(), LayoutPoint(), destRect, phase, tileSize);
2166
2167     m_graphicsLayer->setContentsTileSize(tileSize);
2168     m_graphicsLayer->setContentsTilePhase(phase);
2169     m_graphicsLayer->setContentsRect(destRect);
2170     m_graphicsLayer->setContentsClippingRect(FloatRoundedRect(destRect));
2171     m_graphicsLayer->setContentsToImage(style.backgroundLayers().image()->cachedImage()->image());
2172
2173     didUpdateContentsRect = true;
2174 }
2175
2176 void RenderLayerBacking::updateRootLayerConfiguration()
2177 {
2178     if (!m_isFrameLayerWithTiledBacking)
2179         return;
2180
2181     Color backgroundColor;
2182     bool viewIsTransparent = compositor().viewHasTransparentBackground(&backgroundColor);
2183
2184     if (m_backgroundLayerPaintsFixedRootBackground && m_backgroundLayer) {
2185         if (m_isMainFrameRenderViewLayer) {
2186             m_backgroundLayer->setBackgroundColor(backgroundColor);
2187             m_backgroundLayer->setContentsOpaque(!viewIsTransparent);
2188         }
2189
2190         m_graphicsLayer->setBackgroundColor(Color());
2191         m_graphicsLayer->setContentsOpaque(false);
2192     } else if (m_isMainFrameRenderViewLayer) {
2193         m_graphicsLayer->setBackgroundColor(backgroundColor);
2194         m_graphicsLayer->setContentsOpaque(!viewIsTransparent);
2195     }
2196 }
2197
2198 void RenderLayerBacking::updatePaintingPhases()
2199 {
2200     // Phases for m_childClippingMaskLayer and m_maskLayer are set elsewhere.
2201     OptionSet<GraphicsLayerPaintingPhase> primaryLayerPhases = { GraphicsLayerPaintingPhase::Background, GraphicsLayerPaintingPhase::Foreground };
2202     
2203     if (m_foregroundLayer) {
2204         OptionSet<GraphicsLayerPaintingPhase> foregroundLayerPhases { GraphicsLayerPaintingPhase::Foreground };
2205         
2206         if (m_scrolledContentsLayer)
2207             foregroundLayerPhases.add(GraphicsLayerPaintingPhase::OverflowContents);
2208
2209         m_foregroundLayer->setPaintingPhase(foregroundLayerPhases);
2210         primaryLayerPhases.remove(GraphicsLayerPaintingPhase::Foreground);
2211     }
2212
2213     if (m_backgroundLayer) {
2214         m_backgroundLayer->setPaintingPhase(GraphicsLayerPaintingPhase::Background);
2215         primaryLayerPhases.remove(GraphicsLayerPaintingPhase::Background);
2216     }
2217
2218     if (m_scrolledContentsLayer) {
2219         OptionSet<GraphicsLayerPaintingPhase> scrolledContentLayerPhases = { GraphicsLayerPaintingPhase::OverflowContents, GraphicsLayerPaintingPhase::CompositedScroll };
2220         if (!m_foregroundLayer)
2221             scrolledContentLayerPhases.add(GraphicsLayerPaintingPhase::Foreground);
2222         m_scrolledContentsLayer->setPaintingPhase(scrolledContentLayerPhases);
2223
2224         primaryLayerPhases.remove(GraphicsLayerPaintingPhase::Foreground);
2225         primaryLayerPhases.add(GraphicsLayerPaintingPhase::CompositedScroll);
2226     }
2227
2228     m_graphicsLayer->setPaintingPhase(primaryLayerPhases);
2229 }
2230
2231 static bool supportsDirectlyCompositedBoxDecorations(const RenderLayerModelObject& renderer)
2232 {
2233     if (!GraphicsLayer::supportsBackgroundColorContent())
2234         return false;
2235
2236     const RenderStyle& style = renderer.style();
2237     if (renderer.hasClip())
2238         return false;
2239
2240     if (hasPaintedBoxDecorationsOrBackgroundImage(style))
2241         return false;
2242
2243     // FIXME: We can't create a directly composited background if this
2244     // layer will have children that intersect with the background layer.
2245     // A better solution might be to introduce a flattening layer if
2246     // we do direct box decoration composition.
2247     // https://bugs.webkit.org/show_bug.cgi?id=119461
2248     if (hasPerspectiveOrPreserves3D(style))
2249         return false;
2250
2251     // FIXME: we should be able to allow backgroundComposite; However since this is not a common use case it has been deferred for now.
2252     if (style.backgroundComposite() != CompositeSourceOver)
2253         return false;
2254
2255     return true;
2256 }
2257
2258 bool RenderLayerBacking::paintsBoxDecorations() const
2259 {
2260     if (!m_owningLayer.hasVisibleBoxDecorations())
2261         return false;
2262
2263     return !supportsDirectlyCompositedBoxDecorations(renderer());
2264 }
2265
2266 bool RenderLayerBacking::paintsContent(RenderLayer::PaintedContentRequest& request) const
2267 {
2268     m_owningLayer.updateDescendantDependentFlags();
2269
2270     bool paintsContent = false;
2271
2272     if (m_owningLayer.hasVisibleContent() && m_owningLayer.hasNonEmptyChildRenderers(request))
2273         paintsContent = true;
2274
2275     if (request.isSatisfied())
2276         return paintsContent;
2277
2278     if (isPaintDestinationForDescendantLayers(request))
2279         paintsContent = true;
2280
2281     if (request.isSatisfied())
2282         return paintsContent;
2283
2284     if (request.hasPaintedContent == RequestState::Unknown)
2285         request.hasPaintedContent = RequestState::False;
2286
2287     if (request.hasSubpixelAntialiasedText == RequestState::Unknown)
2288         request.hasSubpixelAntialiasedText = RequestState::False;
2289
2290     return paintsContent;
2291 }
2292
2293 static bool isRestartedPlugin(RenderObject& renderer)
2294 {
2295     if (!is<RenderEmbeddedObject>(renderer))
2296         return false;
2297
2298     auto& element = downcast<RenderEmbeddedObject>(renderer).frameOwnerElement();
2299     if (!is<HTMLPlugInElement>(element))
2300         return false;
2301
2302     return downcast<HTMLPlugInElement>(element).isRestartedPlugin();
2303 }
2304
2305 static bool isCompositedPlugin(RenderObject& renderer)
2306 {
2307     return is<RenderEmbeddedObject>(renderer) && downcast<RenderEmbeddedObject>(renderer).allowsAcceleratedCompositing();
2308 }
2309
2310 // A "simple container layer" is a RenderLayer which has no visible content to render.
2311 // It may have no children, or all its children may be themselves composited.
2312 // This is a useful optimization, because it allows us to avoid allocating backing store.
2313 bool RenderLayerBacking::isSimpleContainerCompositingLayer(PaintedContentsInfo& contentsInfo) const
2314 {
2315     if (m_owningLayer.isRenderViewLayer())
2316         return false;
2317
2318     if (hasBackingSharingLayers())
2319         return false;
2320
2321     if (renderer().isRenderReplaced() && (!isCompositedPlugin(renderer()) || isRestartedPlugin(renderer())))
2322         return false;
2323
2324     if (renderer().isTextControl())
2325         return false;
2326
2327     if (contentsInfo.paintsBoxDecorations() || contentsInfo.paintsContent())
2328         return false;
2329
2330     if (renderer().style().backgroundClip() == FillBox::Text)
2331         return false;
2332     
2333     if (renderer().isDocumentElementRenderer() && m_owningLayer.isolatesCompositedBlending())
2334         return false;
2335
2336     return true;
2337 }
2338
2339 // Returning true stops the traversal.
2340 enum class LayerTraversal { Continue, Stop };
2341
2342 static LayerTraversal traverseVisibleNonCompositedDescendantLayers(RenderLayer& parent, const WTF::Function<LayerTraversal (const RenderLayer&)>& layerFunc)
2343 {
2344     // FIXME: We shouldn't be called with a stale z-order lists. See bug 85512.
2345     parent.updateLayerListsIfNeeded();
2346
2347 #if !ASSERT_DISABLED
2348     LayerListMutationDetector mutationChecker(parent);
2349 #endif
2350
2351     for (auto* childLayer : parent.normalFlowLayers()) {
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     if (parent.isStackingContext() && !parent.hasVisibleDescendant())
2363         return LayerTraversal::Continue;
2364
2365     // Use the m_hasCompositingDescendant bit to optimize?
2366     for (auto* childLayer : parent.negativeZOrderLayers()) {
2367         if (compositedWithOwnBackingStore(*childLayer))
2368             continue;
2369
2370         if (layerFunc(*childLayer) == LayerTraversal::Stop)
2371             return LayerTraversal::Stop;
2372
2373         if (traverseVisibleNonCompositedDescendantLayers(*childLayer, layerFunc) == LayerTraversal::Stop)
2374             return LayerTraversal::Stop;
2375     }
2376
2377     for (auto* childLayer : parent.positiveZOrderLayers()) {
2378         if (compositedWithOwnBackingStore(*childLayer))
2379             continue;
2380
2381         if (layerFunc(*childLayer) == LayerTraversal::Stop)
2382             return LayerTraversal::Stop;
2383
2384         if (traverseVisibleNonCompositedDescendantLayers(*childLayer, layerFunc) == LayerTraversal::Stop)
2385             return LayerTraversal::Stop;
2386     }
2387
2388     return LayerTraversal::Continue;
2389 }
2390
2391 // Conservative test for having no rendered children.
2392 bool RenderLayerBacking::isPaintDestinationForDescendantLayers(RenderLayer::PaintedContentRequest& request) const
2393 {
2394     bool hasPaintingDescendant = false;
2395     traverseVisibleNonCompositedDescendantLayers(m_owningLayer, [&hasPaintingDescendant, &request](const RenderLayer& layer) {
2396         hasPaintingDescendant |= layer.isVisuallyNonEmpty(&request);
2397         return (hasPaintingDescendant && request.isSatisfied()) ? LayerTraversal::Stop : LayerTraversal::Continue;
2398     });
2399
2400     return hasPaintingDescendant;
2401 }
2402
2403 bool RenderLayerBacking::hasVisibleNonCompositedDescendants() const
2404 {
2405     bool hasVisibleDescendant = false;
2406     traverseVisibleNonCompositedDescendantLayers(m_owningLayer, [&hasVisibleDescendant](const RenderLayer& layer) {
2407         hasVisibleDescendant |= layer.hasVisibleContent();
2408         return hasVisibleDescendant ? LayerTraversal::Stop : LayerTraversal::Continue;
2409     });
2410
2411     return hasVisibleDescendant;
2412 }
2413
2414 bool RenderLayerBacking::containsPaintedContent(PaintedContentsInfo& contentsInfo) const
2415 {
2416     if (contentsInfo.isSimpleContainer() || paintsIntoWindow() || paintsIntoCompositedAncestor() || m_artificiallyInflatedBounds || m_owningLayer.isReflection())
2417         return false;
2418
2419     if (contentsInfo.isDirectlyCompositedImage())
2420         return false;
2421
2422     // FIXME: we could optimize cases where the image, video or canvas is known to fill the border box entirely,
2423     // and set background color on the layer in that case, instead of allocating backing store and painting.
2424 #if ENABLE(VIDEO)
2425     if (is<RenderVideo>(renderer()) && downcast<RenderVideo>(renderer()).shouldDisplayVideo())
2426         return m_owningLayer.hasVisibleBoxDecorationsOrBackground() || (!(downcast<RenderVideo>(renderer()).supportsAcceleratedRendering()) && m_requiresOwnBackingStore);
2427 #endif
2428
2429 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
2430     if (is<RenderHTMLCanvas>(renderer()) && canvasCompositingStrategy(renderer()) == CanvasAsLayerContents)
2431         return m_owningLayer.hasVisibleBoxDecorationsOrBackground();
2432 #endif
2433
2434     return true;
2435 }
2436
2437 // An image can be directly compositing if it's the sole content of the layer, and has no box decorations
2438 // that require painting. Direct compositing saves backing store.
2439 bool RenderLayerBacking::isDirectlyCompositedImage() const
2440 {
2441     if (!is<RenderImage>(renderer()) || m_owningLayer.hasVisibleBoxDecorationsOrBackground() || m_owningLayer.paintsWithFilters() || renderer().hasClip())
2442         return false;
2443
2444 #if ENABLE(VIDEO)
2445     if (is<RenderMedia>(renderer()))
2446         return false;
2447 #endif
2448
2449     auto& imageRenderer = downcast<RenderImage>(renderer());
2450     if (auto* cachedImage = imageRenderer.cachedImage()) {
2451         if (!cachedImage->hasImage())
2452             return false;
2453
2454         auto* image = cachedImage->imageForRenderer(&imageRenderer);
2455         if (!is<BitmapImage>(image))
2456             return false;
2457
2458         if (downcast<BitmapImage>(*image).orientationForCurrentFrame() != DefaultImageOrientation)
2459             return false;
2460
2461 #if (PLATFORM(GTK) || PLATFORM(WPE))
2462         // GTK and WPE ports don't support rounded rect clipping at TextureMapper level, so they cannot
2463         // directly composite images that have border-radius propery. Draw them as non directly composited
2464         // content instead. See https://bugs.webkit.org/show_bug.cgi?id=174157.
2465         if (imageRenderer.style().hasBorderRadius())
2466             return false;
2467 #endif
2468
2469         return m_graphicsLayer->shouldDirectlyCompositeImage(image);
2470     }
2471
2472     return false;
2473 }
2474
2475 void RenderLayerBacking::contentChanged(ContentChangeType changeType)
2476 {
2477     PaintedContentsInfo contentsInfo(*this);
2478     if ((changeType == ImageChanged) && contentsInfo.isDirectlyCompositedImage()) {
2479         updateImageContents(contentsInfo);
2480         return;
2481     }
2482
2483     if (changeType == VideoChanged) {
2484         compositor().scheduleCompositingLayerUpdate();
2485         return;
2486     }
2487
2488     if ((changeType == BackgroundImageChanged) && canDirectlyCompositeBackgroundBackgroundImage(renderer().style()))
2489         m_owningLayer.setNeedsCompositingConfigurationUpdate();
2490
2491     if ((changeType == MaskImageChanged) && m_maskLayer)
2492         m_owningLayer.setNeedsCompositingConfigurationUpdate();
2493
2494 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
2495     if ((changeType == CanvasChanged || changeType == CanvasPixelsChanged) && renderer().isCanvas() && canvasCompositingStrategy(renderer()) == CanvasAsLayerContents) {
2496         m_graphicsLayer->setContentsNeedsDisplay();
2497         return;
2498     }
2499 #endif
2500 }
2501
2502 void RenderLayerBacking::updateImageContents(PaintedContentsInfo& contentsInfo)
2503 {
2504     auto& imageRenderer = downcast<RenderImage>(renderer());
2505
2506     auto* cachedImage = imageRenderer.cachedImage();
2507     if (!cachedImage)
2508         return;
2509
2510     auto* image = cachedImage->imageForRenderer(&imageRenderer);
2511     if (!image)
2512         return;
2513
2514     // We have to wait until the image is fully loaded before setting it on the layer.
2515     if (!cachedImage->isLoaded())
2516         return;
2517
2518     // This is a no-op if the layer doesn't have an inner layer for the image.
2519     m_graphicsLayer->setContentsRect(snapRectToDevicePixels(contentsBox(), deviceScaleFactor()));
2520
2521     LayoutRect boxRect(LayoutPoint(), imageRenderer.size());
2522     boxRect.move(contentOffsetInCompositingLayer());
2523     FloatRoundedRect contentsClippingRect = renderer().style().getRoundedInnerBorderFor(boxRect).pixelSnappedRoundedRectForPainting(deviceScaleFactor());
2524     m_graphicsLayer->setContentsClippingRect(contentsClippingRect);
2525
2526     m_graphicsLayer->setContentsToImage(image);
2527     
2528     updateDrawsContent(contentsInfo);
2529     
2530     // Image animation is "lazy", in that it automatically stops unless someone is drawing
2531     // the image. So we have to kick the animation each time; this has the downside that the
2532     // image will keep animating, even if its layer is not visible.
2533     image->startAnimation();
2534 }
2535
2536 FloatPoint3D RenderLayerBacking::computeTransformOriginForPainting(const LayoutRect& borderBox) const
2537 {
2538     const RenderStyle& style = renderer().style();
2539     float deviceScaleFactor = this->deviceScaleFactor();
2540
2541     FloatPoint3D origin;
2542     origin.setX(roundToDevicePixel(floatValueForLength(style.transformOriginX(), borderBox.width()), deviceScaleFactor));
2543     origin.setY(roundToDevicePixel(floatValueForLength(style.transformOriginY(), borderBox.height()), deviceScaleFactor));
2544     origin.setZ(style.transformOriginZ());
2545
2546     return origin;
2547 }
2548
2549 // Return the offset from the top-left of this compositing layer at which the renderer's contents are painted.
2550 LayoutSize RenderLayerBacking::contentOffsetInCompositingLayer() const
2551 {
2552     return LayoutSize(-m_compositedBounds.x() + m_compositedBoundsOffsetFromGraphicsLayer.width(), -m_compositedBounds.y() + m_compositedBoundsOffsetFromGraphicsLayer.height());
2553 }
2554
2555 LayoutRect RenderLayerBacking::contentsBox() const
2556 {
2557     if (!is<RenderBox>(renderer()))
2558         return LayoutRect();
2559
2560     auto& renderBox = downcast<RenderBox>(renderer());
2561     LayoutRect contentsRect;
2562 #if ENABLE(VIDEO)
2563     if (is<RenderVideo>(renderBox))
2564         contentsRect = downcast<RenderVideo>(renderBox).videoBox();
2565     else
2566 #endif
2567     if (is<RenderReplaced>(renderBox)) {
2568         RenderReplaced& renderReplaced = downcast<RenderReplaced>(renderBox);
2569         contentsRect = renderReplaced.replacedContentRect();
2570     } else
2571         contentsRect = renderBox.contentBoxRect();
2572
2573     contentsRect.move(contentOffsetInCompositingLayer());
2574     return contentsRect;
2575 }
2576
2577 static LayoutRect backgroundRectForBox(const RenderBox& box)
2578 {
2579     switch (box.style().backgroundClip()) {
2580     case FillBox::Border:
2581         return box.borderBoxRect();
2582     case FillBox::Padding:
2583         return box.paddingBoxRect();
2584     case FillBox::Content:
2585         return box.contentBoxRect();
2586     default:
2587         break;
2588     }
2589
2590     ASSERT_NOT_REACHED();
2591     return LayoutRect();
2592 }
2593
2594 FloatRect RenderLayerBacking::backgroundBoxForSimpleContainerPainting() const
2595 {
2596     if (!is<RenderBox>(renderer()))
2597         return FloatRect();
2598
2599     LayoutRect backgroundBox = backgroundRectForBox(downcast<RenderBox>(renderer()));
2600     backgroundBox.move(contentOffsetInCompositingLayer());
2601     return snapRectToDevicePixels(backgroundBox, deviceScaleFactor());
2602 }
2603
2604 GraphicsLayer* RenderLayerBacking::parentForSublayers() const
2605 {
2606     if (m_scrolledContentsLayer)
2607         return m_scrolledContentsLayer.get();
2608
2609     return m_childContainmentLayer ? m_childContainmentLayer.get() : m_graphicsLayer.get();
2610 }
2611
2612 GraphicsLayer* RenderLayerBacking::childForSuperlayers() const
2613 {
2614     if (m_ancestorClippingStack)
2615         return m_ancestorClippingStack->firstClippingLayer();
2616
2617     if (m_contentsContainmentLayer)
2618         return m_contentsContainmentLayer.get();
2619     
2620     return m_graphicsLayer.get();
2621 }
2622
2623 bool RenderLayerBacking::paintsIntoWindow() const
2624 {
2625 #if USE(COORDINATED_GRAPHICS)
2626         return false;
2627 #endif
2628
2629     if (m_isFrameLayerWithTiledBacking)
2630         return false;
2631
2632     if (m_owningLayer.isRenderViewLayer()) {
2633 #if PLATFORM(IOS_FAMILY) || USE(COORDINATED_GRAPHICS)
2634         if (compositor().inForcedCompositingMode())
2635             return false;
2636 #endif
2637
2638         return compositor().rootLayerAttachment() != RenderLayerCompositor::RootLayerAttachedViaEnclosingFrame;
2639     }
2640     
2641     return false;
2642 }
2643
2644 void RenderLayerBacking::setRequiresOwnBackingStore(bool requiresOwnBacking)
2645 {
2646     if (requiresOwnBacking == m_requiresOwnBackingStore)
2647         return;
2648     
2649     m_requiresOwnBackingStore = requiresOwnBacking;
2650
2651     // This affects the answer to paintsIntoCompositedAncestor(), which in turn affects
2652     // cached clip rects, so when it changes we have to clear clip rects on descendants.
2653     m_owningLayer.clearClipRectsIncludingDescendants(PaintingClipRects);
2654     m_owningLayer.computeRepaintRectsIncludingDescendants();
2655     
2656     compositor().repaintInCompositedAncestor(m_owningLayer, compositedBounds());
2657 }
2658
2659 void RenderLayerBacking::setContentsNeedDisplay(GraphicsLayer::ShouldClipToLayer shouldClip)
2660 {
2661     ASSERT(!paintsIntoCompositedAncestor());
2662
2663     // Use the repaint as a trigger to re-evaluate direct compositing (which is never used on the root layer).
2664     if (!m_owningLayer.isRenderViewLayer())
2665         m_owningLayer.setNeedsCompositingConfigurationUpdate();
2666
2667     m_owningLayer.invalidateEventRegion();
2668
2669     auto& frameView = renderer().view().frameView();
2670     if (m_isMainFrameRenderViewLayer && frameView.isTrackingRepaints())
2671         frameView.addTrackedRepaintRect(owningLayer().absoluteBoundingBoxForPainting());
2672     
2673     if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
2674         // By default, setNeedsDisplay will clip to the size of the GraphicsLayer, which does not include margin tiles.
2675         // So if the TiledBacking has a margin that needs to be invalidated, we need to send in a rect to setNeedsDisplayInRect
2676         // that is large enough to include the margin. TiledBacking::bounds() includes the margin.
2677         auto* tiledBacking = this->tiledBacking();
2678         FloatRect rectToRepaint = tiledBacking ? tiledBacking->bounds() : FloatRect(FloatPoint(0, 0), m_graphicsLayer->size());
2679         m_graphicsLayer->setNeedsDisplayInRect(rectToRepaint, shouldClip);
2680     }
2681     
2682     if (m_foregroundLayer && m_foregroundLayer->drawsContent())
2683         m_foregroundLayer->setNeedsDisplay();
2684
2685     if (m_backgroundLayer && m_backgroundLayer->drawsContent())
2686         m_backgroundLayer->setNeedsDisplay();
2687
2688     if (m_maskLayer && m_maskLayer->drawsContent())
2689         m_maskLayer->setNeedsDisplay();
2690
2691     if (m_childClippingMaskLayer && m_childClippingMaskLayer->drawsContent())
2692         m_childClippingMaskLayer->setNeedsDisplay();
2693
2694     if (m_scrolledContentsLayer && m_scrolledContentsLayer->drawsContent())
2695         m_scrolledContentsLayer->setNeedsDisplay();
2696 }
2697
2698 // r is in the coordinate space of the layer's render object
2699 void RenderLayerBacking::setContentsNeedDisplayInRect(const LayoutRect& r, GraphicsLayer::ShouldClipToLayer shouldClip)
2700 {
2701     ASSERT(!paintsIntoCompositedAncestor());
2702     
2703     // Use the repaint as a trigger to re-evaluate direct compositing (which is never used on the root layer).
2704     if (!m_owningLayer.isRenderViewLayer())
2705         m_owningLayer.setNeedsCompositingConfigurationUpdate();
2706
2707     m_owningLayer.invalidateEventRegion();
2708
2709     FloatRect pixelSnappedRectForPainting = snapRectToDevicePixels(r, deviceScaleFactor());
2710     auto& frameView = renderer().view().frameView();
2711     if (m_isMainFrameRenderViewLayer && frameView.isTrackingRepaints())
2712         frameView.addTrackedRepaintRect(pixelSnappedRectForPainting);
2713
2714     if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
2715         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2716         layerDirtyRect.move(-m_graphicsLayer->offsetFromRenderer() - m_subpixelOffsetFromRenderer);
2717         m_graphicsLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2718     }
2719
2720     if (m_foregroundLayer && m_foregroundLayer->drawsContent()) {
2721         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2722         layerDirtyRect.move(-m_foregroundLayer->offsetFromRenderer() - m_subpixelOffsetFromRenderer);
2723         m_foregroundLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2724     }
2725
2726     // FIXME: need to split out repaints for the background.
2727     if (m_backgroundLayer && m_backgroundLayer->drawsContent()) {
2728         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2729         layerDirtyRect.move(-m_backgroundLayer->offsetFromRenderer() - m_subpixelOffsetFromRenderer);
2730         m_backgroundLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2731     }
2732
2733     if (m_maskLayer && m_maskLayer->drawsContent()) {
2734         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2735         layerDirtyRect.move(-m_maskLayer->offsetFromRenderer() - m_subpixelOffsetFromRenderer);
2736         m_maskLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2737     }
2738
2739     if (m_childClippingMaskLayer && m_childClippingMaskLayer->drawsContent()) {
2740         FloatRect layerDirtyRect = r;
2741         layerDirtyRect.move(-m_childClippingMaskLayer->offsetFromRenderer());
2742         m_childClippingMaskLayer->setNeedsDisplayInRect(layerDirtyRect);
2743     }
2744
2745     if (m_scrolledContentsLayer && m_scrolledContentsLayer->drawsContent()) {
2746         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2747         layerDirtyRect.move(-m_scrolledContentsLayer->offsetFromRenderer() + toLayoutSize(m_scrolledContentsLayer->scrollOffset()) - m_subpixelOffsetFromRenderer);
2748         m_scrolledContentsLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2749     }
2750 }
2751
2752 void RenderLayerBacking::paintIntoLayer(const GraphicsLayer* graphicsLayer, GraphicsContext& context,
2753     const IntRect& paintDirtyRect, // In the coords of rootLayer.
2754     OptionSet<PaintBehavior> paintBehavior, OptionSet<GraphicsLayerPaintingPhase> paintingPhase)
2755 {
2756     if ((paintsIntoWindow() || paintsIntoCompositedAncestor()) && paintingPhase != OptionSet<GraphicsLayerPaintingPhase>(GraphicsLayerPaintingPhase::ChildClippingMask)) {
2757 #if !PLATFORM(IOS_FAMILY) && !OS(WINDOWS)
2758         // FIXME: Looks like the CALayer tree is out of sync with the GraphicsLayer heirarchy
2759         // when pages are restored from the PageCache.
2760         // <rdar://problem/8712587> ASSERT: When Going Back to Page with Plugins in PageCache
2761         ASSERT_NOT_REACHED();
2762 #endif
2763         return;
2764     }
2765
2766     OptionSet<RenderLayer::PaintLayerFlag> paintFlags;
2767     if (paintingPhase.contains(GraphicsLayerPaintingPhase::Background))
2768         paintFlags.add(RenderLayer::PaintLayerPaintingCompositingBackgroundPhase);
2769     if (paintingPhase.contains(GraphicsLayerPaintingPhase::Foreground))
2770         paintFlags.add(RenderLayer::PaintLayerPaintingCompositingForegroundPhase);
2771     if (paintingPhase.contains(GraphicsLayerPaintingPhase::Mask))
2772         paintFlags.add(RenderLayer::PaintLayerPaintingCompositingMaskPhase);
2773     if (paintingPhase.contains(GraphicsLayerPaintingPhase::ClipPath))
2774         paintFlags.add(RenderLayer::PaintLayerPaintingCompositingClipPathPhase);
2775     if (paintingPhase.contains(GraphicsLayerPaintingPhase::ChildClippingMask))
2776         paintFlags.add(RenderLayer::PaintLayerPaintingChildClippingMaskPhase);
2777     if (paintingPhase.contains(GraphicsLayerPaintingPhase::OverflowContents))
2778         paintFlags.add(RenderLayer::PaintLayerPaintingOverflowContents);
2779     if (paintingPhase.contains(GraphicsLayerPaintingPhase::CompositedScroll))
2780         paintFlags.add(RenderLayer::PaintLayerPaintingCompositingScrollingPhase);
2781
2782     if (graphicsLayer == m_backgroundLayer.get() && m_backgroundLayerPaintsFixedRootBackground)
2783         paintFlags.add({ RenderLayer::PaintLayerPaintingRootBackgroundOnly, RenderLayer::PaintLayerPaintingCompositingForegroundPhase }); // Need PaintLayerPaintingCompositingForegroundPhase to walk child layers.
2784     else if (compositor().fixedRootBackgroundLayer())
2785         paintFlags.add(RenderLayer::PaintLayerPaintingSkipRootBackground);
2786
2787 #ifndef NDEBUG
2788     RenderElement::SetLayoutNeededForbiddenScope forbidSetNeedsLayout(&renderer());
2789 #endif
2790
2791     auto paintOneLayer = [&](RenderLayer& layer, OptionSet<RenderLayer::PaintLayerFlag> paintFlags) {
2792         InspectorInstrumentation::willPaint(layer.renderer());
2793
2794         FrameView::PaintingState paintingState;
2795         if (layer.isRenderViewLayer())
2796             renderer().view().frameView().willPaintContents(context, paintDirtyRect, paintingState);
2797
2798         RenderLayer::LayerPaintingInfo paintingInfo(&m_owningLayer, paintDirtyRect, paintBehavior, -m_subpixelOffsetFromRenderer);
2799
2800         if (&layer == &m_owningLayer) {
2801             layer.paintLayerContents(context, paintingInfo, paintFlags);
2802
2803             if (layer.containsDirtyOverlayScrollbars())
2804                 layer.paintLayerContents(context, paintingInfo, paintFlags | RenderLayer::PaintLayerPaintingOverlayScrollbars);
2805         } else
2806             layer.paintLayerWithEffects(context, paintingInfo, paintFlags);
2807
2808         if (layer.isRenderViewLayer())
2809             renderer().view().frameView().didPaintContents(context, paintDirtyRect, paintingState);
2810
2811         ASSERT(!m_owningLayer.m_usedTransparency);
2812
2813         InspectorInstrumentation::didPaint(layer.renderer(), paintDirtyRect);
2814     };
2815
2816     paintOneLayer(m_owningLayer, paintFlags);
2817     
2818     // FIXME: Need to check m_foregroundLayer, masking etc. webkit.org/b/197565.
2819     GraphicsLayer* destinationForSharingLayers = m_scrolledContentsLayer ? m_scrolledContentsLayer.get() : m_graphicsLayer.get();
2820
2821     if (graphicsLayer == destinationForSharingLayers) {
2822         OptionSet<RenderLayer::PaintLayerFlag> sharingLayerPaintFlags = {
2823             RenderLayer::PaintLayerPaintingCompositingBackgroundPhase,
2824             RenderLayer::PaintLayerPaintingCompositingForegroundPhase };
2825
2826         if (paintingPhase.contains(GraphicsLayerPaintingPhase::OverflowContents))
2827             sharingLayerPaintFlags.add(RenderLayer::PaintLayerPaintingOverflowContents);
2828
2829         for (auto& layerWeakPtr : m_backingSharingLayers)
2830             paintOneLayer(*layerWeakPtr, sharingLayerPaintFlags);
2831     }
2832
2833     compositor().didPaintBacking(this);
2834 }
2835
2836 #if ENABLE(POINTER_EVENTS)
2837 static RefPtr<Pattern> patternForTouchAction(TouchAction touchAction, FloatSize contentOffset, GraphicsContext& destContext)
2838 {
2839     auto toIndex = [](TouchAction touchAction) -> unsigned {
2840         switch (touchAction) {
2841         case TouchAction::Manipulation:
2842             return 1;
2843         case TouchAction::PanX:
2844             return 2;
2845         case TouchAction::PanY:
2846             return 3;
2847         case TouchAction::PinchZoom:
2848             return 4;
2849         case TouchAction::None:
2850         case TouchAction::Auto:
2851             break;
2852         }
2853         return 0;
2854     };
2855
2856     struct TouchActionAndRGB {
2857         TouchAction action;
2858         ASCIILiteral name;
2859         FloatSize phase;
2860     };
2861     static const TouchActionAndRGB actionsAndColors[] = {
2862         { TouchAction::None, "none"_s, { } },
2863         { TouchAction::Manipulation, "manip"_s, { } },
2864         { TouchAction::PanX, "pan-x"_s, { } },
2865         { TouchAction::PanY, "pan-y"_s, { 0, 9 } },
2866         { TouchAction::PinchZoom, "p-z"_s, { 16, 4.5 } },
2867     };
2868     
2869     auto actionIndex = toIndex(touchAction);
2870     if (!actionIndex || actionIndex >= ARRAY_SIZE(actionsAndColors))
2871         return nullptr;
2872
2873     const FloatSize tileSize { 32, 18 };
2874
2875     auto imageBuffer = ImageBuffer::createCompatibleBuffer(tileSize, ColorSpaceSRGB, destContext);
2876     if (!imageBuffer)
2877         return nullptr;
2878
2879     const auto& touchActionData = actionsAndColors[actionIndex];
2880     {
2881         GraphicsContext& imageContext = imageBuffer->context();
2882
2883         FontCascadeDescription fontDescription;
2884         fontDescription.setOneFamily("Helvetica");
2885         fontDescription.setSpecifiedSize(10);
2886         fontDescription.setComputedSize(10);
2887         fontDescription.setWeight(FontSelectionValue(500));
2888         FontCascade font(WTFMove(fontDescription), 0, 0);
2889         font.update(nullptr);
2890
2891         TextRun textRun = TextRun(touchActionData.name);
2892         imageContext.setFillColor(Color(0, 0, 0, 128));
2893
2894         constexpr float textGap = 4;
2895         constexpr float yOffset = 12;
2896         imageContext.drawText(font, textRun, { textGap, yOffset }, 0);
2897     }
2898
2899     auto tileImage = ImageBuffer::sinkIntoImage(WTFMove(imageBuffer));
2900     auto fillPattern = Pattern::create(tileImage.releaseNonNull(), true, true);
2901     AffineTransform patternOffsetTransform;
2902     patternOffsetTransform.translate(contentOffset + touchActionData.phase);
2903     patternOffsetTransform.scale(1 / destContext.scaleFactor());
2904     fillPattern->setPatternSpaceTransform(patternOffsetTransform);
2905
2906     return fillPattern;
2907 }
2908 #endif // ENABLE(POINTER_EVENTS)
2909
2910 void RenderLayerBacking::paintDebugOverlays(const GraphicsLayer* graphicsLayer, GraphicsContext& context)
2911 {
2912     if (graphicsLayer->eventRegion().isEmpty())
2913         return;
2914
2915     GraphicsContextStateSaver stateSaver(context);
2916
2917     // The region is offset by contentOffsetInCompositingLayer() so undo that.
2918     auto contentOffset = roundedIntSize(contentOffsetInCompositingLayer());
2919     context.translate(-contentOffset);
2920
2921     // The interactive part.
2922     auto& eventRegion = graphicsLayer->eventRegion();
2923     Color regionColor(0, 0, 0, 5);
2924     context.setFillColor(regionColor);
2925     for (auto rect : eventRegion.region().rects())
2926         context.fillRect(rect);
2927
2928 #if ENABLE(POINTER_EVENTS)
2929     const TouchAction touchActionList[] = {
2930         TouchAction::None,
2931         TouchAction::Manipulation,
2932         TouchAction::PanX,
2933         TouchAction::PanY,
2934         TouchAction::PinchZoom,
2935     };
2936
2937     for (auto action : touchActionList) {
2938         auto* actionRegion = graphicsLayer->eventRegion().regionForTouchAction(action);
2939         if (!actionRegion)
2940             continue;
2941
2942         auto fillPattern = patternForTouchAction(action, contentOffsetInCompositingLayer(), context);
2943         if (!fillPattern)
2944             continue;
2945
2946         context.setFillPattern(fillPattern.releaseNonNull());
2947         for (auto rect : actionRegion->rects())
2948             context.fillRect(rect);
2949     }
2950 #endif // ENABLE(POINTER_EVENTS)
2951 }
2952
2953 // Up-call from compositing layer drawing callback.
2954 void RenderLayerBacking::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, OptionSet<GraphicsLayerPaintingPhase> paintingPhase, const FloatRect& clip, GraphicsLayerPaintBehavior layerPaintBehavior)
2955 {
2956 #ifndef NDEBUG
2957     renderer().page().setIsPainting(true);
2958 #endif
2959
2960 #if PLATFORM(MAC)
2961     LocalDefaultSystemAppearance localAppearance(renderer().useDarkAppearance());
2962 #endif
2963
2964     // The dirtyRect is in the coords of the painting root.
2965     FloatRect adjustedClipRect = clip;
2966     adjustedClipRect.move(m_subpixelOffsetFromRenderer);
2967     IntRect dirtyRect = enclosingIntRect(adjustedClipRect);
2968
2969     if (!graphicsLayer->repaintCount())
2970         layerPaintBehavior |= GraphicsLayerPaintFirstTilePaint;
2971
2972     if (graphicsLayer == m_graphicsLayer.get()
2973         || graphicsLayer == m_foregroundLayer.get()
2974         || graphicsLayer == m_backgroundLayer.get()
2975         || graphicsLayer == m_maskLayer.get()
2976         || graphicsLayer == m_childClippingMaskLayer.get()
2977         || graphicsLayer == m_scrolledContentsLayer.get()) {
2978
2979         if (!paintingPhase.contains(GraphicsLayerPaintingPhase::OverflowContents))
2980             dirtyRect.intersect(enclosingIntRect(compositedBoundsIncludingMargin()));
2981
2982         // We have to use the same root as for hit testing, because both methods can compute and cache clipRects.
2983         OptionSet<PaintBehavior> behavior = PaintBehavior::Normal;
2984         if (layerPaintBehavior == GraphicsLayerPaintSnapshotting)
2985             behavior.add(PaintBehavior::Snapshotting);
2986         
2987         if (layerPaintBehavior == GraphicsLayerPaintFirstTilePaint)
2988             behavior.add(PaintBehavior::TileFirstPaint);
2989
2990         paintIntoLayer(graphicsLayer, context, dirtyRect, behavior, paintingPhase);
2991
2992         if (renderer().settings().visibleDebugOverlayRegions() & NonFastScrollableRegion) // Piggy-back off the setting that shows touch handler regions.
2993             paintDebugOverlays(graphicsLayer, context);
2994
2995     } else if (graphicsLayer == layerForHorizontalScrollbar()) {
2996         paintScrollbar(m_owningLayer.horizontalScrollbar(), context, dirtyRect);
2997     } else if (graphicsLayer == layerForVerticalScrollbar()) {
2998         paintScrollbar(m_owningLayer.verticalScrollbar(), context, dirtyRect);
2999     } else if (graphicsLayer == layerForScrollCorner()) {
3000         const LayoutRect& scrollCornerAndResizer = m_owningLayer.scrollCornerAndResizerRect();
3001         GraphicsContextStateSaver stateSaver(context);
3002         context.translate(-scrollCornerAndResizer.location());
3003         LayoutRect transformedClip = LayoutRect(clip);
3004         transformedClip.moveBy(scrollCornerAndResizer.location());
3005         m_owningLayer.paintScrollCorner(context, IntPoint(), snappedIntRect(transformedClip));
3006         m_owningLayer.paintResizer(context, IntPoint(), transformedClip);
3007     }
3008 #ifndef NDEBUG
3009     renderer().page().setIsPainting(false);
3010 #endif
3011 }
3012
3013 float RenderLayerBacking::pageScaleFactor() const
3014 {
3015     return compositor().pageScaleFactor();
3016 }
3017
3018 float RenderLayerBacking::zoomedOutPageScaleFactor() const
3019 {
3020     return compositor().zoomedOutPageScaleFactor();
3021 }
3022
3023 float RenderLayerBacking::deviceScaleFactor() const
3024 {
3025     return compositor().deviceScaleFactor();
3026 }
3027
3028 float RenderLayerBacking::contentsScaleMultiplierForNewTiles(const GraphicsLayer* layer) const
3029 {
3030     return compositor().contentsScaleMultiplierForNewTiles(layer);
3031 }
3032
3033 bool RenderLayerBacking::paintsOpaquelyAtNonIntegralScales(const GraphicsLayer*) const
3034 {
3035     return m_isMainFrameRenderViewLayer;
3036 }
3037
3038 void RenderLayerBacking::didChangePlatformLayerForLayer(const GraphicsLayer* layer)
3039 {
3040     compositor().didChangePlatformLayerForLayer(m_owningLayer, layer);
3041 }
3042
3043 bool RenderLayerBacking::getCurrentTransform(const GraphicsLayer* graphicsLayer, TransformationMatrix& transform) const
3044 {
3045     auto* transformedLayer = m_contentsContainmentLayer.get() ? m_contentsContainmentLayer.get() : m_graphicsLayer.get();
3046     if (graphicsLayer != transformedLayer)
3047         return false;
3048
3049     if (m_owningLayer.hasTransform()) {
3050         transform = m_owningLayer.currentTransform(RenderStyle::ExcludeTransformOrigin);
3051         return true;
3052     }
3053     return false;
3054 }
3055
3056 bool RenderLayerBacking::isTrackingRepaints() const
3057 {
3058     return static_cast<GraphicsLayerClient&>(compositor()).isTrackingRepaints();
3059 }
3060
3061 bool RenderLayerBacking::shouldSkipLayerInDump(const GraphicsLayer* layer, LayerTreeAsTextBehavior behavior) const
3062 {
3063     if (behavior & LayerTreeAsTextDebug)
3064         return false;
3065
3066     // Skip the root tile cache's flattening layer.
3067     return m_isMainFrameRenderViewLayer && layer && layer == m_childContainmentLayer.get();
3068 }
3069
3070 bool RenderLayerBacking::shouldDumpPropertyForLayer(const GraphicsLayer* layer, const char* propertyName, LayerTreeAsTextBehavior flags) const
3071 {
3072     // For backwards compatibility with WebKit1 and other platforms,
3073     // skip some properties on the root tile cache.
3074     if (m_isMainFrameRenderViewLayer && layer == m_graphicsLayer.get() && !(flags & LayerTreeAsTextIncludeRootLayerProperties)) {
3075         if (!strcmp(propertyName, "drawsContent"))
3076             return false;
3077
3078         // Background color could be of interest to tests or other dumpers if it's non-white.
3079         if (!strcmp(propertyName, "backgroundColor") && Color::isWhiteColor(layer->backgroundColor()))
3080             return false;
3081
3082         // The root tile cache's repaints will show up at the top with FrameView's,
3083         // so don't dump them twice.
3084         if (!strcmp(propertyName, "repaintRects"))
3085             return false;
3086     }
3087
3088     return true;
3089 }
3090
3091 bool RenderLayerBacking::shouldAggressivelyRetainTiles(const GraphicsLayer*) const
3092 {
3093     // Only the main frame TileController has enough information about in-window state to
3094     // correctly implement aggressive tile retention.
3095     if (!m_isMainFrameRenderViewLayer)
3096         return false;
3097
3098     return renderer().settings().aggressiveTileRetentionEnabled();
3099 }
3100
3101 bool RenderLayerBacking::shouldTemporarilyRetainTileCohorts(const GraphicsLayer*) const
3102 {
3103     return renderer().settings().temporaryTileCohortRetentionEnabled();
3104 }
3105
3106 bool RenderLayerBacking::useGiantTiles() const
3107 {
3108     return renderer().settings().useGiantTiles();
3109 }
3110
3111 void RenderLayerBacking::logFilledVisibleFreshTile(unsigned blankPixelCount)
3112 {
3113     if (auto* loggingClient = renderer().page().performanceLoggingClient())
3114         loggingClient->logScrollingEvent(PerformanceLoggingClient::ScrollingEvent::FilledTile, MonotonicTime::now(), blankPixelCount);
3115 }
3116
3117 #ifndef NDEBUG
3118 void RenderLayerBacking::verifyNotPainting()
3119 {
3120     ASSERT(!renderer().page().isPainting());
3121 }
3122 #endif
3123
3124 bool RenderLayerBacking::startAnimation(double timeOffset, const Animation& animation, const KeyframeList& keyframes)
3125 {
3126     bool hasOpacity = keyframes.containsProperty(CSSPropertyOpacity);
3127     bool hasTransform = renderer().isBox() && keyframes.containsProperty(CSSPropertyTransform);
3128     bool hasFilter = keyframes.containsProperty(CSSPropertyFilter);
3129
3130     bool hasBackdropFilter = false;
3131 #if ENABLE(FILTERS_LEVEL_2)
3132     hasBackdropFilter = keyframes.containsProperty(CSSPropertyWebkitBackdropFilter);
3133 #endif
3134
3135     if (!hasOpacity && !hasTransform && !hasFilter && !hasBackdropFilter)
3136         return false;
3137
3138     KeyframeValueList transformVector(AnimatedPropertyTransform);
3139     KeyframeValueList opacityVector(AnimatedPropertyOpacity);
3140     KeyframeValueList filterVector(AnimatedPropertyFilter);
3141 #if ENABLE(FILTERS_LEVEL_2)
3142     KeyframeValueList backdropFilterVector(AnimatedPropertyWebkitBackdropFilter);
3143 #endif
3144
3145     size_t numKeyframes = keyframes.size();
3146     for (size_t i = 0; i < numKeyframes; ++i) {
3147         const KeyframeValue& currentKeyframe = keyframes[i];
3148         const RenderStyle* keyframeStyle = currentKeyframe.style();
3149         double key = currentKeyframe.key();
3150
3151         if (!keyframeStyle)
3152             continue;
3153             
3154         auto* tf = currentKeyframe.timingFunction();
3155         
3156         bool isFirstOrLastKeyframe = key == 0 || key == 1;
3157         if ((hasTransform && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyTransform))
3158             transformVector.insert(std::make_unique<TransformAnimationValue>(key, keyframeStyle->transform(), tf));
3159
3160         if ((hasOpacity && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyOpacity))
3161             opacityVector.insert(std::make_unique<FloatAnimationValue>(key, keyframeStyle->opacity(), tf));
3162
3163         if ((hasFilter && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyFilter))
3164             filterVector.insert(std::make_unique<FilterAnimationValue>(key, keyframeStyle->filter(), tf));
3165
3166 #if ENABLE(FILTERS_LEVEL_2)
3167         if ((hasBackdropFilter && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitBackdropFilter))
3168             backdropFilterVector.insert(std::make_unique<FilterAnimationValue>(key, keyframeStyle->backdropFilter(), tf));
3169 #endif
3170     }
3171
3172     if (!renderer().settings().acceleratedCompositedAnimationsEnabled())
3173         return false;
3174
3175     bool didAnimate = false;
3176
3177     if (hasTransform && m_graphicsLayer->addAnimation(transformVector, snappedIntRect(renderBox()->borderBoxRect()).size(), &animation, keyframes.animationName(), timeOffset))
3178         didAnimate = true;
3179
3180     if (hasOpacity && m_graphicsLayer->addAnimation(opacityVector, IntSize { }, &animation, keyframes.animationName(), timeOffset))
3181         didAnimate = true;
3182
3183     if (hasFilter && m_graphicsLayer->addAnimation(filterVector, IntSize { }, &animation, keyframes.animationName(), timeOffset))
3184         didAnimate = true;
3185
3186 #if ENABLE(FILTERS_LEVEL_2)
3187     if (hasBackdropFilter && m_graphicsLayer->addAnimation(backdropFilterVector, IntSize { }, &animation, keyframes.animationName(), timeOffset))
3188         didAnimate = true;
3189 #endif
3190
3191     if (didAnimate)
3192         m_owningLayer.setNeedsPostLayoutCompositingUpdate();
3193
3194     return didAnimate;
3195 }
3196
3197 void RenderLayerBacking::animationPaused(double timeOffset, const String& animationName)
3198 {
3199     m_graphicsLayer->pauseAnimation(animationName, timeOffset);
3200 }
3201
3202 void RenderLayerBacking::animationSeeked(double timeOffset, const String& animationName)
3203 {
3204     m_graphicsLayer->seekAnimation(animationName, timeOffset);
3205 }
3206
3207 void RenderLayerBacking::animationFinished(const String& animationName)
3208 {
3209     m_graphicsLayer->removeAnimation(animationName);
3210     m_owningLayer.setNeedsPostLayoutCompositingUpdate();
3211 }
3212
3213 bool RenderLayerBacking::startTransition(double timeOffset, CSSPropertyID property, const RenderStyle* fromStyle, const RenderStyle* toStyle)
3214 {
3215     bool didAnimate = false;
3216
3217     ASSERT(property != CSSPropertyInvalid);
3218
3219     if (property == CSSPropertyOpacity) {
3220         const Animation* opacityAnim = toStyle->transitionForProperty(CSSPropertyOpacity);
3221         if (opacityAnim && !opacityAnim->isEmptyOrZeroDuration()) {
3222             KeyframeValueList opacityVector(AnimatedPropertyOpacity);
3223             opacityVector.insert(std::make_unique<FloatAnimationValue>(0, compositingOpacity(fromStyle->opacity())));
3224             opacityVector.insert(std::make_unique<FloatAnimationValue>(1, compositingOpacity(toStyle->opacity())));
3225             // The boxSize param is only used for transform animations (which can only run on RenderBoxes), so we pass an empty size here.
3226             if (m_graphicsLayer->addAnimation(opacityVector, FloatSize(), opacityAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyOpacity), timeOffset)) {
3227                 // To ensure that the correct opacity is visible when the animation ends, also set the final opacity.
3228                 updateOpacity(*toStyle);
3229                 didAnimate = true;
3230             }
3231         }
3232     }
3233
3234     if (property == CSSPropertyTransform && m_owningLayer.hasTransform()) {
3235         const Animation* transformAnim = toStyle->transitionForProperty(CSSPropertyTransform);
3236         if (transformAnim && !transformAnim->isEmptyOrZeroDuration()) {
3237             KeyframeValueList transformVector(AnimatedPropertyTransform);
3238             transformVector.insert(std::make_unique<TransformAnimationValue>(0, fromStyle->transform()));
3239             transformVector.insert(std::make_unique<TransformAnimationValue>(1, toStyle->transform()));
3240             if (m_graphicsLayer->addAnimation(transformVector, snappedIntRect(renderBox()->borderBoxRect()).size(), transformAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyTransform), timeOffset)) {
3241                 // To ensure that the correct transform is visible when the animation ends, also set the final transform.
3242                 updateTransform(*toStyle);
3243                 didAnimate = true;
3244             }
3245         }
3246     }
3247
3248     if (property == CSSPropertyFilter && m_owningLayer.hasFilter()) {
3249         const Animation* filterAnim = toStyle->transitionForProperty(CSSPropertyFilter);
3250         if (filterAnim && !filterAnim->isEmptyOrZeroDuration()) {
3251             KeyframeValueList filterVector(AnimatedPropertyFilter);
3252             filterVector.insert(std::make_unique<FilterAnimationValue>(0, fromStyle->filter()));
3253             filterVector.insert(std::make_unique<FilterAnimationValue>(1, toStyle->filter()));
3254             if (m_graphicsLayer->addAnimation(filterVector, FloatSize(), filterAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyFilter), timeOffset)) {
3255                 // To ensure that the correct filter is visible when the animation ends, also set the final filter.
3256                 updateFilters(*toStyle);
3257                 didAnimate = true;
3258             }
3259         }
3260     }
3261
3262 #if ENABLE(FILTERS_LEVEL_2)
3263     if (property == CSSPropertyWebkitBackdropFilter && m_owningLayer.hasBackdropFilter()) {
3264         const Animation* backdropFilterAnim = toStyle->transitionForProperty(CSSPropertyWebkitBackdropFilter);
3265         if (backdropFilterAnim && !backdropFilterAnim->isEmptyOrZeroDuration()) {
3266             KeyframeValueList backdropFilterVector(AnimatedPropertyWebkitBackdropFilter);
3267             backdropFilterVector.insert(std::make_unique<FilterAnimationValue>(0, fromStyle->backdropFilter()));
3268             backdropFilterVector.insert(std::make_unique<FilterAnimationValue>(1, toStyle->backdropFilter()));
3269             if (m_graphicsLayer->addAnimation(backdropFilterVector, FloatSize(), backdropFilterAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyWebkitBackdropFilter), timeOffset)) {
3270                 // To ensure that the correct backdrop filter is visible when the animation ends, also set the final backdrop filter.
3271                 updateBackdropFilters(*toStyle);
3272                 didAnimate = true;
3273             }
3274         }
3275     }
3276 #endif
3277
3278     if (didAnimate)
3279         m_owningLayer.setNeedsPostLayoutCompositingUpdate();
3280
3281     return didAnimate;
3282 }
3283
3284 void RenderLayerBacking::transitionPaused(double timeOffset, CSSPropertyID property)
3285 {
3286     AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
3287     if (animatedProperty != AnimatedPropertyInvalid)
3288         m_graphicsLayer->pauseAnimation(GraphicsLayer::animationNameForTransition(animatedProperty), timeOffset);
3289 }
3290
3291 void RenderLayerBacking::transitionFinished(CSSPropertyID property)
3292 {
3293     AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
3294     if (animatedProperty != AnimatedPropertyInvalid) {
3295         m_graphicsLayer->removeAnimation(GraphicsLayer::animationNameForTransition(animatedProperty));
3296         m_owningLayer.setNeedsPostLayoutCompositingUpdate();
3297     }
3298 }
3299
3300 void RenderLayerBacking::notifyAnimationStarted(const GraphicsLayer*, const String&, MonotonicTime time)
3301 {
3302     renderer().animation().notifyAnimationStarted(renderer(), time);
3303 }
3304
3305 void RenderLayerBacking::notifyFlushRequired(const GraphicsLayer* layer)
3306 {
3307     if (renderer().renderTreeBeingDestroyed())
3308         return;
3309     compositor().scheduleLayerFlush(layer->canThrottleLayerFlush());
3310 }
3311
3312 void RenderLayerBacking::notifyFlushBeforeDisplayRefresh(const GraphicsLayer* layer)
3313 {
3314     compositor().notifyFlushBeforeDisplayRefresh(layer);
3315 }
3316
3317 // This is used for the 'freeze' API, for testing only.
3318 void RenderLayerBacking::suspendAnimations(MonotonicTime time)
3319 {
3320     m_graphicsLayer->suspendAnimations(time);
3321 }
3322
3323 void RenderLayerBacking::resumeAnimations()
3324 {
3325     m_graphicsLayer->resumeAnimations();
3326 }
3327
3328 LayoutRect RenderLayerBacking::compositedBounds() const
3329 {
3330     return m_compositedBounds;
3331 }
3332
3333 bool RenderLayerBacking::setCompositedBounds(const LayoutRect& bounds)
3334 {
3335     if (bounds == m_compositedBounds)
3336         return false;
3337
3338     m_compositedBounds = bounds;
3339     return true;
3340 }
3341
3342 LayoutRect RenderLayerBacking::compositedBoundsIncludingMargin() const
3343 {
3344     auto* tiledBacking = this->tiledBacking();
3345     if (!tiledBacking || !tiledBacking->hasMargins())
3346         return compositedBounds();