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