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