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