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