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