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