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