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