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