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