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