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