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