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