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