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