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