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