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