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