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