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