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