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