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