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