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