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