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