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