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