034dbce22f125987b2b7f5104c785accd4e8cad0
[WebKit-https.git] / Source / WebCore / rendering / RenderLayerBacking.cpp
1 /*
2  * Copyright (C) 2009, 2010, 2011 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 "RenderLayerBacking.h"
29
30 #include "AnimationController.h"
31 #include "CanvasRenderingContext.h"
32 #include "CSSPropertyNames.h"
33 #include "CachedImage.h"
34 #include "Chrome.h"
35 #include "FilterEffectRenderer.h"
36 #include "FontCache.h"
37 #include "FrameView.h"
38 #include "GraphicsContext.h"
39 #include "GraphicsLayer.h"
40 #include "HTMLCanvasElement.h"
41 #include "HTMLIFrameElement.h"
42 #include "HTMLMediaElement.h"
43 #include "HTMLNames.h"
44 #include "HTMLPlugInElement.h"
45 #include "InspectorInstrumentation.h"
46 #include "KeyframeList.h"
47 #include "MainFrame.h"
48 #include "PluginViewBase.h"
49 #include "ProgressTracker.h"
50 #include "RenderFlowThread.h"
51 #include "RenderIFrame.h"
52 #include "RenderImage.h"
53 #include "RenderLayerCompositor.h"
54 #include "RenderEmbeddedObject.h"
55 #include "RenderNamedFlowFragment.h"
56 #include "RenderRegion.h"
57 #include "RenderVideo.h"
58 #include "RenderView.h"
59 #include "ScrollingCoordinator.h"
60 #include "Settings.h"
61 #include "StyleResolver.h"
62 #include "TiledBacking.h"
63 #include <wtf/text/StringBuilder.h>
64
65 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
66 #include "GraphicsContext3D.h"
67 #endif
68
69 namespace WebCore {
70
71 using namespace HTMLNames;
72
73 CanvasCompositingStrategy canvasCompositingStrategy(const RenderObject& renderer)
74 {
75     ASSERT(renderer.isCanvas());
76     
77     const HTMLCanvasElement* canvas = downcast<HTMLCanvasElement>(renderer.node());
78     CanvasRenderingContext* context = canvas->renderingContext();
79     if (!context || !context->isAccelerated())
80         return UnacceleratedCanvas;
81     
82     if (context->is3d())
83         return CanvasAsLayerContents;
84
85 #if ENABLE(ACCELERATED_2D_CANVAS)
86     return CanvasAsLayerContents;
87 #else
88     return CanvasPaintedToLayer; // On Mac and iOS we paint accelerated canvases into their layers.
89 #endif
90 }
91
92 // Get the scrolling coordinator in a way that works inside RenderLayerBacking's destructor.
93 static ScrollingCoordinator* scrollingCoordinatorFromLayer(RenderLayer& layer)
94 {
95     Page* page = layer.renderer().frame().page();
96     if (!page)
97         return 0;
98
99     return page->scrollingCoordinator();
100 }
101
102 bool RenderLayerBacking::m_creatingPrimaryGraphicsLayer = false;
103
104 RenderLayerBacking::RenderLayerBacking(RenderLayer& layer)
105     : m_owningLayer(layer)
106     , m_viewportConstrainedNodeID(0)
107     , m_scrollingNodeID(0)
108     , m_artificiallyInflatedBounds(false)
109     , m_isMainFrameRenderViewLayer(false)
110     , m_usingTiledCacheLayer(false)
111     , m_requiresOwnBackingStore(true)
112     , m_canCompositeFilters(false)
113     , m_backgroundLayerPaintsFixedRootBackground(false)
114 {
115     Page* page = renderer().frame().page();
116
117     if (layer.isRootLayer() && page) {
118         m_isMainFrameRenderViewLayer = renderer().frame().isMainFrame();
119         m_usingTiledCacheLayer = page->chrome().client().shouldUseTiledBackingForFrameView(renderer().frame().view());
120     }
121     
122     createPrimaryGraphicsLayer();
123
124     if (m_usingTiledCacheLayer && page) {
125         TiledBacking* tiledBacking = this->tiledBacking();
126
127         tiledBacking->setIsInWindow(page->isInWindow());
128
129         if (m_isMainFrameRenderViewLayer)
130             tiledBacking->setUnparentsOffscreenTiles(true);
131
132         tiledBacking->setScrollingPerformanceLoggingEnabled(page->settings().scrollingPerformanceLoggingEnabled());
133         adjustTiledBackingCoverage();
134     }
135 }
136
137 RenderLayerBacking::~RenderLayerBacking()
138 {
139     updateAncestorClippingLayer(false);
140     updateDescendantClippingLayer(false);
141     updateOverflowControlsLayers(false, false, false);
142     updateForegroundLayer(false);
143     updateBackgroundLayer(false);
144     updateMaskLayer(false);
145     updateScrollingLayers(false);
146     detachFromScrollingCoordinator();
147     destroyGraphicsLayers();
148 }
149
150 void RenderLayerBacking::willDestroyLayer(const GraphicsLayer* layer)
151 {
152     if (layer && layer->usingTiledBacking())
153         compositor().layerTiledBackingUsageChanged(layer, false);
154 }
155
156 std::unique_ptr<GraphicsLayer> RenderLayerBacking::createGraphicsLayer(const String& name)
157 {
158     GraphicsLayerFactory* graphicsLayerFactory = 0;
159     if (Page* page = renderer().frame().page())
160         graphicsLayerFactory = page->chrome().client().graphicsLayerFactory();
161
162     std::unique_ptr<GraphicsLayer> graphicsLayer = GraphicsLayer::create(graphicsLayerFactory, *this);
163
164 #ifndef NDEBUG
165     graphicsLayer->setName(name);
166 #else
167     UNUSED_PARAM(name);
168 #endif
169 #if PLATFORM(COCOA) && USE(CA)
170     graphicsLayer->setAcceleratesDrawing(compositor().acceleratedDrawingEnabled());
171 #endif    
172     
173     return graphicsLayer;
174 }
175
176 bool RenderLayerBacking::shouldUseTiledBacking(const GraphicsLayer*) const
177 {
178     return m_usingTiledCacheLayer && m_creatingPrimaryGraphicsLayer;
179 }
180
181 void RenderLayerBacking::tiledBackingUsageChanged(const GraphicsLayer* layer, bool usingTiledBacking)
182 {
183     compositor().layerTiledBackingUsageChanged(layer, usingTiledBacking);
184 }
185
186 TiledBacking* RenderLayerBacking::tiledBacking() const
187 {
188     return m_graphicsLayer->tiledBacking();
189 }
190
191 static TiledBacking::TileCoverage computeTileCoverage(RenderLayerBacking* backing)
192 {
193     // FIXME: When we use TiledBacking for overflow, this should look at RenderView scrollability.
194     FrameView& frameView = backing->owningLayer().renderer().view().frameView();
195
196     TiledBacking::TileCoverage tileCoverage = TiledBacking::CoverageForVisibleArea;
197     bool useMinimalTilesDuringLiveResize = frameView.inLiveResize();
198     if (frameView.speculativeTilingEnabled() && !useMinimalTilesDuringLiveResize) {
199         bool clipsToExposedRect = !frameView.exposedRect().isInfinite();
200         if (frameView.horizontalScrollbarMode() != ScrollbarAlwaysOff || clipsToExposedRect)
201             tileCoverage |= TiledBacking::CoverageForHorizontalScrolling;
202
203         if (frameView.verticalScrollbarMode() != ScrollbarAlwaysOff || clipsToExposedRect)
204             tileCoverage |= TiledBacking::CoverageForVerticalScrolling;
205     }
206     return tileCoverage;
207 }
208
209 void RenderLayerBacking::adjustTiledBackingCoverage()
210 {
211     if (!m_usingTiledCacheLayer)
212         return;
213
214     TiledBacking::TileCoverage tileCoverage = computeTileCoverage(this);
215     tiledBacking()->setTileCoverage(tileCoverage);
216 }
217
218 void RenderLayerBacking::setTiledBackingHasMargins(bool hasExtendedBackgroundOnLeftAndRight, bool hasExtendedBackgroundOnTopAndBottom)
219 {
220     if (!m_usingTiledCacheLayer)
221         return;
222
223     int marginLeftAndRightSize = hasExtendedBackgroundOnLeftAndRight ? defaultTileWidth : 0;
224     int marginTopAndBottomSize = hasExtendedBackgroundOnTopAndBottom ? defaultTileHeight : 0;
225     tiledBacking()->setTileMargins(marginTopAndBottomSize, marginTopAndBottomSize, marginLeftAndRightSize, marginLeftAndRightSize);
226 }
227
228 void RenderLayerBacking::updateDebugIndicators(bool showBorder, bool showRepaintCounter)
229 {
230     m_graphicsLayer->setShowDebugBorder(showBorder);
231     m_graphicsLayer->setShowRepaintCounter(showRepaintCounter);
232     
233     if (m_ancestorClippingLayer)
234         m_ancestorClippingLayer->setShowDebugBorder(showBorder);
235
236     if (m_foregroundLayer) {
237         m_foregroundLayer->setShowDebugBorder(showBorder);
238         m_foregroundLayer->setShowRepaintCounter(showRepaintCounter);
239     }
240     
241     if (m_contentsContainmentLayer)
242         m_contentsContainmentLayer->setShowDebugBorder(showBorder);
243     
244     if (m_backgroundLayer) {
245         m_backgroundLayer->setShowDebugBorder(showBorder);
246         m_backgroundLayer->setShowRepaintCounter(showRepaintCounter);
247     }
248
249     if (m_maskLayer) {
250         m_maskLayer->setShowDebugBorder(showBorder);
251         m_maskLayer->setShowRepaintCounter(showRepaintCounter);
252     }
253
254     if (m_layerForHorizontalScrollbar)
255         m_layerForHorizontalScrollbar->setShowDebugBorder(showBorder);
256
257     if (m_layerForVerticalScrollbar)
258         m_layerForVerticalScrollbar->setShowDebugBorder(showBorder);
259
260     if (m_layerForScrollCorner)
261         m_layerForScrollCorner->setShowDebugBorder(showBorder);
262
263     if (m_scrollingLayer)
264         m_scrollingLayer->setShowDebugBorder(showBorder);
265
266     if (m_scrollingContentsLayer) {
267         m_scrollingContentsLayer->setShowDebugBorder(showBorder);
268         m_scrollingContentsLayer->setShowRepaintCounter(showRepaintCounter);
269     }
270 }
271
272 void RenderLayerBacking::createPrimaryGraphicsLayer()
273 {
274     String layerName;
275 #ifndef NDEBUG
276     layerName = m_owningLayer.name();
277 #endif
278     
279     // The call to createGraphicsLayer ends calling back into here as
280     // a GraphicsLayerClient to ask if it shouldUseTiledBacking(). We only want
281     // the tile cache on our main layer. This is pretty ugly, but saves us from
282     // exposing the API to all clients.
283
284     m_creatingPrimaryGraphicsLayer = true;
285     m_graphicsLayer = createGraphicsLayer(layerName);
286     m_creatingPrimaryGraphicsLayer = false;
287
288     if (m_usingTiledCacheLayer) {
289         m_childContainmentLayer = createGraphicsLayer("TiledBacking Flattening Layer");
290         m_graphicsLayer->addChild(m_childContainmentLayer.get());
291     }
292
293 #if !PLATFORM(IOS)
294     if (m_isMainFrameRenderViewLayer) {
295         // Page scale is applied above the RenderView on iOS.
296         m_graphicsLayer->setContentsOpaque(true);
297         m_graphicsLayer->setAppliesPageScale();
298     }
299 #endif
300
301 #if PLATFORM(COCOA) && USE(CA)
302     if (!compositor().acceleratedDrawingEnabled() && renderer().isCanvas()) {
303         const HTMLCanvasElement* canvas = downcast<HTMLCanvasElement>(renderer().element());
304         if (canvas->shouldAccelerate(canvas->size()))
305             m_graphicsLayer->setAcceleratesDrawing(true);
306     }
307 #endif    
308     
309     updateOpacity(renderer().style());
310     updateTransform(renderer().style());
311     updateFilters(renderer().style());
312 #if ENABLE(CSS_COMPOSITING)
313     updateBlendMode(renderer().style());
314 #endif
315 }
316
317 #if PLATFORM(IOS)
318 void RenderLayerBacking::layerWillBeDestroyed()
319 {
320     RenderObject& renderer = this->renderer();
321     if (is<RenderEmbeddedObject>(renderer) && downcast<RenderEmbeddedObject>(renderer).allowsAcceleratedCompositing()) {
322         PluginViewBase* pluginViewBase = downcast<PluginViewBase>(downcast<RenderWidget>(renderer).widget());
323         if (pluginViewBase && m_graphicsLayer->contentsLayerForMedia())
324             pluginViewBase->detachPluginLayer();
325     }
326 }
327 #endif
328
329 void RenderLayerBacking::destroyGraphicsLayers()
330 {
331     if (m_graphicsLayer) {
332         willDestroyLayer(m_graphicsLayer.get());
333         m_graphicsLayer->removeFromParent();
334     }
335
336     m_ancestorClippingLayer = nullptr;
337     m_contentsContainmentLayer = nullptr;
338     m_graphicsLayer = nullptr;
339     m_foregroundLayer = nullptr;
340     m_backgroundLayer = nullptr;
341     m_childContainmentLayer = nullptr;
342     m_maskLayer = nullptr;
343
344     m_scrollingLayer = nullptr;
345     m_scrollingContentsLayer = nullptr;
346 }
347
348 void RenderLayerBacking::updateOpacity(const RenderStyle& style)
349 {
350     m_graphicsLayer->setOpacity(compositingOpacity(style.opacity()));
351 }
352
353 void RenderLayerBacking::updateTransform(const RenderStyle& style)
354 {
355     // FIXME: This could use m_owningLayer.transform(), but that currently has transform-origin
356     // baked into it, and we don't want that.
357     TransformationMatrix t;
358     if (m_owningLayer.hasTransform()) {
359         auto& renderBox = downcast<RenderBox>(renderer());
360         style.applyTransform(t, snapRectToDevicePixels(renderBox.borderBoxRect(), deviceScaleFactor()), RenderStyle::ExcludeTransformOrigin);
361         makeMatrixRenderable(t, compositor().canRender3DTransforms());
362     }
363     
364     if (m_contentsContainmentLayer) {
365         m_contentsContainmentLayer->setTransform(t);
366         m_graphicsLayer->setTransform(TransformationMatrix());
367     } else
368         m_graphicsLayer->setTransform(t);
369 }
370
371 void RenderLayerBacking::updateFilters(const RenderStyle& style)
372 {
373     m_canCompositeFilters = m_graphicsLayer->setFilters(style.filter());
374 }
375
376 #if ENABLE(CSS_COMPOSITING)
377 void RenderLayerBacking::updateBlendMode(const RenderStyle& style)
378 {
379     // FIXME: where is the blend mode updated when m_ancestorClippingLayers come and go?
380     if (m_ancestorClippingLayer) {
381         m_ancestorClippingLayer->setBlendMode(style.blendMode());
382         m_graphicsLayer->setBlendMode(BlendModeNormal);
383     } else
384         m_graphicsLayer->setBlendMode(style.blendMode());
385 }
386 #endif
387
388 // FIXME: the hasAcceleratedTouchScrolling()/needsCompositedScrolling() concepts need to be merged.
389 static bool layerOrAncestorIsTransformedOrUsingCompositedScrolling(RenderLayer& layer)
390 {
391     for (RenderLayer* curr = &layer; curr; curr = curr->parent()) {
392         if (curr->hasTransform()
393 #if PLATFORM(IOS)
394             || curr->hasTouchScrollableOverflow()
395 #else
396             || curr->needsCompositedScrolling()
397 #endif
398             )
399             return true;
400     }
401
402     return false;
403 }
404
405 bool RenderLayerBacking::shouldClipCompositedBounds() const
406 {
407 #if !PLATFORM(IOS)
408     // Scrollbar layers use this layer for relative positioning, so don't clip.
409     if (layerForHorizontalScrollbar() || layerForVerticalScrollbar())
410         return false;
411 #endif
412
413     if (m_usingTiledCacheLayer)
414         return false;
415
416     if (layerOrAncestorIsTransformedOrUsingCompositedScrolling(m_owningLayer))
417         return false;
418
419     if (m_owningLayer.isFlowThreadCollectingGraphicsLayersUnderRegions())
420         return false;
421
422     return true;
423 }
424
425 static bool hasNonZeroTransformOrigin(const RenderObject& renderer)
426 {
427     const RenderStyle& style = renderer.style();
428     return (style.transformOriginX().type() == Fixed && style.transformOriginX().value())
429         || (style.transformOriginY().type() == Fixed && style.transformOriginY().value());
430 }
431
432 void RenderLayerBacking::updateCompositedBounds()
433 {
434     LayoutRect layerBounds = m_owningLayer.calculateLayerBounds(&m_owningLayer, LayoutSize(), RenderLayer::DefaultCalculateLayerBoundsFlags | RenderLayer::ExcludeHiddenDescendants | RenderLayer::DontConstrainForMask);
435     // Clip to the size of the document or enclosing overflow-scroll layer.
436     // If this or an ancestor is transformed, we can't currently compute the correct rect to intersect with.
437     // We'd need RenderObject::convertContainerToLocalQuad(), which doesn't yet exist.
438     if (shouldClipCompositedBounds()) {
439         RenderView& view = renderer().view();
440         RenderLayer* rootLayer = view.layer();
441
442         LayoutRect clippingBounds;
443         if (renderer().style().position() == FixedPosition && renderer().container() == &view)
444             clippingBounds = view.frameView().viewportConstrainedVisibleContentRect();
445         else
446             clippingBounds = view.unscaledDocumentRect();
447
448         if (&m_owningLayer != rootLayer)
449             clippingBounds.intersect(m_owningLayer.backgroundClipRect(RenderLayer::ClipRectsContext(rootLayer, AbsoluteClipRects)).rect()); // FIXME: Incorrect for CSS regions.
450
451         LayoutPoint delta = m_owningLayer.convertToLayerCoords(rootLayer, LayoutPoint(), RenderLayer::AdjustForColumns);
452         clippingBounds.move(-delta.x(), -delta.y());
453
454         layerBounds.intersect(clippingBounds);
455     }
456     
457     // If the element has a transform-origin that has fixed lengths, and the renderer has zero size,
458     // then we need to ensure that the compositing layer has non-zero size so that we can apply
459     // the transform-origin via the GraphicsLayer anchorPoint (which is expressed as a fractional value).
460     if (layerBounds.isEmpty() && hasNonZeroTransformOrigin(renderer())) {
461         layerBounds.setWidth(1);
462         layerBounds.setHeight(1);
463         m_artificiallyInflatedBounds = true;
464     } else
465         m_artificiallyInflatedBounds = false;
466
467     setCompositedBounds(layerBounds);
468 }
469
470 void RenderLayerBacking::updateAfterWidgetResize()
471 {
472     if (!renderer().isWidget())
473         return;
474     if (RenderLayerCompositor* innerCompositor = RenderLayerCompositor::frameContentsCompositor(toRenderWidget(&renderer()))) {
475         innerCompositor->frameViewDidChangeSize();
476         innerCompositor->frameViewDidChangeLocation(flooredIntPoint(contentsBox().location()));
477     }
478 }
479
480 void RenderLayerBacking::updateAfterLayout(UpdateAfterLayoutFlags flags)
481 {
482     if (!compositor().compositingLayersNeedRebuild()) {
483         // Calling updateGeometry() here gives incorrect results, because the
484         // position of this layer's GraphicsLayer depends on the position of our compositing
485         // ancestor's GraphicsLayer. That cannot be determined until all the descendant 
486         // RenderLayers of that ancestor have been processed via updateLayerPositions().
487         //
488         // The solution is to update compositing children of this layer here,
489         // via updateCompositingChildrenGeometry().
490         updateCompositedBounds();
491         compositor().updateCompositingDescendantGeometry(m_owningLayer, m_owningLayer, flags & CompositingChildrenOnly);
492         
493         if (flags & IsUpdateRoot) {
494             updateGeometry();
495             compositor().updateRootLayerPosition();
496             RenderLayer* stackingContainer = m_owningLayer.enclosingStackingContainer();
497             if (!compositor().compositingLayersNeedRebuild() && stackingContainer && (stackingContainer != &m_owningLayer))
498                 compositor().updateCompositingDescendantGeometry(*stackingContainer, *stackingContainer, flags & CompositingChildrenOnly);
499         }
500     }
501     
502     if (flags & NeedsFullRepaint && !paintsIntoWindow() && !paintsIntoCompositedAncestor())
503         setContentsNeedDisplay();
504 }
505
506 bool RenderLayerBacking::updateConfiguration()
507 {
508     m_owningLayer.updateDescendantDependentFlags();
509     m_owningLayer.updateZOrderLists();
510
511     bool layerConfigChanged = false;
512     setBackgroundLayerPaintsFixedRootBackground(compositor().needsFixedRootBackgroundLayer(m_owningLayer));
513     
514     // The background layer is currently only used for fixed root backgrounds.
515     if (updateBackgroundLayer(m_backgroundLayerPaintsFixedRootBackground))
516         layerConfigChanged = true;
517
518     if (updateForegroundLayer(compositor().needsContentsCompositingLayer(m_owningLayer)))
519         layerConfigChanged = true;
520     
521     bool needsDescendentsClippingLayer = compositor().clipsCompositingDescendants(m_owningLayer);
522
523     if (!renderer().view().needsLayout()) {
524         bool usesCompositedScrolling;
525 #if PLATFORM(IOS)
526         usesCompositedScrolling = m_owningLayer.hasTouchScrollableOverflow();
527 #else
528         usesCompositedScrolling = m_owningLayer.needsCompositedScrolling();
529 #endif
530         // Our scrolling layer will clip.
531         if (usesCompositedScrolling)
532             needsDescendentsClippingLayer = false;
533
534         if (updateScrollingLayers(usesCompositedScrolling))
535             layerConfigChanged = true;
536
537         if (updateDescendantClippingLayer(needsDescendentsClippingLayer))
538             layerConfigChanged = true;
539     }
540
541     if (updateAncestorClippingLayer(compositor().clippedByAncestor(m_owningLayer)))
542         layerConfigChanged = true;
543
544     if (updateOverflowControlsLayers(requiresHorizontalScrollbarLayer(), requiresVerticalScrollbarLayer(), requiresScrollCornerLayer()))
545         layerConfigChanged = true;
546
547     if (layerConfigChanged)
548         updateInternalHierarchy();
549
550     if (GraphicsLayer* flatteningLayer = tileCacheFlatteningLayer()) {
551         if (layerConfigChanged || flatteningLayer->parent() != m_graphicsLayer.get())
552             m_graphicsLayer->addChild(flatteningLayer);
553     }
554
555     updateMaskLayer(renderer().hasMask());
556
557     if (m_owningLayer.hasReflection()) {
558         if (m_owningLayer.reflectionLayer()->backing()) {
559             GraphicsLayer* reflectionLayer = m_owningLayer.reflectionLayer()->backing()->graphicsLayer();
560             m_graphicsLayer->setReplicatedByLayer(reflectionLayer);
561         }
562     } else
563         m_graphicsLayer->setReplicatedByLayer(0);
564
565     if (!m_owningLayer.isRootLayer()) {
566         bool isSimpleContainer = isSimpleContainerCompositingLayer();
567         bool didUpdateContentsRect = false;
568         updateDirectlyCompositedContents(isSimpleContainer, didUpdateContentsRect);
569     } else
570         updateRootLayerConfiguration();
571     
572     if (isDirectlyCompositedImage())
573         updateImageContents();
574
575     if (is<RenderEmbeddedObject>(renderer()) && downcast<RenderEmbeddedObject>(renderer()).allowsAcceleratedCompositing()) {
576         PluginViewBase* pluginViewBase = downcast<PluginViewBase>(downcast<RenderWidget>(renderer()).widget());
577 #if PLATFORM(IOS)
578         if (pluginViewBase && !m_graphicsLayer->contentsLayerForMedia()) {
579             pluginViewBase->detachPluginLayer();
580             pluginViewBase->attachPluginLayer();
581         }
582 #else
583         if (!pluginViewBase->shouldNotAddLayer())
584             m_graphicsLayer->setContentsToPlatformLayer(pluginViewBase->platformLayer(), GraphicsLayer::ContentsLayerForPlugin);
585 #endif
586     }
587 #if ENABLE(VIDEO)
588     else if (renderer().isVideo()) {
589         HTMLMediaElement* mediaElement = downcast<HTMLMediaElement>(renderer().element());
590         m_graphicsLayer->setContentsToPlatformLayer(mediaElement->platformLayer(), GraphicsLayer::ContentsLayerForMedia);
591     }
592 #endif
593 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
594     else if (renderer().isCanvas() && canvasCompositingStrategy(renderer()) == CanvasAsLayerContents) {
595         const HTMLCanvasElement* canvas = downcast<HTMLCanvasElement>(renderer().element());
596         if (CanvasRenderingContext* context = canvas->renderingContext())
597             m_graphicsLayer->setContentsToPlatformLayer(context->platformLayer(), GraphicsLayer::ContentsLayerForCanvas);
598         layerConfigChanged = true;
599     }
600 #endif
601     if (renderer().isWidget())
602         layerConfigChanged = RenderLayerCompositor::parentFrameContentLayers(toRenderWidget(&renderer()));
603
604     return layerConfigChanged;
605 }
606
607 static LayoutRect clipBox(RenderBox& renderer)
608 {
609     LayoutRect result = LayoutRect::infiniteRect();
610     if (renderer.hasOverflowClip())
611         result = renderer.overflowClipRect(LayoutPoint(), 0); // FIXME: Incorrect for CSS regions.
612
613     if (renderer.hasClip())
614         result.intersect(renderer.clipRect(LayoutPoint(), 0)); // FIXME: Incorrect for CSS regions.
615
616     return result;
617 }
618
619 static FloatSize pixelFractionForLayerPainting(const LayoutPoint& point, float pixelSnappingFactor)
620 {
621     LayoutUnit x = point.x();
622     LayoutUnit y = point.y();
623     x = x >= 0 ? floorToDevicePixel(x, pixelSnappingFactor) : ceilToDevicePixel(x, pixelSnappingFactor);
624     y = y >= 0 ? floorToDevicePixel(y, pixelSnappingFactor) : ceilToDevicePixel(y, pixelSnappingFactor);
625     return point - LayoutPoint(x, y);
626 }
627
628 static void calculateDevicePixelOffsetFromRenderer(const LayoutSize& rendererOffsetFromGraphicsLayer, FloatSize& devicePixelOffsetFromRenderer,
629     LayoutSize& devicePixelFractionFromRenderer, float deviceScaleFactor)
630 {
631     devicePixelFractionFromRenderer = LayoutSize(pixelFractionForLayerPainting(toLayoutPoint(rendererOffsetFromGraphicsLayer), deviceScaleFactor));
632     devicePixelOffsetFromRenderer = rendererOffsetFromGraphicsLayer - devicePixelFractionFromRenderer;
633 }
634
635 void RenderLayerBacking::updateGeometry()
636 {
637     // If we haven't built z-order lists yet, wait until later.
638     if (m_owningLayer.isStackingContainer() && m_owningLayer.m_zOrderListsDirty)
639         return;
640
641     const RenderStyle& style = renderer().style();
642
643     // Set transform property, if it is not animating. We have to do this here because the transform
644     // is affected by the layer dimensions.
645     if (!renderer().animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyWebkitTransform, AnimationBase::Running | AnimationBase::Paused | AnimationBase::FillingFowards))
646         updateTransform(style);
647
648     // Set opacity, if it is not animating.
649     if (!renderer().animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyOpacity, AnimationBase::Running | AnimationBase::Paused | AnimationBase::FillingFowards))
650         updateOpacity(style);
651
652     updateFilters(style);
653
654 #if ENABLE(CSS_COMPOSITING)
655     updateBlendMode(style);
656 #endif
657
658     m_owningLayer.updateDescendantDependentFlags();
659
660     // FIXME: reflections should force transform-style to be flat in the style: https://bugs.webkit.org/show_bug.cgi?id=106959
661     bool preserves3D = style.transformStyle3D() == TransformStyle3DPreserve3D && !renderer().hasReflection();
662     m_graphicsLayer->setPreserves3D(preserves3D);
663     m_graphicsLayer->setBackfaceVisibility(style.backfaceVisibility() == BackfaceVisibilityVisible);
664
665     RenderLayer* compAncestor = m_owningLayer.ancestorCompositingLayer();
666     
667     // We compute everything relative to the enclosing compositing layer.
668     LayoutRect ancestorCompositingBounds;
669     if (compAncestor) {
670         ASSERT(compAncestor->backing());
671         ancestorCompositingBounds = compAncestor->backing()->compositedBounds();
672     }
673
674     /*
675     * GraphicsLayer: device pixel positioned, enclosing rect.
676     * RenderLayer: subpixel positioned.
677     * Offset from renderer (GraphicsLayer <-> RenderLayer::renderer()): subpixel based offset.
678     *
679     *     relativeCompositingBounds
680     *      _______________________________________
681     *     |\          GraphicsLayer               |
682     *     | \                                     |
683     *     |  \ offset from renderer: (device pixel + subpixel)
684     *     |   \                                   |
685     *     |    \______________________________    |
686     *     |    | localCompositingBounds       |   |
687     *     |    |                              |   |
688     *     |    |   RenderLayer::renderer()    |   |
689     *     |    |                              |   |
690     *
691     * localCompositingBounds: this RenderLayer relative to its renderer().
692     * relativeCompositingBounds: this RenderLayer relative to its parent compositing layer.
693     * enclosingRelativeCompositingBounds: this RenderLayer relative to its parent, device pixel enclosing.
694     * rendererOffsetFromGraphicsLayer: RenderLayer::renderer()'s offset from its enclosing GraphicsLayer.
695     * devicePixelOffsetFromRenderer: rendererOffsetFromGraphicsLayer's device pixel part. (6.9px -> 6.5px in case of 2x display)
696     * devicePixelFractionFromRenderer: rendererOffsetFromGraphicsLayer's fractional part (6.9px -> 0.4px in case of 2x display)
697     */
698     float deviceScaleFactor = this->deviceScaleFactor();
699     LayoutRect localCompositingBounds = compositedBounds();
700     LayoutRect relativeCompositingBounds(localCompositingBounds);
701
702     LayoutPoint offsetFromParent = m_owningLayer.convertToLayerCoords(compAncestor, LayoutPoint(), RenderLayer::AdjustForColumns);
703     // Device pixel fractions get accumulated through ancestor layers. Our painting offset is layout offset + parent's painting offset.
704     offsetFromParent = offsetFromParent + (compAncestor ? compAncestor->backing()->devicePixelFractionFromRenderer() : LayoutSize());
705     relativeCompositingBounds.moveBy(offsetFromParent);
706
707     LayoutRect enclosingRelativeCompositingBounds = LayoutRect(encloseRectToDevicePixels(relativeCompositingBounds, deviceScaleFactor));
708     LayoutSize subpixelOffsetAdjustment = enclosingRelativeCompositingBounds.location() - relativeCompositingBounds.location();
709     LayoutSize rendererOffsetFromGraphicsLayer =  toLayoutSize(localCompositingBounds.location()) + subpixelOffsetAdjustment;
710
711     FloatSize devicePixelOffsetFromRenderer;
712     LayoutSize devicePixelFractionFromRenderer;
713     calculateDevicePixelOffsetFromRenderer(rendererOffsetFromGraphicsLayer, devicePixelOffsetFromRenderer, devicePixelFractionFromRenderer, deviceScaleFactor);
714     m_devicePixelFractionFromRenderer = LayoutSize(-devicePixelFractionFromRenderer.width(), -devicePixelFractionFromRenderer.height());
715
716     adjustAncestorCompositingBoundsForFlowThread(ancestorCompositingBounds, compAncestor);
717
718     LayoutPoint graphicsLayerParentLocation;
719     if (compAncestor && compAncestor->backing()->hasClippingLayer()) {
720         // If the compositing ancestor has a layer to clip children, we parent in that, and therefore
721         // position relative to it.
722         // FIXME: need to do some pixel snapping here.
723         LayoutRect clippingBox = clipBox(downcast<RenderBox>(compAncestor->renderer()));
724         graphicsLayerParentLocation = clippingBox.location();
725     } else if (compAncestor)
726         graphicsLayerParentLocation = ancestorCompositingBounds.location();
727     else
728         graphicsLayerParentLocation = renderer().view().documentRect().location();
729
730 #if PLATFORM(IOS)
731     if (compAncestor && compAncestor->hasTouchScrollableOverflow()) {
732         auto& renderBox = downcast<RenderBox>(compAncestor->renderer());
733         LayoutRect paddingBox(renderBox.borderLeft(), renderBox.borderTop(),
734             renderBox.width() - renderBox.borderLeft() - renderBox.borderRight(),
735             renderBox.height() - renderBox.borderTop() - renderBox.borderBottom());
736
737         IntSize scrollOffset = compAncestor->scrolledContentOffset();
738         // FIXME: pixel snap the padding box.
739         graphicsLayerParentLocation = paddingBox.location() - scrollOffset;
740     }
741 #else
742     if (compAncestor && compAncestor->needsCompositedScrolling()) {
743         auto& renderBox = downcast<RenderBox>(compAncestor->renderer());
744         LayoutSize scrollOffset = compAncestor->scrolledContentOffset();
745         LayoutPoint scrollOrigin(renderBox.borderLeft(), renderBox.borderTop());
746         graphicsLayerParentLocation = scrollOrigin - scrollOffset;
747     }
748 #endif
749
750     if (compAncestor && m_ancestorClippingLayer) {
751         // Call calculateRects to get the backgroundRect which is what is used to clip the contents of this
752         // layer. Note that we call it with temporaryClipRects = true because normally when computing clip rects
753         // for a compositing layer, rootLayer is the layer itself.
754         ShouldRespectOverflowClip shouldRespectOverflowClip = compAncestor->isolatesCompositedBlending() ? RespectOverflowClip : IgnoreOverflowClip;
755         RenderLayer::ClipRectsContext clipRectsContext(compAncestor, TemporaryClipRects, IgnoreOverlayScrollbarSize, shouldRespectOverflowClip);
756         LayoutRect parentClipRect = m_owningLayer.backgroundClipRect(clipRectsContext).rect(); // FIXME: Incorrect for CSS regions.
757         ASSERT(parentClipRect != LayoutRect::infiniteRect());
758         m_ancestorClippingLayer->setPosition(FloatPoint(parentClipRect.location() - graphicsLayerParentLocation));
759         m_ancestorClippingLayer->setSize(parentClipRect.size());
760
761         // backgroundRect is relative to compAncestor, so subtract deltaX/deltaY to get back to local coords.
762         m_ancestorClippingLayer->setOffsetFromRenderer(parentClipRect.location() - offsetFromParent);
763
764         // The primary layer is then parented in, and positioned relative to this clipping layer.
765         graphicsLayerParentLocation = parentClipRect.location();
766     }
767
768     LayoutSize contentsSize = enclosingRelativeCompositingBounds.size();
769     
770     if (m_contentsContainmentLayer) {
771         m_contentsContainmentLayer->setPreserves3D(preserves3D);
772         m_contentsContainmentLayer->setPosition(FloatPoint(enclosingRelativeCompositingBounds.location() - graphicsLayerParentLocation));
773         // Use the same size as m_graphicsLayer so transforms behave correctly.
774         m_contentsContainmentLayer->setSize(contentsSize);
775         graphicsLayerParentLocation = enclosingRelativeCompositingBounds.location();
776     }
777
778     m_graphicsLayer->setPosition(FloatPoint(enclosingRelativeCompositingBounds.location() - graphicsLayerParentLocation));
779     m_graphicsLayer->setSize(contentsSize);
780     if (devicePixelOffsetFromRenderer != m_graphicsLayer->offsetFromRenderer()) {
781         m_graphicsLayer->setOffsetFromRenderer(devicePixelOffsetFromRenderer);
782         positionOverflowControlsLayers();
783     }
784
785     if (!m_isMainFrameRenderViewLayer) {
786         // For non-root layers, background is always painted by the primary graphics layer.
787         ASSERT(!m_backgroundLayer);
788         bool hadSubpixelRounding = enclosingRelativeCompositingBounds != relativeCompositingBounds;
789         m_graphicsLayer->setContentsOpaque(!hadSubpixelRounding && m_owningLayer.backgroundIsKnownToBeOpaqueInRect(localCompositingBounds));
790     }
791
792     // If we have a layer that clips children, position it.
793     LayoutRect clippingBox;
794     if (GraphicsLayer* clipLayer = clippingLayer()) {
795         // FIXME: need to do some pixel snapping here.
796         clippingBox = clipBox(downcast<RenderBox>(renderer()));
797         clipLayer->setPosition(FloatPoint(clippingBox.location() - localCompositingBounds.location()));
798         clipLayer->setSize(clippingBox.size());
799         clipLayer->setOffsetFromRenderer(toFloatSize(clippingBox.location()));
800     }
801     
802     if (m_maskLayer) {
803         m_maskLayer->setSize(m_graphicsLayer->size());
804         m_maskLayer->setPosition(FloatPoint());
805         m_maskLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
806     }
807     
808     if (m_owningLayer.hasTransform()) {
809         // Update properties that depend on layer dimensions.
810         FloatPoint3D transformOrigin = computeTransformOriginForPainting(downcast<RenderBox>(renderer()).borderBoxRect());
811         // Get layout bounds in the coords of compAncestor to match relativeCompositingBounds.
812         FloatPoint layerOffset = roundPointToDevicePixels(offsetFromParent, deviceScaleFactor);
813         // Compute the anchor point, which is in the center of the renderer box unless transform-origin is set.
814         FloatPoint3D anchor(enclosingRelativeCompositingBounds.width() ? ((layerOffset.x() - enclosingRelativeCompositingBounds.x()) + transformOrigin.x())
815             / enclosingRelativeCompositingBounds.width() : 0.5, enclosingRelativeCompositingBounds.height() ? ((layerOffset.y() - enclosingRelativeCompositingBounds.y())
816             + transformOrigin.y()) / enclosingRelativeCompositingBounds.height() : 0.5, transformOrigin.z());
817
818         if (m_contentsContainmentLayer)
819             m_contentsContainmentLayer->setAnchorPoint(anchor);
820         else
821             m_graphicsLayer->setAnchorPoint(anchor);
822
823         GraphicsLayer* clipLayer = clippingLayer();
824         if (style.hasPerspective()) {
825             TransformationMatrix t = owningLayer().perspectiveTransform();
826             
827             if (clipLayer) {
828                 clipLayer->setChildrenTransform(t);
829                 m_graphicsLayer->setChildrenTransform(TransformationMatrix());
830             }
831             else
832                 m_graphicsLayer->setChildrenTransform(t);
833         } else {
834             if (clipLayer)
835                 clipLayer->setChildrenTransform(TransformationMatrix());
836             else
837                 m_graphicsLayer->setChildrenTransform(TransformationMatrix());
838         }
839     } else {
840         m_graphicsLayer->setAnchorPoint(FloatPoint3D(0.5, 0.5, 0));
841         if (m_contentsContainmentLayer)
842             m_contentsContainmentLayer->setAnchorPoint(FloatPoint3D(0.5, 0.5, 0));
843     }
844
845     if (m_foregroundLayer) {
846         FloatPoint foregroundPosition;
847         FloatSize foregroundSize = contentsSize;
848         FloatSize foregroundOffset = m_graphicsLayer->offsetFromRenderer();
849         if (hasClippingLayer()) {
850             // If we have a clipping layer (which clips descendants), then the foreground layer is a child of it,
851             // so that it gets correctly sorted with children. In that case, position relative to the clipping layer.
852             foregroundSize = FloatSize(clippingBox.size());
853             foregroundOffset = toFloatSize(clippingBox.location());
854         }
855
856         m_foregroundLayer->setPosition(foregroundPosition);
857         m_foregroundLayer->setSize(foregroundSize);
858         m_foregroundLayer->setOffsetFromRenderer(foregroundOffset);
859     }
860
861     if (m_backgroundLayer) {
862         FloatPoint backgroundPosition;
863         FloatSize backgroundSize = contentsSize;
864         if (backgroundLayerPaintsFixedRootBackground()) {
865             const FrameView& frameView = renderer().view().frameView();
866             backgroundPosition = toLayoutPoint(frameView.scrollOffsetForFixedPosition());
867             backgroundSize = frameView.visibleContentRect().size();
868         }
869         m_backgroundLayer->setPosition(backgroundPosition);
870         m_backgroundLayer->setSize(backgroundSize);
871         m_backgroundLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
872     }
873
874     if (m_owningLayer.reflectionLayer() && m_owningLayer.reflectionLayer()->isComposited()) {
875         RenderLayerBacking* reflectionBacking = m_owningLayer.reflectionLayer()->backing();
876         reflectionBacking->updateGeometry();
877         
878         // The reflection layer has the bounds of m_owningLayer.reflectionLayer(),
879         // but the reflected layer is the bounds of this layer, so we need to position it appropriately.
880         FloatRect layerBounds = compositedBounds();
881         FloatRect reflectionLayerBounds = reflectionBacking->compositedBounds();
882         reflectionBacking->graphicsLayer()->setReplicatedLayerPosition(FloatPoint(layerBounds.location() - reflectionLayerBounds.location()));
883     }
884
885     if (m_scrollingLayer) {
886         ASSERT(m_scrollingContentsLayer);
887         auto& renderBox = downcast<RenderBox>(renderer());
888         LayoutRect paddingBox(renderBox.borderLeft(), renderBox.borderTop(), renderBox.width() - renderBox.borderLeft() - renderBox.borderRight(), renderBox.height() - renderBox.borderTop() - renderBox.borderBottom());
889         LayoutSize scrollOffset = m_owningLayer.scrollOffset();
890
891         // FIXME: need to do some pixel snapping here.
892         m_scrollingLayer->setPosition(FloatPoint(paddingBox.location() - localCompositingBounds.location()));
893
894         IntSize pixelSnappedClientSize(renderBox.pixelSnappedClientWidth(), renderBox.pixelSnappedClientHeight());
895         m_scrollingLayer->setSize(pixelSnappedClientSize);
896 #if PLATFORM(IOS)
897         FloatSize oldScrollingLayerOffset = m_scrollingLayer->offsetFromRenderer();
898         m_scrollingLayer->setOffsetFromRenderer(FloatPoint() - paddingBox.location());
899         bool paddingBoxOffsetChanged = oldScrollingLayerOffset != m_scrollingLayer->offsetFromRenderer();
900
901         if (m_owningLayer.isInUserScroll()) {
902             // If scrolling is happening externally, we don't want to touch the layer bounds origin here because that will cause jitter.
903             m_scrollingLayer->syncBoundsOrigin(FloatPoint(scrollOffset.width(), scrollOffset.height()));
904             m_owningLayer.setRequiresScrollBoundsOriginUpdate(true);
905         } else {
906             // Note that we implement the contents offset via the bounds origin on this layer, rather than a position on the sublayer.
907             m_scrollingLayer->setBoundsOrigin(FloatPoint(scrollOffset.width(), scrollOffset.height()));
908             m_owningLayer.setRequiresScrollBoundsOriginUpdate(false);
909         }
910         
911         IntSize scrollSize(m_owningLayer.scrollWidth(), m_owningLayer.scrollHeight());
912
913         m_scrollingContentsLayer->setPosition(FloatPoint());
914         
915         if (scrollSize != m_scrollingContentsLayer->size() || paddingBoxOffsetChanged)
916             m_scrollingContentsLayer->setNeedsDisplay();
917
918         m_scrollingContentsLayer->setSize(scrollSize);
919         // Scrolling the content layer does not need to trigger a repaint. The offset will be compensated away during painting.
920         // FIXME: The paint offset and the scroll offset should really be separate concepts.
921         m_scrollingContentsLayer->setOffsetFromRenderer(paddingBox.location() - IntPoint() - scrollOffset, GraphicsLayer::DontSetNeedsDisplay);
922 #else
923         m_scrollingContentsLayer->setPosition(FloatPoint(-scrollOffset.width(), -scrollOffset.height()));
924
925         FloatSize oldScrollingLayerOffset = m_scrollingLayer->offsetFromRenderer();
926         m_scrollingLayer->setOffsetFromRenderer(-toFloatSize(paddingBox.location()));
927
928         bool paddingBoxOffsetChanged = oldScrollingLayerOffset != m_scrollingLayer->offsetFromRenderer();
929
930         IntSize scrollSize(m_owningLayer.scrollWidth(), m_owningLayer.scrollHeight());
931         if (scrollSize != m_scrollingContentsLayer->size() || paddingBoxOffsetChanged)
932             m_scrollingContentsLayer->setNeedsDisplay();
933
934         LayoutSize scrollingContentsOffset = toLayoutSize(paddingBox.location() - scrollOffset);
935         if (scrollingContentsOffset != m_scrollingContentsLayer->offsetFromRenderer() || scrollSize != m_scrollingContentsLayer->size())
936             compositor().scrollingLayerDidChange(m_owningLayer);
937
938         m_scrollingContentsLayer->setSize(scrollSize);
939         // FIXME: The paint offset and the scroll offset should really be separate concepts.
940         m_scrollingContentsLayer->setOffsetFromRenderer(scrollingContentsOffset, GraphicsLayer::DontSetNeedsDisplay);
941 #endif
942
943         if (m_foregroundLayer) {
944             m_foregroundLayer->setSize(m_scrollingContentsLayer->size());
945             m_foregroundLayer->setOffsetFromRenderer(m_scrollingContentsLayer->offsetFromRenderer());
946         }
947     }
948
949     // If this layer was created just for clipping or to apply perspective, it doesn't need its own backing store.
950     setRequiresOwnBackingStore(compositor().requiresOwnBackingStore(m_owningLayer, compAncestor, enclosingRelativeCompositingBounds, ancestorCompositingBounds));
951
952     updateAfterWidgetResize();
953
954     compositor().updateScrollCoordinatedStatus(m_owningLayer);
955 }
956
957 void RenderLayerBacking::updateAfterDescendants()
958 {
959     bool isSimpleContainer = false;
960     if (!m_owningLayer.isRootLayer()) {
961         bool didUpdateContentsRect = false;
962         // FIXME: this duplicates work we did in updateConfiguration().
963         isSimpleContainer = isSimpleContainerCompositingLayer();
964         updateDirectlyCompositedContents(isSimpleContainer, didUpdateContentsRect);
965         if (!didUpdateContentsRect && m_graphicsLayer->usesContentsLayer())
966             resetContentsRect();
967     }
968
969     updateDrawsContent(isSimpleContainer);
970
971     m_graphicsLayer->setContentsVisible(m_owningLayer.hasVisibleContent() || isPaintDestinationForDescendentLayers());
972 }
973
974 void RenderLayerBacking::adjustAncestorCompositingBoundsForFlowThread(LayoutRect& ancestorCompositingBounds, const RenderLayer* compositingAncestor) const
975 {
976     if (!m_owningLayer.isInsideFlowThread())
977         return;
978
979     RenderLayer* flowThreadLayer = m_owningLayer.isInsideOutOfFlowThread() ? m_owningLayer.stackingContainer() : nullptr;
980     if (flowThreadLayer && flowThreadLayer->isRenderFlowThread()) {
981         if (m_owningLayer.isFlowThreadCollectingGraphicsLayersUnderRegions()) {
982             // The RenderNamedFlowThread is not composited, as we need it to paint the 
983             // background layer of the regions. We need to compensate for that by manually
984             // subtracting the position of the flow-thread.
985             IntPoint flowPosition;
986             flowThreadLayer->convertToPixelSnappedLayerCoords(compositingAncestor, flowPosition);
987             ancestorCompositingBounds.moveBy(flowPosition);
988         }
989
990         // Move the ancestor position at the top of the region where the composited layer is going to display.
991         RenderFlowThread& flowThread = downcast<RenderFlowThread>(flowThreadLayer->renderer());
992         RenderNamedFlowFragment* parentRegion = flowThread.cachedRegionForCompositedLayer(m_owningLayer);
993         if (!parentRegion)
994             return;
995
996         IntPoint flowDelta;
997         m_owningLayer.convertToPixelSnappedLayerCoords(flowThreadLayer, flowDelta);
998         parentRegion->adjustRegionBoundsFromFlowThreadPortionRect(ancestorCompositingBounds);
999         RenderBoxModelObject& layerOwner = downcast<RenderBoxModelObject>(parentRegion->layerOwner());
1000         RenderLayerBacking* layerOwnerBacking = layerOwner.layer()->backing();
1001         if (!layerOwnerBacking)
1002             return;
1003
1004         // Make sure that the region propagates its borders, paddings, outlines or box-shadows to layers inside it.
1005         // Note that the composited bounds of the RenderRegion are already calculated because
1006         // RenderLayerCompositor::rebuildCompositingLayerTree will only iterate on the content of the region after the
1007         // region itself is computed.
1008         ancestorCompositingBounds.moveBy(roundedIntPoint(layerOwnerBacking->compositedBounds().location()));
1009         ancestorCompositingBounds.move(-layerOwner.borderAndPaddingStart(), -layerOwner.borderAndPaddingBefore());
1010
1011         // If there's a clipping GraphicsLayer on the hierarchy (region graphics layer -> clipping graphics layer ->
1012         // composited content graphics layer), substract the offset of the clipping layer, since it's its parent
1013         // that positions us (the graphics layer of the region).
1014         if (layerOwnerBacking->clippingLayer())
1015             ancestorCompositingBounds.moveBy(roundedIntPoint(layerOwnerBacking->clippingLayer()->position()));
1016     }
1017 }
1018
1019 void RenderLayerBacking::updateDirectlyCompositedContents(bool isSimpleContainer, bool& didUpdateContentsRect)
1020 {
1021     if (!m_owningLayer.hasVisibleContent())
1022         return;
1023
1024     // The order of operations here matters, since the last valid type of contents needs
1025     // to also update the contentsRect.
1026     updateDirectlyCompositedBackgroundColor(isSimpleContainer, didUpdateContentsRect);
1027     updateDirectlyCompositedBackgroundImage(isSimpleContainer, didUpdateContentsRect);
1028 }
1029
1030 void RenderLayerBacking::updateInternalHierarchy()
1031 {
1032     // m_foregroundLayer has to be inserted in the correct order with child layers,
1033     // so it's not inserted here.
1034     if (m_ancestorClippingLayer)
1035         m_ancestorClippingLayer->removeAllChildren();
1036     
1037     if (m_contentsContainmentLayer) {
1038         m_contentsContainmentLayer->removeAllChildren();
1039         if (m_ancestorClippingLayer)
1040             m_ancestorClippingLayer->addChild(m_contentsContainmentLayer.get());
1041     }
1042     
1043     if (m_backgroundLayer)
1044         m_contentsContainmentLayer->addChild(m_backgroundLayer.get());
1045
1046     if (m_contentsContainmentLayer)
1047         m_contentsContainmentLayer->addChild(m_graphicsLayer.get());
1048     else if (m_ancestorClippingLayer)
1049         m_ancestorClippingLayer->addChild(m_graphicsLayer.get());
1050
1051     if (m_childContainmentLayer) {
1052         m_childContainmentLayer->removeFromParent();
1053         m_graphicsLayer->addChild(m_childContainmentLayer.get());
1054     }
1055
1056     if (m_scrollingLayer) {
1057         GraphicsLayer* superlayer = m_childContainmentLayer ? m_childContainmentLayer.get() : m_graphicsLayer.get();
1058         m_scrollingLayer->removeFromParent();
1059         superlayer->addChild(m_scrollingLayer.get());
1060     }
1061
1062     // The clip for child layers does not include space for overflow controls, so they exist as
1063     // siblings of the clipping layer if we have one. Normal children of this layer are set as
1064     // children of the clipping layer.
1065     if (m_layerForHorizontalScrollbar) {
1066         m_layerForHorizontalScrollbar->removeFromParent();
1067         m_graphicsLayer->addChild(m_layerForHorizontalScrollbar.get());
1068     }
1069     if (m_layerForVerticalScrollbar) {
1070         m_layerForVerticalScrollbar->removeFromParent();
1071         m_graphicsLayer->addChild(m_layerForVerticalScrollbar.get());
1072     }
1073     if (m_layerForScrollCorner) {
1074         m_layerForScrollCorner->removeFromParent();
1075         m_graphicsLayer->addChild(m_layerForScrollCorner.get());
1076     }
1077 }
1078
1079 void RenderLayerBacking::resetContentsRect()
1080 {
1081     m_graphicsLayer->setContentsRect(snappedIntRect(contentsBox()));
1082     
1083     LayoutRect contentsClippingRect;
1084     if (is<RenderBox>(renderer()))
1085         contentsClippingRect = downcast<RenderBox>(renderer()).contentBoxRect();
1086
1087     contentsClippingRect.move(contentOffsetInCompostingLayer());
1088     m_graphicsLayer->setContentsClippingRect(snappedIntRect(contentsClippingRect));
1089
1090     m_graphicsLayer->setContentsTileSize(IntSize());
1091     m_graphicsLayer->setContentsTilePhase(IntPoint());
1092 }
1093
1094 void RenderLayerBacking::updateDrawsContent()
1095 {
1096     updateDrawsContent(isSimpleContainerCompositingLayer());
1097 }
1098
1099 void RenderLayerBacking::updateDrawsContent(bool isSimpleContainer)
1100 {
1101     if (m_scrollingLayer) {
1102         // We don't have to consider overflow controls, because we know that the scrollbars are drawn elsewhere.
1103         // m_graphicsLayer only needs backing store if the non-scrolling parts (background, outlines, borders, shadows etc) need to paint.
1104         // m_scrollingLayer never has backing store.
1105         // m_scrollingContentsLayer only needs backing store if the scrolled contents need to paint.
1106         bool hasNonScrollingPaintedContent = m_owningLayer.hasVisibleContent() && m_owningLayer.hasBoxDecorationsOrBackground();
1107         m_graphicsLayer->setDrawsContent(hasNonScrollingPaintedContent);
1108
1109         bool hasScrollingPaintedContent = m_owningLayer.hasVisibleContent() && (renderer().hasBackground() || paintsChildren());
1110         m_scrollingContentsLayer->setDrawsContent(hasScrollingPaintedContent);
1111         return;
1112     }
1113
1114     bool hasPaintedContent = containsPaintedContent(isSimpleContainer);
1115
1116     // FIXME: we could refine this to only allocate backing for one of these layers if possible.
1117     m_graphicsLayer->setDrawsContent(hasPaintedContent);
1118     if (m_foregroundLayer)
1119         m_foregroundLayer->setDrawsContent(hasPaintedContent);
1120
1121     if (m_backgroundLayer)
1122         m_backgroundLayer->setDrawsContent(hasPaintedContent);
1123 }
1124
1125 // Return true if the layer changed.
1126 bool RenderLayerBacking::updateAncestorClippingLayer(bool needsAncestorClip)
1127 {
1128     bool layersChanged = false;
1129
1130     if (needsAncestorClip) {
1131         if (!m_ancestorClippingLayer) {
1132             m_ancestorClippingLayer = createGraphicsLayer("Ancestor clipping Layer");
1133             m_ancestorClippingLayer->setMasksToBounds(true);
1134             layersChanged = true;
1135         }
1136     } else if (hasAncestorClippingLayer()) {
1137         willDestroyLayer(m_ancestorClippingLayer.get());
1138         m_ancestorClippingLayer->removeFromParent();
1139         m_ancestorClippingLayer = nullptr;
1140         layersChanged = true;
1141     }
1142     
1143     return layersChanged;
1144 }
1145
1146 // Return true if the layer changed.
1147 bool RenderLayerBacking::updateDescendantClippingLayer(bool needsDescendantClip)
1148 {
1149     bool layersChanged = false;
1150
1151     if (needsDescendantClip) {
1152         if (!m_childContainmentLayer && !m_usingTiledCacheLayer) {
1153             m_childContainmentLayer = createGraphicsLayer("Child clipping Layer");
1154             m_childContainmentLayer->setMasksToBounds(true);
1155             layersChanged = true;
1156         }
1157     } else if (hasClippingLayer()) {
1158         willDestroyLayer(m_childContainmentLayer.get());
1159         m_childContainmentLayer->removeFromParent();
1160         m_childContainmentLayer = nullptr;
1161         layersChanged = true;
1162     }
1163     
1164     return layersChanged;
1165 }
1166
1167 void RenderLayerBacking::setBackgroundLayerPaintsFixedRootBackground(bool backgroundLayerPaintsFixedRootBackground)
1168 {
1169     m_backgroundLayerPaintsFixedRootBackground = backgroundLayerPaintsFixedRootBackground;
1170 }
1171
1172 bool RenderLayerBacking::requiresHorizontalScrollbarLayer() const
1173 {
1174     if (!m_owningLayer.hasOverlayScrollbars() && !m_owningLayer.needsCompositedScrolling())
1175         return false;
1176     return m_owningLayer.horizontalScrollbar();
1177 }
1178
1179 bool RenderLayerBacking::requiresVerticalScrollbarLayer() const
1180 {
1181     if (!m_owningLayer.hasOverlayScrollbars() && !m_owningLayer.needsCompositedScrolling())
1182         return false;
1183     return m_owningLayer.verticalScrollbar();
1184 }
1185
1186 bool RenderLayerBacking::requiresScrollCornerLayer() const
1187 {
1188     if (!m_owningLayer.hasOverlayScrollbars() && !m_owningLayer.needsCompositedScrolling())
1189         return false;
1190     return !m_owningLayer.scrollCornerAndResizerRect().isEmpty();
1191 }
1192
1193 bool RenderLayerBacking::updateOverflowControlsLayers(bool needsHorizontalScrollbarLayer, bool needsVerticalScrollbarLayer, bool needsScrollCornerLayer)
1194 {
1195     bool horizontalScrollbarLayerChanged = false;
1196     if (needsHorizontalScrollbarLayer) {
1197         if (!m_layerForHorizontalScrollbar) {
1198             m_layerForHorizontalScrollbar = createGraphicsLayer("horizontal scrollbar");
1199             horizontalScrollbarLayerChanged = true;
1200         }
1201     } else if (m_layerForHorizontalScrollbar) {
1202         willDestroyLayer(m_layerForHorizontalScrollbar.get());
1203         m_layerForHorizontalScrollbar = nullptr;
1204         horizontalScrollbarLayerChanged = true;
1205     }
1206
1207     bool verticalScrollbarLayerChanged = false;
1208     if (needsVerticalScrollbarLayer) {
1209         if (!m_layerForVerticalScrollbar) {
1210             m_layerForVerticalScrollbar = createGraphicsLayer("vertical scrollbar");
1211             verticalScrollbarLayerChanged = true;
1212         }
1213     } else if (m_layerForVerticalScrollbar) {
1214         willDestroyLayer(m_layerForVerticalScrollbar.get());
1215         m_layerForVerticalScrollbar = nullptr;
1216         verticalScrollbarLayerChanged = true;
1217     }
1218
1219     bool scrollCornerLayerChanged = false;
1220     if (needsScrollCornerLayer) {
1221         if (!m_layerForScrollCorner) {
1222             m_layerForScrollCorner = createGraphicsLayer("scroll corner");
1223             scrollCornerLayerChanged = true;
1224         }
1225     } else if (m_layerForScrollCorner) {
1226         willDestroyLayer(m_layerForScrollCorner.get());
1227         m_layerForScrollCorner = nullptr;
1228         scrollCornerLayerChanged = true;
1229     }
1230
1231     if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer)) {
1232         if (horizontalScrollbarLayerChanged)
1233             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_owningLayer, HorizontalScrollbar);
1234         if (verticalScrollbarLayerChanged)
1235             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_owningLayer, VerticalScrollbar);
1236     }
1237
1238     return horizontalScrollbarLayerChanged || verticalScrollbarLayerChanged || scrollCornerLayerChanged;
1239 }
1240
1241 void RenderLayerBacking::positionOverflowControlsLayers()
1242 {
1243     if (!m_owningLayer.hasScrollbars())
1244         return;
1245
1246     const IntRect borderBox = downcast<RenderBox>(renderer()).pixelSnappedBorderBoxRect();
1247
1248     FloatSize offsetFromRenderer = m_graphicsLayer->offsetFromRenderer();
1249     if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
1250         IntRect hBarRect = m_owningLayer.rectForHorizontalScrollbar(borderBox);
1251         layer->setPosition(hBarRect.location() - offsetFromRenderer);
1252         layer->setSize(hBarRect.size());
1253         if (layer->usesContentsLayer()) {
1254             IntRect barRect = IntRect(IntPoint(), hBarRect.size());
1255             layer->setContentsRect(barRect);
1256             layer->setContentsClippingRect(barRect);
1257         }
1258         layer->setDrawsContent(m_owningLayer.horizontalScrollbar() && !layer->usesContentsLayer());
1259     }
1260     
1261     if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
1262         IntRect vBarRect = m_owningLayer.rectForVerticalScrollbar(borderBox);
1263         layer->setPosition(vBarRect.location() - offsetFromRenderer);
1264         layer->setSize(vBarRect.size());
1265         if (layer->usesContentsLayer()) {
1266             IntRect barRect = IntRect(IntPoint(), vBarRect.size());
1267             layer->setContentsRect(barRect);
1268             layer->setContentsClippingRect(barRect);
1269         }
1270         layer->setDrawsContent(m_owningLayer.verticalScrollbar() && !layer->usesContentsLayer());
1271     }
1272
1273     if (GraphicsLayer* layer = layerForScrollCorner()) {
1274         const LayoutRect& scrollCornerAndResizer = m_owningLayer.scrollCornerAndResizerRect();
1275         layer->setPosition(scrollCornerAndResizer.location() - offsetFromRenderer);
1276         layer->setSize(scrollCornerAndResizer.size());
1277         layer->setDrawsContent(!scrollCornerAndResizer.isEmpty());
1278     }
1279 }
1280
1281 bool RenderLayerBacking::hasUnpositionedOverflowControlsLayers() const
1282 {
1283     if (GraphicsLayer* layer = layerForHorizontalScrollbar())
1284         if (!layer->drawsContent())
1285             return true;
1286
1287     if (GraphicsLayer* layer = layerForVerticalScrollbar())
1288         if (!layer->drawsContent())
1289             return true;
1290
1291     if (GraphicsLayer* layer = layerForScrollCorner())
1292         if (!layer->drawsContent())
1293             return true;
1294
1295     return false;
1296 }
1297
1298 bool RenderLayerBacking::updateForegroundLayer(bool needsForegroundLayer)
1299 {
1300     bool layerChanged = false;
1301     if (needsForegroundLayer) {
1302         if (!m_foregroundLayer) {
1303             String layerName;
1304 #ifndef NDEBUG
1305             layerName = m_owningLayer.name() + " (foreground)";
1306 #endif
1307             m_foregroundLayer = createGraphicsLayer(layerName);
1308             m_foregroundLayer->setDrawsContent(true);
1309             m_foregroundLayer->setPaintingPhase(GraphicsLayerPaintForeground);
1310             layerChanged = true;
1311         }
1312     } else if (m_foregroundLayer) {
1313         willDestroyLayer(m_foregroundLayer.get());
1314         m_foregroundLayer->removeFromParent();
1315         m_foregroundLayer = nullptr;
1316         layerChanged = true;
1317     }
1318
1319     if (layerChanged) {
1320         m_graphicsLayer->setNeedsDisplay();
1321         m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
1322     }
1323
1324     return layerChanged;
1325 }
1326
1327 bool RenderLayerBacking::updateBackgroundLayer(bool needsBackgroundLayer)
1328 {
1329     bool layerChanged = false;
1330     if (needsBackgroundLayer) {
1331         if (!m_backgroundLayer) {
1332             String layerName;
1333 #ifndef NDEBUG
1334             layerName = m_owningLayer.name() + " (background)";
1335 #endif
1336             m_backgroundLayer = createGraphicsLayer(layerName);
1337             m_backgroundLayer->setDrawsContent(true);
1338             m_backgroundLayer->setAnchorPoint(FloatPoint3D());
1339             m_backgroundLayer->setPaintingPhase(GraphicsLayerPaintBackground);
1340             layerChanged = true;
1341         }
1342         
1343         if (!m_contentsContainmentLayer) {
1344             String layerName;
1345 #ifndef NDEBUG
1346             layerName = m_owningLayer.name() + " (contents containment)";
1347 #endif
1348             m_contentsContainmentLayer = createGraphicsLayer(layerName);
1349             m_contentsContainmentLayer->setAppliesPageScale(true);
1350             m_graphicsLayer->setAppliesPageScale(false);
1351             layerChanged = true;
1352         }
1353     } else {
1354         if (m_backgroundLayer) {
1355             willDestroyLayer(m_backgroundLayer.get());
1356             m_backgroundLayer->removeFromParent();
1357             m_backgroundLayer = nullptr;
1358             layerChanged = true;
1359         }
1360         if (m_contentsContainmentLayer) {
1361             willDestroyLayer(m_contentsContainmentLayer.get());
1362             m_contentsContainmentLayer->removeFromParent();
1363             m_contentsContainmentLayer = nullptr;
1364             layerChanged = true;
1365             m_graphicsLayer->setAppliesPageScale(true);
1366         }
1367     }
1368     
1369     if (layerChanged) {
1370         m_graphicsLayer->setNeedsDisplay();
1371         // This assumes that the background layer is only used for fixed backgrounds, which is currently a correct assumption.
1372         compositor().fixedRootBackgroundLayerChanged();
1373     }
1374     
1375     return layerChanged;
1376 }
1377
1378 void RenderLayerBacking::updateMaskLayer(bool needsMaskLayer)
1379 {
1380     bool layerChanged = false;
1381     if (needsMaskLayer) {
1382         if (!m_maskLayer) {
1383             m_maskLayer = createGraphicsLayer("Mask");
1384             m_maskLayer->setDrawsContent(true);
1385             m_maskLayer->setPaintingPhase(GraphicsLayerPaintMask);
1386             layerChanged = true;
1387             m_graphicsLayer->setMaskLayer(m_maskLayer.get());
1388         }
1389     } else if (m_maskLayer) {
1390         m_graphicsLayer->setMaskLayer(nullptr);
1391         willDestroyLayer(m_maskLayer.get());
1392         m_maskLayer = nullptr;
1393         layerChanged = true;
1394     }
1395
1396     if (layerChanged)
1397         m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
1398 }
1399
1400 bool RenderLayerBacking::updateScrollingLayers(bool needsScrollingLayers)
1401 {
1402     if (needsScrollingLayers == !!m_scrollingLayer)
1403         return false;
1404
1405     if (!m_scrollingLayer) {
1406         // Outer layer which corresponds with the scroll view.
1407         m_scrollingLayer = createGraphicsLayer("Scrolling container");
1408         m_scrollingLayer->setDrawsContent(false);
1409         m_scrollingLayer->setMasksToBounds(true);
1410 #if PLATFORM(IOS)
1411         m_scrollingLayer->setCustomBehavior(GraphicsLayer::CustomScrollingBehavior);
1412 #endif
1413         // Inner layer which renders the content that scrolls.
1414         m_scrollingContentsLayer = createGraphicsLayer("Scrolled Contents");
1415         m_scrollingContentsLayer->setDrawsContent(true);
1416 #if PLATFORM(IOS)
1417         m_scrollingContentsLayer->setCustomBehavior(GraphicsLayer::CustomScrolledContentsBehavior);
1418 #endif
1419         GraphicsLayerPaintingPhase paintPhase = GraphicsLayerPaintOverflowContents | GraphicsLayerPaintCompositedScroll;
1420         if (!m_foregroundLayer)
1421             paintPhase |= GraphicsLayerPaintForeground;
1422         m_scrollingContentsLayer->setPaintingPhase(paintPhase);
1423         m_scrollingLayer->addChild(m_scrollingContentsLayer.get());
1424     } else {
1425         compositor().willRemoveScrollingLayerWithBacking(m_owningLayer, *this);
1426
1427         willDestroyLayer(m_scrollingLayer.get());
1428         willDestroyLayer(m_scrollingContentsLayer.get());
1429         m_scrollingLayer = nullptr;
1430         m_scrollingContentsLayer = nullptr;
1431     }
1432
1433     m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
1434     m_graphicsLayer->setNeedsDisplay(); // Because painting phases changed.
1435
1436     if (m_scrollingLayer)
1437         compositor().didAddScrollingLayer(m_owningLayer);
1438     
1439     return true;
1440 }
1441
1442 void RenderLayerBacking::detachFromScrollingCoordinator()
1443 {
1444     if (!m_scrollingNodeID && !m_viewportConstrainedNodeID)
1445         return;
1446
1447     ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer);
1448     if (!scrollingCoordinator)
1449         return;
1450
1451     if (m_scrollingNodeID)
1452         scrollingCoordinator->detachFromStateTree(m_scrollingNodeID);
1453
1454     if (m_viewportConstrainedNodeID)
1455         scrollingCoordinator->detachFromStateTree(m_viewportConstrainedNodeID);
1456
1457     m_scrollingNodeID = 0;
1458     m_viewportConstrainedNodeID = 0;
1459 }
1460
1461 GraphicsLayerPaintingPhase RenderLayerBacking::paintingPhaseForPrimaryLayer() const
1462 {
1463     unsigned phase = 0;
1464     if (!m_backgroundLayer)
1465         phase |= GraphicsLayerPaintBackground;
1466     if (!m_foregroundLayer)
1467         phase |= GraphicsLayerPaintForeground;
1468     if (!m_maskLayer)
1469         phase |= GraphicsLayerPaintMask;
1470
1471     if (m_scrollingContentsLayer) {
1472         phase &= ~GraphicsLayerPaintForeground;
1473         phase |= GraphicsLayerPaintCompositedScroll;
1474     }
1475
1476     return static_cast<GraphicsLayerPaintingPhase>(phase);
1477 }
1478
1479 float RenderLayerBacking::compositingOpacity(float rendererOpacity) const
1480 {
1481     float finalOpacity = rendererOpacity;
1482     
1483     for (RenderLayer* curr = m_owningLayer.parent(); curr; curr = curr->parent()) {
1484         // We only care about parents that are stacking contexts.
1485         // Recall that opacity creates stacking context.
1486         if (!curr->isStackingContainer())
1487             continue;
1488         
1489         // If we found a compositing layer, we want to compute opacity
1490         // relative to it. So we can break here.
1491         if (curr->isComposited())
1492             break;
1493         
1494         finalOpacity *= curr->renderer().opacity();
1495     }
1496
1497     return finalOpacity;
1498 }
1499
1500 // FIXME: Code is duplicated in RenderLayer. Also, we should probably not consider filters a box decoration here.
1501 static inline bool hasBoxDecorations(const RenderStyle& style)
1502 {
1503     return style.hasBorder() || style.hasBorderRadius() || style.hasOutline() || style.hasAppearance() || style.boxShadow() || style.hasFilter();
1504 }
1505
1506 static bool canCreateTiledImage(const RenderStyle& style)
1507 {
1508     const FillLayer* fillLayer = style.backgroundLayers();
1509     if (fillLayer->next())
1510         return false;
1511
1512     if (!fillLayer->imagesAreLoaded())
1513         return false;
1514
1515     if (fillLayer->attachment() != ScrollBackgroundAttachment)
1516         return false;
1517
1518     Color color = style.visitedDependentColor(CSSPropertyBackgroundColor);
1519
1520     // FIXME: Allow color+image compositing when it makes sense.
1521     // For now bailing out.
1522     if (color.isValid() && color.alpha())
1523         return false;
1524
1525     StyleImage* styleImage = fillLayer->image();
1526
1527     // FIXME: support gradients with isGeneratedImage.
1528     if (!styleImage->isCachedImage())
1529         return false;
1530
1531     Image* image = styleImage->cachedImage()->image();
1532     if (!image->isBitmapImage())
1533         return false;
1534
1535     return true;
1536 }
1537
1538 static bool hasBoxDecorationsOrBackgroundImage(const RenderStyle& style)
1539 {
1540     if (hasBoxDecorations(style))
1541         return true;
1542
1543     if (!style.hasBackgroundImage())
1544         return false;
1545
1546     return !GraphicsLayer::supportsContentsTiling() || !canCreateTiledImage(style);
1547 }
1548
1549 static inline bool hasPerspectiveOrPreserves3D(const RenderStyle& style)
1550 {
1551     return style.hasPerspective() || style.preserves3D();
1552 }
1553
1554 Color RenderLayerBacking::rendererBackgroundColor() const
1555 {
1556     const auto& backgroundRenderer = renderer().isRoot() ? renderer().rendererForRootBackground() : renderer();
1557     return backgroundRenderer.style().visitedDependentColor(CSSPropertyBackgroundColor);
1558 }
1559
1560 void RenderLayerBacking::updateDirectlyCompositedBackgroundColor(bool isSimpleContainer, bool& didUpdateContentsRect)
1561 {
1562     if (!isSimpleContainer) {
1563         m_graphicsLayer->setContentsToSolidColor(Color());
1564         return;
1565     }
1566
1567     Color backgroundColor = rendererBackgroundColor();
1568
1569     // An unset (invalid) color will remove the solid color.
1570     m_graphicsLayer->setContentsToSolidColor(backgroundColor);
1571     FloatRect contentsRect = backgroundBoxForPainting();
1572     m_graphicsLayer->setContentsRect(contentsRect);
1573     m_graphicsLayer->setContentsClippingRect(contentsRect);
1574     didUpdateContentsRect = true;
1575 }
1576
1577 void RenderLayerBacking::updateDirectlyCompositedBackgroundImage(bool isSimpleContainer, bool& didUpdateContentsRect)
1578 {
1579     if (!GraphicsLayer::supportsContentsTiling())
1580         return;
1581
1582     if (isDirectlyCompositedImage())
1583         return;
1584
1585     const RenderStyle& style = renderer().style();
1586
1587     if (!isSimpleContainer || !style.hasBackgroundImage()) {
1588         m_graphicsLayer->setContentsToImage(0);
1589         return;
1590     }
1591
1592     FloatRect destRect = backgroundBoxForPainting();
1593     FloatPoint phase;
1594     FloatSize tileSize;
1595
1596     RefPtr<Image> image = style.backgroundLayers()->image()->cachedImage()->image();
1597     downcast<RenderBox>(renderer()).getGeometryForBackgroundImage(&renderer(), destRect, phase, tileSize);
1598     m_graphicsLayer->setContentsTileSize(tileSize);
1599     m_graphicsLayer->setContentsTilePhase(phase);
1600     m_graphicsLayer->setContentsRect(destRect);
1601     m_graphicsLayer->setContentsClippingRect(destRect);
1602     m_graphicsLayer->setContentsToImage(image.get());
1603     didUpdateContentsRect = true;
1604 }
1605
1606 void RenderLayerBacking::updateRootLayerConfiguration()
1607 {
1608     if (!m_usingTiledCacheLayer)
1609         return;
1610
1611     Color backgroundColor;
1612     bool viewIsTransparent = compositor().viewHasTransparentBackground(&backgroundColor);
1613
1614     if (m_backgroundLayerPaintsFixedRootBackground && m_backgroundLayer) {
1615         m_backgroundLayer->setBackgroundColor(backgroundColor);
1616         m_backgroundLayer->setContentsOpaque(!viewIsTransparent);
1617
1618         m_graphicsLayer->setBackgroundColor(Color());
1619         m_graphicsLayer->setContentsOpaque(false);
1620     } else {
1621         m_graphicsLayer->setBackgroundColor(backgroundColor);
1622         m_graphicsLayer->setContentsOpaque(!viewIsTransparent);
1623     }
1624 }
1625
1626 static bool supportsDirectBoxDecorationsComposition(const RenderLayerModelObject& renderer)
1627 {
1628     if (!GraphicsLayer::supportsBackgroundColorContent())
1629         return false;
1630
1631     const RenderStyle& style = renderer.style();
1632     if (renderer.hasClip())
1633         return false;
1634
1635     if (hasBoxDecorationsOrBackgroundImage(style))
1636         return false;
1637
1638     // FIXME: We can't create a directly composited background if this
1639     // layer will have children that intersect with the background layer.
1640     // A better solution might be to introduce a flattening layer if
1641     // we do direct box decoration composition.
1642     // https://bugs.webkit.org/show_bug.cgi?id=119461
1643     if (hasPerspectiveOrPreserves3D(style))
1644         return false;
1645
1646     // FIXME: we should be able to allow backgroundComposite; However since this is not a common use case it has been deferred for now.
1647     if (style.backgroundComposite() != CompositeSourceOver)
1648         return false;
1649
1650     if (style.backgroundClip() == TextFillBox)
1651         return false;
1652
1653     return true;
1654 }
1655
1656 bool RenderLayerBacking::paintsBoxDecorations() const
1657 {
1658     if (!m_owningLayer.hasVisibleBoxDecorations())
1659         return false;
1660
1661     if (!supportsDirectBoxDecorationsComposition(renderer()))
1662         return true;
1663
1664     return false;
1665 }
1666
1667 bool RenderLayerBacking::paintsChildren() const
1668 {
1669     if (m_owningLayer.hasVisibleContent() && m_owningLayer.hasNonEmptyChildRenderers())
1670         return true;
1671
1672     if (isPaintDestinationForDescendentLayers())
1673         return true;
1674
1675     return false;
1676 }
1677
1678 static bool isRestartedPlugin(RenderObject* renderer)
1679 {
1680     if (!renderer->isEmbeddedObject())
1681         return false;
1682
1683     Element* element = downcast<Element>(renderer->node());
1684     if (!is<HTMLPlugInElement>(element))
1685         return false;
1686
1687     return downcast<HTMLPlugInElement>(*element).isRestartedPlugin();
1688 }
1689
1690 static bool isCompositedPlugin(RenderObject* renderer)
1691 {
1692     return renderer->isEmbeddedObject() && toRenderEmbeddedObject(renderer)->allowsAcceleratedCompositing();
1693 }
1694
1695 // A "simple container layer" is a RenderLayer which has no visible content to render.
1696 // It may have no children, or all its children may be themselves composited.
1697 // This is a useful optimization, because it allows us to avoid allocating backing store.
1698 bool RenderLayerBacking::isSimpleContainerCompositingLayer() const
1699 {
1700     if (renderer().isRenderReplaced() && (!isCompositedPlugin(&renderer()) || isRestartedPlugin(&renderer())))
1701         return false;
1702
1703     if (paintsBoxDecorations() || paintsChildren())
1704         return false;
1705
1706     if (renderer().isRenderNamedFlowFragmentContainer())
1707         return false;
1708
1709     if (renderer().isRoot() && m_owningLayer.isolatesCompositedBlending())
1710         return false;
1711
1712     if (renderer().isRenderView()) {
1713         // Look to see if the root object has a non-simple background
1714         RenderObject* rootObject = renderer().document().documentElement() ? renderer().document().documentElement()->renderer() : 0;
1715         if (!rootObject)
1716             return false;
1717         
1718         // Reject anything that has a border, a border-radius or outline,
1719         // or is not a simple background (no background, or solid color).
1720         if (hasBoxDecorationsOrBackgroundImage(rootObject->style()))
1721             return false;
1722         
1723         // Now look at the body's renderer.
1724         HTMLElement* body = renderer().document().body();
1725         RenderObject* bodyObject = (body && body->hasTagName(bodyTag)) ? body->renderer() : 0;
1726         if (!bodyObject)
1727             return false;
1728         
1729         if (hasBoxDecorationsOrBackgroundImage(bodyObject->style()))
1730             return false;
1731     }
1732
1733     return true;
1734 }
1735
1736 static bool compositedWithOwnBackingStore(const RenderLayer* layer)
1737 {
1738     return layer->isComposited() && !layer->backing()->paintsIntoCompositedAncestor();
1739 }
1740
1741 static bool descendentLayerPaintsIntoAncestor(RenderLayer& parent)
1742 {
1743     // FIXME: We shouldn't be called with a stale z-order lists. See bug 85512.
1744     parent.updateLayerListsIfNeeded();
1745
1746 #if !ASSERT_DISABLED
1747     LayerListMutationDetector mutationChecker(&parent);
1748 #endif
1749
1750     if (Vector<RenderLayer*>* normalFlowList = parent.normalFlowList()) {
1751         size_t listSize = normalFlowList->size();
1752         for (size_t i = 0; i < listSize; ++i) {
1753             RenderLayer* curLayer = normalFlowList->at(i);
1754             if (!compositedWithOwnBackingStore(curLayer)
1755                 && (curLayer->isVisuallyNonEmpty() || descendentLayerPaintsIntoAncestor(*curLayer)))
1756                 return true;
1757         }
1758     }
1759
1760     if (parent.isStackingContainer()) {
1761         if (!parent.hasVisibleDescendant())
1762             return false;
1763
1764         // Use the m_hasCompositingDescendant bit to optimize?
1765         if (Vector<RenderLayer*>* negZOrderList = parent.negZOrderList()) {
1766             size_t listSize = negZOrderList->size();
1767             for (size_t i = 0; i < listSize; ++i) {
1768                 RenderLayer* curLayer = negZOrderList->at(i);
1769                 if (!compositedWithOwnBackingStore(curLayer)
1770                     && (curLayer->isVisuallyNonEmpty() || descendentLayerPaintsIntoAncestor(*curLayer)))
1771                     return true;
1772             }
1773         }
1774
1775         if (Vector<RenderLayer*>* posZOrderList = parent.posZOrderList()) {
1776             size_t listSize = posZOrderList->size();
1777             for (size_t i = 0; i < listSize; ++i) {
1778                 RenderLayer* curLayer = posZOrderList->at(i);
1779                 if (!compositedWithOwnBackingStore(curLayer)
1780                     && (curLayer->isVisuallyNonEmpty() || descendentLayerPaintsIntoAncestor(*curLayer)))
1781                     return true;
1782             }
1783         }
1784     }
1785
1786     return false;
1787 }
1788
1789 // Conservative test for having no rendered children.
1790 bool RenderLayerBacking::isPaintDestinationForDescendentLayers() const
1791 {
1792     return descendentLayerPaintsIntoAncestor(m_owningLayer);
1793 }
1794
1795 bool RenderLayerBacking::containsPaintedContent(bool isSimpleContainer) const
1796 {
1797     if (isSimpleContainer || paintsIntoWindow() || paintsIntoCompositedAncestor() || m_artificiallyInflatedBounds || m_owningLayer.isReflection())
1798         return false;
1799
1800     if (isDirectlyCompositedImage())
1801         return false;
1802
1803     // FIXME: we could optimize cases where the image, video or canvas is known to fill the border box entirely,
1804     // and set background color on the layer in that case, instead of allocating backing store and painting.
1805 #if ENABLE(VIDEO)
1806     if (renderer().isVideo() && toRenderVideo(renderer()).shouldDisplayVideo())
1807         return m_owningLayer.hasBoxDecorationsOrBackground();
1808 #endif
1809
1810 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
1811     if (renderer().isCanvas() && canvasCompositingStrategy(renderer()) == CanvasAsLayerContents)
1812         return m_owningLayer.hasBoxDecorationsOrBackground();
1813 #endif
1814
1815     return true;
1816 }
1817
1818 // An image can be directly compositing if it's the sole content of the layer, and has no box decorations
1819 // that require painting. Direct compositing saves backing store.
1820 bool RenderLayerBacking::isDirectlyCompositedImage() const
1821 {
1822     if (!is<RenderImage>(renderer()) || is<RenderMedia>(renderer()) || m_owningLayer.hasBoxDecorationsOrBackground() || renderer().hasClip())
1823         return false;
1824
1825     auto& imageRenderer = downcast<RenderImage>(renderer());
1826     if (CachedImage* cachedImage = imageRenderer.cachedImage()) {
1827         if (!cachedImage->hasImage())
1828             return false;
1829
1830         Image* image = cachedImage->imageForRenderer(&imageRenderer);
1831         if (!image->isBitmapImage())
1832             return false;
1833
1834         if (image->orientationForCurrentFrame() != DefaultImageOrientation)
1835             return false;
1836
1837         return m_graphicsLayer->shouldDirectlyCompositeImage(image);
1838     }
1839
1840     return false;
1841 }
1842
1843 void RenderLayerBacking::contentChanged(ContentChangeType changeType)
1844 {
1845     if ((changeType == ImageChanged) && isDirectlyCompositedImage()) {
1846         updateImageContents();
1847         return;
1848     }
1849
1850     if ((changeType == BackgroundImageChanged) && canCreateTiledImage(renderer().style()))
1851         updateGeometry();
1852
1853     if ((changeType == MaskImageChanged) && m_maskLayer) {
1854         // The composited layer bounds relies on box->maskClipRect(), which changes
1855         // when the mask image becomes available.
1856         updateAfterLayout(CompositingChildrenOnly | IsUpdateRoot);
1857     }
1858
1859 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
1860     if ((changeType == CanvasChanged || changeType == CanvasPixelsChanged) && renderer().isCanvas() && canvasCompositingStrategy(renderer()) == CanvasAsLayerContents) {
1861         m_graphicsLayer->setContentsNeedsDisplay();
1862         return;
1863     }
1864 #endif
1865 }
1866
1867 void RenderLayerBacking::updateImageContents()
1868 {
1869     auto& imageRenderer = downcast<RenderImage>(renderer());
1870
1871     CachedImage* cachedImage = imageRenderer.cachedImage();
1872     if (!cachedImage)
1873         return;
1874
1875     Image* image = cachedImage->imageForRenderer(&imageRenderer);
1876     if (!image)
1877         return;
1878
1879     // We have to wait until the image is fully loaded before setting it on the layer.
1880     if (!cachedImage->isLoaded())
1881         return;
1882
1883     // This is a no-op if the layer doesn't have an inner layer for the image.
1884     m_graphicsLayer->setContentsRect(snappedIntRect(contentsBox()));
1885
1886     LayoutRect contentsClippingRect = imageRenderer.contentBoxRect();
1887     contentsClippingRect.move(contentOffsetInCompostingLayer());
1888     m_graphicsLayer->setContentsClippingRect(snappedIntRect(contentsClippingRect));
1889
1890     m_graphicsLayer->setContentsToImage(image);
1891     bool isSimpleContainer = false;
1892     updateDrawsContent(isSimpleContainer);
1893     
1894     // Image animation is "lazy", in that it automatically stops unless someone is drawing
1895     // the image. So we have to kick the animation each time; this has the downside that the
1896     // image will keep animating, even if its layer is not visible.
1897     image->startAnimation();
1898 }
1899
1900 FloatPoint3D RenderLayerBacking::computeTransformOriginForPainting(const LayoutRect& borderBox) const
1901 {
1902     const RenderStyle& style = renderer().style();
1903     float deviceScaleFactor = this->deviceScaleFactor();
1904
1905     FloatPoint3D origin;
1906     origin.setX(roundToDevicePixel(floatValueForLength(style.transformOriginX(), borderBox.width()), deviceScaleFactor));
1907     origin.setY(roundToDevicePixel(floatValueForLength(style.transformOriginY(), borderBox.height()), deviceScaleFactor));
1908     origin.setZ(style.transformOriginZ());
1909
1910     return origin;
1911 }
1912
1913 // Return the offset from the top-left of this compositing layer at which the renderer's contents are painted.
1914 LayoutSize RenderLayerBacking::contentOffsetInCompostingLayer() const
1915 {
1916     return LayoutSize(-m_compositedBounds.x(), -m_compositedBounds.y()) + m_devicePixelFractionFromRenderer;
1917 }
1918
1919 LayoutRect RenderLayerBacking::contentsBox() const
1920 {
1921     if (!is<RenderBox>(renderer()))
1922         return LayoutRect();
1923
1924     auto& renderBox = downcast<RenderBox>(renderer());
1925     LayoutRect contentsRect;
1926 #if ENABLE(VIDEO)
1927     if (is<RenderVideo>(renderBox))
1928         contentsRect = downcast<RenderVideo>(renderBox).videoBox();
1929     else
1930 #endif
1931     if (is<RenderReplaced>(renderBox)) {
1932         RenderReplaced& renderReplaced = downcast<RenderReplaced>(renderBox);
1933         contentsRect = renderReplaced.replacedContentRect(renderBox.intrinsicSize());
1934     } else
1935         contentsRect = renderBox.contentBoxRect();
1936
1937     contentsRect.move(contentOffsetInCompostingLayer());
1938     return contentsRect;
1939 }
1940
1941 static LayoutRect backgroundRectForBox(const RenderBox& box)
1942 {
1943     switch (box.style().backgroundClip()) {
1944     case BorderFillBox:
1945         return box.borderBoxRect();
1946     case PaddingFillBox:
1947         return box.paddingBoxRect();
1948     case ContentFillBox:
1949         return box.contentBoxRect();
1950     case TextFillBox:
1951         break;
1952     }
1953
1954     ASSERT_NOT_REACHED();
1955     return LayoutRect();
1956 }
1957
1958 FloatRect RenderLayerBacking::backgroundBoxForPainting() const
1959 {
1960     if (!is<RenderBox>(renderer()))
1961         return FloatRect();
1962
1963     LayoutRect backgroundBox = backgroundRectForBox(downcast<RenderBox>(renderer()));
1964     backgroundBox.move(contentOffsetInCompostingLayer());
1965     return snapRectToDevicePixels(backgroundBox, deviceScaleFactor());
1966 }
1967
1968 GraphicsLayer* RenderLayerBacking::parentForSublayers() const
1969 {
1970     if (m_scrollingContentsLayer)
1971         return m_scrollingContentsLayer.get();
1972
1973 #if PLATFORM(IOS)
1974     // FIXME: Can we remove this iOS-specific code path?
1975     if (GraphicsLayer* clippingLayer = this->clippingLayer())
1976         return clippingLayer;
1977     return m_graphicsLayer.get();
1978 #else
1979     return m_childContainmentLayer ? m_childContainmentLayer.get() : m_graphicsLayer.get();
1980 #endif
1981 }
1982
1983 GraphicsLayer* RenderLayerBacking::childForSuperlayers() const
1984 {
1985     if (m_ancestorClippingLayer)
1986         return m_ancestorClippingLayer.get();
1987
1988     if (m_contentsContainmentLayer)
1989         return m_contentsContainmentLayer.get();
1990     
1991     return m_graphicsLayer.get();
1992 }
1993
1994 bool RenderLayerBacking::paintsIntoWindow() const
1995 {
1996     if (m_usingTiledCacheLayer)
1997         return false;
1998
1999     if (m_owningLayer.isRootLayer()) {
2000 #if PLATFORM(IOS) || USE(COORDINATED_GRAPHICS)
2001         if (compositor().inForcedCompositingMode())
2002             return false;
2003 #endif
2004
2005         return compositor().rootLayerAttachment() != RenderLayerCompositor::RootLayerAttachedViaEnclosingFrame;
2006     }
2007     
2008     return false;
2009 }
2010
2011 void RenderLayerBacking::setRequiresOwnBackingStore(bool requiresOwnBacking)
2012 {
2013     if (requiresOwnBacking == m_requiresOwnBackingStore)
2014         return;
2015     
2016     m_requiresOwnBackingStore = requiresOwnBacking;
2017
2018     // This affects the answer to paintsIntoCompositedAncestor(), which in turn affects
2019     // cached clip rects, so when it changes we have to clear clip rects on descendants.
2020     m_owningLayer.clearClipRectsIncludingDescendants(PaintingClipRects);
2021     m_owningLayer.computeRepaintRectsIncludingDescendants();
2022     
2023     compositor().repaintInCompositedAncestor(m_owningLayer, compositedBounds());
2024 }
2025
2026 void RenderLayerBacking::setContentsNeedDisplay(GraphicsLayer::ShouldClipToLayer shouldClip)
2027 {
2028     ASSERT(!paintsIntoCompositedAncestor());
2029
2030     FrameView& frameView = owningLayer().renderer().view().frameView();
2031     if (m_isMainFrameRenderViewLayer && frameView.isTrackingRepaints())
2032         frameView.addTrackedRepaintRect(owningLayer().absoluteBoundingBoxForPainting());
2033     
2034     if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
2035         // By default, setNeedsDisplay will clip to the size of the GraphicsLayer, which does not include margin tiles.
2036         // So if the TiledBacking has a margin that needs to be invalidated, we need to send in a rect to setNeedsDisplayInRect
2037         // that is large enough to include the margin. TiledBacking::bounds() includes the margin.
2038         TiledBacking* tiledBacking = this->tiledBacking();
2039         FloatRect rectToRepaint = tiledBacking ? tiledBacking->bounds() : FloatRect(FloatPoint(0, 0), m_graphicsLayer->size());
2040         m_graphicsLayer->setNeedsDisplayInRect(rectToRepaint, shouldClip);
2041     }
2042     
2043     if (m_foregroundLayer && m_foregroundLayer->drawsContent())
2044         m_foregroundLayer->setNeedsDisplay();
2045
2046     if (m_backgroundLayer && m_backgroundLayer->drawsContent())
2047         m_backgroundLayer->setNeedsDisplay();
2048
2049     if (m_maskLayer && m_maskLayer->drawsContent())
2050         m_maskLayer->setNeedsDisplay();
2051
2052     if (m_scrollingContentsLayer && m_scrollingContentsLayer->drawsContent())
2053         m_scrollingContentsLayer->setNeedsDisplay();
2054 }
2055
2056 // r is in the coordinate space of the layer's render object
2057 void RenderLayerBacking::setContentsNeedDisplayInRect(const LayoutRect& r, GraphicsLayer::ShouldClipToLayer shouldClip)
2058 {
2059     ASSERT(!paintsIntoCompositedAncestor());
2060
2061     FloatRect pixelSnappedRectForPainting = snapRectToDevicePixels(r, deviceScaleFactor());
2062     FrameView& frameView = owningLayer().renderer().view().frameView();
2063     if (m_isMainFrameRenderViewLayer && frameView.isTrackingRepaints())
2064         frameView.addTrackedRepaintRect(pixelSnappedRectForPainting);
2065
2066     if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
2067         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2068         layerDirtyRect.move(-m_graphicsLayer->offsetFromRenderer() + m_devicePixelFractionFromRenderer);
2069         m_graphicsLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2070     }
2071
2072     if (m_foregroundLayer && m_foregroundLayer->drawsContent()) {
2073         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2074         layerDirtyRect.move(-m_foregroundLayer->offsetFromRenderer() + m_devicePixelFractionFromRenderer);
2075         m_foregroundLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2076     }
2077
2078     // FIXME: need to split out repaints for the background.
2079     if (m_backgroundLayer && m_backgroundLayer->drawsContent()) {
2080         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2081         layerDirtyRect.move(-m_backgroundLayer->offsetFromRenderer() + m_devicePixelFractionFromRenderer);
2082         m_backgroundLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2083     }
2084
2085     if (m_maskLayer && m_maskLayer->drawsContent()) {
2086         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2087         layerDirtyRect.move(-m_maskLayer->offsetFromRenderer() + m_devicePixelFractionFromRenderer);
2088         m_maskLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2089     }
2090
2091     if (m_scrollingContentsLayer && m_scrollingContentsLayer->drawsContent()) {
2092         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2093         layerDirtyRect.move(-m_scrollingContentsLayer->offsetFromRenderer() + m_devicePixelFractionFromRenderer);
2094 #if PLATFORM(IOS)
2095         // Account for the fact that RenderLayerBacking::updateGeometry() bakes scrollOffset into offsetFromRenderer on iOS.
2096         layerDirtyRect.move(-m_owningLayer.scrollOffset() + m_devicePixelFractionFromRenderer);
2097 #endif
2098         m_scrollingContentsLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2099     }
2100 }
2101
2102 void RenderLayerBacking::paintIntoLayer(const GraphicsLayer* graphicsLayer, GraphicsContext* context,
2103     const IntRect& paintDirtyRect, // In the coords of rootLayer.
2104     PaintBehavior paintBehavior, GraphicsLayerPaintingPhase paintingPhase)
2105 {
2106     if (paintsIntoWindow() || paintsIntoCompositedAncestor()) {
2107 #if !PLATFORM(IOS)
2108         // FIXME: Looks like the CALayer tree is out of sync with the GraphicsLayer heirarchy
2109         // when pages are restored from the PageCache.
2110         // <rdar://problem/8712587> ASSERT: When Going Back to Page with Plugins in PageCache
2111         ASSERT_NOT_REACHED();
2112 #endif
2113         return;
2114     }
2115
2116     FontCachePurgePreventer fontCachePurgePreventer;
2117     
2118     RenderLayer::PaintLayerFlags paintFlags = 0;
2119     if (paintingPhase & GraphicsLayerPaintBackground)
2120         paintFlags |= RenderLayer::PaintLayerPaintingCompositingBackgroundPhase;
2121     if (paintingPhase & GraphicsLayerPaintForeground)
2122         paintFlags |= RenderLayer::PaintLayerPaintingCompositingForegroundPhase;
2123     if (paintingPhase & GraphicsLayerPaintMask)
2124         paintFlags |= RenderLayer::PaintLayerPaintingCompositingMaskPhase;
2125     if (paintingPhase & GraphicsLayerPaintOverflowContents)
2126         paintFlags |= RenderLayer::PaintLayerPaintingOverflowContents;
2127     if (paintingPhase & GraphicsLayerPaintCompositedScroll)
2128         paintFlags |= RenderLayer::PaintLayerPaintingCompositingScrollingPhase;
2129
2130     if (graphicsLayer == m_backgroundLayer.get())
2131         paintFlags |= (RenderLayer::PaintLayerPaintingRootBackgroundOnly | RenderLayer::PaintLayerPaintingCompositingForegroundPhase); // Need PaintLayerPaintingCompositingForegroundPhase to walk child layers.
2132     else if (compositor().fixedRootBackgroundLayer())
2133         paintFlags |= RenderLayer::PaintLayerPaintingSkipRootBackground;
2134
2135 #ifndef NDEBUG
2136     RenderElement::SetLayoutNeededForbiddenScope forbidSetNeedsLayout(&renderer());
2137 #endif
2138
2139     FrameView::PaintingState paintingState;
2140     if (m_owningLayer.isRootLayer())
2141         renderer().view().frameView().willPaintContents(context, paintDirtyRect, paintingState);
2142
2143     // FIXME: GraphicsLayers need a way to split for RenderRegions.
2144     RenderLayer::LayerPaintingInfo paintingInfo(&m_owningLayer, paintDirtyRect, paintBehavior, m_devicePixelFractionFromRenderer);
2145     m_owningLayer.paintLayerContents(context, paintingInfo, paintFlags);
2146
2147     if (m_owningLayer.containsDirtyOverlayScrollbars())
2148         m_owningLayer.paintLayerContents(context, paintingInfo, paintFlags | RenderLayer::PaintLayerPaintingOverlayScrollbars);
2149
2150     if (m_owningLayer.isRootLayer())
2151         renderer().view().frameView().didPaintContents(context, paintDirtyRect, paintingState);
2152
2153     compositor().didPaintBacking(this);
2154
2155     ASSERT(!m_owningLayer.m_usedTransparency);
2156 }
2157
2158 static void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
2159 {
2160     if (!scrollbar)
2161         return;
2162
2163     context.save();
2164     const IntRect& scrollbarRect = scrollbar->frameRect();
2165     context.translate(-scrollbarRect.x(), -scrollbarRect.y());
2166     IntRect transformedClip = clip;
2167     transformedClip.moveBy(scrollbarRect.location());
2168     scrollbar->paint(&context, transformedClip);
2169     context.restore();
2170 }
2171
2172 // Up-call from compositing layer drawing callback.
2173 void RenderLayerBacking::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, GraphicsLayerPaintingPhase paintingPhase, const FloatRect& clip)
2174 {
2175 #ifndef NDEBUG
2176     if (Page* page = renderer().frame().page())
2177         page->setIsPainting(true);
2178 #endif
2179
2180     // The dirtyRect is in the coords of the painting root.
2181     FloatRect adjustedClipRect = clip;
2182     adjustedClipRect.move(-m_devicePixelFractionFromRenderer);
2183     IntRect dirtyRect = enclosingIntRect(adjustedClipRect);
2184
2185     if (graphicsLayer == m_graphicsLayer.get()
2186         || graphicsLayer == m_foregroundLayer.get()
2187         || graphicsLayer == m_backgroundLayer.get()
2188         || graphicsLayer == m_maskLayer.get()
2189         || graphicsLayer == m_scrollingContentsLayer.get()) {
2190         InspectorInstrumentation::willPaint(&renderer());
2191
2192         if (!(paintingPhase & GraphicsLayerPaintOverflowContents))
2193             dirtyRect.intersect(enclosingIntRect(compositedBoundsIncludingMargin()));
2194
2195         // We have to use the same root as for hit testing, because both methods can compute and cache clipRects.
2196         paintIntoLayer(graphicsLayer, &context, dirtyRect, PaintBehaviorNormal, paintingPhase);
2197
2198         InspectorInstrumentation::didPaint(&renderer(), dirtyRect);
2199     } else if (graphicsLayer == layerForHorizontalScrollbar()) {
2200         paintScrollbar(m_owningLayer.horizontalScrollbar(), context, dirtyRect);
2201     } else if (graphicsLayer == layerForVerticalScrollbar()) {
2202         paintScrollbar(m_owningLayer.verticalScrollbar(), context, dirtyRect);
2203     } else if (graphicsLayer == layerForScrollCorner()) {
2204         const LayoutRect& scrollCornerAndResizer = m_owningLayer.scrollCornerAndResizerRect();
2205         context.save();
2206         context.translate(-scrollCornerAndResizer.x(), -scrollCornerAndResizer.y());
2207         LayoutRect transformedClip = LayoutRect(clip);
2208         transformedClip.moveBy(scrollCornerAndResizer.location());
2209         m_owningLayer.paintScrollCorner(&context, IntPoint(), snappedIntRect(transformedClip));
2210         m_owningLayer.paintResizer(&context, IntPoint(), transformedClip);
2211         context.restore();
2212     }
2213 #ifndef NDEBUG
2214     if (Page* page = renderer().frame().page())
2215         page->setIsPainting(false);
2216 #endif
2217 }
2218
2219 float RenderLayerBacking::pageScaleFactor() const
2220 {
2221     return compositor().pageScaleFactor();
2222 }
2223
2224 float RenderLayerBacking::zoomedOutPageScaleFactor() const
2225 {
2226     return compositor().zoomedOutPageScaleFactor();
2227 }
2228
2229 float RenderLayerBacking::deviceScaleFactor() const
2230 {
2231     return compositor().deviceScaleFactor();
2232 }
2233
2234 float RenderLayerBacking::contentsScaleMultiplierForNewTiles(const GraphicsLayer* layer) const
2235 {
2236     return compositor().contentsScaleMultiplierForNewTiles(layer);
2237 }
2238
2239 bool RenderLayerBacking::paintsOpaquelyAtNonIntegralScales(const GraphicsLayer*) const
2240 {
2241     return m_isMainFrameRenderViewLayer;
2242 }
2243
2244 void RenderLayerBacking::didCommitChangesForLayer(const GraphicsLayer* layer) const
2245 {
2246     compositor().didFlushChangesForLayer(m_owningLayer, layer);
2247 }
2248
2249 bool RenderLayerBacking::getCurrentTransform(const GraphicsLayer* graphicsLayer, TransformationMatrix& transform) const
2250 {
2251     GraphicsLayer* transformedLayer = m_contentsContainmentLayer.get() ? m_contentsContainmentLayer.get() : m_graphicsLayer.get();
2252     if (graphicsLayer != transformedLayer)
2253         return false;
2254
2255     if (m_owningLayer.hasTransform()) {
2256         transform = m_owningLayer.currentTransform(RenderStyle::ExcludeTransformOrigin);
2257         return true;
2258     }
2259     return false;
2260 }
2261
2262 bool RenderLayerBacking::isTrackingRepaints() const
2263 {
2264     return static_cast<GraphicsLayerClient&>(compositor()).isTrackingRepaints();
2265 }
2266
2267 bool RenderLayerBacking::shouldSkipLayerInDump(const GraphicsLayer* layer, LayerTreeAsTextBehavior) const
2268 {
2269     // Skip the root tile cache's flattening layer.
2270     return m_isMainFrameRenderViewLayer && layer && layer == m_childContainmentLayer.get();
2271 }
2272
2273 bool RenderLayerBacking::shouldDumpPropertyForLayer(const GraphicsLayer* layer, const char* propertyName) const
2274 {
2275     // For backwards compatibility with WebKit1 and other platforms,
2276     // skip some properties on the root tile cache.
2277     if (m_isMainFrameRenderViewLayer && layer == m_graphicsLayer.get()) {
2278         if (!strcmp(propertyName, "drawsContent"))
2279             return false;
2280
2281         // Background color could be of interest to tests or other dumpers if it's non-white.
2282         if (!strcmp(propertyName, "backgroundColor") && layer->backgroundColor() == Color::white)
2283             return false;
2284
2285         // The root tile cache's repaints will show up at the top with FrameView's,
2286         // so don't dump them twice.
2287         if (!strcmp(propertyName, "repaintRects"))
2288             return false;
2289     }
2290
2291     return true;
2292 }
2293
2294 bool RenderLayerBacking::shouldAggressivelyRetainTiles(const GraphicsLayer*) const
2295 {
2296     // Only the main frame TileController has enough information about in-window state to
2297     // correctly implement aggressive tile retention.
2298     if (!m_isMainFrameRenderViewLayer)
2299         return false;
2300
2301     if (Page* page = renderer().frame().page())
2302         return page->settings().aggressiveTileRetentionEnabled();
2303     return false;
2304 }
2305
2306 bool RenderLayerBacking::shouldTemporarilyRetainTileCohorts(const GraphicsLayer*) const
2307 {
2308     if (Page* page = renderer().frame().page())
2309         return page->settings().temporaryTileCohortRetentionEnabled();
2310     return true;
2311 }
2312
2313 #ifndef NDEBUG
2314 void RenderLayerBacking::verifyNotPainting()
2315 {
2316     ASSERT(!renderer().frame().page() || !renderer().frame().page()->isPainting());
2317 }
2318 #endif
2319
2320 bool RenderLayerBacking::startAnimation(double timeOffset, const Animation* anim, const KeyframeList& keyframes)
2321 {
2322     bool hasOpacity = keyframes.containsProperty(CSSPropertyOpacity);
2323     bool hasTransform = renderer().isBox() && keyframes.containsProperty(CSSPropertyWebkitTransform);
2324     bool hasFilter = keyframes.containsProperty(CSSPropertyWebkitFilter);
2325
2326     if (!hasOpacity && !hasTransform && !hasFilter)
2327         return false;
2328     
2329     KeyframeValueList transformVector(AnimatedPropertyWebkitTransform);
2330     KeyframeValueList opacityVector(AnimatedPropertyOpacity);
2331     KeyframeValueList filterVector(AnimatedPropertyWebkitFilter);
2332
2333     size_t numKeyframes = keyframes.size();
2334     for (size_t i = 0; i < numKeyframes; ++i) {
2335         const KeyframeValue& currentKeyframe = keyframes[i];
2336         const RenderStyle* keyframeStyle = currentKeyframe.style();
2337         double key = currentKeyframe.key();
2338
2339         if (!keyframeStyle)
2340             continue;
2341             
2342         TimingFunction* tf = currentKeyframe.timingFunction(keyframes.animationName());
2343         
2344         bool isFirstOrLastKeyframe = key == 0 || key == 1;
2345         if ((hasTransform && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitTransform))
2346             transformVector.insert(TransformAnimationValue::create(key, keyframeStyle->transform(), tf));
2347
2348         if ((hasOpacity && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyOpacity))
2349             opacityVector.insert(FloatAnimationValue::create(key, keyframeStyle->opacity(), tf));
2350
2351         if ((hasFilter && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitFilter))
2352             filterVector.insert(FilterAnimationValue::create(key, keyframeStyle->filter(), tf));
2353     }
2354
2355     if (renderer().frame().page() && !renderer().frame().page()->settings().acceleratedCompositedAnimationsEnabled())
2356         return false;
2357
2358     bool didAnimate = false;
2359
2360     if (hasTransform && m_graphicsLayer->addAnimation(transformVector, downcast<RenderBox>(renderer()).pixelSnappedBorderBoxRect().size(), anim, keyframes.animationName(), timeOffset))
2361         didAnimate = true;
2362
2363     if (hasOpacity && m_graphicsLayer->addAnimation(opacityVector, IntSize(), anim, keyframes.animationName(), timeOffset))
2364         didAnimate = true;
2365
2366     if (hasFilter && m_graphicsLayer->addAnimation(filterVector, IntSize(), anim, keyframes.animationName(), timeOffset))
2367         didAnimate = true;
2368
2369     return didAnimate;
2370 }
2371
2372 void RenderLayerBacking::animationPaused(double timeOffset, const String& animationName)
2373 {
2374     m_graphicsLayer->pauseAnimation(animationName, timeOffset);
2375 }
2376
2377 void RenderLayerBacking::animationFinished(const String& animationName)
2378 {
2379     m_graphicsLayer->removeAnimation(animationName);
2380 }
2381
2382 bool RenderLayerBacking::startTransition(double timeOffset, CSSPropertyID property, const RenderStyle* fromStyle, const RenderStyle* toStyle)
2383 {
2384     bool didAnimate = false;
2385
2386     ASSERT(property != CSSPropertyInvalid);
2387
2388     if (property == CSSPropertyOpacity) {
2389         const Animation* opacityAnim = toStyle->transitionForProperty(CSSPropertyOpacity);
2390         if (opacityAnim && !opacityAnim->isEmptyOrZeroDuration()) {
2391             KeyframeValueList opacityVector(AnimatedPropertyOpacity);
2392             opacityVector.insert(FloatAnimationValue::create(0, compositingOpacity(fromStyle->opacity())));
2393             opacityVector.insert(FloatAnimationValue::create(1, compositingOpacity(toStyle->opacity())));
2394             // The boxSize param is only used for transform animations (which can only run on RenderBoxes), so we pass an empty size here.
2395             if (m_graphicsLayer->addAnimation(opacityVector, FloatSize(), opacityAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyOpacity), timeOffset)) {
2396                 // To ensure that the correct opacity is visible when the animation ends, also set the final opacity.
2397                 updateOpacity(*toStyle);
2398                 didAnimate = true;
2399             }
2400         }
2401     }
2402
2403     if (property == CSSPropertyWebkitTransform && m_owningLayer.hasTransform()) {
2404         const Animation* transformAnim = toStyle->transitionForProperty(CSSPropertyWebkitTransform);
2405         if (transformAnim && !transformAnim->isEmptyOrZeroDuration()) {
2406             KeyframeValueList transformVector(AnimatedPropertyWebkitTransform);
2407             transformVector.insert(TransformAnimationValue::create(0, fromStyle->transform()));
2408             transformVector.insert(TransformAnimationValue::create(1, toStyle->transform()));
2409             if (m_graphicsLayer->addAnimation(transformVector, downcast<RenderBox>(renderer()).pixelSnappedBorderBoxRect().size(), transformAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyWebkitTransform), timeOffset)) {
2410                 // To ensure that the correct transform is visible when the animation ends, also set the final transform.
2411                 updateTransform(*toStyle);
2412                 didAnimate = true;
2413             }
2414         }
2415     }
2416
2417     if (property == CSSPropertyWebkitFilter && m_owningLayer.hasFilter()) {
2418         const Animation* filterAnim = toStyle->transitionForProperty(CSSPropertyWebkitFilter);
2419         if (filterAnim && !filterAnim->isEmptyOrZeroDuration()) {
2420             KeyframeValueList filterVector(AnimatedPropertyWebkitFilter);
2421             filterVector.insert(FilterAnimationValue::create(0, fromStyle->filter()));
2422             filterVector.insert(FilterAnimationValue::create(1, toStyle->filter()));
2423             if (m_graphicsLayer->addAnimation(filterVector, FloatSize(), filterAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyWebkitFilter), timeOffset)) {
2424                 // To ensure that the correct filter is visible when the animation ends, also set the final filter.
2425                 updateFilters(*toStyle);
2426                 didAnimate = true;
2427             }
2428         }
2429     }
2430
2431     return didAnimate;
2432 }
2433
2434 void RenderLayerBacking::transitionPaused(double timeOffset, CSSPropertyID property)
2435 {
2436     AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
2437     if (animatedProperty != AnimatedPropertyInvalid)
2438         m_graphicsLayer->pauseAnimation(GraphicsLayer::animationNameForTransition(animatedProperty), timeOffset);
2439 }
2440
2441 void RenderLayerBacking::transitionFinished(CSSPropertyID property)
2442 {
2443     AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
2444     if (animatedProperty != AnimatedPropertyInvalid)
2445         m_graphicsLayer->removeAnimation(GraphicsLayer::animationNameForTransition(animatedProperty));
2446 }
2447
2448 void RenderLayerBacking::notifyAnimationStarted(const GraphicsLayer*, const String&, double time)
2449 {
2450     renderer().animation().notifyAnimationStarted(renderer(), time);
2451 }
2452
2453 void RenderLayerBacking::notifyFlushRequired(const GraphicsLayer* layer)
2454 {
2455     if (renderer().documentBeingDestroyed())
2456         return;
2457     compositor().scheduleLayerFlush(layer->canThrottleLayerFlush());
2458 }
2459
2460 void RenderLayerBacking::notifyFlushBeforeDisplayRefresh(const GraphicsLayer* layer)
2461 {
2462     compositor().notifyFlushBeforeDisplayRefresh(layer);
2463 }
2464
2465 // This is used for the 'freeze' API, for testing only.
2466 void RenderLayerBacking::suspendAnimations(double time)
2467 {
2468     m_graphicsLayer->suspendAnimations(time);
2469 }
2470
2471 void RenderLayerBacking::resumeAnimations()
2472 {
2473     m_graphicsLayer->resumeAnimations();
2474 }
2475
2476 LayoutRect RenderLayerBacking::compositedBounds() const
2477 {
2478     return m_compositedBounds;
2479 }
2480
2481 void RenderLayerBacking::setCompositedBounds(const LayoutRect& bounds)
2482 {
2483     m_compositedBounds = bounds;
2484 }
2485
2486 LayoutRect RenderLayerBacking::compositedBoundsIncludingMargin() const
2487 {
2488     TiledBacking* tiledBacking = this->tiledBacking();
2489     if (!tiledBacking || !tiledBacking->hasMargins())
2490         return compositedBounds();
2491
2492     LayoutRect boundsIncludingMargin = compositedBounds();
2493     LayoutUnit leftMarginWidth = tiledBacking->leftMarginWidth();
2494     LayoutUnit topMarginHeight = tiledBacking->topMarginHeight();
2495
2496     boundsIncludingMargin.moveBy(LayoutPoint(-leftMarginWidth, -topMarginHeight));
2497     boundsIncludingMargin.expand(leftMarginWidth + tiledBacking->rightMarginWidth(), topMarginHeight + tiledBacking->bottomMarginHeight());
2498
2499     return boundsIncludingMargin;
2500 }
2501
2502 CSSPropertyID RenderLayerBacking::graphicsLayerToCSSProperty(AnimatedPropertyID property)
2503 {
2504     CSSPropertyID cssProperty = CSSPropertyInvalid;
2505     switch (property) {
2506         case AnimatedPropertyWebkitTransform:
2507             cssProperty = CSSPropertyWebkitTransform;
2508             break;
2509         case AnimatedPropertyOpacity:
2510             cssProperty = CSSPropertyOpacity;
2511             break;
2512         case AnimatedPropertyBackgroundColor:
2513             cssProperty = CSSPropertyBackgroundColor;
2514             break;
2515         case AnimatedPropertyWebkitFilter:
2516             cssProperty = CSSPropertyWebkitFilter;
2517             break;
2518         case AnimatedPropertyInvalid:
2519             ASSERT_NOT_REACHED();
2520     }
2521     return cssProperty;
2522 }
2523
2524 AnimatedPropertyID RenderLayerBacking::cssToGraphicsLayerProperty(CSSPropertyID cssProperty)
2525 {
2526     switch (cssProperty) {
2527         case CSSPropertyWebkitTransform:
2528             return AnimatedPropertyWebkitTransform;
2529         case CSSPropertyOpacity:
2530             return AnimatedPropertyOpacity;
2531         case CSSPropertyBackgroundColor:
2532             return AnimatedPropertyBackgroundColor;
2533         case CSSPropertyWebkitFilter:
2534             return AnimatedPropertyWebkitFilter;
2535         default:
2536             // It's fine if we see other css properties here; they are just not accelerated.
2537             break;
2538     }
2539     return AnimatedPropertyInvalid;
2540 }
2541
2542 CompositingLayerType RenderLayerBacking::compositingLayerType() const
2543 {
2544     if (m_graphicsLayer->usesContentsLayer())
2545         return MediaCompositingLayer;
2546
2547     if (m_graphicsLayer->drawsContent())
2548         return m_graphicsLayer->usingTiledBacking() ? TiledCompositingLayer : NormalCompositingLayer;
2549     
2550     return ContainerCompositingLayer;
2551 }
2552
2553 double RenderLayerBacking::backingStoreMemoryEstimate() const
2554 {
2555     double backingMemory;
2556     
2557     // m_ancestorClippingLayer, m_contentsContainmentLayer and m_childContainmentLayer are just used for masking or containment, so have no backing.
2558     backingMemory = m_graphicsLayer->backingStoreMemoryEstimate();
2559     if (m_foregroundLayer)
2560         backingMemory += m_foregroundLayer->backingStoreMemoryEstimate();
2561     if (m_backgroundLayer)
2562         backingMemory += m_backgroundLayer->backingStoreMemoryEstimate();
2563     if (m_maskLayer)
2564         backingMemory += m_maskLayer->backingStoreMemoryEstimate();
2565
2566     if (m_scrollingContentsLayer)
2567         backingMemory += m_scrollingContentsLayer->backingStoreMemoryEstimate();
2568
2569     if (m_layerForHorizontalScrollbar)
2570         backingMemory += m_layerForHorizontalScrollbar->backingStoreMemoryEstimate();
2571
2572     if (m_layerForVerticalScrollbar)
2573         backingMemory += m_layerForVerticalScrollbar->backingStoreMemoryEstimate();
2574
2575     if (m_layerForScrollCorner)
2576         backingMemory += m_layerForScrollCorner->backingStoreMemoryEstimate();
2577     
2578     return backingMemory;
2579 }
2580
2581 } // namespace WebCore