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