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