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