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