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