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