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