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