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