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