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