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