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