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