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