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