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