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