b3537b11eb4b5cb186f55e06494ecddd519ef336
[WebKit-https.git] / Source / WebCore / rendering / RenderLayerCompositor.cpp
1 /*
2  * Copyright (C) 2009, 2010 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 "RenderLayerCompositor.h"
29
30 #include "CSSAnimationController.h"
31 #include "CSSPropertyNames.h"
32 #include "CanvasRenderingContext.h"
33 #include "Chrome.h"
34 #include "ChromeClient.h"
35 #include "DocumentTimeline.h"
36 #include "Frame.h"
37 #include "FrameView.h"
38 #include "FullscreenManager.h"
39 #include "GraphicsLayer.h"
40 #include "HTMLCanvasElement.h"
41 #include "HTMLIFrameElement.h"
42 #include "HTMLNames.h"
43 #include "HitTestResult.h"
44 #include "InspectorInstrumentation.h"
45 #include "LayerAncestorClippingStack.h"
46 #include "LayerOverlapMap.h"
47 #include "Logging.h"
48 #include "NodeList.h"
49 #include "Page.h"
50 #include "PageOverlayController.h"
51 #include "RenderEmbeddedObject.h"
52 #include "RenderFragmentedFlow.h"
53 #include "RenderFullScreen.h"
54 #include "RenderGeometryMap.h"
55 #include "RenderIFrame.h"
56 #include "RenderImage.h"
57 #include "RenderLayerBacking.h"
58 #include "RenderReplica.h"
59 #include "RenderVideo.h"
60 #include "RenderView.h"
61 #include "RuntimeEnabledFeatures.h"
62 #include "ScrollingConstraints.h"
63 #include "ScrollingCoordinator.h"
64 #include "Settings.h"
65 #include "TiledBacking.h"
66 #include "TransformState.h"
67 #include <wtf/HexNumber.h>
68 #include <wtf/MemoryPressureHandler.h>
69 #include <wtf/SetForScope.h>
70 #include <wtf/SystemTracing.h>
71 #include <wtf/text/CString.h>
72 #include <wtf/text/StringBuilder.h>
73 #include <wtf/text/StringConcatenateNumbers.h>
74 #include <wtf/text/TextStream.h>
75
76 #if PLATFORM(IOS_FAMILY)
77 #include "LegacyTileCache.h"
78 #include "RenderScrollbar.h"
79 #endif
80
81 #if PLATFORM(MAC)
82 #include "LocalDefaultSystemAppearance.h"
83 #endif
84
85 #if ENABLE(TREE_DEBUGGING)
86 #include "RenderTreeAsText.h"
87 #endif
88
89 #if ENABLE(3D_TRANSFORMS)
90 // This symbol is used to determine from a script whether 3D rendering is enabled (via 'nm').
91 WEBCORE_EXPORT bool WebCoreHas3DRendering = true;
92 #endif
93
94 #if !PLATFORM(MAC) && !PLATFORM(IOS_FAMILY)
95 #define USE_COMPOSITING_FOR_SMALL_CANVASES 1
96 #endif
97
98 namespace WebCore {
99
100 #if !USE(COMPOSITING_FOR_SMALL_CANVASES)
101 static const int canvasAreaThresholdRequiringCompositing = 50 * 100;
102 #endif
103 // During page loading delay layer flushes up to this many seconds to allow them coalesce, reducing workload.
104 #if PLATFORM(IOS_FAMILY)
105 static const Seconds throttledLayerFlushInitialDelay { 500_ms };
106 static const Seconds throttledLayerFlushDelay { 1.5_s };
107 #else
108 static const Seconds throttledLayerFlushInitialDelay { 500_ms };
109 static const Seconds throttledLayerFlushDelay { 500_ms };
110 #endif
111
112 using namespace HTMLNames;
113
114 struct ScrollingTreeState {
115     Optional<ScrollingNodeID> parentNodeID;
116     size_t nextChildIndex { 0 };
117 };
118
119 struct RenderLayerCompositor::OverlapExtent {
120     LayoutRect bounds;
121     bool extentComputed { false };
122     bool hasTransformAnimation { false };
123     bool animationCausesExtentUncertainty { false };
124
125     bool knownToBeHaveExtentUncertainty() const { return extentComputed && animationCausesExtentUncertainty; }
126 };
127
128 struct RenderLayerCompositor::CompositingState {
129     CompositingState(RenderLayer* compAncestor, bool testOverlap = true)
130         : compositingAncestor(compAncestor)
131         , testingOverlap(testOverlap)
132     {
133     }
134     
135     CompositingState stateForPaintOrderChildren(RenderLayer& layer) const
136     {
137         UNUSED_PARAM(layer);
138         CompositingState childState(compositingAncestor);
139         if (layer.isStackingContext())
140             childState.stackingContextAncestor = &layer;
141         else
142             childState.stackingContextAncestor = stackingContextAncestor;
143
144         childState.backingSharingAncestor = backingSharingAncestor;
145         childState.subtreeIsCompositing = false;
146         childState.testingOverlap = testingOverlap;
147         childState.fullPaintOrderTraversalRequired = fullPaintOrderTraversalRequired;
148         childState.descendantsRequireCompositingUpdate = descendantsRequireCompositingUpdate;
149         childState.ancestorHasTransformAnimation = ancestorHasTransformAnimation;
150 #if ENABLE(CSS_COMPOSITING)
151         childState.hasNotIsolatedCompositedBlendingDescendants = false; // FIXME: should this only be reset for stacking contexts?
152 #endif
153 #if !LOG_DISABLED
154         childState.depth = depth + 1;
155 #endif
156         return childState;
157     }
158
159     void updateWithDescendantStateAndLayer(const CompositingState& childState, const RenderLayer& layer, const OverlapExtent& layerExtent, bool isUnchangedSubtree = false)
160     {
161         // Subsequent layers in the parent stacking context also need to composite.
162         subtreeIsCompositing |= childState.subtreeIsCompositing | layer.isComposited();
163         if (!isUnchangedSubtree)
164             fullPaintOrderTraversalRequired |= childState.fullPaintOrderTraversalRequired;
165
166         // Turn overlap testing off for later layers if it's already off, or if we have an animating transform.
167         // Note that if the layer clips its descendants, there's no reason to propagate the child animation to the parent layers. That's because
168         // we know for sure the animation is contained inside the clipping rectangle, which is already added to the overlap map.
169         auto canReenableOverlapTesting = [&layer]() {
170             return layer.isComposited() && RenderLayerCompositor::clipsCompositingDescendants(layer);
171         };
172         if ((!childState.testingOverlap && !canReenableOverlapTesting()) || layerExtent.knownToBeHaveExtentUncertainty())
173             testingOverlap = false;
174
175 #if ENABLE(CSS_COMPOSITING)
176         if ((layer.isComposited() && layer.hasBlendMode()) || (layer.hasNotIsolatedCompositedBlendingDescendants() && !layer.isolatesCompositedBlending()))
177             hasNotIsolatedCompositedBlendingDescendants = true;
178 #endif
179     }
180
181     bool hasNonRootCompositedAncestor() const
182     {
183         return compositingAncestor && !compositingAncestor->isRenderViewLayer();
184     }
185
186     RenderLayer* compositingAncestor;
187     RenderLayer* backingSharingAncestor { nullptr };
188     RenderLayer* stackingContextAncestor { nullptr };
189     bool subtreeIsCompositing { false };
190     bool testingOverlap { true };
191     bool fullPaintOrderTraversalRequired { false };
192     bool descendantsRequireCompositingUpdate { false };
193     bool ancestorHasTransformAnimation { false };
194 #if ENABLE(CSS_COMPOSITING)
195     bool hasNotIsolatedCompositedBlendingDescendants { false };
196 #endif
197 #if !LOG_DISABLED
198     unsigned depth { 0 };
199 #endif
200 };
201
202 class RenderLayerCompositor::BackingSharingState {
203     WTF_MAKE_NONCOPYABLE(BackingSharingState);
204 public:
205     BackingSharingState() = default;
206
207     RenderLayer* backingProviderCandidate() const { return m_backingProviderCandidate; };
208     
209     void appendSharingLayer(RenderLayer& layer)
210     {
211         ASSERT(m_backingProviderCandidate);
212         m_backingSharingLayers.append(makeWeakPtr(layer));
213     }
214
215     void updateBeforeDescendantTraversal(RenderLayer&, bool willBeComposited);
216     void updateAfterDescendantTraversal(RenderLayer&, RenderLayer* stackingContextAncestor);
217
218 private:
219     void layerWillBeComposited(RenderLayer&);
220
221     void startBackingSharingSequence(RenderLayer& candidateLayer, RenderLayer* candidateStackingContext);
222     void endBackingSharingSequence();
223
224     RenderLayer* m_backingProviderCandidate { nullptr };
225     RenderLayer* m_backingProviderStackingContext { nullptr };
226     Vector<WeakPtr<RenderLayer>> m_backingSharingLayers;
227 };
228
229 void RenderLayerCompositor::BackingSharingState::startBackingSharingSequence(RenderLayer& candidateLayer, RenderLayer* candidateStackingContext)
230 {
231     ASSERT(!m_backingProviderCandidate);
232     ASSERT(m_backingSharingLayers.isEmpty());
233
234     m_backingProviderCandidate = &candidateLayer;
235     m_backingProviderStackingContext = candidateStackingContext;
236 }
237
238 void RenderLayerCompositor::BackingSharingState::endBackingSharingSequence()
239 {
240     if (m_backingProviderCandidate) {
241         m_backingProviderCandidate->backing()->setBackingSharingLayers(WTFMove(m_backingSharingLayers));
242         m_backingSharingLayers.clear();
243     }
244     
245     m_backingProviderCandidate = nullptr;
246 }
247
248 void RenderLayerCompositor::BackingSharingState::updateBeforeDescendantTraversal(RenderLayer& layer, bool willBeComposited)
249 {
250     layer.setBackingProviderLayer(nullptr);
251
252     // A layer that composites resets backing-sharing, since subsequent layers need to composite to overlap it.
253     if (willBeComposited) {
254         m_backingSharingLayers.removeAll(&layer);
255         endBackingSharingSequence();
256     }
257 }
258
259 void RenderLayerCompositor::BackingSharingState::updateAfterDescendantTraversal(RenderLayer& layer, RenderLayer* stackingContextAncestor)
260 {
261     if (layer.isComposited()) {
262         // If this layer is being composited, clean up sharing-related state.
263         layer.disconnectFromBackingProviderLayer();
264         m_backingSharingLayers.removeAll(&layer);
265     }
266
267     if (m_backingProviderCandidate && &layer == m_backingProviderStackingContext) {
268         LOG_WITH_STREAM(Compositing, stream << "End of stacking context for backing provider " << m_backingProviderCandidate << ", ending sharing sequence with " << m_backingSharingLayers.size() << " sharing layers");
269         endBackingSharingSequence();
270     } else if (!m_backingProviderCandidate && layer.isComposited()) {
271         LOG_WITH_STREAM(Compositing, stream << "Post-descendant compositing of " << &layer << ", ending sharing sequence for " << m_backingProviderCandidate << " with " << m_backingSharingLayers.size() << " sharing layers");
272         endBackingSharingSequence();
273         startBackingSharingSequence(layer, stackingContextAncestor);
274     }
275     
276     if (&layer != m_backingProviderCandidate && layer.isComposited())
277         layer.backing()->clearBackingSharingLayers();
278 }
279
280 #if !LOG_DISABLED || ENABLE(TREE_DEBUGGING)
281 static inline bool compositingLogEnabled()
282 {
283     return LogCompositing.state == WTFLogChannelState::On;
284 }
285
286 static inline bool layersLogEnabled()
287 {
288     return LogLayers.state == WTFLogChannelState::On;
289 }
290 #endif
291
292 RenderLayerCompositor::RenderLayerCompositor(RenderView& renderView)
293     : m_renderView(renderView)
294     , m_updateCompositingLayersTimer(*this, &RenderLayerCompositor::updateCompositingLayersTimerFired)
295     , m_layerFlushTimer(*this, &RenderLayerCompositor::layerFlushTimerFired)
296 {
297 #if PLATFORM(IOS_FAMILY)
298     if (m_renderView.frameView().platformWidget())
299         m_legacyScrollingLayerCoordinator = makeUnique<LegacyWebKitScrollingLayerCoordinator>(page().chrome().client(), isMainFrameCompositor());
300 #endif
301 }
302
303 RenderLayerCompositor::~RenderLayerCompositor()
304 {
305     // Take care that the owned GraphicsLayers are deleted first as their destructors may call back here.
306     GraphicsLayer::unparentAndClear(m_rootContentsLayer);
307     
308     GraphicsLayer::unparentAndClear(m_clipLayer);
309     GraphicsLayer::unparentAndClear(m_scrollContainerLayer);
310     GraphicsLayer::unparentAndClear(m_scrolledContentsLayer);
311
312     GraphicsLayer::unparentAndClear(m_overflowControlsHostLayer);
313
314     GraphicsLayer::unparentAndClear(m_layerForHorizontalScrollbar);
315     GraphicsLayer::unparentAndClear(m_layerForVerticalScrollbar);
316     GraphicsLayer::unparentAndClear(m_layerForScrollCorner);
317
318 #if ENABLE(RUBBER_BANDING)
319     GraphicsLayer::unparentAndClear(m_layerForOverhangAreas);
320     GraphicsLayer::unparentAndClear(m_contentShadowLayer);
321     GraphicsLayer::unparentAndClear(m_layerForTopOverhangArea);
322     GraphicsLayer::unparentAndClear(m_layerForBottomOverhangArea);
323     GraphicsLayer::unparentAndClear(m_layerForHeader);
324     GraphicsLayer::unparentAndClear(m_layerForFooter);
325 #endif
326
327     ASSERT(m_rootLayerAttachment == RootLayerUnattached);
328 }
329
330 void RenderLayerCompositor::enableCompositingMode(bool enable /* = true */)
331 {
332     if (enable != m_compositing) {
333         m_compositing = enable;
334         
335         if (m_compositing) {
336             ensureRootLayer();
337             notifyIFramesOfCompositingChange();
338         } else
339             destroyRootLayer();
340         
341         
342         m_renderView.layer()->setNeedsPostLayoutCompositingUpdate();
343     }
344 }
345
346 void RenderLayerCompositor::cacheAcceleratedCompositingFlags()
347 {
348     auto& settings = m_renderView.settings();
349     bool hasAcceleratedCompositing = settings.acceleratedCompositingEnabled();
350
351     // We allow the chrome to override the settings, in case the page is rendered
352     // on a chrome that doesn't allow accelerated compositing.
353     if (hasAcceleratedCompositing) {
354         m_compositingTriggers = page().chrome().client().allowedCompositingTriggers();
355         hasAcceleratedCompositing = m_compositingTriggers;
356     }
357
358     bool showDebugBorders = settings.showDebugBorders();
359     bool showRepaintCounter = settings.showRepaintCounter();
360     bool acceleratedDrawingEnabled = settings.acceleratedDrawingEnabled();
361     bool displayListDrawingEnabled = settings.displayListDrawingEnabled();
362
363     // forceCompositingMode for subframes can only be computed after layout.
364     bool forceCompositingMode = m_forceCompositingMode;
365     if (isMainFrameCompositor())
366         forceCompositingMode = m_renderView.settings().forceCompositingMode() && hasAcceleratedCompositing; 
367     
368     if (hasAcceleratedCompositing != m_hasAcceleratedCompositing || showDebugBorders != m_showDebugBorders || showRepaintCounter != m_showRepaintCounter || forceCompositingMode != m_forceCompositingMode) {
369         if (auto* rootLayer = m_renderView.layer()) {
370             rootLayer->setNeedsCompositingConfigurationUpdate();
371             rootLayer->setDescendantsNeedUpdateBackingAndHierarchyTraversal();
372         }
373     }
374
375     bool debugBordersChanged = m_showDebugBorders != showDebugBorders;
376     m_hasAcceleratedCompositing = hasAcceleratedCompositing;
377     m_forceCompositingMode = forceCompositingMode;
378     m_showDebugBorders = showDebugBorders;
379     m_showRepaintCounter = showRepaintCounter;
380     m_acceleratedDrawingEnabled = acceleratedDrawingEnabled;
381     m_displayListDrawingEnabled = displayListDrawingEnabled;
382     
383     if (debugBordersChanged) {
384         if (m_layerForHorizontalScrollbar)
385             m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
386
387         if (m_layerForVerticalScrollbar)
388             m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
389
390         if (m_layerForScrollCorner)
391             m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
392     }
393     
394     if (updateCompositingPolicy())
395         rootRenderLayer().setDescendantsNeedCompositingRequirementsTraversal();
396 }
397
398 void RenderLayerCompositor::cacheAcceleratedCompositingFlagsAfterLayout()
399 {
400     cacheAcceleratedCompositingFlags();
401
402     if (isMainFrameCompositor())
403         return;
404
405     RequiresCompositingData queryData;
406     bool forceCompositingMode = m_hasAcceleratedCompositing && m_renderView.settings().forceCompositingMode() && requiresCompositingForScrollableFrame(queryData);
407     if (forceCompositingMode != m_forceCompositingMode) {
408         m_forceCompositingMode = forceCompositingMode;
409         rootRenderLayer().setDescendantsNeedCompositingRequirementsTraversal();
410     }
411 }
412
413 bool RenderLayerCompositor::updateCompositingPolicy()
414 {
415     if (!usesCompositing())
416         return false;
417
418     auto currentPolicy = m_compositingPolicy;
419     if (page().compositingPolicyOverride()) {
420         m_compositingPolicy = page().compositingPolicyOverride().value();
421         return m_compositingPolicy != currentPolicy;
422     }
423     
424     auto memoryPolicy = MemoryPressureHandler::currentMemoryUsagePolicy();
425     m_compositingPolicy = memoryPolicy == WTF::MemoryUsagePolicy::Unrestricted ? CompositingPolicy::Normal : CompositingPolicy::Conservative;
426     return m_compositingPolicy != currentPolicy;
427 }
428
429 bool RenderLayerCompositor::canRender3DTransforms() const
430 {
431     return hasAcceleratedCompositing() && (m_compositingTriggers & ChromeClient::ThreeDTransformTrigger);
432 }
433
434 void RenderLayerCompositor::willRecalcStyle()
435 {
436     cacheAcceleratedCompositingFlags();
437 }
438
439 bool RenderLayerCompositor::didRecalcStyleWithNoPendingLayout()
440 {
441     return updateCompositingLayers(CompositingUpdateType::AfterStyleChange);
442 }
443
444 void RenderLayerCompositor::customPositionForVisibleRectComputation(const GraphicsLayer* graphicsLayer, FloatPoint& position) const
445 {
446     if (graphicsLayer != m_scrolledContentsLayer.get())
447         return;
448
449     FloatPoint scrollPosition = -position;
450
451     if (m_renderView.frameView().scrollBehaviorForFixedElements() == StickToDocumentBounds)
452         scrollPosition = m_renderView.frameView().constrainScrollPositionForOverhang(roundedIntPoint(scrollPosition));
453
454     position = -scrollPosition;
455 }
456
457 void RenderLayerCompositor::notifyFlushRequired(const GraphicsLayer* layer)
458 {
459     scheduleLayerFlush(layer->canThrottleLayerFlush());
460 }
461
462 void RenderLayerCompositor::scheduleLayerFlush(bool canThrottle)
463 {
464     ASSERT(!m_flushingLayers);
465
466     if (canThrottle)
467         startInitialLayerFlushTimerIfNeeded();
468
469     if (canThrottle && isThrottlingLayerFlushes())
470         m_hasPendingLayerFlush = true;
471     else {
472         m_hasPendingLayerFlush = false;
473         page().renderingUpdateScheduler().scheduleRenderingUpdate();
474     }
475 }
476
477 FloatRect RenderLayerCompositor::visibleRectForLayerFlushing() const
478 {
479     const FrameView& frameView = m_renderView.frameView();
480 #if PLATFORM(IOS_FAMILY)
481     return frameView.exposedContentRect();
482 #else
483     // Having a m_scrolledContentsLayer indicates that we're doing scrolling via GraphicsLayers.
484     FloatRect visibleRect = m_scrolledContentsLayer ? FloatRect({ }, frameView.sizeForVisibleContent()) : frameView.visibleContentRect();
485
486     if (frameView.viewExposedRect())
487         visibleRect.intersect(frameView.viewExposedRect().value());
488
489     return visibleRect;
490 #endif
491 }
492
493 void RenderLayerCompositor::flushPendingLayerChanges(bool isFlushRoot)
494 {
495     // FrameView::flushCompositingStateIncludingSubframes() flushes each subframe,
496     // but GraphicsLayer::flushCompositingState() will cross frame boundaries
497     // if the GraphicsLayers are connected (the RootLayerAttachedViaEnclosingFrame case).
498     // As long as we're not the root of the flush, we can bail.
499     if (!isFlushRoot && rootLayerAttachment() == RootLayerAttachedViaEnclosingFrame)
500         return;
501
502     if (rootLayerAttachment() == RootLayerUnattached) {
503 #if PLATFORM(IOS_FAMILY)
504         startLayerFlushTimerIfNeeded();
505 #endif
506         m_shouldFlushOnReattach = true;
507         return;
508     }
509
510     auto& frameView = m_renderView.frameView();
511     AnimationUpdateBlock animationUpdateBlock(&frameView.frame().animation());
512
513     ASSERT(!m_flushingLayers);
514     {
515         SetForScope<bool> flushingLayersScope(m_flushingLayers, true);
516
517         if (auto* rootLayer = rootGraphicsLayer()) {
518             FloatRect visibleRect = visibleRectForLayerFlushing();
519             LOG_WITH_STREAM(Compositing,  stream << "\nRenderLayerCompositor " << this << " flushPendingLayerChanges (is root " << isFlushRoot << ") visible rect " << visibleRect);
520             rootLayer->flushCompositingState(visibleRect);
521         }
522         
523         ASSERT(m_flushingLayers);
524
525 #if ENABLE(TREE_DEBUGGING)
526         if (layersLogEnabled()) {
527             LOG(Layers, "RenderLayerCompositor::flushPendingLayerChanges");
528             showGraphicsLayerTree(rootGraphicsLayer());
529         }
530 #endif
531     }
532
533 #if PLATFORM(IOS_FAMILY)
534     updateScrollCoordinatedLayersAfterFlushIncludingSubframes();
535
536     if (isFlushRoot)
537         page().chrome().client().didFlushCompositingLayers();
538 #endif
539
540     ++m_layerFlushCount;
541     startLayerFlushTimerIfNeeded();
542 }
543
544 #if PLATFORM(IOS_FAMILY)
545 void RenderLayerCompositor::updateScrollCoordinatedLayersAfterFlushIncludingSubframes()
546 {
547     updateScrollCoordinatedLayersAfterFlush();
548
549     auto& frame = m_renderView.frameView().frame();
550     for (Frame* subframe = frame.tree().firstChild(); subframe; subframe = subframe->tree().traverseNext(&frame)) {
551         auto* view = subframe->contentRenderer();
552         if (!view)
553             continue;
554
555         view->compositor().updateScrollCoordinatedLayersAfterFlush();
556     }
557 }
558
559 void RenderLayerCompositor::updateScrollCoordinatedLayersAfterFlush()
560 {
561     if (m_legacyScrollingLayerCoordinator) {
562         m_legacyScrollingLayerCoordinator->registerAllViewportConstrainedLayers(*this);
563         m_legacyScrollingLayerCoordinator->registerAllScrollingLayers();
564     }
565 }
566 #endif
567
568 void RenderLayerCompositor::didChangePlatformLayerForLayer(RenderLayer& layer, const GraphicsLayer*)
569 {
570     auto* scrollingCoordinator = this->scrollingCoordinator();
571     if (!scrollingCoordinator)
572         return;
573
574     auto* backing = layer.backing();
575     if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::Scrolling))
576         updateScrollingNodeLayers(nodeID, layer, *scrollingCoordinator);
577
578     if (auto* clippingStack = layer.backing()->ancestorClippingStack())
579         clippingStack->updateScrollingNodeLayers(*scrollingCoordinator);
580
581     if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::ViewportConstrained))
582         scrollingCoordinator->setNodeLayers(nodeID, { backing->graphicsLayer() });
583
584     if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::FrameHosting))
585         scrollingCoordinator->setNodeLayers(nodeID, { backing->graphicsLayer() });
586
587     if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::Positioning))
588         scrollingCoordinator->setNodeLayers(nodeID, { backing->graphicsLayer() });
589 }
590
591 void RenderLayerCompositor::didPaintBacking(RenderLayerBacking*)
592 {
593     auto& frameView = m_renderView.frameView();
594     frameView.setLastPaintTime(MonotonicTime::now());
595     if (frameView.milestonesPendingPaint())
596         frameView.firePaintRelatedMilestonesIfNeeded();
597 }
598
599 void RenderLayerCompositor::didChangeVisibleRect()
600 {
601     auto* rootLayer = rootGraphicsLayer();
602     if (!rootLayer)
603         return;
604
605     FloatRect visibleRect = visibleRectForLayerFlushing();
606     bool requiresFlush = rootLayer->visibleRectChangeRequiresFlush(visibleRect);
607     LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor::didChangeVisibleRect " << visibleRect << " requiresFlush " << requiresFlush);
608     if (requiresFlush)
609         scheduleLayerFlush();
610 }
611
612 void RenderLayerCompositor::notifyFlushBeforeDisplayRefresh(const GraphicsLayer*)
613 {
614     if (!m_layerUpdater) {
615         PlatformDisplayID displayID = page().chrome().displayID();
616         m_layerUpdater = makeUnique<GraphicsLayerUpdater>(*this, displayID);
617     }
618     
619     m_layerUpdater->scheduleUpdate();
620 }
621
622 void RenderLayerCompositor::flushLayersSoon(GraphicsLayerUpdater&)
623 {
624     scheduleLayerFlush(true);
625 }
626
627 void RenderLayerCompositor::layerTiledBackingUsageChanged(const GraphicsLayer* graphicsLayer, bool usingTiledBacking)
628 {
629     if (usingTiledBacking) {
630         ++m_layersWithTiledBackingCount;
631         graphicsLayer->tiledBacking()->setIsInWindow(page().isInWindow());
632     } else {
633         ASSERT(m_layersWithTiledBackingCount > 0);
634         --m_layersWithTiledBackingCount;
635     }
636 }
637
638 void RenderLayerCompositor::scheduleCompositingLayerUpdate()
639 {
640     if (!m_updateCompositingLayersTimer.isActive())
641         m_updateCompositingLayersTimer.startOneShot(0_s);
642 }
643
644 void RenderLayerCompositor::updateCompositingLayersTimerFired()
645 {
646     updateCompositingLayers(CompositingUpdateType::AfterLayout);
647 }
648
649 void RenderLayerCompositor::cancelCompositingLayerUpdate()
650 {
651     m_updateCompositingLayersTimer.stop();
652 }
653
654 static Optional<ScrollingNodeID> frameHostingNodeForFrame(Frame& frame)
655 {
656     if (!frame.document() || !frame.view())
657         return { };
658
659     // Find the frame's enclosing layer in our render tree.
660     auto* ownerElement = frame.document()->ownerElement();
661     if (!ownerElement)
662         return { };
663
664     auto* frameRenderer = ownerElement->renderer();
665     if (!frameRenderer || !is<RenderWidget>(frameRenderer))
666         return { };
667
668     auto& widgetRenderer = downcast<RenderWidget>(*frameRenderer);
669     if (!widgetRenderer.hasLayer() || !widgetRenderer.layer()->isComposited()) {
670         LOG(Scrolling, "frameHostingNodeForFrame: frame renderer has no layer or is not composited.");
671         return { };
672     }
673
674     if (auto frameHostingNodeID = widgetRenderer.layer()->backing()->scrollingNodeIDForRole(ScrollCoordinationRole::FrameHosting))
675         return frameHostingNodeID;
676
677     return { };
678 }
679
680 // Returns true on a successful update.
681 bool RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType updateType, RenderLayer* updateRoot)
682 {
683     LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor " << this << " updateCompositingLayers " << updateType << " contentLayersCount " << m_contentLayersCount);
684
685     TraceScope tracingScope(CompositingUpdateStart, CompositingUpdateEnd);
686
687 #if ENABLE(TREE_DEBUGGING)
688     if (compositingLogEnabled())
689         showPaintOrderTree(m_renderView.layer());
690 #endif
691
692     if (updateType == CompositingUpdateType::AfterStyleChange || updateType == CompositingUpdateType::AfterLayout)
693         cacheAcceleratedCompositingFlagsAfterLayout(); // Some flags (e.g. forceCompositingMode) depend on layout.
694
695     m_updateCompositingLayersTimer.stop();
696
697     ASSERT(m_renderView.document().pageCacheState() == Document::NotInPageCache
698         || m_renderView.document().pageCacheState() == Document::AboutToEnterPageCache);
699     
700     // Compositing layers will be updated in Document::setVisualUpdatesAllowed(bool) if suppressed here.
701     if (!m_renderView.document().visualUpdatesAllowed())
702         return false;
703
704     // Avoid updating the layers with old values. Compositing layers will be updated after the layout is finished.
705     // This happens when m_updateCompositingLayersTimer fires before layout is updated.
706     if (m_renderView.needsLayout()) {
707         LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor " << this << " updateCompositingLayers " << updateType << " - m_renderView.needsLayout, bailing ");
708         return false;
709     }
710
711     if (!m_compositing && (m_forceCompositingMode || (isMainFrameCompositor() && page().pageOverlayController().overlayCount())))
712         enableCompositingMode(true);
713
714     bool isPageScroll = !updateRoot || updateRoot == &rootRenderLayer();
715     updateRoot = &rootRenderLayer();
716
717     if (updateType == CompositingUpdateType::OnScroll || updateType == CompositingUpdateType::OnCompositedScroll) {
718         // We only get here if we didn't scroll on the scrolling thread, so this update needs to re-position viewport-constrained layers.
719         if (m_renderView.settings().acceleratedCompositingForFixedPositionEnabled() && isPageScroll) {
720             if (auto* viewportConstrainedObjects = m_renderView.frameView().viewportConstrainedObjects()) {
721                 for (auto* renderer : *viewportConstrainedObjects) {
722                     if (auto* layer = renderer->layer())
723                         layer->setNeedsCompositingGeometryUpdate();
724                 }
725             }
726         }
727
728         // Scrolling can affect overlap. FIXME: avoid for page scrolling.
729         updateRoot->setDescendantsNeedCompositingRequirementsTraversal();
730     }
731
732     if (updateType == CompositingUpdateType::AfterLayout) {
733         // Ensure that post-layout updates push new scroll position and viewport rects onto the root node.
734         rootRenderLayer().setNeedsScrollingTreeUpdate();
735     }
736
737     if (!updateRoot->hasDescendantNeedingCompositingRequirementsTraversal() && !m_compositing) {
738         LOG_WITH_STREAM(Compositing, stream << " no compositing work to do");
739         return true;
740     }
741
742     if (!updateRoot->needsAnyCompositingTraversal()) {
743         LOG_WITH_STREAM(Compositing, stream << " updateRoot has no dirty child and doesn't need update");
744         return true;
745     }
746
747     ++m_compositingUpdateCount;
748
749     AnimationUpdateBlock animationUpdateBlock(&m_renderView.frameView().frame().animation());
750
751     SetForScope<bool> postLayoutChange(m_inPostLayoutUpdate, true);
752
753 #if !LOG_DISABLED
754     MonotonicTime startTime;
755     if (compositingLogEnabled()) {
756         ++m_rootLayerUpdateCount;
757         startTime = MonotonicTime::now();
758     }
759
760     if (compositingLogEnabled()) {
761         m_obligateCompositedLayerCount = 0;
762         m_secondaryCompositedLayerCount = 0;
763         m_obligatoryBackingStoreBytes = 0;
764         m_secondaryBackingStoreBytes = 0;
765
766         auto& frame = m_renderView.frameView().frame();
767         bool isMainFrame = isMainFrameCompositor();
768         LOG_WITH_STREAM(Compositing, stream << "\nUpdate " << m_rootLayerUpdateCount << " of " << (isMainFrame ? "main frame" : frame.tree().uniqueName().string().utf8().data()) << " - compositing policy is " << m_compositingPolicy);
769     }
770 #endif
771
772     // FIXME: optimize root-only update.
773     if (updateRoot->hasDescendantNeedingCompositingRequirementsTraversal() || updateRoot->needsCompositingRequirementsTraversal()) {
774         auto& rootLayer = rootRenderLayer();
775         CompositingState compositingState(updateRoot);
776         BackingSharingState backingSharingState;
777         LayerOverlapMap overlapMap(rootLayer);
778
779         bool descendantHas3DTransform = false;
780         computeCompositingRequirements(nullptr, rootLayer, overlapMap, compositingState, backingSharingState, descendantHas3DTransform);
781     }
782
783     LOG(Compositing, "\nRenderLayerCompositor::updateCompositingLayers - mid");
784 #if ENABLE(TREE_DEBUGGING)
785     if (compositingLogEnabled())
786         showPaintOrderTree(m_renderView.layer());
787 #endif
788
789     if (updateRoot->hasDescendantNeedingUpdateBackingOrHierarchyTraversal() || updateRoot->needsUpdateBackingOrHierarchyTraversal()) {
790         ScrollingTreeState scrollingTreeState = { 0, 0 };
791         if (!m_renderView.frame().isMainFrame())
792             scrollingTreeState.parentNodeID = frameHostingNodeForFrame(m_renderView.frame());
793
794         Vector<Ref<GraphicsLayer>> childList;
795         updateBackingAndHierarchy(*updateRoot, childList, scrollingTreeState);
796
797         // Host the document layer in the RenderView's root layer.
798         appendDocumentOverlayLayers(childList);
799         // Even when childList is empty, don't drop out of compositing mode if there are
800         // composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
801         if (childList.isEmpty() && !needsCompositingForContentOrOverlays())
802             destroyRootLayer();
803         else if (m_rootContentsLayer)
804             m_rootContentsLayer->setChildren(WTFMove(childList));
805     }
806
807 #if !LOG_DISABLED
808     if (compositingLogEnabled()) {
809         MonotonicTime endTime = MonotonicTime::now();
810         LOG(Compositing, "Total layers   primary   secondary   obligatory backing (KB)   secondary backing(KB)   total backing (KB)  update time (ms)\n");
811
812         LOG(Compositing, "%8d %11d %9d %20.2f %22.2f %22.2f %18.2f\n",
813             m_obligateCompositedLayerCount + m_secondaryCompositedLayerCount, m_obligateCompositedLayerCount,
814             m_secondaryCompositedLayerCount, m_obligatoryBackingStoreBytes / 1024, m_secondaryBackingStoreBytes / 1024, (m_obligatoryBackingStoreBytes + m_secondaryBackingStoreBytes) / 1024, (endTime - startTime).milliseconds());
815     }
816 #endif
817
818     // FIXME: Only do if dirty.
819     updateRootLayerPosition();
820
821 #if ENABLE(TREE_DEBUGGING)
822     if (compositingLogEnabled()) {
823         LOG(Compositing, "RenderLayerCompositor::updateCompositingLayers - post");
824         showPaintOrderTree(m_renderView.layer());
825     }
826 #endif
827
828     InspectorInstrumentation::layerTreeDidChange(&page());
829
830     return true;
831 }
832
833 static bool backingProviderLayerCanIncludeLayer(const RenderLayer& sharedLayer, const RenderLayer& layer)
834 {
835     // Disable sharing when painting shared layers doesn't work correctly.
836     if (layer.hasReflection())
837         return false;
838
839     return layer.ancestorLayerIsInContainingBlockChain(sharedLayer);
840 }
841
842 void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer& layer, LayerOverlapMap& overlapMap, CompositingState& compositingState, BackingSharingState& backingSharingState, bool& descendantHas3DTransform)
843 {
844     if (!layer.hasDescendantNeedingCompositingRequirementsTraversal()
845         && !layer.needsCompositingRequirementsTraversal()
846         && !compositingState.fullPaintOrderTraversalRequired
847         && !compositingState.descendantsRequireCompositingUpdate) {
848         traverseUnchangedSubtree(ancestorLayer, layer, overlapMap, compositingState, backingSharingState, descendantHas3DTransform);
849         return;
850     }
851
852     LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(compositingState.depth * 2, ' ') << &layer << (layer.isNormalFlowOnly() ? " n" : " s") << " computeCompositingRequirements (backing provider candidate " << backingSharingState.backingProviderCandidate() << ")");
853
854     // FIXME: maybe we can avoid updating all remaining layers in paint order.
855     compositingState.fullPaintOrderTraversalRequired |= layer.needsCompositingRequirementsTraversal();
856     compositingState.descendantsRequireCompositingUpdate |= layer.descendantsNeedCompositingRequirementsTraversal();
857
858     layer.updateDescendantDependentFlags();
859     layer.updateLayerListsIfNeeded();
860
861     layer.setHasCompositingDescendant(false);
862
863     // We updated compositing for direct reasons in layerStyleChanged(). Here, check for compositing that can only be evaluated after layout.
864     RequiresCompositingData queryData;
865     bool willBeComposited = layer.isComposited();
866     bool becameCompositedAfterDescendantTraversal = false;
867     IndirectCompositingReason compositingReason = compositingState.subtreeIsCompositing ? IndirectCompositingReason::Stacking : IndirectCompositingReason::None;
868
869     if (layer.needsPostLayoutCompositingUpdate() || compositingState.fullPaintOrderTraversalRequired || compositingState.descendantsRequireCompositingUpdate) {
870         layer.setIndirectCompositingReason(IndirectCompositingReason::None);
871         willBeComposited = needsToBeComposited(layer, queryData);
872     }
873
874     bool layerPaintsIntoProvidedBacking = false;
875     if (!willBeComposited && compositingState.subtreeIsCompositing && backingSharingState.backingProviderCandidate() && canBeComposited(layer) && backingProviderLayerCanIncludeLayer(*backingSharingState.backingProviderCandidate(), layer)) {
876         backingSharingState.appendSharingLayer(layer);
877         LOG(Compositing, " layer %p can share with %p", &layer, backingSharingState.backingProviderCandidate());
878         compositingReason = IndirectCompositingReason::None;
879         layerPaintsIntoProvidedBacking = true;
880     }
881
882     compositingState.fullPaintOrderTraversalRequired |= layer.subsequentLayersNeedCompositingRequirementsTraversal();
883
884     OverlapExtent layerExtent;
885     // Use the fact that we're composited as a hint to check for an animating transform.
886     // FIXME: Maybe needsToBeComposited() should return a bitmask of reasons, to avoid the need to recompute things.
887     if (willBeComposited && !layer.isRenderViewLayer())
888         layerExtent.hasTransformAnimation = isRunningTransformAnimation(layer.renderer());
889
890     bool respectTransforms = !layerExtent.hasTransformAnimation;
891     overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer, respectTransforms);
892
893     // If we know for sure the layer is going to be composited, don't bother looking it up in the overlap map
894     if (!willBeComposited && !layerPaintsIntoProvidedBacking && !overlapMap.isEmpty() && compositingState.testingOverlap) {
895         // If we're testing for overlap, we only need to composite if we overlap something that is already composited.
896         if (layerOverlaps(overlapMap, layer, layerExtent))
897             compositingReason = IndirectCompositingReason::Overlap;
898         else
899             compositingReason = IndirectCompositingReason::None;
900     }
901
902 #if ENABLE(VIDEO)
903     // Video is special. It's the only RenderLayer type that can both have
904     // RenderLayer children and whose children can't use its backing to render
905     // into. These children (the controls) always need to be promoted into their
906     // own layers to draw on top of the accelerated video.
907     if (compositingState.compositingAncestor && compositingState.compositingAncestor->renderer().isVideo())
908         compositingReason = IndirectCompositingReason::Overlap;
909 #endif
910
911     if (compositingReason != IndirectCompositingReason::None)
912         layer.setIndirectCompositingReason(compositingReason);
913
914     // Check if the computed indirect reason will force the layer to become composited.
915     if (!willBeComposited && layer.mustCompositeForIndirectReasons() && canBeComposited(layer)) {
916         LOG_WITH_STREAM(Compositing, stream << "layer " << &layer << " compositing for indirect reason " << layer.indirectCompositingReason() << " (was sharing: " << layerPaintsIntoProvidedBacking << ")");
917         willBeComposited = true;
918         layerPaintsIntoProvidedBacking = false;
919     }
920
921     // The children of this layer don't need to composite, unless there is
922     // a compositing layer among them, so start by inheriting the compositing
923     // ancestor with subtreeIsCompositing set to false.
924     CompositingState currentState = compositingState.stateForPaintOrderChildren(layer);
925     bool didPushOverlapContainer = false;
926
927     auto layerWillComposite = [&] {
928         // This layer is going to be composited, so children can safely ignore the fact that there's an
929         // animation running behind this layer, meaning they can rely on the overlap map testing again.
930         currentState.testingOverlap = true;
931         // This layer now acts as the ancestor for kids.
932         currentState.compositingAncestor = &layer;
933         // Compositing turns off backing sharing.
934         currentState.backingSharingAncestor = nullptr;
935
936         if (layerPaintsIntoProvidedBacking) {
937             layerPaintsIntoProvidedBacking = false;
938             // layerPaintsIntoProvidedBacking was only true for layers that would otherwise composite because of overlap. If we can
939             // no longer share, put this this indirect reason back on the layer so that requiresOwnBackingStore() sees it.
940             layer.setIndirectCompositingReason(IndirectCompositingReason::Overlap);
941             LOG_WITH_STREAM(Compositing, stream << "layer " << &layer << " was sharing now will composite");
942         } else {
943             overlapMap.pushCompositingContainer();
944             didPushOverlapContainer = true;
945             LOG_WITH_STREAM(CompositingOverlap, stream << "layer " << &layer << " will composite, pushed container " << overlapMap);
946         }
947
948         willBeComposited = true;
949     };
950
951     auto layerWillCompositePostDescendants = [&] {
952         layerWillComposite();
953         currentState.subtreeIsCompositing = true;
954         becameCompositedAfterDescendantTraversal = true;
955     };
956
957     if (willBeComposited) {
958         layerWillComposite();
959
960         computeExtent(overlapMap, layer, layerExtent);
961         currentState.ancestorHasTransformAnimation |= layerExtent.hasTransformAnimation;
962         // Too hard to compute animated bounds if both us and some ancestor is animating transform.
963         layerExtent.animationCausesExtentUncertainty |= layerExtent.hasTransformAnimation && compositingState.ancestorHasTransformAnimation;
964     } else if (layerPaintsIntoProvidedBacking) {
965         currentState.backingSharingAncestor = &layer;
966         overlapMap.pushCompositingContainer();
967         didPushOverlapContainer = true;
968         LOG_WITH_STREAM(CompositingOverlap, stream << "layer " << &layer << " will share, pushed container " << overlapMap);
969     }
970
971     backingSharingState.updateBeforeDescendantTraversal(layer, willBeComposited);
972
973 #if !ASSERT_DISABLED
974     LayerListMutationDetector mutationChecker(layer);
975 #endif
976
977     bool anyDescendantHas3DTransform = false;
978     bool descendantsAddedToOverlap = currentState.hasNonRootCompositedAncestor();
979
980     for (auto* childLayer : layer.negativeZOrderLayers()) {
981         computeCompositingRequirements(&layer, *childLayer, overlapMap, currentState, backingSharingState, anyDescendantHas3DTransform);
982
983         // If we have to make a layer for this child, make one now so we can have a contents layer
984         // (since we need to ensure that the -ve z-order child renders underneath our contents).
985         if (!willBeComposited && currentState.subtreeIsCompositing) {
986             layer.setIndirectCompositingReason(IndirectCompositingReason::BackgroundLayer);
987             layerWillComposite();
988         }
989     }
990
991     for (auto* childLayer : layer.normalFlowLayers())
992         computeCompositingRequirements(&layer, *childLayer, overlapMap, currentState, backingSharingState, anyDescendantHas3DTransform);
993
994     for (auto* childLayer : layer.positiveZOrderLayers())
995         computeCompositingRequirements(&layer, *childLayer, overlapMap, currentState, backingSharingState, anyDescendantHas3DTransform);
996
997     // Set the flag to say that this layer has compositing children.
998     layer.setHasCompositingDescendant(currentState.subtreeIsCompositing);
999
1000     // If we just entered compositing mode, the root will have become composited (as long as accelerated compositing is enabled).
1001     if (layer.isRenderViewLayer()) {
1002         if (usesCompositing() && m_hasAcceleratedCompositing)
1003             willBeComposited = true;
1004     }
1005
1006 #if ENABLE(CSS_COMPOSITING)
1007     bool isolatedCompositedBlending = layer.isolatesCompositedBlending();
1008     layer.setHasNotIsolatedCompositedBlendingDescendants(currentState.hasNotIsolatedCompositedBlendingDescendants);
1009     if (layer.isolatesCompositedBlending() != isolatedCompositedBlending) {
1010         // isolatedCompositedBlending affects the result of clippedByAncestor().
1011         layer.setChildrenNeedCompositingGeometryUpdate();
1012     }
1013
1014     ASSERT(!layer.hasNotIsolatedCompositedBlendingDescendants() || layer.hasNotIsolatedBlendingDescendants());
1015 #endif
1016     // Now check for reasons to become composited that depend on the state of descendant layers.
1017     IndirectCompositingReason indirectCompositingReason;
1018     if (!willBeComposited && canBeComposited(layer)
1019         && requiresCompositingForIndirectReason(layer, currentState.subtreeIsCompositing, anyDescendantHas3DTransform, layerPaintsIntoProvidedBacking, indirectCompositingReason)) {
1020         layer.setIndirectCompositingReason(indirectCompositingReason);
1021         layerWillCompositePostDescendants();
1022     }
1023     
1024     if (layer.reflectionLayer()) {
1025         // FIXME: Shouldn't we call computeCompositingRequirements to handle a reflection overlapping with another renderer?
1026         layer.reflectionLayer()->setIndirectCompositingReason(willBeComposited ? IndirectCompositingReason::Stacking : IndirectCompositingReason::None);
1027     }
1028
1029     // setHasCompositingDescendant() may have changed the answer to needsToBeComposited() when clipping, so test that now.
1030     bool isCompositedClippingLayer = canBeComposited(layer) && clipsCompositingDescendants(layer);
1031     if (isCompositedClippingLayer & !willBeComposited)
1032         layerWillCompositePostDescendants();
1033
1034     // If we're back at the root, and no other layers need to be composited, and the root layer itself doesn't need
1035     // to be composited, then we can drop out of compositing mode altogether. However, don't drop out of compositing mode
1036     // if there are composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
1037     RequiresCompositingData rootLayerQueryData;
1038     if (layer.isRenderViewLayer() && !currentState.subtreeIsCompositing && !requiresCompositingLayer(layer, rootLayerQueryData) && !m_forceCompositingMode && !needsCompositingForContentOrOverlays()) {
1039         // Don't drop out of compositing on iOS, because we may flash. See <rdar://problem/8348337>.
1040 #if !PLATFORM(IOS_FAMILY)
1041         enableCompositingMode(false);
1042         willBeComposited = false;
1043 #endif
1044     }
1045
1046     ASSERT(willBeComposited == needsToBeComposited(layer, queryData));
1047
1048     // Create or destroy backing here. However, we can't update geometry because layers above us may become composited
1049     // during post-order traversal (e.g. for clipping).
1050     if (updateBacking(layer, queryData, CompositingChangeRepaintNow, willBeComposited ? BackingRequired::Yes : BackingRequired::No)) {
1051         layer.setNeedsCompositingLayerConnection();
1052         // Child layers need to get a geometry update to recompute their position.
1053         layer.setChildrenNeedCompositingGeometryUpdate();
1054         // The composited bounds of enclosing layers depends on which descendants are composited, so they need a geometry update.
1055         layer.setNeedsCompositingGeometryUpdateOnAncestors();
1056     }
1057
1058     // Update layer state bits.
1059     if (layer.reflectionLayer() && updateLayerCompositingState(*layer.reflectionLayer(), queryData, CompositingChangeRepaintNow))
1060         layer.setNeedsCompositingLayerConnection();
1061     
1062     // FIXME: clarify needsCompositingPaintOrderChildrenUpdate. If a composited layer gets a new ancestor, it needs geometry computations.
1063     if (layer.needsCompositingPaintOrderChildrenUpdate()) {
1064         layer.setChildrenNeedCompositingGeometryUpdate();
1065         layer.setNeedsCompositingLayerConnection();
1066     }
1067
1068     layer.clearCompositingRequirementsTraversalState();
1069
1070     // Compute state passed to the caller.
1071     descendantHas3DTransform |= anyDescendantHas3DTransform || layer.has3DTransform();
1072     compositingState.updateWithDescendantStateAndLayer(currentState, layer, layerExtent);
1073     backingSharingState.updateAfterDescendantTraversal(layer, compositingState.stackingContextAncestor);
1074
1075     bool layerContributesToOverlap = (currentState.compositingAncestor && !currentState.compositingAncestor->isRenderViewLayer()) || currentState.backingSharingAncestor;
1076     updateOverlapMap(overlapMap, layer, layerExtent, didPushOverlapContainer, layerContributesToOverlap, becameCompositedAfterDescendantTraversal && !descendantsAddedToOverlap);
1077
1078     if (layer.isComposited())
1079         layer.backing()->updateAllowsBackingStoreDetaching(layerExtent.bounds);
1080
1081     overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
1082
1083     LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(compositingState.depth * 2, ' ') << &layer << " computeCompositingRequirements - willBeComposited " << willBeComposited << " (backing provider candidate " << backingSharingState.backingProviderCandidate() << ")");
1084 }
1085
1086 // We have to traverse unchanged layers to fill in the overlap map.
1087 void RenderLayerCompositor::traverseUnchangedSubtree(RenderLayer* ancestorLayer, RenderLayer& layer, LayerOverlapMap& overlapMap, CompositingState& compositingState, BackingSharingState& backingSharingState, bool& descendantHas3DTransform)
1088 {
1089     ASSERT(!compositingState.fullPaintOrderTraversalRequired);
1090     ASSERT(!layer.hasDescendantNeedingCompositingRequirementsTraversal());
1091     ASSERT(!layer.needsCompositingRequirementsTraversal());
1092
1093     LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(compositingState.depth * 2, ' ') << &layer << (layer.isNormalFlowOnly() ? " n" : " s") << " traverseUnchangedSubtree");
1094
1095     layer.updateDescendantDependentFlags();
1096     layer.updateLayerListsIfNeeded();
1097
1098     bool layerIsComposited = layer.isComposited();
1099     bool layerPaintsIntoProvidedBacking = false;
1100     bool didPushOverlapContainer = false;
1101
1102     OverlapExtent layerExtent;
1103     if (layerIsComposited && !layer.isRenderViewLayer())
1104         layerExtent.hasTransformAnimation = isRunningTransformAnimation(layer.renderer());
1105
1106     bool respectTransforms = !layerExtent.hasTransformAnimation;
1107     overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer, respectTransforms);
1108
1109     // If we know for sure the layer is going to be composited, don't bother looking it up in the overlap map
1110     if (!layerIsComposited && !overlapMap.isEmpty() && compositingState.testingOverlap)
1111         computeExtent(overlapMap, layer, layerExtent);
1112
1113     if (layer.paintsIntoProvidedBacking()) {
1114         ASSERT(backingSharingState.backingProviderCandidate());
1115         ASSERT(backingProviderLayerCanIncludeLayer(*backingSharingState.backingProviderCandidate(), layer));
1116         backingSharingState.appendSharingLayer(layer);
1117         layerPaintsIntoProvidedBacking = true;
1118     }
1119
1120     CompositingState currentState = compositingState.stateForPaintOrderChildren(layer);
1121
1122     if (layerIsComposited) {
1123         // This layer is going to be composited, so children can safely ignore the fact that there's an
1124         // animation running behind this layer, meaning they can rely on the overlap map testing again.
1125         currentState.testingOverlap = true;
1126         // This layer now acts as the ancestor for kids.
1127         currentState.compositingAncestor = &layer;
1128         currentState.backingSharingAncestor = nullptr;
1129         overlapMap.pushCompositingContainer();
1130         didPushOverlapContainer = true;
1131         LOG_WITH_STREAM(CompositingOverlap, stream << "unchangedSubtree: layer " << &layer << " will composite, pushed container " << overlapMap);
1132
1133         computeExtent(overlapMap, layer, layerExtent);
1134         currentState.ancestorHasTransformAnimation |= layerExtent.hasTransformAnimation;
1135         // Too hard to compute animated bounds if both us and some ancestor is animating transform.
1136         layerExtent.animationCausesExtentUncertainty |= layerExtent.hasTransformAnimation && compositingState.ancestorHasTransformAnimation;
1137     } else if (layerPaintsIntoProvidedBacking) {
1138         overlapMap.pushCompositingContainer();
1139         currentState.backingSharingAncestor = &layer;
1140         didPushOverlapContainer = true;
1141         LOG_WITH_STREAM(CompositingOverlap, stream << "unchangedSubtree: layer " << &layer << " will share, pushed container " << overlapMap);
1142     }
1143
1144     backingSharingState.updateBeforeDescendantTraversal(layer, layerIsComposited);
1145
1146 #if !ASSERT_DISABLED
1147     LayerListMutationDetector mutationChecker(layer);
1148 #endif
1149
1150     bool anyDescendantHas3DTransform = false;
1151
1152     for (auto* childLayer : layer.negativeZOrderLayers()) {
1153         traverseUnchangedSubtree(&layer, *childLayer, overlapMap, currentState, backingSharingState, anyDescendantHas3DTransform);
1154         if (currentState.subtreeIsCompositing)
1155             ASSERT(layerIsComposited);
1156     }
1157
1158     for (auto* childLayer : layer.normalFlowLayers())
1159         traverseUnchangedSubtree(&layer, *childLayer, overlapMap, currentState, backingSharingState, anyDescendantHas3DTransform);
1160
1161     for (auto* childLayer : layer.positiveZOrderLayers())
1162         traverseUnchangedSubtree(&layer, *childLayer, overlapMap, currentState, backingSharingState, anyDescendantHas3DTransform);
1163
1164     // Set the flag to say that this layer has compositing children.
1165     ASSERT(layer.hasCompositingDescendant() == currentState.subtreeIsCompositing);
1166     ASSERT_IMPLIES(canBeComposited(layer) && clipsCompositingDescendants(layer), layerIsComposited);
1167
1168     descendantHas3DTransform |= anyDescendantHas3DTransform || layer.has3DTransform();
1169
1170     ASSERT(!currentState.fullPaintOrderTraversalRequired);
1171     compositingState.updateWithDescendantStateAndLayer(currentState, layer, layerExtent, true);
1172     backingSharingState.updateAfterDescendantTraversal(layer, compositingState.stackingContextAncestor);
1173
1174     bool layerContributesToOverlap = (currentState.compositingAncestor && !currentState.compositingAncestor->isRenderViewLayer()) || currentState.backingSharingAncestor;
1175     updateOverlapMap(overlapMap, layer, layerExtent, didPushOverlapContainer, layerContributesToOverlap);
1176
1177     overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
1178
1179     ASSERT(!layer.needsCompositingRequirementsTraversal());
1180 }
1181
1182 void RenderLayerCompositor::updateBackingAndHierarchy(RenderLayer& layer, Vector<Ref<GraphicsLayer>>& childLayersOfEnclosingLayer, ScrollingTreeState& scrollingTreeState, OptionSet<UpdateLevel> updateLevel, int depth)
1183 {
1184     layer.updateDescendantDependentFlags();
1185     layer.updateLayerListsIfNeeded();
1186
1187     bool layerNeedsUpdate = !updateLevel.isEmpty();
1188     if (layer.descendantsNeedUpdateBackingAndHierarchyTraversal())
1189         updateLevel.add(UpdateLevel::AllDescendants);
1190
1191     ScrollingTreeState stateForDescendants = scrollingTreeState;
1192
1193     auto* layerBacking = layer.backing();
1194     if (layerBacking) {
1195         updateLevel.remove(UpdateLevel::CompositedChildren);
1196
1197         // We updated the composited bounds in RenderLayerBacking::updateAfterLayout(), but it may have changed
1198         // based on which descendants are now composited.
1199         if (layerBacking->updateCompositedBounds()) {
1200             layer.setNeedsCompositingGeometryUpdate();
1201             // Our geometry can affect descendants.
1202             updateLevel.add(UpdateLevel::CompositedChildren);
1203         }
1204         
1205         if (layerNeedsUpdate || layer.needsCompositingConfigurationUpdate()) {
1206             if (layerBacking->updateConfiguration()) {
1207                 layerNeedsUpdate = true; // We also need to update geometry.
1208                 layer.setNeedsCompositingLayerConnection();
1209             }
1210
1211             layerBacking->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
1212         }
1213         
1214         OptionSet<ScrollingNodeChangeFlags> scrollingNodeChanges = { ScrollingNodeChangeFlags::Layer };
1215         if (layerNeedsUpdate || layer.needsCompositingGeometryUpdate()) {
1216             layerBacking->updateGeometry();
1217             scrollingNodeChanges.add(ScrollingNodeChangeFlags::LayerGeometry);
1218         } else if (layer.needsScrollingTreeUpdate())
1219             scrollingNodeChanges.add(ScrollingNodeChangeFlags::LayerGeometry);
1220
1221         // This needs to happen after any geometry update.
1222         // FIXME: Use separate bit for event region invalidation.
1223         if (layerNeedsUpdate || layer.needsCompositingConfigurationUpdate())
1224             layerBacking->updateEventRegion();
1225
1226         if (auto* reflection = layer.reflectionLayer()) {
1227             if (auto* reflectionBacking = reflection->backing()) {
1228                 reflectionBacking->updateCompositedBounds();
1229                 reflectionBacking->updateGeometry();
1230                 reflectionBacking->updateAfterDescendants();
1231             }
1232         }
1233
1234         if (!layer.parent())
1235             updateRootLayerPosition();
1236
1237         // FIXME: do based on dirty flags. Need to do this for changes of geometry, configuration and hierarchy.
1238         // Need to be careful to do the right thing when a scroll-coordinated layer loses a scroll-coordinated ancestor.
1239         stateForDescendants.parentNodeID = updateScrollCoordinationForLayer(layer, scrollingTreeState, scrollingNodeChanges);
1240         stateForDescendants.nextChildIndex = 0;
1241
1242 #if !LOG_DISABLED
1243         logLayerInfo(layer, "updateBackingAndHierarchy", depth);
1244 #else
1245         UNUSED_PARAM(depth);
1246 #endif
1247     }
1248
1249     if (layer.childrenNeedCompositingGeometryUpdate())
1250         updateLevel.add(UpdateLevel::CompositedChildren);
1251
1252     // If this layer has backing, then we are collecting its children, otherwise appending
1253     // to the compositing child list of an enclosing layer.
1254     Vector<Ref<GraphicsLayer>> layerChildren;
1255     auto& childList = layerBacking ? layerChildren : childLayersOfEnclosingLayer;
1256
1257     bool requireDescendantTraversal = layer.hasDescendantNeedingUpdateBackingOrHierarchyTraversal()
1258         || (layer.hasCompositingDescendant() && (!layerBacking || layer.needsCompositingLayerConnection() || !updateLevel.isEmpty()));
1259
1260     bool requiresChildRebuild = layerBacking && layer.needsCompositingLayerConnection() && !layer.hasCompositingDescendant();
1261
1262 #if !ASSERT_DISABLED
1263     LayerListMutationDetector mutationChecker(layer);
1264 #endif
1265
1266     auto appendForegroundLayerIfNecessary = [&] {
1267         // If a negative z-order child is compositing, we get a foreground layer which needs to get parented.
1268         if (layer.negativeZOrderLayers().size()) {
1269             if (layerBacking && layerBacking->foregroundLayer())
1270                 childList.append(*layerBacking->foregroundLayer());
1271         }
1272     };
1273
1274     if (requireDescendantTraversal) {
1275         for (auto* renderLayer : layer.negativeZOrderLayers())
1276             updateBackingAndHierarchy(*renderLayer, childList, stateForDescendants, updateLevel, depth + 1);
1277
1278         appendForegroundLayerIfNecessary();
1279
1280         for (auto* renderLayer : layer.normalFlowLayers())
1281             updateBackingAndHierarchy(*renderLayer, childList, stateForDescendants, updateLevel, depth + 1);
1282         
1283         for (auto* renderLayer : layer.positiveZOrderLayers())
1284             updateBackingAndHierarchy(*renderLayer, childList, stateForDescendants, updateLevel, depth + 1);
1285     } else if (requiresChildRebuild)
1286         appendForegroundLayerIfNecessary();
1287
1288     if (layerBacking) {
1289         if (requireDescendantTraversal || requiresChildRebuild) {
1290             bool parented = false;
1291             if (is<RenderWidget>(layer.renderer()))
1292                 parented = parentFrameContentLayers(downcast<RenderWidget>(layer.renderer()));
1293
1294             if (!parented)
1295                 layerBacking->parentForSublayers()->setChildren(WTFMove(layerChildren));
1296
1297             // If the layer has a clipping layer the overflow controls layers will be siblings of the clipping layer.
1298             // Otherwise, the overflow control layers are normal children.
1299             if (!layerBacking->hasClippingLayer() && !layerBacking->hasScrollingLayer()) {
1300                 if (auto* overflowControlLayer = layerBacking->layerForHorizontalScrollbar())
1301                     layerBacking->parentForSublayers()->addChild(*overflowControlLayer);
1302
1303                 if (auto* overflowControlLayer = layerBacking->layerForVerticalScrollbar())
1304                     layerBacking->parentForSublayers()->addChild(*overflowControlLayer);
1305
1306                 if (auto* overflowControlLayer = layerBacking->layerForScrollCorner())
1307                     layerBacking->parentForSublayers()->addChild(*overflowControlLayer);
1308             }
1309         }
1310
1311         childLayersOfEnclosingLayer.append(*layerBacking->childForSuperlayers());
1312
1313         layerBacking->updateAfterDescendants();
1314     }
1315     
1316     layer.clearUpdateBackingOrHierarchyTraversalState();
1317 }
1318
1319 void RenderLayerCompositor::appendDocumentOverlayLayers(Vector<Ref<GraphicsLayer>>& childList)
1320 {
1321     if (!isMainFrameCompositor() || !m_compositing)
1322         return;
1323
1324     if (!page().pageOverlayController().hasDocumentOverlays())
1325         return;
1326
1327     Ref<GraphicsLayer> overlayHost = page().pageOverlayController().layerWithDocumentOverlays();
1328     childList.append(WTFMove(overlayHost));
1329 }
1330
1331 bool RenderLayerCompositor::needsCompositingForContentOrOverlays() const
1332 {
1333     return m_contentLayersCount + page().pageOverlayController().overlayCount();
1334 }
1335
1336 void RenderLayerCompositor::layerBecameComposited(const RenderLayer& layer)
1337 {
1338     if (&layer != m_renderView.layer())
1339         ++m_contentLayersCount;
1340 }
1341
1342 void RenderLayerCompositor::layerBecameNonComposited(const RenderLayer& layer)
1343 {
1344     // Inform the inspector that the given RenderLayer was destroyed.
1345     // FIXME: "destroyed" is a misnomer.
1346     InspectorInstrumentation::renderLayerDestroyed(&page(), layer);
1347
1348     if (&layer != m_renderView.layer()) {
1349         ASSERT(m_contentLayersCount > 0);
1350         --m_contentLayersCount;
1351     }
1352 }
1353
1354 #if !LOG_DISABLED
1355 void RenderLayerCompositor::logLayerInfo(const RenderLayer& layer, const char* phase, int depth)
1356 {
1357     if (!compositingLogEnabled())
1358         return;
1359
1360     auto* backing = layer.backing();
1361     RequiresCompositingData queryData;
1362     if (requiresCompositingLayer(layer, queryData) || layer.isRenderViewLayer()) {
1363         ++m_obligateCompositedLayerCount;
1364         m_obligatoryBackingStoreBytes += backing->backingStoreMemoryEstimate();
1365     } else {
1366         ++m_secondaryCompositedLayerCount;
1367         m_secondaryBackingStoreBytes += backing->backingStoreMemoryEstimate();
1368     }
1369
1370     LayoutRect absoluteBounds = backing->compositedBounds();
1371     absoluteBounds.move(layer.offsetFromAncestor(m_renderView.layer()));
1372     
1373     StringBuilder logString;
1374     logString.append(pad(' ', 12 + depth * 2, hex(reinterpret_cast<uintptr_t>(&layer))), " id ", backing->graphicsLayer()->primaryLayerID(), " (", FormattedNumber::fixedWidth(absoluteBounds.x().toFloat(), 3), ',', FormattedNumber::fixedWidth(absoluteBounds.y().toFloat(), 3), '-', FormattedNumber::fixedWidth(absoluteBounds.maxX().toFloat(), 3), ',', FormattedNumber::fixedWidth(absoluteBounds.maxY().toFloat(), 3), ") ", FormattedNumber::fixedWidth(backing->backingStoreMemoryEstimate() / 1024, 2), "KB");
1375
1376     if (!layer.renderer().style().hasAutoZIndex())
1377         logString.append(" z-index: ", layer.renderer().style().zIndex());
1378
1379     logString.append(" (", logReasonsForCompositing(layer), ") ");
1380
1381     if (backing->graphicsLayer()->contentsOpaque() || backing->paintsIntoCompositedAncestor() || backing->foregroundLayer() || backing->backgroundLayer()) {
1382         logString.append('[');
1383         bool prependSpace = false;
1384         if (backing->graphicsLayer()->contentsOpaque()) {
1385             logString.appendLiteral("opaque");
1386             prependSpace = true;
1387         }
1388
1389         if (backing->paintsIntoCompositedAncestor()) {
1390             if (prependSpace)
1391                 logString.appendLiteral(", ");
1392             logString.appendLiteral("paints into ancestor");
1393             prependSpace = true;
1394         }
1395
1396         if (backing->foregroundLayer() || backing->backgroundLayer()) {
1397             if (prependSpace)
1398                 logString.appendLiteral(", ");
1399             if (backing->foregroundLayer() && backing->backgroundLayer()) {
1400                 logString.appendLiteral("+foreground+background");
1401                 prependSpace = true;
1402             } else if (backing->foregroundLayer()) {
1403                 logString.appendLiteral("+foreground");
1404                 prependSpace = true;
1405             } else {
1406                 logString.appendLiteral("+background");
1407                 prependSpace = true;
1408             }
1409         }
1410         
1411         if (backing->paintsSubpixelAntialiasedText()) {
1412             if (prependSpace)
1413                 logString.appendLiteral(", ");
1414             logString.appendLiteral("texty");
1415         }
1416
1417         logString.appendLiteral("] ");
1418     }
1419
1420     logString.append(layer.name());
1421
1422     logString.appendLiteral(" - ");
1423     logString.append(phase);
1424
1425     LOG(Compositing, "%s", logString.toString().utf8().data());
1426 }
1427 #endif
1428
1429 static bool clippingChanged(const RenderStyle& oldStyle, const RenderStyle& newStyle)
1430 {
1431     return oldStyle.overflowX() != newStyle.overflowX() || oldStyle.overflowY() != newStyle.overflowY()
1432         || oldStyle.hasClip() != newStyle.hasClip() || oldStyle.clip() != newStyle.clip();
1433 }
1434
1435 static bool styleAffectsLayerGeometry(const RenderStyle& style)
1436 {
1437     return style.hasClip() || style.clipPath() || style.hasBorderRadius();
1438 }
1439
1440 static bool recompositeChangeRequiresGeometryUpdate(const RenderStyle& oldStyle, const RenderStyle& newStyle)
1441 {
1442     return oldStyle.transform() != newStyle.transform()
1443         || oldStyle.transformOriginX() != newStyle.transformOriginX()
1444         || oldStyle.transformOriginY() != newStyle.transformOriginY()
1445         || oldStyle.transformOriginZ() != newStyle.transformOriginZ()
1446         || oldStyle.transformStyle3D() != newStyle.transformStyle3D()
1447         || oldStyle.perspective() != newStyle.perspective()
1448         || oldStyle.perspectiveOriginX() != newStyle.perspectiveOriginX()
1449         || oldStyle.perspectiveOriginY() != newStyle.perspectiveOriginY()
1450         || oldStyle.backfaceVisibility() != newStyle.backfaceVisibility()
1451         || !arePointingToEqualData(oldStyle.clipPath(), newStyle.clipPath());
1452 }
1453
1454 void RenderLayerCompositor::layerStyleChanged(StyleDifference diff, RenderLayer& layer, const RenderStyle* oldStyle)
1455 {
1456     if (diff == StyleDifference::Equal)
1457         return;
1458
1459     // Create or destroy backing here so that code that runs during layout can reliably use isComposited() (though this
1460     // is only true for layers composited for direct reasons).
1461     // Also, it allows us to avoid a tree walk in updateCompositingLayers() when no layer changed its compositing state.
1462     RequiresCompositingData queryData;
1463     queryData.layoutUpToDate = LayoutUpToDate::No;
1464     
1465     bool layerChanged = updateBacking(layer, queryData, CompositingChangeRepaintNow);
1466     if (layerChanged) {
1467         layer.setChildrenNeedCompositingGeometryUpdate();
1468         layer.setNeedsCompositingLayerConnection();
1469         layer.setSubsequentLayersNeedCompositingRequirementsTraversal();
1470         // Ancestor layers that composited for indirect reasons (things listed in styleChangeMayAffectIndirectCompositingReasons()) need to get updated.
1471         // This could be optimized by only setting this flag on layers with the relevant styles.
1472         layer.setNeedsPostLayoutCompositingUpdateOnAncestors();
1473     }
1474     
1475     if (queryData.reevaluateAfterLayout)
1476         layer.setNeedsPostLayoutCompositingUpdate();
1477
1478     const auto& newStyle = layer.renderer().style();
1479
1480     if (hasContentCompositingLayers()) {
1481         if (diff >= StyleDifference::LayoutPositionedMovementOnly) {
1482             layer.setNeedsPostLayoutCompositingUpdate();
1483             layer.setNeedsCompositingGeometryUpdate();
1484         }
1485
1486         if (diff >= StyleDifference::Layout) {
1487             // FIXME: only set flags here if we know we have a composited descendant, but we might not know at this point.
1488             if (oldStyle && clippingChanged(*oldStyle, newStyle)) {
1489                 if (layer.isStackingContext()) {
1490                     layer.setNeedsPostLayoutCompositingUpdate(); // Layer needs to become composited if it has composited descendants.
1491                     layer.setNeedsCompositingConfigurationUpdate(); // If already composited, layer needs to create/destroy clipping layer.
1492                 } else {
1493                     // Descendant (in containing block order) compositing layers need to re-evaluate their clipping,
1494                     // but they might be siblings in z-order so go up to our stacking context.
1495                     if (auto* stackingContext = layer.stackingContext())
1496                         stackingContext->setDescendantsNeedUpdateBackingAndHierarchyTraversal();
1497                 }
1498             }
1499
1500             // These properties trigger compositing if some descendant is composited.
1501             if (oldStyle && styleChangeMayAffectIndirectCompositingReasons(*oldStyle, newStyle))
1502                 layer.setNeedsPostLayoutCompositingUpdate();
1503
1504             layer.setNeedsCompositingGeometryUpdate();
1505         }
1506     }
1507
1508     auto* backing = layer.backing();
1509     if (!backing)
1510         return;
1511
1512     backing->updateConfigurationAfterStyleChange();
1513
1514     if (diff >= StyleDifference::Repaint) {
1515         // Visibility change may affect geometry of the enclosing composited layer.
1516         if (oldStyle && oldStyle->visibility() != newStyle.visibility())
1517             layer.setNeedsCompositingGeometryUpdate();
1518         
1519         // We'll get a diff of Repaint when things like clip-path change; these might affect layer or inner-layer geometry.
1520         if (layer.isComposited() && oldStyle) {
1521             if (styleAffectsLayerGeometry(*oldStyle) || styleAffectsLayerGeometry(newStyle))
1522                 layer.setNeedsCompositingGeometryUpdate();
1523         }
1524     }
1525
1526     // This is necessary to get iframe layers hooked up in response to scheduleInvalidateStyleAndLayerComposition().
1527     if (diff == StyleDifference::RecompositeLayer && layer.isComposited() && is<RenderWidget>(layer.renderer()))
1528         layer.setNeedsCompositingConfigurationUpdate();
1529
1530     if (diff >= StyleDifference::RecompositeLayer && oldStyle && recompositeChangeRequiresGeometryUpdate(*oldStyle, newStyle)) {
1531         // FIXME: transform changes really need to trigger layout. See RenderElement::adjustStyleDifference().
1532         layer.setNeedsPostLayoutCompositingUpdate();
1533         layer.setNeedsCompositingGeometryUpdate();
1534     }
1535 }
1536
1537 bool RenderLayerCompositor::needsCompositingUpdateForStyleChangeOnNonCompositedLayer(RenderLayer& layer, const RenderStyle* oldStyle) const
1538 {
1539     // Needed for scroll bars.
1540     if (layer.isRenderViewLayer())
1541         return true;
1542
1543     if (!oldStyle)
1544         return false;
1545
1546     const RenderStyle& newStyle = layer.renderer().style();
1547     // Visibility change may affect geometry of the enclosing composited layer.
1548     if (oldStyle->visibility() != newStyle.visibility())
1549         return true;
1550
1551     // We don't have any direct reasons for this style change to affect layer composition. Test if it might affect things indirectly.
1552     if (styleChangeMayAffectIndirectCompositingReasons(*oldStyle, newStyle))
1553         return true;
1554
1555     return false;
1556 }
1557
1558 bool RenderLayerCompositor::canCompositeClipPath(const RenderLayer& layer)
1559 {
1560     ASSERT(layer.isComposited());
1561     ASSERT(layer.renderer().style().clipPath());
1562
1563     if (layer.renderer().hasMask())
1564         return false;
1565
1566     auto& clipPath = *layer.renderer().style().clipPath();
1567     return (clipPath.type() != ClipPathOperation::Shape || clipPath.type() == ClipPathOperation::Shape) && GraphicsLayer::supportsLayerType(GraphicsLayer::Type::Shape);
1568 }
1569
1570 // FIXME: remove and never ask questions about reflection layers.
1571 static RenderLayerModelObject& rendererForCompositingTests(const RenderLayer& layer)
1572 {
1573     auto* renderer = &layer.renderer();
1574
1575     // The compositing state of a reflection should match that of its reflected layer.
1576     if (layer.isReflection())
1577         renderer = downcast<RenderLayerModelObject>(renderer->parent()); // The RenderReplica's parent is the object being reflected.
1578
1579     return *renderer;
1580 }
1581
1582 void RenderLayerCompositor::updateRootContentLayerClipping()
1583 {
1584     m_rootContentsLayer->setMasksToBounds(!m_renderView.settings().backgroundShouldExtendBeyondPage());
1585 }
1586
1587 bool RenderLayerCompositor::updateBacking(RenderLayer& layer, RequiresCompositingData& queryData, CompositingChangeRepaint shouldRepaint, BackingRequired backingRequired)
1588 {
1589     bool layerChanged = false;
1590     if (backingRequired == BackingRequired::Unknown)
1591         backingRequired = needsToBeComposited(layer, queryData) ? BackingRequired::Yes : BackingRequired::No;
1592     else {
1593         // Need to fetch viewportConstrainedNotCompositedReason, but without doing all the work that needsToBeComposited does.
1594         requiresCompositingForPosition(rendererForCompositingTests(layer), layer, queryData);
1595     }
1596
1597     if (backingRequired == BackingRequired::Yes) {
1598         layer.disconnectFromBackingProviderLayer();
1599
1600         enableCompositingMode();
1601         
1602         if (!layer.backing()) {
1603             // If we need to repaint, do so before making backing
1604             if (shouldRepaint == CompositingChangeRepaintNow)
1605                 repaintOnCompositingChange(layer); // wrong backing
1606
1607             layer.ensureBacking();
1608
1609             if (layer.isRenderViewLayer() && useCoordinatedScrollingForLayer(layer)) {
1610                 auto& frameView = m_renderView.frameView();
1611                 if (auto* scrollingCoordinator = this->scrollingCoordinator())
1612                     scrollingCoordinator->frameViewRootLayerDidChange(frameView);
1613 #if ENABLE(RUBBER_BANDING)
1614                 updateLayerForHeader(frameView.headerHeight());
1615                 updateLayerForFooter(frameView.footerHeight());
1616 #endif
1617                 updateRootContentLayerClipping();
1618
1619                 if (auto* tiledBacking = layer.backing()->tiledBacking())
1620                     tiledBacking->setTopContentInset(frameView.topContentInset());
1621             }
1622
1623             // This layer and all of its descendants have cached repaints rects that are relative to
1624             // the repaint container, so change when compositing changes; we need to update them here.
1625             if (layer.parent())
1626                 layer.computeRepaintRectsIncludingDescendants();
1627
1628             layer.setNeedsCompositingGeometryUpdate();
1629             layer.setNeedsCompositingConfigurationUpdate();
1630             layer.setNeedsCompositingPaintOrderChildrenUpdate();
1631
1632             layerChanged = true;
1633         }
1634     } else {
1635         if (layer.backing()) {
1636             // If we're removing backing on a reflection, clear the source GraphicsLayer's pointer to
1637             // its replica GraphicsLayer. In practice this should never happen because reflectee and reflection 
1638             // are both either composited, or not composited.
1639             if (layer.isReflection()) {
1640                 auto* sourceLayer = downcast<RenderLayerModelObject>(*layer.renderer().parent()).layer();
1641                 if (auto* backing = sourceLayer->backing()) {
1642                     ASSERT(backing->graphicsLayer()->replicaLayer() == layer.backing()->graphicsLayer());
1643                     backing->graphicsLayer()->setReplicatedByLayer(nullptr);
1644                 }
1645             }
1646
1647             layer.clearBacking();
1648             layerChanged = true;
1649
1650             // This layer and all of its descendants have cached repaints rects that are relative to
1651             // the repaint container, so change when compositing changes; we need to update them here.
1652             layer.computeRepaintRectsIncludingDescendants();
1653
1654             // If we need to repaint, do so now that we've removed the backing
1655             if (shouldRepaint == CompositingChangeRepaintNow)
1656                 repaintOnCompositingChange(layer);
1657         }
1658     }
1659     
1660 #if ENABLE(VIDEO)
1661     if (layerChanged && is<RenderVideo>(layer.renderer())) {
1662         // If it's a video, give the media player a chance to hook up to the layer.
1663         downcast<RenderVideo>(layer.renderer()).acceleratedRenderingStateChanged();
1664     }
1665 #endif
1666
1667     if (layerChanged && is<RenderWidget>(layer.renderer())) {
1668         auto* innerCompositor = frameContentsCompositor(downcast<RenderWidget>(layer.renderer()));
1669         if (innerCompositor && innerCompositor->usesCompositing())
1670             innerCompositor->updateRootLayerAttachment();
1671     }
1672     
1673     if (layerChanged)
1674         layer.clearClipRectsIncludingDescendants(PaintingClipRects);
1675
1676     // If a fixed position layer gained/lost a backing or the reason not compositing it changed,
1677     // the scrolling coordinator needs to recalculate whether it can do fast scrolling.
1678     if (layer.renderer().isFixedPositioned()) {
1679         if (layer.viewportConstrainedNotCompositedReason() != queryData.nonCompositedForPositionReason) {
1680             layer.setViewportConstrainedNotCompositedReason(queryData.nonCompositedForPositionReason);
1681             layerChanged = true;
1682         }
1683         if (layerChanged) {
1684             if (auto* scrollingCoordinator = this->scrollingCoordinator())
1685                 scrollingCoordinator->frameViewFixedObjectsDidChange(m_renderView.frameView());
1686         }
1687     } else
1688         layer.setViewportConstrainedNotCompositedReason(RenderLayer::NoNotCompositedReason);
1689     
1690     if (layer.backing())
1691         layer.backing()->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
1692
1693     return layerChanged;
1694 }
1695
1696 bool RenderLayerCompositor::updateLayerCompositingState(RenderLayer& layer, RequiresCompositingData& queryData, CompositingChangeRepaint shouldRepaint)
1697 {
1698     bool layerChanged = updateBacking(layer, queryData, shouldRepaint);
1699
1700     // See if we need content or clipping layers. Methods called here should assume
1701     // that the compositing state of descendant layers has not been updated yet.
1702     if (layer.backing() && layer.backing()->updateConfiguration())
1703         layerChanged = true;
1704
1705     return layerChanged;
1706 }
1707
1708 void RenderLayerCompositor::repaintOnCompositingChange(RenderLayer& layer)
1709 {
1710     // If the renderer is not attached yet, no need to repaint.
1711     if (&layer.renderer() != &m_renderView && !layer.renderer().parent())
1712         return;
1713
1714     auto* repaintContainer = layer.renderer().containerForRepaint();
1715     if (!repaintContainer)
1716         repaintContainer = &m_renderView;
1717
1718     layer.repaintIncludingNonCompositingDescendants(repaintContainer);
1719     if (repaintContainer == &m_renderView) {
1720         // The contents of this layer may be moving between the window
1721         // and a GraphicsLayer, so we need to make sure the window system
1722         // synchronizes those changes on the screen.
1723         m_renderView.frameView().setNeedsOneShotDrawingSynchronization();
1724     }
1725 }
1726
1727 // This method assumes that layout is up-to-date, unlike repaintOnCompositingChange().
1728 void RenderLayerCompositor::repaintInCompositedAncestor(RenderLayer& layer, const LayoutRect& rect)
1729 {
1730     auto* compositedAncestor = layer.enclosingCompositingLayerForRepaint(ExcludeSelf);
1731     if (!compositedAncestor)
1732         return;
1733
1734     ASSERT(compositedAncestor->backing());
1735     LayoutRect repaintRect = rect;
1736     repaintRect.move(layer.offsetFromAncestor(compositedAncestor));
1737     compositedAncestor->setBackingNeedsRepaintInRect(repaintRect);
1738
1739     // The contents of this layer may be moving from a GraphicsLayer to the window,
1740     // so we need to make sure the window system synchronizes those changes on the screen.
1741     if (compositedAncestor->isRenderViewLayer())
1742         m_renderView.frameView().setNeedsOneShotDrawingSynchronization();
1743 }
1744
1745 // FIXME: remove.
1746 void RenderLayerCompositor::layerWasAdded(RenderLayer&, RenderLayer&)
1747 {
1748 }
1749
1750 void RenderLayerCompositor::layerWillBeRemoved(RenderLayer& parent, RenderLayer& child)
1751 {
1752     if (parent.renderer().renderTreeBeingDestroyed())
1753         return;
1754
1755     if (child.isComposited())
1756         repaintInCompositedAncestor(child, child.backing()->compositedBounds()); // FIXME: do via dirty bits?
1757     else if (child.paintsIntoProvidedBacking()) {
1758         auto* backingProviderLayer = child.backingProviderLayer();
1759         // FIXME: Optimize this repaint.
1760         backingProviderLayer->setBackingNeedsRepaint();
1761         backingProviderLayer->backing()->removeBackingSharingLayer(child);
1762     } else
1763         return;
1764
1765     child.setNeedsCompositingLayerConnection();
1766 }
1767
1768 RenderLayer* RenderLayerCompositor::enclosingNonStackingClippingLayer(const RenderLayer& layer) const
1769 {
1770     for (auto* parent = layer.parent(); parent; parent = parent->parent()) {
1771         if (parent->isStackingContext())
1772             return nullptr;
1773         if (parent->renderer().hasClipOrOverflowClip())
1774             return parent;
1775     }
1776     return nullptr;
1777 }
1778
1779 void RenderLayerCompositor::computeExtent(const LayerOverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& extent) const
1780 {
1781     if (extent.extentComputed)
1782         return;
1783
1784     LayoutRect layerBounds;
1785     if (extent.hasTransformAnimation)
1786         extent.animationCausesExtentUncertainty = !layer.getOverlapBoundsIncludingChildrenAccountingForTransformAnimations(layerBounds);
1787     else
1788         layerBounds = layer.overlapBounds();
1789     
1790     // In the animating transform case, we avoid double-accounting for the transform because
1791     // we told pushMappingsToAncestor() to ignore transforms earlier.
1792     extent.bounds = enclosingLayoutRect(overlapMap.geometryMap().absoluteRect(layerBounds));
1793
1794     // Empty rects never intersect, but we need them to for the purposes of overlap testing.
1795     if (extent.bounds.isEmpty())
1796         extent.bounds.setSize(LayoutSize(1, 1));
1797
1798     RenderLayerModelObject& renderer = layer.renderer();
1799     if (renderer.isFixedPositioned() && renderer.container() == &m_renderView) {
1800         // Because fixed elements get moved around without re-computing overlap, we have to compute an overlap
1801         // rect that covers all the locations that the fixed element could move to.
1802         // FIXME: need to handle sticky too.
1803         extent.bounds = m_renderView.frameView().fixedScrollableAreaBoundsInflatedForScrolling(extent.bounds);
1804     }
1805
1806     extent.extentComputed = true;
1807 }
1808
1809 enum class AncestorTraversal { Continue, Stop };
1810
1811 // This is a simplified version of containing block walking that only handles absolute position.
1812 template <typename Function>
1813 static AncestorTraversal traverseAncestorLayers(const RenderLayer& layer, Function&& function)
1814 {
1815     bool containingBlockCanSkipLayers = layer.renderer().isAbsolutelyPositioned();
1816     RenderLayer* nextPaintOrderParent = layer.paintOrderParent();
1817
1818     for (const auto* ancestorLayer = layer.parent(); ancestorLayer; ancestorLayer = ancestorLayer->parent()) {
1819         bool inContainingBlockChain = true;
1820
1821         if (containingBlockCanSkipLayers)
1822             inContainingBlockChain = ancestorLayer->renderer().canContainAbsolutelyPositionedObjects();
1823
1824         if (function(*ancestorLayer, inContainingBlockChain, ancestorLayer == nextPaintOrderParent) == AncestorTraversal::Stop)
1825             return AncestorTraversal::Stop;
1826
1827         if (inContainingBlockChain)
1828             containingBlockCanSkipLayers = ancestorLayer->renderer().isAbsolutelyPositioned();
1829         
1830         if (ancestorLayer == nextPaintOrderParent)
1831             nextPaintOrderParent = ancestorLayer->paintOrderParent();
1832     }
1833     
1834     return AncestorTraversal::Continue;
1835 }
1836
1837 static bool createsClippingScope(const RenderLayer& layer)
1838 {
1839     return layer.hasCompositedScrollableOverflow();
1840 }
1841
1842 static Vector<LayerOverlapMap::LayerAndBounds> enclosingClippingScopes(const RenderLayer& layer, const RenderLayer& rootLayer)
1843 {
1844     Vector<LayerOverlapMap::LayerAndBounds> clippingScopes;
1845     clippingScopes.append({ const_cast<RenderLayer&>(rootLayer), { } });
1846
1847     if (!layer.hasCompositedScrollingAncestor())
1848         return clippingScopes;
1849
1850     traverseAncestorLayers(layer, [&](const RenderLayer& ancestorLayer, bool inContainingBlockChain, bool) {
1851         if (inContainingBlockChain && createsClippingScope(ancestorLayer)) {
1852             LayoutRect clipRect;
1853             if (is<RenderBox>(ancestorLayer.renderer())) {
1854                 // FIXME: This is expensive. Broken with transforms.
1855                 LayoutPoint offsetFromRoot = ancestorLayer.convertToLayerCoords(&rootLayer, { });
1856                 clipRect = downcast<RenderBox>(ancestorLayer.renderer()).overflowClipRect(offsetFromRoot);
1857             }
1858
1859             LayerOverlapMap::LayerAndBounds layerAndBounds { const_cast<RenderLayer&>(ancestorLayer), clipRect };
1860             clippingScopes.insert(1, layerAndBounds); // Order is roots to leaves.
1861         }
1862         return AncestorTraversal::Continue;
1863     });
1864
1865     return clippingScopes;
1866 }
1867
1868 void RenderLayerCompositor::addToOverlapMap(LayerOverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& extent) const
1869 {
1870     if (layer.isRenderViewLayer())
1871         return;
1872
1873     computeExtent(overlapMap, layer, extent);
1874
1875     // FIXME: constrain the scopes (by composited stacking context ancestor I think).
1876     auto clippingScopes = enclosingClippingScopes(layer, rootRenderLayer());
1877
1878     LayoutRect clipRect;
1879     if (layer.hasCompositedScrollingAncestor()) {
1880         // Compute a clip up to the composited scrolling ancestor, then convert it to absolute coordinates.
1881         auto& scrollingScope = clippingScopes.last();
1882         clipRect = layer.backgroundClipRect(RenderLayer::ClipRectsContext(&scrollingScope.layer, TemporaryClipRects, IgnoreOverlayScrollbarSize, IgnoreOverflowClip)).rect();
1883         if (!clipRect.isInfinite())
1884             clipRect.setLocation(layer.convertToLayerCoords(&rootRenderLayer(), clipRect.location()));
1885     } else
1886         clipRect = layer.backgroundClipRect(RenderLayer::ClipRectsContext(&rootRenderLayer(), AbsoluteClipRects)).rect(); // FIXME: Incorrect for CSS regions.
1887
1888     auto clippedBounds = extent.bounds;
1889     if (!clipRect.isInfinite()) {
1890         // On iOS, pageScaleFactor() is not applied by RenderView, so we should not scale here.
1891         if (!m_renderView.settings().delegatesPageScaling())
1892             clipRect.scale(pageScaleFactor());
1893
1894         clippedBounds.intersect(clipRect);
1895     }
1896
1897     overlapMap.add(layer, clippedBounds, clippingScopes);
1898 }
1899
1900 void RenderLayerCompositor::addDescendantsToOverlapMapRecursive(LayerOverlapMap& overlapMap, const RenderLayer& layer, const RenderLayer* ancestorLayer) const
1901 {
1902     if (!canBeComposited(layer))
1903         return;
1904
1905     // A null ancestorLayer is an indication that 'layer' has already been pushed.
1906     if (ancestorLayer) {
1907         overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer);
1908     
1909         OverlapExtent layerExtent;
1910         addToOverlapMap(overlapMap, layer, layerExtent);
1911     }
1912
1913 #if !ASSERT_DISABLED
1914     LayerListMutationDetector mutationChecker(const_cast<RenderLayer&>(layer));
1915 #endif
1916
1917     for (auto* renderLayer : layer.negativeZOrderLayers())
1918         addDescendantsToOverlapMapRecursive(overlapMap, *renderLayer, &layer);
1919
1920     for (auto* renderLayer : layer.normalFlowLayers())
1921         addDescendantsToOverlapMapRecursive(overlapMap, *renderLayer, &layer);
1922
1923     for (auto* renderLayer : layer.positiveZOrderLayers())
1924         addDescendantsToOverlapMapRecursive(overlapMap, *renderLayer, &layer);
1925     
1926     if (ancestorLayer)
1927         overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
1928 }
1929
1930 void RenderLayerCompositor::updateOverlapMap(LayerOverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& layerExtent, bool didPushContainer, bool addLayerToOverlap, bool addDescendantsToOverlap) const
1931 {
1932     if (addLayerToOverlap) {
1933         addToOverlapMap(overlapMap, layer, layerExtent);
1934         LOG_WITH_STREAM(CompositingOverlap, stream << "layer " << &layer << " contributes to overlap, added to map " << overlapMap);
1935     }
1936
1937     if (addDescendantsToOverlap) {
1938         // If this is the first non-root layer to composite, we need to add all the descendants we already traversed to the overlap map.
1939         addDescendantsToOverlapMapRecursive(overlapMap, layer);
1940         LOG_WITH_STREAM(CompositingOverlap, stream << "layer " << &layer << " composited post descendant traversal, added recursive " << overlapMap);
1941     }
1942
1943     if (didPushContainer) {
1944         overlapMap.popCompositingContainer();
1945         LOG_WITH_STREAM(CompositingOverlap, stream << "layer " << &layer << " is composited or shared, popped container " << overlapMap);
1946     }
1947 }
1948
1949 bool RenderLayerCompositor::layerOverlaps(const LayerOverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& layerExtent) const
1950 {
1951     computeExtent(overlapMap, layer, layerExtent);
1952
1953     auto clippingScopes = enclosingClippingScopes(layer, rootRenderLayer());
1954     return overlapMap.overlapsLayers(layer, layerExtent.bounds, clippingScopes);
1955 }
1956
1957 #if ENABLE(VIDEO)
1958 bool RenderLayerCompositor::canAccelerateVideoRendering(RenderVideo& video) const
1959 {
1960     if (!m_hasAcceleratedCompositing)
1961         return false;
1962
1963     return video.supportsAcceleratedRendering();
1964 }
1965 #endif
1966
1967 void RenderLayerCompositor::frameViewDidChangeLocation(const IntPoint& contentsOffset)
1968 {
1969     if (m_overflowControlsHostLayer)
1970         m_overflowControlsHostLayer->setPosition(contentsOffset);
1971 }
1972
1973 void RenderLayerCompositor::frameViewDidChangeSize()
1974 {
1975     if (auto* layer = m_renderView.layer())
1976         layer->setNeedsCompositingGeometryUpdate();
1977
1978     if (m_scrolledContentsLayer) {
1979         updateScrollLayerClipping();
1980         frameViewDidScroll();
1981         updateOverflowControlsLayers();
1982
1983 #if ENABLE(RUBBER_BANDING)
1984         if (m_layerForOverhangAreas) {
1985             auto& frameView = m_renderView.frameView();
1986             m_layerForOverhangAreas->setSize(frameView.frameRect().size());
1987             m_layerForOverhangAreas->setPosition(FloatPoint(0, frameView.topContentInset()));
1988         }
1989 #endif
1990     }
1991 }
1992
1993 void RenderLayerCompositor::widgetDidChangeSize(RenderWidget& widget)
1994 {
1995     if (!widget.hasLayer())
1996         return;
1997
1998     auto& layer = *widget.layer();
1999
2000     LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor " << this << " widgetDidChangeSize (layer " << &layer << ")");
2001
2002     // Widget size affects answer to requiresCompositingForFrame() so we need to trigger
2003     // a compositing update.
2004     layer.setNeedsPostLayoutCompositingUpdate();
2005     scheduleCompositingLayerUpdate();
2006
2007     if (layer.isComposited())
2008         layer.backing()->updateAfterWidgetResize();
2009 }
2010
2011 bool RenderLayerCompositor::hasCoordinatedScrolling() const
2012 {
2013     auto* scrollingCoordinator = this->scrollingCoordinator();
2014     return scrollingCoordinator && scrollingCoordinator->coordinatesScrollingForFrameView(m_renderView.frameView());
2015 }
2016
2017 void RenderLayerCompositor::updateScrollLayerPosition()
2018 {
2019     ASSERT(!hasCoordinatedScrolling());
2020     ASSERT(m_scrolledContentsLayer);
2021
2022     auto& frameView = m_renderView.frameView();
2023     IntPoint scrollPosition = frameView.scrollPosition();
2024
2025     // We use scroll position here because the root content layer is offset to account for scrollOrigin (see FrameView::positionForRootContentLayer).
2026     m_scrolledContentsLayer->setPosition(FloatPoint(-scrollPosition.x(), -scrollPosition.y()));
2027
2028     if (auto* fixedBackgroundLayer = fixedRootBackgroundLayer())
2029         fixedBackgroundLayer->setPosition(frameView.scrollPositionForFixedPosition());
2030 }
2031
2032 void RenderLayerCompositor::updateScrollLayerClipping()
2033 {
2034     auto* layerForClipping = this->layerForClipping();
2035     if (!layerForClipping)
2036         return;
2037
2038     layerForClipping->setSize(m_renderView.frameView().sizeForVisibleContent());
2039     layerForClipping->setPosition(positionForClipLayer());
2040 }
2041
2042 FloatPoint RenderLayerCompositor::positionForClipLayer() const
2043 {
2044     auto& frameView = m_renderView.frameView();
2045
2046     return FloatPoint(
2047         frameView.shouldPlaceBlockDirectionScrollbarOnLeft() ? frameView.horizontalScrollbarIntrusion() : 0,
2048         FrameView::yPositionForInsetClipLayer(frameView.scrollPosition(), frameView.topContentInset()));
2049 }
2050
2051 void RenderLayerCompositor::frameViewDidScroll()
2052 {
2053     if (!m_scrolledContentsLayer)
2054         return;
2055
2056     // If there's a scrolling coordinator that manages scrolling for this frame view,
2057     // it will also manage updating the scroll layer position.
2058     if (hasCoordinatedScrolling()) {
2059         // We have to schedule a flush in order for the main TiledBacking to update its tile coverage.
2060         scheduleLayerFlush();
2061         return;
2062     }
2063
2064     updateScrollLayerPosition();
2065 }
2066
2067 void RenderLayerCompositor::frameViewDidAddOrRemoveScrollbars()
2068 {
2069     updateOverflowControlsLayers();
2070 }
2071
2072 void RenderLayerCompositor::frameViewDidLayout()
2073 {
2074     if (auto* renderViewBacking = m_renderView.layer()->backing())
2075         renderViewBacking->adjustTiledBackingCoverage();
2076 }
2077
2078 void RenderLayerCompositor::rootLayerConfigurationChanged()
2079 {
2080     auto* renderViewBacking = m_renderView.layer()->backing();
2081     if (renderViewBacking && renderViewBacking->isFrameLayerWithTiledBacking()) {
2082         m_renderView.layer()->setNeedsCompositingConfigurationUpdate();
2083         scheduleCompositingLayerUpdate();
2084     }
2085 }
2086
2087 String RenderLayerCompositor::layerTreeAsText(LayerTreeFlags flags)
2088 {
2089     updateCompositingLayers(CompositingUpdateType::AfterLayout);
2090
2091     if (!m_rootContentsLayer)
2092         return String();
2093
2094     flushPendingLayerChanges(true);
2095     page().renderingUpdateScheduler().scheduleImmediateRenderingUpdate();
2096
2097     LayerTreeAsTextBehavior layerTreeBehavior = LayerTreeAsTextBehaviorNormal;
2098     if (flags & LayerTreeFlagsIncludeDebugInfo)
2099         layerTreeBehavior |= LayerTreeAsTextDebug;
2100     if (flags & LayerTreeFlagsIncludeVisibleRects)
2101         layerTreeBehavior |= LayerTreeAsTextIncludeVisibleRects;
2102     if (flags & LayerTreeFlagsIncludeTileCaches)
2103         layerTreeBehavior |= LayerTreeAsTextIncludeTileCaches;
2104     if (flags & LayerTreeFlagsIncludeRepaintRects)
2105         layerTreeBehavior |= LayerTreeAsTextIncludeRepaintRects;
2106     if (flags & LayerTreeFlagsIncludePaintingPhases)
2107         layerTreeBehavior |= LayerTreeAsTextIncludePaintingPhases;
2108     if (flags & LayerTreeFlagsIncludeContentLayers)
2109         layerTreeBehavior |= LayerTreeAsTextIncludeContentLayers;
2110     if (flags & LayerTreeFlagsIncludeAcceleratesDrawing)
2111         layerTreeBehavior |= LayerTreeAsTextIncludeAcceleratesDrawing;
2112     if (flags & LayerTreeFlagsIncludeClipping)
2113         layerTreeBehavior |= LayerTreeAsTextIncludeClipping;
2114     if (flags & LayerTreeFlagsIncludeBackingStoreAttached)
2115         layerTreeBehavior |= LayerTreeAsTextIncludeBackingStoreAttached;
2116     if (flags & LayerTreeFlagsIncludeRootLayerProperties)
2117         layerTreeBehavior |= LayerTreeAsTextIncludeRootLayerProperties;
2118     if (flags & LayerTreeFlagsIncludeEventRegion)
2119         layerTreeBehavior |= LayerTreeAsTextIncludeEventRegion;
2120
2121     // We skip dumping the scroll and clip layers to keep layerTreeAsText output
2122     // similar between platforms.
2123     String layerTreeText = m_rootContentsLayer->layerTreeAsText(layerTreeBehavior);
2124
2125     // Dump an empty layer tree only if the only composited layer is the main frame's tiled backing,
2126     // so that tests expecting us to drop out of accelerated compositing when there are no layers succeed.
2127     if (!hasContentCompositingLayers() && documentUsesTiledBacking() && !(layerTreeBehavior & LayerTreeAsTextIncludeTileCaches) && !(layerTreeBehavior & LayerTreeAsTextIncludeRootLayerProperties))
2128         layerTreeText = emptyString();
2129
2130     // The true root layer is not included in the dump, so if we want to report
2131     // its repaint rects, they must be included here.
2132     if (flags & LayerTreeFlagsIncludeRepaintRects)
2133         return m_renderView.frameView().trackedRepaintRectsAsText() + layerTreeText;
2134
2135     return layerTreeText;
2136 }
2137
2138 static RenderView* frameContentsRenderView(RenderWidget& renderer)
2139 {
2140     if (auto* contentDocument = renderer.frameOwnerElement().contentDocument())
2141         return contentDocument->renderView();
2142
2143     return nullptr;
2144 }
2145
2146 RenderLayerCompositor* RenderLayerCompositor::frameContentsCompositor(RenderWidget& renderer)
2147 {
2148     if (auto* view = frameContentsRenderView(renderer))
2149         return &view->compositor();
2150
2151     return nullptr;
2152 }
2153
2154 bool RenderLayerCompositor::parentFrameContentLayers(RenderWidget& renderer)
2155 {
2156     auto* innerCompositor = frameContentsCompositor(renderer);
2157     if (!innerCompositor || !innerCompositor->usesCompositing() || innerCompositor->rootLayerAttachment() != RootLayerAttachedViaEnclosingFrame)
2158         return false;
2159     
2160     auto* layer = renderer.layer();
2161     if (!layer->isComposited())
2162         return false;
2163
2164     auto* backing = layer->backing();
2165     auto* hostingLayer = backing->parentForSublayers();
2166     auto* rootLayer = innerCompositor->rootGraphicsLayer();
2167     if (hostingLayer->children().size() != 1 || hostingLayer->children()[0].ptr() != rootLayer) {
2168         hostingLayer->removeAllChildren();
2169         hostingLayer->addChild(*rootLayer);
2170     }
2171
2172     if (auto frameHostingNodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::FrameHosting)) {
2173         auto* contentsRenderView = frameContentsRenderView(renderer);
2174         if (auto frameRootScrollingNodeID = contentsRenderView->frameView().scrollingNodeID()) {
2175             if (auto* scrollingCoordinator = this->scrollingCoordinator())
2176                 scrollingCoordinator->insertNode(ScrollingNodeType::Subframe, frameRootScrollingNodeID, frameHostingNodeID, 0);
2177         }
2178     }
2179
2180     // FIXME: Why always return true and not just when the layers changed?
2181     return true;
2182 }
2183
2184 void RenderLayerCompositor::repaintCompositedLayers()
2185 {
2186     recursiveRepaintLayer(rootRenderLayer());
2187 }
2188
2189 void RenderLayerCompositor::recursiveRepaintLayer(RenderLayer& layer)
2190 {
2191     layer.updateLayerListsIfNeeded();
2192
2193     // FIXME: This method does not work correctly with transforms.
2194     if (layer.isComposited() && !layer.backing()->paintsIntoCompositedAncestor())
2195         layer.setBackingNeedsRepaint();
2196
2197 #if !ASSERT_DISABLED
2198     LayerListMutationDetector mutationChecker(layer);
2199 #endif
2200
2201     if (layer.hasCompositingDescendant()) {
2202         for (auto* renderLayer : layer.negativeZOrderLayers())
2203             recursiveRepaintLayer(*renderLayer);
2204
2205         for (auto* renderLayer : layer.positiveZOrderLayers())
2206             recursiveRepaintLayer(*renderLayer);
2207     }
2208
2209     for (auto* renderLayer : layer.normalFlowLayers())
2210         recursiveRepaintLayer(*renderLayer);
2211 }
2212
2213 RenderLayer& RenderLayerCompositor::rootRenderLayer() const
2214 {
2215     return *m_renderView.layer();
2216 }
2217
2218 GraphicsLayer* RenderLayerCompositor::rootGraphicsLayer() const
2219 {
2220     if (m_overflowControlsHostLayer)
2221         return m_overflowControlsHostLayer.get();
2222     return m_rootContentsLayer.get();
2223 }
2224
2225 void RenderLayerCompositor::setIsInWindow(bool isInWindow)
2226 {
2227     LOG(Compositing, "RenderLayerCompositor %p setIsInWindow %d", this, isInWindow);
2228
2229     if (!usesCompositing())
2230         return;
2231
2232     if (auto* rootLayer = rootGraphicsLayer()) {
2233         GraphicsLayer::traverse(*rootLayer, [isInWindow](GraphicsLayer& layer) {
2234             layer.setIsInWindow(isInWindow);
2235         });
2236     }
2237
2238     if (isInWindow) {
2239         if (m_rootLayerAttachment != RootLayerUnattached)
2240             return;
2241
2242         RootLayerAttachment attachment = isMainFrameCompositor() ? RootLayerAttachedViaChromeClient : RootLayerAttachedViaEnclosingFrame;
2243         attachRootLayer(attachment);
2244 #if PLATFORM(IOS_FAMILY)
2245         if (m_legacyScrollingLayerCoordinator) {
2246             m_legacyScrollingLayerCoordinator->registerAllViewportConstrainedLayers(*this);
2247             m_legacyScrollingLayerCoordinator->registerAllScrollingLayers();
2248         }
2249 #endif
2250     } else {
2251         if (m_rootLayerAttachment == RootLayerUnattached)
2252             return;
2253
2254         detachRootLayer();
2255 #if PLATFORM(IOS_FAMILY)
2256         if (m_legacyScrollingLayerCoordinator) {
2257             m_legacyScrollingLayerCoordinator->unregisterAllViewportConstrainedLayers();
2258             m_legacyScrollingLayerCoordinator->unregisterAllScrollingLayers();
2259         }
2260 #endif
2261     }
2262 }
2263
2264 void RenderLayerCompositor::clearBackingForLayerIncludingDescendants(RenderLayer& layer)
2265 {
2266     if (layer.isComposited())
2267         layer.clearBacking();
2268
2269     for (auto* childLayer = layer.firstChild(); childLayer; childLayer = childLayer->nextSibling())
2270         clearBackingForLayerIncludingDescendants(*childLayer);
2271 }
2272
2273 void RenderLayerCompositor::clearBackingForAllLayers()
2274 {
2275     clearBackingForLayerIncludingDescendants(*m_renderView.layer());
2276 }
2277
2278 void RenderLayerCompositor::updateRootLayerPosition()
2279 {
2280     if (m_rootContentsLayer) {
2281         m_rootContentsLayer->setSize(m_renderView.frameView().contentsSize());
2282         m_rootContentsLayer->setPosition(m_renderView.frameView().positionForRootContentLayer());
2283         m_rootContentsLayer->setAnchorPoint(FloatPoint3D());
2284     }
2285
2286     updateScrollLayerClipping();
2287
2288 #if ENABLE(RUBBER_BANDING)
2289     if (m_contentShadowLayer && m_rootContentsLayer) {
2290         m_contentShadowLayer->setPosition(m_rootContentsLayer->position());
2291         m_contentShadowLayer->setSize(m_rootContentsLayer->size());
2292     }
2293
2294     updateLayerForTopOverhangArea(m_layerForTopOverhangArea != nullptr);
2295     updateLayerForBottomOverhangArea(m_layerForBottomOverhangArea != nullptr);
2296     updateLayerForHeader(m_layerForHeader != nullptr);
2297     updateLayerForFooter(m_layerForFooter != nullptr);
2298 #endif
2299 }
2300
2301 bool RenderLayerCompositor::has3DContent() const
2302 {
2303     return layerHas3DContent(rootRenderLayer());
2304 }
2305
2306 bool RenderLayerCompositor::needsToBeComposited(const RenderLayer& layer, RequiresCompositingData& queryData) const
2307 {
2308     if (!canBeComposited(layer))
2309         return false;
2310
2311     return requiresCompositingLayer(layer, queryData) || layer.mustCompositeForIndirectReasons() || (usesCompositing() && layer.isRenderViewLayer());
2312 }
2313
2314 // Note: this specifies whether the RL needs a compositing layer for intrinsic reasons.
2315 // Use needsToBeComposited() to determine if a RL actually needs a compositing layer.
2316 // FIXME: is clipsCompositingDescendants() an intrinsic reason?
2317 bool RenderLayerCompositor::requiresCompositingLayer(const RenderLayer& layer, RequiresCompositingData& queryData) const
2318 {
2319     auto& renderer = rendererForCompositingTests(layer);
2320
2321     // The root layer always has a compositing layer, but it may not have backing.
2322     return requiresCompositingForTransform(renderer)
2323         || requiresCompositingForAnimation(renderer)
2324         || clipsCompositingDescendants(*renderer.layer())
2325         || requiresCompositingForPosition(renderer, *renderer.layer(), queryData)
2326         || requiresCompositingForCanvas(renderer)
2327         || requiresCompositingForFilters(renderer)
2328         || requiresCompositingForWillChange(renderer)
2329         || requiresCompositingForBackfaceVisibility(renderer)
2330         || requiresCompositingForVideo(renderer)
2331         || requiresCompositingForFrame(renderer, queryData)
2332         || requiresCompositingForPlugin(renderer, queryData)
2333         || requiresCompositingForEditableImage(renderer)
2334         || requiresCompositingForOverflowScrolling(*renderer.layer(), queryData);
2335 }
2336
2337 bool RenderLayerCompositor::canBeComposited(const RenderLayer& layer) const
2338 {
2339     if (m_hasAcceleratedCompositing && layer.isSelfPaintingLayer()) {
2340         if (!layer.isInsideFragmentedFlow())
2341             return true;
2342
2343         // CSS Regions flow threads do not need to be composited as we use composited RenderFragmentContainers
2344         // to render the background of the RenderFragmentedFlow.
2345         if (layer.isRenderFragmentedFlow())
2346             return false;
2347
2348         return true;
2349     }
2350     return false;
2351 }
2352
2353 #if ENABLE(FULLSCREEN_API)
2354 enum class FullScreenDescendant { Yes, No, NotApplicable };
2355 static FullScreenDescendant isDescendantOfFullScreenLayer(const RenderLayer& layer)
2356 {
2357     auto& document = layer.renderer().document();
2358
2359     if (!document.fullscreenManager().isFullscreen() || !document.fullscreenManager().fullscreenRenderer())
2360         return FullScreenDescendant::NotApplicable;
2361
2362     auto* fullScreenLayer = document.fullscreenManager().fullscreenRenderer()->layer();
2363     if (!fullScreenLayer) {
2364         ASSERT_NOT_REACHED();
2365         return FullScreenDescendant::NotApplicable;
2366     }
2367
2368     return layer.isDescendantOf(*fullScreenLayer) ? FullScreenDescendant::Yes : FullScreenDescendant::No;
2369 }
2370 #endif
2371
2372 bool RenderLayerCompositor::requiresOwnBackingStore(const RenderLayer& layer, const RenderLayer* compositingAncestorLayer, const LayoutRect& layerCompositedBoundsInAncestor, const LayoutRect& ancestorCompositedBounds) const
2373 {
2374     auto& renderer = layer.renderer();
2375
2376     if (compositingAncestorLayer
2377         && !(compositingAncestorLayer->backing()->graphicsLayer()->drawsContent()
2378             || compositingAncestorLayer->backing()->paintsIntoWindow()
2379             || compositingAncestorLayer->backing()->paintsIntoCompositedAncestor()))
2380         return true;
2381
2382     RequiresCompositingData queryData;
2383     if (layer.isRenderViewLayer()
2384         || layer.transform() // note: excludes perspective and transformStyle3D.
2385         || requiresCompositingForAnimation(renderer)
2386         || requiresCompositingForPosition(renderer, layer, queryData)
2387         || requiresCompositingForCanvas(renderer)
2388         || requiresCompositingForFilters(renderer)
2389         || requiresCompositingForWillChange(renderer)
2390         || requiresCompositingForBackfaceVisibility(renderer)
2391         || requiresCompositingForVideo(renderer)
2392         || requiresCompositingForFrame(renderer, queryData)
2393         || requiresCompositingForPlugin(renderer, queryData)
2394         || requiresCompositingForEditableImage(renderer)
2395         || requiresCompositingForOverflowScrolling(layer, queryData)
2396         || needsContentsCompositingLayer(layer)
2397         || renderer.isTransparent()
2398         || renderer.hasMask()
2399         || renderer.hasReflection()
2400         || renderer.hasFilter()
2401         || renderer.hasBackdropFilter())
2402         return true;
2403
2404     if (layer.mustCompositeForIndirectReasons()) {
2405         IndirectCompositingReason reason = layer.indirectCompositingReason();
2406         return reason == IndirectCompositingReason::Overlap
2407             || reason == IndirectCompositingReason::OverflowScrollPositioning
2408             || reason == IndirectCompositingReason::Stacking
2409             || reason == IndirectCompositingReason::BackgroundLayer
2410             || reason == IndirectCompositingReason::GraphicalEffect
2411             || reason == IndirectCompositingReason::Preserve3D; // preserve-3d has to create backing store to ensure that 3d-transformed elements intersect.
2412     }
2413
2414     if (!ancestorCompositedBounds.contains(layerCompositedBoundsInAncestor))
2415         return true;
2416
2417     if (layer.isComposited() && layer.backing()->hasBackingSharingLayers())
2418         return true;
2419
2420     return false;
2421 }
2422
2423 OptionSet<CompositingReason> RenderLayerCompositor::reasonsForCompositing(const RenderLayer& layer) const
2424 {
2425     OptionSet<CompositingReason> reasons;
2426
2427     if (!layer.isComposited())
2428         return reasons;
2429
2430     RequiresCompositingData queryData;
2431
2432     auto& renderer = rendererForCompositingTests(layer);
2433
2434     if (requiresCompositingForTransform(renderer))
2435         reasons.add(CompositingReason::Transform3D);
2436
2437     if (requiresCompositingForVideo(renderer))
2438         reasons.add(CompositingReason::Video);
2439     else if (requiresCompositingForCanvas(renderer))
2440         reasons.add(CompositingReason::Canvas);
2441     else if (requiresCompositingForPlugin(renderer, queryData))
2442         reasons.add(CompositingReason::Plugin);
2443     else if (requiresCompositingForFrame(renderer, queryData))
2444         reasons.add(CompositingReason::IFrame);
2445     else if (requiresCompositingForEditableImage(renderer))
2446         reasons.add(CompositingReason::EmbeddedView);
2447
2448     if ((canRender3DTransforms() && renderer.style().backfaceVisibility() == BackfaceVisibility::Hidden))
2449         reasons.add(CompositingReason::BackfaceVisibilityHidden);
2450
2451     if (clipsCompositingDescendants(*renderer.layer()))
2452         reasons.add(CompositingReason::ClipsCompositingDescendants);
2453
2454     if (requiresCompositingForAnimation(renderer))
2455         reasons.add(CompositingReason::Animation);
2456
2457     if (requiresCompositingForFilters(renderer))
2458         reasons.add(CompositingReason::Filters);
2459
2460     if (requiresCompositingForWillChange(renderer))
2461         reasons.add(CompositingReason::WillChange);
2462
2463     if (requiresCompositingForPosition(renderer, *renderer.layer(), queryData))
2464         reasons.add(renderer.isFixedPositioned() ? CompositingReason::PositionFixed : CompositingReason::PositionSticky);
2465
2466     if (requiresCompositingForOverflowScrolling(*renderer.layer(), queryData))
2467         reasons.add(CompositingReason::OverflowScrolling);
2468
2469     switch (renderer.layer()->indirectCompositingReason()) {
2470     case IndirectCompositingReason::None:
2471         break;
2472     case IndirectCompositingReason::Stacking:
2473         reasons.add(CompositingReason::Stacking);
2474         break;
2475     case IndirectCompositingReason::OverflowScrollPositioning:
2476         reasons.add(CompositingReason::OverflowScrollPositioning);
2477         break;
2478     case IndirectCompositingReason::Overlap:
2479         reasons.add(CompositingReason::Overlap);
2480         break;
2481     case IndirectCompositingReason::BackgroundLayer:
2482         reasons.add(CompositingReason::NegativeZIndexChildren);
2483         break;
2484     case IndirectCompositingReason::GraphicalEffect:
2485         if (renderer.hasTransform())
2486             reasons.add(CompositingReason::TransformWithCompositedDescendants);
2487
2488         if (renderer.isTransparent())
2489             reasons.add(CompositingReason::OpacityWithCompositedDescendants);
2490
2491         if (renderer.hasMask())
2492             reasons.add(CompositingReason::MaskWithCompositedDescendants);
2493
2494         if (renderer.hasReflection())
2495             reasons.add(CompositingReason::ReflectionWithCompositedDescendants);
2496
2497         if (renderer.hasFilter() || renderer.hasBackdropFilter())
2498             reasons.add(CompositingReason::FilterWithCompositedDescendants);
2499
2500 #if ENABLE(CSS_COMPOSITING)
2501         if (layer.isolatesCompositedBlending())
2502             reasons.add(CompositingReason::IsolatesCompositedBlendingDescendants);
2503
2504         if (layer.hasBlendMode())
2505             reasons.add(CompositingReason::BlendingWithCompositedDescendants);
2506 #endif
2507         break;
2508     case IndirectCompositingReason::Perspective:
2509         reasons.add(CompositingReason::Perspective);
2510         break;
2511     case IndirectCompositingReason::Preserve3D:
2512         reasons.add(CompositingReason::Preserve3D);
2513         break;
2514     }
2515
2516     if (usesCompositing() && renderer.layer()->isRenderViewLayer())
2517         reasons.add(CompositingReason::Root);
2518
2519     return reasons;
2520 }
2521
2522 #if !LOG_DISABLED
2523 const char* RenderLayerCompositor::logReasonsForCompositing(const RenderLayer& layer)
2524 {
2525     OptionSet<CompositingReason> reasons = reasonsForCompositing(layer);
2526
2527     if (reasons & CompositingReason::Transform3D)
2528         return "3D transform";
2529
2530     if (reasons & CompositingReason::Video)
2531         return "video";
2532
2533     if (reasons & CompositingReason::Canvas)
2534         return "canvas";
2535
2536     if (reasons & CompositingReason::Plugin)
2537         return "plugin";
2538
2539     if (reasons & CompositingReason::IFrame)
2540         return "iframe";
2541
2542     if (reasons & CompositingReason::BackfaceVisibilityHidden)
2543         return "backface-visibility: hidden";
2544
2545     if (reasons & CompositingReason::ClipsCompositingDescendants)
2546         return "clips compositing descendants";
2547
2548     if (reasons & CompositingReason::Animation)
2549         return "animation";
2550
2551     if (reasons & CompositingReason::Filters)
2552         return "filters";
2553
2554     if (reasons & CompositingReason::PositionFixed)
2555         return "position: fixed";
2556
2557     if (reasons & CompositingReason::PositionSticky)
2558         return "position: sticky";
2559
2560     if (reasons & CompositingReason::OverflowScrolling)
2561         return "async overflow scrolling";
2562
2563     if (reasons & CompositingReason::Stacking)
2564         return "stacking";
2565
2566     if (reasons & CompositingReason::Overlap)
2567         return "overlap";
2568
2569     if (reasons & CompositingReason::NegativeZIndexChildren)
2570         return "negative z-index children";
2571
2572     if (reasons & CompositingReason::TransformWithCompositedDescendants)
2573         return "transform with composited descendants";
2574
2575     if (reasons & CompositingReason::OpacityWithCompositedDescendants)
2576         return "opacity with composited descendants";
2577
2578     if (reasons & CompositingReason::MaskWithCompositedDescendants)
2579         return "mask with composited descendants";
2580
2581     if (reasons & CompositingReason::ReflectionWithCompositedDescendants)
2582         return "reflection with composited descendants";
2583
2584     if (reasons & CompositingReason::FilterWithCompositedDescendants)
2585         return "filter with composited descendants";
2586
2587 #if ENABLE(CSS_COMPOSITING)
2588     if (reasons & CompositingReason::BlendingWithCompositedDescendants)
2589         return "blending with composited descendants";
2590
2591     if (reasons & CompositingReason::IsolatesCompositedBlendingDescendants)
2592         return "isolates composited blending descendants";
2593 #endif
2594
2595     if (reasons & CompositingReason::Perspective)
2596         return "perspective";
2597
2598     if (reasons & CompositingReason::Preserve3D)
2599         return "preserve-3d";
2600
2601     if (reasons & CompositingReason::Root)
2602         return "root";
2603
2604     return "";
2605 }
2606 #endif
2607
2608 // Return true if the given layer has some ancestor in the RenderLayer hierarchy that clips,
2609 // up to the enclosing compositing ancestor. This is required because compositing layers are parented
2610 // according to the z-order hierarchy, yet clipping goes down the renderer hierarchy.
2611 // Thus, a RenderLayer can be clipped by a RenderLayer that is an ancestor in the renderer hierarchy,
2612 // but a sibling in the z-order hierarchy.
2613 // FIXME: can we do this without a tree walk?
2614 bool RenderLayerCompositor::clippedByAncestor(RenderLayer& layer, const RenderLayer* compositingAncestor) const
2615 {
2616     ASSERT(layer.isComposited());
2617     if (!compositingAncestor)
2618         return false;
2619
2620     // If the compositingAncestor clips, that will be taken care of by clipsCompositingDescendants(),
2621     // so we only care about clipping between its first child that is our ancestor (the computeClipRoot),
2622     // and layer. The exception is when the compositingAncestor isolates composited blending children,
2623     // in this case it is not allowed to clipsCompositingDescendants() and each of its children
2624     // will be clippedByAncestor()s, including the compositingAncestor.
2625     auto* computeClipRoot = compositingAncestor;
2626     if (!compositingAncestor->isolatesCompositedBlending()) {
2627         computeClipRoot = nullptr;
2628         auto* parent = &layer;
2629         while (parent) {
2630             auto* next = parent->parent();
2631             if (next == compositingAncestor) {
2632                 computeClipRoot = parent;
2633                 break;
2634             }
2635             parent = next;
2636         }
2637
2638         if (!computeClipRoot || computeClipRoot == &layer)
2639             return false;
2640     }
2641
2642     return !layer.backgroundClipRect(RenderLayer::ClipRectsContext(computeClipRoot, TemporaryClipRects)).isInfinite(); // FIXME: Incorrect for CSS regions.
2643 }
2644
2645 bool RenderLayerCompositor::updateAncestorClippingStack(const RenderLayer& layer, const RenderLayer* compositingAncestor) const
2646 {
2647     ASSERT(layer.isComposited());
2648
2649     auto clippingStack = computeAncestorClippingStack(layer, compositingAncestor);
2650     return layer.backing()->updateAncestorClippingStack(WTFMove(clippingStack));
2651 }
2652
2653 Vector<CompositedClipData> RenderLayerCompositor::computeAncestorClippingStack(const RenderLayer& layer, const RenderLayer* compositingAncestor) const
2654 {
2655     // On first pass in WK1, the root may not have become composited yet.
2656     if (!compositingAncestor)
2657         return { };
2658
2659     // We'll start by building a child-to-ancestors stack.
2660     Vector<CompositedClipData> newStack;
2661
2662     // Walk up the containing block chain to composited ancestor, prepending an entry to the clip stack for:
2663     // * each composited scrolling layer
2664     // * each set of RenderLayers which contribute a clip.
2665     bool haveNonScrollableClippingIntermediateLayer = false;
2666     const RenderLayer* currentClippedLayer = &layer;
2667     
2668     auto pushNonScrollableClip = [&](const RenderLayer& clippedLayer, const RenderLayer& clippingRoot, ShouldRespectOverflowClip respectClip = IgnoreOverflowClip) {
2669         // Pass IgnoreOverflowClip to ignore overflow contributed by clippingRoot (which may be a scroller).
2670         auto clipRect = clippedLayer.backgroundClipRect(RenderLayer::ClipRectsContext(&clippingRoot, TemporaryClipRects, IgnoreOverlayScrollbarSize, respectClip)).rect();
2671         auto offset = layer.convertToLayerCoords(&clippingRoot, { }, RenderLayer::AdjustForColumns);
2672         clipRect.moveBy(-offset);
2673
2674         CompositedClipData clipData { const_cast<RenderLayer*>(&clippedLayer), clipRect, false };
2675         newStack.insert(0, WTFMove(clipData));
2676     };
2677
2678     traverseAncestorLayers(layer, [&](const RenderLayer& ancestorLayer, bool isContainingBlockChain, bool /*isPaintOrderAncestor*/) {
2679         if (&ancestorLayer == compositingAncestor) {
2680         
2681             if (haveNonScrollableClippingIntermediateLayer)
2682                 pushNonScrollableClip(*currentClippedLayer, ancestorLayer, ancestorLayer.isolatesCompositedBlending() ? RespectOverflowClip : IgnoreOverflowClip);
2683             else if (ancestorLayer.isolatesCompositedBlending() && newStack.isEmpty())
2684                 pushNonScrollableClip(*currentClippedLayer, ancestorLayer, RespectOverflowClip);
2685
2686             return AncestorTraversal::Stop;
2687         }
2688
2689         if (isContainingBlockChain && ancestorLayer.renderer().hasClipOrOverflowClip()) {
2690             if (ancestorLayer.hasCompositedScrollableOverflow()) {
2691                 if (haveNonScrollableClippingIntermediateLayer) {
2692                     pushNonScrollableClip(*currentClippedLayer, ancestorLayer);
2693                     haveNonScrollableClippingIntermediateLayer = false;
2694                 }
2695
2696                 auto clipRect = parentRelativeScrollableRect(ancestorLayer, &ancestorLayer);
2697                 auto offset = layer.convertToLayerCoords(&ancestorLayer, { }, RenderLayer::AdjustForColumns);
2698                 clipRect.moveBy(-offset);
2699
2700                 CompositedClipData clipData { const_cast<RenderLayer*>(&ancestorLayer), clipRect, true };
2701                 newStack.insert(0, WTFMove(clipData));
2702                 currentClippedLayer = &ancestorLayer;
2703             } else
2704                 haveNonScrollableClippingIntermediateLayer = true;
2705         }
2706
2707         return AncestorTraversal::Continue;
2708     });
2709     
2710     return newStack;
2711 }
2712
2713 // Note that this returns the ScrollingNodeID of the scroller this layer is embedded in, not the layer's own ScrollingNodeID if it has one.
2714 ScrollingNodeID RenderLayerCompositor::asyncScrollableContainerNodeID(const RenderObject& renderer)
2715 {
2716     auto* enclosingLayer = renderer.enclosingLayer();
2717     if (!enclosingLayer)
2718         return 0;
2719     
2720     auto layerScrollingNodeID = [](const RenderLayer& layer) -> ScrollingNodeID {
2721         if (layer.isComposited())
2722             return layer.backing()->scrollingNodeIDForRole(ScrollCoordinationRole::Scrolling);
2723         return 0;
2724     };
2725
2726     // If the renderer is inside the layer, we care about the layer's scrollability. Otherwise, we let traverseAncestorLayers look at ancestors.
2727     if (!renderer.hasLayer()) {
2728         if (auto scrollingNodeID = layerScrollingNodeID(*enclosingLayer))
2729             return scrollingNodeID;
2730     }
2731
2732     ScrollingNodeID containerScrollingNodeID = 0;
2733     traverseAncestorLayers(*enclosingLayer, [&](const RenderLayer& ancestorLayer, bool isContainingBlockChain, bool /*isPaintOrderAncestor*/) {
2734         if (isContainingBlockChain && ancestorLayer.hasCompositedScrollableOverflow()) {
2735             containerScrollingNodeID = layerScrollingNodeID(ancestorLayer);
2736             return AncestorTraversal::Stop;
2737         }
2738         return AncestorTraversal::Continue;
2739     });
2740
2741     return containerScrollingNodeID;
2742 }
2743
2744 // Return true if the given layer is a stacking context and has compositing child
2745 // layers that it needs to clip. In this case we insert a clipping GraphicsLayer
2746 // into the hierarchy between this layer and its children in the z-order hierarchy.
2747 bool RenderLayerCompositor::clipsCompositingDescendants(const RenderLayer& layer)
2748 {
2749     return layer.hasCompositingDescendant() && layer.renderer().hasClipOrOverflowClip() && !layer.isolatesCompositedBlending();
2750 }
2751
2752 bool RenderLayerCompositor::requiresCompositingForAnimation(RenderLayerModelObject& renderer) const
2753 {
2754     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
2755         return false;
2756
2757     if (auto* element = renderer.element()) {
2758         if (auto* timeline = element->document().existingTimeline()) {
2759             if (timeline->runningAnimationsForElementAreAllAccelerated(*element))
2760                 return true;
2761         }
2762     }
2763
2764     if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled())
2765         return false;
2766
2767     auto& animController = renderer.animation();
2768     return (animController.isRunningAnimationOnRenderer(renderer, CSSPropertyOpacity)
2769         && (usesCompositing() || (m_compositingTriggers & ChromeClient::AnimatedOpacityTrigger)))
2770         || animController.isRunningAnimationOnRenderer(renderer, CSSPropertyFilter)
2771 #if ENABLE(FILTERS_LEVEL_2)
2772         || animController.isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitBackdropFilter)
2773 #endif
2774         || animController.isRunningAnimationOnRenderer(renderer, CSSPropertyTransform);
2775 }
2776
2777 bool RenderLayerCompositor::requiresCompositingForTransform(RenderLayerModelObject& renderer) const
2778 {
2779     if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
2780         return false;
2781
2782     // Note that we ask the renderer if it has a transform, because the style may have transforms,
2783     // but the renderer may be an inline that doesn't suppport them.
2784     if (!renderer.hasTransform())
2785         return false;
2786     
2787     switch (m_compositingPolicy) {
2788     case CompositingPolicy::Normal:
2789         return renderer.style().transform().has3DOperation();
2790     case CompositingPolicy::Conservative:
2791         // Continue to allow pages to avoid the very slow software filter path.
2792         if (renderer.style().transform().has3DOperation() && renderer.hasFilter())
2793             return true;
2794         return renderer.style().transform().isRepresentableIn2D() ? false : true;
2795     }
2796     return false;
2797 }
2798
2799 bool RenderLayerCompositor::requiresCompositingForBackfaceVisibility(RenderLayerModelObject& renderer) const
2800 {
2801     if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
2802         return false;
2803
2804     if (renderer.style().backfaceVisibility() != BackfaceVisibility::Hidden)
2805         return false;
2806
2807     if (renderer.layer()->has3DTransformedAncestor())
2808         return true;
2809     
2810     // FIXME: workaround for webkit.org/b/132801
2811     auto* stackingContext = renderer.layer()->stackingContext();
2812     if (stackingContext && stackingContext->renderer().style().transformStyle3D() == TransformStyle3D::Preserve3D)
2813         return true;
2814
2815     return false;
2816 }
2817
2818 bool RenderLayerCompositor::requiresCompositingForVideo(RenderLayerModelObject& renderer) const
2819 {
2820     if (!(m_compositingTriggers & ChromeClient::VideoTrigger))
2821         return false;
2822
2823 #if ENABLE(VIDEO)
2824     if (!is<RenderVideo>(renderer))
2825         return false;
2826
2827     auto& video = downcast<RenderVideo>(renderer);
2828     if ((video.requiresImmediateCompositing() || video.shouldDisplayVideo()) && canAccelerateVideoRendering(video))
2829         return true;
2830 #else
2831     UNUSED_PARAM(renderer);
2832 #endif
2833     return false;
2834 }
2835
2836 bool RenderLayerCompositor::requiresCompositingForCanvas(RenderLayerModelObject& renderer) const
2837 {
2838     if (!(m_compositingTriggers & ChromeClient::CanvasTrigger))
2839         return false;
2840
2841     if (!renderer.isCanvas())
2842         return false;
2843
2844     bool isCanvasLargeEnoughToForceCompositing = true;
2845 #if !USE(COMPOSITING_FOR_SMALL_CANVASES)
2846     auto* canvas = downcast<HTMLCanvasElement>(renderer.element());
2847     auto canvasArea = canvas->size().area<RecordOverflow>();
2848     isCanvasLargeEnoughToForceCompositing = !canvasArea.hasOverflowed() && canvasArea.unsafeGet() >= canvasAreaThresholdRequiringCompositing;
2849 #endif
2850
2851     CanvasCompositingStrategy compositingStrategy = canvasCompositingStrategy(renderer);
2852     if (compositingStrategy == CanvasAsLayerContents)
2853         return true;
2854
2855     if (m_compositingPolicy == CompositingPolicy::Normal)
2856         return compositingStrategy == CanvasPaintedToLayer && isCanvasLargeEnoughToForceCompositing;
2857
2858     return false;
2859 }
2860
2861 bool RenderLayerCompositor::requiresCompositingForFilters(RenderLayerModelObject& renderer) const
2862 {
2863 #if ENABLE(FILTERS_LEVEL_2)
2864     if (renderer.hasBackdropFilter())
2865         return true;
2866 #endif
2867
2868     if (!(m_compositingTriggers & ChromeClient::FilterTrigger))
2869         return false;
2870
2871     return renderer.hasFilter();
2872 }
2873
2874 bool RenderLayerCompositor::requiresCompositingForWillChange(RenderLayerModelObject& renderer) const
2875 {
2876     if (!renderer.style().willChange() || !renderer.style().willChange()->canTriggerCompositing())
2877         return false;
2878
2879 #if ENABLE(FULLSCREEN_API)
2880     // FIXME: does this require layout?
2881     if (renderer.layer() && isDescendantOfFullScreenLayer(*renderer.layer()) == FullScreenDescendant::No)
2882         return false;
2883 #endif
2884
2885     if (m_compositingPolicy == CompositingPolicy::Conservative)
2886         return false;
2887
2888     if (is<RenderBox>(renderer))
2889         return true;
2890
2891     return renderer.style().willChange()->canTriggerCompositingOnInline();
2892 }
2893
2894 bool RenderLayerCompositor::requiresCompositingForPlugin(RenderLayerModelObject& renderer, RequiresCompositingData& queryData) const
2895 {
2896     if (!(m_compositingTriggers & ChromeClient::PluginTrigger))
2897         return false;
2898
2899     bool isCompositedPlugin = is<RenderEmbeddedObject>(renderer) && downcast<RenderEmbeddedObject>(renderer).allowsAcceleratedCompositing();
2900     if (!isCompositedPlugin)
2901         return false;
2902
2903     auto& pluginRenderer = downcast<RenderWidget>(renderer);
2904     if (pluginRenderer.style().visibility() != Visibility::Visible)
2905         return false;
2906
2907     // If we can't reliably know the size of the plugin yet, don't change compositing state.
2908     if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2909         queryData.reevaluateAfterLayout = true;
2910         return pluginRenderer.isComposited();
2911     }
2912
2913     // Don't go into compositing mode if height or width are zero, or size is 1x1.
2914     IntRect contentBox = snappedIntRect(pluginRenderer.contentBoxRect());
2915     return (contentBox.height() * contentBox.width() > 1);
2916 }
2917     
2918 bool RenderLayerCompositor::requiresCompositingForEditableImage(RenderLayerModelObject& renderer) const
2919 {
2920     if (!renderer.isRenderImage())
2921         return false;
2922
2923     auto& image = downcast<RenderImage>(renderer);
2924     if (!image.isEditableImage())
2925         return false;
2926
2927     return true;
2928 }
2929
2930 bool RenderLayerCompositor::requiresCompositingForFrame(RenderLayerModelObject& renderer, RequiresCompositingData& queryData) const
2931 {
2932     if (!is<RenderWidget>(renderer))
2933         return false;
2934
2935     auto& frameRenderer = downcast<RenderWidget>(renderer);
2936     if (frameRenderer.style().visibility() != Visibility::Visible)
2937         return false;
2938
2939     if (!frameRenderer.requiresAcceleratedCompositing())
2940         return false;
2941
2942     if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2943         queryData.reevaluateAfterLayout = true;
2944         return frameRenderer.isComposited();
2945     }
2946
2947     // Don't go into compositing mode if height or width are zero.
2948     return !snappedIntRect(frameRenderer.contentBoxRect()).isEmpty();
2949 }
2950
2951 bool RenderLayerCompositor::requiresCompositingForScrollableFrame(RequiresCompositingData& queryData) const
2952 {
2953     if (isMainFrameCompositor())
2954         return false;
2955
2956 #if PLATFORM(MAC) || PLATFORM(IOS_FAMILY)
2957     if (!m_renderView.settings().asyncFrameScrollingEnabled())
2958         return false;
2959 #endif
2960
2961     if (!(m_compositingTriggers & ChromeClient::ScrollableNonMainFrameTrigger))
2962         return false;
2963
2964     if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2965         queryData.reevaluateAfterLayout = true;
2966         return m_renderView.isComposited();
2967     }
2968
2969     return m_renderView.frameView().isScrollable();
2970 }
2971
2972 bool RenderLayerCompositor::requiresCompositingForPosition(RenderLayerModelObject& renderer, const RenderLayer& layer, RequiresCompositingData& queryData) const
2973 {
2974     // position:fixed elements that create their own stacking context (e.g. have an explicit z-index,
2975     // opacity, transform) can get their own composited layer. A stacking context is required otherwise
2976     // z-index and clipping will be broken.
2977     if (!renderer.isPositioned())
2978         return false;
2979     
2980 #if ENABLE(FULLSCREEN_API)
2981     if (isDescendantOfFullScreenLayer(layer) == FullScreenDescendant::No)
2982         return false;
2983 #endif
2984
2985     auto position = renderer.style().position();
2986     bool isFixed = renderer.isFixedPositioned();
2987     if (isFixed && !layer.isStackingContext())
2988         return false;
2989     
2990     bool isSticky = renderer.isInFlowPositioned() && position == PositionType::Sticky;
2991     if (!isFixed && !isSticky)
2992         return false;
2993
2994     // FIXME: acceleratedCompositingForFixedPositionEnabled should probably be renamed acceleratedCompositingForViewportConstrainedPositionEnabled().
2995     if (!m_renderView.settings().acceleratedCompositingForFixedPositionEnabled())
2996         return false;
2997
2998     if (isSticky)
2999         return isAsyncScrollableStickyLayer(layer);
3000
3001     if (queryData.layoutUpToDate == LayoutUpToDate::No) {
3002         queryData.reevaluateAfterLayout = true;
3003         return layer.isComposited();
3004     }
3005
3006     auto container = renderer.container();
3007     ASSERT(container);
3008
3009     // Don't promote fixed position elements that are descendants of a non-view container, e.g. transformed elements.
3010     // They will stay fixed wrt the container rather than the enclosing frame.
3011     if (container != &m_renderView) {
3012         queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForNonViewContainer;
3013         return false;
3014     }
3015
3016     bool paintsContent = layer.isVisuallyNonEmpty() || layer.hasVisibleDescendant();
3017     if (!paintsContent) {
3018         queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForNoVisibleContent;
3019         return false;
3020     }
3021
3022     bool intersectsViewport = fixedLayerIntersectsViewport(layer);
3023     if (!intersectsViewport) {
3024         queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForBoundsOutOfView;
3025         LOG_WITH_STREAM(Compositing, stream << "Layer " << &layer << " is outside the viewport");
3026         return false;
3027     }
3028
3029     return true;
3030 }
3031
3032 bool RenderLayerCompositor::requiresCompositingForOverflowScrolling(const RenderLayer& layer, RequiresCompositingData& queryData) const
3033 {
3034     if (!layer.canUseCompositedScrolling())
3035         return false;
3036
3037     if (queryData.layoutUpToDate == LayoutUpToDate::No) {
3038         queryData.reevaluateAfterLayout = true;
3039         return layer.isComposited();
3040     }
3041
3042     return layer.hasCompositedScrollableOverflow();
3043 }
3044
3045 // FIXME: why doesn't this handle the clipping cases?
3046 bool RenderLayerCompositor::requiresCompositingForIndirectReason(const RenderLayer& layer, bool hasCompositedDescendants, bool has3DTransformedDescendants, bool paintsIntoProvidedBacking, IndirectCompositingReason& reason) const
3047 {
3048     // When a layer has composited descendants, some effects, like 2d transforms, filters, masks etc must be implemented
3049     // via compositing so that they also apply to those composited descendants.
3050     auto& renderer = layer.renderer();
3051     if (hasCompositedDescendants && (layer.isolatesCompositedBlending() || layer.transform() || renderer.createsGroup() || renderer.hasReflection())) {
3052         reason = IndirectCompositingReason::GraphicalEffect;
3053         return true;
3054     }
3055
3056     // A layer with preserve-3d or perspective only needs to be composited if there are descendant layers that
3057     // will be affected by the preserve-3d or perspective.
3058     if (has3DTransformedDescendants) {
3059         if (renderer.style().transformStyle3D() == TransformStyle3D::Preserve3D) {
3060             reason = IndirectCompositingReason::Preserve3D;
3061             return true;
3062         }
3063     
3064         if (renderer.style().hasPerspective()) {
3065             reason = IndirectCompositingReason::Perspective;
3066             return true;
3067         }
3068     }
3069
3070     // If this layer scrolls independently from the layer that it would paint into, it needs to get composited.
3071     if (!paintsIntoProvidedBacking && layer.hasCompositedScrollingAncestor()) {
3072         auto* paintDestination = layer.paintOrderParent();
3073         if (paintDestination && layerScrollBehahaviorRelativeToCompositedAncestor(layer, *paintDestination) != ScrollPositioningBehavior::None) {
3074             reason = IndirectCompositingReason::OverflowScrollPositioning;
3075             return true;
3076         }
3077     }
3078
3079     reason = IndirectCompositingReason::None;
3080     return false;
3081 }
3082
3083 bool RenderLayerCompositor::styleChangeMayAffectIndirectCompositingReasons(const RenderStyle& oldStyle, const RenderStyle& newStyle)
3084 {
3085     if (RenderElement::createsGroupForStyle(newStyle) != RenderElement::createsGroupForStyle(oldStyle))
3086         return true;
3087     if (newStyle.isolation() != oldStyle.isolation())
3088         return true;
3089     if (newStyle.hasTransform() != oldStyle.hasTransform())
3090         return true;
3091     if (newStyle.boxReflect() != oldStyle.boxReflect())
3092         return true;
3093     if (newStyle.transformStyle3D() != oldStyle.transformStyle3D())
3094         return true;
3095     if (newStyle.hasPerspective() != oldStyle.hasPerspective())
3096         return true;
3097
3098     return false;
3099 }
3100
3101 bool RenderLayerCompositor::isAsyncScrollableStickyLayer(const RenderLayer& layer, const RenderLayer** enclosingAcceleratedOverflowLayer) const
3102 {
3103     ASSERT(layer.renderer().isStickilyPositioned());
3104
3105     auto* enclosingOverflowLayer = layer.enclosingOverflowClipLayer(ExcludeSelf);
3106
3107     if (enclosingOverflowLayer && enclosingOverflowLayer->hasCompositedScrollableOverflow()) {
3108         if (enclosingAcceleratedOverflowLayer)
3109             *enclosingAcceleratedOverflowLayer = enclosingOverflowLayer;
3110         return true;
3111     }
3112
3113     // If the layer is inside normal overflow, it's not async-scrollable.
3114     if (enclosingOverflowLayer)
3115         return false;
3116
3117     // No overflow ancestor, so see if the frame supports async scrolling.
3118     if (hasCoordinatedScrolling())
3119         return true;
3120
3121 #if PLATFORM(IOS_FAMILY)
3122     // iOS WK1 has fixed/sticky support in the main frame via WebFixedPositionContent.
3123     return isMainFrameCompositor();
3124 #else
3125     return false;
3126 #endif
3127 }
3128
3129 bool RenderLayerCompositor::isViewportConstrainedFixedOrStickyLayer(const RenderLayer& layer) const
3130 {
3131     if (layer.renderer().isStickilyPositioned())
3132         return isAsyncScrollableStickyLayer(layer);
3133
3134     if (!layer.renderer().isFixedPositioned())
3135         return false;
3136
3137     // FIXME: Handle fixed inside of a transform, which should not behave as fixed.
3138     for (auto* ancestor = layer.parent(); ancestor; ancestor = ancestor->parent()) {
3139         if (ancestor->hasCompositedScrollableOverflow())
3140             return true;
3141         if (ancestor->isStackingContext() && ancestor->isComposited() && ancestor->renderer().isFixedPositioned())
3142             return false;
3143     }
3144
3145     return true;
3146 }
3147
3148 bool RenderLayerCompositor::fixedLayerIntersectsViewport(const RenderLayer& layer) const
3149 {
3150     ASSERT(layer.renderer().isFixedPositioned());
3151
3152     // Fixed position elements that are invisible in the current view don't get their own layer.
3153     // FIXME: We shouldn't have to check useFixedLayout() here; one of the viewport rects needs to give the correct answer.
3154     LayoutRect viewBounds;
3155     if (m_renderView.frameView().useFixedLayout())
3156         viewBounds = m_renderView.unscaledDocumentRect();
3157     else
3158         viewBounds = m_renderView.frameView().rectForFixedPositionLayout();
3159
3160     LayoutRect layerBounds = layer.calculateLayerBounds(&layer, LayoutSize(), { RenderLayer::UseLocalClipRectIfPossible, RenderLayer::IncludeFilterOutsets, RenderLayer::UseFragmentBoxesExcludingCompositing,
3161         RenderLayer::ExcludeHiddenDescendants, RenderLayer::DontConstrainForMask, RenderLayer::IncludeCompositedDescendants });
3162     // Map to m_renderView to ignore page scale.
3163     FloatRect absoluteBounds = layer.renderer().localToContainerQuad(FloatRect(layerBounds), &m_renderView).boundingBox();
3164     return viewBounds.intersects(enclosingIntRect(absoluteBounds));
3165 }
3166
3167 bool RenderLayerCompositor::useCoordinatedScrollingForLayer(const RenderLayer& layer) const
3168 {
3169     if (layer.isRenderViewLayer() && hasCoordinatedScrolling())
3170         return true;
3171
3172     if (auto* scrollingCoordinator = this->scrollingCoordinator())
3173         return scrollingCoordinator->coordinatesScrollingForOverflowLayer(layer);
3174
3175     return false;
3176 }
3177
3178 static bool isScrolledByOverflowScrollLayer(const RenderLayer& layer, const RenderLayer& overflowScrollLayer)
3179 {
3180     bool scrolledByOverflowScroll = false;
3181     traverseAncestorLayers(layer, [&](const RenderLayer& ancestorLayer, bool inContainingBlockChain, bool) {
3182         if (&ancestorLayer == &overflowScrollLayer) {
3183             scrolledByOverflowScroll = inContainingBlockChain;
3184             return AncestorTraversal::Stop;
3185         }
3186         return AncestorTraversal::Continue;
3187     });
3188     return scrolledByOverflowScroll;
3189 }
3190
3191 static RenderLayer* enclosingCompositedScrollingLayer(const RenderLayer& layer, const RenderLayer& intermediateLayer, bool& sawIntermediateLayer)
3192 {
3193     const auto* ancestorLayer = layer.parent();
3194     while (ancestorLayer) {
3195         if (ancestorLayer == &intermediateLayer)
3196             sawIntermediateLayer = true;
3197
3198         if (ancestorLayer->hasCompositedScrollableOverflow())
3199             return const_cast<RenderLayer*>(ancestorLayer);
3200
3201         ancestorLayer = ancestorLayer->parent();
3202     }
3203
3204     return nullptr;
3205 }
3206
3207 ScrollPositioningBehavior RenderLayerCompositor::layerScrollBehahaviorRelativeToCompositedAncestor(const RenderLayer& layer, const RenderLayer& compositedAncestor)
3208 {
3209     if (!layer.hasCompositedScrollingAncestor())
3210         return ScrollPositioningBehavior::None;
3211
3212     bool compositedAncestorIsInsideScroller = false;
3213     auto* scrollingAncestor = enclosingCompositedScrollingLayer(layer, compositedAncestor, compositedAncestorIsInsideScroller);
3214     if (!scrollingAncestor) {
3215         ASSERT_NOT_REACHED(); // layer.hasCompositedScrollingAncestor() should guarantee we have one.
3216         return ScrollPositioningBehavior::None;
3217     }
3218     
3219     bool ancestorMovedByScroller = &compositedAncestor == scrollingAncestor || (compositedAncestorIsInsideScroller && isScrolledByOverflowScrollLayer(compositedAncestor, *scrollingAncestor));
3220     bool layerMovedByScroller = isScrolledByOverflowScrollLayer(layer, *scrollingAncestor);
3221
3222     if (ancestorMovedByScroller == layerMovedByScroller)
3223         return ScrollPositioningBehavior::None;
3224
3225     return layerMovedByScroller ? ScrollPositioningBehavior::Moves : ScrollPositioningBehavior::Stationary;
3226 }
3227
3228 static void collectStationaryLayerRelatedOverflowNodes(const RenderLayer& layer, const RenderLayer&, Vector<ScrollingNodeID>& scrollingNodes)
3229 {
3230     ASSERT(layer.isComposited());
3231     
3232     auto appendOverflowLayerNodeID = [&scrollingNodes] (const RenderLayer& overflowLayer) {
3233         ASSERT(overflowLayer.isComposited());
3234         auto scrollingNodeID = overflowLayer.backing()->scrollingNodeIDForRole(ScrollCoordinationRole::Scrolling);
3235         if (scrollingNodeID)
3236             scrollingNodes.append(scrollingNodeID);
3237         else
3238             LOG(Scrolling, "Layer %p doesn't have scrolling node ID yet", &overflowLayer);
3239     };
3240
3241     // Collect all the composited scrollers which affect the position of this layer relative to its compositing ancestor (which might be inside the scroller or the scroller itself).
3242     bool seenPaintOrderAncestor = false;
3243     traverseAncestorLayers(layer, [&](const RenderLayer& ancestorLayer, bool isContainingBlockChain, bool isPaintOrderAncestor) {
3244         seenPaintOrderAncestor |= isPaintOrderAncestor;
3245         if (isContainingBlockChain && isPaintOrderAncestor)
3246             return AncestorTraversal::Stop;
3247
3248         if (seenPaintOrderAncestor && !isContainingBlockChain && ancestorLayer.hasCompositedScrollableOverflow())
3249             appendOverflowLayerNodeID(ancestorLayer);
3250
3251         return AncestorTraversal::Continue;
3252     });
3253 }
3254
3255 ScrollPositioningBehavior RenderLayerCompositor::computeCoordinatedPositioningForLayer(const RenderLayer& layer) const
3256 {
3257     if (layer.isRenderViewLayer())
3258         return ScrollPositioningBehavior::None;
3259
3260     if (layer.renderer().isFixedPositioned())
3261         return ScrollPositioningBehavior::None;
3262     
3263     if (!layer.hasCompositedScrollingAncestor())
3264         return ScrollPositioningBehavior::None;
3265
3266     auto* scrollingCoordinator = this->scrollingCoordinator();
3267     if (!scrollingCoordinator)
3268         return ScrollPositioningBehavior::None;
3269
3270     auto* compositedAncestor = layer.ancestorCompositingLayer();
3271     if (!compositedAncestor) {
3272         ASSERT_NOT_REACHED();
3273         return ScrollPositioningBehavior::None;
3274     }
3275
3276     return layerScrollBehahaviorRelativeToCompositedAncestor(layer, *compositedAncestor);
3277 }
3278
3279 static Vector<ScrollingNodeID> collectRelatedCoordinatedScrollingNodes(const RenderLayer& layer, ScrollPositioningBehavior positioningBehavior)
3280 {
3281     Vector<ScrollingNodeID> overflowNodeIDs;
3282
3283     switch (positioningBehavior) {
3284     case ScrollPositioningBehavior::Stationary: {
3285         auto* compositedAncestor = layer.ancestorCompositingLayer();
3286         if (!compositedAncestor)
3287             return overflowNodeIDs;
3288         collectStationaryLayerRelatedOverflowNodes(layer, *compositedAncestor, overflowNodeIDs);
3289         break;
3290     }
3291     case ScrollPositioningBehavior::Moves:
3292     case ScrollPositioningBehavior::None:
3293         ASSERT_NOT_REACHED();
3294         break;
3295     }
3296
3297     return overflowNodeIDs;
3298 }
3299
3300 bool RenderLayerCompositor::isLayerForIFrameWithScrollCoordinatedContents(const RenderLayer& layer) const
3301 {
3302     if (!is<RenderWidget>(layer.renderer()))
3303         return false;
3304
3305     auto* contentDocument = downcast<RenderWidget>(layer.renderer()).frameOwnerElement().contentDocument();
3306     if (!contentDocument)
3307         return false;
3308
3309     auto* view = contentDocument->renderView();
3310     if (!view)
3311         return false;
3312
3313     if (auto* scrollingCoordinator = this->scrollingCoordinator())
3314         return scrollingCoordinator->coordinatesScrollingForFrameView(view->frameView());
3315
3316     return false;
3317 }
3318
3319 bool RenderLayerCompositor::isRunningTransformAnimation(RenderLayerModelObject& renderer) const
3320 {
3321     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
3322         return false;
3323
3324     if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled()) {
3325         if (auto* element = renderer.element()) {
3326             if (auto* timeline = element->document().existingTimeline())
3327                 return timeline->isRunningAnimationOnRenderer(renderer, CSSPropertyTransform);
3328         }
3329         return false;
3330     }
3331     return renderer.animation().isRunningAnimationOnRenderer(renderer, CSSPropertyTransform);
3332 }
3333
3334 // If an element has composited negative z-index children, those children render in front of the
3335 // layer background, so we need an extra 'contents' layer for the foreground of the layer object.
3336 bool RenderLayerCompositor::needsContentsCompositingLayer(const RenderLayer& layer) const
3337 {
3338     for (auto* layer : layer.negativeZOrderLayers()) {
3339         if (layer->isComposited() || layer->hasCompositingDescendant())
3340             return true;
3341     }
3342
3343     return false;
3344 }
3345
3346 bool RenderLayerCompositor::requiresScrollLayer(RootLayerAttachment attachment) const
3347 {
3348     auto& frameView = m_renderView.frameView();
3349
3350     // This applies when the application UI handles scrolling, in which case RenderLayerCompositor doesn't need to manage it.
3351     if (frameView.delegatesScrolling() && isMainFrameCompositor())
3352         return false;
3353
3354     // We need to handle our own scrolling if we're:
3355     return !m_renderView.frameView().platformWidget() // viewless (i.e. non-Mac, or Mac in WebKit2)
3356         || attachment == RootLayerAttachedViaEnclosingFrame; // a composited frame on Mac
3357 }
3358
3359 void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
3360 {
3361     if (!scrollbar)
3362         return;
3363
3364     context.save();
3365     const IntRect& scrollbarRect = scrollbar->frameRect();
3366     context.translate(-scrollbarRect.location());
3367     IntRect transformedClip = clip;
3368     transformedClip.moveBy(scrollbarRect.location());
3369     scrollbar->paint(context, transformedClip);
3370     context.restore();
3371 }
3372
3373 void RenderLayerCompositor::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, OptionSet<GraphicsLayerPaintingPhase>, const FloatRect& clip, GraphicsLayerPaintBehavior)
3374 {
3375 #if PLATFORM(MAC)
3376     LocalDefaultSystemAppearance localAppearance(m_renderView.useDarkAppearance());
3377 #endif
3378
3379     IntRect pixelSnappedRectForIntegralPositionedItems = snappedIntRect(LayoutRect(clip));
3380     if (graphicsLayer == layerForHorizontalScrollbar())
3381         paintScrollbar(m_renderView.frameView().horizontalScrollbar(), context, pixelSnappedRectForIntegralPositionedItems);
3382     else if (graphicsLayer == layerForVerticalScrollbar())
3383         paintScrollbar(m_renderView.frameView().verticalScrollbar(), context, pixelSnappedRectForIntegralPositionedItems);
3384     else if (graphicsLayer == layerForScrollCorner()) {
3385         const IntRect& scrollCorner = m_renderView.frameView().scrollCornerRect();
3386         context.save();
3387         context.translate(-scrollCorner.location());
3388         IntRect transformedClip = pixelSnappedRectForIntegralPositionedItems;
3389         transformedClip.moveBy(scrollCorner.location());
3390         m_renderView.frameView().paintScrollCorner(context, transformedClip);
3391         context.restore();
3392     }
3393 }
3394
3395 bool RenderLayerCompositor::supportsFixedRootBackgroundCompositing() const
3396 {
3397     auto* renderViewBacking = m_renderView.layer()->backing();
3398     return renderViewBacking && renderViewBacking->isFrameLayerWithTiledBacking();
3399 }
3400
3401 bool RenderLayerCompositor::needsFixedRootBackgroundLayer(const RenderLayer& layer) const
3402 {
3403     if (!layer.isRenderViewLayer())
3404         return false;
3405
3406     if (m_renderView.settings().fixedBackgroundsPaintRelativeToDocument())
3407         return false;
3408
3409     return supportsFixedRootBackgroundCompositing() && m_renderView.rootBackgroundIsEntirelyFixed();
3410 }
3411
3412 GraphicsLayer* RenderLayerCompositor::fixedRootBackgroundLayer() const
3413 {
3414     // Get the fixed root background from the RenderView layer's backing.
3415     auto* viewLayer = m_renderView.layer();
3416     if (!viewLayer)
3417         return nullptr;
3418
3419     if (viewLayer->isComposited() && viewLayer->backing()->backgroundLayerPaintsFixedRootBackground())
3420         return viewLayer->backing()->backgroundLayer();
3421
3422     return nullptr;
3423 }
3424
3425 void RenderLayerCompositor::resetTrackedRepaintRects()
3426 {
3427     if (auto* rootLayer = rootGraphicsLayer()) {
3428         GraphicsLayer::traverse(*rootLayer, [](GraphicsLayer& layer) {
3429             layer.resetTrackedRepaints();
3430         });
3431     }
3432 }
3433
3434 float RenderLayerCompositor::deviceScaleFactor() const
3435 {
3436     return m_renderView.document().deviceScaleFactor();
3437 }
3438
3439 float RenderLayerCompositor::pageScaleFactor() const
3440 {
3441     return page().pageScaleFactor();
3442 }
3443
3444 float RenderLayerCompositor::zoomedOutPageScaleFactor() const
3445 {
3446     return page().zoomedOutPageScaleFactor();
3447 }
3448
3449 float RenderLayerCompositor::contentsScaleMultiplierForNewTiles(const GraphicsLayer*) const
3450 {
3451 #if PLATFORM(IOS_FAMILY)
3452     LegacyTileCache* tileCache = nullptr;
3453     if (auto* frameView = page().mainFrame().view())
3454         tileCache = frameView->legacyTileCache();
3455
3456     if (!tileCache)
3457         return 1;
3458
3459     return tileCache->tileControllerShouldUseLowScaleTiles() ? 0.125 : 1;
3460 #else
3461     return 1;
3462 #endif
3463 }
3464
3465 bool RenderLayerCompositor::documentUsesTiledBacking() const
3466 {
3467     auto* layer = m_renderView.layer();
3468     if (!layer)
3469         return false;
3470
3471     auto* backing = layer->backing();
3472     if (!backing)
3473         return false;
3474
3475     return backing->isFrameLayerWithTiledBacking();
3476 }
3477
3478 bool RenderLayerCompositor::isMainFrameCompositor() const
3479 {
3480     return m_renderView.frameView().frame().isMainFrame();
3481 }
3482
3483 bool RenderLayerCompositor::shouldCompositeOverflowControls() const
3484 {
3485     auto& frameView = m_renderView.frameView();
3486
3487     if (!frameView.managesScrollbars())
3488         return false;
3489
3490     if (documentUsesTiledBacking())
3491         return true;
3492
3493     if (m_overflowControlsHostLayer && isMainFrameCompositor())
3494         return true;
3495
3496 #if !USE(COORDINATED_GRAPHICS)
3497     if (!frameView.hasOverlayScrollbars())
3498         return false;
3499 #endif
3500
3501     return true;
3502 }
3503
3504 bool RenderLayerCompositor::requiresHorizontalScrollbarLayer() const
3505 {
3506     return shouldCompositeOverflowControls() && m_renderView.frameView().horizontalScrollbar();
3507 }
3508
3509 bool RenderLayerCompositor::requiresVerticalScrollbarLayer() const
3510 {
3511     return shouldCompositeOverflowControls() && m_renderView.frameView().verticalScrollbar();
3512 }
3513
3514 bool RenderLayerCompositor::requiresScrollCornerLayer() const
3515 {
3516     return shouldCompositeOverflowControls() && m_renderView.frameView().isScrollCornerVisible();
3517 }
3518
3519 #if ENABLE(RUBBER_BANDING)
3520 bool RenderLayerCompositor::requiresOverhangAreasLayer() const
3521 {
3522     if (!isMainFrameCompositor())
3523         return false;
3524
3525     // We do want a layer if we're using tiled drawing and can scroll.
3526     if (documentUsesTiledBacking() && m_renderView.frameView().hasOpaqueBackground() && !m_renderView.frameView().prohibitsScrolling())
3527         return true;
3528
3529     return false;
3530 }
3531
3532 bool RenderLayerCompositor::requiresContentShadowLayer() const
3533 {
3534     if (!isMainFrameCompositor())
3535         return false;
3536
3537 #if PLATFORM(COCOA)
3538     if (viewHasTransparentBackground())
3539         return false;
3540
3541     // If the background is going to extend, then it doesn't make sense to have a shadow layer.
3542     if (m_renderView.settings().backgroundShouldExtendBeyondPage())
3543         return false;
3544
3545     // On Mac, we want a content shadow layer if we're using tiled drawing and can scroll.
3546     if (documentUsesTiledBacking() && !m_renderView.frameView().prohibitsScrolling())
3547         return true;
3548 #endif
3549
3550     return false;
3551 }
3552
3553 GraphicsLayer* RenderLayerCompositor::updateLayerForTopOverhangArea(bool wantsLayer)
3554 {
3555     if (!isMainFrameCompositor())
3556         return nullptr;
3557
3558     if (!wantsLayer) {
3559         GraphicsLayer::unparentAndClear(m_layerForTopOverhangArea);
3560         return nullptr;
3561     }
3562
3563     if (!m_layerForTopOverhangArea) {
3564         m_layerForTopOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), *this);
3565         m_layerForTopOverhangArea->setName("top overhang");
3566         m_scrolledContentsLayer->addChildBelow(*m_layerForTopOverhangArea, m_rootContentsLayer.get());
3567     }
3568
3569     return m_layerForTopOverhangArea.get();
3570 }
3571
3572 GraphicsLayer* RenderLayerCompositor::updateLayerForBottomOverhangArea(bool wantsLayer)
3573 {
3574     if (!isMainFrameCompositor())
3575         return nullptr;
3576
3577     if (!wantsLayer) {
3578         GraphicsLayer::unparentAndClear(m_layerForBottomOverhangArea);
3579         return nullptr;
3580     }
3581
3582     if (!m_layerForBottomOverhangArea) {
3583         m_layerForBottomOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), *this);
3584         m_layerForBottomOverhangArea->setName("bottom overhang");
3585         m_scrolledContentsLayer->addChildBelow(*m_layerForBottomOverhangArea, m_rootContentsLayer.get());
3586     }
3587
3588     m_layerForBottomOverhangArea->setPosition(FloatPoint(0, m_rootContentsLayer->size().height() + m_renderView.frameView().headerHeight()
3589         + m_renderView.frameView().footerHeight() + m_renderView.frameView().topContentInset()));
3590     return m_layerForBottomOverhangArea.get();
3591 }
3592
3593 GraphicsLayer* RenderLayerCompositor::updateLayerForHeader(bool wantsLayer)
3594 {
3595     if (!isMainFrameCompositor())
3596         return nullptr;
3597
3598     if (!wantsLayer) {
3599         if (m_layerForHeader) {
3600             GraphicsLayer::unparentAndClear(m_layerForHeader);
3601
3602             // The ScrollingTree knows about the header layer, and the position of the root layer is affected
3603             // by the header layer, so if we remove the header, we need to tell the scrolling tree.
3604             if (auto* scrollingCoordinator = this->scrollingCoordinator())
3605                 scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
3606         }
3607         return nullptr;
3608     }
3609
3610     if (!m_layerForHeader) {
3611         m_layerForHeader = GraphicsLayer::create(graphicsLayerFactory(), *this);
3612         m_layerForHeader->setName("header");
3613         m_scrolledContentsLayer->addChildAbove(*m_layerForHeader, m_rootContentsLayer.get());
3614         m_renderView.frameView().addPaintPendingMilestones(DidFirstFlushForHeaderLayer);
3615     }
3616
3617     m_layerForHeader->setPosition(FloatPoint(0,
3618         FrameView::yPositionForHeaderLayer(m_renderView.frameView().scrollPosition(), m_renderView.frameView().topContentInset())));
3619     m_layerForHeader->setAnchorPoint(FloatPoint3D());
3620     m_layerForHeader->setSize(FloatSize(m_renderView.frameView().visibleWidth(), m_renderView.frameView().headerHeight()));
3621
3622     if (auto* scrollingCoordinator = this->scrollingCoordinator())
3623         scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
3624
3625     page().chrome().client().didAddHeaderLayer(*m_layerForHeader);
3626
3627     return m_layerForHeader.get();
3628 }
3629
3630 GraphicsLayer* RenderLayerCompositor::updateLayerForFooter(bool wantsLayer)
3631 {
3632     if (!isMainFrameCompositor())
3633         return nullptr;
3634
3635     if (!wantsLayer) {
3636         if (m_layerForFooter) {
3637             GraphicsLayer::unparentAndClear(m_layerForFooter);
3638
3639             // The ScrollingTree knows about the footer layer, and the total scrollable size is affected
3640             // by the footer layer, so if we remove the footer, we need to tell the scrolling tree.
3641             if (auto* scrollingCoordinator = this->scrollingCoordinator())
3642                 scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
3643         }
3644         return nullptr;
3645     }
3646
3647     if (!m_layerForFooter) {
3648         m_layerForFooter = GraphicsLayer::create(graphicsLayerFactory(), *this);
3649         m_layerForFooter->setName("footer");
3650         m_scrolledContentsLayer->addChildAbove(*m_layerForFooter, m_rootContentsLayer.get());
3651     }
3652
3653     float totalContentHeight = m_rootContentsLayer->size().height() + m_renderView.frameView().headerHeight() + m_renderView.frameView().footerHeight();
3654     m_layerForFooter->setPosition(FloatPoint(0, FrameView::yPositionForFooterLayer(m_renderView.frameView().scrollPosition(),
3655         m_renderView.frameView().topContentInset(), totalContentHeight, m_renderView.frameView().footerHeight())));
3656     m_layerForFooter->setAnchorPoint(FloatPoint3D());
3657     m_layerForFooter->setSize(FloatSize(m_renderView.frameView().visibleWidth(), m_renderView.frameView().footerHeight()));
3658
3659     if (auto* scrollingCoordinator = this->scrollingCoordinator())
3660         scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
3661
3662     page().chrome().client().didAddFooterLayer(*m_layerForFooter);
3663
3664     return m_layerForFooter.get();
3665 }
3666
3667 #endif
3668
3669 bool RenderLayerCompositor::viewHasTransparentBackground(Color* backgroundColor) const
3670 {
3671     if (m_renderView.frameView().isTransparent()) {
3672         if (backgroundColor)
3673             *backgroundColor = Color(); // Return an invalid color.
3674         return true;
3675     }
3676
3677     Color documentBackgroundColor = m_renderView.frameView().documentBackgroundColor();
3678     if (!documentBackgroundColor.isValid())
3679         documentBackgroundColor = m_renderView.frameView().baseBackgroundColor();
3680
3681     ASSERT(documentBackgroundColor.isValid());
3682
3683     if (backgroundColor)
3684         *backgroundColor = documentBackgroundColor;
3685
3686     return !documentBackgroundColor.isOpaque();
3687 }
3688
3689 // We can't rely on getting layerStyleChanged() for a style change that affects the root background, because the style change may
3690 // be on the body which has no RenderLayer.
3691 void RenderLayerCompositor::rootOrBodyStyleChanged(RenderElement& renderer, const RenderStyle* oldStyle)
3692 {
3693     if (!usesCompositing())
3694         return;
3695
3696     Color oldBackgroundColor;
3697     if (oldStyle)
3698         oldBackgroundColor = oldStyle->visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor);
3699
3700     if (oldBackgroundColor != renderer.style().visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor))
3701         rootBackgroundColorOrTransparencyChanged();
3702
3703     bool hadFixedBackground = oldStyle && oldStyle->hasEntirelyFixedBackground();
3704     if (hadFixedBackground != renderer.style().hasEntirelyFixedBackground())
3705         rootLayerConfigurationChanged();
3706 }
3707
3708 void RenderLayerCompositor::rootBackgroundColorOrTransparencyChanged()
3709 {
3710     if (!usesCompositing())
3711         return;
3712
3713     Color backgroundColor;
3714     bool isTransparent = viewHasTransparentBackground(&backgroundColor);
3715     
3716     Color extendedBackgroundColor = m_renderView.settings().backgroundShouldExtendBeyondPage() ? backgroundColor : Color();
3717     
3718     bool transparencyChanged = m_viewBackgroundIsTransparent != isTransparent;
3719     bool backgroundColorChanged = m_viewBackgroundColor != backgroundColor;
3720     bool extendedBackgroundColorChanged = m_rootExtendedBackgroundColor != extendedBackgroundColor;
3721
3722     if (!transparencyChanged && !backgroundColorChanged && !extendedBackgroundColorChanged)
3723         return;
3724
3725     LOG(Compositing, "RenderLayerCompositor %p rootBackgroundColorOrTransparencyChanged. isTransparent=%d", this, isTransparent);
3726
3727     m_viewBackgroundIsTransparent = isTransparent;
3728     m_viewBackgroundColor = backgroundColor;
3729     m_rootExtendedBackgroundColor = extendedBackgroundColor;
3730     
3731     if (extendedBackgroundColorChanged) {
3732         page().chrome().client().pageExtendedBackgroundColorDidChange(m_rootExtendedBackgroundColor);
3733         
3734 #if ENABLE(RUBBER_BANDING)
3735         if (m_layerForOverhangAreas) {
3736             m_layerForOverhangAreas->setBackgroundColor(m_rootExtendedBackgroundColor);
3737
3738             if (!m_rootExtendedBackgroundColor.isValid())
3739                 m_layerForOverhangAreas->setCustomAppearance(GraphicsLayer::CustomAppearance::ScrollingOverhang);
3740         }
3741 #endif
3742     }
3743     
3744     rootLayerConfigurationChanged();
3745 }
3746
3747 void RenderLayerCompositor::updateOverflowControlsLayers()
3748 {
3749 #if ENABLE(RUBBER_BANDING)
3750     if (requiresOverhangAreasLayer()) {
3751         if (!m_layerForOverhangAreas) {
3752             m_layerForOverhangAreas = GraphicsLayer::create(graphicsLayerFactory(), *this);
3753             m_layerForOverhangAreas->setName("overhang areas");
3754             m_layerForOverhangAreas->setDrawsContent(false);
3755
3756             float topContentInset = m_renderView.frameView().topContentInset();
3757             IntSize overhangAreaSize = m_renderView.frameView().frameRect().size();
3758             overhangAreaSize.setHeight(overhangAreaSize.height() - topContentInset);
3759             m_layerForOverhangAreas->setSize(overhangAreaSize);
3760             m_layerForOverhangAreas->setPosition(FloatPoint(0, topContentInset));
3761             m_layerForOverhangAreas->setAnchorPoint(FloatPoint3D());
3762
3763             if (m_renderView.settings().backgroundShouldExtendBeyondPage())
3764                 m_layerForOverhangAreas->setBackgroundColor(m_renderView.frameView().documentBackgroundColor());
3765             else
3766                 m_layerForOverhangAreas->setCustomAppearance(GraphicsLayer::CustomAppearance::ScrollingOverhang);
3767
3768             // We want the overhang areas layer to be positioned below the frame contents,
3769             // so insert it below the clip layer.
3770             m_overflowControlsHostLayer->addChildBelow(*m_layerForOverhangAreas, layerForClipping());
3771         }
3772     } else
3773         GraphicsLayer::unparentAndClear(m_layerForOverhangAreas);
3774
3775     if (requiresContentShadowLayer()) {
3776         if (!m_contentShadowLayer) {
3777             m_contentShadowLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3778             m_contentShadowLayer->setName("content shadow");
3779             m_contentShadowLayer->setSize(m_rootContentsLayer->size());
3780             m_contentShadowLayer->setPosition(m_rootContentsLayer->position());
3781             m_contentShadowLayer->setAnchorPoint(FloatPoint3D());
3782             m_contentShadowLayer->setCustomAppearance(GraphicsLayer::CustomAppearance::ScrollingShadow);
3783
3784             m_scrolledContentsLayer->addChildBelow(*m_contentShadowLayer, m_rootContentsLayer.get());
3785         }
3786     } else
3787         GraphicsLayer::unparentAndClear(m_contentShadowLayer);
3788 #endif
3789
3790     if (requiresHorizontalScrollbarLayer()) {
3791         if (!m_layerForHorizontalScrollbar) {
3792             m_layerForHorizontalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), *this);
3793             m_layerForHorizontalScrollbar->setAllowsBackingStoreDetaching(false);
3794             m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
3795             m_layerForHorizontalScrollbar->setName("horizontal scrollbar container");
3796 #if PLATFORM(COCOA) && USE(CA)
3797             m_layerForHorizontalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
3798 #endif
3799             m_overflowControlsHostLayer->addChild(*m_layerForHorizontalScrollbar);
3800
3801             if (auto* scrollingCoordinator = this->scrollingCoordinator())
3802                 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), HorizontalScrollbar);
3803         }
3804     } else if (m_layerForHorizontalScrollbar) {
3805         GraphicsLayer::unparentAndClear(m_layerForHorizontalScrollbar);
3806
3807         if (auto* scrollingCoordinator = this->scrollingCoordinator())
3808             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), HorizontalScrollbar);
3809     }
3810
3811     if (requiresVerticalScrollbarLayer()) {
3812         if (!m_layerForVerticalScrollbar) {
3813             m_layerForVerticalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), *this);
3814             m_layerForVerticalScrollbar->setAllowsBackingStoreDetaching(false);
3815             m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
3816             m_layerForVerticalScrollbar->setName("vertical scrollbar container");
3817 #if PLATFORM(COCOA) && USE(CA)
3818             m_layerForVerticalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
3819 #endif
3820             m_overflowControlsHostLayer->addChild(*m_layerForVerticalScrollbar);
3821
3822             if (auto* scrollingCoordinator = this->scrollingCoordinator())
3823                 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), VerticalScrollbar);
3824         }
3825     } else if (m_layerForVerticalScrollbar) {
3826         GraphicsLayer::unparentAndClear(m_layerForVerticalScrollbar);
3827
3828         if (auto* scrollingCoordinator = this->scrollingCoordinator())
3829             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), VerticalScrollbar);
3830     }
3831
3832     if (requiresScrollCornerLayer()) {