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