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