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