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