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