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