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