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