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