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