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