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