[EFL][WK2] Extract the control of page background out of color_set
[WebKit-https.git] / Source / WebCore / rendering / RenderLayerCompositor.cpp
1 /*
2  * Copyright (C) 2009, 2010 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27
28 #include "RenderLayerCompositor.h"
29
30 #include "AnimationController.h"
31 #include "CanvasRenderingContext.h"
32 #include "CSSPropertyNames.h"
33 #include "Chrome.h"
34 #include "ChromeClient.h"
35 #include "FlowThreadController.h"
36 #include "Frame.h"
37 #include "FrameView.h"
38 #include "GraphicsLayer.h"
39 #include "HTMLCanvasElement.h"
40 #include "HTMLIFrameElement.h"
41 #include "HTMLNames.h"
42 #include "HitTestResult.h"
43 #include "InspectorInstrumentation.h"
44 #include "Logging.h"
45 #include "MainFrame.h"
46 #include "NodeList.h"
47 #include "Page.h"
48 #include "ProgressTracker.h"
49 #include "RenderEmbeddedObject.h"
50 #include "RenderFlowThread.h"
51 #include "RenderFullScreen.h"
52 #include "RenderGeometryMap.h"
53 #include "RenderIFrame.h"
54 #include "RenderLayerBacking.h"
55 #include "RenderNamedFlowFragment.h"
56 #include "RenderReplica.h"
57 #include "RenderVideo.h"
58 #include "RenderView.h"
59 #include "ScrollingConstraints.h"
60 #include "ScrollingCoordinator.h"
61 #include "Settings.h"
62 #include "TiledBacking.h"
63 #include "TransformState.h"
64 #include <wtf/CurrentTime.h>
65 #include <wtf/TemporaryChange.h>
66 #include <wtf/text/CString.h>
67 #include <wtf/text/StringBuilder.h>
68
69 #if PLATFORM(IOS)
70 #include "LegacyTileCache.h"
71 #include "MainFrame.h"
72 #include "Region.h"
73 #include "RenderScrollbar.h"
74 #endif
75
76 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
77 #include "HTMLAudioElement.h"
78 #include "HTMLMediaElement.h"
79 #endif
80
81 #ifndef NDEBUG
82 #include "RenderTreeAsText.h"
83 #endif
84
85 #if ENABLE(3D_RENDERING)
86 // This symbol is used to determine from a script whether 3D rendering is enabled (via 'nm').
87 bool WebCoreHas3DRendering = true;
88 #endif
89
90 #if !PLATFORM(MAC) && !PLATFORM(IOS)
91 #define WTF_USE_COMPOSITING_FOR_SMALL_CANVASES 1
92 #endif
93
94 namespace WebCore {
95
96 static const int canvasAreaThresholdRequiringCompositing = 50 * 100;
97 // During page loading delay layer flushes up to this many seconds to allow them coalesce, reducing workload.
98 #if PLATFORM(IOS)
99 static const double throttledLayerFlushInitialDelay = .5;
100 static const double throttledLayerFlushDelay = 1.5;
101 #else
102 static const double throttledLayerFlushInitialDelay = .5;
103 static const double throttledLayerFlushDelay = .5;
104 #endif
105
106 using namespace HTMLNames;
107
108 class RenderLayerCompositor::OverlapMap {
109     WTF_MAKE_NONCOPYABLE(OverlapMap);
110 public:
111     OverlapMap()
112         : m_geometryMap(UseTransforms)
113     {
114         // Begin assuming the root layer will be composited so that there is
115         // something on the stack. The root layer should also never get an
116         // popCompositingContainer call.
117         pushCompositingContainer();
118     }
119
120     void add(const RenderLayer* layer, const IntRect& bounds)
121     {
122         // Layers do not contribute to overlap immediately--instead, they will
123         // contribute to overlap as soon as their composited ancestor has been
124         // recursively processed and popped off the stack.
125         ASSERT(m_overlapStack.size() >= 2);
126         m_overlapStack[m_overlapStack.size() - 2].append(bounds);
127         m_layers.add(layer);
128     }
129
130     bool contains(const RenderLayer* layer)
131     {
132         return m_layers.contains(layer);
133     }
134
135     bool overlapsLayers(const IntRect& bounds) const
136     {
137         return m_overlapStack.last().intersects(bounds);
138     }
139
140     bool isEmpty()
141     {
142         return m_layers.isEmpty();
143     }
144
145     void pushCompositingContainer()
146     {
147         m_overlapStack.append(RectList());
148     }
149
150     void popCompositingContainer()
151     {
152         m_overlapStack[m_overlapStack.size() - 2].append(m_overlapStack.last());
153         m_overlapStack.removeLast();
154     }
155
156     RenderGeometryMap& geometryMap() { return m_geometryMap; }
157
158 private:
159     struct RectList {
160         Vector<IntRect> rects;
161         IntRect boundingRect;
162         
163         void append(const IntRect& rect)
164         {
165             rects.append(rect);
166             boundingRect.unite(rect);
167         }
168
169         void append(const RectList& rectList)
170         {
171             rects.appendVector(rectList.rects);
172             boundingRect.unite(rectList.boundingRect);
173         }
174         
175         bool intersects(const IntRect& rect) const
176         {
177             if (!rects.size() || !boundingRect.intersects(rect))
178                 return false;
179
180             for (unsigned i = 0; i < rects.size(); i++) {
181                 if (rects[i].intersects(rect))
182                     return true;
183             }
184             return false;
185         }
186     };
187
188     Vector<RectList> m_overlapStack;
189     HashSet<const RenderLayer*> m_layers;
190     RenderGeometryMap m_geometryMap;
191 };
192
193 struct CompositingState {
194     CompositingState(RenderLayer* compAncestor, bool testOverlap = true)
195         : m_compositingAncestor(compAncestor)
196         , m_subtreeIsCompositing(false)
197         , m_testingOverlap(testOverlap)
198         , m_subtreeHasBlending(false)
199 #ifndef NDEBUG
200         , m_depth(0)
201 #endif
202     {
203     }
204     
205     CompositingState(const CompositingState& other)
206         : m_compositingAncestor(other.m_compositingAncestor)
207         , m_subtreeIsCompositing(other.m_subtreeIsCompositing)
208         , m_testingOverlap(other.m_testingOverlap)
209         , m_subtreeHasBlending(other.m_subtreeHasBlending)
210 #ifndef NDEBUG
211         , m_depth(other.m_depth + 1)
212 #endif
213     {
214     }
215     
216     RenderLayer* m_compositingAncestor;
217     bool m_subtreeIsCompositing;
218     bool m_testingOverlap;
219     bool m_subtreeHasBlending;
220 #ifndef NDEBUG
221     int m_depth;
222 #endif
223 };
224
225
226 #if !LOG_DISABLED
227 static inline bool compositingLogEnabled()
228 {
229     return LogCompositing.state == WTFLogChannelOn;
230 }
231 #endif
232
233 RenderLayerCompositor::RenderLayerCompositor(RenderView& renderView)
234     : m_renderView(renderView)
235     , m_updateCompositingLayersTimer(this, &RenderLayerCompositor::updateCompositingLayersTimerFired)
236     , m_hasAcceleratedCompositing(true)
237     , m_compositingTriggers(static_cast<ChromeClient::CompositingTriggerFlags>(ChromeClient::AllTriggers))
238     , m_compositedLayerCount(0)
239     , m_showDebugBorders(false)
240     , m_showRepaintCounter(false)
241     , m_acceleratedDrawingEnabled(false)
242     , m_reevaluateCompositingAfterLayout(false)
243     , m_compositing(false)
244     , m_compositingLayersNeedRebuild(false)
245     , m_flushingLayers(false)
246     , m_shouldFlushOnReattach(false)
247     , m_forceCompositingMode(false)
248     , m_inPostLayoutUpdate(false)
249     , m_isTrackingRepaints(false)
250     , m_layersWithTiledBackingCount(0)
251     , m_rootLayerAttachment(RootLayerUnattached)
252     , m_layerFlushTimer(this, &RenderLayerCompositor::layerFlushTimerFired)
253     , m_layerFlushThrottlingEnabled(page() && page()->progress().isMainLoadProgressing())
254     , m_layerFlushThrottlingTemporarilyDisabledForInteraction(false)
255     , m_hasPendingLayerFlush(false)
256     , m_paintRelatedMilestonesTimer(this, &RenderLayerCompositor::paintRelatedMilestonesTimerFired)
257 #if !LOG_DISABLED
258     , m_rootLayerUpdateCount(0)
259     , m_obligateCompositedLayerCount(0)
260     , m_secondaryCompositedLayerCount(0)
261     , m_obligatoryBackingStoreBytes(0)
262     , m_secondaryBackingStoreBytes(0)
263 #endif
264 {
265 }
266
267 RenderLayerCompositor::~RenderLayerCompositor()
268 {
269     // Take care that the owned GraphicsLayers are deleted first as their destructors may call back here.
270     m_clipLayer = nullptr;
271     m_scrollLayer = nullptr;
272     ASSERT(m_rootLayerAttachment == RootLayerUnattached);
273 }
274
275 void RenderLayerCompositor::enableCompositingMode(bool enable /* = true */)
276 {
277     if (enable != m_compositing) {
278         m_compositing = enable;
279         
280         if (m_compositing) {
281             ensureRootLayer();
282             notifyIFramesOfCompositingChange();
283         } else
284             destroyRootLayer();
285     }
286 }
287
288 void RenderLayerCompositor::cacheAcceleratedCompositingFlags()
289 {
290     bool hasAcceleratedCompositing = false;
291     bool showDebugBorders = false;
292     bool showRepaintCounter = false;
293     bool forceCompositingMode = false;
294     bool acceleratedDrawingEnabled = false;
295
296     const Settings& settings = m_renderView.frameView().frame().settings();
297     hasAcceleratedCompositing = settings.acceleratedCompositingEnabled();
298
299     // We allow the chrome to override the settings, in case the page is rendered
300     // on a chrome that doesn't allow accelerated compositing.
301     if (hasAcceleratedCompositing) {
302         if (Page* page = this->page()) {
303             m_compositingTriggers = page->chrome().client().allowedCompositingTriggers();
304             hasAcceleratedCompositing = m_compositingTriggers;
305         }
306     }
307
308     showDebugBorders = settings.showDebugBorders();
309     showRepaintCounter = settings.showRepaintCounter();
310     forceCompositingMode = settings.forceCompositingMode() && hasAcceleratedCompositing;
311
312     if (forceCompositingMode && m_renderView.document().ownerElement())
313         forceCompositingMode = requiresCompositingForScrollableFrame();
314
315     acceleratedDrawingEnabled = settings.acceleratedDrawingEnabled();
316
317     if (hasAcceleratedCompositing != m_hasAcceleratedCompositing || showDebugBorders != m_showDebugBorders || showRepaintCounter != m_showRepaintCounter || forceCompositingMode != m_forceCompositingMode)
318         setCompositingLayersNeedRebuild();
319
320     bool debugBordersChanged = m_showDebugBorders != showDebugBorders;
321     m_hasAcceleratedCompositing = hasAcceleratedCompositing;
322     m_showDebugBorders = showDebugBorders;
323     m_showRepaintCounter = showRepaintCounter;
324     m_forceCompositingMode = forceCompositingMode;
325     m_acceleratedDrawingEnabled = acceleratedDrawingEnabled;
326     
327     if (debugBordersChanged) {
328         if (m_layerForHorizontalScrollbar)
329             m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
330
331         if (m_layerForVerticalScrollbar)
332             m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
333
334         if (m_layerForScrollCorner)
335             m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
336     }
337 }
338
339 bool RenderLayerCompositor::canRender3DTransforms() const
340 {
341     return hasAcceleratedCompositing() && (m_compositingTriggers & ChromeClient::ThreeDTransformTrigger);
342 }
343
344 void RenderLayerCompositor::setCompositingLayersNeedRebuild(bool needRebuild)
345 {
346     if (inCompositingMode())
347         m_compositingLayersNeedRebuild = needRebuild;
348 }
349
350 void RenderLayerCompositor::customPositionForVisibleRectComputation(const GraphicsLayer* graphicsLayer, FloatPoint& position) const
351 {
352     if (graphicsLayer != m_scrollLayer.get())
353         return;
354
355     FloatPoint scrollPosition = -position;
356
357     if (m_renderView.frameView().scrollBehaviorForFixedElements() == StickToDocumentBounds)
358         scrollPosition = m_renderView.frameView().constrainScrollPositionForOverhang(roundedIntPoint(scrollPosition));
359
360     position = -scrollPosition;
361 }
362
363 void RenderLayerCompositor::notifyFlushRequired(const GraphicsLayer* layer)
364 {
365     scheduleLayerFlush(layer->canThrottleLayerFlush());
366 }
367
368 void RenderLayerCompositor::scheduleLayerFlushNow()
369 {
370     m_hasPendingLayerFlush = false;
371     if (Page* page = this->page())
372         page->chrome().client().scheduleCompositingLayerFlush();
373 }
374
375 void RenderLayerCompositor::scheduleLayerFlush(bool canThrottle)
376 {
377     ASSERT(!m_flushingLayers);
378
379     if (canThrottle)
380         startInitialLayerFlushTimerIfNeeded();
381
382     if (canThrottle && isThrottlingLayerFlushes()) {
383         m_hasPendingLayerFlush = true;
384         return;
385     }
386     scheduleLayerFlushNow();
387 }
388
389 #if PLATFORM(IOS)
390 ChromeClient* RenderLayerCompositor::chromeClient() const
391 {
392     Page* page = m_renderView.frameView().frame().page();
393     if (!page)
394         return 0;
395     return &page->chrome().client();
396 }
397 #endif
398
399 void RenderLayerCompositor::flushPendingLayerChanges(bool isFlushRoot)
400 {
401     // FrameView::flushCompositingStateIncludingSubframes() flushes each subframe,
402     // but GraphicsLayer::flushCompositingState() will cross frame boundaries
403     // if the GraphicsLayers are connected (the RootLayerAttachedViaEnclosingFrame case).
404     // As long as we're not the root of the flush, we can bail.
405     if (!isFlushRoot && rootLayerAttachment() == RootLayerAttachedViaEnclosingFrame)
406         return;
407     
408     if (rootLayerAttachment() == RootLayerUnattached) {
409 #if PLATFORM(IOS)
410         startLayerFlushTimerIfNeeded();
411 #endif
412         m_shouldFlushOnReattach = true;
413         return;
414     }
415
416     FrameView& frameView = m_renderView.frameView();
417     AnimationUpdateBlock animationUpdateBlock(&frameView.frame().animation());
418
419     ASSERT(!m_flushingLayers);
420     m_flushingLayers = true;
421
422     if (GraphicsLayer* rootLayer = rootGraphicsLayer()) {
423 #if PLATFORM(IOS)
424         double horizontalMargin = defaultTileWidth / pageScaleFactor();
425         double verticalMargin = defaultTileHeight / pageScaleFactor();
426         rootLayer->flushCompositingState(frameView.computeCoverageRect(horizontalMargin, verticalMargin));
427 #else
428         // Having a m_clipLayer indicates that we're doing scrolling via GraphicsLayers.
429         IntRect visibleRect = m_clipLayer ? IntRect(IntPoint(), frameView.contentsSize()) : frameView.visibleContentRect();
430         rootLayer->flushCompositingState(visibleRect);
431 #endif
432     }
433     
434     ASSERT(m_flushingLayers);
435     m_flushingLayers = false;
436
437 #if PLATFORM(IOS)
438     updateCustomLayersAfterFlush();
439
440     ChromeClient* client = this->chromeClient();
441     if (client && isFlushRoot)
442         client->didFlushCompositingLayers();
443 #endif
444
445     for (auto it = m_scrollCoordinatedLayersNeedingUpdate.begin(), end = m_scrollCoordinatedLayersNeedingUpdate.end(); it != end; ++it)
446         updateScrollCoordinatedStatus(**it);
447
448     m_scrollCoordinatedLayersNeedingUpdate.clear();
449     startLayerFlushTimerIfNeeded();
450 }
451
452 #if PLATFORM(IOS)
453 static bool scrollbarHasDisplayNone(Scrollbar* scrollbar)
454 {
455     if (!scrollbar || !scrollbar->isCustomScrollbar())
456         return false;
457
458     RefPtr<RenderStyle> scrollbarStyle = static_cast<RenderScrollbar*>(scrollbar)->getScrollbarPseudoStyle(ScrollbarBGPart, SCROLLBAR);
459     return scrollbarStyle && scrollbarStyle->display() == NONE;
460 }
461
462 // FIXME: Can we make |layer| const RenderLayer&?
463 static void updateScrollingLayerWithClient(RenderLayer& layer, ChromeClient* client)
464 {
465     if (!client)
466         return;
467
468     RenderLayerBacking* backing = layer.backing();
469     ASSERT(backing);
470
471     bool allowHorizontalScrollbar = !scrollbarHasDisplayNone(layer.horizontalScrollbar());
472     bool allowVerticalScrollbar = !scrollbarHasDisplayNone(layer.verticalScrollbar());
473     client->addOrUpdateScrollingLayer(layer.renderer().element(), backing->scrollingLayer()->platformLayer(), backing->scrollingContentsLayer()->platformLayer(),
474         IntSize(layer.scrollWidth(), layer.scrollHeight()), allowHorizontalScrollbar, allowVerticalScrollbar);
475 }
476
477 void RenderLayerCompositor::updateCustomLayersAfterFlush()
478 {
479     registerAllViewportConstrainedLayers();
480
481     if (!m_scrollingLayersNeedingUpdate.isEmpty()) {
482         ChromeClient* chromeClient = this->chromeClient();
483
484         for (auto it = m_scrollingLayersNeedingUpdate.begin(), end = m_scrollingLayersNeedingUpdate.end(); it != end; ++it)
485             updateScrollingLayerWithClient(**it, chromeClient);
486         m_scrollingLayersNeedingUpdate.clear();
487     }
488     m_scrollingLayersNeedingUpdate.clear();
489 }
490 #endif
491
492 void RenderLayerCompositor::didFlushChangesForLayer(RenderLayer& layer, const GraphicsLayer* graphicsLayer)
493 {
494     if (m_scrollCoordinatedLayers.contains(&layer))
495         m_scrollCoordinatedLayersNeedingUpdate.add(&layer);
496
497 #if PLATFORM(IOS)
498     if (m_scrollingLayers.contains(&layer))
499         m_scrollingLayersNeedingUpdate.add(&layer);
500 #endif
501
502     RenderLayerBacking* backing = layer.backing();
503     if (backing->backgroundLayerPaintsFixedRootBackground() && graphicsLayer == backing->backgroundLayer())
504         fixedRootBackgroundLayerChanged();
505 }
506
507 void RenderLayerCompositor::didPaintBacking(RenderLayerBacking*)
508 {
509     FrameView& frameView = m_renderView.frameView();
510     frameView.setLastPaintTime(monotonicallyIncreasingTime());
511     if (frameView.milestonesPendingPaint() && !m_paintRelatedMilestonesTimer.isActive())
512         m_paintRelatedMilestonesTimer.startOneShot(0);
513 }
514
515 void RenderLayerCompositor::didChangeVisibleRect()
516 {
517     GraphicsLayer* rootLayer = rootGraphicsLayer();
518     if (!rootLayer)
519         return;
520
521     const FrameView& frameView = m_renderView.frameView();
522
523 #if PLATFORM(IOS)
524     IntRect visibleRect = frameView.exposedContentRect();
525 #else
526     IntRect visibleRect = m_clipLayer ? IntRect(IntPoint(), frameView.contentsSize()) : frameView.visibleContentRect();
527 #endif
528     if (!rootLayer->visibleRectChangeRequiresFlush(visibleRect))
529         return;
530     scheduleLayerFlushNow();
531 }
532
533 void RenderLayerCompositor::notifyFlushBeforeDisplayRefresh(const GraphicsLayer*)
534 {
535     if (!m_layerUpdater) {
536         PlatformDisplayID displayID = 0;
537         if (Page* page = this->page())
538             displayID = page->chrome().displayID();
539
540         m_layerUpdater = std::make_unique<GraphicsLayerUpdater>(this, displayID);
541     }
542     
543     m_layerUpdater->scheduleUpdate();
544 }
545
546 void RenderLayerCompositor::flushLayers(GraphicsLayerUpdater*)
547 {
548     flushPendingLayerChanges(true); // FIXME: deal with iframes
549 }
550
551 void RenderLayerCompositor::layerTiledBackingUsageChanged(const GraphicsLayer*, bool usingTiledBacking)
552 {
553     if (usingTiledBacking)
554         ++m_layersWithTiledBackingCount;
555     else {
556         ASSERT(m_layersWithTiledBackingCount > 0);
557         --m_layersWithTiledBackingCount;
558     }
559 }
560
561 RenderLayerCompositor* RenderLayerCompositor::enclosingCompositorFlushingLayers() const
562 {
563     for (Frame* frame = &m_renderView.frameView().frame(); frame; frame = frame->tree().parent()) {
564         RenderLayerCompositor* compositor = frame->contentRenderer() ? &frame->contentRenderer()->compositor() : 0;
565         if (compositor->isFlushingLayers())
566             return compositor;
567     }
568     
569     return 0;
570 }
571
572 void RenderLayerCompositor::scheduleCompositingLayerUpdate()
573 {
574     if (!m_updateCompositingLayersTimer.isActive())
575         m_updateCompositingLayersTimer.startOneShot(0);
576 }
577
578 void RenderLayerCompositor::updateCompositingLayersTimerFired(Timer<RenderLayerCompositor>&)
579 {
580     updateCompositingLayers(CompositingUpdateAfterLayout);
581 }
582
583 bool RenderLayerCompositor::hasAnyAdditionalCompositedLayers(const RenderLayer& rootLayer) const
584 {
585     return m_compositedLayerCount > (rootLayer.isComposited() ? 1 : 0);
586 }
587
588 void RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType updateType, RenderLayer* updateRoot)
589 {
590     m_updateCompositingLayersTimer.stop();
591     
592     // Compositing layers will be updated in Document::implicitClose() if suppressed here.
593     if (!m_renderView.document().visualUpdatesAllowed())
594         return;
595
596     // Avoid updating the layers with old values. Compositing layers will be updated after the layout is finished.
597     if (m_renderView.needsLayout())
598         return;
599
600     if (m_forceCompositingMode && !m_compositing)
601         enableCompositingMode(true);
602
603     if (!m_reevaluateCompositingAfterLayout && !m_compositing)
604         return;
605
606     AnimationUpdateBlock animationUpdateBlock(&m_renderView.frameView().frame().animation());
607
608     TemporaryChange<bool> postLayoutChange(m_inPostLayoutUpdate, true);
609     
610     bool checkForHierarchyUpdate = m_reevaluateCompositingAfterLayout;
611     bool needGeometryUpdate = false;
612
613     switch (updateType) {
614     case CompositingUpdateAfterStyleChange:
615     case CompositingUpdateAfterLayout:
616     case CompositingUpdateOnHitTest:
617         checkForHierarchyUpdate = true;
618         break;
619     case CompositingUpdateOnScroll:
620         checkForHierarchyUpdate = true; // Overlap can change with scrolling, so need to check for hierarchy updates.
621
622         needGeometryUpdate = true;
623         break;
624     case CompositingUpdateOnCompositedScroll:
625         needGeometryUpdate = true;
626         break;
627     }
628
629     if (!checkForHierarchyUpdate && !needGeometryUpdate)
630         return;
631
632     bool needHierarchyUpdate = m_compositingLayersNeedRebuild;
633     bool isFullUpdate = !updateRoot;
634
635     // Only clear the flag if we're updating the entire hierarchy.
636     m_compositingLayersNeedRebuild = false;
637     updateRoot = &rootRenderLayer();
638
639     if (isFullUpdate && updateType == CompositingUpdateAfterLayout)
640         m_reevaluateCompositingAfterLayout = false;
641
642 #if !LOG_DISABLED
643     double startTime = 0;
644     if (compositingLogEnabled()) {
645         ++m_rootLayerUpdateCount;
646         startTime = monotonicallyIncreasingTime();
647     }
648 #endif
649
650     if (checkForHierarchyUpdate) {
651         if (m_renderView.hasRenderNamedFlowThreads() && isFullUpdate)
652             m_renderView.flowThreadController().updateFlowThreadsLayerToRegionMappingsIfNeeded();
653         // Go through the layers in presentation order, so that we can compute which RenderLayers need compositing layers.
654         // FIXME: we could maybe do this and the hierarchy udpate in one pass, but the parenting logic would be more complex.
655         CompositingState compState(updateRoot);
656         bool layersChanged = false;
657         bool saw3DTransform = false;
658         OverlapMap overlapTestRequestMap;
659         computeCompositingRequirements(nullptr, *updateRoot, &overlapTestRequestMap, compState, layersChanged, saw3DTransform);
660         needHierarchyUpdate |= layersChanged;
661     }
662
663 #if !LOG_DISABLED
664     if (compositingLogEnabled() && isFullUpdate && (needHierarchyUpdate || needGeometryUpdate)) {
665         m_obligateCompositedLayerCount = 0;
666         m_secondaryCompositedLayerCount = 0;
667         m_obligatoryBackingStoreBytes = 0;
668         m_secondaryBackingStoreBytes = 0;
669
670         Frame& frame = m_renderView.frameView().frame();
671         bool isMainFrame = !m_renderView.document().ownerElement();
672         LOG(Compositing, "\nUpdate %d of %s.\n", m_rootLayerUpdateCount, isMainFrame ? "main frame" : frame.tree().uniqueName().string().utf8().data());
673     }
674 #endif
675
676     if (needHierarchyUpdate) {
677         // Update the hierarchy of the compositing layers.
678         Vector<GraphicsLayer*> childList;
679         rebuildCompositingLayerTree(*updateRoot, childList, 0);
680
681         // Host the document layer in the RenderView's root layer.
682         if (isFullUpdate) {
683             // Even when childList is empty, don't drop out of compositing mode if there are
684             // composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
685             if (childList.isEmpty() && !hasAnyAdditionalCompositedLayers(*updateRoot))
686                 destroyRootLayer();
687             else
688                 m_rootContentLayer->setChildren(childList);
689         }
690     } else if (needGeometryUpdate) {
691         // We just need to do a geometry update. This is only used for position:fixed scrolling;
692         // most of the time, geometry is updated via RenderLayer::styleChanged().
693         updateLayerTreeGeometry(*updateRoot, 0);
694     }
695     
696 #if !LOG_DISABLED
697     if (compositingLogEnabled() && isFullUpdate && (needHierarchyUpdate || needGeometryUpdate)) {
698         double endTime = monotonicallyIncreasingTime();
699         LOG(Compositing, "Total layers   primary   secondary   obligatory backing (KB)   secondary backing(KB)   total backing (KB)  update time (ms)\n");
700
701         LOG(Compositing, "%8d %11d %9d %20.2f %22.2f %22.2f %18.2f\n",
702             m_obligateCompositedLayerCount + m_secondaryCompositedLayerCount, m_obligateCompositedLayerCount,
703             m_secondaryCompositedLayerCount, m_obligatoryBackingStoreBytes / 1024, m_secondaryBackingStoreBytes / 1024, (m_obligatoryBackingStoreBytes + m_secondaryBackingStoreBytes) / 1024, 1000.0 * (endTime - startTime));
704     }
705 #endif
706     ASSERT(updateRoot || !m_compositingLayersNeedRebuild);
707
708     if (!hasAcceleratedCompositing())
709         enableCompositingMode(false);
710
711     // Inform the inspector that the layer tree has changed.
712     InspectorInstrumentation::layerTreeDidChange(page());
713 }
714
715 void RenderLayerCompositor::layerBecameNonComposited(const RenderLayer& layer)
716 {
717     // Inform the inspector that the given RenderLayer was destroyed.
718     InspectorInstrumentation::renderLayerDestroyed(page(), &layer);
719
720     ASSERT(m_compositedLayerCount > 0);
721     --m_compositedLayerCount;
722 }
723
724 #if !LOG_DISABLED
725 void RenderLayerCompositor::logLayerInfo(const RenderLayer& layer, int depth)
726 {
727     if (!compositingLogEnabled())
728         return;
729
730     RenderLayerBacking* backing = layer.backing();
731     if (requiresCompositingLayer(layer) || layer.isRootLayer()) {
732         ++m_obligateCompositedLayerCount;
733         m_obligatoryBackingStoreBytes += backing->backingStoreMemoryEstimate();
734     } else {
735         ++m_secondaryCompositedLayerCount;
736         m_secondaryBackingStoreBytes += backing->backingStoreMemoryEstimate();
737     }
738
739     StringBuilder logString;
740     logString.append(String::format("%*p %dx%d %.2fKB", 12 + depth * 2, &layer,
741         backing->compositedBounds().width().round(), backing->compositedBounds().height().round(),
742         backing->backingStoreMemoryEstimate() / 1024));
743     
744     logString.append(" (");
745     logString.append(logReasonsForCompositing(layer));
746     logString.append(") ");
747
748     if (backing->graphicsLayer()->contentsOpaque() || backing->paintsIntoCompositedAncestor()) {
749         logString.append('[');
750         if (backing->graphicsLayer()->contentsOpaque())
751             logString.append("opaque");
752         if (backing->paintsIntoCompositedAncestor())
753             logString.append("paints into ancestor");
754         logString.append("] ");
755     }
756
757     logString.append(layer.name());
758
759     LOG(Compositing, "%s", logString.toString().utf8().data());
760 }
761 #endif
762
763 bool RenderLayerCompositor::updateBacking(RenderLayer& layer, CompositingChangeRepaint shouldRepaint)
764 {
765     bool layerChanged = false;
766     RenderLayer::ViewportConstrainedNotCompositedReason viewportConstrainedNotCompositedReason = RenderLayer::NoNotCompositedReason;
767
768     if (needsToBeComposited(layer, &viewportConstrainedNotCompositedReason)) {
769         enableCompositingMode();
770         
771         if (!layer.backing()) {
772             // If we need to repaint, do so before making backing
773             if (shouldRepaint == CompositingChangeRepaintNow)
774                 repaintOnCompositingChange(layer);
775
776             layer.ensureBacking();
777
778             // At this time, the ScrollingCoordinator only supports the top-level frame.
779             if (layer.isRootLayer() && !m_renderView.document().ownerElement()) {
780                 updateScrollCoordinatedStatus(layer);
781                 if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
782                     scrollingCoordinator->frameViewRootLayerDidChange(&m_renderView.frameView());
783 #if ENABLE(RUBBER_BANDING)
784                 if (Page* page = this->page()) {
785                     updateLayerForHeader(page->headerHeight());
786                     updateLayerForFooter(page->footerHeight());
787                 }
788 #endif
789                 if (m_renderView.frameView().frame().settings().backgroundShouldExtendBeyondPage())
790                     m_rootContentLayer->setMasksToBounds(false);
791             }
792
793             // This layer and all of its descendants have cached repaints rects that are relative to
794             // the repaint container, so change when compositing changes; we need to update them here.
795             if (layer.parent())
796                 layer.computeRepaintRectsIncludingDescendants();
797
798             layerChanged = true;
799         }
800     } else {
801         if (layer.backing()) {
802             // If we're removing backing on a reflection, clear the source GraphicsLayer's pointer to
803             // its replica GraphicsLayer. In practice this should never happen because reflectee and reflection 
804             // are both either composited, or not composited.
805             if (layer.isReflection()) {
806                 RenderLayer* sourceLayer = toRenderLayerModelObject(layer.renderer().parent())->layer();
807                 if (RenderLayerBacking* backing = sourceLayer->backing()) {
808                     ASSERT(backing->graphicsLayer()->replicaLayer() == layer.backing()->graphicsLayer());
809                     backing->graphicsLayer()->setReplicatedByLayer(0);
810                 }
811             }
812
813             removeFromScrollCoordinatedLayers(layer);
814
815             layer.clearBacking();
816             layerChanged = true;
817
818             // This layer and all of its descendants have cached repaints rects that are relative to
819             // the repaint container, so change when compositing changes; we need to update them here.
820             layer.computeRepaintRectsIncludingDescendants();
821
822             // If we need to repaint, do so now that we've removed the backing
823             if (shouldRepaint == CompositingChangeRepaintNow)
824                 repaintOnCompositingChange(layer);
825         }
826     }
827     
828 #if ENABLE(VIDEO)
829     if (layerChanged && layer.renderer().isVideo()) {
830         // If it's a video, give the media player a chance to hook up to the layer.
831         toRenderVideo(layer.renderer()).acceleratedRenderingStateChanged();
832     }
833 #endif
834
835     if (layerChanged && layer.renderer().isWidget()) {
836         RenderLayerCompositor* innerCompositor = frameContentsCompositor(toRenderWidget(&layer.renderer()));
837         if (innerCompositor && innerCompositor->inCompositingMode())
838             innerCompositor->updateRootLayerAttachment();
839     }
840     
841     if (layerChanged)
842         layer.clearClipRectsIncludingDescendants(PaintingClipRects);
843
844     // If a fixed position layer gained/lost a backing or the reason not compositing it changed,
845     // the scrolling coordinator needs to recalculate whether it can do fast scrolling.
846     if (layer.renderer().style().position() == FixedPosition) {
847         if (layer.viewportConstrainedNotCompositedReason() != viewportConstrainedNotCompositedReason) {
848             layer.setViewportConstrainedNotCompositedReason(viewportConstrainedNotCompositedReason);
849             layerChanged = true;
850         }
851         if (layerChanged) {
852             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
853                 scrollingCoordinator->frameViewFixedObjectsDidChange(&m_renderView.frameView());
854         }
855     } else
856         layer.setViewportConstrainedNotCompositedReason(RenderLayer::NoNotCompositedReason);
857     
858     if (layer.backing())
859         layer.backing()->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
860
861     return layerChanged;
862 }
863
864 bool RenderLayerCompositor::updateLayerCompositingState(RenderLayer& layer, CompositingChangeRepaint shouldRepaint)
865 {
866     bool layerChanged = updateBacking(layer, shouldRepaint);
867
868     // See if we need content or clipping layers. Methods called here should assume
869     // that the compositing state of descendant layers has not been updated yet.
870     if (layer.backing() && layer.backing()->updateGraphicsLayerConfiguration())
871         layerChanged = true;
872
873     return layerChanged;
874 }
875
876 void RenderLayerCompositor::repaintOnCompositingChange(RenderLayer& layer)
877 {
878     // If the renderer is not attached yet, no need to repaint.
879     if (&layer.renderer() != &m_renderView && !layer.renderer().parent())
880         return;
881
882     RenderLayerModelObject* repaintContainer = layer.renderer().containerForRepaint();
883     if (!repaintContainer)
884         repaintContainer = &m_renderView;
885
886     layer.repaintIncludingNonCompositingDescendants(repaintContainer);
887     if (repaintContainer == &m_renderView) {
888         // The contents of this layer may be moving between the window
889         // and a GraphicsLayer, so we need to make sure the window system
890         // synchronizes those changes on the screen.
891         m_renderView.frameView().setNeedsOneShotDrawingSynchronization();
892     }
893 }
894
895 // This method assumes that layout is up-to-date, unlike repaintOnCompositingChange().
896 void RenderLayerCompositor::repaintInCompositedAncestor(RenderLayer& layer, const LayoutRect& rect)
897 {
898     RenderLayer* compositedAncestor = layer.enclosingCompositingLayerForRepaint(ExcludeSelf);
899     if (compositedAncestor) {
900         ASSERT(compositedAncestor->backing());
901
902         LayoutPoint offset;
903         layer.convertToLayerCoords(compositedAncestor, offset);
904
905         LayoutRect repaintRect = rect;
906         repaintRect.moveBy(offset);
907
908         compositedAncestor->setBackingNeedsRepaintInRect(repaintRect);
909     }
910
911     // The contents of this layer may be moving from a GraphicsLayer to the window,
912     // so we need to make sure the window system synchronizes those changes on the screen.
913     if (compositedAncestor == m_renderView.layer())
914         m_renderView.frameView().setNeedsOneShotDrawingSynchronization();
915 }
916
917 // The bounds of the GraphicsLayer created for a compositing layer is the union of the bounds of all the descendant
918 // RenderLayers that are rendered by the composited RenderLayer.
919 LayoutRect RenderLayerCompositor::calculateCompositedBounds(const RenderLayer& layer, const RenderLayer& ancestorLayer) const
920 {
921     if (!canBeComposited(layer))
922         return LayoutRect();
923     return layer.calculateLayerBounds(&ancestorLayer, nullptr, RenderLayer::DefaultCalculateLayerBoundsFlags | RenderLayer::ExcludeHiddenDescendants | RenderLayer::DontConstrainForMask);
924 }
925
926 void RenderLayerCompositor::layerWasAdded(RenderLayer&, RenderLayer&)
927 {
928     setCompositingLayersNeedRebuild();
929 }
930
931 void RenderLayerCompositor::layerWillBeRemoved(RenderLayer& parent, RenderLayer& child)
932 {
933     if (!child.isComposited() || parent.renderer().documentBeingDestroyed())
934         return;
935
936     removeFromScrollCoordinatedLayers(child);
937     repaintInCompositedAncestor(child, child.backing()->compositedBounds());
938
939     setCompositingParent(child, nullptr);
940     setCompositingLayersNeedRebuild();
941 }
942
943 RenderLayer* RenderLayerCompositor::enclosingNonStackingClippingLayer(const RenderLayer& layer) const
944 {
945     for (RenderLayer* parent = layer.parent(); parent; parent = parent->parent()) {
946         if (parent->isStackingContainer())
947             return nullptr;
948         if (parent->renderer().hasClipOrOverflowClip())
949             return parent;
950     }
951     return nullptr;
952 }
953
954 void RenderLayerCompositor::addToOverlapMap(OverlapMap& overlapMap, RenderLayer& layer, IntRect& layerBounds, bool& boundsComputed)
955 {
956     if (layer.isRootLayer())
957         return;
958
959     if (!boundsComputed) {
960         // FIXME: If this layer's overlap bounds include its children, we don't need to add its
961         // children's bounds to the overlap map.
962         layerBounds = enclosingIntRect(overlapMap.geometryMap().absoluteRect(layer.overlapBounds()));
963         // Empty rects never intersect, but we need them to for the purposes of overlap testing.
964         if (layerBounds.isEmpty())
965             layerBounds.setSize(IntSize(1, 1));
966         boundsComputed = true;
967     }
968
969     IntRect clipRect = pixelSnappedIntRect(layer.backgroundClipRect(RenderLayer::ClipRectsContext(&rootRenderLayer(), 0, AbsoluteClipRects)).rect()); // FIXME: Incorrect for CSS regions.
970
971     // On iOS, pageScaleFactor() is not applied by RenderView, so we should not scale here.
972     // FIXME: Set Settings::delegatesPageScaling to true for iOS.
973 #if !PLATFORM(IOS)
974     const Settings& settings = m_renderView.frameView().frame().settings();
975     if (!settings.delegatesPageScaling())
976         clipRect.scale(pageScaleFactor());
977 #endif
978     clipRect.intersect(layerBounds);
979     overlapMap.add(&layer, clipRect);
980 }
981
982 void RenderLayerCompositor::addToOverlapMapRecursive(OverlapMap& overlapMap, RenderLayer& layer, RenderLayer* ancestorLayer)
983 {
984     if (!canBeComposited(layer) || overlapMap.contains(&layer))
985         return;
986
987     // A null ancestorLayer is an indication that 'layer' has already been pushed.
988     if (ancestorLayer)
989         overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer);
990     
991     IntRect bounds;
992     bool haveComputedBounds = false;
993     addToOverlapMap(overlapMap, layer, bounds, haveComputedBounds);
994
995 #if !ASSERT_DISABLED
996     LayerListMutationDetector mutationChecker(&layer);
997 #endif
998
999     if (layer.isStackingContainer()) {
1000         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1001             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i)
1002                 addToOverlapMapRecursive(overlapMap, *negZOrderList->at(i), &layer);
1003         }
1004     }
1005
1006     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1007         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i)
1008             addToOverlapMapRecursive(overlapMap, *normalFlowList->at(i), &layer);
1009     }
1010
1011     if (layer.isStackingContainer()) {
1012         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1013             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i)
1014                 addToOverlapMapRecursive(overlapMap, *posZOrderList->at(i), &layer);
1015         }
1016     }
1017     
1018     if (ancestorLayer)
1019         overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
1020 }
1021
1022 void RenderLayerCompositor::computeCompositingRequirementsForNamedFlowFixed(RenderLayer& layer, OverlapMap* overlapMap, CompositingState& childState, bool& layersChanged, bool& anyDescendantHas3DTransform)
1023 {
1024     if (!layer.isRootLayer())
1025         return;
1026
1027     if (!layer.renderer().view().hasRenderNamedFlowThreads())
1028         return;
1029
1030     Vector<RenderLayer*> fixedLayers;
1031     layer.renderer().view().flowThreadController().collectFixedPositionedLayers(fixedLayers);
1032
1033     for (size_t i = 0; i < fixedLayers.size(); ++i) {
1034         RenderLayer* fixedLayer = fixedLayers.at(i);
1035         computeCompositingRequirements(&layer, *fixedLayer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1036     }
1037 }
1038
1039 //  Recurse through the layers in z-index and overflow order (which is equivalent to painting order)
1040 //  For the z-order children of a compositing layer:
1041 //      If a child layers has a compositing layer, then all subsequent layers must
1042 //      be compositing in order to render above that layer.
1043 //
1044 //      If a child in the negative z-order list is compositing, then the layer itself
1045 //      must be compositing so that its contents render over that child.
1046 //      This implies that its positive z-index children must also be compositing.
1047 //
1048 void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer& layer, OverlapMap* overlapMap, CompositingState& compositingState, bool& layersChanged, bool& descendantHas3DTransform)
1049 {
1050     layer.updateDescendantDependentFlags();
1051     layer.updateLayerListsIfNeeded();
1052
1053     if (layer.isFlowThreadCollectingGraphicsLayersUnderRegions()) {
1054         RenderFlowThread& flowThread = toRenderFlowThread(layer.renderer());
1055         layer.setHasCompositingDescendant(flowThread.hasCompositingRegionDescendant());
1056
1057         // Before returning, we need to update the lists of all child layers. This is required because,
1058         // if this flow thread will not be painted (for instance because of having no regions, or only invalid regions),
1059         // the child layers will never have their lists updated (which would normally happen during painting).
1060         layer.updateDescendantsLayerListsIfNeeded(true);
1061
1062         return;
1063     }
1064
1065     if (overlapMap)
1066         overlapMap->geometryMap().pushMappingsToAncestor(&layer, ancestorLayer);
1067     
1068     // Clear the flag
1069     layer.setHasCompositingDescendant(false);
1070
1071     RenderLayer::IndirectCompositingReason compositingReason = compositingState.m_subtreeIsCompositing ? RenderLayer::IndirectCompositingForStacking : RenderLayer::NoIndirectCompositingReason;
1072
1073     bool haveComputedBounds = false;
1074     IntRect absBounds;
1075     if (overlapMap && !overlapMap->isEmpty() && compositingState.m_testingOverlap) {
1076         // If we're testing for overlap, we only need to composite if we overlap something that is already composited.
1077         absBounds = enclosingIntRect(overlapMap->geometryMap().absoluteRect(layer.overlapBounds()));
1078
1079         // Empty rects never intersect, but we need them to for the purposes of overlap testing.
1080         if (absBounds.isEmpty())
1081             absBounds.setSize(IntSize(1, 1));
1082         haveComputedBounds = true;
1083         compositingReason = overlapMap->overlapsLayers(absBounds) ? RenderLayer::IndirectCompositingForOverlap : RenderLayer::NoIndirectCompositingReason;
1084     }
1085
1086 #if ENABLE(VIDEO)
1087     // Video is special. It's the only RenderLayer type that can both have
1088     // RenderLayer children and whose children can't use its backing to render
1089     // into. These children (the controls) always need to be promoted into their
1090     // own layers to draw on top of the accelerated video.
1091     if (compositingState.m_compositingAncestor && compositingState.m_compositingAncestor->renderer().isVideo())
1092         compositingReason = RenderLayer::IndirectCompositingForOverlap;
1093 #endif
1094
1095     layer.setIndirectCompositingReason(compositingReason);
1096
1097     // The children of this layer don't need to composite, unless there is
1098     // a compositing layer among them, so start by inheriting the compositing
1099     // ancestor with m_subtreeIsCompositing set to false.
1100     CompositingState childState(compositingState);
1101     childState.m_subtreeIsCompositing = false;
1102
1103     bool willBeComposited = needsToBeComposited(layer);
1104     if (willBeComposited) {
1105         // Tell the parent it has compositing descendants.
1106         compositingState.m_subtreeIsCompositing = true;
1107         // This layer now acts as the ancestor for kids.
1108         childState.m_compositingAncestor = &layer;
1109
1110         if (overlapMap)
1111             overlapMap->pushCompositingContainer();
1112         // This layer is going to be composited, so children can safely ignore the fact that there's an 
1113         // animation running behind this layer, meaning they can rely on the overlap map testing again.
1114         childState.m_testingOverlap = true;
1115     }
1116
1117 #if !ASSERT_DISABLED
1118     LayerListMutationDetector mutationChecker(&layer);
1119 #endif
1120
1121     bool anyDescendantHas3DTransform = false;
1122
1123     if (layer.isStackingContainer()) {
1124         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1125             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i) {
1126                 computeCompositingRequirements(&layer, *negZOrderList->at(i), overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1127
1128                 // If we have to make a layer for this child, make one now so we can have a contents layer
1129                 // (since we need to ensure that the -ve z-order child renders underneath our contents).
1130                 if (!willBeComposited && childState.m_subtreeIsCompositing) {
1131                     // make layer compositing
1132                     layer.setIndirectCompositingReason(RenderLayer::IndirectCompositingForBackgroundLayer);
1133                     childState.m_compositingAncestor = &layer;
1134                     if (overlapMap)
1135                         overlapMap->pushCompositingContainer();
1136                     // This layer is going to be composited, so children can safely ignore the fact that there's an 
1137                     // animation running behind this layer, meaning they can rely on the overlap map testing again
1138                     childState.m_testingOverlap = true;
1139                     willBeComposited = true;
1140                 }
1141             }
1142         }
1143     }
1144
1145     if (layer.renderer().isRenderNamedFlowFragmentContainer()) {
1146         // We are going to collect layers from the RenderFlowThread into the GraphicsLayer of the parent of the
1147         // anonymous RenderRegion, but first we need to make sure that the parent itself of the region is going to
1148         // have a composited layer. We only want to make regions composited when there's an actual layer that we
1149         // need to move to that region.
1150         computeRegionCompositingRequirements(toRenderBlockFlow(layer.renderer()).renderNamedFlowFragment(), overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1151     }
1152
1153     
1154     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1155         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i)
1156             computeCompositingRequirements(&layer, *normalFlowList->at(i), overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1157     }
1158
1159     if (layer.isStackingContainer()) {
1160         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1161             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i)
1162                 computeCompositingRequirements(&layer, *posZOrderList->at(i), overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1163         }
1164     }
1165
1166     if (layer.isRootLayer())
1167         computeCompositingRequirementsForNamedFlowFixed(layer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1168
1169     // If we just entered compositing mode, the root will have become composited (as long as accelerated compositing is enabled).
1170     if (layer.isRootLayer()) {
1171         if (inCompositingMode() && m_hasAcceleratedCompositing)
1172             willBeComposited = true;
1173     }
1174     
1175     // If the layer composited for other reasons than blending, it is no longer needed to keep track of whether a child was blended.
1176     if (compositingState.m_subtreeHasBlending && !layer.hasBlendMode())
1177         compositingState.m_subtreeHasBlending = false;
1178
1179     ASSERT(willBeComposited == needsToBeComposited(layer));
1180
1181     // All layers (even ones that aren't being composited) need to get added to
1182     // the overlap map. Layers that do not composite will draw into their
1183     // compositing ancestor's backing, and so are still considered for overlap.
1184     if (overlapMap && childState.m_compositingAncestor && !childState.m_compositingAncestor->isRootLayer())
1185         addToOverlapMap(*overlapMap, layer, absBounds, haveComputedBounds);
1186
1187     if (childState.m_subtreeHasBlending || layer.hasBlendMode())
1188         compositingState.m_subtreeHasBlending = true;
1189
1190     // Now check for reasons to become composited that depend on the state of descendant layers.
1191     RenderLayer::IndirectCompositingReason indirectCompositingReason;
1192     if (!willBeComposited && canBeComposited(layer)
1193         && requiresCompositingForIndirectReason(layer.renderer(), childState.m_subtreeIsCompositing, compositingState.m_subtreeHasBlending, anyDescendantHas3DTransform, indirectCompositingReason)) {
1194         layer.setIndirectCompositingReason(indirectCompositingReason);
1195         childState.m_compositingAncestor = &layer;
1196         if (overlapMap) {
1197             overlapMap->pushCompositingContainer();
1198             addToOverlapMapRecursive(*overlapMap, layer);
1199         }
1200         willBeComposited = true;
1201     }
1202     
1203     ASSERT(willBeComposited == needsToBeComposited(layer));
1204     if (layer.reflectionLayer()) {
1205         // FIXME: Shouldn't we call computeCompositingRequirements to handle a reflection overlapping with another renderer?
1206         layer.reflectionLayer()->setIndirectCompositingReason(willBeComposited ? RenderLayer::IndirectCompositingForStacking : RenderLayer::NoIndirectCompositingReason);
1207     }
1208
1209     // Subsequent layers in the parent stacking context also need to composite.
1210     if (childState.m_subtreeIsCompositing)
1211         compositingState.m_subtreeIsCompositing = true;
1212
1213     // Set the flag to say that this SC has compositing children.
1214     layer.setHasCompositingDescendant(childState.m_subtreeIsCompositing);
1215
1216     // setHasCompositingDescendant() may have changed the answer to needsToBeComposited() when clipping,
1217     // so test that again.
1218     bool isCompositedClippingLayer = canBeComposited(layer) && clipsCompositingDescendants(layer);
1219
1220     // Turn overlap testing off for later layers if it's already off, or if we have an animating transform.
1221     // Note that if the layer clips its descendants, there's no reason to propagate the child animation to the parent layers. That's because
1222     // we know for sure the animation is contained inside the clipping rectangle, which is already added to the overlap map.
1223     if ((!childState.m_testingOverlap && !isCompositedClippingLayer) || isRunningAcceleratedTransformAnimation(layer.renderer()))
1224         compositingState.m_testingOverlap = false;
1225     
1226     if (isCompositedClippingLayer) {
1227         if (!willBeComposited) {
1228             childState.m_compositingAncestor = &layer;
1229             if (overlapMap) {
1230                 overlapMap->pushCompositingContainer();
1231                 addToOverlapMapRecursive(*overlapMap, layer);
1232             }
1233             willBeComposited = true;
1234          }
1235     }
1236
1237     if (overlapMap && childState.m_compositingAncestor == &layer && !layer.isRootLayer())
1238         overlapMap->popCompositingContainer();
1239
1240     // If we're back at the root, and no other layers need to be composited, and the root layer itself doesn't need
1241     // to be composited, then we can drop out of compositing mode altogether. However, don't drop out of compositing mode
1242     // if there are composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
1243     if (layer.isRootLayer() && !childState.m_subtreeIsCompositing && !requiresCompositingLayer(layer) && !m_forceCompositingMode && !hasAnyAdditionalCompositedLayers(layer)) {
1244         // Don't drop out of compositing on iOS, because we may flash. See <rdar://problem/8348337>.
1245 #if !PLATFORM(IOS)
1246         enableCompositingMode(false);
1247         willBeComposited = false;
1248 #endif
1249     }
1250     
1251     // If the layer is going into compositing mode, repaint its old location.
1252     ASSERT(willBeComposited == needsToBeComposited(layer));
1253     if (!layer.isComposited() && willBeComposited)
1254         repaintOnCompositingChange(layer);
1255
1256     // Update backing now, so that we can use isComposited() reliably during tree traversal in rebuildCompositingLayerTree().
1257     if (updateBacking(layer, CompositingChangeRepaintNow))
1258         layersChanged = true;
1259
1260     if (layer.reflectionLayer() && updateLayerCompositingState(*layer.reflectionLayer(), CompositingChangeRepaintNow))
1261         layersChanged = true;
1262
1263     descendantHas3DTransform |= anyDescendantHas3DTransform || layer.has3DTransform();
1264
1265     if (overlapMap)
1266         overlapMap->geometryMap().popMappingsToAncestor(ancestorLayer);
1267 }
1268
1269 void RenderLayerCompositor::computeRegionCompositingRequirements(RenderNamedFlowFragment* region, OverlapMap* overlapMap, CompositingState& childState, bool& layersChanged, bool& anyDescendantHas3DTransform)
1270 {
1271     if (!region->isValid())
1272         return;
1273
1274     RenderFlowThread* flowThread = region->flowThread();
1275     
1276     if (overlapMap)
1277         overlapMap->geometryMap().pushRenderFlowThread(flowThread);
1278
1279     if (const RenderLayerList* layerList = flowThread->getLayerListForRegion(region)) {
1280         for (size_t i = 0, listSize = layerList->size(); i < listSize; ++i) {
1281             RenderLayer& curLayer = *layerList->at(i);
1282             ASSERT(flowThread->regionForCompositedLayer(curLayer) == region);
1283             computeCompositingRequirements(flowThread->layer(), curLayer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1284         }
1285     }
1286
1287     if (overlapMap)
1288         overlapMap->geometryMap().popMappingsToAncestor(&region->layerOwner());
1289 }
1290
1291 void RenderLayerCompositor::setCompositingParent(RenderLayer& childLayer, RenderLayer* parentLayer)
1292 {
1293     ASSERT(!parentLayer || childLayer.ancestorCompositingLayer() == parentLayer);
1294     ASSERT(childLayer.isComposited());
1295
1296     // It's possible to be called with a parent that isn't yet composited when we're doing
1297     // partial updates as required by painting or hit testing. Just bail in that case;
1298     // we'll do a full layer update soon.
1299     if (!parentLayer || !parentLayer->isComposited())
1300         return;
1301
1302     if (parentLayer) {
1303         GraphicsLayer* hostingLayer = parentLayer->backing()->parentForSublayers();
1304         GraphicsLayer* hostedLayer = childLayer.backing()->childForSuperlayers();
1305         
1306         hostingLayer->addChild(hostedLayer);
1307     } else
1308         childLayer.backing()->childForSuperlayers()->removeFromParent();
1309 }
1310
1311 void RenderLayerCompositor::removeCompositedChildren(RenderLayer& layer)
1312 {
1313     ASSERT(layer.isComposited());
1314
1315     layer.backing()->parentForSublayers()->removeAllChildren();
1316 }
1317
1318 #if ENABLE(VIDEO)
1319 bool RenderLayerCompositor::canAccelerateVideoRendering(RenderVideo& video) const
1320 {
1321     if (!m_hasAcceleratedCompositing)
1322         return false;
1323
1324     return video.supportsAcceleratedRendering();
1325 }
1326 #endif
1327
1328 void RenderLayerCompositor::rebuildCompositingLayerTreeForNamedFlowFixed(RenderLayer& layer, Vector<GraphicsLayer*>& childGraphicsLayersOfEnclosingLayer, int depth)
1329 {
1330     if (!layer.isRootLayer())
1331         return;
1332
1333     if (!layer.renderer().view().hasRenderNamedFlowThreads())
1334         return;
1335
1336     Vector<RenderLayer*> fixedLayers;
1337     layer.renderer().view().flowThreadController().collectFixedPositionedLayers(fixedLayers);
1338
1339     for (size_t i = 0; i < fixedLayers.size(); ++i) {
1340         RenderLayer* fixedLayer = fixedLayers.at(i);
1341         rebuildCompositingLayerTree(*fixedLayer, childGraphicsLayersOfEnclosingLayer, depth);
1342     }
1343 }
1344
1345 void RenderLayerCompositor::rebuildCompositingLayerTree(RenderLayer& layer, Vector<GraphicsLayer*>& childLayersOfEnclosingLayer, int depth)
1346 {
1347     // Make the layer compositing if necessary, and set up clipping and content layers.
1348     // Note that we can only do work here that is independent of whether the descendant layers
1349     // have been processed. computeCompositingRequirements() will already have done the repaint if necessary.
1350
1351     // Do not iterate the RenderFlowThread directly. We are going to collect composited layers as part of regions.
1352     if (layer.isFlowThreadCollectingGraphicsLayersUnderRegions())
1353         return;
1354
1355     RenderLayerBacking* layerBacking = layer.backing();
1356     if (layerBacking) {
1357         // The compositing state of all our children has been updated already, so now
1358         // we can compute and cache the composited bounds for this layer.
1359         layerBacking->updateCompositedBounds();
1360
1361         if (RenderLayer* reflection = layer.reflectionLayer()) {
1362             if (reflection->backing())
1363                 reflection->backing()->updateCompositedBounds();
1364         }
1365
1366         if (layerBacking->updateGraphicsLayerConfiguration())
1367             layerBacking->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
1368         
1369         layerBacking->updateGraphicsLayerGeometry();
1370
1371         if (!layer.parent())
1372             updateRootLayerPosition();
1373
1374 #if !LOG_DISABLED
1375         logLayerInfo(layer, depth);
1376 #else
1377         UNUSED_PARAM(depth);
1378 #endif
1379         if (layerBacking->hasUnpositionedOverflowControlsLayers())
1380             layer.positionNewlyCreatedOverflowControls();
1381     }
1382
1383     // If this layer has backing, then we are collecting its children, otherwise appending
1384     // to the compositing child list of an enclosing layer.
1385     Vector<GraphicsLayer*> layerChildren;
1386     Vector<GraphicsLayer*>& childList = layerBacking ? layerChildren : childLayersOfEnclosingLayer;
1387
1388 #if !ASSERT_DISABLED
1389     LayerListMutationDetector mutationChecker(&layer);
1390 #endif
1391
1392     if (layer.isStackingContainer()) {
1393         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1394             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i)
1395                 rebuildCompositingLayerTree(*negZOrderList->at(i), childList, depth + 1);
1396         }
1397
1398         // If a negative z-order child is compositing, we get a foreground layer which needs to get parented.
1399         if (layerBacking && layerBacking->foregroundLayer())
1400             childList.append(layerBacking->foregroundLayer());
1401     }
1402
1403     if (layer.renderer().isRenderNamedFlowFragmentContainer())
1404         rebuildRegionCompositingLayerTree(toRenderBlockFlow(layer.renderer()).renderNamedFlowFragment(), layerChildren, depth + 1);
1405
1406     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1407         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i)
1408             rebuildCompositingLayerTree(*normalFlowList->at(i), childList, depth + 1);
1409     }
1410     
1411     if (layer.isStackingContainer()) {
1412         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1413             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i)
1414                 rebuildCompositingLayerTree(*posZOrderList->at(i), childList, depth + 1);
1415         }
1416     }
1417
1418     if (layer.isRootLayer())
1419         rebuildCompositingLayerTreeForNamedFlowFixed(layer, childList, depth + 1);
1420
1421     if (layerBacking) {
1422         bool parented = false;
1423         if (layer.renderer().isWidget())
1424             parented = parentFrameContentLayers(toRenderWidget(&layer.renderer()));
1425
1426         if (!parented)
1427             layerBacking->parentForSublayers()->setChildren(layerChildren);
1428
1429         // If the layer has a clipping layer the overflow controls layers will be siblings of the clipping layer.
1430         // Otherwise, the overflow control layers are normal children.
1431         if (!layerBacking->hasClippingLayer() && !layerBacking->hasScrollingLayer()) {
1432             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForHorizontalScrollbar()) {
1433                 overflowControlLayer->removeFromParent();
1434                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
1435             }
1436
1437             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForVerticalScrollbar()) {
1438                 overflowControlLayer->removeFromParent();
1439                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
1440             }
1441
1442             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForScrollCorner()) {
1443                 overflowControlLayer->removeFromParent();
1444                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
1445             }
1446         }
1447
1448         childLayersOfEnclosingLayer.append(layerBacking->childForSuperlayers());
1449     }
1450 }
1451
1452 void RenderLayerCompositor::rebuildRegionCompositingLayerTree(RenderNamedFlowFragment* region, Vector<GraphicsLayer*>& childList, int depth)
1453 {
1454     if (!region->isValid())
1455         return;
1456
1457     RenderFlowThread* flowThread = region->flowThread();
1458     ASSERT(flowThread->collectsGraphicsLayersUnderRegions());
1459     if (const RenderLayerList* layerList = flowThread->getLayerListForRegion(region)) {
1460         for (size_t i = 0, listSize = layerList->size(); i < listSize; ++i) {
1461             RenderLayer& curLayer = *layerList->at(i);
1462             ASSERT(flowThread->regionForCompositedLayer(curLayer) == region);
1463             rebuildCompositingLayerTree(curLayer, childList, depth + 1);
1464         }
1465     }
1466 }
1467
1468 void RenderLayerCompositor::frameViewDidChangeLocation(const IntPoint& contentsOffset)
1469 {
1470     if (m_overflowControlsHostLayer)
1471         m_overflowControlsHostLayer->setPosition(contentsOffset);
1472 }
1473
1474 void RenderLayerCompositor::frameViewDidChangeSize()
1475 {
1476     if (m_clipLayer) {
1477         const FrameView& frameView = m_renderView.frameView();
1478         m_clipLayer->setSize(frameView.unscaledTotalVisibleContentSize());
1479
1480         frameViewDidScroll();
1481         updateOverflowControlsLayers();
1482
1483 #if ENABLE(RUBBER_BANDING)
1484         if (m_layerForOverhangAreas)
1485             m_layerForOverhangAreas->setSize(frameView.frameRect().size());
1486 #endif
1487     }
1488 }
1489
1490 bool RenderLayerCompositor::hasCoordinatedScrolling() const
1491 {
1492     ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator();
1493     return scrollingCoordinator && scrollingCoordinator->coordinatesScrollingForFrameView(&m_renderView.frameView());
1494 }
1495
1496 void RenderLayerCompositor::updateScrollLayerPosition()
1497 {
1498     ASSERT(m_scrollLayer);
1499
1500     FrameView& frameView = m_renderView.frameView();
1501     IntPoint scrollPosition = frameView.scrollPosition();
1502
1503     const Settings& settings = m_renderView.frameView().frame().settings();
1504     if (settings.compositedScrollingForFramesEnabled()) {
1505         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
1506             scrollingCoordinator->scrollableAreaScrollLayerDidChange(&frameView);
1507     }
1508
1509     m_scrollLayer->setPosition(FloatPoint(-scrollPosition.x(), -scrollPosition.y()));
1510
1511     if (GraphicsLayer* fixedBackgroundLayer = fixedRootBackgroundLayer())
1512         fixedBackgroundLayer->setPosition(toLayoutPoint(frameView.scrollOffsetForFixedPosition()));
1513 }
1514
1515 void RenderLayerCompositor::frameViewDidScroll()
1516 {
1517     if (!m_scrollLayer)
1518         return;
1519
1520     // If there's a scrolling coordinator that manages scrolling for this frame view,
1521     // it will also manage updating the scroll layer position.
1522     if (hasCoordinatedScrolling()) {
1523         // We have to schedule a flush in order for the main TiledBacking to update its tile coverage.
1524         scheduleLayerFlushNow();
1525         return;
1526     }
1527
1528     updateScrollLayerPosition();
1529 }
1530
1531 void RenderLayerCompositor::frameViewDidAddOrRemoveScrollbars()
1532 {
1533     updateOverflowControlsLayers();
1534 }
1535
1536 void RenderLayerCompositor::frameViewDidLayout()
1537 {
1538     RenderLayerBacking* renderViewBacking = m_renderView.layer()->backing();
1539     if (renderViewBacking)
1540         renderViewBacking->adjustTiledBackingCoverage();
1541 }
1542
1543 void RenderLayerCompositor::rootFixedBackgroundsChanged()
1544 {
1545     RenderLayerBacking* renderViewBacking = m_renderView.layer()->backing();
1546     if (renderViewBacking && renderViewBacking->usingTiledBacking())
1547         setCompositingLayersNeedRebuild();
1548 }
1549
1550 void RenderLayerCompositor::scrollingLayerDidChange(RenderLayer& layer)
1551 {
1552     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
1553         scrollingCoordinator->scrollableAreaScrollLayerDidChange(&layer);
1554 }
1555
1556 void RenderLayerCompositor::fixedRootBackgroundLayerChanged()
1557 {
1558     if (m_renderView.documentBeingDestroyed())
1559         return;
1560
1561     if (m_renderView.layer()->isComposited())
1562         updateScrollCoordinatedStatus(*m_renderView.layer());
1563 }
1564
1565 String RenderLayerCompositor::layerTreeAsText(LayerTreeFlags flags)
1566 {
1567     updateCompositingLayers(CompositingUpdateAfterLayout);
1568
1569     if (!m_rootContentLayer)
1570         return String();
1571
1572     flushPendingLayerChanges(true);
1573
1574     LayerTreeAsTextBehavior layerTreeBehavior = LayerTreeAsTextBehaviorNormal;
1575     if (flags & LayerTreeFlagsIncludeDebugInfo)
1576         layerTreeBehavior |= LayerTreeAsTextDebug;
1577     if (flags & LayerTreeFlagsIncludeVisibleRects)
1578         layerTreeBehavior |= LayerTreeAsTextIncludeVisibleRects;
1579     if (flags & LayerTreeFlagsIncludeTileCaches)
1580         layerTreeBehavior |= LayerTreeAsTextIncludeTileCaches;
1581     if (flags & LayerTreeFlagsIncludeRepaintRects)
1582         layerTreeBehavior |= LayerTreeAsTextIncludeRepaintRects;
1583     if (flags & LayerTreeFlagsIncludePaintingPhases)
1584         layerTreeBehavior |= LayerTreeAsTextIncludePaintingPhases;
1585     if (flags & LayerTreeFlagsIncludeContentLayers)
1586         layerTreeBehavior |= LayerTreeAsTextIncludeContentLayers;
1587
1588     // We skip dumping the scroll and clip layers to keep layerTreeAsText output
1589     // similar between platforms.
1590     String layerTreeText = m_rootContentLayer->layerTreeAsText(layerTreeBehavior);
1591
1592     // Dump an empty layer tree only if the only composited layer is the main frame's tiled backing,
1593     // so that tests expecting us to drop out of accelerated compositing when there are no layers succeed.
1594     if (!hasAnyAdditionalCompositedLayers(rootRenderLayer()) && mainFrameBackingIsTiled() && !(layerTreeBehavior & LayerTreeAsTextIncludeTileCaches))
1595         layerTreeText = "";
1596
1597     // The true root layer is not included in the dump, so if we want to report
1598     // its repaint rects, they must be included here.
1599     if (flags & LayerTreeFlagsIncludeRepaintRects)
1600         return m_renderView.frameView().trackedRepaintRectsAsText() + layerTreeText;
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     LegacyTileCache* tileCache = nullptr;
2686     if (Page* page = this->page()) {
2687         if (FrameView* frameView = page->mainFrame().view())
2688             tileCache = frameView->legacyTileCache();
2689     }
2690
2691     if (!tileCache)
2692         return 1;
2693
2694     return tileCache->tilingMode() == LegacyTileCache::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) || PLATFORM(EFL)
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()) {