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