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