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