Move RenderLayerCompositor's OverlapMap to its own file
[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 ENABLE(TREE_DEBUGGING)
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 ENABLE(TREE_DEBUGGING)
171     int 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 #if ENABLE(TREE_DEBUGGING)
834     LOG(Compositing, "%*p %s computeCompositingRequirements (backing provider candidate %p)", 12 + compositingState.depth * 2, &layer, layer.isNormalFlowOnly() ? "n" : "s", backingSharingState.backingProviderCandidate());
835 #endif
836
837     // FIXME: maybe we can avoid updating all remaining layers in paint order.
838     compositingState.fullPaintOrderTraversalRequired |= layer.needsCompositingRequirementsTraversal();
839     compositingState.descendantsRequireCompositingUpdate |= layer.descendantsNeedCompositingRequirementsTraversal();
840
841     layer.updateDescendantDependentFlags();
842     layer.updateLayerListsIfNeeded();
843
844     layer.setHasCompositingDescendant(false);
845
846     // We updated compositing for direct reasons in layerStyleChanged(). Here, check for compositing that can only be evaluated after layout.
847     RequiresCompositingData queryData;
848     bool willBeComposited = layer.isComposited();
849     if (layer.needsPostLayoutCompositingUpdate() || compositingState.fullPaintOrderTraversalRequired || compositingState.descendantsRequireCompositingUpdate) {
850         layer.setIndirectCompositingReason(RenderLayer::IndirectCompositingReason::None);
851         willBeComposited = needsToBeComposited(layer, queryData);
852     }
853
854     compositingState.fullPaintOrderTraversalRequired |= layer.subsequentLayersNeedCompositingRequirementsTraversal();
855
856     OverlapExtent layerExtent;
857     // Use the fact that we're composited as a hint to check for an animating transform.
858     // FIXME: Maybe needsToBeComposited() should return a bitmask of reasons, to avoid the need to recompute things.
859     if (willBeComposited && !layer.isRenderViewLayer())
860         layerExtent.hasTransformAnimation = isRunningTransformAnimation(layer.renderer());
861
862     bool respectTransforms = !layerExtent.hasTransformAnimation;
863     overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer, respectTransforms);
864
865     RenderLayer::IndirectCompositingReason compositingReason = compositingState.subtreeIsCompositing ? RenderLayer::IndirectCompositingReason::Stacking : RenderLayer::IndirectCompositingReason::None;
866     bool layerPaintsIntoProvidedBacking = false;
867
868     // If we know for sure the layer is going to be composited, don't bother looking it up in the overlap map
869     if (!willBeComposited && !overlapMap.isEmpty() && compositingState.testingOverlap) {
870         computeExtent(overlapMap, layer, layerExtent);
871
872         // If we're testing for overlap, we only need to composite if we overlap something that is already composited.
873         if (overlapMap.overlapsLayers(layerExtent.bounds)) {
874             if (backingSharingState.backingProviderCandidate() && canBeComposited(layer) && backingProviderLayerCanIncludeLayer(*backingSharingState.backingProviderCandidate(), layer)) {
875                 backingSharingState.appendSharingLayer(layer);
876                 LOG(Compositing, " layer %p can share with %p", &layer, backingSharingState.backingProviderCandidate());
877                 compositingReason = RenderLayer::IndirectCompositingReason::None;
878                 layerPaintsIntoProvidedBacking = true;
879             } else
880                 compositingReason = RenderLayer::IndirectCompositingReason::Overlap;
881         } else
882             compositingReason = RenderLayer::IndirectCompositingReason::None;
883     }
884
885 #if ENABLE(VIDEO)
886     // Video is special. It's the only RenderLayer type that can both have
887     // RenderLayer children and whose children can't use its backing to render
888     // into. These children (the controls) always need to be promoted into their
889     // own layers to draw on top of the accelerated video.
890     if (compositingState.compositingAncestor && compositingState.compositingAncestor->renderer().isVideo())
891         compositingReason = RenderLayer::IndirectCompositingReason::Overlap;
892 #endif
893
894     if (compositingReason != RenderLayer::IndirectCompositingReason::None)
895         layer.setIndirectCompositingReason(compositingReason);
896
897     // Check if the computed indirect reason will force the layer to become composited.
898     if (!willBeComposited && layer.mustCompositeForIndirectReasons() && canBeComposited(layer))
899         willBeComposited = true;
900
901     // The children of this layer don't need to composite, unless there is
902     // a compositing layer among them, so start by inheriting the compositing
903     // ancestor with subtreeIsCompositing set to false.
904     CompositingState childState = compositingState.stateForPaintOrderChildren(layer);
905
906     auto layerWillComposite = [&](bool postDescendants = false) {
907         // This layer now acts as the ancestor for kids.
908         childState.compositingAncestor = &layer;
909         overlapMap.pushCompositingContainer();
910         
911         if (postDescendants) {
912             childState.subtreeIsCompositing = true;
913             addToOverlapMapRecursive(overlapMap, layer);
914         }
915
916         // This layer is going to be composited, so children can safely ignore the fact that there's an
917         // animation running behind this layer, meaning they can rely on the overlap map testing again.
918         childState.testingOverlap = true;
919         willBeComposited = true;
920         layerPaintsIntoProvidedBacking = false;
921     };
922
923     if (willBeComposited) {
924         // Tell the parent it has compositing descendants.
925         compositingState.subtreeIsCompositing = true;
926         
927         layerWillComposite();
928
929         computeExtent(overlapMap, layer, layerExtent);
930         childState.ancestorHasTransformAnimation |= layerExtent.hasTransformAnimation;
931         // Too hard to compute animated bounds if both us and some ancestor is animating transform.
932         layerExtent.animationCausesExtentUncertainty |= layerExtent.hasTransformAnimation && compositingState.ancestorHasTransformAnimation;
933     } else if (layerPaintsIntoProvidedBacking) {
934         childState.backingSharingAncestor = &layer;
935         overlapMap.pushCompositingContainer();
936     }
937
938     backingSharingState.updateBeforeDescendantTraversal(layer, willBeComposited);
939
940 #if !ASSERT_DISABLED
941     LayerListMutationDetector mutationChecker(layer);
942 #endif
943
944     bool anyDescendantHas3DTransform = false;
945
946     for (auto* childLayer : layer.negativeZOrderLayers()) {
947         computeCompositingRequirements(&layer, *childLayer, overlapMap, childState, backingSharingState, anyDescendantHas3DTransform);
948
949         // If we have to make a layer for this child, make one now so we can have a contents layer
950         // (since we need to ensure that the -ve z-order child renders underneath our contents).
951         if (!willBeComposited && childState.subtreeIsCompositing) {
952             // make layer compositing
953             layer.setIndirectCompositingReason(RenderLayer::IndirectCompositingReason::BackgroundLayer);
954             layerWillComposite();
955         }
956     }
957     
958     for (auto* childLayer : layer.normalFlowLayers())
959         computeCompositingRequirements(&layer, *childLayer, overlapMap, childState, backingSharingState, anyDescendantHas3DTransform);
960
961     for (auto* childLayer : layer.positiveZOrderLayers())
962         computeCompositingRequirements(&layer, *childLayer, overlapMap, childState, backingSharingState, anyDescendantHas3DTransform);
963
964     // If we just entered compositing mode, the root will have become composited (as long as accelerated compositing is enabled).
965     if (layer.isRenderViewLayer()) {
966         if (usesCompositing() && m_hasAcceleratedCompositing)
967             willBeComposited = true;
968     }
969     
970     // All layers (even ones that aren't being composited) need to get added to
971     // the overlap map. Layers that do not composite will draw into their
972     // compositing ancestor's backing, and so are still considered for overlap.
973     // FIXME: When layerExtent has taken animation bounds into account, we also know that the bounds
974     // include descendants, so we don't need to add them all to the overlap map.
975     if (childState.compositingAncestor && !childState.compositingAncestor->isRenderViewLayer())
976         addToOverlapMap(overlapMap, layer, layerExtent);
977
978 #if ENABLE(CSS_COMPOSITING)
979     bool isolatedCompositedBlending = layer.isolatesCompositedBlending();
980     layer.setHasNotIsolatedCompositedBlendingDescendants(childState.hasNotIsolatedCompositedBlendingDescendants);
981     if (layer.isolatesCompositedBlending() != isolatedCompositedBlending) {
982         // isolatedCompositedBlending affects the result of clippedByAncestor().
983         layer.setChildrenNeedCompositingGeometryUpdate();
984     }
985
986     ASSERT(!layer.hasNotIsolatedCompositedBlendingDescendants() || layer.hasNotIsolatedBlendingDescendants());
987 #endif
988     // Now check for reasons to become composited that depend on the state of descendant layers.
989     RenderLayer::IndirectCompositingReason indirectCompositingReason;
990     if (!willBeComposited && canBeComposited(layer)
991         && requiresCompositingForIndirectReason(layer, compositingState.compositingAncestor, childState.subtreeIsCompositing, anyDescendantHas3DTransform, layerPaintsIntoProvidedBacking, indirectCompositingReason)) {
992         layer.setIndirectCompositingReason(indirectCompositingReason);
993         layerWillComposite(true);
994     }
995     
996     if (layer.reflectionLayer()) {
997         // FIXME: Shouldn't we call computeCompositingRequirements to handle a reflection overlapping with another renderer?
998         layer.reflectionLayer()->setIndirectCompositingReason(willBeComposited ? RenderLayer::IndirectCompositingReason::Stacking : RenderLayer::IndirectCompositingReason::None);
999     }
1000
1001     // Set the flag to say that this layer has compositing children.
1002     layer.setHasCompositingDescendant(childState.subtreeIsCompositing);
1003
1004     // setHasCompositingDescendant() may have changed the answer to needsToBeComposited() when clipping, so test that again.
1005     bool isCompositedClippingLayer = canBeComposited(layer) && clipsCompositingDescendants(layer);
1006
1007     // Turn overlap testing off for later layers if it's already off, or if we have an animating transform.
1008     // Note that if the layer clips its descendants, there's no reason to propagate the child animation to the parent layers. That's because
1009     // we know for sure the animation is contained inside the clipping rectangle, which is already added to the overlap map.
1010     if ((!childState.testingOverlap && !isCompositedClippingLayer) || layerExtent.knownToBeHaveExtentUncertainty())
1011         compositingState.testingOverlap = false;
1012     
1013     if (isCompositedClippingLayer & !willBeComposited)
1014         layerWillComposite(true);
1015
1016 #if ENABLE(CSS_COMPOSITING)
1017     if ((willBeComposited && layer.hasBlendMode()) || (layer.hasNotIsolatedCompositedBlendingDescendants() && !layer.isolatesCompositedBlending()))
1018         compositingState.hasNotIsolatedCompositedBlendingDescendants = true;
1019 #endif
1020
1021     if ((childState.compositingAncestor == &layer && !layer.isRenderViewLayer()) || childState.backingSharingAncestor == &layer)
1022         overlapMap.popCompositingContainer();
1023
1024     // If we're back at the root, and no other layers need to be composited, and the root layer itself doesn't need
1025     // to be composited, then we can drop out of compositing mode altogether. However, don't drop out of compositing mode
1026     // if there are composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
1027     RequiresCompositingData rootLayerQueryData;
1028     if (layer.isRenderViewLayer() && !childState.subtreeIsCompositing && !requiresCompositingLayer(layer, rootLayerQueryData) && !m_forceCompositingMode && !needsCompositingForContentOrOverlays()) {
1029         // Don't drop out of compositing on iOS, because we may flash. See <rdar://problem/8348337>.
1030 #if !PLATFORM(IOS_FAMILY)
1031         enableCompositingMode(false);
1032         willBeComposited = false;
1033 #endif
1034     }
1035
1036     compositingState.propagateStateFromChildren(childState);
1037
1038     ASSERT(willBeComposited == needsToBeComposited(layer, queryData));
1039
1040     // Create or destroy backing here. However, we can't update geometry because layers above us may become composited
1041     // during post-order traversal (e.g. for clipping).
1042     if (updateBacking(layer, queryData, CompositingChangeRepaintNow, willBeComposited ? BackingRequired::Yes : BackingRequired::No)) {
1043         layer.setNeedsCompositingLayerConnection();
1044         // Child layers need to get a geometry update to recompute their position.
1045         layer.setChildrenNeedCompositingGeometryUpdate();
1046         // The composited bounds of enclosing layers depends on which descendants are composited, so they need a geometry update.
1047         layer.setNeedsCompositingGeometryUpdateOnAncestors();
1048     }
1049
1050     backingSharingState.updateAfterDescendantTraversal(layer, compositingState.stackingContextAncestor);
1051
1052     if (layer.reflectionLayer() && updateLayerCompositingState(*layer.reflectionLayer(), queryData, CompositingChangeRepaintNow))
1053         layer.setNeedsCompositingLayerConnection();
1054
1055     descendantHas3DTransform |= anyDescendantHas3DTransform || layer.has3DTransform();
1056     
1057     // FIXME: clarify needsCompositingPaintOrderChildrenUpdate. If a composited layer gets a new ancestor, it needs geometry computations.
1058     if (layer.needsCompositingPaintOrderChildrenUpdate()) {
1059         layer.setChildrenNeedCompositingGeometryUpdate();
1060         layer.setNeedsCompositingLayerConnection();
1061     }
1062
1063 #if ENABLE(TREE_DEBUGGING)
1064     LOG(Compositing, "%*p computeCompositingRequirements - willBeComposited %d (backing provider candidate %p)", 12 + compositingState.depth * 2, &layer, willBeComposited, backingSharingState.backingProviderCandidate());
1065 #endif
1066
1067     layer.clearCompositingRequirementsTraversalState();
1068     
1069     overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
1070 }
1071
1072 // We have to traverse unchanged layers to fill in the overlap map.
1073 void RenderLayerCompositor::traverseUnchangedSubtree(RenderLayer* ancestorLayer, RenderLayer& layer, LayerOverlapMap& overlapMap, CompositingState& compositingState, BackingSharingState& backingSharingState, bool& descendantHas3DTransform)
1074 {
1075     ASSERT(!compositingState.fullPaintOrderTraversalRequired);
1076     ASSERT(!layer.hasDescendantNeedingCompositingRequirementsTraversal());
1077     ASSERT(!layer.needsCompositingRequirementsTraversal());
1078
1079 #if ENABLE(TREE_DEBUGGING)
1080     LOG(Compositing, "%*p traverseUnchangedSubtree", 12 + compositingState.depth * 2, &layer);
1081 #endif
1082
1083     layer.updateDescendantDependentFlags();
1084     layer.updateLayerListsIfNeeded();
1085
1086     bool layerIsComposited = layer.isComposited();
1087
1088     OverlapExtent layerExtent;
1089     if (layerIsComposited && !layer.isRenderViewLayer())
1090         layerExtent.hasTransformAnimation = isRunningTransformAnimation(layer.renderer());
1091
1092     bool respectTransforms = !layerExtent.hasTransformAnimation;
1093     overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer, respectTransforms);
1094
1095     // If we know for sure the layer is going to be composited, don't bother looking it up in the overlap map
1096     if (!layerIsComposited && !overlapMap.isEmpty() && compositingState.testingOverlap)
1097         computeExtent(overlapMap, layer, layerExtent);
1098
1099     if (layer.paintsIntoProvidedBacking()) {
1100         ASSERT(backingSharingState.backingProviderCandidate());
1101         ASSERT(backingProviderLayerCanIncludeLayer(*backingSharingState.backingProviderCandidate(), layer));
1102         backingSharingState.appendSharingLayer(layer);
1103     }
1104
1105     CompositingState childState = compositingState.stateForPaintOrderChildren(layer);
1106
1107     if (layerIsComposited) {
1108         // Tell the parent it has compositing descendants.
1109         compositingState.subtreeIsCompositing = true;
1110         // This layer now acts as the ancestor for kids.
1111         childState.compositingAncestor = &layer;
1112
1113         overlapMap.pushCompositingContainer();
1114         // This layer is going to be composited, so children can safely ignore the fact that there's an
1115         // animation running behind this layer, meaning they can rely on the overlap map testing again.
1116         childState.testingOverlap = true;
1117
1118         computeExtent(overlapMap, layer, layerExtent);
1119         childState.ancestorHasTransformAnimation |= layerExtent.hasTransformAnimation;
1120         // Too hard to compute animated bounds if both us and some ancestor is animating transform.
1121         layerExtent.animationCausesExtentUncertainty |= layerExtent.hasTransformAnimation && compositingState.ancestorHasTransformAnimation;
1122     }
1123
1124     backingSharingState.updateBeforeDescendantTraversal(layer, layerIsComposited);
1125
1126 #if !ASSERT_DISABLED
1127     LayerListMutationDetector mutationChecker(layer);
1128 #endif
1129
1130     bool anyDescendantHas3DTransform = false;
1131
1132     for (auto* childLayer : layer.negativeZOrderLayers()) {
1133         traverseUnchangedSubtree(&layer, *childLayer, overlapMap, childState, backingSharingState, anyDescendantHas3DTransform);
1134         if (childState.subtreeIsCompositing)
1135             ASSERT(layerIsComposited);
1136     }
1137     
1138     for (auto* childLayer : layer.normalFlowLayers())
1139         traverseUnchangedSubtree(&layer, *childLayer, overlapMap, childState, backingSharingState, anyDescendantHas3DTransform);
1140
1141     for (auto* childLayer : layer.positiveZOrderLayers())
1142         traverseUnchangedSubtree(&layer, *childLayer, overlapMap, childState, backingSharingState, anyDescendantHas3DTransform);
1143
1144     // All layers (even ones that aren't being composited) need to get added to
1145     // the overlap map. Layers that do not composite will draw into their
1146     // compositing ancestor's backing, and so are still considered for overlap.
1147     // FIXME: When layerExtent has taken animation bounds into account, we also know that the bounds
1148     // include descendants, so we don't need to add them all to the overlap map.
1149     if (childState.compositingAncestor && !childState.compositingAncestor->isRenderViewLayer())
1150         addToOverlapMap(overlapMap, layer, layerExtent);
1151
1152     compositingState.propagateStateFromChildrenForUnchangedSubtree(childState);
1153
1154     // Set the flag to say that this layer has compositing children.
1155     ASSERT(layer.hasCompositingDescendant() == childState.subtreeIsCompositing);
1156
1157     // setHasCompositingDescendant() may have changed the answer to needsToBeComposited() when clipping, so test that again.
1158     bool isCompositedClippingLayer = canBeComposited(layer) && clipsCompositingDescendants(layer);
1159
1160     // Turn overlap testing off for later layers if it's already off, or if we have an animating transform.
1161     // Note that if the layer clips its descendants, there's no reason to propagate the child animation to the parent layers. That's because
1162     // we know for sure the animation is contained inside the clipping rectangle, which is already added to the overlap map.
1163     if ((!childState.testingOverlap && !isCompositedClippingLayer) || layerExtent.knownToBeHaveExtentUncertainty())
1164         compositingState.testingOverlap = false;
1165     
1166     if (isCompositedClippingLayer)
1167         ASSERT(layerIsComposited);
1168
1169 #if ENABLE(CSS_COMPOSITING)
1170     if ((layerIsComposited && layer.hasBlendMode())
1171         || (layer.hasNotIsolatedCompositedBlendingDescendants() && !layer.isolatesCompositedBlending()))
1172         compositingState.hasNotIsolatedCompositedBlendingDescendants = true;
1173 #endif
1174
1175     if ((childState.compositingAncestor == &layer && !layer.isRenderViewLayer()) || childState.backingSharingAncestor == &layer)
1176         overlapMap.popCompositingContainer();
1177
1178     backingSharingState.updateAfterDescendantTraversal(layer, compositingState.stackingContextAncestor);
1179
1180     descendantHas3DTransform |= anyDescendantHas3DTransform || layer.has3DTransform();
1181
1182     ASSERT(!layer.needsCompositingRequirementsTraversal());
1183
1184     overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
1185 }
1186
1187 void RenderLayerCompositor::updateBackingAndHierarchy(RenderLayer& layer, Vector<Ref<GraphicsLayer>>& childLayersOfEnclosingLayer, ScrollingTreeState& scrollingTreeState, OptionSet<UpdateLevel> updateLevel, int depth)
1188 {
1189     layer.updateDescendantDependentFlags();
1190     layer.updateLayerListsIfNeeded();
1191
1192     bool layerNeedsUpdate = !updateLevel.isEmpty();
1193     if (layer.descendantsNeedUpdateBackingAndHierarchyTraversal())
1194         updateLevel.add(UpdateLevel::AllDescendants);
1195
1196     ScrollingTreeState stateForDescendants = scrollingTreeState;
1197
1198     auto* layerBacking = layer.backing();
1199     if (layerBacking) {
1200         updateLevel.remove(UpdateLevel::CompositedChildren);
1201
1202         // We updated the composited bounds in RenderLayerBacking::updateAfterLayout(), but it may have changed
1203         // based on which descendants are now composited.
1204         if (layerBacking->updateCompositedBounds()) {
1205             layer.setNeedsCompositingGeometryUpdate();
1206             // Our geometry can affect descendants.
1207             updateLevel.add(UpdateLevel::CompositedChildren);
1208         }
1209         
1210         if (layerNeedsUpdate || layer.needsCompositingConfigurationUpdate()) {
1211             if (layerBacking->updateConfiguration()) {
1212                 layerNeedsUpdate = true; // We also need to update geometry.
1213                 layer.setNeedsCompositingLayerConnection();
1214             }
1215
1216             layerBacking->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
1217         }
1218         
1219         OptionSet<ScrollingNodeChangeFlags> scrollingNodeChanges = { ScrollingNodeChangeFlags::Layer };
1220         if (layerNeedsUpdate || layer.needsCompositingGeometryUpdate()) {
1221             layerBacking->updateGeometry();
1222             scrollingNodeChanges.add(ScrollingNodeChangeFlags::LayerGeometry);
1223         } else if (layer.needsScrollingTreeUpdate())
1224             scrollingNodeChanges.add(ScrollingNodeChangeFlags::LayerGeometry);
1225
1226         if (auto* reflection = layer.reflectionLayer()) {
1227             if (auto* reflectionBacking = reflection->backing()) {
1228                 reflectionBacking->updateCompositedBounds();
1229                 reflectionBacking->updateGeometry();
1230                 reflectionBacking->updateAfterDescendants();
1231             }
1232         }
1233
1234         if (!layer.parent())
1235             updateRootLayerPosition();
1236
1237         // FIXME: do based on dirty flags. Need to do this for changes of geometry, configuration and hierarchy.
1238         // Need to be careful to do the right thing when a scroll-coordinated layer loses a scroll-coordinated ancestor.
1239         stateForDescendants.parentNodeID = updateScrollCoordinationForLayer(layer, scrollingTreeState, layerBacking->coordinatedScrollingRoles(), scrollingNodeChanges);
1240         stateForDescendants.nextChildIndex = 0;
1241
1242 #if !LOG_DISABLED
1243         logLayerInfo(layer, "updateBackingAndHierarchy", depth);
1244 #else
1245         UNUSED_PARAM(depth);
1246 #endif
1247     }
1248
1249     if (layer.childrenNeedCompositingGeometryUpdate())
1250         updateLevel.add(UpdateLevel::CompositedChildren);
1251
1252     // If this layer has backing, then we are collecting its children, otherwise appending
1253     // to the compositing child list of an enclosing layer.
1254     Vector<Ref<GraphicsLayer>> layerChildren;
1255     auto& childList = layerBacking ? layerChildren : childLayersOfEnclosingLayer;
1256
1257     bool requireDescendantTraversal = layer.hasDescendantNeedingUpdateBackingOrHierarchyTraversal()
1258         || (layer.hasCompositingDescendant() && (!layerBacking || layer.needsCompositingLayerConnection() || !updateLevel.isEmpty()));
1259
1260     bool requiresChildRebuild = layerBacking && layer.needsCompositingLayerConnection() && !layer.hasCompositingDescendant();
1261
1262 #if !ASSERT_DISABLED
1263     LayerListMutationDetector mutationChecker(layer);
1264 #endif
1265     
1266     auto appendForegroundLayerIfNecessary = [&] () {
1267         // If a negative z-order child is compositing, we get a foreground layer which needs to get parented.
1268         if (layer.negativeZOrderLayers().size()) {
1269             if (layerBacking && layerBacking->foregroundLayer())
1270                 childList.append(*layerBacking->foregroundLayer());
1271         }
1272     };
1273
1274     if (requireDescendantTraversal) {
1275         for (auto* renderLayer : layer.negativeZOrderLayers())
1276             updateBackingAndHierarchy(*renderLayer, childList, stateForDescendants, updateLevel, depth + 1);
1277
1278         appendForegroundLayerIfNecessary();
1279
1280         for (auto* renderLayer : layer.normalFlowLayers())
1281             updateBackingAndHierarchy(*renderLayer, childList, stateForDescendants, updateLevel, depth + 1);
1282         
1283         for (auto* renderLayer : layer.positiveZOrderLayers())
1284             updateBackingAndHierarchy(*renderLayer, childList, stateForDescendants, updateLevel, depth + 1);
1285     } else if (requiresChildRebuild)
1286         appendForegroundLayerIfNecessary();
1287
1288     if (layerBacking) {
1289         if (requireDescendantTraversal || requiresChildRebuild) {
1290             bool parented = false;
1291             if (is<RenderWidget>(layer.renderer()))
1292                 parented = parentFrameContentLayers(downcast<RenderWidget>(layer.renderer()));
1293
1294             if (!parented)
1295                 layerBacking->parentForSublayers()->setChildren(WTFMove(layerChildren));
1296
1297             // If the layer has a clipping layer the overflow controls layers will be siblings of the clipping layer.
1298             // Otherwise, the overflow control layers are normal children.
1299             if (!layerBacking->hasClippingLayer() && !layerBacking->hasScrollingLayer()) {
1300                 if (auto* overflowControlLayer = layerBacking->layerForHorizontalScrollbar())
1301                     layerBacking->parentForSublayers()->addChild(*overflowControlLayer);
1302
1303                 if (auto* overflowControlLayer = layerBacking->layerForVerticalScrollbar())
1304                     layerBacking->parentForSublayers()->addChild(*overflowControlLayer);
1305
1306                 if (auto* overflowControlLayer = layerBacking->layerForScrollCorner())
1307                     layerBacking->parentForSublayers()->addChild(*overflowControlLayer);
1308             }
1309         }
1310
1311         childLayersOfEnclosingLayer.append(*layerBacking->childForSuperlayers());
1312
1313         layerBacking->updateAfterDescendants();
1314     }
1315     
1316     layer.clearUpdateBackingOrHierarchyTraversalState();
1317 }
1318
1319 void RenderLayerCompositor::appendDocumentOverlayLayers(Vector<Ref<GraphicsLayer>>& childList)
1320 {
1321     if (!isMainFrameCompositor() || !m_compositing)
1322         return;
1323
1324     if (!page().pageOverlayController().hasDocumentOverlays())
1325         return;
1326
1327     Ref<GraphicsLayer> overlayHost = page().pageOverlayController().layerWithDocumentOverlays();
1328     childList.append(WTFMove(overlayHost));
1329 }
1330
1331 bool RenderLayerCompositor::needsCompositingForContentOrOverlays() const
1332 {
1333     return m_contentLayersCount + page().pageOverlayController().overlayCount();
1334 }
1335
1336 void RenderLayerCompositor::layerBecameComposited(const RenderLayer& layer)
1337 {
1338     if (&layer != m_renderView.layer())
1339         ++m_contentLayersCount;
1340 }
1341
1342 void RenderLayerCompositor::layerBecameNonComposited(const RenderLayer& layer)
1343 {
1344     // Inform the inspector that the given RenderLayer was destroyed.
1345     // FIXME: "destroyed" is a misnomer.
1346     InspectorInstrumentation::renderLayerDestroyed(&page(), layer);
1347
1348     if (&layer != m_renderView.layer()) {
1349         ASSERT(m_contentLayersCount > 0);
1350         --m_contentLayersCount;
1351     }
1352 }
1353
1354 #if !LOG_DISABLED
1355 void RenderLayerCompositor::logLayerInfo(const RenderLayer& layer, const char* phase, int depth)
1356 {
1357     if (!compositingLogEnabled())
1358         return;
1359
1360     auto* backing = layer.backing();
1361     RequiresCompositingData queryData;
1362     if (requiresCompositingLayer(layer, queryData) || layer.isRenderViewLayer()) {
1363         ++m_obligateCompositedLayerCount;
1364         m_obligatoryBackingStoreBytes += backing->backingStoreMemoryEstimate();
1365     } else {
1366         ++m_secondaryCompositedLayerCount;
1367         m_secondaryBackingStoreBytes += backing->backingStoreMemoryEstimate();
1368     }
1369
1370     LayoutRect absoluteBounds = backing->compositedBounds();
1371     absoluteBounds.move(layer.offsetFromAncestor(m_renderView.layer()));
1372     
1373     StringBuilder logString;
1374     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"));
1375
1376     if (!layer.renderer().style().hasAutoZIndex())
1377         logString.append(makeString(" z-index: ", layer.renderer().style().zIndex()));
1378
1379     logString.appendLiteral(" (");
1380     logString.append(logReasonsForCompositing(layer));
1381     logString.appendLiteral(") ");
1382
1383     if (backing->graphicsLayer()->contentsOpaque() || backing->paintsIntoCompositedAncestor() || backing->foregroundLayer() || backing->backgroundLayer()) {
1384         logString.append('[');
1385         bool prependSpace = false;
1386         if (backing->graphicsLayer()->contentsOpaque()) {
1387             logString.appendLiteral("opaque");
1388             prependSpace = true;
1389         }
1390
1391         if (backing->paintsIntoCompositedAncestor()) {
1392             if (prependSpace)
1393                 logString.appendLiteral(", ");
1394             logString.appendLiteral("paints into ancestor");
1395             prependSpace = true;
1396         }
1397
1398         if (backing->foregroundLayer() || backing->backgroundLayer()) {
1399             if (prependSpace)
1400                 logString.appendLiteral(", ");
1401             if (backing->foregroundLayer() && backing->backgroundLayer()) {
1402                 logString.appendLiteral("+foreground+background");
1403                 prependSpace = true;
1404             } else if (backing->foregroundLayer()) {
1405                 logString.appendLiteral("+foreground");
1406                 prependSpace = true;
1407             } else {
1408                 logString.appendLiteral("+background");
1409                 prependSpace = true;
1410             }
1411         }
1412         
1413         if (backing->paintsSubpixelAntialiasedText()) {
1414             if (prependSpace)
1415                 logString.appendLiteral(", ");
1416             logString.appendLiteral("texty");
1417         }
1418
1419         logString.appendLiteral("] ");
1420     }
1421
1422     logString.append(layer.name());
1423
1424     logString.appendLiteral(" - ");
1425     logString.append(phase);
1426
1427     LOG(Compositing, "%s", logString.toString().utf8().data());
1428 }
1429 #endif
1430
1431 static bool clippingChanged(const RenderStyle& oldStyle, const RenderStyle& newStyle)
1432 {
1433     return oldStyle.overflowX() != newStyle.overflowX() || oldStyle.overflowY() != newStyle.overflowY()
1434         || oldStyle.hasClip() != newStyle.hasClip() || oldStyle.clip() != newStyle.clip();
1435 }
1436
1437 static bool styleAffectsLayerGeometry(const RenderStyle& style)
1438 {
1439     return style.hasClip() || style.clipPath() || style.hasBorderRadius();
1440 }
1441
1442 static bool recompositeChangeRequiresGeometryUpdate(const RenderStyle& oldStyle, const RenderStyle& newStyle)
1443 {
1444     return oldStyle.transform() != newStyle.transform()
1445         || oldStyle.transformOriginX() != newStyle.transformOriginX()
1446         || oldStyle.transformOriginY() != newStyle.transformOriginY()
1447         || oldStyle.transformOriginZ() != newStyle.transformOriginZ()
1448         || oldStyle.transformStyle3D() != newStyle.transformStyle3D()
1449         || oldStyle.perspective() != newStyle.perspective()
1450         || oldStyle.perspectiveOriginX() != newStyle.perspectiveOriginX()
1451         || oldStyle.perspectiveOriginY() != newStyle.perspectiveOriginY()
1452         || oldStyle.backfaceVisibility() != newStyle.backfaceVisibility()
1453         || !arePointingToEqualData(oldStyle.clipPath(), newStyle.clipPath());
1454 }
1455
1456 void RenderLayerCompositor::layerStyleChanged(StyleDifference diff, RenderLayer& layer, const RenderStyle* oldStyle)
1457 {
1458     if (diff == StyleDifference::Equal)
1459         return;
1460
1461     // Create or destroy backing here so that code that runs during layout can reliably use isComposited() (though this
1462     // is only true for layers composited for direct reasons).
1463     // Also, it allows us to avoid a tree walk in updateCompositingLayers() when no layer changed its compositing state.
1464     RequiresCompositingData queryData;
1465     queryData.layoutUpToDate = LayoutUpToDate::No;
1466     
1467     bool layerChanged = updateBacking(layer, queryData, CompositingChangeRepaintNow);
1468     if (layerChanged) {
1469         layer.setChildrenNeedCompositingGeometryUpdate();
1470         layer.setNeedsCompositingLayerConnection();
1471         layer.setSubsequentLayersNeedCompositingRequirementsTraversal();
1472         // Ancestor layers that composited for indirect reasons (things listed in styleChangeMayAffectIndirectCompositingReasons()) need to get updated.
1473         // This could be optimized by only setting this flag on layers with the relevant styles.
1474         layer.setNeedsPostLayoutCompositingUpdateOnAncestors();
1475     }
1476     
1477     if (queryData.reevaluateAfterLayout)
1478         layer.setNeedsPostLayoutCompositingUpdate();
1479
1480     if (diff >= StyleDifference::LayoutPositionedMovementOnly && hasContentCompositingLayers()) {
1481         layer.setNeedsPostLayoutCompositingUpdate();
1482         layer.setNeedsCompositingGeometryUpdate();
1483     }
1484
1485     auto* backing = layer.backing();
1486     if (!backing)
1487         return;
1488
1489     backing->updateConfigurationAfterStyleChange();
1490
1491     const auto& newStyle = layer.renderer().style();
1492
1493     if (diff >= StyleDifference::Repaint) {
1494         // Visibility change may affect geometry of the enclosing composited layer.
1495         if (oldStyle && oldStyle->visibility() != newStyle.visibility())
1496             layer.setNeedsCompositingGeometryUpdate();
1497         
1498         // We'll get a diff of Repaint when things like clip-path change; these might affect layer or inner-layer geometry.
1499         if (layer.isComposited() && oldStyle) {
1500             if (styleAffectsLayerGeometry(*oldStyle) || styleAffectsLayerGeometry(newStyle))
1501                 layer.setNeedsCompositingGeometryUpdate();
1502         }
1503     }
1504
1505     // This is necessary to get iframe layers hooked up in response to scheduleInvalidateStyleAndLayerComposition().
1506     if (diff == StyleDifference::RecompositeLayer && layer.isComposited() && is<RenderWidget>(layer.renderer()))
1507         layer.setNeedsCompositingConfigurationUpdate();
1508
1509     if (diff >= StyleDifference::RecompositeLayer && oldStyle && recompositeChangeRequiresGeometryUpdate(*oldStyle, newStyle)) {
1510         // FIXME: transform changes really need to trigger layout. See RenderElement::adjustStyleDifference().
1511         layer.setNeedsPostLayoutCompositingUpdate();
1512         layer.setNeedsCompositingGeometryUpdate();
1513     }
1514
1515     if (diff >= StyleDifference::Layout) {
1516         // FIXME: only set flags here if we know we have a composited descendant, but we might not know at this point.
1517         if (oldStyle && clippingChanged(*oldStyle, newStyle)) {
1518             if (layer.isStackingContext()) {
1519                 layer.setNeedsPostLayoutCompositingUpdate(); // Layer needs to become composited if it has composited descendants.
1520                 layer.setNeedsCompositingConfigurationUpdate(); // If already composited, layer needs to create/destroy clipping layer.
1521             } else {
1522                 // Descendant (in containing block order) compositing layers need to re-evaluate their clipping,
1523                 // but they might be siblings in z-order so go up to our stacking context.
1524                 if (auto* stackingContext = layer.stackingContext())
1525                     stackingContext->setDescendantsNeedUpdateBackingAndHierarchyTraversal();
1526             }
1527         }
1528
1529         // These properties trigger compositing if some descendant is composited.
1530         if (oldStyle && styleChangeMayAffectIndirectCompositingReasons(*oldStyle, newStyle))
1531             layer.setNeedsPostLayoutCompositingUpdate();
1532
1533         layer.setNeedsCompositingGeometryUpdate();
1534     }
1535 }
1536
1537 bool RenderLayerCompositor::needsCompositingUpdateForStyleChangeOnNonCompositedLayer(RenderLayer& layer, const RenderStyle* oldStyle) const
1538 {
1539     // Needed for scroll bars.
1540     if (layer.isRenderViewLayer())
1541         return true;
1542
1543     if (!oldStyle)
1544         return false;
1545
1546     const RenderStyle& newStyle = layer.renderer().style();
1547     // Visibility change may affect geometry of the enclosing composited layer.
1548     if (oldStyle->visibility() != newStyle.visibility())
1549         return true;
1550
1551     // We don't have any direct reasons for this style change to affect layer composition. Test if it might affect things indirectly.
1552     if (styleChangeMayAffectIndirectCompositingReasons(*oldStyle, newStyle))
1553         return true;
1554
1555     return false;
1556 }
1557
1558 bool RenderLayerCompositor::canCompositeClipPath(const RenderLayer& layer)
1559 {
1560     ASSERT(layer.isComposited());
1561     ASSERT(layer.renderer().style().clipPath());
1562
1563     if (layer.renderer().hasMask())
1564         return false;
1565
1566     auto& clipPath = *layer.renderer().style().clipPath();
1567     return (clipPath.type() != ClipPathOperation::Shape || clipPath.type() == ClipPathOperation::Shape) && GraphicsLayer::supportsLayerType(GraphicsLayer::Type::Shape);
1568 }
1569
1570 // FIXME: remove and never ask questions about reflection layers.
1571 static RenderLayerModelObject& rendererForCompositingTests(const RenderLayer& layer)
1572 {
1573     auto* renderer = &layer.renderer();
1574
1575     // The compositing state of a reflection should match that of its reflected layer.
1576     if (layer.isReflection())
1577         renderer = downcast<RenderLayerModelObject>(renderer->parent()); // The RenderReplica's parent is the object being reflected.
1578
1579     return *renderer;
1580 }
1581
1582 void RenderLayerCompositor::updateRootContentLayerClipping()
1583 {
1584     m_rootContentsLayer->setMasksToBounds(!m_renderView.settings().backgroundShouldExtendBeyondPage());
1585 }
1586
1587 bool RenderLayerCompositor::updateBacking(RenderLayer& layer, RequiresCompositingData& queryData, CompositingChangeRepaint shouldRepaint, BackingRequired backingRequired)
1588 {
1589     bool layerChanged = false;
1590     if (backingRequired == BackingRequired::Unknown)
1591         backingRequired = needsToBeComposited(layer, queryData) ? BackingRequired::Yes : BackingRequired::No;
1592     else {
1593         // Need to fetch viewportConstrainedNotCompositedReason, but without doing all the work that needsToBeComposited does.
1594         requiresCompositingForPosition(rendererForCompositingTests(layer), layer, queryData);
1595     }
1596
1597     if (backingRequired == BackingRequired::Yes) {
1598         layer.disconnectFromBackingProviderLayer();
1599
1600         enableCompositingMode();
1601         
1602         if (!layer.backing()) {
1603             // If we need to repaint, do so before making backing
1604             if (shouldRepaint == CompositingChangeRepaintNow)
1605                 repaintOnCompositingChange(layer);
1606
1607             layer.ensureBacking();
1608
1609             if (layer.isRenderViewLayer() && useCoordinatedScrollingForLayer(layer)) {
1610                 auto& frameView = m_renderView.frameView();
1611                 if (auto* scrollingCoordinator = this->scrollingCoordinator())
1612                     scrollingCoordinator->frameViewRootLayerDidChange(frameView);
1613 #if ENABLE(RUBBER_BANDING)
1614                 updateLayerForHeader(frameView.headerHeight());
1615                 updateLayerForFooter(frameView.footerHeight());
1616 #endif
1617                 updateRootContentLayerClipping();
1618
1619                 if (auto* tiledBacking = layer.backing()->tiledBacking())
1620                     tiledBacking->setTopContentInset(frameView.topContentInset());
1621             }
1622
1623             // This layer and all of its descendants have cached repaints rects that are relative to
1624             // the repaint container, so change when compositing changes; we need to update them here.
1625             if (layer.parent())
1626                 layer.computeRepaintRectsIncludingDescendants();
1627             
1628             layer.setNeedsCompositingGeometryUpdate();
1629             layer.setNeedsCompositingConfigurationUpdate();
1630             layer.setNeedsCompositingPaintOrderChildrenUpdate();
1631
1632             layerChanged = true;
1633         }
1634     } else {
1635         if (layer.backing()) {
1636             // If we're removing backing on a reflection, clear the source GraphicsLayer's pointer to
1637             // its replica GraphicsLayer. In practice this should never happen because reflectee and reflection 
1638             // are both either composited, or not composited.
1639             if (layer.isReflection()) {
1640                 auto* sourceLayer = downcast<RenderLayerModelObject>(*layer.renderer().parent()).layer();
1641                 if (auto* backing = sourceLayer->backing()) {
1642                     ASSERT(backing->graphicsLayer()->replicaLayer() == layer.backing()->graphicsLayer());
1643                     backing->graphicsLayer()->setReplicatedByLayer(nullptr);
1644                 }
1645             }
1646
1647             layer.clearBacking();
1648             layerChanged = true;
1649
1650             // This layer and all of its descendants have cached repaints rects that are relative to
1651             // the repaint container, so change when compositing changes; we need to update them here.
1652             layer.computeRepaintRectsIncludingDescendants();
1653
1654             // If we need to repaint, do so now that we've removed the backing
1655             if (shouldRepaint == CompositingChangeRepaintNow)
1656                 repaintOnCompositingChange(layer);
1657         }
1658     }
1659     
1660 #if ENABLE(VIDEO)
1661     if (layerChanged && is<RenderVideo>(layer.renderer())) {
1662         // If it's a video, give the media player a chance to hook up to the layer.
1663         downcast<RenderVideo>(layer.renderer()).acceleratedRenderingStateChanged();
1664     }
1665 #endif
1666
1667     if (layerChanged && is<RenderWidget>(layer.renderer())) {
1668         auto* innerCompositor = frameContentsCompositor(downcast<RenderWidget>(layer.renderer()));
1669         if (innerCompositor && innerCompositor->usesCompositing())
1670             innerCompositor->updateRootLayerAttachment();
1671     }
1672     
1673     if (layerChanged)
1674         layer.clearClipRectsIncludingDescendants(PaintingClipRects);
1675
1676     // If a fixed position layer gained/lost a backing or the reason not compositing it changed,
1677     // the scrolling coordinator needs to recalculate whether it can do fast scrolling.
1678     if (layer.renderer().isFixedPositioned()) {
1679         if (layer.viewportConstrainedNotCompositedReason() != queryData.nonCompositedForPositionReason) {
1680             layer.setViewportConstrainedNotCompositedReason(queryData.nonCompositedForPositionReason);
1681             layerChanged = true;
1682         }
1683         if (layerChanged) {
1684             if (auto* scrollingCoordinator = this->scrollingCoordinator())
1685                 scrollingCoordinator->frameViewFixedObjectsDidChange(m_renderView.frameView());
1686         }
1687     } else
1688         layer.setViewportConstrainedNotCompositedReason(RenderLayer::NoNotCompositedReason);
1689     
1690     if (layer.backing())
1691         layer.backing()->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
1692
1693     return layerChanged;
1694 }
1695
1696 bool RenderLayerCompositor::updateLayerCompositingState(RenderLayer& layer, RequiresCompositingData& queryData, CompositingChangeRepaint shouldRepaint)
1697 {
1698     bool layerChanged = updateBacking(layer, queryData, shouldRepaint);
1699
1700     // See if we need content or clipping layers. Methods called here should assume
1701     // that the compositing state of descendant layers has not been updated yet.
1702     if (layer.backing() && layer.backing()->updateConfiguration())
1703         layerChanged = true;
1704
1705     return layerChanged;
1706 }
1707
1708 void RenderLayerCompositor::repaintOnCompositingChange(RenderLayer& layer)
1709 {
1710     // If the renderer is not attached yet, no need to repaint.
1711     if (&layer.renderer() != &m_renderView && !layer.renderer().parent())
1712         return;
1713
1714     auto* repaintContainer = layer.renderer().containerForRepaint();
1715     if (!repaintContainer)
1716         repaintContainer = &m_renderView;
1717
1718     layer.repaintIncludingNonCompositingDescendants(repaintContainer);
1719     if (repaintContainer == &m_renderView) {
1720         // The contents of this layer may be moving between the window
1721         // and a GraphicsLayer, so we need to make sure the window system
1722         // synchronizes those changes on the screen.
1723         m_renderView.frameView().setNeedsOneShotDrawingSynchronization();
1724     }
1725 }
1726
1727 // This method assumes that layout is up-to-date, unlike repaintOnCompositingChange().
1728 void RenderLayerCompositor::repaintInCompositedAncestor(RenderLayer& layer, const LayoutRect& rect)
1729 {
1730     auto* compositedAncestor = layer.enclosingCompositingLayerForRepaint(ExcludeSelf);
1731     if (!compositedAncestor)
1732         return;
1733
1734     ASSERT(compositedAncestor->backing());
1735     LayoutRect repaintRect = rect;
1736     repaintRect.move(layer.offsetFromAncestor(compositedAncestor));
1737     compositedAncestor->setBackingNeedsRepaintInRect(repaintRect);
1738
1739     // The contents of this layer may be moving from a GraphicsLayer to the window,
1740     // so we need to make sure the window system synchronizes those changes on the screen.
1741     if (compositedAncestor->isRenderViewLayer())
1742         m_renderView.frameView().setNeedsOneShotDrawingSynchronization();
1743 }
1744
1745 // FIXME: remove.
1746 void RenderLayerCompositor::layerWasAdded(RenderLayer&, RenderLayer&)
1747 {
1748 }
1749
1750 void RenderLayerCompositor::layerWillBeRemoved(RenderLayer& parent, RenderLayer& child)
1751 {
1752     if (parent.renderer().renderTreeBeingDestroyed())
1753         return;
1754
1755     if (child.isComposited())
1756         repaintInCompositedAncestor(child, child.backing()->compositedBounds()); // FIXME: do via dirty bits?
1757     else if (child.paintsIntoProvidedBacking()) {
1758         auto* backingProviderLayer = child.backingProviderLayer();
1759         // FIXME: Optimize this repaint.
1760         backingProviderLayer->setBackingNeedsRepaint();
1761         backingProviderLayer->backing()->removeBackingSharingLayer(child);
1762     } else
1763         return;
1764
1765     child.setNeedsCompositingLayerConnection();
1766 }
1767
1768 RenderLayer* RenderLayerCompositor::enclosingNonStackingClippingLayer(const RenderLayer& layer) const
1769 {
1770     for (auto* parent = layer.parent(); parent; parent = parent->parent()) {
1771         if (parent->isStackingContext())
1772             return nullptr;
1773         if (parent->renderer().hasClipOrOverflowClip())
1774             return parent;
1775     }
1776     return nullptr;
1777 }
1778
1779 void RenderLayerCompositor::computeExtent(const LayerOverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& extent) const
1780 {
1781     if (extent.extentComputed)
1782         return;
1783
1784     LayoutRect layerBounds;
1785     if (extent.hasTransformAnimation)
1786         extent.animationCausesExtentUncertainty = !layer.getOverlapBoundsIncludingChildrenAccountingForTransformAnimations(layerBounds);
1787     else
1788         layerBounds = layer.overlapBounds();
1789     
1790     // In the animating transform case, we avoid double-accounting for the transform because
1791     // we told pushMappingsToAncestor() to ignore transforms earlier.
1792     extent.bounds = enclosingLayoutRect(overlapMap.geometryMap().absoluteRect(layerBounds));
1793
1794     // Empty rects never intersect, but we need them to for the purposes of overlap testing.
1795     if (extent.bounds.isEmpty())
1796         extent.bounds.setSize(LayoutSize(1, 1));
1797
1798
1799     RenderLayerModelObject& renderer = layer.renderer();
1800     if (renderer.isFixedPositioned() && renderer.container() == &m_renderView) {
1801         // Because fixed elements get moved around without re-computing overlap, we have to compute an overlap
1802         // rect that covers all the locations that the fixed element could move to.
1803         // FIXME: need to handle sticky too.
1804         extent.bounds = m_renderView.frameView().fixedScrollableAreaBoundsInflatedForScrolling(extent.bounds);
1805     }
1806
1807     extent.extentComputed = true;
1808 }
1809
1810 void RenderLayerCompositor::addToOverlapMap(LayerOverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& extent)
1811 {
1812     if (layer.isRenderViewLayer())
1813         return;
1814
1815     computeExtent(overlapMap, layer, extent);
1816
1817     LayoutRect clipRect = layer.backgroundClipRect(RenderLayer::ClipRectsContext(&rootRenderLayer(), AbsoluteClipRects)).rect(); // FIXME: Incorrect for CSS regions.
1818
1819     // On iOS, pageScaleFactor() is not applied by RenderView, so we should not scale here.
1820     if (!m_renderView.settings().delegatesPageScaling())
1821         clipRect.scale(pageScaleFactor());
1822     clipRect.intersect(extent.bounds);
1823     overlapMap.add(clipRect);
1824 }
1825
1826 void RenderLayerCompositor::addToOverlapMapRecursive(LayerOverlapMap& overlapMap, const RenderLayer& layer, const RenderLayer* ancestorLayer)
1827 {
1828     if (!canBeComposited(layer))
1829         return;
1830
1831     // A null ancestorLayer is an indication that 'layer' has already been pushed.
1832     if (ancestorLayer)
1833         overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer);
1834     
1835     OverlapExtent layerExtent;
1836     addToOverlapMap(overlapMap, layer, layerExtent);
1837
1838 #if !ASSERT_DISABLED
1839     LayerListMutationDetector mutationChecker(const_cast<RenderLayer&>(layer));
1840 #endif
1841
1842     for (auto* renderLayer : layer.negativeZOrderLayers())
1843         addToOverlapMapRecursive(overlapMap, *renderLayer, &layer);
1844
1845     for (auto* renderLayer : layer.normalFlowLayers())
1846         addToOverlapMapRecursive(overlapMap, *renderLayer, &layer);
1847
1848     for (auto* renderLayer : layer.positiveZOrderLayers())
1849         addToOverlapMapRecursive(overlapMap, *renderLayer, &layer);
1850     
1851     if (ancestorLayer)
1852         overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
1853 }
1854
1855 #if ENABLE(VIDEO)
1856 bool RenderLayerCompositor::canAccelerateVideoRendering(RenderVideo& video) const
1857 {
1858     if (!m_hasAcceleratedCompositing)
1859         return false;
1860
1861     return video.supportsAcceleratedRendering();
1862 }
1863 #endif
1864
1865 void RenderLayerCompositor::frameViewDidChangeLocation(const IntPoint& contentsOffset)
1866 {
1867     if (m_overflowControlsHostLayer)
1868         m_overflowControlsHostLayer->setPosition(contentsOffset);
1869 }
1870
1871 void RenderLayerCompositor::frameViewDidChangeSize()
1872 {
1873     if (auto* layer = m_renderView.layer())
1874         layer->setNeedsCompositingGeometryUpdate();
1875
1876     if (m_scrolledContentsLayer) {
1877         updateScrollLayerClipping();
1878         frameViewDidScroll();
1879         updateOverflowControlsLayers();
1880
1881 #if ENABLE(RUBBER_BANDING)
1882         if (m_layerForOverhangAreas) {
1883             auto& frameView = m_renderView.frameView();
1884             m_layerForOverhangAreas->setSize(frameView.frameRect().size());
1885             m_layerForOverhangAreas->setPosition(FloatPoint(0, frameView.topContentInset()));
1886         }
1887 #endif
1888     }
1889 }
1890
1891 bool RenderLayerCompositor::hasCoordinatedScrolling() const
1892 {
1893     auto* scrollingCoordinator = this->scrollingCoordinator();
1894     return scrollingCoordinator && scrollingCoordinator->coordinatesScrollingForFrameView(m_renderView.frameView());
1895 }
1896
1897 void RenderLayerCompositor::updateScrollLayerPosition()
1898 {
1899     ASSERT(!hasCoordinatedScrolling());
1900     ASSERT(m_scrolledContentsLayer);
1901
1902     auto& frameView = m_renderView.frameView();
1903     IntPoint scrollPosition = frameView.scrollPosition();
1904
1905     m_scrolledContentsLayer->setPosition(FloatPoint(-scrollPosition.x(), -scrollPosition.y()));
1906
1907     if (auto* fixedBackgroundLayer = fixedRootBackgroundLayer())
1908         fixedBackgroundLayer->setPosition(frameView.scrollPositionForFixedPosition());
1909 }
1910
1911 void RenderLayerCompositor::updateScrollLayerClipping()
1912 {
1913     auto* layerForClipping = this->layerForClipping();
1914     if (!layerForClipping)
1915         return;
1916
1917     layerForClipping->setSize(m_renderView.frameView().sizeForVisibleContent());
1918     layerForClipping->setPosition(positionForClipLayer());
1919 }
1920
1921 FloatPoint RenderLayerCompositor::positionForClipLayer() const
1922 {
1923     auto& frameView = m_renderView.frameView();
1924
1925     return FloatPoint(
1926         frameView.shouldPlaceBlockDirectionScrollbarOnLeft() ? frameView.horizontalScrollbarIntrusion() : 0,
1927         FrameView::yPositionForInsetClipLayer(frameView.scrollPosition(), frameView.topContentInset()));
1928 }
1929
1930 void RenderLayerCompositor::frameViewDidScroll()
1931 {
1932     if (!m_scrolledContentsLayer)
1933         return;
1934
1935     // If there's a scrolling coordinator that manages scrolling for this frame view,
1936     // it will also manage updating the scroll layer position.
1937     if (hasCoordinatedScrolling()) {
1938         // We have to schedule a flush in order for the main TiledBacking to update its tile coverage.
1939         scheduleLayerFlush();
1940         return;
1941     }
1942
1943     updateScrollLayerPosition();
1944 }
1945
1946 void RenderLayerCompositor::frameViewDidAddOrRemoveScrollbars()
1947 {
1948     updateOverflowControlsLayers();
1949 }
1950
1951 void RenderLayerCompositor::frameViewDidLayout()
1952 {
1953     if (auto* renderViewBacking = m_renderView.layer()->backing())
1954         renderViewBacking->adjustTiledBackingCoverage();
1955 }
1956
1957 void RenderLayerCompositor::rootLayerConfigurationChanged()
1958 {
1959     auto* renderViewBacking = m_renderView.layer()->backing();
1960     if (renderViewBacking && renderViewBacking->isFrameLayerWithTiledBacking()) {
1961         m_renderView.layer()->setNeedsCompositingConfigurationUpdate();
1962         scheduleCompositingLayerUpdate();
1963     }
1964 }
1965
1966 String RenderLayerCompositor::layerTreeAsText(LayerTreeFlags flags)
1967 {
1968     updateCompositingLayers(CompositingUpdateType::AfterLayout);
1969
1970     if (!m_rootContentsLayer)
1971         return String();
1972
1973     flushPendingLayerChanges(true);
1974     page().renderingUpdateScheduler().scheduleCompositingLayerFlush();
1975
1976     LayerTreeAsTextBehavior layerTreeBehavior = LayerTreeAsTextBehaviorNormal;
1977     if (flags & LayerTreeFlagsIncludeDebugInfo)
1978         layerTreeBehavior |= LayerTreeAsTextDebug;
1979     if (flags & LayerTreeFlagsIncludeVisibleRects)
1980         layerTreeBehavior |= LayerTreeAsTextIncludeVisibleRects;
1981     if (flags & LayerTreeFlagsIncludeTileCaches)
1982         layerTreeBehavior |= LayerTreeAsTextIncludeTileCaches;
1983     if (flags & LayerTreeFlagsIncludeRepaintRects)
1984         layerTreeBehavior |= LayerTreeAsTextIncludeRepaintRects;
1985     if (flags & LayerTreeFlagsIncludePaintingPhases)
1986         layerTreeBehavior |= LayerTreeAsTextIncludePaintingPhases;
1987     if (flags & LayerTreeFlagsIncludeContentLayers)
1988         layerTreeBehavior |= LayerTreeAsTextIncludeContentLayers;
1989     if (flags & LayerTreeFlagsIncludeAcceleratesDrawing)
1990         layerTreeBehavior |= LayerTreeAsTextIncludeAcceleratesDrawing;
1991     if (flags & LayerTreeFlagsIncludeBackingStoreAttached)
1992         layerTreeBehavior |= LayerTreeAsTextIncludeBackingStoreAttached;
1993     if (flags & LayerTreeFlagsIncludeRootLayerProperties)
1994         layerTreeBehavior |= LayerTreeAsTextIncludeRootLayerProperties;
1995     if (flags & LayerTreeFlagsIncludeEventRegion)
1996         layerTreeBehavior |= LayerTreeAsTextIncludeEventRegion;
1997
1998     // We skip dumping the scroll and clip layers to keep layerTreeAsText output
1999     // similar between platforms.
2000     String layerTreeText = m_rootContentsLayer->layerTreeAsText(layerTreeBehavior);
2001
2002     // Dump an empty layer tree only if the only composited layer is the main frame's tiled backing,
2003     // so that tests expecting us to drop out of accelerated compositing when there are no layers succeed.
2004     if (!hasContentCompositingLayers() && documentUsesTiledBacking() && !(layerTreeBehavior & LayerTreeAsTextIncludeTileCaches) && !(layerTreeBehavior & LayerTreeAsTextIncludeRootLayerProperties))
2005         layerTreeText = emptyString();
2006
2007     // The true root layer is not included in the dump, so if we want to report
2008     // its repaint rects, they must be included here.
2009     if (flags & LayerTreeFlagsIncludeRepaintRects)
2010         return m_renderView.frameView().trackedRepaintRectsAsText() + layerTreeText;
2011
2012     return layerTreeText;
2013 }
2014
2015 static RenderView* frameContentsRenderView(RenderWidget& renderer)
2016 {
2017     if (auto* contentDocument = renderer.frameOwnerElement().contentDocument())
2018         return contentDocument->renderView();
2019
2020     return nullptr;
2021 }
2022
2023 RenderLayerCompositor* RenderLayerCompositor::frameContentsCompositor(RenderWidget& renderer)
2024 {
2025     if (auto* view = frameContentsRenderView(renderer))
2026         return &view->compositor();
2027
2028     return nullptr;
2029 }
2030
2031 bool RenderLayerCompositor::parentFrameContentLayers(RenderWidget& renderer)
2032 {
2033     auto* innerCompositor = frameContentsCompositor(renderer);
2034     if (!innerCompositor || !innerCompositor->usesCompositing() || innerCompositor->rootLayerAttachment() != RootLayerAttachedViaEnclosingFrame)
2035         return false;
2036     
2037     auto* layer = renderer.layer();
2038     if (!layer->isComposited())
2039         return false;
2040
2041     auto* backing = layer->backing();
2042     auto* hostingLayer = backing->parentForSublayers();
2043     auto* rootLayer = innerCompositor->rootGraphicsLayer();
2044     if (hostingLayer->children().size() != 1 || hostingLayer->children()[0].ptr() != rootLayer) {
2045         hostingLayer->removeAllChildren();
2046         hostingLayer->addChild(*rootLayer);
2047     }
2048
2049     if (auto frameHostingNodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::FrameHosting)) {
2050         auto* contentsRenderView = frameContentsRenderView(renderer);
2051         if (auto frameRootScrollingNodeID = contentsRenderView->frameView().scrollingNodeID()) {
2052             if (auto* scrollingCoordinator = this->scrollingCoordinator())
2053                 scrollingCoordinator->insertNode(ScrollingNodeType::Subframe, frameRootScrollingNodeID, frameHostingNodeID, 0);
2054         }
2055     }
2056
2057     // FIXME: Why always return true and not just when the layers changed?
2058     return true;
2059 }
2060
2061 void RenderLayerCompositor::repaintCompositedLayers()
2062 {
2063     recursiveRepaintLayer(rootRenderLayer());
2064 }
2065
2066 void RenderLayerCompositor::recursiveRepaintLayer(RenderLayer& layer)
2067 {
2068     layer.updateLayerListsIfNeeded();
2069
2070     // FIXME: This method does not work correctly with transforms.
2071     if (layer.isComposited() && !layer.backing()->paintsIntoCompositedAncestor())
2072         layer.setBackingNeedsRepaint();
2073
2074 #if !ASSERT_DISABLED
2075     LayerListMutationDetector mutationChecker(layer);
2076 #endif
2077
2078     if (layer.hasCompositingDescendant()) {
2079         for (auto* renderLayer : layer.negativeZOrderLayers())
2080             recursiveRepaintLayer(*renderLayer);
2081
2082         for (auto* renderLayer : layer.positiveZOrderLayers())
2083             recursiveRepaintLayer(*renderLayer);
2084     }
2085
2086     for (auto* renderLayer : layer.normalFlowLayers())
2087         recursiveRepaintLayer(*renderLayer);
2088 }
2089
2090 RenderLayer& RenderLayerCompositor::rootRenderLayer() const
2091 {
2092     return *m_renderView.layer();
2093 }
2094
2095 GraphicsLayer* RenderLayerCompositor::rootGraphicsLayer() const
2096 {
2097     if (m_overflowControlsHostLayer)
2098         return m_overflowControlsHostLayer.get();
2099     return m_rootContentsLayer.get();
2100 }
2101
2102 void RenderLayerCompositor::setIsInWindow(bool isInWindow)
2103 {
2104     LOG(Compositing, "RenderLayerCompositor %p setIsInWindow %d", this, isInWindow);
2105
2106     if (!usesCompositing())
2107         return;
2108
2109     if (auto* rootLayer = rootGraphicsLayer()) {
2110         GraphicsLayer::traverse(*rootLayer, [isInWindow](GraphicsLayer& layer) {
2111             layer.setIsInWindow(isInWindow);
2112         });
2113     }
2114
2115     if (isInWindow) {
2116         if (m_rootLayerAttachment != RootLayerUnattached)
2117             return;
2118
2119         RootLayerAttachment attachment = isMainFrameCompositor() ? RootLayerAttachedViaChromeClient : RootLayerAttachedViaEnclosingFrame;
2120         attachRootLayer(attachment);
2121 #if PLATFORM(IOS_FAMILY)
2122         if (m_legacyScrollingLayerCoordinator) {
2123             m_legacyScrollingLayerCoordinator->registerAllViewportConstrainedLayers(*this);
2124             m_legacyScrollingLayerCoordinator->registerAllScrollingLayers();
2125         }
2126 #endif
2127     } else {
2128         if (m_rootLayerAttachment == RootLayerUnattached)
2129             return;
2130
2131         detachRootLayer();
2132 #if PLATFORM(IOS_FAMILY)
2133         if (m_legacyScrollingLayerCoordinator) {
2134             m_legacyScrollingLayerCoordinator->unregisterAllViewportConstrainedLayers();
2135             m_legacyScrollingLayerCoordinator->unregisterAllScrollingLayers();
2136         }
2137 #endif
2138     }
2139 }
2140
2141 void RenderLayerCompositor::clearBackingForLayerIncludingDescendants(RenderLayer& layer)
2142 {
2143     if (layer.isComposited())
2144         layer.clearBacking();
2145
2146     for (auto* childLayer = layer.firstChild(); childLayer; childLayer = childLayer->nextSibling())
2147         clearBackingForLayerIncludingDescendants(*childLayer);
2148 }
2149
2150 void RenderLayerCompositor::clearBackingForAllLayers()
2151 {
2152     clearBackingForLayerIncludingDescendants(*m_renderView.layer());
2153 }
2154
2155 void RenderLayerCompositor::updateRootLayerPosition()
2156 {
2157     if (m_rootContentsLayer) {
2158         m_rootContentsLayer->setSize(m_renderView.frameView().contentsSize());
2159         m_rootContentsLayer->setPosition(m_renderView.frameView().positionForRootContentLayer());
2160         m_rootContentsLayer->setAnchorPoint(FloatPoint3D());
2161     }
2162
2163     updateScrollLayerClipping();
2164
2165 #if ENABLE(RUBBER_BANDING)
2166     if (m_contentShadowLayer && m_rootContentsLayer) {
2167         m_contentShadowLayer->setPosition(m_rootContentsLayer->position());
2168         m_contentShadowLayer->setSize(m_rootContentsLayer->size());
2169     }
2170
2171     updateLayerForTopOverhangArea(m_layerForTopOverhangArea != nullptr);
2172     updateLayerForBottomOverhangArea(m_layerForBottomOverhangArea != nullptr);
2173     updateLayerForHeader(m_layerForHeader != nullptr);
2174     updateLayerForFooter(m_layerForFooter != nullptr);
2175 #endif
2176 }
2177
2178 bool RenderLayerCompositor::has3DContent() const
2179 {
2180     return layerHas3DContent(rootRenderLayer());
2181 }
2182
2183 bool RenderLayerCompositor::needsToBeComposited(const RenderLayer& layer, RequiresCompositingData& queryData) const
2184 {
2185     if (!canBeComposited(layer))
2186         return false;
2187
2188     return requiresCompositingLayer(layer, queryData) || layer.mustCompositeForIndirectReasons() || (usesCompositing() && layer.isRenderViewLayer());
2189 }
2190
2191 // Note: this specifies whether the RL needs a compositing layer for intrinsic reasons.
2192 // Use needsToBeComposited() to determine if a RL actually needs a compositing layer.
2193 // FIXME: is clipsCompositingDescendants() an intrinsic reason?
2194 bool RenderLayerCompositor::requiresCompositingLayer(const RenderLayer& layer, RequiresCompositingData& queryData) const
2195 {
2196     auto& renderer = rendererForCompositingTests(layer);
2197
2198     // The root layer always has a compositing layer, but it may not have backing.
2199     return requiresCompositingForTransform(renderer)
2200         || requiresCompositingForAnimation(renderer)
2201         || clipsCompositingDescendants(*renderer.layer())
2202         || requiresCompositingForPosition(renderer, *renderer.layer(), queryData)
2203         || requiresCompositingForCanvas(renderer)
2204         || requiresCompositingForFilters(renderer)
2205         || requiresCompositingForWillChange(renderer)
2206         || requiresCompositingForBackfaceVisibility(renderer)
2207         || requiresCompositingForVideo(renderer)
2208         || requiresCompositingForFrame(renderer, queryData)
2209         || requiresCompositingForPlugin(renderer, queryData)
2210         || requiresCompositingForEditableImage(renderer)
2211         || requiresCompositingForOverflowScrolling(*renderer.layer(), queryData);
2212 }
2213
2214 bool RenderLayerCompositor::canBeComposited(const RenderLayer& layer) const
2215 {
2216     if (m_hasAcceleratedCompositing && layer.isSelfPaintingLayer()) {
2217         if (!layer.isInsideFragmentedFlow())
2218             return true;
2219
2220         // CSS Regions flow threads do not need to be composited as we use composited RenderFragmentContainers
2221         // to render the background of the RenderFragmentedFlow.
2222         if (layer.isRenderFragmentedFlow())
2223             return false;
2224
2225         return true;
2226     }
2227     return false;
2228 }
2229
2230 #if ENABLE(FULLSCREEN_API)
2231 enum class FullScreenDescendant { Yes, No, NotApplicable };
2232 static FullScreenDescendant isDescendantOfFullScreenLayer(const RenderLayer& layer)
2233 {
2234     auto& document = layer.renderer().document();
2235
2236     if (!document.fullscreenManager().isFullscreen() || !document.fullscreenManager().fullscreenRenderer())
2237         return FullScreenDescendant::NotApplicable;
2238
2239     auto* fullScreenLayer = document.fullscreenManager().fullscreenRenderer()->layer();
2240     if (!fullScreenLayer) {
2241         ASSERT_NOT_REACHED();
2242         return FullScreenDescendant::NotApplicable;
2243     }
2244
2245     return layer.isDescendantOf(*fullScreenLayer) ? FullScreenDescendant::Yes : FullScreenDescendant::No;
2246 }
2247 #endif
2248
2249 bool RenderLayerCompositor::requiresOwnBackingStore(const RenderLayer& layer, const RenderLayer* compositingAncestorLayer, const LayoutRect& layerCompositedBoundsInAncestor, const LayoutRect& ancestorCompositedBounds) const
2250 {
2251     auto& renderer = layer.renderer();
2252
2253     if (compositingAncestorLayer
2254         && !(compositingAncestorLayer->backing()->graphicsLayer()->drawsContent()
2255             || compositingAncestorLayer->backing()->paintsIntoWindow()
2256             || compositingAncestorLayer->backing()->paintsIntoCompositedAncestor()))
2257         return true;
2258
2259     RequiresCompositingData queryData;
2260     if (layer.isRenderViewLayer()
2261         || layer.transform() // note: excludes perspective and transformStyle3D.
2262         || requiresCompositingForAnimation(renderer)
2263         || requiresCompositingForPosition(renderer, layer, queryData)
2264         || requiresCompositingForCanvas(renderer)
2265         || requiresCompositingForFilters(renderer)
2266         || requiresCompositingForWillChange(renderer)
2267         || requiresCompositingForBackfaceVisibility(renderer)
2268         || requiresCompositingForVideo(renderer)
2269         || requiresCompositingForFrame(renderer, queryData)
2270         || requiresCompositingForPlugin(renderer, queryData)
2271         || requiresCompositingForEditableImage(renderer)
2272         || requiresCompositingForOverflowScrolling(layer, queryData)
2273         || needsContentsCompositingLayer(layer)
2274         || renderer.isTransparent()
2275         || renderer.hasMask()
2276         || renderer.hasReflection()
2277         || renderer.hasFilter()
2278         || renderer.hasBackdropFilter())
2279         return true;
2280
2281     if (layer.mustCompositeForIndirectReasons()) {
2282         RenderLayer::IndirectCompositingReason reason = layer.indirectCompositingReason();
2283         return reason == RenderLayer::IndirectCompositingReason::Overlap
2284             || reason == RenderLayer::IndirectCompositingReason::OverflowScrollPositioning
2285             || reason == RenderLayer::IndirectCompositingReason::Stacking
2286             || reason == RenderLayer::IndirectCompositingReason::BackgroundLayer
2287             || reason == RenderLayer::IndirectCompositingReason::GraphicalEffect
2288             || reason == RenderLayer::IndirectCompositingReason::Preserve3D; // preserve-3d has to create backing store to ensure that 3d-transformed elements intersect.
2289     }
2290
2291     if (!ancestorCompositedBounds.contains(layerCompositedBoundsInAncestor))
2292         return true;
2293
2294     if (layer.isComposited() && layer.backing()->hasBackingSharingLayers())
2295         return true;
2296
2297     return false;
2298 }
2299
2300 OptionSet<CompositingReason> RenderLayerCompositor::reasonsForCompositing(const RenderLayer& layer) const
2301 {
2302     OptionSet<CompositingReason> reasons;
2303
2304     if (!layer.isComposited())
2305         return reasons;
2306
2307     RequiresCompositingData queryData;
2308
2309     auto& renderer = rendererForCompositingTests(layer);
2310
2311     if (requiresCompositingForTransform(renderer))
2312         reasons.add(CompositingReason::Transform3D);
2313
2314     if (requiresCompositingForVideo(renderer))
2315         reasons.add(CompositingReason::Video);
2316     else if (requiresCompositingForCanvas(renderer))
2317         reasons.add(CompositingReason::Canvas);
2318     else if (requiresCompositingForPlugin(renderer, queryData))
2319         reasons.add(CompositingReason::Plugin);
2320     else if (requiresCompositingForFrame(renderer, queryData))
2321         reasons.add(CompositingReason::IFrame);
2322     else if (requiresCompositingForEditableImage(renderer))
2323         reasons.add(CompositingReason::EmbeddedView);
2324
2325     if ((canRender3DTransforms() && renderer.style().backfaceVisibility() == BackfaceVisibility::Hidden))
2326         reasons.add(CompositingReason::BackfaceVisibilityHidden);
2327
2328     if (clipsCompositingDescendants(*renderer.layer()))
2329         reasons.add(CompositingReason::ClipsCompositingDescendants);
2330
2331     if (requiresCompositingForAnimation(renderer))
2332         reasons.add(CompositingReason::Animation);
2333
2334     if (requiresCompositingForFilters(renderer))
2335         reasons.add(CompositingReason::Filters);
2336
2337     if (requiresCompositingForWillChange(renderer))
2338         reasons.add(CompositingReason::WillChange);
2339
2340     if (requiresCompositingForPosition(renderer, *renderer.layer(), queryData))
2341         reasons.add(renderer.isFixedPositioned() ? CompositingReason::PositionFixed : CompositingReason::PositionSticky);
2342
2343     if (requiresCompositingForOverflowScrolling(*renderer.layer(), queryData))
2344         reasons.add(CompositingReason::OverflowScrolling);
2345
2346     switch (renderer.layer()->indirectCompositingReason()) {
2347     case RenderLayer::IndirectCompositingReason::None:
2348         break;
2349     case RenderLayer::IndirectCompositingReason::Stacking:
2350         reasons.add(CompositingReason::Stacking);
2351         break;
2352     case RenderLayer::IndirectCompositingReason::OverflowScrollPositioning:
2353         reasons.add(CompositingReason::OverflowScrollPositioning);
2354         break;
2355     case RenderLayer::IndirectCompositingReason::Overlap:
2356         reasons.add(CompositingReason::Overlap);
2357         break;
2358     case RenderLayer::IndirectCompositingReason::BackgroundLayer:
2359         reasons.add(CompositingReason::NegativeZIndexChildren);
2360         break;
2361     case RenderLayer::IndirectCompositingReason::GraphicalEffect:
2362         if (renderer.hasTransform())
2363             reasons.add(CompositingReason::TransformWithCompositedDescendants);
2364
2365         if (renderer.isTransparent())
2366             reasons.add(CompositingReason::OpacityWithCompositedDescendants);
2367
2368         if (renderer.hasMask())
2369             reasons.add(CompositingReason::MaskWithCompositedDescendants);
2370
2371         if (renderer.hasReflection())
2372             reasons.add(CompositingReason::ReflectionWithCompositedDescendants);
2373
2374         if (renderer.hasFilter() || renderer.hasBackdropFilter())
2375             reasons.add(CompositingReason::FilterWithCompositedDescendants);
2376
2377 #if ENABLE(CSS_COMPOSITING)
2378         if (layer.isolatesCompositedBlending())
2379             reasons.add(CompositingReason::IsolatesCompositedBlendingDescendants);
2380
2381         if (layer.hasBlendMode())
2382             reasons.add(CompositingReason::BlendingWithCompositedDescendants);
2383 #endif
2384         break;
2385     case RenderLayer::IndirectCompositingReason::Perspective:
2386         reasons.add(CompositingReason::Perspective);
2387         break;
2388     case RenderLayer::IndirectCompositingReason::Preserve3D:
2389         reasons.add(CompositingReason::Preserve3D);
2390         break;
2391     }
2392
2393     if (usesCompositing() && renderer.layer()->isRenderViewLayer())
2394         reasons.add(CompositingReason::Root);
2395
2396     return reasons;
2397 }
2398
2399 #if !LOG_DISABLED
2400 const char* RenderLayerCompositor::logReasonsForCompositing(const RenderLayer& layer)
2401 {
2402     OptionSet<CompositingReason> reasons = reasonsForCompositing(layer);
2403
2404     if (reasons & CompositingReason::Transform3D)
2405         return "3D transform";
2406
2407     if (reasons & CompositingReason::Video)
2408         return "video";
2409
2410     if (reasons & CompositingReason::Canvas)
2411         return "canvas";
2412
2413     if (reasons & CompositingReason::Plugin)
2414         return "plugin";
2415
2416     if (reasons & CompositingReason::IFrame)
2417         return "iframe";
2418
2419     if (reasons & CompositingReason::BackfaceVisibilityHidden)
2420         return "backface-visibility: hidden";
2421
2422     if (reasons & CompositingReason::ClipsCompositingDescendants)
2423         return "clips compositing descendants";
2424
2425     if (reasons & CompositingReason::Animation)
2426         return "animation";
2427
2428     if (reasons & CompositingReason::Filters)
2429         return "filters";
2430
2431     if (reasons & CompositingReason::PositionFixed)
2432         return "position: fixed";
2433
2434     if (reasons & CompositingReason::PositionSticky)
2435         return "position: sticky";
2436
2437     if (reasons & CompositingReason::OverflowScrolling)
2438         return "async overflow scrolling";
2439
2440     if (reasons & CompositingReason::Stacking)
2441         return "stacking";
2442
2443     if (reasons & CompositingReason::Overlap)
2444         return "overlap";
2445
2446     if (reasons & CompositingReason::NegativeZIndexChildren)
2447         return "negative z-index children";
2448
2449     if (reasons & CompositingReason::TransformWithCompositedDescendants)
2450         return "transform with composited descendants";
2451
2452     if (reasons & CompositingReason::OpacityWithCompositedDescendants)
2453         return "opacity with composited descendants";
2454
2455     if (reasons & CompositingReason::MaskWithCompositedDescendants)
2456         return "mask with composited descendants";
2457
2458     if (reasons & CompositingReason::ReflectionWithCompositedDescendants)
2459         return "reflection with composited descendants";
2460
2461     if (reasons & CompositingReason::FilterWithCompositedDescendants)
2462         return "filter with composited descendants";
2463
2464 #if ENABLE(CSS_COMPOSITING)
2465     if (reasons & CompositingReason::BlendingWithCompositedDescendants)
2466         return "blending with composited descendants";
2467
2468     if (reasons & CompositingReason::IsolatesCompositedBlendingDescendants)
2469         return "isolates composited blending descendants";
2470 #endif
2471
2472     if (reasons & CompositingReason::Perspective)
2473         return "perspective";
2474
2475     if (reasons & CompositingReason::Preserve3D)
2476         return "preserve-3d";
2477
2478     if (reasons & CompositingReason::Root)
2479         return "root";
2480
2481     return "";
2482 }
2483 #endif
2484
2485 // Return true if the given layer has some ancestor in the RenderLayer hierarchy that clips,
2486 // up to the enclosing compositing ancestor. This is required because compositing layers are parented
2487 // according to the z-order hierarchy, yet clipping goes down the renderer hierarchy.
2488 // Thus, a RenderLayer can be clipped by a RenderLayer that is an ancestor in the renderer hierarchy,
2489 // but a sibling in the z-order hierarchy.
2490 // FIXME: can we do this without a tree walk?
2491 bool RenderLayerCompositor::clippedByAncestor(RenderLayer& layer) const
2492 {
2493     ASSERT(layer.isComposited());
2494     if (!layer.parent())
2495         return false;
2496
2497     // On first pass in WK1, the root may not have become composited yet.
2498     auto* compositingAncestor = layer.ancestorCompositingLayer();
2499     if (!compositingAncestor)
2500         return false;
2501
2502     // If the compositingAncestor clips, that will be taken care of by clipsCompositingDescendants(),
2503     // so we only care about clipping between its first child that is our ancestor (the computeClipRoot),
2504     // and layer. The exception is when the compositingAncestor isolates composited blending children,
2505     // in this case it is not allowed to clipsCompositingDescendants() and each of its children
2506     // will be clippedByAncestor()s, including the compositingAncestor.
2507     auto* computeClipRoot = compositingAncestor;
2508     if (!compositingAncestor->isolatesCompositedBlending()) {
2509         computeClipRoot = nullptr;
2510         auto* parent = &layer;
2511         while (parent) {
2512             auto* next = parent->parent();
2513             if (next == compositingAncestor) {
2514                 computeClipRoot = parent;
2515                 break;
2516             }
2517             parent = next;
2518         }
2519
2520         if (!computeClipRoot || computeClipRoot == &layer)
2521             return false;
2522     }
2523
2524     return !layer.backgroundClipRect(RenderLayer::ClipRectsContext(computeClipRoot, TemporaryClipRects)).isInfinite(); // FIXME: Incorrect for CSS regions.
2525 }
2526
2527 // Return true if the given layer is a stacking context and has compositing child
2528 // layers that it needs to clip. In this case we insert a clipping GraphicsLayer
2529 // into the hierarchy between this layer and its children in the z-order hierarchy.
2530 bool RenderLayerCompositor::clipsCompositingDescendants(const RenderLayer& layer) const
2531 {
2532     return layer.hasCompositingDescendant() && layer.renderer().hasClipOrOverflowClip() && !layer.isolatesCompositedBlending();
2533 }
2534
2535 bool RenderLayerCompositor::requiresCompositingForAnimation(RenderLayerModelObject& renderer) const
2536 {
2537     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
2538         return false;
2539
2540     if (auto* element = renderer.element()) {
2541         if (auto* timeline = element->document().existingTimeline()) {
2542             if (timeline->runningAnimationsForElementAreAllAccelerated(*element))
2543                 return true;
2544         }
2545     }
2546
2547     if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled())
2548         return false;
2549
2550     auto& animController = renderer.animation();
2551     return (animController.isRunningAnimationOnRenderer(renderer, CSSPropertyOpacity)
2552         && (usesCompositing() || (m_compositingTriggers & ChromeClient::AnimatedOpacityTrigger)))
2553         || animController.isRunningAnimationOnRenderer(renderer, CSSPropertyFilter)
2554 #if ENABLE(FILTERS_LEVEL_2)
2555         || animController.isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitBackdropFilter)
2556 #endif
2557         || animController.isRunningAnimationOnRenderer(renderer, CSSPropertyTransform);
2558 }
2559
2560 bool RenderLayerCompositor::requiresCompositingForTransform(RenderLayerModelObject& renderer) const
2561 {
2562     if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
2563         return false;
2564
2565     // Note that we ask the renderer if it has a transform, because the style may have transforms,
2566     // but the renderer may be an inline that doesn't suppport them.
2567     if (!renderer.hasTransform())
2568         return false;
2569     
2570     switch (m_compositingPolicy) {
2571     case CompositingPolicy::Normal:
2572         return renderer.style().transform().has3DOperation();
2573     case CompositingPolicy::Conservative:
2574         // Continue to allow pages to avoid the very slow software filter path.
2575         if (renderer.style().transform().has3DOperation() && renderer.hasFilter())
2576             return true;
2577         return renderer.style().transform().isRepresentableIn2D() ? false : true;
2578     }
2579     return false;
2580 }
2581
2582 bool RenderLayerCompositor::requiresCompositingForBackfaceVisibility(RenderLayerModelObject& renderer) const
2583 {
2584     if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
2585         return false;
2586
2587     if (renderer.style().backfaceVisibility() != BackfaceVisibility::Hidden)
2588         return false;
2589
2590     if (renderer.layer()->has3DTransformedAncestor())
2591         return true;
2592     
2593     // FIXME: workaround for webkit.org/b/132801
2594     auto* stackingContext = renderer.layer()->stackingContext();
2595     if (stackingContext && stackingContext->renderer().style().transformStyle3D() == TransformStyle3D::Preserve3D)
2596         return true;
2597
2598     return false;
2599 }
2600
2601 bool RenderLayerCompositor::requiresCompositingForVideo(RenderLayerModelObject& renderer) const
2602 {
2603     if (!(m_compositingTriggers & ChromeClient::VideoTrigger))
2604         return false;
2605
2606 #if ENABLE(VIDEO)
2607     if (!is<RenderVideo>(renderer))
2608         return false;
2609
2610     auto& video = downcast<RenderVideo>(renderer);
2611     if ((video.requiresImmediateCompositing() || video.shouldDisplayVideo()) && canAccelerateVideoRendering(video))
2612         return true;
2613 #else
2614     UNUSED_PARAM(renderer);
2615 #endif
2616     return false;
2617 }
2618
2619 bool RenderLayerCompositor::requiresCompositingForCanvas(RenderLayerModelObject& renderer) const
2620 {
2621     if (!(m_compositingTriggers & ChromeClient::CanvasTrigger))
2622         return false;
2623
2624     if (!renderer.isCanvas())
2625         return false;
2626
2627     bool isCanvasLargeEnoughToForceCompositing = true;
2628 #if !USE(COMPOSITING_FOR_SMALL_CANVASES)
2629     auto* canvas = downcast<HTMLCanvasElement>(renderer.element());
2630     auto canvasArea = canvas->size().area<RecordOverflow>();
2631     isCanvasLargeEnoughToForceCompositing = !canvasArea.hasOverflowed() && canvasArea.unsafeGet() >= canvasAreaThresholdRequiringCompositing;
2632 #endif
2633
2634     CanvasCompositingStrategy compositingStrategy = canvasCompositingStrategy(renderer);
2635     if (compositingStrategy == CanvasAsLayerContents)
2636         return true;
2637
2638     if (m_compositingPolicy == CompositingPolicy::Normal)
2639         return compositingStrategy == CanvasPaintedToLayer && isCanvasLargeEnoughToForceCompositing;
2640
2641     return false;
2642 }
2643
2644 bool RenderLayerCompositor::requiresCompositingForFilters(RenderLayerModelObject& renderer) const
2645 {
2646 #if ENABLE(FILTERS_LEVEL_2)
2647     if (renderer.hasBackdropFilter())
2648         return true;
2649 #endif
2650
2651     if (!(m_compositingTriggers & ChromeClient::FilterTrigger))
2652         return false;
2653
2654     return renderer.hasFilter();
2655 }
2656
2657 bool RenderLayerCompositor::requiresCompositingForWillChange(RenderLayerModelObject& renderer) const
2658 {
2659     if (!renderer.style().willChange() || !renderer.style().willChange()->canTriggerCompositing())
2660         return false;
2661
2662 #if ENABLE(FULLSCREEN_API)
2663     // FIXME: does this require layout?
2664     if (renderer.layer() && isDescendantOfFullScreenLayer(*renderer.layer()) == FullScreenDescendant::No)
2665         return false;
2666 #endif
2667
2668     if (m_compositingPolicy == CompositingPolicy::Conservative)
2669         return false;
2670
2671     if (is<RenderBox>(renderer))
2672         return true;
2673
2674     return renderer.style().willChange()->canTriggerCompositingOnInline();
2675 }
2676
2677 bool RenderLayerCompositor::requiresCompositingForPlugin(RenderLayerModelObject& renderer, RequiresCompositingData& queryData) const
2678 {
2679     if (!(m_compositingTriggers & ChromeClient::PluginTrigger))
2680         return false;
2681
2682     bool isCompositedPlugin = is<RenderEmbeddedObject>(renderer) && downcast<RenderEmbeddedObject>(renderer).allowsAcceleratedCompositing();
2683     if (!isCompositedPlugin)
2684         return false;
2685
2686     auto& pluginRenderer = downcast<RenderWidget>(renderer);
2687     if (pluginRenderer.style().visibility() != Visibility::Visible)
2688         return false;
2689
2690     // If we can't reliably know the size of the plugin yet, don't change compositing state.
2691     if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2692         queryData.reevaluateAfterLayout = true;
2693         return pluginRenderer.isComposited();
2694     }
2695
2696     // Don't go into compositing mode if height or width are zero, or size is 1x1.
2697     IntRect contentBox = snappedIntRect(pluginRenderer.contentBoxRect());
2698     return (contentBox.height() * contentBox.width() > 1);
2699 }
2700     
2701 bool RenderLayerCompositor::requiresCompositingForEditableImage(RenderLayerModelObject& renderer) const
2702 {
2703     if (!renderer.isRenderImage())
2704         return false;
2705
2706     auto& image = downcast<RenderImage>(renderer);
2707     if (!image.isEditableImage())
2708         return false;
2709
2710     return true;
2711 }
2712
2713 bool RenderLayerCompositor::requiresCompositingForFrame(RenderLayerModelObject& renderer, RequiresCompositingData& queryData) const
2714 {
2715     if (!is<RenderWidget>(renderer))
2716         return false;
2717
2718     auto& frameRenderer = downcast<RenderWidget>(renderer);
2719     if (frameRenderer.style().visibility() != Visibility::Visible)
2720         return false;
2721
2722     if (!frameRenderer.requiresAcceleratedCompositing())
2723         return false;
2724
2725     if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2726         queryData.reevaluateAfterLayout = true;
2727         return frameRenderer.isComposited();
2728     }
2729
2730     // Don't go into compositing mode if height or width are zero.
2731     return !snappedIntRect(frameRenderer.contentBoxRect()).isEmpty();
2732 }
2733
2734 bool RenderLayerCompositor::requiresCompositingForScrollableFrame(RequiresCompositingData& queryData) const
2735 {
2736     if (isMainFrameCompositor())
2737         return false;
2738
2739 #if PLATFORM(MAC) || PLATFORM(IOS_FAMILY)
2740     if (!m_renderView.settings().asyncFrameScrollingEnabled())
2741         return false;
2742 #endif
2743
2744     if (!(m_compositingTriggers & ChromeClient::ScrollableNonMainFrameTrigger))
2745         return false;
2746
2747     if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2748         queryData.reevaluateAfterLayout = true;
2749         return m_renderView.isComposited();
2750     }
2751
2752     return m_renderView.frameView().isScrollable();
2753 }
2754
2755 bool RenderLayerCompositor::requiresCompositingForPosition(RenderLayerModelObject& renderer, const RenderLayer& layer, RequiresCompositingData& queryData) const
2756 {
2757     // position:fixed elements that create their own stacking context (e.g. have an explicit z-index,
2758     // opacity, transform) can get their own composited layer. A stacking context is required otherwise
2759     // z-index and clipping will be broken.
2760     if (!renderer.isPositioned())
2761         return false;
2762     
2763 #if ENABLE(FULLSCREEN_API)
2764     if (isDescendantOfFullScreenLayer(layer) == FullScreenDescendant::No)
2765         return false;
2766 #endif
2767
2768     auto position = renderer.style().position();
2769     bool isFixed = renderer.isFixedPositioned();
2770     if (isFixed && !layer.isStackingContext())
2771         return false;
2772     
2773     bool isSticky = renderer.isInFlowPositioned() && position == PositionType::Sticky;
2774     if (!isFixed && !isSticky)
2775         return false;
2776
2777     // FIXME: acceleratedCompositingForFixedPositionEnabled should probably be renamed acceleratedCompositingForViewportConstrainedPositionEnabled().
2778     if (!m_renderView.settings().acceleratedCompositingForFixedPositionEnabled())
2779         return false;
2780
2781     if (isSticky)
2782         return isAsyncScrollableStickyLayer(layer);
2783
2784     if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2785         queryData.reevaluateAfterLayout = true;
2786         return layer.isComposited();
2787     }
2788
2789     auto container = renderer.container();
2790     ASSERT(container);
2791
2792     // Don't promote fixed position elements that are descendants of a non-view container, e.g. transformed elements.
2793     // They will stay fixed wrt the container rather than the enclosing frame.j
2794     if (container != &m_renderView) {
2795         queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForNonViewContainer;
2796         return false;
2797     }
2798
2799     bool paintsContent = layer.isVisuallyNonEmpty() || layer.hasVisibleDescendant();
2800     if (!paintsContent) {
2801         queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForNoVisibleContent;
2802         return false;
2803     }
2804
2805     bool intersectsViewport = fixedLayerIntersectsViewport(layer);
2806     if (!intersectsViewport) {
2807         queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForBoundsOutOfView;
2808         LOG_WITH_STREAM(Compositing, stream << "Layer " << &layer << " is outside the viewport");
2809         return false;
2810     }
2811
2812     return true;
2813 }
2814
2815 bool RenderLayerCompositor::requiresCompositingForOverflowScrolling(const RenderLayer& layer, RequiresCompositingData& queryData) const
2816 {
2817     if (!layer.canUseCompositedScrolling())
2818         return false;
2819
2820     if (queryData.layoutUpToDate == LayoutUpToDate::No) {
2821         queryData.reevaluateAfterLayout = true;
2822         return layer.isComposited();
2823     }
2824
2825     return layer.hasCompositedScrollableOverflow();
2826 }
2827
2828 // FIXME: why doesn't this handle the clipping cases?
2829 bool RenderLayerCompositor::requiresCompositingForIndirectReason(const RenderLayer& layer, const RenderLayer* compositingAncestor, bool hasCompositedDescendants, bool has3DTransformedDescendants, bool paintsIntoProvidedBacking, RenderLayer::IndirectCompositingReason& reason) const
2830 {
2831     // When a layer has composited descendants, some effects, like 2d transforms, filters, masks etc must be implemented
2832     // via compositing so that they also apply to those composited descendants.
2833     auto& renderer = layer.renderer();
2834     if (hasCompositedDescendants && (layer.isolatesCompositedBlending() || layer.transform() || renderer.createsGroup() || renderer.hasReflection())) {
2835         reason = RenderLayer::IndirectCompositingReason::GraphicalEffect;
2836         return true;
2837     }
2838
2839     // A layer with preserve-3d or perspective only needs to be composited if there are descendant layers that
2840     // will be affected by the preserve-3d or perspective.
2841     if (has3DTransformedDescendants) {
2842         if (renderer.style().transformStyle3D() == TransformStyle3D::Preserve3D) {
2843             reason = RenderLayer::IndirectCompositingReason::Preserve3D;
2844             return true;
2845         }
2846     
2847         if (renderer.style().hasPerspective()) {
2848             reason = RenderLayer::IndirectCompositingReason::Perspective;
2849             return true;
2850         }
2851     }
2852
2853     if (!paintsIntoProvidedBacking && renderer.isAbsolutelyPositioned() && compositingAncestor && layer.hasCompositedScrollingAncestor()) {
2854         if (layerContainingBlockCrossesCoordinatedScrollingBoundary(layer, *compositingAncestor)) {
2855             reason = RenderLayer::IndirectCompositingReason::OverflowScrollPositioning;
2856             return true;
2857         }
2858     }
2859
2860     reason = RenderLayer::IndirectCompositingReason::None;
2861     return false;
2862 }
2863
2864 bool RenderLayerCompositor::styleChangeMayAffectIndirectCompositingReasons(const RenderStyle& oldStyle, const RenderStyle& newStyle)
2865 {
2866     if (RenderElement::createsGroupForStyle(newStyle) != RenderElement::createsGroupForStyle(oldStyle))
2867         return true;
2868     if (newStyle.isolation() != oldStyle.isolation())
2869         return true;
2870     if (newStyle.hasTransform() != oldStyle.hasTransform())
2871         return true;
2872     if (newStyle.boxReflect() != oldStyle.boxReflect())
2873         return true;
2874     if (newStyle.transformStyle3D() != oldStyle.transformStyle3D())
2875         return true;
2876     if (newStyle.hasPerspective() != oldStyle.hasPerspective())
2877         return true;
2878
2879     return false;
2880 }
2881
2882 bool RenderLayerCompositor::isAsyncScrollableStickyLayer(const RenderLayer& layer, const RenderLayer** enclosingAcceleratedOverflowLayer) const
2883 {
2884     ASSERT(layer.renderer().isStickilyPositioned());
2885
2886     auto* enclosingOverflowLayer = layer.enclosingOverflowClipLayer(ExcludeSelf);
2887
2888     if (enclosingOverflowLayer && enclosingOverflowLayer->hasCompositedScrollableOverflow()) {
2889         if (enclosingAcceleratedOverflowLayer)
2890             *enclosingAcceleratedOverflowLayer = enclosingOverflowLayer;
2891         return true;
2892     }
2893
2894     // If the layer is inside normal overflow, it's not async-scrollable.
2895     if (enclosingOverflowLayer)
2896         return false;
2897
2898     // No overflow ancestor, so see if the frame supports async scrolling.
2899     if (hasCoordinatedScrolling())
2900         return true;
2901
2902 #if PLATFORM(IOS_FAMILY)
2903     // iOS WK1 has fixed/sticky support in the main frame via WebFixedPositionContent.
2904     return isMainFrameCompositor();
2905 #else
2906     return false;
2907 #endif
2908 }
2909
2910 bool RenderLayerCompositor::isViewportConstrainedFixedOrStickyLayer(const RenderLayer& layer) const
2911 {
2912     if (layer.renderer().isStickilyPositioned())
2913         return isAsyncScrollableStickyLayer(layer);
2914
2915     if (!layer.renderer().isFixedPositioned())
2916         return false;
2917
2918     // FIXME: Handle fixed inside of a transform, which should not behave as fixed.
2919     for (auto* stackingContext = layer.stackingContext(); stackingContext; stackingContext = stackingContext->stackingContext()) {
2920         if (stackingContext->isComposited() && stackingContext->renderer().isFixedPositioned())
2921             return false;
2922     }
2923
2924     return true;
2925 }
2926
2927 bool RenderLayerCompositor::fixedLayerIntersectsViewport(const RenderLayer& layer) const
2928 {
2929     ASSERT(layer.renderer().isFixedPositioned());
2930
2931     // Fixed position elements that are invisible in the current view don't get their own layer.
2932     // FIXME: We shouldn't have to check useFixedLayout() here; one of the viewport rects needs to give the correct answer.
2933     LayoutRect viewBounds;
2934     if (m_renderView.frameView().useFixedLayout())
2935         viewBounds = m_renderView.unscaledDocumentRect();
2936     else
2937         viewBounds = m_renderView.frameView().rectForFixedPositionLayout();
2938
2939     LayoutRect layerBounds = layer.calculateLayerBounds(&layer, LayoutSize(), { RenderLayer::UseLocalClipRectIfPossible, RenderLayer::IncludeFilterOutsets, RenderLayer::UseFragmentBoxesExcludingCompositing,
2940         RenderLayer::ExcludeHiddenDescendants, RenderLayer::DontConstrainForMask, RenderLayer::IncludeCompositedDescendants });
2941     // Map to m_renderView to ignore page scale.
2942     FloatRect absoluteBounds = layer.renderer().localToContainerQuad(FloatRect(layerBounds), &m_renderView).boundingBox();
2943     return viewBounds.intersects(enclosingIntRect(absoluteBounds));
2944 }
2945
2946 bool RenderLayerCompositor::useCoordinatedScrollingForLayer(const RenderLayer& layer) const
2947 {
2948     if (layer.isRenderViewLayer() && hasCoordinatedScrolling())
2949         return true;
2950
2951     if (auto* scrollingCoordinator = this->scrollingCoordinator())
2952         return scrollingCoordinator->coordinatesScrollingForOverflowLayer(layer);
2953
2954     return false;
2955 }
2956
2957 static RenderLayer* enclosingCompositedScrollingLayer(const RenderLayer& layer, const RenderLayer& intermediateLayer, bool& sawIntermediateLayer)
2958 {
2959     const auto* currLayer = &layer;
2960     while (currLayer) {
2961         if (currLayer == &intermediateLayer)
2962             sawIntermediateLayer = true;
2963
2964         if (currLayer->hasCompositedScrollableOverflow())
2965             return const_cast<RenderLayer*>(currLayer);
2966
2967         currLayer = currLayer->parent();
2968     }
2969
2970     return nullptr;
2971 }
2972
2973 // Return true if overflowScrollLayer is in layer's containing block chain.
2974 static bool isScrolledByOverflowScrollLayer(const RenderLayer& layer, const RenderLayer& overflowScrollLayer)
2975 {
2976     bool containingBlockCanSkipLayers = layer.renderer().isAbsolutelyPositioned();
2977
2978     for (const auto* currLayer = layer.parent(); currLayer; currLayer = currLayer->parent()) {
2979         bool inContainingBlockChain = true;
2980         if (containingBlockCanSkipLayers) {
2981             inContainingBlockChain = currLayer->renderer().canContainAbsolutelyPositionedObjects();
2982             if (inContainingBlockChain)
2983                 containingBlockCanSkipLayers = currLayer->renderer().isAbsolutelyPositioned();
2984         }
2985
2986         if (currLayer == &overflowScrollLayer)
2987             return inContainingBlockChain;
2988     }
2989
2990     return false;
2991 }
2992
2993 static bool isNonScrolledLayerInsideScrolledCompositedAncestor(const RenderLayer& layer, const RenderLayer& compositedAncestor, const RenderLayer& scrollingAncestor)
2994 {
2995     bool ancestorMovedByScroller = &compositedAncestor == &scrollingAncestor || isScrolledByOverflowScrollLayer(compositedAncestor, scrollingAncestor);
2996     bool layerMovedByScroller = isScrolledByOverflowScrollLayer(layer, scrollingAncestor);
2997
2998     return ancestorMovedByScroller && !layerMovedByScroller;
2999 }
3000
3001 bool RenderLayerCompositor::layerContainingBlockCrossesCoordinatedScrollingBoundary(const RenderLayer& layer, const RenderLayer& compositedAncestor)
3002 {
3003     bool compositedAncestorIsInsideScroller = false;
3004     auto* scrollingAncestor = enclosingCompositedScrollingLayer(layer, compositedAncestor, compositedAncestorIsInsideScroller);
3005     if (!scrollingAncestor) {
3006         ASSERT_NOT_REACHED(); // layer.hasCompositedScrollingAncestor() should guarantee we have one.
3007         return false;
3008     }
3009     
3010     if (!compositedAncestorIsInsideScroller)
3011         return false;
3012
3013     return isNonScrolledLayerInsideScrolledCompositedAncestor(layer, compositedAncestor, *scrollingAncestor);
3014 }
3015
3016 static void collectStationaryLayerRelatedOverflowNodes(const RenderLayer& layer, const RenderLayer& /*compositedAncestor*/, Vector<ScrollingNodeID>& scrollingNodes)
3017 {
3018     ASSERT(layer.isComposited());
3019     
3020     auto appendOverflowLayerNodeID = [&scrollingNodes] (const RenderLayer& overflowLayer) {
3021         ASSERT(overflowLayer.isComposited());
3022         auto scrollingNodeID = overflowLayer.backing()->scrollingNodeIDForRole(ScrollCoordinationRole::Scrolling);
3023         if (scrollingNodeID)
3024             scrollingNodes.append(scrollingNodeID);
3025         else
3026             LOG(Scrolling, "Layer %p doesn't have scrolling node ID yet", &overflowLayer);
3027     };
3028
3029     ASSERT(layer.renderer().isAbsolutelyPositioned());
3030     bool containingBlockCanSkipLayers = true;
3031
3032     for (const auto* currLayer = layer.parent(); currLayer; currLayer = currLayer->parent()) {
3033         bool inContainingBlockChain = true;
3034         if (containingBlockCanSkipLayers) {
3035             inContainingBlockChain = currLayer->renderer().canContainAbsolutelyPositionedObjects();
3036             if (inContainingBlockChain)
3037                 containingBlockCanSkipLayers = currLayer->renderer().isAbsolutelyPositioned();
3038         }
3039
3040         if (currLayer->hasCompositedScrollableOverflow()) {
3041             appendOverflowLayerNodeID(*currLayer);
3042             break;
3043         }
3044     }
3045 }
3046
3047
3048 ScrollPositioningBehavior RenderLayerCompositor::computeCoordinatedPositioningForLayer(const RenderLayer& layer) const
3049 {
3050     if (layer.isRenderViewLayer())
3051         return ScrollPositioningBehavior::None;
3052
3053     if (layer.renderer().isFixedPositioned())
3054         return ScrollPositioningBehavior::None;
3055     
3056     if (!layer.hasCompositedScrollingAncestor())
3057         return ScrollPositioningBehavior::None;
3058
3059     auto* scrollingCoordinator = this->scrollingCoordinator();
3060     if (!scrollingCoordinator)
3061         return ScrollPositioningBehavior::None;
3062
3063     auto* compositedAncestor = layer.ancestorCompositingLayer();
3064     if (!compositedAncestor) {
3065         ASSERT_NOT_REACHED();
3066         return ScrollPositioningBehavior::None;
3067     }
3068
3069     bool compositedAncestorIsInsideScroller = false;
3070     auto* scrollingAncestor = enclosingCompositedScrollingLayer(layer, *compositedAncestor, compositedAncestorIsInsideScroller);
3071     if (!scrollingAncestor) {
3072         ASSERT_NOT_REACHED(); // layer.hasCompositedScrollingAncestor() should guarantee we have one.
3073         return ScrollPositioningBehavior::None;
3074     }
3075
3076     // There are two cases we have to deal with here:
3077     // 1. There's a composited overflow:scroll in the parent chain between the renderer and its containing block, and the layer's
3078     //    composited (z-order) ancestor is inside the scroller or is the scroller. In this case, we have to compensate for scroll position
3079     //    changes to make the positioned layer stay in the same place. This only applies to position:absolute (since we handle fixed elsewhere).
3080     if (layer.renderer().isAbsolutelyPositioned()) {
3081         if (compositedAncestorIsInsideScroller && isNonScrolledLayerInsideScrolledCompositedAncestor(layer, *compositedAncestor, *scrollingAncestor))
3082             return ScrollPositioningBehavior::Stationary;
3083     }
3084
3085     // 2. The layer's containing block is the overflow or inside the overflow:scroll, but its z-order ancestor is
3086     //    outside the overflow:scroll. In that case, we have to move the layer via the scrolling tree to make
3087     //    it move along with the overflow scrolling.
3088     if (!compositedAncestorIsInsideScroller && isScrolledByOverflowScrollLayer(layer, *scrollingAncestor))
3089         return ScrollPositioningBehavior::Moves;
3090
3091     return ScrollPositioningBehavior::None;
3092 }
3093
3094 static Vector<ScrollingNodeID> collectRelatedCoordinatedScrollingNodes(const RenderLayer& layer, ScrollPositioningBehavior positioningBehavior)
3095 {
3096     Vector<ScrollingNodeID> overflowNodeData;
3097
3098     switch (positioningBehavior) {
3099     case ScrollPositioningBehavior::Moves: {
3100         // Collect all the composited scrollers between this layer and its composited ancestor.
3101         auto* compositedAncestor = layer.ancestorCompositingLayer();
3102         for (const auto* currLayer = layer.parent(); currLayer != compositedAncestor; currLayer = currLayer->parent()) {
3103             if (currLayer->hasCompositedScrollableOverflow()) {
3104                 auto scrollingNodeID = currLayer->isComposited() ? currLayer->backing()->scrollingNodeIDForRole(ScrollCoordinationRole::Scrolling) : 0;
3105                 if (scrollingNodeID)
3106                     overflowNodeData.append(scrollingNodeID);
3107                 else
3108                     LOG(Scrolling, "Layer %p isn't composited or doesn't have scrolling node ID yet", &layer);
3109             }
3110         }
3111         break;
3112     }
3113     case ScrollPositioningBehavior::Stationary: {
3114         ASSERT(layer.renderer().isAbsolutelyPositioned());
3115         // Collect all the composited scrollers between this layer and its composited ancestor.
3116         auto* compositedAncestor = layer.ancestorCompositingLayer();
3117         if (!compositedAncestor)
3118             return overflowNodeData;
3119         collectStationaryLayerRelatedOverflowNodes(layer, *compositedAncestor, overflowNodeData);
3120         break;
3121     }
3122     case ScrollPositioningBehavior::None:
3123         ASSERT_NOT_REACHED();
3124         break;
3125     }
3126
3127     return overflowNodeData;
3128 }
3129
3130 bool RenderLayerCompositor::isLayerForIFrameWithScrollCoordinatedContents(const RenderLayer& layer) const
3131 {
3132     if (!is<RenderWidget>(layer.renderer()))
3133         return false;
3134
3135     auto* contentDocument = downcast<RenderWidget>(layer.renderer()).frameOwnerElement().contentDocument();
3136     if (!contentDocument)
3137         return false;
3138
3139     auto* view = contentDocument->renderView();
3140     if (!view)
3141         return false;
3142
3143     if (auto* scrollingCoordinator = this->scrollingCoordinator())
3144         return scrollingCoordinator->coordinatesScrollingForFrameView(view->frameView());
3145
3146     return false;
3147 }
3148
3149 bool RenderLayerCompositor::isRunningTransformAnimation(RenderLayerModelObject& renderer) const
3150 {
3151     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
3152         return false;
3153
3154     if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled()) {
3155         if (auto* element = renderer.element()) {
3156             if (auto* timeline = element->document().existingTimeline())
3157                 return timeline->isRunningAnimationOnRenderer(renderer, CSSPropertyTransform);
3158         }
3159         return false;
3160     }
3161     return renderer.animation().isRunningAnimationOnRenderer(renderer, CSSPropertyTransform);
3162 }
3163
3164 // If an element has negative z-index children, those children render in front of the 
3165 // layer background, so we need an extra 'contents' layer for the foreground of the layer object.
3166 bool RenderLayerCompositor::needsContentsCompositingLayer(const RenderLayer& layer) const
3167 {
3168     return layer.hasNegativeZOrderLayers();
3169 }
3170
3171 bool RenderLayerCompositor::requiresScrollLayer(RootLayerAttachment attachment) const
3172 {
3173     auto& frameView = m_renderView.frameView();
3174
3175     // This applies when the application UI handles scrolling, in which case RenderLayerCompositor doesn't need to manage it.
3176     if (frameView.delegatesScrolling() && isMainFrameCompositor())
3177         return false;
3178
3179     // We need to handle our own scrolling if we're:
3180     return !m_renderView.frameView().platformWidget() // viewless (i.e. non-Mac, or Mac in WebKit2)
3181         || attachment == RootLayerAttachedViaEnclosingFrame; // a composited frame on Mac
3182 }
3183
3184 void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
3185 {
3186     if (!scrollbar)
3187         return;
3188
3189     context.save();
3190     const IntRect& scrollbarRect = scrollbar->frameRect();
3191     context.translate(-scrollbarRect.location());
3192     IntRect transformedClip = clip;
3193     transformedClip.moveBy(scrollbarRect.location());
3194     scrollbar->paint(context, transformedClip);
3195     context.restore();
3196 }
3197
3198 void RenderLayerCompositor::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, GraphicsLayerPaintingPhase, const FloatRect& clip, GraphicsLayerPaintBehavior)
3199 {
3200 #if PLATFORM(MAC)
3201     LocalDefaultSystemAppearance localAppearance(m_renderView.useDarkAppearance());
3202 #endif
3203
3204     IntRect pixelSnappedRectForIntegralPositionedItems = snappedIntRect(LayoutRect(clip));
3205     if (graphicsLayer == layerForHorizontalScrollbar())
3206         paintScrollbar(m_renderView.frameView().horizontalScrollbar(), context, pixelSnappedRectForIntegralPositionedItems);
3207     else if (graphicsLayer == layerForVerticalScrollbar())
3208         paintScrollbar(m_renderView.frameView().verticalScrollbar(), context, pixelSnappedRectForIntegralPositionedItems);
3209     else if (graphicsLayer == layerForScrollCorner()) {
3210         const IntRect& scrollCorner = m_renderView.frameView().scrollCornerRect();
3211         context.save();
3212         context.translate(-scrollCorner.location());
3213         IntRect transformedClip = pixelSnappedRectForIntegralPositionedItems;
3214         transformedClip.moveBy(scrollCorner.location());
3215         m_renderView.frameView().paintScrollCorner(context, transformedClip);
3216         context.restore();
3217     }
3218 }
3219
3220 bool RenderLayerCompositor::supportsFixedRootBackgroundCompositing() const
3221 {
3222     auto* renderViewBacking = m_renderView.layer()->backing();
3223     return renderViewBacking && renderViewBacking->isFrameLayerWithTiledBacking();
3224 }
3225
3226 bool RenderLayerCompositor::needsFixedRootBackgroundLayer(const RenderLayer& layer) const
3227 {
3228     if (!layer.isRenderViewLayer())
3229         return false;
3230
3231     if (m_renderView.settings().fixedBackgroundsPaintRelativeToDocument())
3232         return false;
3233
3234     return supportsFixedRootBackgroundCompositing() && m_renderView.rootBackgroundIsEntirelyFixed();
3235 }
3236
3237 GraphicsLayer* RenderLayerCompositor::fixedRootBackgroundLayer() const
3238 {
3239     // Get the fixed root background from the RenderView layer's backing.
3240     auto* viewLayer = m_renderView.layer();
3241     if (!viewLayer)
3242         return nullptr;
3243
3244     if (viewLayer->isComposited() && viewLayer->backing()->backgroundLayerPaintsFixedRootBackground())
3245         return viewLayer->backing()->backgroundLayer();
3246
3247     return nullptr;
3248 }
3249
3250 void RenderLayerCompositor::resetTrackedRepaintRects()
3251 {
3252     if (auto* rootLayer = rootGraphicsLayer()) {
3253         GraphicsLayer::traverse(*rootLayer, [](GraphicsLayer& layer) {
3254             layer.resetTrackedRepaints();
3255         });
3256     }
3257 }
3258
3259 float RenderLayerCompositor::deviceScaleFactor() const
3260 {
3261     return m_renderView.document().deviceScaleFactor();
3262 }
3263
3264 float RenderLayerCompositor::pageScaleFactor() const
3265 {
3266     return page().pageScaleFactor();
3267 }
3268
3269 float RenderLayerCompositor::zoomedOutPageScaleFactor() const
3270 {
3271     return page().zoomedOutPageScaleFactor();
3272 }
3273
3274 float RenderLayerCompositor::contentsScaleMultiplierForNewTiles(const GraphicsLayer*) const
3275 {
3276 #if PLATFORM(IOS_FAMILY)
3277     LegacyTileCache* tileCache = nullptr;
3278     if (auto* frameView = page().mainFrame().view())
3279         tileCache = frameView->legacyTileCache();
3280
3281     if (!tileCache)
3282         return 1;
3283
3284     return tileCache->tileControllerShouldUseLowScaleTiles() ? 0.125 : 1;
3285 #else
3286     return 1;
3287 #endif
3288 }
3289
3290 bool RenderLayerCompositor::documentUsesTiledBacking() const
3291 {
3292     auto* layer = m_renderView.layer();
3293     if (!layer)
3294         return false;
3295
3296     auto* backing = layer->backing();
3297     if (!backing)
3298         return false;
3299
3300     return backing->isFrameLayerWithTiledBacking();
3301 }
3302
3303 bool RenderLayerCompositor::isMainFrameCompositor() const
3304 {
3305     return m_renderView.frameView().frame().isMainFrame();
3306 }
3307
3308 bool RenderLayerCompositor::shouldCompositeOverflowControls() const
3309 {
3310     auto& frameView = m_renderView.frameView();
3311
3312     if (!frameView.managesScrollbars())
3313         return false;
3314
3315     if (documentUsesTiledBacking())
3316         return true;
3317
3318     if (m_overflowControlsHostLayer && isMainFrameCompositor())
3319         return true;
3320
3321 #if !USE(COORDINATED_GRAPHICS)
3322     if (!frameView.hasOverlayScrollbars())
3323         return false;
3324 #endif
3325
3326     return true;
3327 }
3328
3329 bool RenderLayerCompositor::requiresHorizontalScrollbarLayer() const
3330 {
3331     return shouldCompositeOverflowControls() && m_renderView.frameView().horizontalScrollbar();
3332 }
3333
3334 bool RenderLayerCompositor::requiresVerticalScrollbarLayer() const
3335 {
3336     return shouldCompositeOverflowControls() && m_renderView.frameView().verticalScrollbar();
3337 }
3338
3339 bool RenderLayerCompositor::requiresScrollCornerLayer() const
3340 {
3341     return shouldCompositeOverflowControls() && m_renderView.frameView().isScrollCornerVisible();
3342 }
3343
3344 #if ENABLE(RUBBER_BANDING)
3345 bool RenderLayerCompositor::requiresOverhangAreasLayer() const
3346 {
3347     if (!isMainFrameCompositor())
3348         return false;
3349
3350     // We do want a layer if we're using tiled drawing and can scroll.
3351     if (documentUsesTiledBacking() && m_renderView.frameView().hasOpaqueBackground() && !m_renderView.frameView().prohibitsScrolling())
3352         return true;
3353
3354     return false;
3355 }
3356
3357 bool RenderLayerCompositor::requiresContentShadowLayer() const
3358 {
3359     if (!isMainFrameCompositor())
3360         return false;
3361
3362 #if PLATFORM(COCOA)
3363     if (viewHasTransparentBackground())
3364         return false;
3365
3366     // If the background is going to extend, then it doesn't make sense to have a shadow layer.
3367     if (m_renderView.settings().backgroundShouldExtendBeyondPage())
3368         return false;
3369
3370     // On Mac, we want a content shadow layer if we're using tiled drawing and can scroll.
3371     if (documentUsesTiledBacking() && !m_renderView.frameView().prohibitsScrolling())
3372         return true;
3373 #endif
3374
3375     return false;
3376 }
3377
3378 GraphicsLayer* RenderLayerCompositor::updateLayerForTopOverhangArea(bool wantsLayer)
3379 {
3380     if (!isMainFrameCompositor())
3381         return nullptr;
3382
3383     if (!wantsLayer) {
3384         GraphicsLayer::unparentAndClear(m_layerForTopOverhangArea);
3385         return nullptr;
3386     }
3387
3388     if (!m_layerForTopOverhangArea) {
3389         m_layerForTopOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), *this);
3390         m_layerForTopOverhangArea->setName("top overhang");
3391         m_scrolledContentsLayer->addChildBelow(*m_layerForTopOverhangArea, m_rootContentsLayer.get());
3392     }
3393
3394     return m_layerForTopOverhangArea.get();
3395 }
3396
3397 GraphicsLayer* RenderLayerCompositor::updateLayerForBottomOverhangArea(bool wantsLayer)
3398 {
3399     if (!isMainFrameCompositor())
3400         return nullptr;
3401
3402     if (!wantsLayer) {
3403         GraphicsLayer::unparentAndClear(m_layerForBottomOverhangArea);
3404         return nullptr;
3405     }
3406
3407     if (!m_layerForBottomOverhangArea) {
3408         m_layerForBottomOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), *this);
3409         m_layerForBottomOverhangArea->setName("bottom overhang");
3410         m_scrolledContentsLayer->addChildBelow(*m_layerForBottomOverhangArea, m_rootContentsLayer.get());
3411     }
3412
3413     m_layerForBottomOverhangArea->setPosition(FloatPoint(0, m_rootContentsLayer->size().height() + m_renderView.frameView().headerHeight()
3414         + m_renderView.frameView().footerHeight() + m_renderView.frameView().topContentInset()));
3415     return m_layerForBottomOverhangArea.get();
3416 }
3417
3418 GraphicsLayer* RenderLayerCompositor::updateLayerForHeader(bool wantsLayer)
3419 {
3420     if (!isMainFrameCompositor())
3421         return nullptr;
3422
3423     if (!wantsLayer) {
3424         if (m_layerForHeader) {
3425             GraphicsLayer::unparentAndClear(m_layerForHeader);
3426
3427             // The ScrollingTree knows about the header layer, and the position of the root layer is affected
3428             // by the header layer, so if we remove the header, we need to tell the scrolling tree.
3429             if (auto* scrollingCoordinator = this->scrollingCoordinator())
3430                 scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
3431         }
3432         return nullptr;
3433     }
3434
3435     if (!m_layerForHeader) {
3436         m_layerForHeader = GraphicsLayer::create(graphicsLayerFactory(), *this);
3437         m_layerForHeader->setName("header");
3438         m_scrolledContentsLayer->addChildAbove(*m_layerForHeader, m_rootContentsLayer.get());
3439         m_renderView.frameView().addPaintPendingMilestones(DidFirstFlushForHeaderLayer);
3440     }
3441
3442     m_layerForHeader->setPosition(FloatPoint(0,
3443         FrameView::yPositionForHeaderLayer(m_renderView.frameView().scrollPosition(), m_renderView.frameView().topContentInset())));
3444     m_layerForHeader->setAnchorPoint(FloatPoint3D());
3445     m_layerForHeader->setSize(FloatSize(m_renderView.frameView().visibleWidth(), m_renderView.frameView().headerHeight()));
3446
3447     if (auto* scrollingCoordinator = this->scrollingCoordinator())
3448         scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
3449
3450     page().chrome().client().didAddHeaderLayer(*m_layerForHeader);
3451
3452     return m_layerForHeader.get();
3453 }
3454
3455 GraphicsLayer* RenderLayerCompositor::updateLayerForFooter(bool wantsLayer)
3456 {
3457     if (!isMainFrameCompositor())
3458         return nullptr;
3459
3460     if (!wantsLayer) {
3461         if (m_layerForFooter) {
3462             GraphicsLayer::unparentAndClear(m_layerForFooter);
3463
3464             // The ScrollingTree knows about the footer layer, and the total scrollable size is affected
3465             // by the footer layer, so if we remove the footer, we need to tell the scrolling tree.
3466             if (auto* scrollingCoordinator = this->scrollingCoordinator())
3467                 scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
3468         }
3469         return nullptr;
3470     }
3471
3472     if (!m_layerForFooter) {
3473         m_layerForFooter = GraphicsLayer::create(graphicsLayerFactory(), *this);
3474         m_layerForFooter->setName("footer");
3475         m_scrolledContentsLayer->addChildAbove(*m_layerForFooter, m_rootContentsLayer.get());
3476     }
3477
3478     float totalContentHeight = m_rootContentsLayer->size().height() + m_renderView.frameView().headerHeight() + m_renderView.frameView().footerHeight();
3479     m_layerForFooter->setPosition(FloatPoint(0, FrameView::yPositionForFooterLayer(m_renderView.frameView().scrollPosition(),
3480         m_renderView.frameView().topContentInset(), totalContentHeight, m_renderView.frameView().footerHeight())));
3481     m_layerForFooter->setAnchorPoint(FloatPoint3D());
3482     m_layerForFooter->setSize(FloatSize(m_renderView.frameView().visibleWidth(), m_renderView.frameView().footerHeight()));
3483
3484     if (auto* scrollingCoordinator = this->scrollingCoordinator())
3485         scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.frameView());
3486
3487     page().chrome().client().didAddFooterLayer(*m_layerForFooter);
3488
3489     return m_layerForFooter.get();
3490 }
3491
3492 #endif
3493
3494 bool RenderLayerCompositor::viewHasTransparentBackground(Color* backgroundColor) const
3495 {
3496     if (m_renderView.frameView().isTransparent()) {
3497         if (backgroundColor)
3498             *backgroundColor = Color(); // Return an invalid color.
3499         return true;
3500     }
3501
3502     Color documentBackgroundColor = m_renderView.frameView().documentBackgroundColor();
3503     if (!documentBackgroundColor.isValid())
3504         documentBackgroundColor = m_renderView.frameView().baseBackgroundColor();
3505
3506     ASSERT(documentBackgroundColor.isValid());
3507
3508     if (backgroundColor)
3509         *backgroundColor = documentBackgroundColor;
3510
3511     return !documentBackgroundColor.isOpaque();
3512 }
3513
3514 // We can't rely on getting layerStyleChanged() for a style change that affects the root background, because the style change may
3515 // be on the body which has no RenderLayer.
3516 void RenderLayerCompositor::rootOrBodyStyleChanged(RenderElement& renderer, const RenderStyle* oldStyle)
3517 {
3518     if (!usesCompositing())
3519         return;
3520
3521     Color oldBackgroundColor;
3522     if (oldStyle)
3523         oldBackgroundColor = oldStyle->visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor);
3524
3525     if (oldBackgroundColor != renderer.style().visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor))
3526         rootBackgroundColorOrTransparencyChanged();
3527
3528     bool hadFixedBackground = oldStyle && oldStyle->hasEntirelyFixedBackground();
3529     if (hadFixedBackground != renderer.style().hasEntirelyFixedBackground())
3530         rootLayerConfigurationChanged();
3531 }
3532
3533 void RenderLayerCompositor::rootBackgroundColorOrTransparencyChanged()
3534 {
3535     if (!usesCompositing())
3536         return;
3537
3538     Color backgroundColor;
3539     bool isTransparent = viewHasTransparentBackground(&backgroundColor);
3540     
3541     Color extendedBackgroundColor = m_renderView.settings().backgroundShouldExtendBeyondPage() ? backgroundColor : Color();
3542     
3543     bool transparencyChanged = m_viewBackgroundIsTransparent != isTransparent;
3544     bool backgroundColorChanged = m_viewBackgroundColor != backgroundColor;
3545     bool extendedBackgroundColorChanged = m_rootExtendedBackgroundColor != extendedBackgroundColor;
3546
3547     if (!transparencyChanged && !backgroundColorChanged && !extendedBackgroundColorChanged)
3548         return;
3549
3550     LOG(Compositing, "RenderLayerCompositor %p rootBackgroundColorOrTransparencyChanged. isTransparent=%d", this, isTransparent);
3551
3552     m_viewBackgroundIsTransparent = isTransparent;
3553     m_viewBackgroundColor = backgroundColor;
3554     m_rootExtendedBackgroundColor = extendedBackgroundColor;
3555     
3556     if (extendedBackgroundColorChanged) {
3557         page().chrome().client().pageExtendedBackgroundColorDidChange(m_rootExtendedBackgroundColor);
3558         
3559 #if ENABLE(RUBBER_BANDING)
3560         if (m_layerForOverhangAreas) {
3561             m_layerForOverhangAreas->setBackgroundColor(m_rootExtendedBackgroundColor);
3562
3563             if (!m_rootExtendedBackgroundColor.isValid())
3564                 m_layerForOverhangAreas->setCustomAppearance(GraphicsLayer::CustomAppearance::ScrollingOverhang);
3565         }
3566 #endif
3567     }
3568     
3569     rootLayerConfigurationChanged();
3570 }
3571
3572 void RenderLayerCompositor::updateOverflowControlsLayers()
3573 {
3574 #if ENABLE(RUBBER_BANDING)
3575     if (requiresOverhangAreasLayer()) {
3576         if (!m_layerForOverhangAreas) {
3577             m_layerForOverhangAreas = GraphicsLayer::create(graphicsLayerFactory(), *this);
3578             m_layerForOverhangAreas->setName("overhang areas");
3579             m_layerForOverhangAreas->setDrawsContent(false);
3580
3581             float topContentInset = m_renderView.frameView().topContentInset();
3582             IntSize overhangAreaSize = m_renderView.frameView().frameRect().size();
3583             overhangAreaSize.setHeight(overhangAreaSize.height() - topContentInset);
3584             m_layerForOverhangAreas->setSize(overhangAreaSize);
3585             m_layerForOverhangAreas->setPosition(FloatPoint(0, topContentInset));
3586             m_layerForOverhangAreas->setAnchorPoint(FloatPoint3D());
3587
3588             if (m_renderView.settings().backgroundShouldExtendBeyondPage())
3589                 m_layerForOverhangAreas->setBackgroundColor(m_renderView.frameView().documentBackgroundColor());
3590             else
3591                 m_layerForOverhangAreas->setCustomAppearance(GraphicsLayer::CustomAppearance::ScrollingOverhang);
3592
3593             // We want the overhang areas layer to be positioned below the frame contents,
3594             // so insert it below the clip layer.
3595             m_overflowControlsHostLayer->addChildBelow(*m_layerForOverhangAreas, layerForClipping());
3596         }
3597     } else
3598         GraphicsLayer::unparentAndClear(m_layerForOverhangAreas);
3599
3600     if (requiresContentShadowLayer()) {
3601         if (!m_contentShadowLayer) {
3602             m_contentShadowLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3603             m_contentShadowLayer->setName("content shadow");
3604             m_contentShadowLayer->setSize(m_rootContentsLayer->size());
3605             m_contentShadowLayer->setPosition(m_rootContentsLayer->position());
3606             m_contentShadowLayer->setAnchorPoint(FloatPoint3D());
3607             m_contentShadowLayer->setCustomAppearance(GraphicsLayer::CustomAppearance::ScrollingShadow);
3608
3609             m_scrolledContentsLayer->addChildBelow(*m_contentShadowLayer, m_rootContentsLayer.get());
3610         }
3611     } else
3612         GraphicsLayer::unparentAndClear(m_contentShadowLayer);
3613 #endif
3614
3615     if (requiresHorizontalScrollbarLayer()) {
3616         if (!m_layerForHorizontalScrollbar) {
3617             m_layerForHorizontalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), *this);
3618             m_layerForHorizontalScrollbar->setCanDetachBackingStore(false);
3619             m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
3620             m_layerForHorizontalScrollbar->setName("horizontal scrollbar container");
3621 #if PLATFORM(COCOA) && USE(CA)
3622             m_layerForHorizontalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
3623 #endif
3624             m_overflowControlsHostLayer->addChild(*m_layerForHorizontalScrollbar);
3625
3626             if (auto* scrollingCoordinator = this->scrollingCoordinator())
3627                 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), HorizontalScrollbar);
3628         }
3629     } else if (m_layerForHorizontalScrollbar) {
3630         GraphicsLayer::unparentAndClear(m_layerForHorizontalScrollbar);
3631
3632         if (auto* scrollingCoordinator = this->scrollingCoordinator())
3633             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), HorizontalScrollbar);
3634     }
3635
3636     if (requiresVerticalScrollbarLayer()) {
3637         if (!m_layerForVerticalScrollbar) {
3638             m_layerForVerticalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), *this);
3639             m_layerForVerticalScrollbar->setCanDetachBackingStore(false);
3640             m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
3641             m_layerForVerticalScrollbar->setName("vertical scrollbar container");
3642 #if PLATFORM(COCOA) && USE(CA)
3643             m_layerForVerticalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
3644 #endif
3645             m_overflowControlsHostLayer->addChild(*m_layerForVerticalScrollbar);
3646
3647             if (auto* scrollingCoordinator = this->scrollingCoordinator())
3648                 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), VerticalScrollbar);
3649         }
3650     } else if (m_layerForVerticalScrollbar) {
3651         GraphicsLayer::unparentAndClear(m_layerForVerticalScrollbar);
3652
3653         if (auto* scrollingCoordinator = this->scrollingCoordinator())
3654             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), VerticalScrollbar);
3655     }
3656
3657     if (requiresScrollCornerLayer()) {
3658         if (!m_layerForScrollCorner) {
3659             m_layerForScrollCorner = GraphicsLayer::create(graphicsLayerFactory(), *this);
3660             m_layerForScrollCorner->setCanDetachBackingStore(false);
3661             m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
3662             m_layerForScrollCorner->setName("scroll corner");
3663 #if PLATFORM(COCOA) && USE(CA)
3664             m_layerForScrollCorner->setAcceleratesDrawing(acceleratedDrawingEnabled());
3665 #endif
3666             m_overflowControlsHostLayer->addChild(*m_layerForScrollCorner);
3667         }
3668     } else
3669         GraphicsLayer::unparentAndClear(m_layerForScrollCorner);
3670
3671     m_renderView.frameView().positionScrollbarLayers();
3672 }
3673
3674 void RenderLayerCompositor::ensureRootLayer()
3675 {
3676     RootLayerAttachment expectedAttachment = isMainFrameCompositor() ? RootLayerAttachedViaChromeClient : RootLayerAttachedViaEnclosingFrame;
3677     if (expectedAttachment == m_rootLayerAttachment)
3678          return;
3679
3680     if (!m_rootContentsLayer) {
3681         m_rootContentsLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3682         m_rootContentsLayer->setName("content root");
3683         IntRect overflowRect = snappedIntRect(m_renderView.layoutOverflowRect());
3684         m_rootContentsLayer->setSize(FloatSize(overflowRect.maxX(), overflowRect.maxY()));
3685         m_rootContentsLayer->setPosition(FloatPoint());
3686
3687 #if PLATFORM(IOS_FAMILY)
3688         // Page scale is applied above this on iOS, so we'll just say that our root layer applies it.
3689         auto& frame = m_renderView.frameView().frame();
3690         if (frame.isMainFrame())
3691             m_rootContentsLayer->setAppliesPageScale();
3692 #endif
3693
3694         // Need to clip to prevent transformed content showing outside this frame
3695         updateRootContentLayerClipping();
3696     }
3697
3698     if (requiresScrollLayer(expectedAttachment)) {
3699         if (!m_overflowControlsHostLayer) {
3700             ASSERT(!m_scrolledContentsLayer);
3701             ASSERT(!m_clipLayer);
3702
3703             // Create a layer to host the clipping layer and the overflow controls layers.
3704             m_overflowControlsHostLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3705             m_overflowControlsHostLayer->setName("overflow controls host");
3706
3707             m_scrolledContentsLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3708             m_scrolledContentsLayer->setName("scrolled contents");
3709             m_scrolledContentsLayer->setAnchorPoint({ });
3710
3711 #if PLATFORM(IOS_FAMILY)
3712             if (m_renderView.settings().asyncFrameScrollingEnabled()) {
3713                 m_scrollContainerLayer = GraphicsLayer::create(graphicsLayerFactory(), *this, GraphicsLayer::Type::ScrollContainer);
3714
3715                 m_scrollContainerLayer->setName("scroll container");
3716                 m_scrollContainerLayer->setMasksToBounds(true);
3717                 m_scrollContainerLayer->setAnchorPoint({ });
3718
3719                 m_scrollContainerLayer->addChild(*m_scrolledContentsLayer);
3720                 m_overflowControlsHostLayer->addChild(*m_scrollContainerLayer);
3721             }
3722 #endif
3723             if (!m_scrollContainerLayer) {
3724                 m_clipLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3725                 m_clipLayer->setName("frame clipping");
3726                 m_clipLayer->setMasksToBounds(true);
3727                 m_clipLayer->setAnchorPoint({ });
3728
3729                 m_clipLayer->addChild(*m_scrolledContentsLayer);
3730                 m_overflowControlsHostLayer->addChild(*m_clipLayer);
3731             }
3732
3733             m_scrolledContentsLayer->addChild(*m_rootContentsLayer);
3734
3735             updateScrollLayerClipping();
3736             updateOverflowControlsLayers();
3737
3738             if (hasCoordinatedScrolling())
3739                 scheduleLayerFlush(true);
3740             else
3741                 updateScrollLayerPosition();
3742         }
3743     } else {
3744         if (m_overflowControlsHostLayer) {
3745             GraphicsLayer::unparentAndClear(m_overflowControlsHostLayer);
3746             GraphicsLayer::unparentAndClear(m_clipLayer);
3747             GraphicsLayer::unparentAndClear(m_scrollContainerLayer);
3748             GraphicsLayer::unparentAndClear(m_scrolledContentsLayer);
3749         }
3750     }
3751
3752     // Check to see if we have to change the attachment
3753     if (m_rootLayerAttachment != RootLayerUnattached)
3754         detachRootLayer();
3755
3756     attachRootLayer(expectedAttachment);
3757 }
3758
3759 void RenderLayerCompositor::destroyRootLayer()
3760 {
3761     if (!m_rootContentsLayer)
3762         return;
3763
3764     detachRootLayer();
3765
3766 #if ENABLE(RUBBER_BANDING)
3767     GraphicsLayer::unparentAndClear(m_layerForOverhangAreas);
3768 #endif
3769
3770     if (m_layerForHorizontalScrollbar) {
3771         GraphicsLayer::unparentAndClear(m_layerForHorizontalScrollbar);
3772         if (auto* scrollingCoordinator = this->scrollingCoordinator())
3773             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), HorizontalScrollbar);
3774         if (auto* horizontalScrollbar = m_renderView.frameView().verticalScrollbar())
3775             m_renderView.frameView().invalidateScrollbar(*horizontalScrollbar, IntRect(IntPoint(0, 0), horizontalScrollbar->frameRect().size()));
3776     }
3777
3778     if (m_layerForVerticalScrollbar) {
3779         GraphicsLayer::unparentAndClear(m_layerForVerticalScrollbar);
3780         if (auto* scrollingCoordinator = this->scrollingCoordinator())
3781             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), VerticalScrollbar);
3782         if (auto* verticalScrollbar = m_renderView.frameView().verticalScrollbar())
3783             m_renderView.frameView().invalidateScrollbar(*verticalScrollbar, IntRect(IntPoint(0, 0), verticalScrollbar->frameRect().size()));
3784     }
3785
3786     if (m_layerForScrollCorner) {
3787         GraphicsLayer::unparentAndClear(m_layerForScrollCorner);
3788         m_renderView.frameView().invalidateScrollCorner(m_renderView.frameView().scrollCornerRect());
3789     }
3790
3791     if (m_overflowControlsHostLayer) {
3792         GraphicsLayer::unparentAndClear(m_overflowControlsHostLayer);
3793         GraphicsLayer::unparentAndClear(m_clipLayer);
3794         GraphicsLayer::unparentAndClear(m_scrollContainerLayer);
3795         GraphicsLayer::unparentAndClear(m_scrolledContentsLayer);
3796     }
3797     ASSERT(!m_scrolledContentsLayer);
3798     GraphicsLayer::unparentAndClear(m_rootContentsLayer);
3799
3800     m_layerUpdater = nullptr;
3801 }
3802
3803 void RenderLayerCompositor::attachRootLayer(RootLayerAttachment attachment)
3804 {
3805     if (!m_rootContentsLayer)
3806         return;
3807
3808     LOG(Compositing, "RenderLayerCompositor %p attachRootLayer %d", this, attachment);
3809
3810     switch (attachment) {
3811         case RootLayerUnattached:
3812             ASSERT_NOT_REACHED();
3813             break;
3814         case RootLayerAttachedViaChromeClient: {
3815             auto& frame = m_renderView.frameView().frame();
3816             page().chrome().client().attachRootGraphicsLayer(frame, rootGraphicsLayer());
3817             break;
3818         }
3819         case RootLayerAttachedViaEnclosingFrame: {
3820             // The layer will get hooked up via RenderLayerBacking::updateConfiguration()
3821             // for the frame's renderer in the parent document.