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