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