[iOS WK2] Avoid lots of compositing backing store for offscreen position:fixed descen...
[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         m_backingSharingLayers.append(makeWeakPtr(layer));
211     }
212
213     void updateBeforeDescendantTraversal(RenderLayer&, bool willBeComposited);
214     void updateAfterDescendantTraversal(RenderLayer&, RenderLayer* stackingContextAncestor);
215
216 private:
217     void layerWillBeComposited(RenderLayer&);
218
219     void startBackingSharingSequence(RenderLayer& candidateLayer, RenderLayer* candidateStackingContext);
220     void endBackingSharingSequence();
221
222     RenderLayer* m_backingProviderCandidate { nullptr };
223     RenderLayer* m_backingProviderStackingContext { nullptr };
224     Vector<WeakPtr<RenderLayer>> m_backingSharingLayers;
225 };
226
227 void RenderLayerCompositor::BackingSharingState::startBackingSharingSequence(RenderLayer& candidateLayer, RenderLayer* candidateStackingContext)
228 {
229     ASSERT(!m_backingProviderCandidate);
230     ASSERT(m_backingSharingLayers.isEmpty());
231
232     m_backingProviderCandidate = &candidateLayer;
233     m_backingProviderStackingContext = candidateStackingContext;
234 }
235
236 void RenderLayerCompositor::BackingSharingState::endBackingSharingSequence()
237 {
238     if (m_backingProviderCandidate) {
239         m_backingProviderCandidate->backing()->setBackingSharingLayers(WTFMove(m_backingSharingLayers));
240         m_backingSharingLayers.clear();
241     }
242     
243     m_backingProviderCandidate = nullptr;
244 }
245
246 void RenderLayerCompositor::BackingSharingState::updateBeforeDescendantTraversal(RenderLayer& layer, bool willBeComposited)
247 {
248     layer.setBackingProviderLayer(nullptr);
249
250     // A layer that composites resets backing-sharing, since subsequent layers need to composite to overlap it.
251     if (willBeComposited) {
252         m_backingSharingLayers.removeAll(&layer);
253         endBackingSharingSequence();
254     }
255 }
256
257 void RenderLayerCompositor::BackingSharingState::updateAfterDescendantTraversal(RenderLayer& layer, RenderLayer* stackingContextAncestor)
258 {
259     if (layer.isComposited()) {
260         // If this layer is being composited, clean up sharing-related state.
261         layer.disconnectFromBackingProviderLayer();
262         m_backingSharingLayers.removeAll(&layer);
263     }
264
265     if (m_backingProviderCandidate && &layer == m_backingProviderStackingContext) {
266         LOG_WITH_STREAM(Compositing, stream << "End of stacking context for backing provider " << m_backingProviderCandidate << ", ending sharing sequence with " << m_backingSharingLayers.size() << " sharing layers");
267         endBackingSharingSequence();
268     } else if (!m_backingProviderCandidate && layer.isComposited()) {
269         LOG_WITH_STREAM(Compositing, stream << "Post-descendant compositing of " << &layer << ", ending sharing sequence for " << m_backingProviderCandidate << " with " << m_backingSharingLayers.size() << " sharing layers");
270         endBackingSharingSequence();
271         startBackingSharingSequence(layer, stackingContextAncestor);
272     }
273     
274     if (&layer != m_backingProviderCandidate && layer.isComposited())
275         layer.backing()->clearBackingSharingLayers();
276 }
277
278 #if !LOG_DISABLED || ENABLE(TREE_DEBUGGING)
279 static inline bool compositingLogEnabled()
280 {
281     return LogCompositing.state == WTFLogChannelState::On;
282 }
283
284 static inline bool layersLogEnabled()
285 {
286     return LogLayers.state == WTFLogChannelState::On;
287 }
288 #endif
289
290 RenderLayerCompositor::RenderLayerCompositor(RenderView& renderView)
291     : m_renderView(renderView)
292     , m_updateCompositingLayersTimer(*this, &RenderLayerCompositor::updateCompositingLayersTimerFired)
293     , m_layerFlushTimer(*this, &RenderLayerCompositor::layerFlushTimerFired)
294 {
295 #if PLATFORM(IOS_FAMILY)
296     if (m_renderView.frameView().platformWidget())
297         m_legacyScrollingLayerCoordinator = std::make_unique<LegacyWebKitScrollingLayerCoordinator>(page().chrome().client(), isMainFrameCompositor());
298 #endif
299 }
300
301 RenderLayerCompositor::~RenderLayerCompositor()
302 {
303     // Take care that the owned GraphicsLayers are deleted first as their destructors may call back here.
304     GraphicsLayer::unparentAndClear(m_rootContentsLayer);
305     
306     GraphicsLayer::unparentAndClear(m_clipLayer);
307     GraphicsLayer::unparentAndClear(m_scrollContainerLayer);
308     GraphicsLayer::unparentAndClear(m_scrolledContentsLayer);
309
310     GraphicsLayer::unparentAndClear(m_overflowControlsHostLayer);
311
312     GraphicsLayer::unparentAndClear(m_layerForHorizontalScrollbar);
313     GraphicsLayer::unparentAndClear(m_layerForVerticalScrollbar);
314     GraphicsLayer::unparentAndClear(m_layerForScrollCorner);
315
316 #if ENABLE(RUBBER_BANDING)
317     GraphicsLayer::unparentAndClear(m_layerForOverhangAreas);
318     GraphicsLayer::unparentAndClear(m_contentShadowLayer);
319     GraphicsLayer::unparentAndClear(m_layerForTopOverhangArea);
320     GraphicsLayer::unparentAndClear(m_layerForBottomOverhangArea);
321     GraphicsLayer::unparentAndClear(m_layerForHeader);
322     GraphicsLayer::unparentAndClear(m_layerForFooter);
323 #endif
324
325     ASSERT(m_rootLayerAttachment == RootLayerUnattached);
326 }
327
328 void RenderLayerCompositor::enableCompositingMode(bool enable /* = true */)
329 {
330     if (enable != m_compositing) {
331         m_compositing = enable;
332         
333         if (m_compositing) {
334             ensureRootLayer();
335             notifyIFramesOfCompositingChange();
336         } else
337             destroyRootLayer();
338         
339         
340         m_renderView.layer()->setNeedsPostLayoutCompositingUpdate();
341     }
342 }
343
344 void RenderLayerCompositor::cacheAcceleratedCompositingFlags()
345 {
346     auto& settings = m_renderView.settings();
347     bool hasAcceleratedCompositing = settings.acceleratedCompositingEnabled();
348
349     // We allow the chrome to override the settings, in case the page is rendered
350     // on a chrome that doesn't allow accelerated compositing.
351     if (hasAcceleratedCompositing) {
352         m_compositingTriggers = page().chrome().client().allowedCompositingTriggers();
353         hasAcceleratedCompositing = m_compositingTriggers;
354     }
355
356     bool showDebugBorders = settings.showDebugBorders();
357     bool showRepaintCounter = settings.showRepaintCounter();
358     bool acceleratedDrawingEnabled = settings.acceleratedDrawingEnabled();
359     bool displayListDrawingEnabled = settings.displayListDrawingEnabled();
360
361     // forceCompositingMode for subframes can only be computed after layout.
362     bool forceCompositingMode = m_forceCompositingMode;
363     if (isMainFrameCompositor())
364         forceCompositingMode = m_renderView.settings().forceCompositingMode() && hasAcceleratedCompositing; 
365     
366     if (hasAcceleratedCompositing != m_hasAcceleratedCompositing || showDebugBorders != m_showDebugBorders || showRepaintCounter != m_showRepaintCounter || forceCompositingMode != m_forceCompositingMode) {
367         if (auto* rootLayer = m_renderView.layer()) {
368             rootLayer->setNeedsCompositingConfigurationUpdate();
369             rootLayer->setDescendantsNeedUpdateBackingAndHierarchyTraversal();
370         }
371     }
372
373     bool debugBordersChanged = m_showDebugBorders != showDebugBorders;
374     m_hasAcceleratedCompositing = hasAcceleratedCompositing;
375     m_forceCompositingMode = forceCompositingMode;
376     m_showDebugBorders = showDebugBorders;
377     m_showRepaintCounter = showRepaintCounter;
378     m_acceleratedDrawingEnabled = acceleratedDrawingEnabled;
379     m_displayListDrawingEnabled = displayListDrawingEnabled;
380     
381     if (debugBordersChanged) {
382         if (m_layerForHorizontalScrollbar)
383             m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
384
385         if (m_layerForVerticalScrollbar)
386             m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
387
388         if (m_layerForScrollCorner)
389             m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
390     }
391     
392     if (updateCompositingPolicy())
393         rootRenderLayer().setDescendantsNeedCompositingRequirementsTraversal();
394 }
395
396 void RenderLayerCompositor::cacheAcceleratedCompositingFlagsAfterLayout()
397 {
398     cacheAcceleratedCompositingFlags();
399
400     if (isMainFrameCompositor())
401         return;
402
403     RequiresCompositingData queryData;
404     bool forceCompositingMode = m_hasAcceleratedCompositing && m_renderView.settings().forceCompositingMode() && requiresCompositingForScrollableFrame(queryData);
405     if (forceCompositingMode != m_forceCompositingMode) {
406         m_forceCompositingMode = forceCompositingMode;
407         rootRenderLayer().setDescendantsNeedCompositingRequirementsTraversal();
408     }
409 }
410
411 bool RenderLayerCompositor::updateCompositingPolicy()
412 {
413     if (!usesCompositing())
414         return false;
415
416     auto currentPolicy = m_compositingPolicy;
417     if (page().compositingPolicyOverride()) {
418         m_compositingPolicy = page().compositingPolicyOverride().value();
419         return m_compositingPolicy != currentPolicy;
420     }
421     
422     auto memoryPolicy = MemoryPressureHandler::currentMemoryUsagePolicy();
423     m_compositingPolicy = memoryPolicy == WTF::MemoryUsagePolicy::Unrestricted ? CompositingPolicy::Normal : CompositingPolicy::Conservative;
424     return m_compositingPolicy != currentPolicy;
425 }
426
427 bool RenderLayerCompositor::canRender3DTransforms() const
428 {
429     return hasAcceleratedCompositing() && (m_compositingTriggers & ChromeClient::ThreeDTransformTrigger);
430 }
431
432 void RenderLayerCompositor::willRecalcStyle()
433 {
434     cacheAcceleratedCompositingFlags();
435 }
436
437 bool RenderLayerCompositor::didRecalcStyleWithNoPendingLayout()
438 {
439     return updateCompositingLayers(CompositingUpdateType::AfterStyleChange);
440 }
441
442 void RenderLayerCompositor::customPositionForVisibleRectComputation(const GraphicsLayer* graphicsLayer, FloatPoint& position) const
443 {
444     if (graphicsLayer != m_scrolledContentsLayer.get())
445         return;
446
447     FloatPoint scrollPosition = -position;
448
449     if (m_renderView.frameView().scrollBehaviorForFixedElements() == StickToDocumentBounds)
450         scrollPosition = m_renderView.frameView().constrainScrollPositionForOverhang(roundedIntPoint(scrollPosition));
451
452     position = -scrollPosition;
453 }
454
455 void RenderLayerCompositor::notifyFlushRequired(const GraphicsLayer* layer)
456 {
457     scheduleLayerFlush(layer->canThrottleLayerFlush());
458 }
459
460 void RenderLayerCompositor::scheduleLayerFlush(bool canThrottle)
461 {
462     ASSERT(!m_flushingLayers);
463
464     if (canThrottle)
465         startInitialLayerFlushTimerIfNeeded();
466
467     if (canThrottle && isThrottlingLayerFlushes())
468         m_hasPendingLayerFlush = true;
469     else {
470         m_hasPendingLayerFlush = false;
471         page().renderingUpdateScheduler().scheduleRenderingUpdate();
472     }
473 }
474
475 FloatRect RenderLayerCompositor::visibleRectForLayerFlushing() const
476 {
477     const FrameView& frameView = m_renderView.frameView();
478 #if PLATFORM(IOS_FAMILY)
479     return frameView.exposedContentRect();
480 #else
481     // Having a m_scrolledContentsLayer indicates that we're doing scrolling via GraphicsLayers.
482     FloatRect visibleRect = m_scrolledContentsLayer ? FloatRect({ }, frameView.sizeForVisibleContent()) : frameView.visibleContentRect();
483
484     if (frameView.viewExposedRect())
485         visibleRect.intersect(frameView.viewExposedRect().value());
486
487     return visibleRect;
488 #endif
489 }
490
491 void RenderLayerCompositor::flushPendingLayerChanges(bool isFlushRoot)
492 {
493     // FrameView::flushCompositingStateIncludingSubframes() flushes each subframe,
494     // but GraphicsLayer::flushCompositingState() will cross frame boundaries
495     // if the GraphicsLayers are connected (the RootLayerAttachedViaEnclosingFrame case).
496     // As long as we're not the root of the flush, we can bail.
497     if (!isFlushRoot && rootLayerAttachment() == RootLayerAttachedViaEnclosingFrame)
498         return;
499
500     if (rootLayerAttachment() == RootLayerUnattached) {
501 #if PLATFORM(IOS_FAMILY)
502         startLayerFlushTimerIfNeeded();
503 #endif
504         m_shouldFlushOnReattach = true;
505         return;
506     }
507
508     auto& frameView = m_renderView.frameView();
509     AnimationUpdateBlock animationUpdateBlock(&frameView.frame().animation());
510
511     ASSERT(!m_flushingLayers);
512     {
513         SetForScope<bool> flushingLayersScope(m_flushingLayers, true);
514
515         if (auto* rootLayer = rootGraphicsLayer()) {
516             FloatRect visibleRect = visibleRectForLayerFlushing();
517             LOG_WITH_STREAM(Compositing,  stream << "\nRenderLayerCompositor " << this << " flushPendingLayerChanges (is root " << isFlushRoot << ") visible rect " << visibleRect);
518             rootLayer->flushCompositingState(visibleRect);
519         }
520         
521         ASSERT(m_flushingLayers);
522
523 #if ENABLE(TREE_DEBUGGING)
524         if (layersLogEnabled()) {
525             LOG(Layers, "RenderLayerCompositor::flushPendingLayerChanges");
526             showGraphicsLayerTree(rootGraphicsLayer());
527         }
528 #endif
529     }
530
531 #if PLATFORM(IOS_FAMILY)
532     updateScrollCoordinatedLayersAfterFlushIncludingSubframes();
533
534     if (isFlushRoot)
535         page().chrome().client().didFlushCompositingLayers();
536 #endif
537
538     ++m_layerFlushCount;
539     startLayerFlushTimerIfNeeded();
540 }
541
542 #if PLATFORM(IOS_FAMILY)
543 void RenderLayerCompositor::updateScrollCoordinatedLayersAfterFlushIncludingSubframes()
544 {
545     updateScrollCoordinatedLayersAfterFlush();
546
547     auto& frame = m_renderView.frameView().frame();
548     for (Frame* subframe = frame.tree().firstChild(); subframe; subframe = subframe->tree().traverseNext(&frame)) {
549         auto* view = subframe->contentRenderer();
550         if (!view)
551             continue;
552
553         view->compositor().updateScrollCoordinatedLayersAfterFlush();
554     }
555 }
556
557 void RenderLayerCompositor::updateScrollCoordinatedLayersAfterFlush()
558 {
559     if (m_legacyScrollingLayerCoordinator) {
560         m_legacyScrollingLayerCoordinator->registerAllViewportConstrainedLayers(*this);
561         m_legacyScrollingLayerCoordinator->registerAllScrollingLayers();
562     }
563 }
564 #endif
565
566 void RenderLayerCompositor::didChangePlatformLayerForLayer(RenderLayer& layer, const GraphicsLayer*)
567 {
568     auto* scrollingCoordinator = this->scrollingCoordinator();
569     if (!scrollingCoordinator)
570         return;
571
572     auto* backing = layer.backing();
573     if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::Scrolling))
574         updateScrollingNodeLayers(nodeID, layer, *scrollingCoordinator);
575
576     if (auto* clippingStack = layer.backing()->ancestorClippingStack())
577         clippingStack->updateScrollingNodeLayers(*scrollingCoordinator);
578
579     if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::ViewportConstrained))
580         scrollingCoordinator->setNodeLayers(nodeID, { backing->graphicsLayer() });
581
582     if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::FrameHosting))
583         scrollingCoordinator->setNodeLayers(nodeID, { backing->graphicsLayer() });
584
585     if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::Positioning))
586         scrollingCoordinator->setNodeLayers(nodeID, { backing->graphicsLayer() });
587 }
588
589 void RenderLayerCompositor::didPaintBacking(RenderLayerBacking*)
590 {
591     auto& frameView = m_renderView.frameView();
592     frameView.setLastPaintTime(MonotonicTime::now());
593     if (frameView.milestonesPendingPaint())
594         frameView.firePaintRelatedMilestonesIfNeeded();
595 }
596
597 void RenderLayerCompositor::didChangeVisibleRect()
598 {
599     auto* rootLayer = rootGraphicsLayer();
600     if (!rootLayer)
601         return;
602
603     FloatRect visibleRect = visibleRectForLayerFlushing();
604     bool requiresFlush = rootLayer->visibleRectChangeRequiresFlush(visibleRect);
605     LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor::didChangeVisibleRect " << visibleRect << " requiresFlush " << requiresFlush);
606     if (requiresFlush)
607         scheduleLayerFlush();
608 }
609
610 void RenderLayerCompositor::notifyFlushBeforeDisplayRefresh(const GraphicsLayer*)
611 {
612     if (!m_layerUpdater) {
613         PlatformDisplayID displayID = page().chrome().displayID();
614         m_layerUpdater = std::make_unique<GraphicsLayerUpdater>(*this, displayID);
615     }
616     
617     m_layerUpdater->scheduleUpdate();
618 }
619
620 void RenderLayerCompositor::flushLayersSoon(GraphicsLayerUpdater&)
621 {
622     scheduleLayerFlush(true);
623 }
624
625 void RenderLayerCompositor::layerTiledBackingUsageChanged(const GraphicsLayer* graphicsLayer, bool usingTiledBacking)
626 {
627     if (usingTiledBacking) {
628         ++m_layersWithTiledBackingCount;
629         graphicsLayer->tiledBacking()->setIsInWindow(page().isInWindow());
630     } else {
631         ASSERT(m_layersWithTiledBackingCount > 0);
632         --m_layersWithTiledBackingCount;
633     }
634 }
635
636 void RenderLayerCompositor::scheduleCompositingLayerUpdate()
637 {
638     if (!m_updateCompositingLayersTimer.isActive())
639         m_updateCompositingLayersTimer.startOneShot(0_s);
640 }
641
642 void RenderLayerCompositor::updateCompositingLayersTimerFired()
643 {
644     updateCompositingLayers(CompositingUpdateType::AfterLayout);
645 }
646
647 void RenderLayerCompositor::cancelCompositingLayerUpdate()
648 {
649     m_updateCompositingLayersTimer.stop();
650 }
651
652 static Optional<ScrollingNodeID> frameHostingNodeForFrame(Frame& frame)
653 {
654     if (!frame.document() || !frame.view())
655         return { };
656
657     // Find the frame's enclosing layer in our render tree.
658     auto* ownerElement = frame.document()->ownerElement();
659     if (!ownerElement)
660         return { };
661
662     auto* frameRenderer = ownerElement->renderer();
663     if (!frameRenderer || !is<RenderWidget>(frameRenderer))
664         return { };
665
666     auto& widgetRenderer = downcast<RenderWidget>(*frameRenderer);
667     if (!widgetRenderer.hasLayer() || !widgetRenderer.layer()->isComposited()) {
668         LOG(Scrolling, "frameHostingNodeForFrame: frame renderer has no layer or is not composited.");
669         return { };
670     }
671
672     if (auto frameHostingNodeID = widgetRenderer.layer()->backing()->scrollingNodeIDForRole(ScrollCoordinationRole::FrameHosting))
673         return frameHostingNodeID;
674
675     return { };
676 }
677
678 // Returns true on a successful update.
679 bool RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType updateType, RenderLayer* updateRoot)
680 {
681     LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor " << this << " updateCompositingLayers " << updateType << " contentLayersCount " << m_contentLayersCount);
682
683 #if ENABLE(TREE_DEBUGGING)
684     if (compositingLogEnabled())
685         showPaintOrderTree(m_renderView.layer());
686 #endif
687
688     if (updateType == CompositingUpdateType::AfterStyleChange || updateType == CompositingUpdateType::AfterLayout)
689         cacheAcceleratedCompositingFlagsAfterLayout(); // Some flags (e.g. forceCompositingMode) depend on layout.
690
691     m_updateCompositingLayersTimer.stop();
692
693     ASSERT(m_renderView.document().pageCacheState() == Document::NotInPageCache);
694     
695     // Compositing layers will be updated in Document::setVisualUpdatesAllowed(bool) if suppressed here.
696     if (!m_renderView.document().visualUpdatesAllowed())
697         return false;
698
699     // Avoid updating the layers with old values. Compositing layers will be updated after the layout is finished.
700     // This happens when m_updateCompositingLayersTimer fires before layout is updated.
701     if (m_renderView.needsLayout()) {
702         LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor " << this << " updateCompositingLayers " << updateType << " - m_renderView.needsLayout, bailing ");
703         return false;
704     }
705
706     if (!m_compositing && (m_forceCompositingMode || (isMainFrameCompositor() && page().pageOverlayController().overlayCount())))
707         enableCompositingMode(true);
708
709     bool isPageScroll = !updateRoot || updateRoot == &rootRenderLayer();
710     updateRoot = &rootRenderLayer();
711
712     if (updateType == CompositingUpdateType::OnScroll || updateType == CompositingUpdateType::OnCompositedScroll) {
713         // We only get here if we didn't scroll on the scrolling thread, so this update needs to re-position viewport-constrained layers.
714         if (m_renderView.settings().acceleratedCompositingForFixedPositionEnabled() && isPageScroll) {
715             if (auto* viewportConstrainedObjects = m_renderView.frameView().viewportConstrainedObjects()) {
716                 for (auto* renderer : *viewportConstrainedObjects) {
717                     if (auto* layer = renderer->layer())
718                         layer->setNeedsCompositingGeometryUpdate();
719                 }
720             }
721         }
722
723         // Scrolling can affect overlap. FIXME: avoid for page scrolling.
724         updateRoot->setDescendantsNeedCompositingRequirementsTraversal();
725     }
726
727     if (updateType == CompositingUpdateType::AfterLayout) {
728         // Ensure that post-layout updates push new scroll position and viewport rects onto the root node.
729         rootRenderLayer().setNeedsScrollingTreeUpdate();
730     }
731
732     if (!updateRoot->hasDescendantNeedingCompositingRequirementsTraversal() && !m_compositing) {
733         LOG_WITH_STREAM(Compositing, stream << " no compositing work to do");
734         return true;
735     }
736
737     if (!updateRoot->needsAnyCompositingTraversal()) {
738         LOG_WITH_STREAM(Compositing, stream << " updateRoot has no dirty child and doesn't need update");
739         return true;
740     }
741
742     ++m_compositingUpdateCount;
743
744     AnimationUpdateBlock animationUpdateBlock(&m_renderView.frameView().frame().animation());
745
746     SetForScope<bool> postLayoutChange(m_inPostLayoutUpdate, true);
747
748 #if !LOG_DISABLED
749     MonotonicTime startTime;
750     if (compositingLogEnabled()) {
751         ++m_rootLayerUpdateCount;
752         startTime = MonotonicTime::now();
753     }
754
755     if (compositingLogEnabled()) {
756         m_obligateCompositedLayerCount = 0;
757         m_secondaryCompositedLayerCount = 0;
758         m_obligatoryBackingStoreBytes = 0;
759         m_secondaryBackingStoreBytes = 0;
760
761         auto& frame = m_renderView.frameView().frame();
762         bool isMainFrame = isMainFrameCompositor();
763         LOG_WITH_STREAM(Compositing, stream << "\nUpdate " << m_rootLayerUpdateCount << " of " << (isMainFrame ? "main frame" : frame.tree().uniqueName().string().utf8().data()) << " - compositing policy is " << m_compositingPolicy);
764     }
765 #endif
766
767     // FIXME: optimize root-only update.
768     if (updateRoot->hasDescendantNeedingCompositingRequirementsTraversal() || updateRoot->needsCompositingRequirementsTraversal()) {
769         auto& rootLayer = rootRenderLayer();
770         CompositingState compositingState(updateRoot);
771         BackingSharingState backingSharingState;
772         LayerOverlapMap overlapMap(rootLayer);
773
774         bool descendantHas3DTransform = false;
775         computeCompositingRequirements(nullptr, rootLayer, overlapMap, compositingState, backingSharingState, descendantHas3DTransform);
776     }
777
778     LOG(Compositing, "\nRenderLayerCompositor::updateCompositingLayers - mid");
779 #if ENABLE(TREE_DEBUGGING)
780     if (compositingLogEnabled())
781         showPaintOrderTree(m_renderView.layer());
782 #endif
783
784     if (updateRoot->hasDescendantNeedingUpdateBackingOrHierarchyTraversal() || updateRoot->needsUpdateBackingOrHierarchyTraversal()) {
785         ScrollingTreeState scrollingTreeState = { 0, 0 };
786         if (!m_renderView.frame().isMainFrame())
787             scrollingTreeState.parentNodeID = frameHostingNodeForFrame(m_renderView.frame());
788
789         Vector<Ref<GraphicsLayer>> childList;
790         updateBackingAndHierarchy(*updateRoot, childList, scrollingTreeState);
791
792         // Host the document layer in the RenderView's root layer.
793         appendDocumentOverlayLayers(childList);
794         // Even when childList is empty, don't drop out of compositing mode if there are
795         // composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
796         if (childList.isEmpty() && !needsCompositingForContentOrOverlays())
797             destroyRootLayer();
798         else if (m_rootContentsLayer)
799             m_rootContentsLayer->setChildren(WTFMove(childList));
800     }
801
802 #if !LOG_DISABLED
803     if (compositingLogEnabled()) {
804         MonotonicTime endTime = MonotonicTime::now();
805         LOG(Compositing, "Total layers   primary   secondary   obligatory backing (KB)   secondary backing(KB)   total backing (KB)  update time (ms)\n");
806
807         LOG(Compositing, "%8d %11d %9d %20.2f %22.2f %22.2f %18.2f\n",
808             m_obligateCompositedLayerCount + m_secondaryCompositedLayerCount, m_obligateCompositedLayerCount,
809             m_secondaryCompositedLayerCount, m_obligatoryBackingStoreBytes / 1024, m_secondaryBackingStoreBytes / 1024, (m_obligatoryBackingStoreBytes + m_secondaryBackingStoreBytes) / 1024, (endTime - startTime).milliseconds());
810     }
811 #endif
812
813     // FIXME: Only do if dirty.
814     updateRootLayerPosition();
815
816 #if ENABLE(TREE_DEBUGGING)
817     if (compositingLogEnabled()) {
818         LOG(Compositing, "RenderLayerCompositor::updateCompositingLayers - post");
819         showPaintOrderTree(m_renderView.layer());
820     }
821 #endif
822
823     InspectorInstrumentation::layerTreeDidChange(&page());
824
825     return true;
826 }
827
828 static bool backingProviderLayerCanIncludeLayer(const RenderLayer& sharedLayer, const RenderLayer& layer)
829 {
830     // Disable sharing when painting shared layers doesn't work correctly.
831     if (layer.hasReflection())
832         return false;
833
834     return layer.ancestorLayerIsInContainingBlockChain(sharedLayer);
835 }
836
837 void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer& layer, LayerOverlapMap& overlapMap, CompositingState& compositingState, BackingSharingState& backingSharingState, bool& descendantHas3DTransform)
838 {
839     if (!layer.hasDescendantNeedingCompositingRequirementsTraversal()
840         && !layer.needsCompositingRequirementsTraversal()
841         && !compositingState.fullPaintOrderTraversalRequired
842         && !compositingState.descendantsRequireCompositingUpdate) {
843         traverseUnchangedSubtree(ancestorLayer, layer, overlapMap, compositingState, backingSharingState, descendantHas3DTransform);
844         return;
845     }
846
847     LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(compositingState.depth * 2, ' ') << &layer << (layer.isNormalFlowOnly() ? " n" : " s") << " computeCompositingRequirements (backing provider candidate " << backingSharingState.backingProviderCandidate() << ")");
848
849     // FIXME: maybe we can avoid updating all remaining layers in paint order.
850     compositingState.fullPaintOrderTraversalRequired |= layer.needsCompositingRequirementsTraversal();
851     compositingState.descendantsRequireCompositingUpdate |= layer.descendantsNeedCompositingRequirementsTraversal();
852
853     layer.updateDescendantDependentFlags();
854     layer.updateLayerListsIfNeeded();
855
856     layer.setHasCompositingDescendant(false);
857
858     // We updated compositing for direct reasons in layerStyleChanged(). Here, check for compositing that can only be evaluated after layout.
859     RequiresCompositingData queryData;
860     bool willBeComposited = layer.isComposited();
861     bool becameCompositedAfterDescendantTraversal = false;
862     IndirectCompositingReason compositingReason = compositingState.subtreeIsCompositing ? IndirectCompositingReason::Stacking : IndirectCompositingReason::None;
863
864     if (layer.needsPostLayoutCompositingUpdate() || compositingState.fullPaintOrderTraversalRequired || compositingState.descendantsRequireCompositingUpdate) {
865         layer.setIndirectCompositingReason(IndirectCompositingReason::None);
866         willBeComposited = needsToBeComposited(layer, queryData);
867     }
868
869     bool layerPaintsIntoProvidedBacking = false;
870     if (!willBeComposited && compositingState.subtreeIsCompositing && backingSharingState.backingProviderCandidate() && canBeComposited(layer) && backingProviderLayerCanIncludeLayer(*backingSharingState.backingProviderCandidate(), layer)) {
871         backingSharingState.appendSharingLayer(layer);
872         LOG(Compositing, " layer %p can share with %p", &layer, backingSharingState.backingProviderCandidate());
873         compositingReason = IndirectCompositingReason::None;
874         layerPaintsIntoProvidedBacking = true;
875     }
876
877     compositingState.fullPaintOrderTraversalRequired |= layer.subsequentLayersNeedCompositingRequirementsTraversal();
878
879     OverlapExtent layerExtent;
880     // Use the fact that we're composited as a hint to check for an animating transform.
881     // FIXME: Maybe needsToBeComposited() should return a bitmask of reasons, to avoid the need to recompute things.
882     if (willBeComposited && !layer.isRenderViewLayer())
883         layerExtent.hasTransformAnimation = isRunningTransformAnimation(layer.renderer());
884
885     bool respectTransforms = !layerExtent.hasTransformAnimation;
886     overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer, respectTransforms);
887
888     // If we know for sure the layer is going to be composited, don't bother looking it up in the overlap map
889     if (!willBeComposited && !layerPaintsIntoProvidedBacking && !overlapMap.isEmpty() && compositingState.testingOverlap) {
890         // If we're testing for overlap, we only need to composite if we overlap something that is already composited.
891         if (layerOverlaps(overlapMap, layer, layerExtent))
892             compositingReason = IndirectCompositingReason::Overlap;
893         else
894             compositingReason = IndirectCompositingReason::None;
895     }
896
897 #if ENABLE(VIDEO)
898     // Video is special. It's the only RenderLayer type that can both have
899     // RenderLayer children and whose children can't use its backing to render
900     // into. These children (the controls) always need to be promoted into their
901     // own layers to draw on top of the accelerated video.
902     if (compositingState.compositingAncestor && compositingState.compositingAncestor->renderer().isVideo())
903         compositingReason = IndirectCompositingReason::Overlap;
904 #endif
905
906     if (compositingReason != IndirectCompositingReason::None)
907         layer.setIndirectCompositingReason(compositingReason);
908
909     // Check if the computed indirect reason will force the layer to become composited.
910     if (!willBeComposited && layer.mustCompositeForIndirectReasons() && canBeComposited(layer)) {
911         LOG_WITH_STREAM(Compositing, stream << "layer " << &layer << " compositing for indirect reason " << layer.indirectCompositingReason() << " (was sharing: " << layerPaintsIntoProvidedBacking << ")");
912         willBeComposited = true;
913         layerPaintsIntoProvidedBacking = false;
914     }
915
916     // The children of this layer don't need to composite, unless there is
917     // a compositing layer among them, so start by inheriting the compositing
918     // ancestor with subtreeIsCompositing set to false.
919     CompositingState currentState = compositingState.stateForPaintOrderChildren(layer);
920     bool didPushOverlapContainer = false;
921
922     auto layerWillComposite = [&] {
923         // This layer is going to be composited, so children can safely ignore the fact that there's an
924         // animation running behind this layer, meaning they can rely on the overlap map testing again.
925         currentState.testingOverlap = true;
926         // This layer now acts as the ancestor for kids.
927         currentState.compositingAncestor = &layer;
928         // Compositing turns off backing sharing.
929         currentState.backingSharingAncestor = nullptr;
930
931         if (layerPaintsIntoProvidedBacking) {
932             layerPaintsIntoProvidedBacking = false;
933             // layerPaintsIntoProvidedBacking was only true for layers that would otherwise composite because of overlap. If we can
934             // no longer share, put this this indirect reason back on the layer so that requiresOwnBackingStore() sees it.
935             layer.setIndirectCompositingReason(IndirectCompositingReason::Overlap);
936             LOG_WITH_STREAM(Compositing, stream << "layer " << &layer << " was sharing now will composite");
937         } else {
938             overlapMap.pushCompositingContainer();
939             didPushOverlapContainer = true;
940             LOG_WITH_STREAM(CompositingOverlap, stream << "layer " << &layer << " will composite, pushed container " << overlapMap);
941         }
942
943         willBeComposited = true;
944     };
945
946     auto layerWillCompositePostDescendants = [&] {
947         layerWillComposite();
948         currentState.subtreeIsCompositing = true;
949         becameCompositedAfterDescendantTraversal = true;
950     };
951
952     if (willBeComposited) {
953         layerWillComposite();
954
955         computeExtent(overlapMap, layer, layerExtent);
956         currentState.ancestorHasTransformAnimation |= layerExtent.hasTransformAnimation;
957         // Too hard to compute animated bounds if both us and some ancestor is animating transform.
958         layerExtent.animationCausesExtentUncertainty |= layerExtent.hasTransformAnimation && compositingState.ancestorHasTransformAnimation;
959     } else if (layerPaintsIntoProvidedBacking) {
960         currentState.backingSharingAncestor = &layer;
961         overlapMap.pushCompositingContainer();
962         didPushOverlapContainer = true;
963         LOG_WITH_STREAM(CompositingOverlap, stream << "layer " << &layer << " will share, pushed container " << overlapMap);
964     }
965
966     backingSharingState.updateBeforeDescendantTraversal(layer, willBeComposited);
967
968 #if !ASSERT_DISABLED
969     LayerListMutationDetector mutationChecker(layer);
970 #endif
971
972     bool anyDescendantHas3DTransform = false;
973     bool descendantsAddedToOverlap = currentState.hasNonRootCompositedAncestor();
974
975     for (auto* childLayer : layer.negativeZOrderLayers()) {
976         computeCompositingRequirements(&layer, *childLayer, overlapMap, currentState, backingSharingState, anyDescendantHas3DTransform);
977
978         // If we have to make a layer for this child, make one now so we can have a contents layer
979         // (since we need to ensure that the -ve z-order child renders underneath our contents).
980         if (!willBeComposited && currentState.subtreeIsCompositing) {
981             layer.setIndirectCompositingReason(IndirectCompositingReason::BackgroundLayer);
982             layerWillComposite();
983         }
984     }
985
986     for (auto* childLayer : layer.normalFlowLayers())
987         computeCompositingRequirements(&layer, *childLayer, overlapMap, currentState, backingSharingState, anyDescendantHas3DTransform);
988
989     for (auto* childLayer : layer.positiveZOrderLayers())
990         computeCompositingRequirements(&layer, *childLayer, overlapMap, currentState, backingSharingState, anyDescendantHas3DTransform);
991
992     // Set the flag to say that this layer has compositing children.
993     layer.setHasCompositingDescendant(currentState.subtreeIsCompositing);
994
995     // If we just entered compositing mode, the root will have become composited (as long as accelerated compositing is enabled).
996     if (layer.isRenderViewLayer()) {
997         if (usesCompositing() && m_hasAcceleratedCompositing)
998             willBeComposited = true;
999     }
1000
1001 #if ENABLE(CSS_COMPOSITING)
1002     bool isolatedCompositedBlending = layer.isolatesCompositedBlending();
1003     layer.setHasNotIsolatedCompositedBlendingDescendants(currentState.hasNotIsolatedCompositedBlendingDescendants);
1004     if (layer.isolatesCompositedBlending() != isolatedCompositedBlending) {
1005         // isolatedCompositedBlending affects the result of clippedByAncestor().
1006         layer.setChildrenNeedCompositingGeometryUpdate();
1007     }
1008
1009     ASSERT(!layer.hasNotIsolatedCompositedBlendingDescendants() || layer.hasNotIsolatedBlendingDescendants());
1010 #endif
1011     // Now check for reasons to become composited that depend on the state of descendant layers.
1012     IndirectCompositingReason indirectCompositingReason;
1013     if (!willBeComposited && canBeComposited(layer)
1014         && requiresCompositingForIndirectReason(layer, currentState.subtreeIsCompositing, anyDescendantHas3DTransform, layerPaintsIntoProvidedBacking, indirectCompositingReason)) {
1015         layer.setIndirectCompositingReason(indirectCompositingReason);
1016         layerWillCompositePostDescendants();
1017     }
1018     
1019     if (layer.reflectionLayer()) {
1020         // FIXME: Shouldn't we call computeCompositingRequirements to handle a reflection overlapping with another renderer?
1021         layer.reflectionLayer()->setIndirectCompositingReason(willBeComposited ? IndirectCompositingReason::Stacking : IndirectCompositingReason::None);
1022     }
1023
1024     // setHasCompositingDescendant() may have changed the answer to needsToBeComposited() when clipping, so test that now.
1025     bool isCompositedClippingLayer = canBeComposited(layer) && clipsCompositingDescendants(layer);
1026     if (isCompositedClippingLayer & !willBeComposited)
1027         layerWillCompositePostDescendants();
1028
1029     // If we're back at the root, and no other layers need to be composited, and the root layer itself doesn't need
1030     // to be composited, then we can drop out of compositing mode altogether. However, don't drop out of compositing mode
1031     // if there are composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
1032     RequiresCompositingData rootLayerQueryData;
1033     if (layer.isRenderViewLayer() && !currentState.subtreeIsCompositing && !requiresCompositingLayer(layer, rootLayerQueryData) && !m_forceCompositingMode && !needsCompositingForContentOrOverlays()) {
1034         // Don't drop out of compositing on iOS, because we may flash. See <rdar://problem/8348337>.
1035 #if !PLATFORM(IOS_FAMILY)
1036         enableCompositingMode(false);
1037         willBeComposited = false;
1038 #endif
1039     }
1040
1041     ASSERT(willBeComposited == needsToBeComposited(layer, queryData));
1042
1043     // Create or destroy backing here. However, we can't update geometry because layers above us may become composited
1044     // during post-order traversal (e.g. for clipping).
1045     if (updateBacking(layer, queryData, CompositingChangeRepaintNow, willBeComposited ? BackingRequired::Yes : BackingRequired::No)) {
1046         layer.setNeedsCompositingLayerConnection();
1047         // Child layers need to get a geometry update to recompute their position.
1048         layer.setChildrenNeedCompositingGeometryUpdate();
1049         // The composited bounds of enclosing layers depends on which descendants are composited, so they need a geometry update.
1050         layer.setNeedsCompositingGeometryUpdateOnAncestors();
1051     }
1052
1053     // Update layer state bits.
1054     if (layer.reflectionLayer() && updateLayerCompositingState(*layer.reflectionLayer(), queryData, CompositingChangeRepaintNow))
1055         layer.setNeedsCompositingLayerConnection();
1056     
1057     // FIXME: clarify needsCompositingPaintOrderChildrenUpdate. If a composited layer gets a new ancestor, it needs geometry computations.
1058     if (layer.needsCompositingPaintOrderChildrenUpdate()) {
1059         layer.setChildrenNeedCompositingGeometryUpdate();
1060         layer.setNeedsCompositingLayerConnection();
1061     }
1062
1063     layer.clearCompositingRequirementsTraversalState();
1064
1065     // Compute state passed to the caller.
1066     descendantHas3DTransform |= anyDescendantHas3DTransform || layer.has3DTransform();
1067     compositingState.updateWithDescendantStateAndLayer(currentState, layer, layerExtent);
1068     backingSharingState.updateAfterDescendantTraversal(layer, compositingState.stackingContextAncestor);
1069
1070     bool layerContributesToOverlap = (currentState.compositingAncestor && !currentState.compositingAncestor->isRenderViewLayer()) || currentState.backingSharingAncestor;
1071     updateOverlapMap(overlapMap, layer, layerExtent, didPushOverlapContainer, layerContributesToOverlap, becameCompositedAfterDescendantTraversal && !descendantsAddedToOverlap);
1072
1073     if (layer.isComposited())
1074         layer.backing()->updateAllowsBackingStoreDetaching(layerExtent.bounds);
1075
1076     overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
1077
1078     LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(compositingState.depth * 2, ' ') << &layer << " computeCompositingRequirements - willBeComposited " << willBeComposited << " (backing provider candidate " << backingSharingState.backingProviderCandidate() << ")");
1079 }
1080
1081 // We have to traverse unchanged layers to fill in the overlap map.
1082 void RenderLayerCompositor::traverseUnchangedSubtree(RenderLayer* ancestorLayer, RenderLayer& layer, LayerOverlapMap& overlapMap, CompositingState& compositingState, BackingSharingState& backingSharingState, bool& descendantHas3DTransform)
1083 {
1084     ASSERT(!compositingState.fullPaintOrderTraversalRequired);
1085     ASSERT(!layer.hasDescendantNeedingCompositingRequirementsTraversal());
1086     ASSERT(!layer.needsCompositingRequirementsTraversal());
1087
1088     LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(compositingState.depth * 2, ' ') << &layer << (layer.isNormalFlowOnly() ? " n" : " s") << " traverseUnchangedSubtree");
1089
1090     layer.updateDescendantDependentFlags();
1091     layer.updateLayerListsIfNeeded();
1092
1093     bool layerIsComposited = layer.isComposited();
1094     bool layerPaintsIntoProvidedBacking = false;
1095     bool didPushOverlapContainer = false;
1096
1097     OverlapExtent layerExtent;
1098     if (layerIsComposited && !layer.isRenderViewLayer())
1099         layerExtent.hasTransformAnimation = isRunningTransformAnimation(layer.renderer());
1100
1101     bool respectTransforms = !layerExtent.hasTransformAnimation;
1102     overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer, respectTransforms);
1103
1104     // If we know for sure the layer is going to be composited, don't bother looking it up in the overlap map
1105     if (!layerIsComposited && !overlapMap.isEmpty() && compositingState.testingOverlap)
1106         computeExtent(overlapMap, layer, layerExtent);
1107
1108     if (layer.paintsIntoProvidedBacking()) {
1109         ASSERT(backingSharingState.backingProviderCandidate());
1110         ASSERT(backingProviderLayerCanIncludeLayer(*backingSharingState.backingProviderCandidate(), layer));
1111         backingSharingState.appendSharingLayer(layer);
1112         layerPaintsIntoProvidedBacking = true;
1113     }
1114
1115     CompositingState currentState = compositingState.stateForPaintOrderChildren(layer);
1116
1117     if (layerIsComposited) {
1118         // This layer is going to be composited, so children can safely ignore the fact that there's an
1119         // animation running behind this layer, meaning they can rely on the overlap map testing again.
1120         currentState.testingOverlap = true;
1121         // This layer now acts as the ancestor for kids.
1122         currentState.compositingAncestor = &layer;
1123         currentState.backingSharingAncestor = nullptr;
1124         overlapMap.pushCompositingContainer();
1125         didPushOverlapContainer = true;
1126         LOG_WITH_STREAM(CompositingOverlap, stream << "unchangedSubtree: layer " << &layer << " will composite, pushed container " << overlapMap);
1127
1128         computeExtent(overlapMap, layer, layerExtent);
1129         currentState.ancestorHasTransformAnimation |= layerExtent.hasTransformAnimation;
1130         // Too hard to compute animated bounds if both us and some ancestor is animating transform.
1131         layerExtent.animationCausesExtentUncertainty |= layerExtent.hasTransformAnimation && compositingState.ancestorHasTransformAnimation;
1132     } else if (layerPaintsIntoProvidedBacking) {
1133         overlapMap.pushCompositingContainer();
1134         currentState.backingSharingAncestor = &layer;
1135         didPushOverlapContainer = true;
1136         LOG_WITH_STREAM(CompositingOverlap, stream << "unchangedSubtree: layer " << &layer << " will share, pushed container " << overlapMap);
1137     }
1138
1139     backingSharingState.updateBeforeDescendantTraversal(layer, layerIsComposited);
1140
1141 #if !ASSERT_DISABLED
1142     LayerListMutationDetector mutationChecker(layer);
1143 #endif
1144
1145     bool anyDescendantHas3DTransform = false;
1146
1147     for (auto* childLayer : layer.negativeZOrderLayers()) {
1148         traverseUnchangedSubtree(&layer, *childLayer, overlapMap, currentState, backingSharingState, anyDescendantHas3DTransform);
1149         if (currentState.subtreeIsCompositing)
1150             ASSERT(layerIsComposited);
1151     }
1152
1153     for (auto* childLayer : layer.normalFlowLayers())
1154         traverseUnchangedSubtree(&layer, *childLayer, overlapMap, currentState, backingSharingState, anyDescendantHas3DTransform);
1155
1156     for (auto* childLayer : layer.positiveZOrderLayers())
1157         traverseUnchangedSubtree(&layer, *childLayer, overlapMap, currentState, backingSharingState, anyDescendantHas3DTransform);
1158
1159     // Set the flag to say that this layer has compositing children.
1160     ASSERT(layer.hasCompositingDescendant() == currentState.subtreeIsCompositing);
1161     ASSERT_IMPLIES(canBeComposited(layer) && clipsCompositingDescendants(layer), layerIsComposited);
1162
1163     descendantHas3DTransform |= anyDescendantHas3DTransform || layer.has3DTransform();
1164
1165     ASSERT(!currentState.fullPaintOrderTraversalRequired);
1166     compositingState.updateWithDescendantStateAndLayer(currentState, layer, layerExtent, true);
1167     backingSharingState.updateAfterDescendantTraversal(layer, compositingState.stackingContextAncestor);
1168
1169     bool layerContributesToOverlap = (currentState.compositingAncestor && !currentState.compositingAncestor->isRenderViewLayer()) || currentState.backingSharingAncestor;
1170     updateOverlapMap(overlapMap, layer, layerExtent, didPushOverlapContainer, layerContributesToOverlap);
1171
1172     overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
1173
1174     ASSERT(!layer.needsCompositingRequirementsTraversal());
1175 }
1176
1177 void RenderLayerCompositor::updateBackingAndHierarchy(RenderLayer& layer, Vector<Ref<GraphicsLayer>>& childLayersOfEnclosingLayer, ScrollingTreeState& scrollingTreeState, OptionSet<UpdateLevel> updateLevel, int depth)
1178 {
1179     layer.updateDescendantDependentFlags();
1180     layer.updateLayerListsIfNeeded();
1181
1182     bool layerNeedsUpdate = !updateLevel.isEmpty();
1183     if (layer.descendantsNeedUpdateBackingAndHierarchyTraversal())
1184         updateLevel.add(UpdateLevel::AllDescendants);
1185
1186     ScrollingTreeState stateForDescendants = scrollingTreeState;
1187
1188     auto* layerBacking = layer.backing();
1189     if (layerBacking) {
1190         updateLevel.remove(UpdateLevel::CompositedChildren);
1191
1192         // We updated the composited bounds in RenderLayerBacking::updateAfterLayout(), but it may have changed
1193         // based on which descendants are now composited.
1194         if (layerBacking->updateCompositedBounds()) {
1195             layer.setNeedsCompositingGeometryUpdate();
1196             // Our geometry can affect descendants.
1197             updateLevel.add(UpdateLevel::CompositedChildren);
1198         }
1199         
1200         if (layerNeedsUpdate || layer.needsCompositingConfigurationUpdate()) {
1201             if (layerBacking->updateConfiguration()) {
1202                 layerNeedsUpdate = true; // We also need to update geometry.
1203                 layer.setNeedsCompositingLayerConnection();
1204             }
1205
1206             layerBacking->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
1207         }
1208         
1209         OptionSet<ScrollingNodeChangeFlags> scrollingNodeChanges = { ScrollingNodeChangeFlags::Layer };
1210         if (layerNeedsUpdate || layer.needsCompositingGeometryUpdate()) {
1211             layerBacking->updateGeometry();
1212             scrollingNodeChanges.add(ScrollingNodeChangeFlags::LayerGeometry);
1213         } else if (layer.needsScrollingTreeUpdate())
1214             scrollingNodeChanges.add(ScrollingNodeChangeFlags::LayerGeometry);
1215
1216         // This needs to happen after any geometry update.
1217         // FIXME: Use separate bit for event region invalidation.
1218         if (layerNeedsUpdate || layer.needsCompositingConfigurationUpdate())
1219             layerBacking->updateEventRegion();
1220
1221         if (auto* reflection = layer.reflectionLayer()) {
1222             if (auto* reflectionBacking = reflection->backing()) {
1223                 reflectionBacking->updateCompositedBounds();
1224                 reflectionBacking->updateGeometry();
1225                 reflectionBacking->updateAfterDescendants();
1226             }
1227         }
1228
1229         if (!layer.parent())
1230             updateRootLayerPosition();
1231
1232         // FIXME: do based on dirty flags. Need to do this for changes of geometry, configuration and hierarchy.
1233         // Need to be careful to do the right thing when a scroll-coordinated layer loses a scroll-coordinated ancestor.
1234         stateForDescendants.parentNodeID = updateScrollCoordinationForLayer(layer, scrollingTreeState, scrollingNodeChanges);
1235         stateForDescendants.nextChildIndex = 0;
1236
1237 #if !LOG_DISABLED
1238         logLayerInfo(layer, "updateBackingAndHierarchy", depth);
1239 #else
1240         UNUSED_PARAM(depth);
1241 #endif
1242     }
1243
1244     if (layer.childrenNeedCompositingGeometryUpdate())
1245         updateLevel.add(UpdateLevel::CompositedChildren);
1246
1247     // If this layer has backing, then we are collecting its children, otherwise appending
1248     // to the compositing child list of an enclosing layer.
1249     Vector<Ref<GraphicsLayer>> layerChildren;
1250     auto& childList = layerBacking ? layerChildren : childLayersOfEnclosingLayer;
1251
1252     bool requireDescendantTraversal = layer.hasDescendantNeedingUpdateBackingOrHierarchyTraversal()
1253         || (layer.hasCompositingDescendant() && (!layerBacking || layer.needsCompositingLayerConnection() || !updateLevel.isEmpty()));
1254
1255     bool requiresChildRebuild = layerBacking && layer.needsCompositingLayerConnection() && !layer.hasCompositingDescendant();
1256
1257 #if !ASSERT_DISABLED
1258     LayerListMutationDetector mutationChecker(layer);
1259 #endif
1260
1261     auto appendForegroundLayerIfNecessary = [&] {
1262         // If a negative z-order child is compositing, we get a foreground layer which needs to get parented.
1263         if (layer.negativeZOrderLayers().size()) {
1264             if (layerBacking && layerBacking->foregroundLayer())
1265                 childList.append(*layerBacking->foregroundLayer());
1266         }
1267     };
1268
1269     if (requireDescendantTraversal) {
1270         for (auto* renderLayer : layer.negativeZOrderLayers())
1271             updateBackingAndHierarchy(*renderLayer, childList, stateForDescendants, updateLevel, depth + 1);
1272
1273         appendForegroundLayerIfNecessary();
1274
1275         for (auto* renderLayer : layer.normalFlowLayers())
1276             updateBackingAndHierarchy(*renderLayer, childList, stateForDescendants, updateLevel, depth + 1);
1277         
1278         for (auto* renderLayer : layer.positiveZOrderLayers())
1279             updateBackingAndHierarchy(*renderLayer, childList, stateForDescendants, updateLevel, depth + 1);
1280     } else if (requiresChildRebuild)
1281         appendForegroundLayerIfNecessary();
1282
1283     if (layerBacking) {
1284         if (requireDescendantTraversal || requiresChildRebuild) {
1285             bool parented = false;
1286             if (is<RenderWidget>(layer.renderer()))
1287                 parented = parentFrameContentLayers(downcast<RenderWidget>(layer.renderer()));
1288
1289             if (!parented)
1290                 layerBacking->parentForSublayers()->setChildren(WTFMove(layerChildren));
1291
1292             // If the layer has a clipping layer the overflow controls layers will be siblings of the clipping layer.
1293             // Otherwise, the overflow control layers are normal children.
1294             if (!layerBacking->hasClippingLayer() && !layerBacking->hasScrollingLayer()) {
1295                 if (auto* overflowControlLayer = layerBacking->layerForHorizontalScrollbar())
1296                     layerBacking->parentForSublayers()->addChild(*overflowControlLayer);
1297
1298                 if (auto* overflowControlLayer = layerBacking->layerForVerticalScrollbar())
1299                     layerBacking->parentForSublayers()->addChild(*overflowControlLayer);
1300
1301                 if (auto* overflowControlLayer = layerBacking->layerForScrollCorner())
1302                     layerBacking->parentForSublayers()->addChild(*overflowControlLayer);
1303             }
1304         }
1305
1306         childLayersOfEnclosingLayer.append(*layerBacking->childForSuperlayers());
1307
1308         layerBacking->updateAfterDescendants();
1309     }
1310     
1311     layer.clearUpdateBackingOrHierarchyTraversalState();
1312 }
1313
1314 void RenderLayerCompositor::appendDocumentOverlayLayers(Vector<Ref<GraphicsLayer>>& childList)
1315 {
1316     if (!isMainFrameCompositor() || !m_compositing)
1317         return;
1318
1319     if (!page().pageOverlayController().hasDocumentOverlays())
1320         return;
1321
1322     Ref<GraphicsLayer> overlayHost = page().pageOverlayController().layerWithDocumentOverlays();
1323     childList.append(WTFMove(overlayHost));
1324 }
1325
1326 bool RenderLayerCompositor::needsCompositingForContentOrOverlays() const
1327 {
1328     return m_contentLayersCount + page().pageOverlayController().overlayCount();
1329 }
1330
1331 void RenderLayerCompositor::layerBecameComposited(const RenderLayer& layer)
1332 {
1333     if (&layer != m_renderView.layer())
1334         ++m_contentLayersCount;
1335 }
1336
1337 void RenderLayerCompositor::layerBecameNonComposited(const RenderLayer& layer)
1338 {
1339     // Inform the inspector that the given RenderLayer was destroyed.
1340     // FIXME: "destroyed" is a misnomer.
1341     InspectorInstrumentation::renderLayerDestroyed(&page(), layer);
1342
1343     if (&layer != m_renderView.layer()) {
1344         ASSERT(m_contentLayersCount > 0);
1345         --m_contentLayersCount;
1346     }
1347 }
1348
1349 #if !LOG_DISABLED
1350 void RenderLayerCompositor::logLayerInfo(const RenderLayer& layer, const char* phase, int depth)
1351 {
1352     if (!compositingLogEnabled())
1353         return;
1354
1355     auto* backing = layer.backing();
1356     RequiresCompositingData queryData;
1357     if (requiresCompositingLayer(layer, queryData) || layer.isRenderViewLayer()) {
1358         ++m_obligateCompositedLayerCount;
1359         m_obligatoryBackingStoreBytes += backing->backingStoreMemoryEstimate();
1360     } else {
1361         ++m_secondaryCompositedLayerCount;
1362         m_secondaryBackingStoreBytes += backing->backingStoreMemoryEstimate();
1363     }
1364
1365     LayoutRect absoluteBounds = backing->compositedBounds();
1366     absoluteBounds.move(layer.offsetFromAncestor(m_renderView.layer()));
1367     
1368     StringBuilder logString;
1369     logString.append(makeString(pad(' ', 12 + depth * 2, hex(reinterpret_cast<uintptr_t>(&layer))), " id ", backing->graphicsLayer()->primaryLayerID(), " (", FormattedNumber::fixedWidth(absoluteBounds.x().toFloat(), 3), ',', FormattedNumber::fixedWidth(absoluteBounds.y().toFloat(), 3), '-', FormattedNumber::fixedWidth(absoluteBounds.maxX().toFloat(), 3), ',', FormattedNumber::fixedWidth(absoluteBounds.maxY().toFloat(), 3), ") ", FormattedNumber::fixedWidth(backing->backingStoreMemoryEstimate() / 1024, 2), "KB"));
1370
1371     if (!layer.renderer().style().hasAutoZIndex())
1372         logString.append(makeString(" z-index: ", layer.renderer().style().zIndex()));
1373
1374     logString.appendLiteral(" (");
1375     logString.append(logReasonsForCompositing(layer));
1376     logString.appendLiteral(") ");
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 // Return true if the given layer is a stacking context and has compositing child
2712 // layers that it needs to clip. In this case we insert a clipping GraphicsLayer
2713 // into the hierarchy between this layer and its children in the z-order hierarchy.
2714 bool RenderLayerCompositor::clipsCompositingDescendants(const RenderLayer& layer)
2715 {
2716     return layer.hasCompositingDescendant() && layer.renderer().hasClipOrOverflowClip() && !layer.isolatesCompositedBlending();
2717 }
2718
2719 bool RenderLayerCompositor::requiresCompositingForAnimation(RenderLayerModelObject& renderer) const
2720 {
2721     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
2722         return false;
2723
2724     if (auto* element = renderer.element()) {
2725         if (auto* timeline = element->document().existingTimeline()) {
2726             if (timeline->runningAnimationsForElementAreAllAccelerated(*element))
2727                 return true;
2728         }
2729     }
2730
2731     if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled())
2732         return false;
2733
2734     auto& animController = renderer.animation();
2735     return (animController.isRunningAnimationOnRenderer(renderer, CSSPropertyOpacity)
2736         && (usesCompositing() || (m_compositingTriggers & ChromeClient::AnimatedOpacityTrigger)))
2737         || animController.isRunningAnimationOnRenderer(renderer, CSSPropertyFilter)
2738 #if ENABLE(FILTERS_LEVEL_2)
2739         || animController.isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitBackdropFilter)
2740 #endif
2741         || animController.isRunningAnimationOnRenderer(renderer, CSSPropertyTransform);
2742 }
2743
2744 bool RenderLayerCompositor::requiresCompositingForTransform(RenderLayerModelObject& renderer) const
2745 {
2746     if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
2747         return false;
2748
2749     // Note that we ask the renderer if it has a transform, because the style may have transforms,
2750     // but the renderer may be an inline that doesn't suppport them.
2751     if (!renderer.hasTransform())
2752         return false;
2753     
2754     switch (m_compositingPolicy) {
2755     case CompositingPolicy::Normal:
2756         return renderer.style().transform().has3DOperation();
2757     case CompositingPolicy::Conservative:
2758         // Continue to allow pages to avoid the very slow software filter path.
2759         if (renderer.style().transform().has3DOperation() && renderer.hasFilter())
2760             return true;
2761         return renderer.style().transform().isRepresentableIn2D() ? false : true;
2762     }
2763     return false;
2764 }
2765
2766 bool RenderLayerCompositor::requiresCompositingForBackfaceVisibility(RenderLayerModelObject& renderer) const
2767 {
2768     if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
2769         return false;
2770
2771     if (renderer.style().backfaceVisibility() != BackfaceVisibility::Hidden)
2772         return false;
2773
2774     if (renderer.layer()->has3DTransformedAncestor())
2775         return true;
2776     
2777     // FIXME: workaround for webkit.org/b/132801
2778     auto* stackingContext = renderer.layer()->stackingContext();
2779     if (stackingContext && stackingContext->renderer().style().transformStyle3D() == TransformStyle3D::Preserve3D)
2780         return true;
2781
2782     return false;
2783 }
2784
2785 bool RenderLayerCompositor::requiresCompositingForVideo(RenderLayerModelObject& renderer) const
2786 {
2787     if (!(m_compositingTriggers & ChromeClient::VideoTrigger))
2788         return false;
2789
2790 #if ENABLE(VIDEO)
2791     if (!is<RenderVideo>(renderer))
2792         return false;
2793
2794     auto& video = downcast<RenderVideo>(renderer);
2795     if ((video.requiresImmediateCompositing() || video.shouldDisplayVideo()) && canAccelerateVideoRendering(video))
2796         return true;
2797 #else
2798     UNUSED_PARAM(renderer);
2799 #endif
2800     return false;
2801 }
2802
2803 bool RenderLayerCompositor::requiresCompositingForCanvas(RenderLayerModelObject& renderer) const
2804 {
2805     if (!(m_compositingTriggers & ChromeClient::CanvasTrigger))
2806         return false;
2807
2808     if (!renderer.isCanvas())
2809         return false;
2810
2811     bool isCanvasLargeEnoughToForceCompositing = true;
2812 #if !USE(COMPOSITING_FOR_SMALL_CANVASES)
2813     auto* canvas = downcast<HTMLCanvasElement>(renderer.element());
2814     auto canvasArea = canvas->size().area<RecordOverflow>();
2815     isCanvasLargeEnoughToForceCompositing = !canvasArea.hasOverflowed() && canvasArea.unsafeGet() >= canvasAreaThresholdRequiringCompositing;
2816 #endif
2817
2818     CanvasCompositingStrategy compositingStrategy = canvasCompositingStrategy(renderer);
2819     if (compositingStrategy == CanvasAsLayerContents)
2820         return true;
2821
2822     if (m_compositingPolicy == CompositingPolicy::Normal)
2823         return compositingStrategy == CanvasPaintedToLayer && isCanvasLargeEnoughToForceCompositing;
2824
2825     return false;
2826 }
2827
2828 bool RenderLayerCompositor::requiresCompositingForFilters(RenderLayerModelObject& renderer) const
2829 {
2830 #if ENABLE(FILTERS_LEVEL_2)
2831     if (renderer.hasBackdropFilter())
2832         return true;
2833 #endif
2834
2835     if (!(m_compositingTriggers & ChromeClient::FilterTrigger))
2836         return false;
2837
2838     return renderer.hasFilter();
2839 }
2840
2841 bool RenderLayerCompositor::requiresCompositingForWillChange(RenderLayerModelObject& renderer) const
2842 {
2843     if (!renderer.style().willChange() || !renderer.style().willChange()->canTriggerCompositing())
2844         return false;
2845
2846 #if ENABLE(FULLSCREEN_API)
2847     // FIXME: does this require layout?
2848     if (renderer.layer() && isDescendantOfFullScreenLayer(*renderer.layer()) == FullScreenDescendant::No)
2849         return false;
2850 #endif
2851
2852     if (m_compositingPolicy == CompositingPolicy::Conservative)
2853         return false;
2854
2855     if (is<RenderBox>(renderer))
2856         return true;
2857
2858     return renderer.style().willChange()->canTriggerCompositingOnInline();
2859 }
2860
2861 bool RenderLayerCompositor::requiresCompositingForPlugin(RenderLayerModelObject& renderer, RequiresCompositingData& queryData) const
2862 {
2863     if (!(m_compositingTriggers & ChromeClient::PluginTrigger))
2864         return false;
2865
2866     bool isCompositedPlugin = is<RenderEmbeddedObject>(renderer) && downcast<RenderEmbeddedObject>(renderer).allowsAcceleratedCompositing();
2867     if (!isCompositedPlugin)
2868         return false;
2869
2870     auto& pluginRenderer = downcast<RenderWidget>(renderer);
2871     if (pluginRenderer.style().visibility() != Visibility::Visible)
2872         return false;
2873
2874     // If we can't reliably know the size of the plugin yet, don't change compositing state.
2875     if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2876         queryData.reevaluateAfterLayout = true;
2877         return pluginRenderer.isComposited();
2878     }
2879
2880     // Don't go into compositing mode if height or width are zero, or size is 1x1.
2881     IntRect contentBox = snappedIntRect(pluginRenderer.contentBoxRect());
2882     return (contentBox.height() * contentBox.width() > 1);
2883 }
2884     
2885 bool RenderLayerCompositor::requiresCompositingForEditableImage(RenderLayerModelObject& renderer) const
2886 {
2887     if (!renderer.isRenderImage())
2888         return false;
2889
2890     auto& image = downcast<RenderImage>(renderer);
2891     if (!image.isEditableImage())
2892         return false;
2893
2894     return true;
2895 }
2896
2897 bool RenderLayerCompositor::requiresCompositingForFrame(RenderLayerModelObject& renderer, RequiresCompositingData& queryData) const
2898 {
2899     if (!is<RenderWidget>(renderer))
2900         return false;
2901
2902     auto& frameRenderer = downcast<RenderWidget>(renderer);
2903     if (frameRenderer.style().visibility() != Visibility::Visible)
2904         return false;
2905
2906     if (!frameRenderer.requiresAcceleratedCompositing())
2907         return false;
2908
2909     if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2910         queryData.reevaluateAfterLayout = true;
2911         return frameRenderer.isComposited();
2912     }
2913
2914     // Don't go into compositing mode if height or width are zero.
2915     return !snappedIntRect(frameRenderer.contentBoxRect()).isEmpty();
2916 }
2917
2918 bool RenderLayerCompositor::requiresCompositingForScrollableFrame(RequiresCompositingData& queryData) const
2919 {
2920     if (isMainFrameCompositor())
2921         return false;
2922
2923 #if PLATFORM(MAC) || PLATFORM(IOS_FAMILY)
2924     if (!m_renderView.settings().asyncFrameScrollingEnabled())
2925         return false;
2926 #endif
2927
2928     if (!(m_compositingTriggers & ChromeClient::ScrollableNonMainFrameTrigger))
2929         return false;
2930
2931     if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2932         queryData.reevaluateAfterLayout = true;
2933         return m_renderView.isComposited();
2934     }
2935
2936     return m_renderView.frameView().isScrollable();
2937 }
2938
2939 bool RenderLayerCompositor::requiresCompositingForPosition(RenderLayerModelObject& renderer, const RenderLayer& layer, RequiresCompositingData& queryData) const
2940 {
2941     // position:fixed elements that create their own stacking context (e.g. have an explicit z-index,
2942     // opacity, transform) can get their own composited layer. A stacking context is required otherwise
2943     // z-index and clipping will be broken.
2944     if (!renderer.isPositioned())
2945         return false;
2946     
2947 #if ENABLE(FULLSCREEN_API)
2948     if (isDescendantOfFullScreenLayer(layer) == FullScreenDescendant::No)
2949         return false;
2950 #endif
2951
2952     auto position = renderer.style().position();
2953     bool isFixed = renderer.isFixedPositioned();
2954     if (isFixed && !layer.isStackingContext())
2955         return false;
2956     
2957     bool isSticky = renderer.isInFlowPositioned() && position == PositionType::Sticky;
2958     if (!isFixed && !isSticky)
2959         return false;
2960
2961     // FIXME: acceleratedCompositingForFixedPositionEnabled should probably be renamed acceleratedCompositingForViewportConstrainedPositionEnabled().
2962     if (!m_renderView.settings().acceleratedCompositingForFixedPositionEnabled())
2963         return false;
2964
2965     if (isSticky)
2966         return isAsyncScrollableStickyLayer(layer);
2967
2968     if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2969         queryData.reevaluateAfterLayout = true;
2970         return layer.isComposited();
2971     }
2972
2973     auto container = renderer.container();
2974     ASSERT(container);
2975
2976     // Don't promote fixed position elements that are descendants of a non-view container, e.g. transformed elements.
2977     // They will stay fixed wrt the container rather than the enclosing frame.
2978     if (container != &m_renderView) {
2979         queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForNonViewContainer;
2980         return false;
2981     }
2982
2983     bool paintsContent = layer.isVisuallyNonEmpty() || layer.hasVisibleDescendant();
2984     if (!paintsContent) {
2985         queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForNoVisibleContent;
2986         return false;
2987     }
2988
2989     bool intersectsViewport = fixedLayerIntersectsViewport(layer);
2990     if (!intersectsViewport) {
2991         queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForBoundsOutOfView;
2992         LOG_WITH_STREAM(Compositing, stream << "Layer " << &layer << " is outside the viewport");
2993         return false;
2994     }
2995
2996     return true;
2997 }
2998
2999 bool RenderLayerCompositor::requiresCompositingForOverflowScrolling(const RenderLayer& layer, RequiresCompositingData& queryData) const
3000 {
3001     if (!layer.canUseCompositedScrolling())
3002         return false;
3003
3004     if (queryData.layoutUpToDate == LayoutUpToDate::No) {
3005         queryData.reevaluateAfterLayout = true;
3006         return layer.isComposited();
3007     }
3008
3009     return layer.hasCompositedScrollableOverflow();
3010 }
3011
3012 // FIXME: why doesn't this handle the clipping cases?
3013 bool RenderLayerCompositor::requiresCompositingForIndirectReason(const RenderLayer& layer, bool hasCompositedDescendants, bool has3DTransformedDescendants, bool paintsIntoProvidedBacking, IndirectCompositingReason& reason) const
3014 {
3015     // When a layer has composited descendants, some effects, like 2d transforms, filters, masks etc must be implemented
3016     // via compositing so that they also apply to those composited descendants.
3017     auto& renderer = layer.renderer();
3018     if (hasCompositedDescendants && (layer.isolatesCompositedBlending() || layer.transform() || renderer.createsGroup() || renderer.hasReflection())) {
3019         reason = IndirectCompositingReason::GraphicalEffect;
3020         return true;
3021     }
3022
3023     // A layer with preserve-3d or perspective only needs to be composited if there are descendant layers that
3024     // will be affected by the preserve-3d or perspective.
3025     if (has3DTransformedDescendants) {
3026         if (renderer.style().transformStyle3D() == TransformStyle3D::Preserve3D) {
3027             reason = IndirectCompositingReason::Preserve3D;
3028             return true;
3029         }
3030     
3031         if (renderer.style().hasPerspective()) {
3032             reason = IndirectCompositingReason::Perspective;
3033             return true;
3034         }
3035     }
3036
3037     // If this layer scrolls independently from the layer that it would paint into, it needs to get composited.
3038     if (!paintsIntoProvidedBacking && layer.hasCompositedScrollingAncestor()) {
3039         auto* paintDestination = layer.paintOrderParent();
3040         if (paintDestination && layerScrollBehahaviorRelativeToCompositedAncestor(layer, *paintDestination) != ScrollPositioningBehavior::None) {
3041             reason = IndirectCompositingReason::OverflowScrollPositioning;
3042             return true;
3043         }
3044     }
3045
3046     reason = IndirectCompositingReason::None;
3047     return false;
3048 }
3049
3050 bool RenderLayerCompositor::styleChangeMayAffectIndirectCompositingReasons(const RenderStyle& oldStyle, const RenderStyle& newStyle)
3051 {
3052     if (RenderElement::createsGroupForStyle(newStyle) != RenderElement::createsGroupForStyle(oldStyle))
3053         return true;
3054     if (newStyle.isolation() != oldStyle.isolation())
3055         return true;
3056     if (newStyle.hasTransform() != oldStyle.hasTransform())
3057         return true;
3058     if (newStyle.boxReflect() != oldStyle.boxReflect())
3059         return true;
3060     if (newStyle.transformStyle3D() != oldStyle.transformStyle3D())
3061         return true;
3062     if (newStyle.hasPerspective() != oldStyle.hasPerspective())
3063         return true;
3064
3065     return false;
3066 }
3067
3068 bool RenderLayerCompositor::isAsyncScrollableStickyLayer(const RenderLayer& layer, const RenderLayer** enclosingAcceleratedOverflowLayer) const
3069 {
3070     ASSERT(layer.renderer().isStickilyPositioned());
3071
3072     auto* enclosingOverflowLayer = layer.enclosingOverflowClipLayer(ExcludeSelf);
3073
3074     if (enclosingOverflowLayer && enclosingOverflowLayer->hasCompositedScrollableOverflow()) {
3075         if (enclosingAcceleratedOverflowLayer)
3076             *enclosingAcceleratedOverflowLayer = enclosingOverflowLayer;
3077         return true;
3078     }
3079
3080     // If the layer is inside normal overflow, it's not async-scrollable.
3081     if (enclosingOverflowLayer)
3082         return false;
3083
3084     // No overflow ancestor, so see if the frame supports async scrolling.
3085     if (hasCoordinatedScrolling())
3086         return true;
3087
3088 #if PLATFORM(IOS_FAMILY)
3089     // iOS WK1 has fixed/sticky support in the main frame via WebFixedPositionContent.
3090     return isMainFrameCompositor();
3091 #else
3092     return false;
3093 #endif
3094 }
3095
3096 bool RenderLayerCompositor::isViewportConstrainedFixedOrStickyLayer(const RenderLayer& layer) const
3097 {
3098     if (layer.renderer().isStickilyPositioned())
3099         return isAsyncScrollableStickyLayer(layer);
3100
3101     if (!layer.renderer().isFixedPositioned())
3102         return false;
3103
3104     // FIXME: Handle fixed inside of a transform, which should not behave as fixed.
3105     for (auto* ancestor = layer.parent(); ancestor; ancestor = ancestor->parent()) {
3106         if (ancestor->hasCompositedScrollableOverflow())
3107             return true;
3108         if (ancestor->isStackingContext() && ancestor->isComposited() && ancestor->renderer().isFixedPositioned())
3109             return false;
3110     }
3111
3112     return true;
3113 }
3114
3115 bool RenderLayerCompositor::fixedLayerIntersectsViewport(const RenderLayer& layer) const
3116 {
3117     ASSERT(layer.renderer().isFixedPositioned());
3118
3119     // Fixed position elements that are invisible in the current view don't get their own layer.
3120     // FIXME: We shouldn't have to check useFixedLayout() here; one of the viewport rects needs to give the correct answer.
3121     LayoutRect viewBounds;
3122     if (m_renderView.frameView().useFixedLayout())
3123         viewBounds = m_renderView.unscaledDocumentRect();
3124     else
3125         viewBounds = m_renderView.frameView().rectForFixedPositionLayout();
3126
3127     LayoutRect layerBounds = layer.calculateLayerBounds(&layer, LayoutSize(), { RenderLayer::UseLocalClipRectIfPossible, RenderLayer::IncludeFilterOutsets, RenderLayer::UseFragmentBoxesExcludingCompositing,
3128         RenderLayer::ExcludeHiddenDescendants, RenderLayer::DontConstrainForMask, RenderLayer::IncludeCompositedDescendants });
3129     // Map to m_renderView to ignore page scale.
3130     FloatRect absoluteBounds = layer.renderer().localToContainerQuad(FloatRect(layerBounds), &m_renderView).boundingBox();
3131     return viewBounds.intersects(enclosingIntRect(absoluteBounds));
3132 }
3133
3134 bool RenderLayerCompositor::useCoordinatedScrollingForLayer(const RenderLayer& layer) const
3135 {
3136     if (layer.isRenderViewLayer() && hasCoordinatedScrolling())
3137         return true;
3138
3139     if (auto* scrollingCoordinator = this->scrollingCoordinator())
3140         return scrollingCoordinator->coordinatesScrollingForOverflowLayer(layer);
3141
3142     return false;
3143 }
3144
3145 static bool isScrolledByOverflowScrollLayer(const RenderLayer& layer, const RenderLayer& overflowScrollLayer)
3146 {
3147     bool scrolledByOverflowScroll = false;
3148     traverseAncestorLayers(layer, [&](const RenderLayer& ancestorLayer, bool inContainingBlockChain, bool) {
3149         if (&ancestorLayer == &overflowScrollLayer) {
3150             scrolledByOverflowScroll = inContainingBlockChain;
3151             return AncestorTraversal::Stop;
3152         }
3153         return AncestorTraversal::Continue;
3154     });
3155     return scrolledByOverflowScroll;
3156 }
3157
3158 static RenderLayer* enclosingCompositedScrollingLayer(const RenderLayer& layer, const RenderLayer& intermediateLayer, bool& sawIntermediateLayer)
3159 {
3160     const auto* ancestorLayer = layer.parent();
3161     while (ancestorLayer) {
3162         if (ancestorLayer == &intermediateLayer)
3163             sawIntermediateLayer = true;
3164
3165         if (ancestorLayer->hasCompositedScrollableOverflow())
3166             return const_cast<RenderLayer*>(ancestorLayer);
3167
3168         ancestorLayer = ancestorLayer->parent();
3169     }
3170
3171     return nullptr;
3172 }
3173
3174 ScrollPositioningBehavior RenderLayerCompositor::layerScrollBehahaviorRelativeToCompositedAncestor(const RenderLayer& layer, const RenderLayer& compositedAncestor)
3175 {
3176     if (!layer.hasCompositedScrollingAncestor())
3177         return ScrollPositioningBehavior::None;
3178
3179     bool compositedAncestorIsInsideScroller = false;
3180     auto* scrollingAncestor = enclosingCompositedScrollingLayer(layer, compositedAncestor, compositedAncestorIsInsideScroller);
3181     if (!scrollingAncestor) {
3182         ASSERT_NOT_REACHED(); // layer.hasCompositedScrollingAncestor() should guarantee we have one.
3183         return ScrollPositioningBehavior::None;
3184     }
3185     
3186     bool ancestorMovedByScroller = &compositedAncestor == scrollingAncestor || (compositedAncestorIsInsideScroller && isScrolledByOverflowScrollLayer(compositedAncestor, *scrollingAncestor));
3187     bool layerMovedByScroller = isScrolledByOverflowScrollLayer(layer, *scrollingAncestor);
3188
3189     if (ancestorMovedByScroller == layerMovedByScroller)
3190         return ScrollPositioningBehavior::None;
3191
3192     return layerMovedByScroller ? ScrollPositioningBehavior::Moves : ScrollPositioningBehavior::Stationary;
3193 }
3194
3195 static void collectStationaryLayerRelatedOverflowNodes(const RenderLayer& layer, const RenderLayer&, Vector<ScrollingNodeID>& scrollingNodes)
3196 {
3197     ASSERT(layer.isComposited());
3198     
3199     auto appendOverflowLayerNodeID = [&scrollingNodes] (const RenderLayer& overflowLayer) {
3200         ASSERT(overflowLayer.isComposited());
3201         auto scrollingNodeID = overflowLayer.backing()->scrollingNodeIDForRole(ScrollCoordinationRole::Scrolling);
3202         if (scrollingNodeID)
3203             scrollingNodes.append(scrollingNodeID);
3204         else
3205             LOG(Scrolling, "Layer %p doesn't have scrolling node ID yet", &overflowLayer);
3206     };
3207
3208     // 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).
3209     bool seenPaintOrderAncestor = false;
3210     traverseAncestorLayers(layer, [&](const RenderLayer& ancestorLayer, bool isContainingBlockChain, bool isPaintOrderAncestor) {
3211         seenPaintOrderAncestor |= isPaintOrderAncestor;
3212         if (isContainingBlockChain && isPaintOrderAncestor)
3213             return AncestorTraversal::Stop;
3214
3215         if (seenPaintOrderAncestor && !isContainingBlockChain && ancestorLayer.hasCompositedScrollableOverflow())
3216             appendOverflowLayerNodeID(ancestorLayer);
3217
3218         return AncestorTraversal::Continue;
3219     });
3220 }
3221
3222 ScrollPositioningBehavior RenderLayerCompositor::computeCoordinatedPositioningForLayer(const RenderLayer& layer) const
3223 {
3224     if (layer.isRenderViewLayer())
3225         return ScrollPositioningBehavior::None;
3226
3227     if (layer.renderer().isFixedPositioned())
3228         return ScrollPositioningBehavior::None;
3229     
3230     if (!layer.hasCompositedScrollingAncestor())
3231         return ScrollPositioningBehavior::None;
3232
3233     auto* scrollingCoordinator = this->scrollingCoordinator();
3234     if (!scrollingCoordinator)
3235         return ScrollPositioningBehavior::None;
3236
3237     auto* compositedAncestor = layer.ancestorCompositingLayer();
3238     if (!compositedAncestor) {
3239         ASSERT_NOT_REACHED();
3240         return ScrollPositioningBehavior::None;
3241     }
3242
3243     return layerScrollBehahaviorRelativeToCompositedAncestor(layer, *compositedAncestor);
3244 }
3245
3246 static Vector<ScrollingNodeID> collectRelatedCoordinatedScrollingNodes(const RenderLayer& layer, ScrollPositioningBehavior positioningBehavior)
3247 {
3248     Vector<ScrollingNodeID> overflowNodeIDs;
3249
3250     switch (positioningBehavior) {
3251     case ScrollPositioningBehavior::Stationary: {
3252         auto* compositedAncestor = layer.ancestorCompositingLayer();
3253         if (!compositedAncestor)
3254             return overflowNodeIDs;
3255         collectStationaryLayerRelatedOverflowNodes(layer, *compositedAncestor, overflowNodeIDs);
3256         break;
3257     }
3258     case ScrollPositioningBehavior::Moves:
3259     case ScrollPositioningBehavior::None:
3260         ASSERT_NOT_REACHED();
3261         break;
3262     }
3263
3264     return overflowNodeIDs;
3265 }
3266
3267 bool RenderLayerCompositor::isLayerForIFrameWithScrollCoordinatedContents(const RenderLayer& layer) const
3268 {
3269     if (!is<RenderWidget>(layer.renderer()))
3270         return false;
3271
3272     auto* contentDocument = downcast<RenderWidget>(layer.renderer()).frameOwnerElement().contentDocument();
3273     if (!contentDocument)
3274         return false;
3275
3276     auto* view = contentDocument->renderView();
3277     if (!view)
3278         return false;
3279
3280     if (auto* scrollingCoordinator = this->scrollingCoordinator())
3281         return scrollingCoordinator->coordinatesScrollingForFrameView(view->frameView());
3282
3283     return false;
3284 }
3285
3286 bool RenderLayerCompositor::isRunningTransformAnimation(RenderLayerModelObject& renderer)&n