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