12edc86082e0d640c0f6a73d8b5392427db9e030
[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         double horizontalMargin = defaultTileWidth / pageScaleFactor();
424         double verticalMargin = defaultTileHeight / pageScaleFactor();
425         rootLayer->flushCompositingState(frameView.computeCoverageRect(horizontalMargin, verticalMargin));
426 #else
427         // Having a m_clipLayer indicates that we're doing scrolling via GraphicsLayers.
428         IntRect visibleRect = m_clipLayer ? IntRect(IntPoint(), frameView.contentsSize()) : frameView.visibleContentRect();
429         rootLayer->flushCompositingState(visibleRect);
430 #endif
431     }
432     
433     ASSERT(m_flushingLayers);
434     m_flushingLayers = false;
435
436 #if PLATFORM(IOS)
437     updateCustomLayersAfterFlush();
438
439     ChromeClient* client = this->chromeClient();
440     if (client && isFlushRoot)
441         client->didFlushCompositingLayers();
442 #endif
443
444     for (auto it = m_scrollCoordinatedLayersNeedingUpdate.begin(), end = m_scrollCoordinatedLayersNeedingUpdate.end(); it != end; ++it)
445         updateScrollCoordinatedStatus(**it);
446
447     m_scrollCoordinatedLayersNeedingUpdate.clear();
448     startLayerFlushTimerIfNeeded();
449 }
450
451 #if PLATFORM(IOS)
452 static bool scrollbarHasDisplayNone(Scrollbar* scrollbar)
453 {
454     if (!scrollbar || !scrollbar->isCustomScrollbar())
455         return false;
456
457     RefPtr<RenderStyle> scrollbarStyle = static_cast<RenderScrollbar*>(scrollbar)->getScrollbarPseudoStyle(ScrollbarBGPart, SCROLLBAR);
458     return scrollbarStyle && scrollbarStyle->display() == NONE;
459 }
460
461 // FIXME: Can we make |layer| const RenderLayer&?
462 static void updateScrollingLayerWithClient(RenderLayer& layer, ChromeClient* client)
463 {
464     if (!client)
465         return;
466
467     RenderLayerBacking* backing = layer.backing();
468     ASSERT(backing);
469
470     bool allowHorizontalScrollbar = !scrollbarHasDisplayNone(layer.horizontalScrollbar());
471     bool allowVerticalScrollbar = !scrollbarHasDisplayNone(layer.verticalScrollbar());
472     client->addOrUpdateScrollingLayer(layer.renderer().element(), backing->scrollingLayer()->platformLayer(), backing->scrollingContentsLayer()->platformLayer(),
473         IntSize(layer.scrollWidth(), layer.scrollHeight()), allowHorizontalScrollbar, allowVerticalScrollbar);
474 }
475
476 void RenderLayerCompositor::updateCustomLayersAfterFlush()
477 {
478     registerAllViewportConstrainedLayers();
479
480     if (!m_scrollingLayersNeedingUpdate.isEmpty()) {
481         ChromeClient* chromeClient = this->chromeClient();
482
483         for (auto it = m_scrollingLayersNeedingUpdate.begin(), end = m_scrollingLayersNeedingUpdate.end(); it != end; ++it)
484             updateScrollingLayerWithClient(**it, chromeClient);
485         m_scrollingLayersNeedingUpdate.clear();
486     }
487     m_scrollingLayersNeedingUpdate.clear();
488 }
489 #endif
490
491 void RenderLayerCompositor::didFlushChangesForLayer(RenderLayer& layer, const GraphicsLayer* graphicsLayer)
492 {
493     if (m_scrollCoordinatedLayers.contains(&layer))
494         m_scrollCoordinatedLayersNeedingUpdate.add(&layer);
495
496 #if PLATFORM(IOS)
497     if (m_scrollingLayers.contains(&layer))
498         m_scrollingLayersNeedingUpdate.add(&layer);
499 #endif
500
501     RenderLayerBacking* backing = layer.backing();
502     if (backing->backgroundLayerPaintsFixedRootBackground() && graphicsLayer == backing->backgroundLayer())
503         fixedRootBackgroundLayerChanged();
504 }
505
506 void RenderLayerCompositor::didPaintBacking(RenderLayerBacking*)
507 {
508     FrameView& frameView = m_renderView.frameView();
509     frameView.setLastPaintTime(monotonicallyIncreasingTime());
510     if (frameView.milestonesPendingPaint() && !m_paintRelatedMilestonesTimer.isActive())
511         m_paintRelatedMilestonesTimer.startOneShot(0);
512 }
513
514 void RenderLayerCompositor::didChangeVisibleRect()
515 {
516     GraphicsLayer* rootLayer = rootGraphicsLayer();
517     if (!rootLayer)
518         return;
519
520     const FrameView& frameView = m_renderView.frameView();
521
522 #if PLATFORM(IOS)
523     IntRect visibleRect = frameView.exposedContentRect();
524 #else
525     IntRect visibleRect = m_clipLayer ? IntRect(IntPoint(), frameView.contentsSize()) : frameView.visibleContentRect();
526 #endif
527     if (!rootLayer->visibleRectChangeRequiresFlush(visibleRect))
528         return;
529     scheduleLayerFlushNow();
530 }
531
532 void RenderLayerCompositor::notifyFlushBeforeDisplayRefresh(const GraphicsLayer*)
533 {
534     if (!m_layerUpdater) {
535         PlatformDisplayID displayID = 0;
536         if (Page* page = this->page())
537             displayID = page->chrome().displayID();
538
539         m_layerUpdater = adoptPtr(new GraphicsLayerUpdater(this, displayID));
540     }
541     
542     m_layerUpdater->scheduleUpdate();
543 }
544
545 void RenderLayerCompositor::flushLayers(GraphicsLayerUpdater*)
546 {
547     flushPendingLayerChanges(true); // FIXME: deal with iframes
548 }
549
550 void RenderLayerCompositor::layerTiledBackingUsageChanged(const GraphicsLayer*, bool usingTiledBacking)
551 {
552     if (usingTiledBacking)
553         ++m_layersWithTiledBackingCount;
554     else {
555         ASSERT(m_layersWithTiledBackingCount > 0);
556         --m_layersWithTiledBackingCount;
557     }
558 }
559
560 RenderLayerCompositor* RenderLayerCompositor::enclosingCompositorFlushingLayers() const
561 {
562     for (Frame* frame = &m_renderView.frameView().frame(); frame; frame = frame->tree().parent()) {
563         RenderLayerCompositor* compositor = frame->contentRenderer() ? &frame->contentRenderer()->compositor() : 0;
564         if (compositor->isFlushingLayers())
565             return compositor;
566     }
567     
568     return 0;
569 }
570
571 void RenderLayerCompositor::scheduleCompositingLayerUpdate()
572 {
573     if (!m_updateCompositingLayersTimer.isActive())
574         m_updateCompositingLayersTimer.startOneShot(0);
575 }
576
577 void RenderLayerCompositor::updateCompositingLayersTimerFired(Timer<RenderLayerCompositor>&)
578 {
579     updateCompositingLayers(CompositingUpdateAfterLayout);
580 }
581
582 bool RenderLayerCompositor::hasAnyAdditionalCompositedLayers(const RenderLayer& rootLayer) const
583 {
584     return m_compositedLayerCount > (rootLayer.isComposited() ? 1 : 0);
585 }
586
587 void RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType updateType, RenderLayer* updateRoot)
588 {
589     m_updateCompositingLayersTimer.stop();
590     
591     // Compositing layers will be updated in Document::implicitClose() if suppressed here.
592     if (!m_renderView.document().visualUpdatesAllowed())
593         return;
594
595     // Avoid updating the layers with old values. Compositing layers will be updated after the layout is finished.
596     if (m_renderView.needsLayout())
597         return;
598
599     if (m_forceCompositingMode && !m_compositing)
600         enableCompositingMode(true);
601
602     if (!m_reevaluateCompositingAfterLayout && !m_compositing)
603         return;
604
605     AnimationUpdateBlock animationUpdateBlock(&m_renderView.frameView().frame().animation());
606
607     TemporaryChange<bool> postLayoutChange(m_inPostLayoutUpdate, true);
608     
609     bool checkForHierarchyUpdate = m_reevaluateCompositingAfterLayout;
610     bool needGeometryUpdate = false;
611
612     switch (updateType) {
613     case CompositingUpdateAfterStyleChange:
614     case CompositingUpdateAfterLayout:
615     case CompositingUpdateOnHitTest:
616         checkForHierarchyUpdate = true;
617         break;
618     case CompositingUpdateOnScroll:
619         checkForHierarchyUpdate = true; // Overlap can change with scrolling, so need to check for hierarchy updates.
620
621         needGeometryUpdate = true;
622         break;
623     case CompositingUpdateOnCompositedScroll:
624         needGeometryUpdate = true;
625         break;
626     }
627
628     if (!checkForHierarchyUpdate && !needGeometryUpdate)
629         return;
630
631     bool needHierarchyUpdate = m_compositingLayersNeedRebuild;
632     bool isFullUpdate = !updateRoot;
633
634     // Only clear the flag if we're updating the entire hierarchy.
635     m_compositingLayersNeedRebuild = false;
636     updateRoot = &rootRenderLayer();
637
638     if (isFullUpdate && updateType == CompositingUpdateAfterLayout)
639         m_reevaluateCompositingAfterLayout = false;
640
641 #if !LOG_DISABLED
642     double startTime = 0;
643     if (compositingLogEnabled()) {
644         ++m_rootLayerUpdateCount;
645         startTime = monotonicallyIncreasingTime();
646     }
647 #endif
648
649     if (checkForHierarchyUpdate) {
650         if (m_renderView.hasRenderNamedFlowThreads() && isFullUpdate)
651             m_renderView.flowThreadController().updateFlowThreadsLayerToRegionMappingsIfNeeded();
652         // Go through the layers in presentation order, so that we can compute which RenderLayers need compositing layers.
653         // FIXME: we could maybe do this and the hierarchy udpate in one pass, but the parenting logic would be more complex.
654         CompositingState compState(updateRoot);
655         bool layersChanged = false;
656         bool saw3DTransform = false;
657         OverlapMap overlapTestRequestMap;
658         computeCompositingRequirements(nullptr, *updateRoot, &overlapTestRequestMap, compState, layersChanged, saw3DTransform);
659         needHierarchyUpdate |= layersChanged;
660     }
661
662 #if !LOG_DISABLED
663     if (compositingLogEnabled() && isFullUpdate && (needHierarchyUpdate || needGeometryUpdate)) {
664         m_obligateCompositedLayerCount = 0;
665         m_secondaryCompositedLayerCount = 0;
666         m_obligatoryBackingStoreBytes = 0;
667         m_secondaryBackingStoreBytes = 0;
668
669         Frame& frame = m_renderView.frameView().frame();
670         bool isMainFrame = !m_renderView.document().ownerElement();
671         LOG(Compositing, "\nUpdate %d of %s.\n", m_rootLayerUpdateCount, isMainFrame ? "main frame" : frame.tree().uniqueName().string().utf8().data());
672     }
673 #endif
674
675     if (needHierarchyUpdate) {
676         // Update the hierarchy of the compositing layers.
677         Vector<GraphicsLayer*> childList;
678         rebuildCompositingLayerTree(*updateRoot, childList, 0);
679
680         // Host the document layer in the RenderView's root layer.
681         if (isFullUpdate) {
682             // Even when childList is empty, don't drop out of compositing mode if there are
683             // composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
684             if (childList.isEmpty() && !hasAnyAdditionalCompositedLayers(*updateRoot))
685                 destroyRootLayer();
686             else
687                 m_rootContentLayer->setChildren(childList);
688         }
689     } else if (needGeometryUpdate) {
690         // We just need to do a geometry update. This is only used for position:fixed scrolling;
691         // most of the time, geometry is updated via RenderLayer::styleChanged().
692         updateLayerTreeGeometry(*updateRoot, 0);
693     }
694     
695 #if !LOG_DISABLED
696     if (compositingLogEnabled() && isFullUpdate && (needHierarchyUpdate || needGeometryUpdate)) {
697         double endTime = monotonicallyIncreasingTime();
698         LOG(Compositing, "Total layers   primary   secondary   obligatory backing (KB)   secondary backing(KB)   total backing (KB)  update time (ms)\n");
699
700         LOG(Compositing, "%8d %11d %9d %20.2f %22.2f %22.2f %18.2f\n",
701             m_obligateCompositedLayerCount + m_secondaryCompositedLayerCount, m_obligateCompositedLayerCount,
702             m_secondaryCompositedLayerCount, m_obligatoryBackingStoreBytes / 1024, m_secondaryBackingStoreBytes / 1024, (m_obligatoryBackingStoreBytes + m_secondaryBackingStoreBytes) / 1024, 1000.0 * (endTime - startTime));
703     }
704 #endif
705     ASSERT(updateRoot || !m_compositingLayersNeedRebuild);
706
707     if (!hasAcceleratedCompositing())
708         enableCompositingMode(false);
709
710     // Inform the inspector that the layer tree has changed.
711     InspectorInstrumentation::layerTreeDidChange(page());
712 }
713
714 void RenderLayerCompositor::layerBecameNonComposited(const RenderLayer& layer)
715 {
716     // Inform the inspector that the given RenderLayer was destroyed.
717     InspectorInstrumentation::renderLayerDestroyed(page(), &layer);
718
719     ASSERT(m_compositedLayerCount > 0);
720     --m_compositedLayerCount;
721 }
722
723 #if !LOG_DISABLED
724 void RenderLayerCompositor::logLayerInfo(const RenderLayer& layer, int depth)
725 {
726     if (!compositingLogEnabled())
727         return;
728
729     RenderLayerBacking* backing = layer.backing();
730     if (requiresCompositingLayer(layer) || layer.isRootLayer()) {
731         ++m_obligateCompositedLayerCount;
732         m_obligatoryBackingStoreBytes += backing->backingStoreMemoryEstimate();
733     } else {
734         ++m_secondaryCompositedLayerCount;
735         m_secondaryBackingStoreBytes += backing->backingStoreMemoryEstimate();
736     }
737
738     StringBuilder logString;
739     logString.append(String::format("%*p %dx%d %.2fKB", 12 + depth * 2, &layer,
740         backing->compositedBounds().width().round(), backing->compositedBounds().height().round(),
741         backing->backingStoreMemoryEstimate() / 1024));
742     
743     logString.append(" (");
744     logString.append(logReasonsForCompositing(layer));
745     logString.append(") ");
746
747     if (backing->graphicsLayer()->contentsOpaque() || backing->paintsIntoCompositedAncestor()) {
748         logString.append('[');
749         if (backing->graphicsLayer()->contentsOpaque())
750             logString.append("opaque");
751         if (backing->paintsIntoCompositedAncestor())
752             logString.append("paints into ancestor");
753         logString.append("] ");
754     }
755
756     logString.append(layer.name());
757
758     LOG(Compositing, "%s", logString.toString().utf8().data());
759 }
760 #endif
761
762 bool RenderLayerCompositor::updateBacking(RenderLayer& layer, CompositingChangeRepaint shouldRepaint)
763 {
764     bool layerChanged = false;
765     RenderLayer::ViewportConstrainedNotCompositedReason viewportConstrainedNotCompositedReason = RenderLayer::NoNotCompositedReason;
766
767     if (needsToBeComposited(layer, &viewportConstrainedNotCompositedReason)) {
768         enableCompositingMode();
769         
770         if (!layer.backing()) {
771             // If we need to repaint, do so before making backing
772             if (shouldRepaint == CompositingChangeRepaintNow)
773                 repaintOnCompositingChange(layer);
774
775             layer.ensureBacking();
776
777             // At this time, the ScrollingCoordinator only supports the top-level frame.
778             if (layer.isRootLayer() && !m_renderView.document().ownerElement()) {
779                 updateScrollCoordinatedStatus(layer);
780                 if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
781                     scrollingCoordinator->frameViewRootLayerDidChange(&m_renderView.frameView());
782 #if ENABLE(RUBBER_BANDING)
783                 if (Page* page = this->page()) {
784                     updateLayerForHeader(page->headerHeight());
785                     updateLayerForFooter(page->footerHeight());
786                 }
787 #endif
788                 if (m_renderView.frameView().frame().settings().backgroundShouldExtendBeyondPage())
789                     m_rootContentLayer->setMasksToBounds(false);
790             }
791
792             // This layer and all of its descendants have cached repaints rects that are relative to
793             // the repaint container, so change when compositing changes; we need to update them here.
794             if (layer.parent())
795                 layer.computeRepaintRectsIncludingDescendants();
796
797             layerChanged = true;
798         }
799     } else {
800         if (layer.backing()) {
801             // If we're removing backing on a reflection, clear the source GraphicsLayer's pointer to
802             // its replica GraphicsLayer. In practice this should never happen because reflectee and reflection 
803             // are both either composited, or not composited.
804             if (layer.isReflection()) {
805                 RenderLayer* sourceLayer = toRenderLayerModelObject(layer.renderer().parent())->layer();
806                 if (RenderLayerBacking* backing = sourceLayer->backing()) {
807                     ASSERT(backing->graphicsLayer()->replicaLayer() == layer.backing()->graphicsLayer());
808                     backing->graphicsLayer()->setReplicatedByLayer(0);
809                 }
810             }
811
812             removeFromScrollCoordinatedLayers(layer);
813
814             layer.clearBacking();
815             layerChanged = true;
816
817             // This layer and all of its descendants have cached repaints rects that are relative to
818             // the repaint container, so change when compositing changes; we need to update them here.
819             layer.computeRepaintRectsIncludingDescendants();
820
821             // If we need to repaint, do so now that we've removed the backing
822             if (shouldRepaint == CompositingChangeRepaintNow)
823                 repaintOnCompositingChange(layer);
824         }
825     }
826     
827 #if ENABLE(VIDEO)
828     if (layerChanged && layer.renderer().isVideo()) {
829         // If it's a video, give the media player a chance to hook up to the layer.
830         toRenderVideo(layer.renderer()).acceleratedRenderingStateChanged();
831     }
832 #endif
833
834     if (layerChanged && layer.renderer().isWidget()) {
835         RenderLayerCompositor* innerCompositor = frameContentsCompositor(toRenderWidget(&layer.renderer()));
836         if (innerCompositor && innerCompositor->inCompositingMode())
837             innerCompositor->updateRootLayerAttachment();
838     }
839     
840     if (layerChanged)
841         layer.clearClipRectsIncludingDescendants(PaintingClipRects);
842
843     // If a fixed position layer gained/lost a backing or the reason not compositing it changed,
844     // the scrolling coordinator needs to recalculate whether it can do fast scrolling.
845     if (layer.renderer().style().position() == FixedPosition) {
846         if (layer.viewportConstrainedNotCompositedReason() != viewportConstrainedNotCompositedReason) {
847             layer.setViewportConstrainedNotCompositedReason(viewportConstrainedNotCompositedReason);
848             layerChanged = true;
849         }
850         if (layerChanged) {
851             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
852                 scrollingCoordinator->frameViewFixedObjectsDidChange(&m_renderView.frameView());
853         }
854     } else
855         layer.setViewportConstrainedNotCompositedReason(RenderLayer::NoNotCompositedReason);
856     
857     if (layer.backing())
858         layer.backing()->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
859
860     return layerChanged;
861 }
862
863 bool RenderLayerCompositor::updateLayerCompositingState(RenderLayer& layer, CompositingChangeRepaint shouldRepaint)
864 {
865     bool layerChanged = updateBacking(layer, shouldRepaint);
866
867     // See if we need content or clipping layers. Methods called here should assume
868     // that the compositing state of descendant layers has not been updated yet.
869     if (layer.backing() && layer.backing()->updateGraphicsLayerConfiguration())
870         layerChanged = true;
871
872     return layerChanged;
873 }
874
875 void RenderLayerCompositor::repaintOnCompositingChange(RenderLayer& layer)
876 {
877     // If the renderer is not attached yet, no need to repaint.
878     if (&layer.renderer() != &m_renderView && !layer.renderer().parent())
879         return;
880
881     RenderLayerModelObject* repaintContainer = layer.renderer().containerForRepaint();
882     if (!repaintContainer)
883         repaintContainer = &m_renderView;
884
885     layer.repaintIncludingNonCompositingDescendants(repaintContainer);
886     if (repaintContainer == &m_renderView) {
887         // The contents of this layer may be moving between the window
888         // and a GraphicsLayer, so we need to make sure the window system
889         // synchronizes those changes on the screen.
890         m_renderView.frameView().setNeedsOneShotDrawingSynchronization();
891     }
892 }
893
894 // This method assumes that layout is up-to-date, unlike repaintOnCompositingChange().
895 void RenderLayerCompositor::repaintInCompositedAncestor(RenderLayer& layer, const LayoutRect& rect)
896 {
897     RenderLayer* compositedAncestor = layer.enclosingCompositingLayerForRepaint(ExcludeSelf);
898     if (compositedAncestor) {
899         ASSERT(compositedAncestor->backing());
900
901         LayoutPoint offset;
902         layer.convertToLayerCoords(compositedAncestor, offset);
903
904         LayoutRect repaintRect = rect;
905         repaintRect.moveBy(offset);
906
907         compositedAncestor->setBackingNeedsRepaintInRect(repaintRect);
908     }
909
910     // The contents of this layer may be moving from a GraphicsLayer to the window,
911     // so we need to make sure the window system synchronizes those changes on the screen.
912     if (compositedAncestor == m_renderView.layer())
913         m_renderView.frameView().setNeedsOneShotDrawingSynchronization();
914 }
915
916 // The bounds of the GraphicsLayer created for a compositing layer is the union of the bounds of all the descendant
917 // RenderLayers that are rendered by the composited RenderLayer.
918 LayoutRect RenderLayerCompositor::calculateCompositedBounds(const RenderLayer& layer, const RenderLayer& ancestorLayer) const
919 {
920     if (!canBeComposited(layer))
921         return LayoutRect();
922     return layer.calculateLayerBounds(&ancestorLayer, nullptr, RenderLayer::DefaultCalculateLayerBoundsFlags | RenderLayer::ExcludeHiddenDescendants | RenderLayer::DontConstrainForMask);
923 }
924
925 void RenderLayerCompositor::layerWasAdded(RenderLayer&, RenderLayer&)
926 {
927     setCompositingLayersNeedRebuild();
928 }
929
930 void RenderLayerCompositor::layerWillBeRemoved(RenderLayer& parent, RenderLayer& child)
931 {
932     if (!child.isComposited() || parent.renderer().documentBeingDestroyed())
933         return;
934
935     removeFromScrollCoordinatedLayers(child);
936     repaintInCompositedAncestor(child, child.backing()->compositedBounds());
937
938     setCompositingParent(child, nullptr);
939     setCompositingLayersNeedRebuild();
940 }
941
942 RenderLayer* RenderLayerCompositor::enclosingNonStackingClippingLayer(const RenderLayer& layer) const
943 {
944     for (RenderLayer* parent = layer.parent(); parent; parent = parent->parent()) {
945         if (parent->isStackingContainer())
946             return nullptr;
947         if (parent->renderer().hasClipOrOverflowClip())
948             return parent;
949     }
950     return nullptr;
951 }
952
953 void RenderLayerCompositor::addToOverlapMap(OverlapMap& overlapMap, RenderLayer& layer, IntRect& layerBounds, bool& boundsComputed)
954 {
955     if (layer.isRootLayer())
956         return;
957
958     if (!boundsComputed) {
959         // FIXME: If this layer's overlap bounds include its children, we don't need to add its
960         // children's bounds to the overlap map.
961         layerBounds = enclosingIntRect(overlapMap.geometryMap().absoluteRect(layer.overlapBounds()));
962         // Empty rects never intersect, but we need them to for the purposes of overlap testing.
963         if (layerBounds.isEmpty())
964             layerBounds.setSize(IntSize(1, 1));
965         boundsComputed = true;
966     }
967
968     IntRect clipRect = pixelSnappedIntRect(layer.backgroundClipRect(RenderLayer::ClipRectsContext(&rootRenderLayer(), 0, AbsoluteClipRects)).rect()); // FIXME: Incorrect for CSS regions.
969
970     // On iOS, pageScaleFactor() is not applied by RenderView, so we should not scale here.
971     // FIXME: Set Settings::delegatesPageScaling to true for iOS.
972 #if !PLATFORM(IOS)
973     const Settings& settings = m_renderView.frameView().frame().settings();
974     if (!settings.delegatesPageScaling())
975         clipRect.scale(pageScaleFactor());
976 #endif
977     clipRect.intersect(layerBounds);
978     overlapMap.add(&layer, clipRect);
979 }
980
981 void RenderLayerCompositor::addToOverlapMapRecursive(OverlapMap& overlapMap, RenderLayer& layer, RenderLayer* ancestorLayer)
982 {
983     if (!canBeComposited(layer) || overlapMap.contains(&layer))
984         return;
985
986     // A null ancestorLayer is an indication that 'layer' has already been pushed.
987     if (ancestorLayer)
988         overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer);
989     
990     IntRect bounds;
991     bool haveComputedBounds = false;
992     addToOverlapMap(overlapMap, layer, bounds, haveComputedBounds);
993
994 #if !ASSERT_DISABLED
995     LayerListMutationDetector mutationChecker(&layer);
996 #endif
997
998     if (layer.isStackingContainer()) {
999         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1000             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i)
1001                 addToOverlapMapRecursive(overlapMap, *negZOrderList->at(i), &layer);
1002         }
1003     }
1004
1005     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1006         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i)
1007             addToOverlapMapRecursive(overlapMap, *normalFlowList->at(i), &layer);
1008     }
1009
1010     if (layer.isStackingContainer()) {
1011         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1012             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i)
1013                 addToOverlapMapRecursive(overlapMap, *posZOrderList->at(i), &layer);
1014         }
1015     }
1016     
1017     if (ancestorLayer)
1018         overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
1019 }
1020
1021 void RenderLayerCompositor::computeCompositingRequirementsForNamedFlowFixed(RenderLayer& layer, OverlapMap* overlapMap, CompositingState& childState, bool& layersChanged, bool& anyDescendantHas3DTransform)
1022 {
1023     if (!layer.isRootLayer())
1024         return;
1025
1026     if (!layer.renderer().view().hasRenderNamedFlowThreads())
1027         return;
1028
1029     Vector<RenderLayer*> fixedLayers;
1030     layer.renderer().view().flowThreadController().collectFixedPositionedLayers(fixedLayers);
1031
1032     for (size_t i = 0; i < fixedLayers.size(); ++i) {
1033         RenderLayer* fixedLayer = fixedLayers.at(i);
1034         computeCompositingRequirements(&layer, *fixedLayer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1035     }
1036 }
1037
1038 //  Recurse through the layers in z-index and overflow order (which is equivalent to painting order)
1039 //  For the z-order children of a compositing layer:
1040 //      If a child layers has a compositing layer, then all subsequent layers must
1041 //      be compositing in order to render above that layer.
1042 //
1043 //      If a child in the negative z-order list is compositing, then the layer itself
1044 //      must be compositing so that its contents render over that child.
1045 //      This implies that its positive z-index children must also be compositing.
1046 //
1047 void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer& layer, OverlapMap* overlapMap, CompositingState& compositingState, bool& layersChanged, bool& descendantHas3DTransform)
1048 {
1049     layer.updateDescendantDependentFlags();
1050     layer.updateLayerListsIfNeeded();
1051
1052     if (layer.isFlowThreadCollectingGraphicsLayersUnderRegions()) {
1053         RenderFlowThread& flowThread = toRenderFlowThread(layer.renderer());
1054         layer.setHasCompositingDescendant(flowThread.hasCompositingRegionDescendant());
1055
1056         // Before returning, we need to update the lists of all child layers. This is required because,
1057         // if this flow thread will not be painted (for instance because of having no regions, or only invalid regions),
1058         // the child layers will never have their lists updated (which would normally happen during painting).
1059         layer.updateDescendantsLayerListsIfNeeded(true);
1060
1061         return;
1062     }
1063
1064     if (overlapMap)
1065         overlapMap->geometryMap().pushMappingsToAncestor(&layer, ancestorLayer);
1066     
1067     // Clear the flag
1068     layer.setHasCompositingDescendant(false);
1069
1070     RenderLayer::IndirectCompositingReason compositingReason = compositingState.m_subtreeIsCompositing ? RenderLayer::IndirectCompositingForStacking : RenderLayer::NoIndirectCompositingReason;
1071
1072     bool haveComputedBounds = false;
1073     IntRect absBounds;
1074     if (overlapMap && !overlapMap->isEmpty() && compositingState.m_testingOverlap) {
1075         // If we're testing for overlap, we only need to composite if we overlap something that is already composited.
1076         absBounds = enclosingIntRect(overlapMap->geometryMap().absoluteRect(layer.overlapBounds()));
1077
1078         // Empty rects never intersect, but we need them to for the purposes of overlap testing.
1079         if (absBounds.isEmpty())
1080             absBounds.setSize(IntSize(1, 1));
1081         haveComputedBounds = true;
1082         compositingReason = overlapMap->overlapsLayers(absBounds) ? RenderLayer::IndirectCompositingForOverlap : RenderLayer::NoIndirectCompositingReason;
1083     }
1084
1085 #if ENABLE(VIDEO)
1086     // Video is special. It's the only RenderLayer type that can both have
1087     // RenderLayer children and whose children can't use its backing to render
1088     // into. These children (the controls) always need to be promoted into their
1089     // own layers to draw on top of the accelerated video.
1090     if (compositingState.m_compositingAncestor && compositingState.m_compositingAncestor->renderer().isVideo())
1091         compositingReason = RenderLayer::IndirectCompositingForOverlap;
1092 #endif
1093
1094     layer.setIndirectCompositingReason(compositingReason);
1095
1096     // The children of this layer don't need to composite, unless there is
1097     // a compositing layer among them, so start by inheriting the compositing
1098     // ancestor with m_subtreeIsCompositing set to false.
1099     CompositingState childState(compositingState);
1100     childState.m_subtreeIsCompositing = false;
1101
1102     bool willBeComposited = needsToBeComposited(layer);
1103     if (willBeComposited) {
1104         // Tell the parent it has compositing descendants.
1105         compositingState.m_subtreeIsCompositing = true;
1106         // This layer now acts as the ancestor for kids.
1107         childState.m_compositingAncestor = &layer;
1108
1109         if (overlapMap)
1110             overlapMap->pushCompositingContainer();
1111         // This layer is going to be composited, so children can safely ignore the fact that there's an 
1112         // animation running behind this layer, meaning they can rely on the overlap map testing again.
1113         childState.m_testingOverlap = true;
1114     }
1115
1116 #if !ASSERT_DISABLED
1117     LayerListMutationDetector mutationChecker(&layer);
1118 #endif
1119
1120     bool anyDescendantHas3DTransform = false;
1121
1122     if (layer.isStackingContainer()) {
1123         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1124             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i) {
1125                 computeCompositingRequirements(&layer, *negZOrderList->at(i), overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1126
1127                 // If we have to make a layer for this child, make one now so we can have a contents layer
1128                 // (since we need to ensure that the -ve z-order child renders underneath our contents).
1129                 if (!willBeComposited && childState.m_subtreeIsCompositing) {
1130                     // make layer compositing
1131                     layer.setIndirectCompositingReason(RenderLayer::IndirectCompositingForBackgroundLayer);
1132                     childState.m_compositingAncestor = &layer;
1133                     if (overlapMap)
1134                         overlapMap->pushCompositingContainer();
1135                     // This layer is going to be composited, so children can safely ignore the fact that there's an 
1136                     // animation running behind this layer, meaning they can rely on the overlap map testing again
1137                     childState.m_testingOverlap = true;
1138                     willBeComposited = true;
1139                 }
1140             }
1141         }
1142     }
1143
1144     if (layer.renderer().isRenderNamedFlowFragmentContainer()) {
1145         // We are going to collect layers from the RenderFlowThread into the GraphicsLayer of the parent of the
1146         // anonymous RenderRegion, but first we need to make sure that the parent itself of the region is going to
1147         // have a composited layer. We only want to make regions composited when there's an actual layer that we
1148         // need to move to that region.
1149         computeRegionCompositingRequirements(toRenderBlockFlow(layer.renderer()).renderNamedFlowFragment(), overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1150     }
1151
1152     
1153     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1154         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i)
1155             computeCompositingRequirements(&layer, *normalFlowList->at(i), overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1156     }
1157
1158     if (layer.isStackingContainer()) {
1159         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1160             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i)
1161                 computeCompositingRequirements(&layer, *posZOrderList->at(i), overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1162         }
1163     }
1164
1165     if (layer.isRootLayer())
1166         computeCompositingRequirementsForNamedFlowFixed(layer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1167
1168     // If we just entered compositing mode, the root will have become composited (as long as accelerated compositing is enabled).
1169     if (layer.isRootLayer()) {
1170         if (inCompositingMode() && m_hasAcceleratedCompositing)
1171             willBeComposited = true;
1172     }
1173     
1174     // If the layer composited for other reasons than blending, it is no longer needed to keep track of whether a child was blended.
1175     if (compositingState.m_subtreeHasBlending && !layer.hasBlendMode())
1176         compositingState.m_subtreeHasBlending = false;
1177
1178     ASSERT(willBeComposited == needsToBeComposited(layer));
1179
1180     // All layers (even ones that aren't being composited) need to get added to
1181     // the overlap map. Layers that do not composite will draw into their
1182     // compositing ancestor's backing, and so are still considered for overlap.
1183     if (overlapMap && childState.m_compositingAncestor && !childState.m_compositingAncestor->isRootLayer())
1184         addToOverlapMap(*overlapMap, layer, absBounds, haveComputedBounds);
1185
1186     if (childState.m_subtreeHasBlending || layer.hasBlendMode())
1187         compositingState.m_subtreeHasBlending = true;
1188
1189     // Now check for reasons to become composited that depend on the state of descendant layers.
1190     RenderLayer::IndirectCompositingReason indirectCompositingReason;
1191     if (!willBeComposited && canBeComposited(layer)
1192         && requiresCompositingForIndirectReason(layer.renderer(), childState.m_subtreeIsCompositing, compositingState.m_subtreeHasBlending, anyDescendantHas3DTransform, indirectCompositingReason)) {
1193         layer.setIndirectCompositingReason(indirectCompositingReason);
1194         childState.m_compositingAncestor = &layer;
1195         if (overlapMap) {
1196             overlapMap->pushCompositingContainer();
1197             addToOverlapMapRecursive(*overlapMap, layer);
1198         }
1199         willBeComposited = true;
1200     }
1201     
1202     ASSERT(willBeComposited == needsToBeComposited(layer));
1203     if (layer.reflectionLayer()) {
1204         // FIXME: Shouldn't we call computeCompositingRequirements to handle a reflection overlapping with another renderer?
1205         layer.reflectionLayer()->setIndirectCompositingReason(willBeComposited ? RenderLayer::IndirectCompositingForStacking : RenderLayer::NoIndirectCompositingReason);
1206     }
1207
1208     // Subsequent layers in the parent stacking context also need to composite.
1209     if (childState.m_subtreeIsCompositing)
1210         compositingState.m_subtreeIsCompositing = true;
1211
1212     // Set the flag to say that this SC has compositing children.
1213     layer.setHasCompositingDescendant(childState.m_subtreeIsCompositing);
1214
1215     // setHasCompositingDescendant() may have changed the answer to needsToBeComposited() when clipping,
1216     // so test that again.
1217     bool isCompositedClippingLayer = canBeComposited(layer) && clipsCompositingDescendants(layer);
1218
1219     // Turn overlap testing off for later layers if it's already off, or if we have an animating transform.
1220     // Note that if the layer clips its descendants, there's no reason to propagate the child animation to the parent layers. That's because
1221     // we know for sure the animation is contained inside the clipping rectangle, which is already added to the overlap map.
1222     if ((!childState.m_testingOverlap && !isCompositedClippingLayer) || isRunningAcceleratedTransformAnimation(layer.renderer()))
1223         compositingState.m_testingOverlap = false;
1224     
1225     if (isCompositedClippingLayer) {
1226         if (!willBeComposited) {
1227             childState.m_compositingAncestor = &layer;
1228             if (overlapMap) {
1229                 overlapMap->pushCompositingContainer();
1230                 addToOverlapMapRecursive(*overlapMap, layer);
1231             }
1232             willBeComposited = true;
1233          }
1234     }
1235
1236     if (overlapMap && childState.m_compositingAncestor == &layer && !layer.isRootLayer())
1237         overlapMap->popCompositingContainer();
1238
1239     // If we're back at the root, and no other layers need to be composited, and the root layer itself doesn't need
1240     // to be composited, then we can drop out of compositing mode altogether. However, don't drop out of compositing mode
1241     // if there are composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
1242     if (layer.isRootLayer() && !childState.m_subtreeIsCompositing && !requiresCompositingLayer(layer) && !m_forceCompositingMode && !hasAnyAdditionalCompositedLayers(layer)) {
1243         // Don't drop out of compositing on iOS, because we may flash. See <rdar://problem/8348337>.
1244 #if !PLATFORM(IOS)
1245         enableCompositingMode(false);
1246         willBeComposited = false;
1247 #endif
1248     }
1249     
1250     // If the layer is going into compositing mode, repaint its old location.
1251     ASSERT(willBeComposited == needsToBeComposited(layer));
1252     if (!layer.isComposited() && willBeComposited)
1253         repaintOnCompositingChange(layer);
1254
1255     // Update backing now, so that we can use isComposited() reliably during tree traversal in rebuildCompositingLayerTree().
1256     if (updateBacking(layer, CompositingChangeRepaintNow))
1257         layersChanged = true;
1258
1259     if (layer.reflectionLayer() && updateLayerCompositingState(*layer.reflectionLayer(), CompositingChangeRepaintNow))
1260         layersChanged = true;
1261
1262     descendantHas3DTransform |= anyDescendantHas3DTransform || layer.has3DTransform();
1263
1264     if (overlapMap)
1265         overlapMap->geometryMap().popMappingsToAncestor(ancestorLayer);
1266 }
1267
1268 void RenderLayerCompositor::computeRegionCompositingRequirements(RenderNamedFlowFragment* region, OverlapMap* overlapMap, CompositingState& childState, bool& layersChanged, bool& anyDescendantHas3DTransform)
1269 {
1270     if (!region->isValid())
1271         return;
1272
1273     RenderFlowThread* flowThread = region->flowThread();
1274     
1275     if (overlapMap)
1276         overlapMap->geometryMap().pushRenderFlowThread(flowThread);
1277
1278     if (const RenderLayerList* layerList = flowThread->getLayerListForRegion(region)) {
1279         for (size_t i = 0, listSize = layerList->size(); i < listSize; ++i) {
1280             RenderLayer& curLayer = *layerList->at(i);
1281             ASSERT(flowThread->regionForCompositedLayer(curLayer) == region);
1282             computeCompositingRequirements(flowThread->layer(), curLayer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1283         }
1284     }
1285
1286     if (overlapMap)
1287         overlapMap->geometryMap().popMappingsToAncestor(&region->layerOwner());
1288 }
1289
1290 void RenderLayerCompositor::setCompositingParent(RenderLayer& childLayer, RenderLayer* parentLayer)
1291 {
1292     ASSERT(!parentLayer || childLayer.ancestorCompositingLayer() == parentLayer);
1293     ASSERT(childLayer.isComposited());
1294
1295     // It's possible to be called with a parent that isn't yet composited when we're doing
1296     // partial updates as required by painting or hit testing. Just bail in that case;
1297     // we'll do a full layer update soon.
1298     if (!parentLayer || !parentLayer->isComposited())
1299         return;
1300
1301     if (parentLayer) {
1302         GraphicsLayer* hostingLayer = parentLayer->backing()->parentForSublayers();
1303         GraphicsLayer* hostedLayer = childLayer.backing()->childForSuperlayers();
1304         
1305         hostingLayer->addChild(hostedLayer);
1306     } else
1307         childLayer.backing()->childForSuperlayers()->removeFromParent();
1308 }
1309
1310 void RenderLayerCompositor::removeCompositedChildren(RenderLayer& layer)
1311 {
1312     ASSERT(layer.isComposited());
1313
1314     layer.backing()->parentForSublayers()->removeAllChildren();
1315 }
1316
1317 #if ENABLE(VIDEO)
1318 bool RenderLayerCompositor::canAccelerateVideoRendering(RenderVideo& video) const
1319 {
1320     if (!m_hasAcceleratedCompositing)
1321         return false;
1322
1323     return video.supportsAcceleratedRendering();
1324 }
1325 #endif
1326
1327 void RenderLayerCompositor::rebuildCompositingLayerTreeForNamedFlowFixed(RenderLayer& layer, Vector<GraphicsLayer*>& childGraphicsLayersOfEnclosingLayer, int depth)
1328 {
1329     if (!layer.isRootLayer())
1330         return;
1331
1332     if (!layer.renderer().view().hasRenderNamedFlowThreads())
1333         return;
1334
1335     Vector<RenderLayer*> fixedLayers;
1336     layer.renderer().view().flowThreadController().collectFixedPositionedLayers(fixedLayers);
1337
1338     for (size_t i = 0; i < fixedLayers.size(); ++i) {
1339         RenderLayer* fixedLayer = fixedLayers.at(i);
1340         rebuildCompositingLayerTree(*fixedLayer, childGraphicsLayersOfEnclosingLayer, depth);
1341     }
1342 }
1343
1344 void RenderLayerCompositor::rebuildCompositingLayerTree(RenderLayer& layer, Vector<GraphicsLayer*>& childLayersOfEnclosingLayer, int depth)
1345 {
1346     // Make the layer compositing if necessary, and set up clipping and content layers.
1347     // Note that we can only do work here that is independent of whether the descendant layers
1348     // have been processed. computeCompositingRequirements() will already have done the repaint if necessary.
1349
1350     // Do not iterate the RenderFlowThread directly. We are going to collect composited layers as part of regions.
1351     if (layer.isFlowThreadCollectingGraphicsLayersUnderRegions())
1352         return;
1353
1354     RenderLayerBacking* layerBacking = layer.backing();
1355     if (layerBacking) {
1356         // The compositing state of all our children has been updated already, so now
1357         // we can compute and cache the composited bounds for this layer.
1358         layerBacking->updateCompositedBounds();
1359
1360         if (RenderLayer* reflection = layer.reflectionLayer()) {
1361             if (reflection->backing())
1362                 reflection->backing()->updateCompositedBounds();
1363         }
1364
1365         if (layerBacking->updateGraphicsLayerConfiguration())
1366             layerBacking->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
1367         
1368         layerBacking->updateGraphicsLayerGeometry();
1369
1370         if (!layer.parent())
1371             updateRootLayerPosition();
1372
1373 #if !LOG_DISABLED
1374         logLayerInfo(layer, depth);
1375 #else
1376         UNUSED_PARAM(depth);
1377 #endif
1378         if (layerBacking->hasUnpositionedOverflowControlsLayers())
1379             layer.positionNewlyCreatedOverflowControls();
1380     }
1381
1382     // If this layer has backing, then we are collecting its children, otherwise appending
1383     // to the compositing child list of an enclosing layer.
1384     Vector<GraphicsLayer*> layerChildren;
1385     Vector<GraphicsLayer*>& childList = layerBacking ? layerChildren : childLayersOfEnclosingLayer;
1386
1387 #if !ASSERT_DISABLED
1388     LayerListMutationDetector mutationChecker(&layer);
1389 #endif
1390
1391     if (layer.isStackingContainer()) {
1392         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1393             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i)
1394                 rebuildCompositingLayerTree(*negZOrderList->at(i), childList, depth + 1);
1395         }
1396
1397         // If a negative z-order child is compositing, we get a foreground layer which needs to get parented.
1398         if (layerBacking && layerBacking->foregroundLayer())
1399             childList.append(layerBacking->foregroundLayer());
1400     }
1401
1402     if (layer.renderer().isRenderNamedFlowFragmentContainer())
1403         rebuildRegionCompositingLayerTree(toRenderBlockFlow(layer.renderer()).renderNamedFlowFragment(), layerChildren, depth + 1);
1404
1405     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1406         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i)
1407             rebuildCompositingLayerTree(*normalFlowList->at(i), childList, depth + 1);
1408     }
1409     
1410     if (layer.isStackingContainer()) {
1411         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1412             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i)
1413                 rebuildCompositingLayerTree(*posZOrderList->at(i), childList, depth + 1);
1414         }
1415     }
1416
1417     if (layer.isRootLayer())
1418         rebuildCompositingLayerTreeForNamedFlowFixed(layer, childList, depth + 1);
1419
1420     if (layerBacking) {
1421         bool parented = false;
1422         if (layer.renderer().isWidget())
1423             parented = parentFrameContentLayers(toRenderWidget(&layer.renderer()));
1424
1425         if (!parented)
1426             layerBacking->parentForSublayers()->setChildren(layerChildren);
1427
1428         // If the layer has a clipping layer the overflow controls layers will be siblings of the clipping layer.
1429         // Otherwise, the overflow control layers are normal children.
1430         if (!layerBacking->hasClippingLayer() && !layerBacking->hasScrollingLayer()) {
1431             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForHorizontalScrollbar()) {
1432                 overflowControlLayer->removeFromParent();
1433                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
1434             }
1435
1436             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForVerticalScrollbar()) {
1437                 overflowControlLayer->removeFromParent();
1438                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
1439             }
1440
1441             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForScrollCorner()) {
1442                 overflowControlLayer->removeFromParent();
1443                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
1444             }
1445         }
1446
1447         childLayersOfEnclosingLayer.append(layerBacking->childForSuperlayers());
1448     }
1449 }
1450
1451 void RenderLayerCompositor::rebuildRegionCompositingLayerTree(RenderNamedFlowFragment* region, Vector<GraphicsLayer*>& childList, int depth)
1452 {
1453     if (!region->isValid())
1454         return;
1455
1456     RenderFlowThread* flowThread = region->flowThread();
1457     ASSERT(flowThread->collectsGraphicsLayersUnderRegions());
1458     if (const RenderLayerList* layerList = flowThread->getLayerListForRegion(region)) {
1459         for (size_t i = 0, listSize = layerList->size(); i < listSize; ++i) {
1460             RenderLayer& curLayer = *layerList->at(i);
1461             ASSERT(flowThread->regionForCompositedLayer(curLayer) == region);
1462             rebuildCompositingLayerTree(curLayer, childList, depth + 1);
1463         }
1464     }
1465 }
1466
1467 void RenderLayerCompositor::frameViewDidChangeLocation(const IntPoint& contentsOffset)
1468 {
1469     if (m_overflowControlsHostLayer)
1470         m_overflowControlsHostLayer->setPosition(contentsOffset);
1471 }
1472
1473 void RenderLayerCompositor::frameViewDidChangeSize()
1474 {
1475     if (m_clipLayer) {
1476         const FrameView& frameView = m_renderView.frameView();
1477         m_clipLayer->setSize(frameView.unscaledTotalVisibleContentSize());
1478
1479         frameViewDidScroll();
1480         updateOverflowControlsLayers();
1481
1482 #if ENABLE(RUBBER_BANDING)
1483         if (m_layerForOverhangAreas)
1484             m_layerForOverhangAreas->setSize(frameView.frameRect().size());
1485 #endif
1486     }
1487 }
1488
1489 bool RenderLayerCompositor::hasCoordinatedScrolling() const
1490 {
1491     ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator();
1492     return scrollingCoordinator && scrollingCoordinator->coordinatesScrollingForFrameView(&m_renderView.frameView());
1493 }
1494
1495 void RenderLayerCompositor::updateScrollLayerPosition()
1496 {
1497     ASSERT(m_scrollLayer);
1498
1499     FrameView& frameView = m_renderView.frameView();
1500     IntPoint scrollPosition = frameView.scrollPosition();
1501
1502     const Settings& settings = m_renderView.frameView().frame().settings();
1503     if (settings.compositedScrollingForFramesEnabled()) {
1504         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
1505             scrollingCoordinator->scrollableAreaScrollLayerDidChange(&frameView);
1506     }
1507
1508     m_scrollLayer->setPosition(FloatPoint(-scrollPosition.x(), -scrollPosition.y()));
1509
1510     if (GraphicsLayer* fixedBackgroundLayer = fixedRootBackgroundLayer())
1511         fixedBackgroundLayer->setPosition(toLayoutPoint(frameView.scrollOffsetForFixedPosition()));
1512 }
1513
1514 void RenderLayerCompositor::frameViewDidScroll()
1515 {
1516     if (!m_scrollLayer)
1517         return;
1518
1519     // If there's a scrolling coordinator that manages scrolling for this frame view,
1520     // it will also manage updating the scroll layer position.
1521     if (hasCoordinatedScrolling()) {
1522         // We have to schedule a flush in order for the main TiledBacking to update its tile coverage.
1523         scheduleLayerFlushNow();
1524         return;
1525     }
1526
1527     updateScrollLayerPosition();
1528 }
1529
1530 void RenderLayerCompositor::frameViewDidAddOrRemoveScrollbars()
1531 {
1532     updateOverflowControlsLayers();
1533 }
1534
1535 void RenderLayerCompositor::frameViewDidLayout()
1536 {
1537     RenderLayerBacking* renderViewBacking = m_renderView.layer()->backing();
1538     if (renderViewBacking)
1539         renderViewBacking->adjustTiledBackingCoverage();
1540 }
1541
1542 void RenderLayerCompositor::rootFixedBackgroundsChanged()
1543 {
1544     RenderLayerBacking* renderViewBacking = m_renderView.layer()->backing();
1545     if (renderViewBacking && renderViewBacking->usingTiledBacking())
1546         setCompositingLayersNeedRebuild();
1547 }
1548
1549 void RenderLayerCompositor::scrollingLayerDidChange(RenderLayer& layer)
1550 {
1551     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
1552         scrollingCoordinator->scrollableAreaScrollLayerDidChange(&layer);
1553 }
1554
1555 void RenderLayerCompositor::fixedRootBackgroundLayerChanged()
1556 {
1557     if (m_renderView.documentBeingDestroyed())
1558         return;
1559
1560     if (m_renderView.layer()->isComposited())
1561         updateScrollCoordinatedStatus(*m_renderView.layer());
1562 }
1563
1564 String RenderLayerCompositor::layerTreeAsText(LayerTreeFlags flags)
1565 {
1566     updateCompositingLayers(CompositingUpdateAfterLayout);
1567
1568     if (!m_rootContentLayer)
1569         return String();
1570
1571     flushPendingLayerChanges(true);
1572
1573     LayerTreeAsTextBehavior layerTreeBehavior = LayerTreeAsTextBehaviorNormal;
1574     if (flags & LayerTreeFlagsIncludeDebugInfo)
1575         layerTreeBehavior |= LayerTreeAsTextDebug;
1576     if (flags & LayerTreeFlagsIncludeVisibleRects)
1577         layerTreeBehavior |= LayerTreeAsTextIncludeVisibleRects;
1578     if (flags & LayerTreeFlagsIncludeTileCaches)
1579         layerTreeBehavior |= LayerTreeAsTextIncludeTileCaches;
1580     if (flags & LayerTreeFlagsIncludeRepaintRects)
1581         layerTreeBehavior |= LayerTreeAsTextIncludeRepaintRects;
1582     if (flags & LayerTreeFlagsIncludePaintingPhases)
1583         layerTreeBehavior |= LayerTreeAsTextIncludePaintingPhases;
1584     if (flags & LayerTreeFlagsIncludeContentLayers)
1585         layerTreeBehavior |= LayerTreeAsTextIncludeContentLayers;
1586
1587     // We skip dumping the scroll and clip layers to keep layerTreeAsText output
1588     // similar between platforms.
1589     String layerTreeText = m_rootContentLayer->layerTreeAsText(layerTreeBehavior);
1590
1591     // Dump an empty layer tree only if the only composited layer is the main frame's tiled backing,
1592     // so that tests expecting us to drop out of accelerated compositing when there are no layers succeed.
1593     if (!hasAnyAdditionalCompositedLayers(rootRenderLayer()) && mainFrameBackingIsTiled() && !(layerTreeBehavior & LayerTreeAsTextIncludeTileCaches))
1594         layerTreeText = "";
1595
1596     // The true root layer is not included in the dump, so if we want to report
1597     // its repaint rects, they must be included here.
1598     if (flags & LayerTreeFlagsIncludeRepaintRects)
1599         return m_renderView.frameView().trackedRepaintRectsAsText() + layerTreeText;
1600
1601     return layerTreeText;
1602 }
1603
1604 RenderLayerCompositor* RenderLayerCompositor::frameContentsCompositor(RenderWidget* renderer)
1605 {
1606     if (Document* contentDocument = renderer->frameOwnerElement().contentDocument()) {
1607         if (RenderView* view = contentDocument->renderView())
1608             return &view->compositor();
1609     }
1610     return 0;
1611 }
1612
1613 bool RenderLayerCompositor::parentFrameContentLayers(RenderWidget* renderer)
1614 {
1615     RenderLayerCompositor* innerCompositor = frameContentsCompositor(renderer);
1616     if (!innerCompositor || !innerCompositor->inCompositingMode() || innerCompositor->rootLayerAttachment() != RootLayerAttachedViaEnclosingFrame)
1617         return false;
1618     
1619     RenderLayer* layer = renderer->layer();
1620     if (!layer->isComposited())
1621         return false;
1622
1623     RenderLayerBacking* backing = layer->backing();
1624     GraphicsLayer* hostingLayer = backing->parentForSublayers();
1625     GraphicsLayer* rootLayer = innerCompositor->rootGraphicsLayer();
1626     if (hostingLayer->children().size() != 1 || hostingLayer->children()[0] != rootLayer) {
1627         hostingLayer->removeAllChildren();
1628         hostingLayer->addChild(rootLayer);
1629     }
1630     return true;
1631 }
1632
1633 // This just updates layer geometry without changing the hierarchy.
1634 void RenderLayerCompositor::updateLayerTreeGeometry(RenderLayer& layer, int depth)
1635 {
1636     if (RenderLayerBacking* layerBacking = layer.backing()) {
1637         // The compositing state of all our children has been updated already, so now
1638         // we can compute and cache the composited bounds for this layer.
1639         layerBacking->updateCompositedBounds();
1640
1641         if (RenderLayer* reflection = layer.reflectionLayer()) {
1642             if (reflection->backing())
1643                 reflection->backing()->updateCompositedBounds();
1644         }
1645
1646         layerBacking->updateGraphicsLayerConfiguration();
1647         layerBacking->updateGraphicsLayerGeometry();
1648
1649         if (!layer.parent())
1650             updateRootLayerPosition();
1651
1652 #if !LOG_DISABLED
1653         logLayerInfo(layer, depth);
1654 #else
1655         UNUSED_PARAM(depth);
1656 #endif
1657     }
1658
1659 #if !ASSERT_DISABLED
1660     LayerListMutationDetector mutationChecker(&layer);
1661 #endif
1662
1663     if (layer.isStackingContainer()) {
1664         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1665             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i)
1666                 updateLayerTreeGeometry(*negZOrderList->at(i), depth + 1);
1667         }
1668     }
1669
1670     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1671         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i)
1672             updateLayerTreeGeometry(*normalFlowList->at(i), depth + 1);
1673     }
1674     
1675     if (layer.isStackingContainer()) {
1676         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1677             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i)
1678                 updateLayerTreeGeometry(*posZOrderList->at(i), depth + 1);
1679         }
1680     }
1681 }
1682
1683 // Recurs down the RenderLayer tree until its finds the compositing descendants of compositingAncestor and updates their geometry.
1684 void RenderLayerCompositor::updateCompositingDescendantGeometry(RenderLayer& compositingAncestor, RenderLayer& layer, bool compositedChildrenOnly)
1685 {
1686     if (&layer != &compositingAncestor) {
1687         if (RenderLayerBacking* layerBacking = layer.backing()) {
1688             layerBacking->updateCompositedBounds();
1689
1690             if (RenderLayer* reflection = layer.reflectionLayer()) {
1691                 if (reflection->backing())
1692                     reflection->backing()->updateCompositedBounds();
1693             }
1694
1695             layerBacking->updateGraphicsLayerGeometry();
1696             if (compositedChildrenOnly)
1697                 return;
1698         }
1699     }
1700
1701     if (layer.reflectionLayer())
1702         updateCompositingDescendantGeometry(compositingAncestor, *layer.reflectionLayer(), compositedChildrenOnly);
1703
1704     if (!layer.hasCompositingDescendant())
1705         return;
1706
1707 #if !ASSERT_DISABLED
1708     LayerListMutationDetector mutationChecker(&layer);
1709 #endif
1710     
1711     if (layer.isStackingContainer()) {
1712         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1713             size_t listSize = negZOrderList->size();
1714             for (size_t i = 0; i < listSize; ++i)
1715                 updateCompositingDescendantGeometry(compositingAncestor, *negZOrderList->at(i), compositedChildrenOnly);
1716         }
1717     }
1718
1719     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1720         size_t listSize = normalFlowList->size();
1721         for (size_t i = 0; i < listSize; ++i)
1722             updateCompositingDescendantGeometry(compositingAncestor, *normalFlowList->at(i), compositedChildrenOnly);
1723     }
1724     
1725     if (layer.isStackingContainer()) {
1726         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1727             size_t listSize = posZOrderList->size();
1728             for (size_t i = 0; i < listSize; ++i)
1729                 updateCompositingDescendantGeometry(compositingAncestor, *posZOrderList->at(i), compositedChildrenOnly);
1730         }
1731     }
1732 }
1733
1734
1735 void RenderLayerCompositor::repaintCompositedLayers(const IntRect* absRect)
1736 {
1737     recursiveRepaintLayer(rootRenderLayer(), absRect);
1738 }
1739
1740 void RenderLayerCompositor::recursiveRepaintLayer(RenderLayer& layer, const IntRect* rect)
1741 {
1742     // FIXME: This method does not work correctly with transforms.
1743     if (layer.isComposited() && !layer.backing()->paintsIntoCompositedAncestor()) {
1744         if (rect)
1745             layer.setBackingNeedsRepaintInRect(*rect);
1746         else
1747             layer.setBackingNeedsRepaint();
1748     }
1749
1750 #if !ASSERT_DISABLED
1751     LayerListMutationDetector mutationChecker(&layer);
1752 #endif
1753
1754     if (layer.hasCompositingDescendant()) {
1755         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1756             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i) {
1757                 RenderLayer& childLayer = *negZOrderList->at(i);
1758                 if (rect) {
1759                     IntRect childRect(*rect);
1760                     childLayer.convertToPixelSnappedLayerCoords(&layer, childRect);
1761                     recursiveRepaintLayer(childLayer, &childRect);
1762                 } else
1763                     recursiveRepaintLayer(childLayer);
1764             }
1765         }
1766
1767         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1768             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i) {
1769                 RenderLayer& childLayer = *posZOrderList->at(i);
1770                 if (rect) {
1771                     IntRect childRect(*rect);
1772                     childLayer.convertToPixelSnappedLayerCoords(&layer, childRect);
1773                     recursiveRepaintLayer(childLayer, &childRect);
1774                 } else
1775                     recursiveRepaintLayer(childLayer);
1776             }
1777         }
1778     }
1779     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1780         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i) {
1781             RenderLayer& childLayer = *normalFlowList->at(i);
1782             if (rect) {
1783                 IntRect childRect(*rect);
1784                 childLayer.convertToPixelSnappedLayerCoords(&layer, childRect);
1785                 recursiveRepaintLayer(childLayer, &childRect);
1786             } else
1787                 recursiveRepaintLayer(childLayer);
1788         }
1789     }
1790 }
1791
1792 RenderLayer& RenderLayerCompositor::rootRenderLayer() const
1793 {
1794     return *m_renderView.layer();
1795 }
1796
1797 GraphicsLayer* RenderLayerCompositor::rootGraphicsLayer() const
1798 {
1799     if (m_overflowControlsHostLayer)
1800         return m_overflowControlsHostLayer.get();
1801     return m_rootContentLayer.get();
1802 }
1803
1804 GraphicsLayer* RenderLayerCompositor::scrollLayer() const
1805 {
1806     return m_scrollLayer.get();
1807 }
1808
1809 #if ENABLE(RUBBER_BANDING)
1810 GraphicsLayer* RenderLayerCompositor::headerLayer() const
1811 {
1812     return m_layerForHeader.get();
1813 }
1814
1815 GraphicsLayer* RenderLayerCompositor::footerLayer() const
1816 {
1817     return m_layerForFooter.get();
1818 }
1819 #endif
1820
1821 TiledBacking* RenderLayerCompositor::pageTiledBacking() const
1822 {
1823     RenderLayerBacking* renderViewBacking = m_renderView.layer()->backing();
1824     return renderViewBacking ? renderViewBacking->tiledBacking() : nullptr;
1825 }
1826
1827 void RenderLayerCompositor::setIsInWindow(bool isInWindow)
1828 {
1829     if (TiledBacking* tiledBacking = pageTiledBacking())
1830         tiledBacking->setIsInWindow(isInWindow);
1831
1832     if (!inCompositingMode())
1833         return;
1834
1835     if (isInWindow) {
1836         if (m_rootLayerAttachment != RootLayerUnattached)
1837             return;
1838
1839         RootLayerAttachment attachment = shouldPropagateCompositingToEnclosingFrame() ? RootLayerAttachedViaEnclosingFrame : RootLayerAttachedViaChromeClient;
1840         attachRootLayer(attachment);
1841 #if PLATFORM(IOS)
1842         registerAllViewportConstrainedLayers();
1843         registerAllScrollingLayers();
1844 #endif
1845     } else {
1846         if (m_rootLayerAttachment == RootLayerUnattached)
1847             return;
1848
1849         detachRootLayer();
1850 #if PLATFORM(IOS)
1851         unregisterAllViewportConstrainedLayers();
1852         unregisterAllScrollingLayers();
1853 #endif
1854     }
1855 }
1856
1857 void RenderLayerCompositor::clearBackingForLayerIncludingDescendants(RenderLayer& layer)
1858 {
1859     if (layer.isComposited()) {
1860         removeFromScrollCoordinatedLayers(layer);
1861         layer.clearBacking();
1862     }
1863
1864     for (RenderLayer* childLayer = layer.firstChild(); childLayer; childLayer = childLayer->nextSibling())
1865         clearBackingForLayerIncludingDescendants(*childLayer);
1866 }
1867
1868 void RenderLayerCompositor::clearBackingForAllLayers()
1869 {
1870     clearBackingForLayerIncludingDescendants(*m_renderView.layer());
1871 }
1872
1873 void RenderLayerCompositor::updateRootLayerPosition()
1874 {
1875     if (m_rootContentLayer) {
1876         const IntRect& documentRect = m_renderView.documentRect();
1877         m_rootContentLayer->setSize(documentRect.size());        
1878         m_rootContentLayer->setPosition(FloatPoint(documentRect.x(), documentRect.y() + m_renderView.frameView().headerHeight()
1879             + m_renderView.frameView().topContentInset()));
1880     }
1881     if (m_clipLayer)
1882         m_clipLayer->setSize(m_renderView.frameView().unscaledTotalVisibleContentSize());
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().unscaledTotalVisibleContentSize());
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 = FrameScrollingNode;
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 FrameScrollingNode:
3504         case OverflowScrollingNode:
3505             break;
3506         }
3507         
3508         parentNodeID = nodeID;
3509     }
3510
3511     if (reasons & Scrolling) {
3512         ScrollingNodeID nodeID = backing->scrollingNodeID();
3513         if (!nodeID)
3514             nodeID = scrollingCoordinator->uniqueScrollLayerID();
3515
3516         nodeID = scrollingCoordinator->attachToStateTree(isRootLayer ? FrameScrollingNode : OverflowScrollingNode, nodeID, parentNodeID);
3517         backing->setScrollingNodeID(nodeID);
3518
3519         GraphicsLayer* scrollingLayer = backing->scrollingLayer();
3520         GraphicsLayer* scrolledContentsLayer = backing->scrollingContentsLayer();
3521         GraphicsLayer* counterScrollingLayer = nullptr;
3522
3523         if (isRootLayer) {
3524             scrollingLayer = m_scrollLayer.get();
3525             scrolledContentsLayer = nullptr;
3526             counterScrollingLayer = fixedRootBackgroundLayer();
3527             scrollingCoordinator->updateScrollingNode(nodeID, scrollingLayer, scrolledContentsLayer, counterScrollingLayer);
3528         } else {
3529             ScrollingCoordinator::ScrollingGeometry scrollingGeometry;
3530             scrollingGeometry.scrollOrigin = layer.scrollOrigin();
3531             scrollingGeometry.scrollPosition = layer.scrollPosition();
3532             scrollingGeometry.contentSize = layer.contentsSize();
3533             scrollingCoordinator->updateScrollingNode(nodeID, scrollingLayer, scrolledContentsLayer, counterScrollingLayer, &scrollingGeometry);
3534         }
3535     }
3536 }
3537
3538 void RenderLayerCompositor::detachScrollCoordinatedLayer(RenderLayer& layer)
3539 {
3540     if (RenderLayerBacking* backing = layer.backing())
3541         backing->detachFromScrollingCoordinator();
3542 }
3543
3544 #if PLATFORM(IOS)
3545 typedef HashMap<PlatformLayer*, OwnPtr<ViewportConstraints>> LayerMap;
3546 typedef HashMap<PlatformLayer*, PlatformLayer*> StickyContainerMap;
3547
3548 void RenderLayerCompositor::registerAllViewportConstrainedLayers()
3549 {
3550     // Only the main frame should register fixed/sticky layers.
3551     if (m_renderView.document().ownerElement())
3552         return;
3553
3554     if (scrollingCoordinator())
3555         return;
3556
3557     LayerMap layerMap;
3558     StickyContainerMap stickyContainerMap;
3559
3560     for (auto it = m_scrollCoordinatedLayers.begin(), end = m_scrollCoordinatedLayers.end(); it != end; ++it) {
3561         RenderLayer& layer = **it;
3562         ASSERT(layer.isComposited());
3563
3564         std::unique_ptr<ViewportConstraints> constraints;
3565         if (layer.renderer().isStickyPositioned()) {
3566             constraints = std::make_unique<StickyPositionViewportConstraints>(computeStickyViewportConstraints(layer));
3567             const RenderLayer* enclosingTouchScrollableLayer = nullptr;
3568             if (isStickyInAcceleratedScrollingLayerOrViewport(layer, &enclosingTouchScrollableLayer) && enclosingTouchScrollableLayer) {
3569                 ASSERT(enclosingTouchScrollableLayer->isComposited());
3570                 stickyContainerMap.add(layer.backing()->graphicsLayer()->platformLayer(), enclosingTouchScrollableLayer->backing()->scrollingLayer()->platformLayer());
3571             }
3572         } else if (layer.renderer().style().position() == FixedPosition)
3573             constraints = std::make_unique<FixedPositionViewportConstraints>(computeFixedViewportConstraints(layer));
3574         else
3575             continue;
3576
3577         layerMap.add(layer.backing()->graphicsLayer()->platformLayer(), adoptPtr(constraints.release()));
3578     }
3579     
3580     if (ChromeClient* client = this->chromeClient())
3581         client->updateViewportConstrainedLayers(layerMap, stickyContainerMap);
3582 }
3583
3584 void RenderLayerCompositor::unregisterAllViewportConstrainedLayers()
3585 {
3586     // Only the main frame should register fixed/sticky layers.
3587     if (m_renderView.document().ownerElement())
3588         return;
3589
3590     if (scrollingCoordinator())
3591         return;
3592
3593     if (ChromeClient* client = this->chromeClient()) {
3594         LayerMap layerMap;
3595         StickyContainerMap stickyContainerMap;
3596         client->updateViewportConstrainedLayers(layerMap, stickyContainerMap);
3597     }
3598 }
3599
3600 void RenderLayerCompositor::registerAllScrollingLayers()
3601 {
3602     ChromeClient* client = this->chromeClient();
3603     if (!client)
3604         return;
3605
3606     for (auto it = m_scrollingLayers.begin(), end = m_scrollingLayers.end(); it != end; ++it)
3607         updateScrollingLayerWithClient(**it, client);
3608 }
3609
3610 void RenderLayerCompositor::unregisterAllScrollingLayers()
3611 {
3612     ChromeClient* client = this->chromeClient();
3613     if (!client)
3614         return;
3615
3616     for (auto it = m_scrollingLayers.begin(), end = m_scrollingLayers.end(); it != end; ++it) {
3617         RenderLayer& layer = **it;
3618         RenderLayerBacking* backing = layer.backing();
3619         ASSERT(backing);
3620         client->removeScrollingLayer(layer.renderer().element(), backing->scrollingLayer()->platformLayer(), backing->scrollingContentsLayer()->platformLayer());
3621     }
3622 }
3623 #endif
3624
3625 void RenderLayerCompositor::willRemoveScrollingLayer(RenderLayer& layer)
3626 {
3627     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator()) {
3628         RenderLayerBacking* backing = layer.backing();
3629     
3630         if (backing)
3631             scrollingCoordinator->detachFromStateTree(backing->scrollingNodeID());
3632
3633         // For Coordinated Graphics.
3634         scrollingCoordinator->scrollableAreaScrollLayerDidChange(&layer);
3635         return;
3636     }
3637
3638 #if PLATFORM(IOS)
3639     m_scrollingLayersNeedingUpdate.remove(&layer);
3640     m_scrollingLayers.remove(&layer);
3641
3642     if (m_renderView.document().inPageCache() || !layer.backing())
3643         return;
3644
3645     if (ChromeClient* client = this->chromeClient()) {
3646         PlatformLayer* scrollingLayer = layer.backing()->scrollingLayer()->platformLayer();
3647         PlatformLayer* contentsLayer = layer.backing()->scrollingContentsLayer()->platformLayer();
3648         client->removeScrollingLayer(layer.renderer().element(), scrollingLayer, contentsLayer);
3649     }
3650 #endif
3651 }
3652
3653 void RenderLayerCompositor::didAddScrollingLayer(RenderLayer& layer)
3654 {
3655     updateScrollCoordinatedStatus(layer);
3656
3657     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator()) {
3658         // For Coordinated Graphics.
3659         scrollingCoordinator->scrollableAreaScrollLayerDidChange(&layer);
3660         return;
3661     }
3662
3663 #if PLATFORM(IOS)
3664     ASSERT(!m_renderView.document().inPageCache());
3665     m_scrollingLayers.add(&layer);
3666 #endif
3667 }
3668
3669 void RenderLayerCompositor::windowScreenDidChange(PlatformDisplayID displayID)
3670 {
3671     if (m_layerUpdater)
3672         m_layerUpdater->screenDidChange(displayID);
3673 }
3674
3675 ScrollingCoordinator* RenderLayerCompositor::scrollingCoordinator() const
3676 {
3677     if (Page* page = this->page())
3678         return page->scrollingCoordinator();
3679
3680     return 0;
3681 }
3682
3683 GraphicsLayerFactory* RenderLayerCompositor::graphicsLayerFactory() const
3684 {
3685     if (Page* page = this->page())
3686         return page->chrome().client().graphicsLayerFactory();
3687
3688     return 0;
3689 }
3690
3691 Page* RenderLayerCompositor::page() const
3692 {
3693     return m_renderView.frameView().frame().page();
3694 }
3695
3696 void RenderLayerCompositor::setLayerFlushThrottlingEnabled(bool enabled)
3697 {
3698     m_layerFlushThrottlingEnabled = enabled;
3699     if (m_layerFlushThrottlingEnabled)
3700         return;
3701     m_layerFlushTimer.stop();
3702     if (!m_hasPendingLayerFlush)
3703         return;
3704     scheduleLayerFlushNow();
3705 }
3706
3707 void RenderLayerCompositor::disableLayerFlushThrottlingTemporarilyForInteraction()
3708 {
3709     if (m_layerFlushThrottlingTemporarilyDisabledForInteraction)
3710         return;
3711     m_layerFlushThrottlingTemporarilyDisabledForInteraction = true;
3712 }
3713
3714 bool RenderLayerCompositor::isThrottlingLayerFlushes() const
3715 {
3716     if (!m_layerFlushThrottlingEnabled)
3717         return false;
3718     if (!m_layerFlushTimer.isActive())
3719         return false;
3720     if (m_layerFlushThrottlingTemporarilyDisabledForInteraction)
3721         return false;
3722     return true;
3723 }
3724
3725 void RenderLayerCompositor::startLayerFlushTimerIfNeeded()
3726 {
3727     m_layerFlushThrottlingTemporarilyDisabledForInteraction = false;
3728     m_layerFlushTimer.stop();
3729     if (!m_layerFlushThrottlingEnabled)
3730         return;
3731     m_layerFlushTimer.startOneShot(throttledLayerFlushDelay);
3732 }
3733
3734 void RenderLayerCompositor::startInitialLayerFlushTimerIfNeeded()
3735 {
3736     if (!m_layerFlushThrottlingEnabled)
3737         return;
3738     if (m_layerFlushTimer.isActive())
3739         return;
3740     m_layerFlushTimer.startOneShot(throttledLayerFlushInitialDelay);
3741 }
3742
3743 void RenderLayerCompositor::layerFlushTimerFired(Timer<RenderLayerCompositor>&)
3744 {
3745     if (!m_hasPendingLayerFlush)
3746         return;
3747     scheduleLayerFlushNow();
3748 }
3749
3750 void RenderLayerCompositor::paintRelatedMilestonesTimerFired(Timer<RenderLayerCompositor>&)
3751 {
3752     Frame& frame = m_renderView.frameView().frame();
3753     Page* page = frame.page();
3754     if (!page)
3755         return;
3756
3757     // If the layer tree is frozen, we'll paint when it's unfrozen and schedule the timer again.
3758     if (page->chrome().client().layerTreeStateIsFrozen())
3759         return;
3760
3761     m_renderView.frameView().firePaintRelatedMilestonesIfNeeded();
3762 }
3763
3764 } // namespace WebCore