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