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