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