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