[WK2] Pinch-zoom shadows can overlap headers and footers
[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 = enclosingIntRect(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         LayoutRect repaintRect = rect;
962         repaintRect.move(layer.offsetFromAncestor(compositedAncestor));
963         compositedAncestor->setBackingNeedsRepaintInRect(repaintRect);
964     }
965
966     // The contents of this layer may be moving from a GraphicsLayer to the window,
967     // so we need to make sure the window system synchronizes those changes on the screen.
968     if (compositedAncestor == m_renderView.layer())
969         m_renderView.frameView().setNeedsOneShotDrawingSynchronization();
970 }
971
972 // The bounds of the GraphicsLayer created for a compositing layer is the union of the bounds of all the descendant
973 // RenderLayers that are rendered by the composited RenderLayer.
974 LayoutRect RenderLayerCompositor::calculateCompositedBounds(const RenderLayer& layer, const RenderLayer& ancestorLayer) const
975 {
976     if (!canBeComposited(layer))
977         return LayoutRect();
978     return layer.calculateLayerBounds(&ancestorLayer, layer.offsetFromAncestor(&ancestorLayer), RenderLayer::DefaultCalculateLayerBoundsFlags | RenderLayer::ExcludeHiddenDescendants | RenderLayer::DontConstrainForMask);
979 }
980
981 void RenderLayerCompositor::layerWasAdded(RenderLayer&, RenderLayer&)
982 {
983     setCompositingLayersNeedRebuild();
984 }
985
986 void RenderLayerCompositor::layerWillBeRemoved(RenderLayer& parent, RenderLayer& child)
987 {
988     if (!child.isComposited() || parent.renderer().documentBeingDestroyed())
989         return;
990
991     removeFromScrollCoordinatedLayers(child);
992     repaintInCompositedAncestor(child, child.backing()->compositedBounds());
993
994     setCompositingParent(child, nullptr);
995     setCompositingLayersNeedRebuild();
996 }
997
998 RenderLayer* RenderLayerCompositor::enclosingNonStackingClippingLayer(const RenderLayer& layer) const
999 {
1000     for (RenderLayer* parent = layer.parent(); parent; parent = parent->parent()) {
1001         if (parent->isStackingContainer())
1002             return nullptr;
1003         if (parent->renderer().hasClipOrOverflowClip())
1004             return parent;
1005     }
1006     return nullptr;
1007 }
1008
1009 void RenderLayerCompositor::addToOverlapMap(OverlapMap& overlapMap, RenderLayer& layer, IntRect& layerBounds, bool& boundsComputed)
1010 {
1011     if (layer.isRootLayer())
1012         return;
1013
1014     if (!boundsComputed) {
1015         // FIXME: If this layer's overlap bounds include its children, we don't need to add its
1016         // children's bounds to the overlap map.
1017         layerBounds = enclosingIntRect(overlapMap.geometryMap().absoluteRect(layer.overlapBounds()));
1018         // Empty rects never intersect, but we need them to for the purposes of overlap testing.
1019         if (layerBounds.isEmpty())
1020             layerBounds.setSize(IntSize(1, 1));
1021         boundsComputed = true;
1022     }
1023
1024     IntRect clipRect = pixelSnappedIntRect(layer.backgroundClipRect(RenderLayer::ClipRectsContext(&rootRenderLayer(), AbsoluteClipRects)).rect()); // FIXME: Incorrect for CSS regions.
1025
1026     // On iOS, pageScaleFactor() is not applied by RenderView, so we should not scale here.
1027     // FIXME: Set Settings::delegatesPageScaling to true for iOS.
1028 #if !PLATFORM(IOS)
1029     const Settings& settings = m_renderView.frameView().frame().settings();
1030     if (!settings.delegatesPageScaling())
1031         clipRect.scale(pageScaleFactor());
1032 #endif
1033     clipRect.intersect(layerBounds);
1034     overlapMap.add(&layer, clipRect);
1035 }
1036
1037 void RenderLayerCompositor::addToOverlapMapRecursive(OverlapMap& overlapMap, RenderLayer& layer, RenderLayer* ancestorLayer)
1038 {
1039     if (!canBeComposited(layer) || overlapMap.contains(&layer))
1040         return;
1041
1042     // A null ancestorLayer is an indication that 'layer' has already been pushed.
1043     if (ancestorLayer)
1044         overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer);
1045     
1046     IntRect bounds;
1047     bool haveComputedBounds = false;
1048     addToOverlapMap(overlapMap, layer, bounds, haveComputedBounds);
1049
1050 #if !ASSERT_DISABLED
1051     LayerListMutationDetector mutationChecker(&layer);
1052 #endif
1053
1054     if (layer.isStackingContainer()) {
1055         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1056             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i)
1057                 addToOverlapMapRecursive(overlapMap, *negZOrderList->at(i), &layer);
1058         }
1059     }
1060
1061     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1062         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i)
1063             addToOverlapMapRecursive(overlapMap, *normalFlowList->at(i), &layer);
1064     }
1065
1066     if (layer.isStackingContainer()) {
1067         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1068             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i)
1069                 addToOverlapMapRecursive(overlapMap, *posZOrderList->at(i), &layer);
1070         }
1071     }
1072     
1073     if (ancestorLayer)
1074         overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
1075 }
1076
1077 void RenderLayerCompositor::computeCompositingRequirementsForNamedFlowFixed(RenderLayer& layer, OverlapMap* overlapMap, CompositingState& childState, bool& layersChanged, bool& anyDescendantHas3DTransform)
1078 {
1079     if (!layer.isRootLayer())
1080         return;
1081
1082     if (!layer.renderer().view().hasRenderNamedFlowThreads())
1083         return;
1084
1085     Vector<RenderLayer*> fixedLayers;
1086     layer.renderer().view().flowThreadController().collectFixedPositionedLayers(fixedLayers);
1087
1088     for (size_t i = 0; i < fixedLayers.size(); ++i) {
1089         RenderLayer* fixedLayer = fixedLayers.at(i);
1090         computeCompositingRequirements(&layer, *fixedLayer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1091     }
1092 }
1093
1094 //  Recurse through the layers in z-index and overflow order (which is equivalent to painting order)
1095 //  For the z-order children of a compositing layer:
1096 //      If a child layers has a compositing layer, then all subsequent layers must
1097 //      be compositing in order to render above that layer.
1098 //
1099 //      If a child in the negative z-order list is compositing, then the layer itself
1100 //      must be compositing so that its contents render over that child.
1101 //      This implies that its positive z-index children must also be compositing.
1102 //
1103 void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer& layer, OverlapMap* overlapMap, CompositingState& compositingState, bool& layersChanged, bool& descendantHas3DTransform)
1104 {
1105     layer.updateDescendantDependentFlags();
1106     layer.updateLayerListsIfNeeded();
1107
1108     if (layer.isFlowThreadCollectingGraphicsLayersUnderRegions()) {
1109         RenderFlowThread& flowThread = toRenderFlowThread(layer.renderer());
1110         layer.setHasCompositingDescendant(flowThread.hasCompositingRegionDescendant());
1111
1112         // Before returning, we need to update the lists of all child layers. This is required because,
1113         // if this flow thread will not be painted (for instance because of having no regions, or only invalid regions),
1114         // the child layers will never have their lists updated (which would normally happen during painting).
1115         layer.updateDescendantsLayerListsIfNeeded(true);
1116
1117         return;
1118     }
1119
1120     if (overlapMap)
1121         overlapMap->geometryMap().pushMappingsToAncestor(&layer, ancestorLayer);
1122     
1123     // Clear the flag
1124     layer.setHasCompositingDescendant(false);
1125     layer.setIndirectCompositingReason(RenderLayer::NoIndirectCompositingReason);
1126
1127     // Check if the layer needs to be composited for non-indirect reasons (ex. 3D transform).
1128     // We use this value to avoid checking the overlap-map, if we know for sure the layer
1129     // is already going to be composited for other reasons.
1130     bool willBeComposited = needsToBeComposited(layer);
1131
1132     RenderLayer::IndirectCompositingReason compositingReason = compositingState.m_subtreeIsCompositing ? RenderLayer::IndirectCompositingForStacking : RenderLayer::NoIndirectCompositingReason;
1133     bool haveComputedBounds = false;
1134     IntRect absBounds;
1135
1136     // If we know for sure the layer is going to be composited, don't bother looking it up in the overlap map
1137     if (!willBeComposited && overlapMap && !overlapMap->isEmpty() && compositingState.m_testingOverlap) {
1138         // If we're testing for overlap, we only need to composite if we overlap something that is already composited.
1139         absBounds = enclosingIntRect(overlapMap->geometryMap().absoluteRect(layer.overlapBounds()));
1140
1141         // Empty rects never intersect, but we need them to for the purposes of overlap testing.
1142         if (absBounds.isEmpty())
1143             absBounds.setSize(IntSize(1, 1));
1144         haveComputedBounds = true;
1145         compositingReason = overlapMap->overlapsLayers(absBounds) ? RenderLayer::IndirectCompositingForOverlap : RenderLayer::NoIndirectCompositingReason;
1146     }
1147
1148 #if ENABLE(VIDEO)
1149     // Video is special. It's the only RenderLayer type that can both have
1150     // RenderLayer children and whose children can't use its backing to render
1151     // into. These children (the controls) always need to be promoted into their
1152     // own layers to draw on top of the accelerated video.
1153     if (compositingState.m_compositingAncestor && compositingState.m_compositingAncestor->renderer().isVideo())
1154         compositingReason = RenderLayer::IndirectCompositingForOverlap;
1155 #endif
1156
1157     layer.setIndirectCompositingReason(compositingReason);
1158
1159     // Check if the computed indirect reason will force the layer to become composited.
1160     if (!willBeComposited && layer.mustCompositeForIndirectReasons() && canBeComposited(layer))
1161         willBeComposited = true;
1162     ASSERT(willBeComposited == needsToBeComposited(layer));
1163
1164     // The children of this layer don't need to composite, unless there is
1165     // a compositing layer among them, so start by inheriting the compositing
1166     // ancestor with m_subtreeIsCompositing set to false.
1167     CompositingState childState(compositingState);
1168     childState.m_subtreeIsCompositing = false;
1169 #if ENABLE(CSS_COMPOSITING)
1170     childState.m_hasNotIsolatedCompositedBlendingDescendants = false;
1171 #endif
1172
1173     if (willBeComposited) {
1174         // Tell the parent it has compositing descendants.
1175         compositingState.m_subtreeIsCompositing = true;
1176         // This layer now acts as the ancestor for kids.
1177         childState.m_compositingAncestor = &layer;
1178
1179         if (overlapMap)
1180             overlapMap->pushCompositingContainer();
1181         // This layer is going to be composited, so children can safely ignore the fact that there's an 
1182         // animation running behind this layer, meaning they can rely on the overlap map testing again.
1183         childState.m_testingOverlap = true;
1184     }
1185
1186 #if !ASSERT_DISABLED
1187     LayerListMutationDetector mutationChecker(&layer);
1188 #endif
1189
1190     bool anyDescendantHas3DTransform = false;
1191
1192     if (layer.isStackingContainer()) {
1193         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1194             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i) {
1195                 computeCompositingRequirements(&layer, *negZOrderList->at(i), overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1196
1197                 // If we have to make a layer for this child, make one now so we can have a contents layer
1198                 // (since we need to ensure that the -ve z-order child renders underneath our contents).
1199                 if (!willBeComposited && childState.m_subtreeIsCompositing) {
1200                     // make layer compositing
1201                     layer.setIndirectCompositingReason(RenderLayer::IndirectCompositingForBackgroundLayer);
1202                     childState.m_compositingAncestor = &layer;
1203                     if (overlapMap)
1204                         overlapMap->pushCompositingContainer();
1205                     // This layer is going to be composited, so children can safely ignore the fact that there's an 
1206                     // animation running behind this layer, meaning they can rely on the overlap map testing again
1207                     childState.m_testingOverlap = true;
1208                     willBeComposited = true;
1209                 }
1210             }
1211         }
1212     }
1213
1214     if (layer.renderer().isRenderNamedFlowFragmentContainer()) {
1215         // We are going to collect layers from the RenderFlowThread into the GraphicsLayer of the parent of the
1216         // anonymous RenderRegion, but first we need to make sure that the parent itself of the region is going to
1217         // have a composited layer. We only want to make regions composited when there's an actual layer that we
1218         // need to move to that region.
1219         computeRegionCompositingRequirements(toRenderBlockFlow(layer.renderer()).renderNamedFlowFragment(), overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1220     }
1221
1222     
1223     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1224         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i)
1225             computeCompositingRequirements(&layer, *normalFlowList->at(i), overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1226     }
1227
1228     if (layer.isStackingContainer()) {
1229         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1230             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i)
1231                 computeCompositingRequirements(&layer, *posZOrderList->at(i), overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1232         }
1233     }
1234
1235     if (layer.isRootLayer())
1236         computeCompositingRequirementsForNamedFlowFixed(layer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1237
1238     // If we just entered compositing mode, the root will have become composited (as long as accelerated compositing is enabled).
1239     if (layer.isRootLayer()) {
1240         if (inCompositingMode() && m_hasAcceleratedCompositing)
1241             willBeComposited = true;
1242     }
1243     
1244     ASSERT(willBeComposited == needsToBeComposited(layer));
1245
1246     // All layers (even ones that aren't being composited) need to get added to
1247     // the overlap map. Layers that do not composite will draw into their
1248     // compositing ancestor's backing, and so are still considered for overlap.
1249     if (overlapMap && childState.m_compositingAncestor && !childState.m_compositingAncestor->isRootLayer())
1250         addToOverlapMap(*overlapMap, layer, absBounds, haveComputedBounds);
1251
1252 #if ENABLE(CSS_COMPOSITING)
1253     layer.setHasNotIsolatedCompositedBlendingDescendants(childState.m_hasNotIsolatedCompositedBlendingDescendants);
1254     ASSERT(!layer.hasNotIsolatedCompositedBlendingDescendants() || layer.hasNotIsolatedBlendingDescendants());
1255 #endif
1256     // Now check for reasons to become composited that depend on the state of descendant layers.
1257     RenderLayer::IndirectCompositingReason indirectCompositingReason;
1258     if (!willBeComposited && canBeComposited(layer)
1259         && requiresCompositingForIndirectReason(layer.renderer(), childState.m_subtreeIsCompositing, anyDescendantHas3DTransform, indirectCompositingReason)) {
1260         layer.setIndirectCompositingReason(indirectCompositingReason);
1261         childState.m_compositingAncestor = &layer;
1262         if (overlapMap) {
1263             overlapMap->pushCompositingContainer();
1264             addToOverlapMapRecursive(*overlapMap, layer);
1265         }
1266         willBeComposited = true;
1267     }
1268     
1269     ASSERT(willBeComposited == needsToBeComposited(layer));
1270     if (layer.reflectionLayer()) {
1271         // FIXME: Shouldn't we call computeCompositingRequirements to handle a reflection overlapping with another renderer?
1272         layer.reflectionLayer()->setIndirectCompositingReason(willBeComposited ? RenderLayer::IndirectCompositingForStacking : RenderLayer::NoIndirectCompositingReason);
1273     }
1274
1275     // Subsequent layers in the parent stacking context also need to composite.
1276     if (childState.m_subtreeIsCompositing)
1277         compositingState.m_subtreeIsCompositing = true;
1278
1279     // Set the flag to say that this SC has compositing children.
1280     layer.setHasCompositingDescendant(childState.m_subtreeIsCompositing);
1281
1282     // setHasCompositingDescendant() may have changed the answer to needsToBeComposited() when clipping,
1283     // so test that again.
1284     bool isCompositedClippingLayer = canBeComposited(layer) && clipsCompositingDescendants(layer);
1285
1286     // Turn overlap testing off for later layers if it's already off, or if we have an animating transform.
1287     // Note that if the layer clips its descendants, there's no reason to propagate the child animation to the parent layers. That's because
1288     // we know for sure the animation is contained inside the clipping rectangle, which is already added to the overlap map.
1289     if ((!childState.m_testingOverlap && !isCompositedClippingLayer) || isRunningAcceleratedTransformAnimation(layer.renderer()))
1290         compositingState.m_testingOverlap = false;
1291     
1292     if (isCompositedClippingLayer) {
1293         if (!willBeComposited) {
1294             childState.m_compositingAncestor = &layer;
1295             if (overlapMap) {
1296                 overlapMap->pushCompositingContainer();
1297                 addToOverlapMapRecursive(*overlapMap, layer);
1298             }
1299             willBeComposited = true;
1300          }
1301     }
1302
1303 #if ENABLE(CSS_COMPOSITING)
1304     if ((willBeComposited && layer.hasBlendMode())
1305         || (layer.hasNotIsolatedCompositedBlendingDescendants() && !layer.isolatesCompositedBlending()))
1306         compositingState.m_hasNotIsolatedCompositedBlendingDescendants = true;
1307 #endif
1308
1309     if (overlapMap && childState.m_compositingAncestor == &layer && !layer.isRootLayer())
1310         overlapMap->popCompositingContainer();
1311
1312     // If we're back at the root, and no other layers need to be composited, and the root layer itself doesn't need
1313     // to be composited, then we can drop out of compositing mode altogether. However, don't drop out of compositing mode
1314     // if there are composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
1315     if (layer.isRootLayer() && !childState.m_subtreeIsCompositing && !requiresCompositingLayer(layer) && !m_forceCompositingMode && !hasAnyAdditionalCompositedLayers(layer)) {
1316         // Don't drop out of compositing on iOS, because we may flash. See <rdar://problem/8348337>.
1317 #if !PLATFORM(IOS)
1318         enableCompositingMode(false);
1319         willBeComposited = false;
1320 #endif
1321     }
1322     
1323     // If the layer is going into compositing mode, repaint its old location.
1324     ASSERT(willBeComposited == needsToBeComposited(layer));
1325     if (!layer.isComposited() && willBeComposited)
1326         repaintOnCompositingChange(layer);
1327
1328     // Update backing now, so that we can use isComposited() reliably during tree traversal in rebuildCompositingLayerTree().
1329     if (updateBacking(layer, CompositingChangeRepaintNow))
1330         layersChanged = true;
1331
1332     if (layer.reflectionLayer() && updateLayerCompositingState(*layer.reflectionLayer(), CompositingChangeRepaintNow))
1333         layersChanged = true;
1334
1335     descendantHas3DTransform |= anyDescendantHas3DTransform || layer.has3DTransform();
1336
1337     if (overlapMap)
1338         overlapMap->geometryMap().popMappingsToAncestor(ancestorLayer);
1339 }
1340
1341 void RenderLayerCompositor::computeRegionCompositingRequirements(RenderNamedFlowFragment* region, OverlapMap* overlapMap, CompositingState& childState, bool& layersChanged, bool& anyDescendantHas3DTransform)
1342 {
1343     if (!region->isValid())
1344         return;
1345
1346     RenderFlowThread* flowThread = region->flowThread();
1347     
1348     if (overlapMap)
1349         overlapMap->geometryMap().pushRenderFlowThread(flowThread);
1350
1351     if (const RenderLayerList* layerList = flowThread->getLayerListForRegion(region)) {
1352         for (size_t i = 0, listSize = layerList->size(); i < listSize; ++i) {
1353             RenderLayer& curLayer = *layerList->at(i);
1354             ASSERT(flowThread->regionForCompositedLayer(curLayer) == region);
1355             computeCompositingRequirements(flowThread->layer(), curLayer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1356         }
1357     }
1358
1359     if (overlapMap)
1360         overlapMap->geometryMap().popMappingsToAncestor(&region->layerOwner());
1361 }
1362
1363 void RenderLayerCompositor::setCompositingParent(RenderLayer& childLayer, RenderLayer* parentLayer)
1364 {
1365     ASSERT(!parentLayer || childLayer.ancestorCompositingLayer() == parentLayer);
1366     ASSERT(childLayer.isComposited());
1367
1368     // It's possible to be called with a parent that isn't yet composited when we're doing
1369     // partial updates as required by painting or hit testing. Just bail in that case;
1370     // we'll do a full layer update soon.
1371     if (!parentLayer || !parentLayer->isComposited())
1372         return;
1373
1374     if (parentLayer) {
1375         GraphicsLayer* hostingLayer = parentLayer->backing()->parentForSublayers();
1376         GraphicsLayer* hostedLayer = childLayer.backing()->childForSuperlayers();
1377         
1378         hostingLayer->addChild(hostedLayer);
1379     } else
1380         childLayer.backing()->childForSuperlayers()->removeFromParent();
1381 }
1382
1383 void RenderLayerCompositor::removeCompositedChildren(RenderLayer& layer)
1384 {
1385     ASSERT(layer.isComposited());
1386
1387     layer.backing()->parentForSublayers()->removeAllChildren();
1388 }
1389
1390 #if ENABLE(VIDEO)
1391 bool RenderLayerCompositor::canAccelerateVideoRendering(RenderVideo& video) const
1392 {
1393     if (!m_hasAcceleratedCompositing)
1394         return false;
1395
1396     return video.supportsAcceleratedRendering();
1397 }
1398 #endif
1399
1400 void RenderLayerCompositor::rebuildCompositingLayerTreeForNamedFlowFixed(RenderLayer& layer, Vector<GraphicsLayer*>& childGraphicsLayersOfEnclosingLayer, int depth)
1401 {
1402     if (!layer.isRootLayer())
1403         return;
1404
1405     if (!layer.renderer().view().hasRenderNamedFlowThreads())
1406         return;
1407
1408     Vector<RenderLayer*> fixedLayers;
1409     layer.renderer().view().flowThreadController().collectFixedPositionedLayers(fixedLayers);
1410
1411     for (size_t i = 0; i < fixedLayers.size(); ++i) {
1412         RenderLayer* fixedLayer = fixedLayers.at(i);
1413         rebuildCompositingLayerTree(*fixedLayer, childGraphicsLayersOfEnclosingLayer, depth);
1414     }
1415 }
1416
1417 void RenderLayerCompositor::rebuildCompositingLayerTree(RenderLayer& layer, Vector<GraphicsLayer*>& childLayersOfEnclosingLayer, int depth)
1418 {
1419     // Make the layer compositing if necessary, and set up clipping and content layers.
1420     // Note that we can only do work here that is independent of whether the descendant layers
1421     // have been processed. computeCompositingRequirements() will already have done the repaint if necessary.
1422
1423     // Do not iterate the RenderFlowThread directly. We are going to collect composited layers as part of regions.
1424     if (layer.isFlowThreadCollectingGraphicsLayersUnderRegions())
1425         return;
1426
1427     RenderLayerBacking* layerBacking = layer.backing();
1428     if (layerBacking) {
1429         // The compositing state of all our children has been updated already, so now
1430         // we can compute and cache the composited bounds for this layer.
1431         layerBacking->updateCompositedBounds();
1432
1433         if (RenderLayer* reflection = layer.reflectionLayer()) {
1434             if (reflection->backing())
1435                 reflection->backing()->updateCompositedBounds();
1436         }
1437
1438         if (layerBacking->updateConfiguration())
1439             layerBacking->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
1440         
1441         layerBacking->updateGeometry();
1442
1443         if (!layer.parent())
1444             updateRootLayerPosition();
1445
1446 #if !LOG_DISABLED
1447         logLayerInfo(layer, depth);
1448 #else
1449         UNUSED_PARAM(depth);
1450 #endif
1451         if (layerBacking->hasUnpositionedOverflowControlsLayers())
1452             layer.positionNewlyCreatedOverflowControls();
1453     }
1454
1455     // If this layer has backing, then we are collecting its children, otherwise appending
1456     // to the compositing child list of an enclosing layer.
1457     Vector<GraphicsLayer*> layerChildren;
1458     Vector<GraphicsLayer*>& childList = layerBacking ? layerChildren : childLayersOfEnclosingLayer;
1459
1460 #if !ASSERT_DISABLED
1461     LayerListMutationDetector mutationChecker(&layer);
1462 #endif
1463
1464     if (layer.isStackingContainer()) {
1465         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1466             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i)
1467                 rebuildCompositingLayerTree(*negZOrderList->at(i), childList, depth + 1);
1468         }
1469
1470         // If a negative z-order child is compositing, we get a foreground layer which needs to get parented.
1471         if (layerBacking && layerBacking->foregroundLayer())
1472             childList.append(layerBacking->foregroundLayer());
1473     }
1474
1475     if (layer.renderer().isRenderNamedFlowFragmentContainer())
1476         rebuildRegionCompositingLayerTree(toRenderBlockFlow(layer.renderer()).renderNamedFlowFragment(), layerChildren, depth + 1);
1477
1478     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1479         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i)
1480             rebuildCompositingLayerTree(*normalFlowList->at(i), childList, depth + 1);
1481     }
1482     
1483     if (layer.isStackingContainer()) {
1484         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1485             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i)
1486                 rebuildCompositingLayerTree(*posZOrderList->at(i), childList, depth + 1);
1487         }
1488     }
1489
1490     if (layer.isRootLayer())
1491         rebuildCompositingLayerTreeForNamedFlowFixed(layer, childList, depth + 1);
1492
1493     if (layerBacking) {
1494         bool parented = false;
1495         if (layer.renderer().isWidget())
1496             parented = parentFrameContentLayers(toRenderWidget(&layer.renderer()));
1497
1498         if (!parented)
1499             layerBacking->parentForSublayers()->setChildren(layerChildren);
1500
1501         // If the layer has a clipping layer the overflow controls layers will be siblings of the clipping layer.
1502         // Otherwise, the overflow control layers are normal children.
1503         if (!layerBacking->hasClippingLayer() && !layerBacking->hasScrollingLayer()) {
1504             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForHorizontalScrollbar()) {
1505                 overflowControlLayer->removeFromParent();
1506                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
1507             }
1508
1509             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForVerticalScrollbar()) {
1510                 overflowControlLayer->removeFromParent();
1511                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
1512             }
1513
1514             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForScrollCorner()) {
1515                 overflowControlLayer->removeFromParent();
1516                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
1517             }
1518         }
1519
1520         childLayersOfEnclosingLayer.append(layerBacking->childForSuperlayers());
1521     }
1522     
1523     if (RenderLayerBacking* layerBacking = layer.backing())
1524         layerBacking->updateAfterDescendents();
1525 }
1526
1527 void RenderLayerCompositor::rebuildRegionCompositingLayerTree(RenderNamedFlowFragment* region, Vector<GraphicsLayer*>& childList, int depth)
1528 {
1529     if (!region->isValid())
1530         return;
1531
1532     RenderFlowThread* flowThread = region->flowThread();
1533     ASSERT(flowThread->collectsGraphicsLayersUnderRegions());
1534     if (const RenderLayerList* layerList = flowThread->getLayerListForRegion(region)) {
1535         for (size_t i = 0, listSize = layerList->size(); i < listSize; ++i) {
1536             RenderLayer& curLayer = *layerList->at(i);
1537             ASSERT(flowThread->regionForCompositedLayer(curLayer) == region);
1538             rebuildCompositingLayerTree(curLayer, childList, depth + 1);
1539         }
1540     }
1541 }
1542
1543 void RenderLayerCompositor::frameViewDidChangeLocation(const IntPoint& contentsOffset)
1544 {
1545     if (m_overflowControlsHostLayer)
1546         m_overflowControlsHostLayer->setPosition(contentsOffset);
1547 }
1548
1549 void RenderLayerCompositor::frameViewDidChangeSize()
1550 {
1551     if (m_clipLayer) {
1552         const FrameView& frameView = m_renderView.frameView();
1553         m_clipLayer->setSize(frameView.unscaledTotalVisibleContentSize());
1554         m_clipLayer->setPosition(positionForClipLayer());
1555
1556         frameViewDidScroll();
1557         updateOverflowControlsLayers();
1558
1559 #if ENABLE(RUBBER_BANDING)
1560         if (m_layerForOverhangAreas) {
1561             m_layerForOverhangAreas->setSize(frameView.frameRect().size());
1562             m_layerForOverhangAreas->setPosition(FloatPoint(0, m_renderView.frameView().topContentInset()));
1563         }
1564 #endif
1565     }
1566 }
1567
1568 bool RenderLayerCompositor::hasCoordinatedScrolling() const
1569 {
1570     ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator();
1571     return scrollingCoordinator && scrollingCoordinator->coordinatesScrollingForFrameView(&m_renderView.frameView());
1572 }
1573
1574 void RenderLayerCompositor::updateScrollLayerPosition()
1575 {
1576     ASSERT(m_scrollLayer);
1577
1578     FrameView& frameView = m_renderView.frameView();
1579     IntPoint scrollPosition = frameView.scrollPosition();
1580
1581     m_scrollLayer->setPosition(FloatPoint(-scrollPosition.x(), -scrollPosition.y()));
1582
1583     if (GraphicsLayer* fixedBackgroundLayer = fixedRootBackgroundLayer())
1584         fixedBackgroundLayer->setPosition(toLayoutPoint(frameView.scrollOffsetForFixedPosition()));
1585 }
1586
1587 FloatPoint RenderLayerCompositor::positionForClipLayer() const
1588 {
1589     return FloatPoint(0, FrameView::yPositionForInsetClipLayer(m_renderView.frameView().scrollPosition(), m_renderView.frameView().topContentInset()));
1590 }
1591
1592 void RenderLayerCompositor::frameViewDidScroll()
1593 {
1594     if (!m_scrollLayer)
1595         return;
1596
1597     // If there's a scrolling coordinator that manages scrolling for this frame view,
1598     // it will also manage updating the scroll layer position.
1599     if (hasCoordinatedScrolling()) {
1600         // We have to schedule a flush in order for the main TiledBacking to update its tile coverage.
1601         scheduleLayerFlushNow();
1602         return;
1603     }
1604
1605     updateScrollLayerPosition();
1606 }
1607
1608 void RenderLayerCompositor::frameViewDidAddOrRemoveScrollbars()
1609 {
1610     updateOverflowControlsLayers();
1611 }
1612
1613 void RenderLayerCompositor::frameViewDidLayout()
1614 {
1615     RenderLayerBacking* renderViewBacking = m_renderView.layer()->backing();
1616     if (renderViewBacking)
1617         renderViewBacking->adjustTiledBackingCoverage();
1618 }
1619
1620 void RenderLayerCompositor::rootFixedBackgroundsChanged()
1621 {
1622     RenderLayerBacking* renderViewBacking = m_renderView.layer()->backing();
1623     if (renderViewBacking && renderViewBacking->usingTiledBacking())
1624         setCompositingLayersNeedRebuild();
1625 }
1626
1627 void RenderLayerCompositor::scrollingLayerDidChange(RenderLayer& layer)
1628 {
1629     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
1630         scrollingCoordinator->scrollableAreaScrollLayerDidChange(&layer);
1631 }
1632
1633 void RenderLayerCompositor::fixedRootBackgroundLayerChanged()
1634 {
1635     if (m_renderView.documentBeingDestroyed())
1636         return;
1637
1638     if (m_renderView.layer()->isComposited())
1639         updateScrollCoordinatedStatus(*m_renderView.layer());
1640 }
1641
1642 String RenderLayerCompositor::layerTreeAsText(LayerTreeFlags flags)
1643 {
1644     updateCompositingLayers(CompositingUpdateAfterLayout);
1645
1646     if (!m_rootContentLayer)
1647         return String();
1648
1649     flushPendingLayerChanges(true);
1650
1651     LayerTreeAsTextBehavior layerTreeBehavior = LayerTreeAsTextBehaviorNormal;
1652     if (flags & LayerTreeFlagsIncludeDebugInfo)
1653         layerTreeBehavior |= LayerTreeAsTextDebug;
1654     if (flags & LayerTreeFlagsIncludeVisibleRects)
1655         layerTreeBehavior |= LayerTreeAsTextIncludeVisibleRects;
1656     if (flags & LayerTreeFlagsIncludeTileCaches)
1657         layerTreeBehavior |= LayerTreeAsTextIncludeTileCaches;
1658     if (flags & LayerTreeFlagsIncludeRepaintRects)
1659         layerTreeBehavior |= LayerTreeAsTextIncludeRepaintRects;
1660     if (flags & LayerTreeFlagsIncludePaintingPhases)
1661         layerTreeBehavior |= LayerTreeAsTextIncludePaintingPhases;
1662     if (flags & LayerTreeFlagsIncludeContentLayers)
1663         layerTreeBehavior |= LayerTreeAsTextIncludeContentLayers;
1664
1665     // We skip dumping the scroll and clip layers to keep layerTreeAsText output
1666     // similar between platforms.
1667     String layerTreeText = m_rootContentLayer->layerTreeAsText(layerTreeBehavior);
1668
1669     // Dump an empty layer tree only if the only composited layer is the main frame's tiled backing,
1670     // so that tests expecting us to drop out of accelerated compositing when there are no layers succeed.
1671     if (!hasAnyAdditionalCompositedLayers(rootRenderLayer()) && mainFrameBackingIsTiled() && !(layerTreeBehavior & LayerTreeAsTextIncludeTileCaches))
1672         layerTreeText = "";
1673
1674     // The true root layer is not included in the dump, so if we want to report
1675     // its repaint rects, they must be included here.
1676     if (flags & LayerTreeFlagsIncludeRepaintRects)
1677         return m_renderView.frameView().trackedRepaintRectsAsText() + layerTreeText;
1678
1679     return layerTreeText;
1680 }
1681
1682 RenderLayerCompositor* RenderLayerCompositor::frameContentsCompositor(RenderWidget* renderer)
1683 {
1684     if (Document* contentDocument = renderer->frameOwnerElement().contentDocument()) {
1685         if (RenderView* view = contentDocument->renderView())
1686             return &view->compositor();
1687     }
1688     return 0;
1689 }
1690
1691 bool RenderLayerCompositor::parentFrameContentLayers(RenderWidget* renderer)
1692 {
1693     RenderLayerCompositor* innerCompositor = frameContentsCompositor(renderer);
1694     if (!innerCompositor || !innerCompositor->inCompositingMode() || innerCompositor->rootLayerAttachment() != RootLayerAttachedViaEnclosingFrame)
1695         return false;
1696     
1697     RenderLayer* layer = renderer->layer();
1698     if (!layer->isComposited())
1699         return false;
1700
1701     RenderLayerBacking* backing = layer->backing();
1702     GraphicsLayer* hostingLayer = backing->parentForSublayers();
1703     GraphicsLayer* rootLayer = innerCompositor->rootGraphicsLayer();
1704     if (hostingLayer->children().size() != 1 || hostingLayer->children()[0] != rootLayer) {
1705         hostingLayer->removeAllChildren();
1706         hostingLayer->addChild(rootLayer);
1707     }
1708     return true;
1709 }
1710
1711 // This just updates layer geometry without changing the hierarchy.
1712 void RenderLayerCompositor::updateLayerTreeGeometry(RenderLayer& layer, int depth)
1713 {
1714     if (RenderLayerBacking* layerBacking = layer.backing()) {
1715         // The compositing state of all our children has been updated already, so now
1716         // we can compute and cache the composited bounds for this layer.
1717         layerBacking->updateCompositedBounds();
1718
1719         if (RenderLayer* reflection = layer.reflectionLayer()) {
1720             if (reflection->backing())
1721                 reflection->backing()->updateCompositedBounds();
1722         }
1723
1724         layerBacking->updateConfiguration();
1725         layerBacking->updateGeometry();
1726
1727         if (!layer.parent())
1728             updateRootLayerPosition();
1729
1730 #if !LOG_DISABLED
1731         logLayerInfo(layer, depth);
1732 #else
1733         UNUSED_PARAM(depth);
1734 #endif
1735     }
1736
1737 #if !ASSERT_DISABLED
1738     LayerListMutationDetector mutationChecker(&layer);
1739 #endif
1740
1741     if (layer.isStackingContainer()) {
1742         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1743             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i)
1744                 updateLayerTreeGeometry(*negZOrderList->at(i), depth + 1);
1745         }
1746     }
1747
1748     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1749         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i)
1750             updateLayerTreeGeometry(*normalFlowList->at(i), depth + 1);
1751     }
1752     
1753     if (layer.isStackingContainer()) {
1754         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1755             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i)
1756                 updateLayerTreeGeometry(*posZOrderList->at(i), depth + 1);
1757         }
1758     }
1759
1760     if (RenderLayerBacking* layerBacking = layer.backing())
1761         layerBacking->updateAfterDescendents();
1762 }
1763
1764 // Recurs down the RenderLayer tree until its finds the compositing descendants of compositingAncestor and updates their geometry.
1765 void RenderLayerCompositor::updateCompositingDescendantGeometry(RenderLayer& compositingAncestor, RenderLayer& layer, bool compositedChildrenOnly)
1766 {
1767     if (&layer != &compositingAncestor) {
1768         if (RenderLayerBacking* layerBacking = layer.backing()) {
1769             layerBacking->updateCompositedBounds();
1770
1771             if (RenderLayer* reflection = layer.reflectionLayer()) {
1772                 if (reflection->backing())
1773                     reflection->backing()->updateCompositedBounds();
1774             }
1775
1776             layerBacking->updateGeometry();
1777             if (compositedChildrenOnly) {
1778                 layerBacking->updateAfterDescendents();
1779                 return;
1780             }
1781         }
1782     }
1783
1784     if (layer.reflectionLayer())
1785         updateCompositingDescendantGeometry(compositingAncestor, *layer.reflectionLayer(), compositedChildrenOnly);
1786
1787     if (!layer.hasCompositingDescendant())
1788         return;
1789
1790 #if !ASSERT_DISABLED
1791     LayerListMutationDetector mutationChecker(&layer);
1792 #endif
1793     
1794     if (layer.isStackingContainer()) {
1795         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1796             size_t listSize = negZOrderList->size();
1797             for (size_t i = 0; i < listSize; ++i)
1798                 updateCompositingDescendantGeometry(compositingAncestor, *negZOrderList->at(i), compositedChildrenOnly);
1799         }
1800     }
1801
1802     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1803         size_t listSize = normalFlowList->size();
1804         for (size_t i = 0; i < listSize; ++i)
1805             updateCompositingDescendantGeometry(compositingAncestor, *normalFlowList->at(i), compositedChildrenOnly);
1806     }
1807     
1808     if (layer.isStackingContainer()) {
1809         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1810             size_t listSize = posZOrderList->size();
1811             for (size_t i = 0; i < listSize; ++i)
1812                 updateCompositingDescendantGeometry(compositingAncestor, *posZOrderList->at(i), compositedChildrenOnly);
1813         }
1814     }
1815     
1816     if (&layer != &compositingAncestor) {
1817         if (RenderLayerBacking* layerBacking = layer.backing())
1818             layerBacking->updateAfterDescendents();
1819     }
1820 }
1821
1822 void RenderLayerCompositor::repaintCompositedLayers(const IntRect* absRect)
1823 {
1824     recursiveRepaintLayer(rootRenderLayer(), absRect);
1825 }
1826
1827 void RenderLayerCompositor::recursiveRepaintLayer(RenderLayer& layer, const IntRect* rect)
1828 {
1829     // FIXME: This method does not work correctly with transforms.
1830     if (layer.isComposited() && !layer.backing()->paintsIntoCompositedAncestor()) {
1831         if (rect)
1832             layer.setBackingNeedsRepaintInRect(*rect);
1833         else
1834             layer.setBackingNeedsRepaint();
1835     }
1836
1837 #if !ASSERT_DISABLED
1838     LayerListMutationDetector mutationChecker(&layer);
1839 #endif
1840
1841     if (layer.hasCompositingDescendant()) {
1842         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1843             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i) {
1844                 RenderLayer& childLayer = *negZOrderList->at(i);
1845                 if (rect) {
1846                     IntRect childRect(*rect);
1847                     childLayer.convertToPixelSnappedLayerCoords(&layer, childRect);
1848                     recursiveRepaintLayer(childLayer, &childRect);
1849                 } else
1850                     recursiveRepaintLayer(childLayer);
1851             }
1852         }
1853
1854         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1855             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i) {
1856                 RenderLayer& childLayer = *posZOrderList->at(i);
1857                 if (rect) {
1858                     IntRect childRect(*rect);
1859                     childLayer.convertToPixelSnappedLayerCoords(&layer, childRect);
1860                     recursiveRepaintLayer(childLayer, &childRect);
1861                 } else
1862                     recursiveRepaintLayer(childLayer);
1863             }
1864         }
1865     }
1866     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1867         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i) {
1868             RenderLayer& childLayer = *normalFlowList->at(i);
1869             if (rect) {
1870                 IntRect childRect(*rect);
1871                 childLayer.convertToPixelSnappedLayerCoords(&layer, childRect);
1872                 recursiveRepaintLayer(childLayer, &childRect);
1873             } else
1874                 recursiveRepaintLayer(childLayer);
1875         }
1876     }
1877 }
1878
1879 RenderLayer& RenderLayerCompositor::rootRenderLayer() const
1880 {
1881     return *m_renderView.layer();
1882 }
1883
1884 GraphicsLayer* RenderLayerCompositor::rootGraphicsLayer() const
1885 {
1886     if (m_overflowControlsHostLayer)
1887         return m_overflowControlsHostLayer.get();
1888     return m_rootContentLayer.get();
1889 }
1890
1891 GraphicsLayer* RenderLayerCompositor::scrollLayer() const
1892 {
1893     return m_scrollLayer.get();
1894 }
1895
1896 GraphicsLayer* RenderLayerCompositor::clipLayer() const
1897 {
1898     return m_clipLayer.get();
1899 }
1900
1901 GraphicsLayer* RenderLayerCompositor::rootContentLayer() const
1902 {
1903     return m_rootContentLayer.get();
1904 }
1905
1906 #if ENABLE(RUBBER_BANDING)
1907 GraphicsLayer* RenderLayerCompositor::headerLayer() const
1908 {
1909     return m_layerForHeader.get();
1910 }
1911
1912 GraphicsLayer* RenderLayerCompositor::footerLayer() const
1913 {
1914     return m_layerForFooter.get();
1915 }
1916 #endif
1917
1918 void RenderLayerCompositor::setIsInWindowForLayerIncludingDescendants(RenderLayer& layer, bool isInWindow)
1919 {
1920     if (layer.isComposited() && layer.backing()->usingTiledBacking())
1921         layer.backing()->tiledBacking()->setIsInWindow(isInWindow);
1922
1923     // No need to recurse if we don't have any other tiled layers.
1924     if (hasNonMainLayersWithTiledBacking())
1925         return;
1926
1927     for (RenderLayer* childLayer = layer.firstChild(); childLayer; childLayer = childLayer->nextSibling())
1928         setIsInWindowForLayerIncludingDescendants(*childLayer, isInWindow);
1929 }
1930
1931 void RenderLayerCompositor::setIsInWindow(bool isInWindow)
1932 {
1933     setIsInWindowForLayerIncludingDescendants(*m_renderView.layer(), isInWindow);
1934     
1935     if (!inCompositingMode())
1936         return;
1937
1938     if (isInWindow) {
1939         if (m_rootLayerAttachment != RootLayerUnattached)
1940             return;
1941
1942         RootLayerAttachment attachment = shouldPropagateCompositingToEnclosingFrame() ? RootLayerAttachedViaEnclosingFrame : RootLayerAttachedViaChromeClient;
1943         attachRootLayer(attachment);
1944 #if PLATFORM(IOS)
1945         registerAllViewportConstrainedLayers();
1946         registerAllScrollingLayers();
1947 #endif
1948     } else {
1949         if (m_rootLayerAttachment == RootLayerUnattached)
1950             return;
1951
1952         detachRootLayer();
1953 #if PLATFORM(IOS)
1954         unregisterAllViewportConstrainedLayers();
1955         unregisterAllScrollingLayers();
1956 #endif
1957     }
1958 }
1959
1960 void RenderLayerCompositor::clearBackingForLayerIncludingDescendants(RenderLayer& layer)
1961 {
1962     if (layer.isComposited()) {
1963         removeFromScrollCoordinatedLayers(layer);
1964         layer.clearBacking();
1965     }
1966
1967     for (RenderLayer* childLayer = layer.firstChild(); childLayer; childLayer = childLayer->nextSibling())
1968         clearBackingForLayerIncludingDescendants(*childLayer);
1969 }
1970
1971 void RenderLayerCompositor::clearBackingForAllLayers()
1972 {
1973     clearBackingForLayerIncludingDescendants(*m_renderView.layer());
1974 }
1975
1976 void RenderLayerCompositor::updateRootLayerPosition()
1977 {
1978     if (m_rootContentLayer) {
1979         const IntRect& documentRect = m_renderView.documentRect();
1980         m_rootContentLayer->setSize(documentRect.size());        
1981         m_rootContentLayer->setPosition(FloatPoint(documentRect.x(), documentRect.y()
1982             + FrameView::yPositionForRootContentLayer(m_renderView.frameView().scrollPosition(), m_renderView.frameView().topContentInset(), m_renderView.frameView().headerHeight())));
1983         m_rootContentLayer->setAnchorPoint(FloatPoint3D());
1984     }
1985     if (m_clipLayer) {
1986         m_clipLayer->setSize(m_renderView.frameView().unscaledTotalVisibleContentSize());
1987         m_clipLayer->setPosition(positionForClipLayer());
1988     }
1989
1990 #if ENABLE(RUBBER_BANDING)
1991     if (m_contentShadowLayer) {
1992         m_contentShadowLayer->setPosition(m_rootContentLayer->position());
1993         m_contentShadowLayer->setSize(m_rootContentLayer->size());
1994     }
1995
1996     updateLayerForTopOverhangArea(m_layerForTopOverhangArea != nullptr);
1997     updateLayerForBottomOverhangArea(m_layerForBottomOverhangArea != nullptr);
1998     updateLayerForHeader(m_layerForHeader != nullptr);
1999     updateLayerForFooter(m_layerForFooter != nullptr);
2000 #endif
2001 }
2002
2003 bool RenderLayerCompositor::has3DContent() const
2004 {
2005     return layerHas3DContent(rootRenderLayer());
2006 }
2007
2008 bool RenderLayerCompositor::allowsIndependentlyCompositedFrames(const FrameView* view)
2009 {
2010 #if PLATFORM(MAC)
2011     // frames are only independently composited in Mac pre-WebKit2.
2012     return view->platformWidget();
2013 #else
2014     UNUSED_PARAM(view);
2015 #endif
2016     return false;
2017 }
2018
2019 bool RenderLayerCompositor::shouldPropagateCompositingToEnclosingFrame() const
2020 {
2021     // Parent document content needs to be able to render on top of a composited frame, so correct behavior
2022     // is to have the parent document become composited too. However, this can cause problems on platforms that
2023     // use native views for frames (like Mac), so disable that behavior on those platforms for now.
2024     HTMLFrameOwnerElement* ownerElement = m_renderView.document().ownerElement();
2025     RenderElement* renderer = ownerElement ? ownerElement->renderer() : 0;
2026
2027     // If we are the top-level frame, don't propagate.
2028     if (!ownerElement)
2029         return false;
2030
2031     if (!allowsIndependentlyCompositedFrames(&m_renderView.frameView()))
2032         return true;
2033
2034     if (!renderer || !renderer->isWidget())
2035         return false;
2036
2037     // On Mac, only propagate compositing if the frame is overlapped in the parent
2038     // document, or the parent is already compositing, or the main frame is scaled.
2039     Page* page = this->page();
2040     if (page && page->pageScaleFactor() != 1)
2041         return true;
2042     
2043     RenderWidget* frameRenderer = toRenderWidget(renderer);
2044     if (frameRenderer->widget()) {
2045         ASSERT(frameRenderer->widget()->isFrameView());
2046         FrameView* view = toFrameView(frameRenderer->widget());
2047         if (view->isOverlappedIncludingAncestors() || view->hasCompositingAncestor())
2048             return true;
2049     }
2050
2051     return false;
2052 }
2053
2054 bool RenderLayerCompositor::needsToBeComposited(const RenderLayer& layer, RenderLayer::ViewportConstrainedNotCompositedReason* viewportConstrainedNotCompositedReason) const
2055 {
2056     if (!canBeComposited(layer))
2057         return false;
2058
2059     return requiresCompositingLayer(layer, viewportConstrainedNotCompositedReason) || layer.mustCompositeForIndirectReasons() || (inCompositingMode() && layer.isRootLayer());
2060 }
2061
2062 // Note: this specifies whether the RL needs a compositing layer for intrinsic reasons.
2063 // Use needsToBeComposited() to determine if a RL actually needs a compositing layer.
2064 // static
2065 bool RenderLayerCompositor::requiresCompositingLayer(const RenderLayer& layer, RenderLayer::ViewportConstrainedNotCompositedReason* viewportConstrainedNotCompositedReason) const
2066 {
2067     auto renderer = &layer.renderer();
2068
2069     // The compositing state of a reflection should match that of its reflected layer.
2070     if (layer.isReflection())
2071         renderer = toRenderLayerModelObject(renderer->parent()); // The RenderReplica's parent is the object being reflected.
2072
2073     // The root layer always has a compositing layer, but it may not have backing.
2074     return requiresCompositingForTransform(*renderer)
2075         || requiresCompositingForVideo(*renderer)
2076         || requiresCompositingForCanvas(*renderer)
2077         || requiresCompositingForPlugin(*renderer)
2078         || requiresCompositingForFrame(*renderer)
2079         || requiresCompositingForBackfaceVisibility(*renderer)
2080         || clipsCompositingDescendants(*renderer->layer())
2081         || requiresCompositingForAnimation(*renderer)
2082         || requiresCompositingForFilters(*renderer)
2083         || requiresCompositingForPosition(*renderer, *renderer->layer(), viewportConstrainedNotCompositedReason)
2084 #if PLATFORM(IOS)
2085         || requiresCompositingForScrolling(*renderer->layer())
2086 #endif
2087         || requiresCompositingForOverflowScrolling(*renderer->layer());
2088 }
2089
2090 bool RenderLayerCompositor::canBeComposited(const RenderLayer& layer) const
2091 {
2092     if (m_hasAcceleratedCompositing && layer.isSelfPaintingLayer()) {
2093         if (!layer.isInsideFlowThread())
2094             return true;
2095
2096         // CSS Regions flow threads do not need to be composited as we use composited RenderRegions
2097         // to render the background of the RenderFlowThread.
2098         if (layer.isRenderFlowThread())
2099             return false;
2100
2101         return true;
2102     }
2103     return false;
2104 }
2105
2106 bool RenderLayerCompositor::requiresOwnBackingStore(const RenderLayer& layer, const RenderLayer* compositingAncestorLayer, const LayoutRect& layerCompositedBoundsInAncestor, const LayoutRect& ancestorCompositedBounds) const
2107 {
2108     auto& renderer = layer.renderer();
2109
2110     if (compositingAncestorLayer
2111         && !(compositingAncestorLayer->backing()->graphicsLayer()->drawsContent()
2112             || compositingAncestorLayer->backing()->paintsIntoWindow()
2113             || compositingAncestorLayer->backing()->paintsIntoCompositedAncestor()))
2114         return true;
2115
2116     if (layer.isRootLayer()
2117         || layer.transform() // note: excludes perspective and transformStyle3D.
2118         || requiresCompositingForVideo(renderer)
2119         || requiresCompositingForCanvas(renderer)
2120         || requiresCompositingForPlugin(renderer)
2121         || requiresCompositingForFrame(renderer)
2122         || requiresCompositingForBackfaceVisibility(renderer)
2123         || requiresCompositingForAnimation(renderer)
2124         || requiresCompositingForFilters(renderer)
2125         || requiresCompositingForPosition(renderer, layer)
2126         || requiresCompositingForOverflowScrolling(layer)
2127         || renderer.isTransparent()
2128         || renderer.hasMask()
2129         || renderer.hasReflection()
2130         || renderer.hasFilter()
2131 #if PLATFORM(IOS)
2132         || requiresCompositingForScrolling(layer)
2133 #endif
2134         )
2135         return true;
2136         
2137     
2138     if (layer.mustCompositeForIndirectReasons()) {
2139         RenderLayer::IndirectCompositingReason reason = layer.indirectCompositingReason();
2140         return reason == RenderLayer::IndirectCompositingForOverlap
2141             || reason == RenderLayer::IndirectCompositingForStacking
2142             || reason == RenderLayer::IndirectCompositingForBackgroundLayer
2143             || reason == RenderLayer::IndirectCompositingForGraphicalEffect
2144             || reason == RenderLayer::IndirectCompositingForPreserve3D; // preserve-3d has to create backing store to ensure that 3d-transformed elements intersect.
2145     }
2146
2147     if (!ancestorCompositedBounds.contains(layerCompositedBoundsInAncestor))
2148         return true;
2149
2150     return false;
2151 }
2152
2153 CompositingReasons RenderLayerCompositor::reasonsForCompositing(const RenderLayer& layer) const
2154 {
2155     CompositingReasons reasons = CompositingReasonNone;
2156
2157     if (!layer.isComposited())
2158         return reasons;
2159
2160     auto renderer = &layer.renderer();
2161     if (layer.isReflection())
2162         renderer = toRenderLayerModelObject(renderer->parent());
2163
2164     if (requiresCompositingForTransform(*renderer))
2165         reasons |= CompositingReason3DTransform;
2166
2167     if (requiresCompositingForVideo(*renderer))
2168         reasons |= CompositingReasonVideo;
2169     else if (requiresCompositingForCanvas(*renderer))
2170         reasons |= CompositingReasonCanvas;
2171     else if (requiresCompositingForPlugin(*renderer))
2172         reasons |= CompositingReasonPlugin;
2173     else if (requiresCompositingForFrame(*renderer))
2174         reasons |= CompositingReasonIFrame;
2175     
2176     if ((canRender3DTransforms() && renderer->style().backfaceVisibility() == BackfaceVisibilityHidden))
2177         reasons |= CompositingReasonBackfaceVisibilityHidden;
2178
2179     if (clipsCompositingDescendants(*renderer->layer()))
2180         reasons |= CompositingReasonClipsCompositingDescendants;
2181
2182     if (requiresCompositingForAnimation(*renderer))
2183         reasons |= CompositingReasonAnimation;
2184
2185     if (requiresCompositingForFilters(*renderer))
2186         reasons |= CompositingReasonFilters;
2187
2188     if (requiresCompositingForPosition(*renderer, *renderer->layer()))
2189         reasons |= renderer->style().position() == FixedPosition ? CompositingReasonPositionFixed : CompositingReasonPositionSticky;
2190
2191 #if PLATFORM(IOS)
2192     if (requiresCompositingForScrolling(*renderer->layer()))
2193         reasons |= CompositingReasonOverflowScrollingTouch;
2194 #endif
2195
2196     if (requiresCompositingForOverflowScrolling(*renderer->layer()))
2197         reasons |= CompositingReasonOverflowScrollingTouch;
2198
2199     if (renderer->layer()->indirectCompositingReason() == RenderLayer::IndirectCompositingForStacking)
2200         reasons |= CompositingReasonStacking;
2201     else if (renderer->layer()->indirectCompositingReason() == RenderLayer::IndirectCompositingForOverlap)
2202         reasons |= CompositingReasonOverlap;
2203     else if (renderer->layer()->indirectCompositingReason() == RenderLayer::IndirectCompositingForBackgroundLayer)
2204         reasons |= CompositingReasonNegativeZIndexChildren;
2205     else if (renderer->layer()->indirectCompositingReason() == RenderLayer::IndirectCompositingForGraphicalEffect) {
2206         if (renderer->layer()->transform())
2207             reasons |= CompositingReasonTransformWithCompositedDescendants;
2208
2209         if (renderer->isTransparent())
2210             reasons |= CompositingReasonOpacityWithCompositedDescendants;
2211
2212         if (renderer->hasMask())
2213             reasons |= CompositingReasonMaskWithCompositedDescendants;
2214
2215         if (renderer->hasReflection())
2216             reasons |= CompositingReasonReflectionWithCompositedDescendants;
2217
2218         if (renderer->hasFilter())
2219             reasons |= CompositingReasonFilterWithCompositedDescendants;
2220
2221 #if ENABLE(CSS_COMPOSITING)
2222         if (layer.isolatesCompositedBlending())
2223             reasons |= CompositingReasonIsolatesCompositedBlendingDescendants;
2224
2225         if (layer.hasBlendMode())
2226             reasons |= CompositingReasonBlendingWithCompositedDescendants;
2227 #endif
2228
2229     } else if (renderer->layer()->indirectCompositingReason() == RenderLayer::IndirectCompositingForPerspective)
2230         reasons |= CompositingReasonPerspective;
2231     else if (renderer->layer()->indirectCompositingReason() == RenderLayer::IndirectCompositingForPreserve3D)
2232         reasons |= CompositingReasonPreserve3D;
2233
2234     if (inCompositingMode() && renderer->layer()->isRootLayer())
2235         reasons |= CompositingReasonRoot;
2236
2237     return reasons;
2238 }
2239
2240 #if !LOG_DISABLED
2241 const char* RenderLayerCompositor::logReasonsForCompositing(const RenderLayer& layer)
2242 {
2243     CompositingReasons reasons = reasonsForCompositing(layer);
2244
2245     if (reasons & CompositingReason3DTransform)
2246         return "3D transform";
2247
2248     if (reasons & CompositingReasonVideo)
2249         return "video";
2250     else if (reasons & CompositingReasonCanvas)
2251         return "canvas";
2252     else if (reasons & CompositingReasonPlugin)
2253         return "plugin";
2254     else if (reasons & CompositingReasonIFrame)
2255         return "iframe";
2256     
2257     if (reasons & CompositingReasonBackfaceVisibilityHidden)
2258         return "backface-visibility: hidden";
2259
2260     if (reasons & CompositingReasonClipsCompositingDescendants)
2261         return "clips compositing descendants";
2262
2263     if (reasons & CompositingReasonAnimation)
2264         return "animation";
2265
2266     if (reasons & CompositingReasonFilters)
2267         return "filters";
2268
2269     if (reasons & CompositingReasonPositionFixed)
2270         return "position: fixed";
2271
2272     if (reasons & CompositingReasonPositionSticky)
2273         return "position: sticky";
2274
2275     if (reasons & CompositingReasonOverflowScrollingTouch)
2276         return "-webkit-overflow-scrolling: touch";
2277
2278     if (reasons & CompositingReasonStacking)
2279         return "stacking";
2280
2281     if (reasons & CompositingReasonOverlap)
2282         return "overlap";
2283
2284     if (reasons & CompositingReasonNegativeZIndexChildren)
2285         return "negative z-index children";
2286
2287     if (reasons & CompositingReasonTransformWithCompositedDescendants)
2288         return "transform with composited descendants";
2289
2290     if (reasons & CompositingReasonOpacityWithCompositedDescendants)
2291         return "opacity with composited descendants";
2292
2293     if (reasons & CompositingReasonMaskWithCompositedDescendants)
2294         return "mask with composited descendants";
2295
2296     if (reasons & CompositingReasonReflectionWithCompositedDescendants)
2297         return "reflection with composited descendants";
2298
2299     if (reasons & CompositingReasonFilterWithCompositedDescendants)
2300         return "filter with composited descendants";
2301
2302 #if ENABLE(CSS_COMPOSITING)
2303     if (reasons & CompositingReasonBlendingWithCompositedDescendants)
2304         return "blending with composited descendants";
2305
2306     if (reasons & CompositingReasonIsolatesCompositedBlendingDescendants)
2307         return "isolates composited blending descendants";
2308 #endif
2309
2310     if (reasons & CompositingReasonPerspective)
2311         return "perspective";
2312
2313     if (reasons & CompositingReasonPreserve3D)
2314         return "preserve-3d";
2315
2316     if (reasons & CompositingReasonRoot)
2317         return "root";
2318
2319     return "";
2320 }
2321 #endif
2322
2323 // Return true if the given layer has some ancestor in the RenderLayer hierarchy that clips,
2324 // up to the enclosing compositing ancestor. This is required because compositing layers are parented
2325 // according to the z-order hierarchy, yet clipping goes down the renderer hierarchy.
2326 // Thus, a RenderLayer can be clipped by a RenderLayer that is an ancestor in the renderer hierarchy,
2327 // but a sibling in the z-order hierarchy.
2328 bool RenderLayerCompositor::clippedByAncestor(RenderLayer& layer) const
2329 {
2330     if (!layer.isComposited() || !layer.parent())
2331         return false;
2332
2333     RenderLayer* compositingAncestor = layer.ancestorCompositingLayer();
2334     if (!compositingAncestor)
2335         return false;
2336
2337     // If the compositingAncestor clips, that will be taken care of by clipsCompositingDescendants(),
2338     // so we only care about clipping between its first child that is our ancestor (the computeClipRoot),
2339     // and layer. The exception is when the compositingAncestor isolates composited blending children,
2340     // in this case it is not allowed to clipsCompositingDescendants() and each of its children
2341     // will be clippedByAncestor()s, including the compositingAncestor.
2342     RenderLayer* computeClipRoot = compositingAncestor;
2343     if (!compositingAncestor->isolatesCompositedBlending()) {
2344         computeClipRoot = nullptr;
2345         RenderLayer* parent = &layer;
2346         while (parent) {
2347             RenderLayer* next = parent->parent();
2348             if (next == compositingAncestor) {
2349                 computeClipRoot = parent;
2350                 break;
2351             }
2352             parent = next;
2353         }
2354
2355         if (!computeClipRoot || computeClipRoot == &layer)
2356             return false;
2357     }
2358
2359     return layer.backgroundClipRect(RenderLayer::ClipRectsContext(computeClipRoot, TemporaryClipRects)).rect() != LayoutRect::infiniteRect(); // FIXME: Incorrect for CSS regions.
2360 }
2361
2362 // Return true if the given layer is a stacking context and has compositing child
2363 // layers that it needs to clip. In this case we insert a clipping GraphicsLayer
2364 // into the hierarchy between this layer and its children in the z-order hierarchy.
2365 bool RenderLayerCompositor::clipsCompositingDescendants(const RenderLayer& layer) const
2366 {
2367     return layer.hasCompositingDescendant() && layer.renderer().hasClipOrOverflowClip() && !layer.isolatesCompositedBlending();
2368 }
2369
2370 bool RenderLayerCompositor::requiresCompositingForScrollableFrame() const
2371 {
2372     // Need this done first to determine overflow.
2373     ASSERT(!m_renderView.needsLayout());
2374     HTMLFrameOwnerElement* ownerElement = m_renderView.document().ownerElement();
2375     if (!ownerElement)
2376         return false;
2377
2378     if (!(m_compositingTriggers & ChromeClient::ScrollableInnerFrameTrigger))
2379         return false;
2380
2381     return m_renderView.frameView().isScrollable();
2382 }
2383
2384 bool RenderLayerCompositor::requiresCompositingForTransform(RenderLayerModelObject& renderer) const
2385 {
2386     if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
2387         return false;
2388
2389     // Note that we ask the renderer if it has a transform, because the style may have transforms,
2390     // but the renderer may be an inline that doesn't suppport them.
2391     return renderer.hasTransform() && renderer.style().transform().has3DOperation();
2392 }
2393
2394 bool RenderLayerCompositor::requiresCompositingForBackfaceVisibility(RenderLayerModelObject& renderer) const
2395 {
2396     if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
2397         return false;
2398
2399     return renderer.style().backfaceVisibility() == BackfaceVisibilityHidden && renderer.layer()->has3DTransformedAncestor();
2400 }
2401
2402 bool RenderLayerCompositor::requiresCompositingForVideo(RenderLayerModelObject& renderer) const
2403 {
2404     if (!(m_compositingTriggers & ChromeClient::VideoTrigger))
2405         return false;
2406 #if ENABLE(VIDEO)
2407     if (renderer.isVideo()) {
2408         RenderVideo& video = toRenderVideo(renderer);
2409         return (video.requiresImmediateCompositing() || video.shouldDisplayVideo()) && canAccelerateVideoRendering(video);
2410     }
2411 #else
2412     UNUSED_PARAM(renderer);
2413 #endif
2414     return false;
2415 }
2416
2417 bool RenderLayerCompositor::requiresCompositingForCanvas(RenderLayerModelObject& renderer) const
2418 {
2419     if (!(m_compositingTriggers & ChromeClient::CanvasTrigger))
2420         return false;
2421
2422     if (renderer.isCanvas()) {
2423 #if USE(COMPOSITING_FOR_SMALL_CANVASES)
2424         bool isCanvasLargeEnoughToForceCompositing = true;
2425 #else
2426         HTMLCanvasElement* canvas = toHTMLCanvasElement(renderer.element());
2427         bool isCanvasLargeEnoughToForceCompositing = canvas->size().area() >= canvasAreaThresholdRequiringCompositing;
2428 #endif
2429         CanvasCompositingStrategy compositingStrategy = canvasCompositingStrategy(renderer);
2430         return compositingStrategy == CanvasAsLayerContents || (compositingStrategy == CanvasPaintedToLayer && isCanvasLargeEnoughToForceCompositing);
2431     }
2432
2433     return false;
2434 }
2435
2436 bool RenderLayerCompositor::requiresCompositingForPlugin(RenderLayerModelObject& renderer) const
2437 {
2438     if (!(m_compositingTriggers & ChromeClient::PluginTrigger))
2439         return false;
2440
2441     bool composite = renderer.isEmbeddedObject() && toRenderEmbeddedObject(&renderer)->allowsAcceleratedCompositing();
2442     if (!composite)
2443         return false;
2444
2445     m_reevaluateCompositingAfterLayout = true;
2446     
2447     RenderWidget& pluginRenderer = *toRenderWidget(&renderer);
2448     // If we can't reliably know the size of the plugin yet, don't change compositing state.
2449     if (pluginRenderer.needsLayout())
2450         return pluginRenderer.hasLayer() && pluginRenderer.layer()->isComposited();
2451
2452     // Don't go into compositing mode if height or width are zero, or size is 1x1.
2453     IntRect contentBox = pixelSnappedIntRect(pluginRenderer.contentBoxRect());
2454     return contentBox.height() * contentBox.width() > 1;
2455 }
2456
2457 bool RenderLayerCompositor::requiresCompositingForFrame(RenderLayerModelObject& renderer) const
2458 {
2459     if (!renderer.isWidget())
2460         return false;
2461
2462     RenderWidget& frameRenderer = *toRenderWidget(&renderer);
2463
2464     if (!frameRenderer.requiresAcceleratedCompositing())
2465         return false;
2466
2467     m_reevaluateCompositingAfterLayout = true;
2468
2469     RenderLayerCompositor* innerCompositor = frameContentsCompositor(&frameRenderer);
2470     if (!innerCompositor || !innerCompositor->shouldPropagateCompositingToEnclosingFrame())
2471         return false;
2472
2473     // If we can't reliably know the size of the iframe yet, don't change compositing state.
2474     if (!frameRenderer.parent() || frameRenderer.needsLayout())
2475         return frameRenderer.hasLayer() && frameRenderer.layer()->isComposited();
2476     
2477     // Don't go into compositing mode if height or width are zero.
2478     return !pixelSnappedIntRect(frameRenderer.contentBoxRect()).isEmpty();
2479 }
2480
2481 bool RenderLayerCompositor::requiresCompositingForAnimation(RenderLayerModelObject& renderer) const
2482 {
2483     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
2484         return false;
2485
2486     const AnimationBase::RunningState activeAnimationState = AnimationBase::Running | AnimationBase::Paused | AnimationBase::FillingFowards;
2487     AnimationController& animController = renderer.animation();
2488     return (animController.isRunningAnimationOnRenderer(&renderer, CSSPropertyOpacity, activeAnimationState)
2489             && (inCompositingMode() || (m_compositingTriggers & ChromeClient::AnimatedOpacityTrigger)))
2490 #if ENABLE(CSS_FILTERS)
2491             || animController.isRunningAnimationOnRenderer(&renderer, CSSPropertyWebkitFilter, activeAnimationState)
2492 #endif // CSS_FILTERS
2493             || animController.isRunningAnimationOnRenderer(&renderer, CSSPropertyWebkitTransform, activeAnimationState);
2494 }
2495
2496 bool RenderLayerCompositor::requiresCompositingForIndirectReason(RenderLayerModelObject& renderer, bool hasCompositedDescendants, bool has3DTransformedDescendants, RenderLayer::IndirectCompositingReason& reason) const
2497 {
2498     RenderLayer& layer = *toRenderBoxModelObject(renderer).layer();
2499
2500     // When a layer has composited descendants, some effects, like 2d transforms, filters, masks etc must be implemented
2501     // via compositing so that they also apply to those composited descendants.
2502     if (hasCompositedDescendants && (layer.isolatesCompositedBlending() || layer.transform() || renderer.createsGroup() || renderer.hasReflection() || renderer.isRenderNamedFlowFragmentContainer())) {
2503         reason = RenderLayer::IndirectCompositingForGraphicalEffect;
2504         return true;
2505     }
2506
2507     // A layer with preserve-3d or perspective only needs to be composited if there are descendant layers that
2508     // will be affected by the preserve-3d or perspective.
2509     if (has3DTransformedDescendants) {
2510         if (renderer.style().transformStyle3D() == TransformStyle3DPreserve3D) {
2511             reason = RenderLayer::IndirectCompositingForPreserve3D;
2512             return true;
2513         }
2514     
2515         if (renderer.style().hasPerspective()) {
2516             reason = RenderLayer::IndirectCompositingForPerspective;
2517             return true;
2518         }
2519     }
2520
2521     reason = RenderLayer::NoIndirectCompositingReason;
2522     return false;
2523 }
2524
2525 bool RenderLayerCompositor::requiresCompositingForFilters(RenderLayerModelObject& renderer) const
2526 {
2527 #if ENABLE(CSS_FILTERS)
2528     if (!(m_compositingTriggers & ChromeClient::FilterTrigger))
2529         return false;
2530
2531     return renderer.hasFilter();
2532 #else
2533     UNUSED_PARAM(renderer);
2534     return false;
2535 #endif
2536 }
2537
2538 bool RenderLayerCompositor::isAsyncScrollableStickyLayer(const RenderLayer& layer, const RenderLayer** enclosingAcceleratedOverflowLayer) const
2539 {
2540     ASSERT(layer.renderer().isStickyPositioned());
2541
2542     RenderLayer* enclosingOverflowLayer = layer.enclosingOverflowClipLayer(ExcludeSelf);
2543
2544 #if PLATFORM(IOS)
2545     if (enclosingOverflowLayer && enclosingOverflowLayer->hasTouchScrollableOverflow()) {
2546         if (enclosingAcceleratedOverflowLayer)
2547             *enclosingAcceleratedOverflowLayer = enclosingOverflowLayer;
2548         return true;
2549     }
2550 #else
2551     UNUSED_PARAM(enclosingAcceleratedOverflowLayer);
2552 #endif
2553     // If the layer is inside normal overflow, it's not async-scrollable.
2554     if (enclosingOverflowLayer)
2555         return false;
2556
2557     // No overflow ancestor, so see if the frame supports async scrolling.
2558     if (hasCoordinatedScrolling())
2559         return true;
2560
2561 #if PLATFORM(IOS)
2562     // iOS WK1 has fixed/sticky support in the main frame via WebFixedPositionContent.
2563     return m_renderView.frameView().frame().isMainFrame();
2564 #else
2565     return false;
2566 #endif
2567 }
2568
2569 bool RenderLayerCompositor::isViewportConstrainedFixedOrStickyLayer(const RenderLayer& layer) const
2570 {
2571     if (layer.renderer().isStickyPositioned())
2572         return isAsyncScrollableStickyLayer(layer);
2573
2574     if (layer.renderer().style().position() != FixedPosition)
2575         return false;
2576
2577     // FIXME: Handle fixed inside of a transform, which should not behave as fixed.
2578     for (RenderLayer* stackingContainer = layer.stackingContainer(); stackingContainer; stackingContainer = stackingContainer->stackingContainer()) {
2579         if (stackingContainer->isComposited() && stackingContainer->renderer().style().position() == FixedPosition)
2580             return false;
2581     }
2582
2583     return true;
2584 }
2585
2586 static bool useCoordinatedScrollingForLayer(RenderView& view, const RenderLayer& layer)
2587 {
2588     if (layer.isRootLayer() && view.frameView().frame().isMainFrame())
2589         return true;
2590
2591 #if PLATFORM(IOS)
2592     return layer.hasTouchScrollableOverflow();
2593 #else
2594     return layer.needsCompositedScrolling();
2595 #endif
2596 }
2597
2598 bool RenderLayerCompositor::requiresCompositingForPosition(RenderLayerModelObject& renderer, const RenderLayer& layer, RenderLayer::ViewportConstrainedNotCompositedReason* viewportConstrainedNotCompositedReason) const
2599 {
2600     // position:fixed elements that create their own stacking context (e.g. have an explicit z-index,
2601     // opacity, transform) can get their own composited layer. A stacking context is required otherwise
2602     // z-index and clipping will be broken.
2603     if (!renderer.isPositioned())
2604         return false;
2605     
2606     EPosition position = renderer.style().position();
2607     bool isFixed = renderer.isOutOfFlowPositioned() && position == FixedPosition;
2608     if (isFixed && !layer.isStackingContainer())
2609         return false;
2610     
2611     bool isSticky = renderer.isInFlowPositioned() && position == StickyPosition;
2612     if (!isFixed && !isSticky)
2613         return false;
2614
2615     // FIXME: acceleratedCompositingForFixedPositionEnabled should probably be renamed acceleratedCompositingForViewportConstrainedPositionEnabled().
2616     const Settings& settings = m_renderView.frameView().frame().settings();
2617     if (!settings.acceleratedCompositingForFixedPositionEnabled())
2618         return false;
2619
2620     if (isSticky)
2621         return isAsyncScrollableStickyLayer(layer);
2622
2623     auto container = renderer.container();
2624     // If the renderer is not hooked up yet then we have to wait until it is.
2625     if (!container) {
2626         m_reevaluateCompositingAfterLayout = true;
2627         return false;
2628     }
2629
2630     // Don't promote fixed position elements that are descendants of a non-view container, e.g. transformed elements.
2631     // They will stay fixed wrt the container rather than the enclosing frame.
2632     if (container != &m_renderView && !renderer.fixedPositionedWithNamedFlowContainingBlock()) {
2633         if (viewportConstrainedNotCompositedReason)
2634             *viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForNonViewContainer;
2635         return false;
2636     }
2637     
2638     // Subsequent tests depend on layout. If we can't tell now, just keep things the way they are until layout is done.
2639     if (!m_inPostLayoutUpdate) {
2640         m_reevaluateCompositingAfterLayout = true;
2641         return layer.isComposited();
2642     }
2643
2644     bool paintsContent = layer.isVisuallyNonEmpty() || layer.hasVisibleDescendant();
2645     if (!paintsContent) {
2646         if (viewportConstrainedNotCompositedReason)
2647             *viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForNoVisibleContent;
2648         return false;
2649     }
2650
2651     // Fixed position elements that are invisible in the current view don't get their own layer.
2652     LayoutRect viewBounds = m_renderView.frameView().viewportConstrainedVisibleContentRect();
2653     LayoutRect layerBounds = layer.calculateLayerBounds(&layer, LayoutSize(), RenderLayer::UseLocalClipRectIfPossible | RenderLayer::IncludeLayerFilterOutsets | RenderLayer::UseFragmentBoxesExcludingCompositing
2654         | RenderLayer::ExcludeHiddenDescendants | RenderLayer::DontConstrainForMask | RenderLayer::IncludeCompositedDescendants);
2655     // Map to m_renderView to ignore page scale.
2656     FloatRect absoluteBounds = layer.renderer().localToContainerQuad(FloatRect(layerBounds), &m_renderView).boundingBox();
2657     if (!viewBounds.intersects(enclosingIntRect(absoluteBounds))) {
2658         if (viewportConstrainedNotCompositedReason)
2659             *viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForBoundsOutOfView;
2660         return false;
2661     }
2662     
2663     return true;
2664 }
2665
2666 bool RenderLayerCompositor::requiresCompositingForOverflowScrolling(const RenderLayer& layer) const
2667 {
2668     return layer.needsCompositedScrolling();
2669 }
2670
2671 #if PLATFORM(IOS)
2672 bool RenderLayerCompositor::requiresCompositingForScrolling(const RenderLayer& layer) const
2673 {
2674     if (!layer.hasAcceleratedTouchScrolling())
2675         return false;
2676
2677     if (!m_inPostLayoutUpdate) {
2678         m_reevaluateCompositingAfterLayout = true;
2679         return layer.isComposited();
2680     }
2681
2682     return layer.hasTouchScrollableOverflow();
2683 }
2684 #endif
2685
2686 bool RenderLayerCompositor::isRunningAcceleratedTransformAnimation(RenderLayerModelObject& renderer) const
2687 {
2688     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
2689         return false;
2690
2691     return renderer.animation().isRunningAcceleratedAnimationOnRenderer(&renderer, CSSPropertyWebkitTransform, AnimationBase::Running | AnimationBase::Paused);
2692 }
2693
2694 // If an element has negative z-index children, those children render in front of the 
2695 // layer background, so we need an extra 'contents' layer for the foreground of the layer
2696 // object.
2697 bool RenderLayerCompositor::needsContentsCompositingLayer(const RenderLayer& layer) const
2698 {
2699     return layer.hasNegativeZOrderList();
2700 }
2701
2702 bool RenderLayerCompositor::requiresScrollLayer(RootLayerAttachment attachment) const
2703 {
2704     FrameView& frameView = m_renderView.frameView();
2705
2706     // This applies when the application UI handles scrolling, in which case RenderLayerCompositor doesn't need to manage it.
2707     if (frameView.delegatesScrolling() && frameView.frame().isMainFrame())
2708         return false;
2709
2710     // We need to handle our own scrolling if we're:
2711     return !m_renderView.frameView().platformWidget() // viewless (i.e. non-Mac, or Mac in WebKit2)
2712         || attachment == RootLayerAttachedViaEnclosingFrame; // a composited frame on Mac
2713 }
2714
2715 static void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
2716 {
2717     if (!scrollbar)
2718         return;
2719
2720     context.save();
2721     const IntRect& scrollbarRect = scrollbar->frameRect();
2722     context.translate(-scrollbarRect.x(), -scrollbarRect.y());
2723     IntRect transformedClip = clip;
2724     transformedClip.moveBy(scrollbarRect.location());
2725     scrollbar->paint(&context, transformedClip);
2726     context.restore();
2727 }
2728
2729 void RenderLayerCompositor::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, GraphicsLayerPaintingPhase, const FloatRect& clip)
2730 {
2731     IntRect pixelSnappedRectForIntegralPositionedItems = pixelSnappedIntRect(LayoutRect(clip));
2732     if (graphicsLayer == layerForHorizontalScrollbar())
2733         paintScrollbar(m_renderView.frameView().horizontalScrollbar(), context, pixelSnappedRectForIntegralPositionedItems);
2734     else if (graphicsLayer == layerForVerticalScrollbar())
2735         paintScrollbar(m_renderView.frameView().verticalScrollbar(), context, pixelSnappedRectForIntegralPositionedItems);
2736     else if (graphicsLayer == layerForScrollCorner()) {
2737         const IntRect& scrollCorner = m_renderView.frameView().scrollCornerRect();
2738         context.save();
2739         context.translate(-scrollCorner.x(), -scrollCorner.y());
2740         IntRect transformedClip = pixelSnappedRectForIntegralPositionedItems;
2741         transformedClip.moveBy(scrollCorner.location());
2742         m_renderView.frameView().paintScrollCorner(&context, transformedClip);
2743         context.restore();
2744     }
2745 }
2746
2747 bool RenderLayerCompositor::supportsFixedRootBackgroundCompositing() const
2748 {
2749     RenderLayerBacking* renderViewBacking = m_renderView.layer()->backing();
2750     return renderViewBacking && renderViewBacking->usingTiledBacking();
2751 }
2752
2753 bool RenderLayerCompositor::needsFixedRootBackgroundLayer(const RenderLayer& layer) const
2754 {
2755     if (&layer != m_renderView.layer())
2756         return false;
2757
2758     if (m_renderView.frameView().frame().settings().fixedBackgroundsPaintRelativeToDocument())
2759         return false;
2760
2761     return supportsFixedRootBackgroundCompositing() && m_renderView.rootBackgroundIsEntirelyFixed();
2762 }
2763
2764 GraphicsLayer* RenderLayerCompositor::fixedRootBackgroundLayer() const
2765 {
2766     // Get the fixed root background from the RenderView layer's backing.
2767     RenderLayer* viewLayer = m_renderView.layer();
2768     if (!viewLayer)
2769         return nullptr;
2770
2771     if (viewLayer->isComposited() && viewLayer->backing()->backgroundLayerPaintsFixedRootBackground())
2772         return viewLayer->backing()->backgroundLayer();
2773
2774     return nullptr;
2775 }
2776
2777 static void resetTrackedRepaintRectsRecursive(GraphicsLayer& graphicsLayer)
2778 {
2779     graphicsLayer.resetTrackedRepaints();
2780
2781     for (size_t i = 0, size = graphicsLayer.children().size(); i < size; ++i)
2782         resetTrackedRepaintRectsRecursive(*graphicsLayer.children()[i]);
2783
2784     if (GraphicsLayer* replicaLayer = graphicsLayer.replicaLayer())
2785         resetTrackedRepaintRectsRecursive(*replicaLayer);
2786
2787     if (GraphicsLayer* maskLayer = graphicsLayer.maskLayer())
2788         resetTrackedRepaintRectsRecursive(*maskLayer);
2789 }
2790
2791 void RenderLayerCompositor::resetTrackedRepaintRects()
2792 {
2793     if (GraphicsLayer* rootLayer = rootGraphicsLayer())
2794         resetTrackedRepaintRectsRecursive(*rootLayer);
2795 }
2796
2797 void RenderLayerCompositor::setTracksRepaints(bool tracksRepaints)
2798 {
2799     m_isTrackingRepaints = tracksRepaints;
2800 }
2801
2802 bool RenderLayerCompositor::isTrackingRepaints() const
2803 {
2804     return m_isTrackingRepaints;
2805 }
2806
2807 float RenderLayerCompositor::deviceScaleFactor() const
2808 {
2809     Page* page = this->page();
2810     return page ? page->deviceScaleFactor() : 1;
2811 }
2812
2813 float RenderLayerCompositor::pageScaleFactor() const
2814 {
2815     Page* page = this->page();
2816     return page ? page->pageScaleFactor() : 1;
2817 }
2818
2819 float RenderLayerCompositor::zoomedOutPageScaleFactor() const
2820 {
2821     Page* page = this->page();
2822     return page ? page->zoomedOutPageScaleFactor() : 0;
2823 }
2824
2825 float RenderLayerCompositor::contentsScaleMultiplierForNewTiles(const GraphicsLayer*) const
2826 {
2827 #if PLATFORM(IOS)
2828     LegacyTileCache* tileCache = nullptr;
2829     if (Page* page = this->page()) {
2830         if (FrameView* frameView = page->mainFrame().view())
2831             tileCache = frameView->legacyTileCache();
2832     }
2833
2834     if (!tileCache)
2835         return 1;
2836
2837     return tileCache->tileControllerShouldUseLowScaleTiles() ? 0.125 : 1;
2838 #else
2839     return 1;
2840 #endif
2841 }
2842
2843 void RenderLayerCompositor::didCommitChangesForLayer(const GraphicsLayer*) const
2844 {
2845     // Nothing to do here yet.
2846 }
2847
2848 bool RenderLayerCompositor::mainFrameBackingIsTiled() const
2849 {
2850     RenderLayer* layer = m_renderView.layer();
2851     if (!layer)
2852         return false;
2853
2854     RenderLayerBacking* backing = layer->backing();
2855     if (!backing)
2856         return false;
2857
2858     return backing->usingTiledBacking();
2859 }
2860
2861 bool RenderLayerCompositor::shouldCompositeOverflowControls() const
2862 {
2863     FrameView& frameView = m_renderView.frameView();
2864
2865     if (frameView.platformWidget())
2866         return false;
2867
2868     if (frameView.delegatesScrolling())
2869         return false;
2870
2871     if (mainFrameBackingIsTiled())
2872         return true;
2873
2874     if (!frameView.hasOverlayScrollbars())
2875         return false;
2876
2877     return true;
2878 }
2879
2880 bool RenderLayerCompositor::requiresHorizontalScrollbarLayer() const
2881 {
2882     return shouldCompositeOverflowControls() && m_renderView.frameView().horizontalScrollbar();
2883 }
2884
2885 bool RenderLayerCompositor::requiresVerticalScrollbarLayer() const
2886 {
2887     return shouldCompositeOverflowControls() && m_renderView.frameView().verticalScrollbar();
2888 }
2889
2890 bool RenderLayerCompositor::requiresScrollCornerLayer() const
2891 {
2892     return shouldCompositeOverflowControls() && m_renderView.frameView().isScrollCornerVisible();
2893 }
2894
2895 #if ENABLE(RUBBER_BANDING)
2896 bool RenderLayerCompositor::requiresOverhangAreasLayer() const
2897 {
2898     // We don't want a layer if this is a subframe.
2899     if (m_renderView.document().ownerElement())
2900         return false;
2901
2902     // We do want a layer if we're using tiled drawing and can scroll.
2903     if (mainFrameBackingIsTiled() && m_renderView.frameView().hasOpaqueBackground() && !m_renderView.frameView().prohibitsScrolling())
2904         return true;
2905
2906     return false;
2907 }
2908
2909 bool RenderLayerCompositor::requiresContentShadowLayer() const
2910 {
2911     // We don't want a layer if this is a subframe.
2912     if (m_renderView.document().ownerElement())
2913         return false;
2914
2915 #if PLATFORM(COCOA)
2916     if (viewHasTransparentBackground())
2917         return false;
2918
2919     // If the background is going to extend, then it doesn't make sense to have a shadow layer.
2920     if (m_renderView.frameView().frame().settings().backgroundShouldExtendBeyondPage())
2921         return false;
2922
2923     // On Mac, we want a content shadow layer if we're using tiled drawing and can scroll.
2924     if (mainFrameBackingIsTiled() && !m_renderView.frameView().prohibitsScrolling())
2925         return true;
2926 #endif
2927
2928     return false;
2929 }
2930
2931 GraphicsLayer* RenderLayerCompositor::updateLayerForTopOverhangArea(bool wantsLayer)
2932 {
2933     if (m_renderView.document().ownerElement())
2934         return 0;
2935
2936     if (!wantsLayer) {
2937         if (m_layerForTopOverhangArea) {
2938             m_layerForTopOverhangArea->removeFromParent();
2939             m_layerForTopOverhangArea = nullptr;
2940         }
2941         return 0;
2942     }
2943
2944     if (!m_layerForTopOverhangArea) {
2945         m_layerForTopOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), *this);
2946 #ifndef NDEBUG
2947         m_layerForTopOverhangArea->setName("top overhang area");
2948 #endif
2949         m_scrollLayer->addChildBelow(m_layerForTopOverhangArea.get(), m_rootContentLayer.get());
2950     }
2951
2952     return m_layerForTopOverhangArea.get();
2953 }
2954
2955 GraphicsLayer* RenderLayerCompositor::updateLayerForBottomOverhangArea(bool wantsLayer)
2956 {
2957     if (m_renderView.document().ownerElement())
2958         return 0;
2959
2960     if (!wantsLayer) {
2961         if (m_layerForBottomOverhangArea) {
2962             m_layerForBottomOverhangArea->removeFromParent();
2963             m_layerForBottomOverhangArea = nullptr;
2964         }
2965         return 0;
2966     }
2967
2968     if (!m_layerForBottomOverhangArea) {
2969         m_layerForBottomOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), *this);
2970 #ifndef NDEBUG
2971         m_layerForBottomOverhangArea->setName("bottom overhang area");
2972 #endif
2973         m_scrollLayer->addChildBelow(m_layerForBottomOverhangArea.get(), m_rootContentLayer.get());
2974     }
2975
2976     m_layerForBottomOverhangArea->setPosition(FloatPoint(0, m_rootContentLayer->size().height() + m_renderView.frameView().headerHeight()
2977         + m_renderView.frameView().footerHeight() + m_renderView.frameView().topContentInset()));
2978     return m_layerForBottomOverhangArea.get();
2979 }
2980
2981 GraphicsLayer* RenderLayerCompositor::updateLayerForHeader(bool wantsLayer)
2982 {
2983     if (m_renderView.document().ownerElement())
2984         return 0;
2985
2986     if (!wantsLayer) {
2987         if (m_layerForHeader) {
2988             m_layerForHeader->removeFromParent();
2989             m_layerForHeader = nullptr;
2990
2991             // The ScrollingTree knows about the header layer, and the position of the root layer is affected
2992             // by the header layer, so if we remove the header, we need to tell the scrolling tree.
2993             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2994                 scrollingCoordinator->frameViewRootLayerDidChange(&m_renderView.frameView());
2995         }
2996         return 0;
2997     }
2998
2999     if (!m_layerForHeader) {
3000         m_layerForHeader = GraphicsLayer::create(graphicsLayerFactory(), *this);
3001 #ifndef NDEBUG
3002         m_layerForHeader->setName("header");
3003 #endif
3004         m_scrollLayer->addChildAbove(m_layerForHeader.get(), m_rootContentLayer.get());
3005         m_renderView.frameView().addPaintPendingMilestones(DidFirstFlushForHeaderLayer);
3006     }
3007
3008     m_layerForHeader->setPosition(FloatPoint(0,
3009         FrameView::yPositionForHeaderLayer(m_renderView.frameView().scrollPosition(), m_renderView.frameView().topContentInset())));
3010     m_layerForHeader->setAnchorPoint(FloatPoint3D());
3011     m_layerForHeader->setSize(FloatSize(m_renderView.frameView().visibleWidth(), m_renderView.frameView().headerHeight()));
3012
3013     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3014         scrollingCoordinator->frameViewRootLayerDidChange(&m_renderView.frameView());
3015
3016     if (Page* page = this->page())
3017         page->chrome().client().didAddHeaderLayer(m_layerForHeader.get());
3018
3019     return m_layerForHeader.get();
3020 }
3021
3022 GraphicsLayer* RenderLayerCompositor::updateLayerForFooter(bool wantsLayer)
3023 {
3024     if (m_renderView.document().ownerElement())
3025         return 0;
3026
3027     if (!wantsLayer) {
3028         if (m_layerForFooter) {
3029             m_layerForFooter->removeFromParent();
3030             m_layerForFooter = nullptr;
3031
3032             // The ScrollingTree knows about the footer layer, and the total scrollable size is affected
3033             // by the footer layer, so if we remove the footer, we need to tell the scrolling tree.
3034             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3035                 scrollingCoordinator->frameViewRootLayerDidChange(&m_renderView.frameView());
3036         }
3037         return 0;
3038     }
3039
3040     if (!m_layerForFooter) {
3041         m_layerForFooter = GraphicsLayer::create(graphicsLayerFactory(), *this);
3042 #ifndef NDEBUG
3043         m_layerForFooter->setName("footer");
3044 #endif
3045         m_scrollLayer->addChildAbove(m_layerForFooter.get(), m_rootContentLayer.get());
3046     }
3047
3048     float totalContentHeight = m_rootContentLayer->size().height() + m_renderView.frameView().headerHeight() + m_renderView.frameView().footerHeight();
3049     m_layerForFooter->setPosition(FloatPoint(0, FrameView::yPositionForFooterLayer(m_renderView.frameView().scrollPosition(),
3050         m_renderView.frameView().topContentInset(), totalContentHeight, m_renderView.frameView().footerHeight())));
3051     m_layerForFooter->setAnchorPoint(FloatPoint3D());
3052     m_layerForFooter->setSize(FloatSize(m_renderView.frameView().visibleWidth(), m_renderView.frameView().footerHeight()));
3053
3054     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3055         scrollingCoordinator->frameViewRootLayerDidChange(&m_renderView.frameView());
3056
3057     if (Page* page = this->page())
3058         page->chrome().client().didAddFooterLayer(m_layerForFooter.get());
3059
3060     return m_layerForFooter.get();
3061 }
3062
3063 #endif
3064
3065 bool RenderLayerCompositor::viewHasTransparentBackground(Color* backgroundColor) const
3066 {
3067     if (m_renderView.frameView().isTransparent()) {
3068         if (backgroundColor)
3069             *backgroundColor = Color(); // Return an invalid color.
3070         return true;
3071     }
3072
3073     Color documentBackgroundColor = m_renderView.frameView().documentBackgroundColor();
3074     if (!documentBackgroundColor.isValid())
3075         documentBackgroundColor = Color::white;
3076
3077     if (backgroundColor)
3078         *backgroundColor = documentBackgroundColor;
3079         
3080     return documentBackgroundColor.hasAlpha();
3081 }
3082
3083 void RenderLayerCompositor::setRootExtendedBackgroundColor(const Color& color)
3084 {
3085     if (color == m_rootExtendedBackgroundColor)
3086         return;
3087
3088     m_rootExtendedBackgroundColor = color;
3089
3090     if (Page* page = this->page())
3091         page->chrome().client().pageExtendedBackgroundColorDidChange(color);
3092
3093 #if ENABLE(RUBBER_BANDING)
3094     if (!m_layerForOverhangAreas)
3095         return;
3096
3097     m_layerForOverhangAreas->setBackgroundColor(m_rootExtendedBackgroundColor);
3098
3099     if (!m_rootExtendedBackgroundColor.isValid())
3100         m_layerForOverhangAreas->setCustomAppearance(GraphicsLayer::ScrollingOverhang);
3101 #endif
3102 }
3103
3104 void RenderLayerCompositor::updateOverflowControlsLayers()
3105 {
3106 #if ENABLE(RUBBER_BANDING)
3107     if (requiresOverhangAreasLayer()) {
3108         if (!m_layerForOverhangAreas) {
3109             m_layerForOverhangAreas = GraphicsLayer::create(graphicsLayerFactory(), *this);
3110 #ifndef NDEBUG
3111             m_layerForOverhangAreas->setName("overhang areas");
3112 #endif
3113             m_layerForOverhangAreas->setDrawsContent(false);
3114
3115             float topContentInset = m_renderView.frameView().topContentInset();
3116             IntSize overhangAreaSize = m_renderView.frameView().frameRect().size();
3117             overhangAreaSize.setHeight(overhangAreaSize.height() - topContentInset);
3118             m_layerForOverhangAreas->setSize(overhangAreaSize);
3119             m_layerForOverhangAreas->setPosition(FloatPoint(0, topContentInset));
3120             m_layerForOverhangAreas->setAnchorPoint(FloatPoint3D());
3121
3122             if (m_renderView.frameView().frame().settings().backgroundShouldExtendBeyondPage())
3123                 m_layerForOverhangAreas->setBackgroundColor(m_renderView.frameView().documentBackgroundColor());
3124             else
3125                 m_layerForOverhangAreas->setCustomAppearance(GraphicsLayer::ScrollingOverhang);
3126
3127             // We want the overhang areas layer to be positioned below the frame contents,
3128             // so insert it below the clip layer.
3129             m_overflowControlsHostLayer->addChildBelow(m_layerForOverhangAreas.get(), m_clipLayer.get());
3130         }
3131     } else if (m_layerForOverhangAreas) {
3132         m_layerForOverhangAreas->removeFromParent();
3133         m_layerForOverhangAreas = nullptr;
3134     }
3135
3136     if (requiresContentShadowLayer()) {
3137         if (!m_contentShadowLayer) {
3138             m_contentShadowLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3139 #ifndef NDEBUG
3140             m_contentShadowLayer->setName("content shadow");
3141 #endif
3142             m_contentShadowLayer->setSize(m_rootContentLayer->size());
3143             m_contentShadowLayer->setPosition(m_rootContentLayer->position());
3144             m_contentShadowLayer->setAnchorPoint(FloatPoint3D());
3145             m_contentShadowLayer->setCustomAppearance(GraphicsLayer::ScrollingShadow);
3146
3147             m_scrollLayer->addChildBelow(m_contentShadowLayer.get(), m_rootContentLayer.get());
3148         }
3149     } else if (m_contentShadowLayer) {
3150         m_contentShadowLayer->removeFromParent();
3151         m_contentShadowLayer = nullptr;
3152     }
3153 #endif
3154
3155     if (requiresHorizontalScrollbarLayer()) {
3156         if (!m_layerForHorizontalScrollbar) {
3157             m_layerForHorizontalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), *this);
3158             m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
3159 #ifndef NDEBUG
3160             m_layerForHorizontalScrollbar->setName("horizontal scrollbar container");
3161
3162 #endif
3163 #if PLATFORM(COCOA) && USE(CA)
3164             m_layerForHorizontalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
3165 #endif
3166             m_overflowControlsHostLayer->addChild(m_layerForHorizontalScrollbar.get());
3167
3168             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3169                 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_renderView.frameView(), HorizontalScrollbar);
3170         }
3171     } else if (m_layerForHorizontalScrollbar) {
3172         m_layerForHorizontalScrollbar->removeFromParent();
3173         m_layerForHorizontalScrollbar = nullptr;
3174
3175         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3176             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_renderView.frameView(), HorizontalScrollbar);
3177     }
3178
3179     if (requiresVerticalScrollbarLayer()) {
3180         if (!m_layerForVerticalScrollbar) {
3181             m_layerForVerticalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), *this);
3182             m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
3183 #ifndef NDEBUG
3184             m_layerForVerticalScrollbar->setName("vertical scrollbar container");
3185 #endif
3186 #if PLATFORM(COCOA) && USE(CA)
3187             m_layerForVerticalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
3188 #endif
3189             m_overflowControlsHostLayer->addChild(m_layerForVerticalScrollbar.get());
3190
3191             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3192                 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_renderView.frameView(), VerticalScrollbar);
3193         }
3194     } else if (m_layerForVerticalScrollbar) {
3195         m_layerForVerticalScrollbar->removeFromParent();
3196         m_layerForVerticalScrollbar = nullptr;
3197
3198         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3199             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_renderView.frameView(), VerticalScrollbar);
3200     }
3201
3202     if (requiresScrollCornerLayer()) {
3203         if (!m_layerForScrollCorner) {
3204             m_layerForScrollCorner = GraphicsLayer::create(graphicsLayerFactory(), *this);
3205             m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
3206 #ifndef NDEBUG
3207             m_layerForScrollCorner->setName("scroll corner");
3208 #endif
3209 #if PLATFORM(COCOA) && USE(CA)
3210             m_layerForScrollCorner->setAcceleratesDrawing(acceleratedDrawingEnabled());
3211 #endif
3212             m_overflowControlsHostLayer->addChild(m_layerForScrollCorner.get());
3213         }
3214     } else if (m_layerForScrollCorner) {
3215         m_layerForScrollCorner->removeFromParent();
3216         m_layerForScrollCorner = nullptr;
3217     }
3218
3219     m_renderView.frameView().positionScrollbarLayers();
3220 }
3221
3222 void RenderLayerCompositor::ensureRootLayer()
3223 {
3224     RootLayerAttachment expectedAttachment = shouldPropagateCompositingToEnclosingFrame() ? RootLayerAttachedViaEnclosingFrame : RootLayerAttachedViaChromeClient;
3225     if (expectedAttachment == m_rootLayerAttachment)
3226          return;
3227
3228     if (!m_rootContentLayer) {
3229         m_rootContentLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3230 #ifndef NDEBUG
3231         m_rootContentLayer->setName("content root");
3232 #endif
3233         IntRect overflowRect = m_renderView.pixelSnappedLayoutOverflowRect();
3234         m_rootContentLayer->setSize(FloatSize(overflowRect.maxX(), overflowRect.maxY()));
3235         m_rootContentLayer->setPosition(FloatPoint());
3236
3237 #if PLATFORM(IOS) || PLATFORM(EFL)
3238         // Page scale is applied above this on iOS, so we'll just say that our root layer applies it.
3239         Frame& frame = m_renderView.frameView().frame();
3240         if (frame.isMainFrame())
3241             m_rootContentLayer->setAppliesPageScale();
3242 #endif
3243
3244         // Need to clip to prevent transformed content showing outside this frame
3245         m_rootContentLayer->setMasksToBounds(true);
3246     }
3247
3248     if (requiresScrollLayer(expectedAttachment)) {
3249         if (!m_overflowControlsHostLayer) {
3250             ASSERT(!m_scrollLayer);
3251             ASSERT(!m_clipLayer);
3252
3253             // Create a layer to host the clipping layer and the overflow controls layers.
3254             m_overflowControlsHostLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3255 #ifndef NDEBUG
3256             m_overflowControlsHostLayer->setName("overflow controls host");
3257 #endif
3258
3259             // Create a clipping layer if this is an iframe
3260             m_clipLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3261 #ifndef NDEBUG
3262             m_clipLayer->setName("frame clipping");
3263 #endif
3264             m_clipLayer->setMasksToBounds(true);
3265             
3266             m_scrollLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
3267 #ifndef NDEBUG
3268             m_scrollLayer->setName("frame scrolling");
3269 #endif
3270             // Hook them up
3271             m_overflowControlsHostLayer->addChild(m_clipLayer.get());
3272             m_clipLayer->addChild(m_scrollLayer.get());
3273             m_scrollLayer->addChild(m_rootContentLayer.get());
3274
3275             m_clipLayer->setSize(m_renderView.frameView().unscaledTotalVisibleContentSize());
3276             m_clipLayer->setPosition(positionForClipLayer());
3277             m_clipLayer->setAnchorPoint(FloatPoint3D());
3278
3279             updateOverflowControlsLayers();
3280
3281             if (hasCoordinatedScrolling())
3282                 scheduleLayerFlush(true);
3283             else
3284                 updateScrollLayerPosition();
3285         }
3286     } else {
3287         if (m_overflowControlsHostLayer) {
3288             m_overflowControlsHostLayer = nullptr;
3289             m_clipLayer = nullptr;
3290             m_scrollLayer = nullptr;
3291         }
3292     }
3293
3294     // Check to see if we have to change the attachment
3295     if (m_rootLayerAttachment != RootLayerUnattached)
3296         detachRootLayer();
3297
3298     attachRootLayer(expectedAttachment);
3299 }
3300
3301 void RenderLayerCompositor::destroyRootLayer()
3302 {
3303     if (!m_rootContentLayer)
3304         return;
3305
3306     detachRootLayer();
3307
3308 #if ENABLE(RUBBER_BANDING)
3309     if (m_layerForOverhangAreas) {
3310         m_layerForOverhangAreas->removeFromParent();
3311         m_layerForOverhangAreas = nullptr;
3312     }
3313 #endif
3314
3315     if (m_layerForHorizontalScrollbar) {
3316         m_layerForHorizontalScrollbar->removeFromParent();
3317         m_layerForHorizontalScrollbar = nullptr;
3318         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3319             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_renderView.frameView(), HorizontalScrollbar);
3320         if (Scrollbar* horizontalScrollbar = m_renderView.frameView().verticalScrollbar())
3321             m_renderView.frameView().invalidateScrollbar(horizontalScrollbar, IntRect(IntPoint(0, 0), horizontalScrollbar->frameRect().size()));