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