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