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