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