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