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