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