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