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