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