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