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