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