Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / rendering / compositing / CompositedLayerMapping.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 COMPUTER, 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 "core/rendering/compositing/CompositedLayerMapping.h"
29
30 #include "core/HTMLNames.h"
31 #include "core/fetch/ImageResource.h"
32 #include "core/frame/FrameView.h"
33 #include "core/html/HTMLCanvasElement.h"
34 #include "core/html/HTMLIFrameElement.h"
35 #include "core/html/HTMLMediaElement.h"
36 #include "core/html/canvas/CanvasRenderingContext.h"
37 #include "core/inspector/InspectorInstrumentation.h"
38 #include "core/inspector/InspectorNodeIds.h"
39 #include "core/inspector/InspectorTraceEvents.h"
40 #include "core/page/Chrome.h"
41 #include "core/page/ChromeClient.h"
42 #include "core/page/Page.h"
43 #include "core/page/scrolling/ScrollingCoordinator.h"
44 #include "core/plugins/PluginView.h"
45 #include "core/rendering/FilterEffectRenderer.h"
46 #include "core/rendering/RenderEmbeddedObject.h"
47 #include "core/rendering/RenderImage.h"
48 #include "core/rendering/RenderLayerStackingNodeIterator.h"
49 #include "core/rendering/RenderPart.h"
50 #include "core/rendering/RenderVideo.h"
51 #include "core/rendering/RenderView.h"
52 #include "core/rendering/compositing/RenderLayerCompositor.h"
53 #include "core/rendering/style/KeyframeList.h"
54 #include "platform/LengthFunctions.h"
55 #include "platform/RuntimeEnabledFeatures.h"
56 #include "platform/fonts/FontCache.h"
57 #include "platform/graphics/GraphicsContext.h"
58 #include "wtf/CurrentTime.h"
59 #include "wtf/text/StringBuilder.h"
60
61 namespace blink {
62
63 using namespace HTMLNames;
64
65 static IntRect clipBox(RenderBox* renderer);
66
67 static IntRect contentsRect(const RenderObject* renderer)
68 {
69     if (!renderer->isBox())
70         return IntRect();
71
72     return renderer->isVideo() ?
73         toRenderVideo(renderer)->videoBox() :
74         pixelSnappedIntRect(toRenderBox(renderer)->contentBoxRect());
75 }
76
77 static IntRect backgroundRect(const RenderObject* renderer)
78 {
79     if (!renderer->isBox())
80         return IntRect();
81
82     LayoutRect rect;
83     const RenderBox* box = toRenderBox(renderer);
84     EFillBox clip = box->style()->backgroundClip();
85     switch (clip) {
86     case BorderFillBox:
87         rect = box->borderBoxRect();
88         break;
89     case PaddingFillBox:
90         rect = box->paddingBoxRect();
91         break;
92     case ContentFillBox:
93         rect = box->contentBoxRect();
94         break;
95     case TextFillBox:
96         break;
97     }
98
99     return pixelSnappedIntRect(rect);
100 }
101
102 static inline bool isAcceleratedCanvas(const RenderObject* renderer)
103 {
104     if (renderer->isCanvas()) {
105         HTMLCanvasElement* canvas = toHTMLCanvasElement(renderer->node());
106         if (CanvasRenderingContext* context = canvas->renderingContext())
107             return context->isAccelerated();
108     }
109     return false;
110 }
111
112 static bool hasBoxDecorationsOrBackgroundImage(const RenderStyle* style)
113 {
114     return style->hasBoxDecorations() || style->hasBackgroundImage();
115 }
116
117 static bool contentLayerSupportsDirectBackgroundComposition(const RenderObject* renderer)
118 {
119     // No support for decorations - border, border-radius or outline.
120     // Only simple background - solid color or transparent.
121     if (hasBoxDecorationsOrBackgroundImage(renderer->style()))
122         return false;
123
124     // If there is no background, there is nothing to support.
125     if (!renderer->style()->hasBackground())
126         return true;
127
128     // Simple background that is contained within the contents rect.
129     return contentsRect(renderer).contains(backgroundRect(renderer));
130 }
131
132 static WebLayer* platformLayerForPlugin(RenderObject* renderer)
133 {
134     if (!renderer->isEmbeddedObject())
135         return 0;
136     Widget* widget = toRenderEmbeddedObject(renderer)->widget();
137     if (!widget || !widget->isPluginView())
138         return 0;
139     return toPluginView(widget)->platformLayer();
140
141 }
142
143 static inline bool isAcceleratedContents(RenderObject* renderer)
144 {
145     return isAcceleratedCanvas(renderer)
146         || (renderer->isEmbeddedObject() && toRenderEmbeddedObject(renderer)->requiresAcceleratedCompositing())
147         || renderer->isVideo();
148 }
149
150 // Get the scrolling coordinator in a way that works inside CompositedLayerMapping's destructor.
151 static ScrollingCoordinator* scrollingCoordinatorFromLayer(RenderLayer& layer)
152 {
153     Page* page = layer.renderer()->frame()->page();
154     if (!page)
155         return 0;
156
157     return page->scrollingCoordinator();
158 }
159
160 CompositedLayerMapping::CompositedLayerMapping(RenderLayer& layer)
161     : m_owningLayer(layer)
162     , m_pendingUpdateScope(GraphicsLayerUpdateNone)
163     , m_isMainFrameRenderViewLayer(false)
164     , m_requiresOwnBackingStoreForIntrinsicReasons(false)
165     , m_requiresOwnBackingStoreForAncestorReasons(false)
166     , m_backgroundLayerPaintsFixedRootBackground(false)
167     , m_scrollingContentsAreEmpty(false)
168 {
169     if (layer.isRootLayer() && renderer()->frame()->isMainFrame())
170         m_isMainFrameRenderViewLayer = true;
171
172     createPrimaryGraphicsLayer();
173 }
174
175 CompositedLayerMapping::~CompositedLayerMapping()
176 {
177     // Hits in compositing/squashing/squash-onto-nephew.html.
178     DisableCompositingQueryAsserts disabler;
179
180     // Do not leave the destroyed pointer dangling on any RenderLayers that painted to this mapping's squashing layer.
181     for (size_t i = 0; i < m_squashedLayers.size(); ++i) {
182         RenderLayer* oldSquashedLayer = m_squashedLayers[i].renderLayer;
183         if (oldSquashedLayer->groupedMapping() == this) {
184             oldSquashedLayer->setGroupedMapping(0, true);
185             oldSquashedLayer->setLostGroupedMapping(true);
186         }
187     }
188
189     updateClippingLayers(false, false);
190     updateOverflowControlsLayers(false, false, false, false);
191     updateChildTransformLayer(false);
192     updateForegroundLayer(false);
193     updateBackgroundLayer(false);
194     updateMaskLayer(false);
195     updateClippingMaskLayers(false);
196     updateScrollingLayers(false);
197     updateSquashingLayers(false);
198     destroyGraphicsLayers();
199 }
200
201 PassOwnPtr<GraphicsLayer> CompositedLayerMapping::createGraphicsLayer(CompositingReasons reasons)
202 {
203     GraphicsLayerFactory* graphicsLayerFactory = 0;
204     if (Page* page = renderer()->frame()->page())
205         graphicsLayerFactory = page->chrome().client().graphicsLayerFactory();
206
207     OwnPtr<GraphicsLayer> graphicsLayer = GraphicsLayer::create(graphicsLayerFactory, this);
208
209     graphicsLayer->setCompositingReasons(reasons);
210     if (Node* owningNode = m_owningLayer.renderer()->generatingNode())
211         graphicsLayer->setOwnerNodeId(InspectorNodeIds::idForNode(owningNode));
212
213     return graphicsLayer.release();
214 }
215
216 void CompositedLayerMapping::createPrimaryGraphicsLayer()
217 {
218     m_graphicsLayer = createGraphicsLayer(m_owningLayer.compositingReasons());
219
220 #if !OS(ANDROID)
221     if (m_isMainFrameRenderViewLayer)
222         m_graphicsLayer->contentLayer()->setDrawCheckerboardForMissingTiles(true);
223 #endif
224
225     updateOpacity(renderer()->style());
226     updateTransform(renderer()->style());
227     updateFilters(renderer()->style());
228
229     if (RuntimeEnabledFeatures::cssCompositingEnabled()) {
230         updateLayerBlendMode(renderer()->style());
231         updateIsRootForIsolatedGroup();
232     }
233 }
234
235 void CompositedLayerMapping::destroyGraphicsLayers()
236 {
237     if (m_graphicsLayer)
238         m_graphicsLayer->removeFromParent();
239
240     m_ancestorClippingLayer = nullptr;
241     m_graphicsLayer = nullptr;
242     m_foregroundLayer = nullptr;
243     m_backgroundLayer = nullptr;
244     m_childContainmentLayer = nullptr;
245     m_childTransformLayer = nullptr;
246     m_maskLayer = nullptr;
247     m_childClippingMaskLayer = nullptr;
248
249     m_scrollingLayer = nullptr;
250     m_scrollingContentsLayer = nullptr;
251     m_scrollingBlockSelectionLayer = nullptr;
252 }
253
254 void CompositedLayerMapping::updateOpacity(const RenderStyle* style)
255 {
256     m_graphicsLayer->setOpacity(compositingOpacity(style->opacity()));
257 }
258
259 void CompositedLayerMapping::updateTransform(const RenderStyle* style)
260 {
261     // FIXME: This could use m_owningLayer.transform(), but that currently has transform-origin
262     // baked into it, and we don't want that.
263     TransformationMatrix t;
264     if (m_owningLayer.hasTransform()) {
265         style->applyTransform(t, toRenderBox(renderer())->pixelSnappedBorderBoxRect().size(), RenderStyle::ExcludeTransformOrigin);
266         makeMatrixRenderable(t, compositor()->hasAcceleratedCompositing());
267     }
268
269     m_graphicsLayer->setTransform(t);
270 }
271
272 void CompositedLayerMapping::updateFilters(const RenderStyle* style)
273 {
274     m_graphicsLayer->setFilters(owningLayer().computeFilterOperations(style));
275 }
276
277 void CompositedLayerMapping::updateLayerBlendMode(const RenderStyle* style)
278 {
279     setBlendMode(style->blendMode());
280 }
281
282 void CompositedLayerMapping::updateIsRootForIsolatedGroup()
283 {
284     bool isolate = m_owningLayer.shouldIsolateCompositedDescendants();
285
286     // non stacking context layers should never isolate
287     ASSERT(m_owningLayer.stackingNode()->isStackingContext() || !isolate);
288
289     m_graphicsLayer->setIsRootForIsolatedGroup(isolate);
290 }
291
292 void CompositedLayerMapping::updateContentsOpaque()
293 {
294     // For non-root layers, background is always painted by the primary graphics layer.
295     ASSERT(m_isMainFrameRenderViewLayer || !m_backgroundLayer);
296     if (m_backgroundLayer) {
297         m_graphicsLayer->setContentsOpaque(false);
298         m_backgroundLayer->setContentsOpaque(m_owningLayer.backgroundIsKnownToBeOpaqueInRect(compositedBounds()));
299     } else {
300         m_graphicsLayer->setContentsOpaque(m_owningLayer.backgroundIsKnownToBeOpaqueInRect(compositedBounds()));
301     }
302 }
303
304 void CompositedLayerMapping::updateCompositedBounds()
305 {
306     ASSERT(m_owningLayer.compositor()->lifecycle().state() == DocumentLifecycle::InCompositingUpdate);
307     // FIXME: if this is really needed for performance, it would be better to store it on RenderLayer.
308     m_compositedBounds = m_owningLayer.boundingBoxForCompositing();
309 }
310
311 void CompositedLayerMapping::updateAfterWidgetResize()
312 {
313     if (renderer()->isRenderPart()) {
314         if (RenderLayerCompositor* innerCompositor = RenderLayerCompositor::frameContentsCompositor(toRenderPart(renderer()))) {
315             innerCompositor->frameViewDidChangeSize();
316             // We can floor this point because our frameviews are always aligned to pixel boundaries.
317             ASSERT(contentsBox().location() == flooredIntPoint(contentsBox().location()));
318             innerCompositor->frameViewDidChangeLocation(flooredIntPoint(contentsBox().location()));
319         }
320     }
321 }
322
323 void CompositedLayerMapping::updateCompositingReasons()
324 {
325     // All other layers owned by this mapping will have the same compositing reason
326     // for their lifetime, so they are initialized only when created.
327     m_graphicsLayer->setCompositingReasons(m_owningLayer.compositingReasons());
328 }
329
330 bool CompositedLayerMapping::owningLayerClippedByLayerNotAboveCompositedAncestor()
331 {
332     if (!m_owningLayer.parent())
333         return false;
334
335     const RenderLayer* compositingAncestor = m_owningLayer.enclosingLayerWithCompositedLayerMapping(ExcludeSelf);
336     if (!compositingAncestor)
337         return false;
338
339     const RenderObject* clippingContainer = m_owningLayer.clippingContainer();
340     if (!clippingContainer)
341         return false;
342
343     if (compositingAncestor->renderer()->isDescendantOf(clippingContainer))
344         return false;
345
346     return true;
347 }
348
349 bool CompositedLayerMapping::updateGraphicsLayerConfiguration()
350 {
351     ASSERT(m_owningLayer.compositor()->lifecycle().state() == DocumentLifecycle::InCompositingUpdate);
352
353     RenderLayerCompositor* compositor = this->compositor();
354     RenderObject* renderer = this->renderer();
355
356     bool layerConfigChanged = false;
357     setBackgroundLayerPaintsFixedRootBackground(compositor->needsFixedRootBackgroundLayer(&m_owningLayer));
358
359     // The background layer is currently only used for fixed root backgrounds.
360     if (updateBackgroundLayer(m_backgroundLayerPaintsFixedRootBackground))
361         layerConfigChanged = true;
362
363     if (updateForegroundLayer(compositor->needsContentsCompositingLayer(&m_owningLayer)))
364         layerConfigChanged = true;
365
366     bool needsDescendantsClippingLayer = compositor->clipsCompositingDescendants(&m_owningLayer);
367
368     // Our scrolling layer will clip.
369     if (m_owningLayer.needsCompositedScrolling())
370         needsDescendantsClippingLayer = false;
371
372     RenderLayer* scrollParent = compositor->acceleratedCompositingForOverflowScrollEnabled() ? m_owningLayer.scrollParent() : 0;
373
374     // This is required because compositing layers are parented
375     // according to the z-order hierarchy, yet clipping goes down the renderer hierarchy.
376     // Thus, a RenderLayer can be clipped by a RenderLayer that is an ancestor in the renderer hierarchy,
377     // but a sibling in the z-order hierarchy. Further, that sibling need not be composited at all.
378     // In such scenarios, an ancestor clipping layer is necessary to apply the composited clip for this layer.
379     bool needsAncestorClip = owningLayerClippedByLayerNotAboveCompositedAncestor();
380
381     if (scrollParent) {
382         // If our containing block is our ancestor scrolling layer, then we'll already be clipped
383         // to it via our scroll parent and we don't need an ancestor clipping layer.
384         if (m_owningLayer.renderer()->containingBlock()->enclosingLayer() == m_owningLayer.ancestorScrollingLayer())
385             needsAncestorClip = false;
386     }
387
388     if (updateClippingLayers(needsAncestorClip, needsDescendantsClippingLayer))
389         layerConfigChanged = true;
390
391     if (updateOverflowControlsLayers(requiresHorizontalScrollbarLayer(), requiresVerticalScrollbarLayer(), requiresScrollCornerLayer(), needsAncestorClip))
392         layerConfigChanged = true;
393
394     bool scrollingConfigChanged = false;
395     if (updateScrollingLayers(m_owningLayer.needsCompositedScrolling())) {
396         layerConfigChanged = true;
397         scrollingConfigChanged = true;
398     }
399
400     bool hasPerspective = false;
401     if (RenderStyle* style = renderer->style())
402         hasPerspective = style->hasPerspective();
403     bool needsChildTransformLayer = hasPerspective && (layerForChildrenTransform() == m_childTransformLayer.get()) && renderer->isBox();
404     if (updateChildTransformLayer(needsChildTransformLayer))
405         layerConfigChanged = true;
406
407     updateScrollParent(scrollParent);
408     updateClipParent();
409
410     if (updateSquashingLayers(!m_squashedLayers.isEmpty()))
411         layerConfigChanged = true;
412
413     if (layerConfigChanged)
414         updateInternalHierarchy();
415
416     if (scrollingConfigChanged) {
417         if (renderer->view())
418             compositor->scrollingLayerDidChange(&m_owningLayer);
419     }
420
421     // A mask layer is not part of the hierarchy proper, it's an auxiliary layer
422     // that's plugged into another GraphicsLayer that is part of the hierarchy.
423     // It has no parent or child GraphicsLayer. For that reason, we process it
424     // here, after the hierarchy has been updated.
425     bool maskLayerChanged = false;
426     if (updateMaskLayer(renderer->hasMask())) {
427         maskLayerChanged = true;
428         m_graphicsLayer->setMaskLayer(m_maskLayer.get());
429     }
430
431     bool hasChildClippingLayer = compositor->clipsCompositingDescendants(&m_owningLayer) && (hasClippingLayer() || hasScrollingLayer());
432     // If we have a border radius or clip path on a scrolling layer, we need a clipping mask to properly
433     // clip the scrolled contents, even if there are no composited descendants.
434     bool hasClipPath = renderer->style()->clipPath();
435     bool needsChildClippingMask = (hasClipPath || renderer->style()->hasBorderRadius()) && (hasChildClippingLayer || isAcceleratedContents(renderer) || hasScrollingLayer());
436     if (updateClippingMaskLayers(needsChildClippingMask)) {
437         // Clip path clips the entire subtree, including scrollbars. It must be attached directly onto
438         // the main m_graphicsLayer.
439         if (hasClipPath)
440             m_graphicsLayer->setMaskLayer(m_childClippingMaskLayer.get());
441         else if (hasClippingLayer())
442             clippingLayer()->setMaskLayer(m_childClippingMaskLayer.get());
443         else if (hasScrollingLayer())
444             scrollingLayer()->setMaskLayer(m_childClippingMaskLayer.get());
445         else if (isAcceleratedContents(renderer))
446             m_graphicsLayer->setContentsClippingMaskLayer(m_childClippingMaskLayer.get());
447     }
448
449     if (m_owningLayer.reflectionInfo()) {
450         if (m_owningLayer.reflectionInfo()->reflectionLayer()->hasCompositedLayerMapping()) {
451             GraphicsLayer* reflectionLayer = m_owningLayer.reflectionInfo()->reflectionLayer()->compositedLayerMapping()->mainGraphicsLayer();
452             m_graphicsLayer->setReplicatedByLayer(reflectionLayer);
453         }
454     } else {
455         m_graphicsLayer->setReplicatedByLayer(0);
456     }
457
458     updateBackgroundColor();
459
460     if (isDirectlyCompositedImage())
461         updateImageContents();
462
463     if (WebLayer* layer = platformLayerForPlugin(renderer)) {
464         m_graphicsLayer->setContentsToPlatformLayer(layer);
465     } else if (renderer->node() && renderer->node()->isFrameOwnerElement() && toHTMLFrameOwnerElement(renderer->node())->contentFrame()) {
466         WebLayer* layer = toHTMLFrameOwnerElement(renderer->node())->contentFrame()->remotePlatformLayer();
467         if (layer)
468             m_graphicsLayer->setContentsToPlatformLayer(layer);
469     } else if (renderer->isVideo()) {
470         HTMLMediaElement* mediaElement = toHTMLMediaElement(renderer->node());
471         m_graphicsLayer->setContentsToPlatformLayer(mediaElement->platformLayer());
472     } else if (isAcceleratedCanvas(renderer)) {
473         HTMLCanvasElement* canvas = toHTMLCanvasElement(renderer->node());
474         if (CanvasRenderingContext* context = canvas->renderingContext())
475             m_graphicsLayer->setContentsToPlatformLayer(context->platformLayer());
476         layerConfigChanged = true;
477     }
478     if (renderer->isRenderPart())
479         layerConfigChanged = RenderLayerCompositor::parentFrameContentLayers(toRenderPart(renderer));
480
481     // Changes to either the internal hierarchy or the mask layer have an impact
482     // on painting phases, so we need to update when either are updated.
483     if (layerConfigChanged || maskLayerChanged)
484         updatePaintingPhases();
485
486     return layerConfigChanged;
487 }
488
489 static IntRect clipBox(RenderBox* renderer)
490 {
491     LayoutRect result = PaintInfo::infiniteRect();
492     if (renderer->hasOverflowClip())
493         result = renderer->overflowClipRect(LayoutPoint());
494
495     if (renderer->hasClip())
496         result.intersect(renderer->clipRect(LayoutPoint()));
497
498     return pixelSnappedIntRect(result);
499 }
500
501 static LayoutPoint computeOffsetFromCompositedAncestor(const RenderLayer* layer, const RenderLayer* compositedAncestor)
502 {
503     LayoutPoint offset;
504     layer->convertToLayerCoords(compositedAncestor, offset);
505     if (compositedAncestor)
506         offset.move(compositedAncestor->compositedLayerMapping()->owningLayer().subpixelAccumulation());
507     return offset;
508 }
509
510 void CompositedLayerMapping::computeBoundsOfOwningLayer(const RenderLayer* compositedAncestor, IntRect& localBounds, IntRect& compositingBoundsRelativeToCompositedAncestor, LayoutPoint& offsetFromCompositedAncestor,
511     IntPoint& snappedOffsetFromCompositedAncestor)
512 {
513     LayoutRect localRawCompositingBounds = compositedBounds();
514     offsetFromCompositedAncestor = computeOffsetFromCompositedAncestor(&m_owningLayer, compositedAncestor);
515     snappedOffsetFromCompositedAncestor = IntPoint(offsetFromCompositedAncestor.x().round(), offsetFromCompositedAncestor.y().round());
516
517     LayoutSize subpixelAccumulation = offsetFromCompositedAncestor - snappedOffsetFromCompositedAncestor;
518     m_owningLayer.setSubpixelAccumulation(subpixelAccumulation);
519
520     // Move the bounds by the subpixel accumulation so that it pixel-snaps relative to absolute pixels instead of local coordinates.
521     localRawCompositingBounds.move(subpixelAccumulation);
522     localBounds = pixelSnappedIntRect(localRawCompositingBounds);
523
524     compositingBoundsRelativeToCompositedAncestor = localBounds;
525     compositingBoundsRelativeToCompositedAncestor.moveBy(snappedOffsetFromCompositedAncestor);
526 }
527
528 void CompositedLayerMapping::updateSquashingLayerGeometry(const LayoutPoint& offsetFromCompositedAncestor, const IntPoint& graphicsLayerParentLocation, const RenderLayer& referenceLayer,
529     Vector<GraphicsLayerPaintInfo>& layers, GraphicsLayer* squashingLayer, LayoutPoint* offsetFromTransformedAncestor, Vector<RenderLayer*>& layersNeedingPaintInvalidation)
530 {
531     if (!squashingLayer)
532         return;
533     ASSERT(compositor()->layerSquashingEnabled());
534
535     LayoutPoint offsetFromReferenceLayerToParentGraphicsLayer(offsetFromCompositedAncestor);
536     offsetFromReferenceLayerToParentGraphicsLayer.moveBy(-graphicsLayerParentLocation);
537
538     // FIXME: Cache these offsets.
539     LayoutPoint referenceOffsetFromTransformedAncestor = referenceLayer.computeOffsetFromTransformedAncestor();
540
541     LayoutRect totalSquashBounds;
542     for (size_t i = 0; i < layers.size(); ++i) {
543         LayoutRect squashedBounds = layers[i].renderLayer->boundingBoxForCompositing();
544
545         // Store the local bounds of the RenderLayer subtree before applying the offset.
546         layers[i].compositedBounds = squashedBounds;
547
548         LayoutPoint offsetFromTransformedAncestorForSquashedLayer = layers[i].renderLayer->computeOffsetFromTransformedAncestor();
549         LayoutSize offsetFromSquashingLayer = offsetFromTransformedAncestorForSquashedLayer - referenceOffsetFromTransformedAncestor;
550
551         squashedBounds.move(offsetFromSquashingLayer);
552         totalSquashBounds.unite(squashedBounds);
553     }
554
555     // The totalSquashBounds is positioned with respect to referenceLayer of this CompositedLayerMapping.
556     // But the squashingLayer needs to be positioned with respect to the ancestor CompositedLayerMapping.
557     // The conversion between referenceLayer and the ancestor CLM is already computed as
558     // offsetFromReferenceLayerToParentGraphicsLayer.
559     totalSquashBounds.moveBy(offsetFromReferenceLayerToParentGraphicsLayer);
560     IntRect squashLayerBounds = enclosingIntRect(totalSquashBounds);
561     IntPoint squashLayerOrigin = squashLayerBounds.location();
562     LayoutSize squashLayerOriginInOwningLayerSpace = squashLayerOrigin - offsetFromReferenceLayerToParentGraphicsLayer;
563
564     // Now that the squashing bounds are known, we can convert the RenderLayer painting offsets
565     // from CLM owning layer space to the squashing layer space.
566     //
567     // The painting offset we want to compute for each squashed RenderLayer is essentially the position of
568     // the squashed RenderLayer described w.r.t. referenceLayer's origin. For this purpose we already cached
569     // offsetFromSquashingCLM before, which describes where the squashed RenderLayer is located w.r.t.
570     // referenceLayer. So we just need to convert that point from referenceLayer space to referenceLayer
571     // space. This is simply done by subtracing squashLayerOriginInOwningLayerSpace, but then the offset
572     // overall needs to be negated because that's the direction that the painting code expects the
573     // offset to be.
574     for (size_t i = 0; i < layers.size(); ++i) {
575         LayoutPoint offsetFromTransformedAncestorForSquashedLayer = layers[i].renderLayer->computeOffsetFromTransformedAncestor();
576         LayoutSize offsetFromSquashLayerOrigin = (offsetFromTransformedAncestorForSquashedLayer - referenceOffsetFromTransformedAncestor) - squashLayerOriginInOwningLayerSpace;
577
578         // It is ok to issue paint invalidation here, because all of the geometry needed to correctly invalidate paint is computed by this point.
579         IntSize newOffsetFromRenderer = -IntSize(offsetFromSquashLayerOrigin.width().round(), offsetFromSquashLayerOrigin.height().round());
580         LayoutSize subpixelAccumulation = offsetFromSquashLayerOrigin + newOffsetFromRenderer;
581         if (layers[i].offsetFromRendererSet && layers[i].offsetFromRenderer != newOffsetFromRenderer) {
582             layers[i].renderLayer->paintInvalidator().paintInvalidationIncludingNonCompositingDescendants();
583             layersNeedingPaintInvalidation.append(layers[i].renderLayer);
584         }
585         layers[i].offsetFromRenderer = newOffsetFromRenderer;
586         layers[i].offsetFromRendererSet = true;
587
588         layers[i].renderLayer->setSubpixelAccumulation(subpixelAccumulation);
589     }
590
591     squashingLayer->setPosition(squashLayerBounds.location());
592     squashingLayer->setSize(squashLayerBounds.size());
593
594     *offsetFromTransformedAncestor = referenceOffsetFromTransformedAncestor;
595     offsetFromTransformedAncestor->move(squashLayerOriginInOwningLayerSpace);
596
597     for (size_t i = 0; i < layers.size(); ++i)
598         layers[i].localClipRectForSquashedLayer = localClipRectForSquashedLayer(referenceLayer, layers[i], layers);
599 }
600
601 void CompositedLayerMapping::updateGraphicsLayerGeometry(const RenderLayer* compositingContainer, const RenderLayer* compositingStackingContext, Vector<RenderLayer*>& layersNeedingPaintInvalidation)
602 {
603     ASSERT(m_owningLayer.compositor()->lifecycle().state() == DocumentLifecycle::InCompositingUpdate);
604
605     // Set transform property, if it is not animating. We have to do this here because the transform
606     // is affected by the layer dimensions.
607     if (!renderer()->style()->isRunningTransformAnimationOnCompositor())
608         updateTransform(renderer()->style());
609
610     // Set opacity, if it is not animating.
611     if (!renderer()->style()->isRunningOpacityAnimationOnCompositor())
612         updateOpacity(renderer()->style());
613
614     if (!renderer()->style()->isRunningFilterAnimationOnCompositor())
615         updateFilters(renderer()->style());
616
617     // We compute everything relative to the enclosing compositing layer.
618     IntRect ancestorCompositingBounds;
619     if (compositingContainer) {
620         ASSERT(compositingContainer->hasCompositedLayerMapping());
621         ancestorCompositingBounds = compositingContainer->compositedLayerMapping()->pixelSnappedCompositedBounds();
622     }
623
624     IntRect localCompositingBounds;
625     IntRect relativeCompositingBounds;
626     LayoutPoint offsetFromCompositedAncestor;
627     IntPoint snappedOffsetFromCompositedAncestor;
628     computeBoundsOfOwningLayer(compositingContainer, localCompositingBounds, relativeCompositingBounds, offsetFromCompositedAncestor, snappedOffsetFromCompositedAncestor);
629
630     IntPoint graphicsLayerParentLocation;
631     computeGraphicsLayerParentLocation(compositingContainer, ancestorCompositingBounds, graphicsLayerParentLocation);
632
633     // Might update graphicsLayerParentLocation.
634     updateAncestorClippingLayerGeometry(compositingContainer, snappedOffsetFromCompositedAncestor, graphicsLayerParentLocation);
635     updateOverflowControlsHostLayerGeometry(compositingStackingContext);
636
637     FloatSize contentsSize = relativeCompositingBounds.size();
638
639     updateMainGraphicsLayerGeometry(relativeCompositingBounds, localCompositingBounds, graphicsLayerParentLocation);
640     updateSquashingLayerGeometry(offsetFromCompositedAncestor, graphicsLayerParentLocation, m_owningLayer, m_squashedLayers, m_squashingLayer.get(), &m_squashingLayerOffsetFromTransformedAncestor, layersNeedingPaintInvalidation);
641
642     // If we have a layer that clips children, position it.
643     IntRect clippingBox;
644     if (m_childContainmentLayer)
645         clippingBox = clipBox(toRenderBox(renderer()));
646
647     updateChildContainmentLayerGeometry(clippingBox, localCompositingBounds);
648     updateChildTransformLayerGeometry();
649
650     updateMaskLayerGeometry();
651     updateTransformGeometry(snappedOffsetFromCompositedAncestor, relativeCompositingBounds);
652     updateForegroundLayerGeometry(contentsSize, clippingBox);
653     updateBackgroundLayerGeometry(contentsSize);
654     updateReflectionLayerGeometry(layersNeedingPaintInvalidation);
655     updateScrollingLayerGeometry(localCompositingBounds);
656     updateChildClippingMaskLayerGeometry();
657
658     if (m_owningLayer.scrollableArea() && m_owningLayer.scrollableArea()->scrollsOverflow())
659         m_owningLayer.scrollableArea()->positionOverflowControls(IntSize());
660
661     if (RuntimeEnabledFeatures::cssCompositingEnabled()) {
662         updateLayerBlendMode(renderer()->style());
663         updateIsRootForIsolatedGroup();
664     }
665
666     updateContentsRect();
667     updateBackgroundColor();
668     updateDrawsContent();
669     updateContentsOpaque();
670     updateAfterWidgetResize();
671     updateRenderingContext();
672     updateShouldFlattenTransform();
673     updateChildrenTransform();
674     updateScrollParent(compositor()->acceleratedCompositingForOverflowScrollEnabled() ? m_owningLayer.scrollParent() : 0);
675     registerScrollingLayers();
676
677     updateCompositingReasons();
678 }
679
680 void CompositedLayerMapping::updateMainGraphicsLayerGeometry(const IntRect& relativeCompositingBounds, const IntRect& localCompositingBounds, IntPoint& graphicsLayerParentLocation)
681 {
682     m_graphicsLayer->setPosition(FloatPoint(relativeCompositingBounds.location() - graphicsLayerParentLocation));
683     m_graphicsLayer->setOffsetFromRenderer(toIntSize(localCompositingBounds.location()));
684
685     FloatSize oldSize = m_graphicsLayer->size();
686     const IntSize& contentsSize = relativeCompositingBounds.size();
687     if (oldSize != contentsSize)
688         m_graphicsLayer->setSize(contentsSize);
689
690     // m_graphicsLayer is the corresponding GraphicsLayer for this RenderLayer and its non-compositing
691     // descendants. So, the visibility flag for m_graphicsLayer should be true if there are any
692     // non-compositing visible layers.
693     bool contentsVisible = m_owningLayer.hasVisibleContent() || hasVisibleNonCompositingDescendant(&m_owningLayer);
694     if (RuntimeEnabledFeatures::overlayFullscreenVideoEnabled() && renderer()->isVideo()) {
695         HTMLMediaElement* mediaElement = toHTMLMediaElement(renderer()->node());
696         if (mediaElement->isFullscreen())
697             contentsVisible = false;
698     }
699     m_graphicsLayer->setContentsVisible(contentsVisible);
700
701     m_graphicsLayer->setBackfaceVisibility(renderer()->style()->backfaceVisibility() == BackfaceVisibilityVisible);
702 }
703
704 void CompositedLayerMapping::computeGraphicsLayerParentLocation(const RenderLayer* compositingContainer, const IntRect& ancestorCompositingBounds, IntPoint& graphicsLayerParentLocation)
705 {
706     if (compositingContainer && compositingContainer->compositedLayerMapping()->hasClippingLayer()) {
707         // If the compositing ancestor has a layer to clip children, we parent in that, and therefore
708         // position relative to it.
709         IntRect clippingBox = clipBox(toRenderBox(compositingContainer->renderer()));
710         graphicsLayerParentLocation = clippingBox.location() + roundedIntSize(compositingContainer->subpixelAccumulation());
711     } else if (compositingContainer && compositingContainer->compositedLayerMapping()->childTransformLayer()) {
712         // Similarly, if the compositing ancestor has a child transform layer, we parent in that, and therefore
713         // position relative to it. It's already taken into account the contents offset, so we do not need to here.
714         graphicsLayerParentLocation = roundedIntPoint(compositingContainer->subpixelAccumulation());
715     } else if (compositingContainer) {
716         graphicsLayerParentLocation = ancestorCompositingBounds.location();
717     } else {
718         graphicsLayerParentLocation = renderer()->view()->documentRect().location();
719     }
720
721     if (compositingContainer && compositingContainer->needsCompositedScrolling()) {
722         RenderBox* renderBox = toRenderBox(compositingContainer->renderer());
723         IntSize scrollOffset = renderBox->scrolledContentOffset();
724         IntPoint scrollOrigin(renderBox->borderLeft(), renderBox->borderTop());
725         graphicsLayerParentLocation = scrollOrigin - scrollOffset;
726     }
727 }
728
729 void CompositedLayerMapping::updateAncestorClippingLayerGeometry(const RenderLayer* compositingContainer, const IntPoint& snappedOffsetFromCompositedAncestor, IntPoint& graphicsLayerParentLocation)
730 {
731     if (!compositingContainer || !m_ancestorClippingLayer)
732         return;
733
734     // FIXME: this should use cached clip rects, but this sometimes give
735     // inaccurate results (and trips the ASSERTS in RenderLayerClipper).
736     ClipRectsContext clipRectsContext(compositingContainer, UncachedClipRects, IgnoreOverlayScrollbarSize);
737     clipRectsContext.setIgnoreOverflowClip();
738     IntRect parentClipRect = pixelSnappedIntRect(m_owningLayer.clipper().backgroundClipRect(clipRectsContext).rect());
739     ASSERT(parentClipRect != PaintInfo::infiniteRect());
740     m_ancestorClippingLayer->setPosition(FloatPoint(parentClipRect.location() - graphicsLayerParentLocation));
741     m_ancestorClippingLayer->setSize(parentClipRect.size());
742
743     // backgroundRect is relative to compositingContainer, so subtract snappedOffsetFromCompositedAncestor.X/snappedOffsetFromCompositedAncestor.Y to get back to local coords.
744     m_ancestorClippingLayer->setOffsetFromRenderer(parentClipRect.location() - snappedOffsetFromCompositedAncestor);
745
746     // The primary layer is then parented in, and positioned relative to this clipping layer.
747     graphicsLayerParentLocation = parentClipRect.location();
748 }
749
750 void CompositedLayerMapping::updateOverflowControlsHostLayerGeometry(const RenderLayer* compositingStackingContext)
751 {
752     if (!m_overflowControlsHostLayer)
753         return;
754
755     if (needsToReparentOverflowControls()) {
756         if (m_overflowControlsClippingLayer) {
757             m_overflowControlsClippingLayer->setPosition(m_ancestorClippingLayer->position());
758             m_overflowControlsClippingLayer->setSize(m_ancestorClippingLayer->size());
759             m_overflowControlsClippingLayer->setOffsetFromRenderer(m_ancestorClippingLayer->offsetFromRenderer());
760             m_overflowControlsClippingLayer->setMasksToBounds(true);
761
762             m_overflowControlsHostLayer->setPosition(IntPoint(-m_overflowControlsClippingLayer->offsetFromRenderer()));
763         } else {
764             ASSERT(m_owningLayer.transformAncestor() == compositingStackingContext->transformAncestor());
765             LayoutPoint localOffsetToTransformedAncestor = m_owningLayer.computeOffsetFromTransformedAncestor();
766             LayoutPoint compositingStackingContextOffsetToTransformedAncestor = compositingStackingContext->computeOffsetFromTransformedAncestor();
767
768             m_overflowControlsHostLayer->setPosition(FloatPoint(localOffsetToTransformedAncestor - compositingStackingContextOffsetToTransformedAncestor));
769         }
770     } else {
771         m_overflowControlsHostLayer->setPosition(FloatPoint());
772     }
773 }
774
775 void CompositedLayerMapping::updateChildContainmentLayerGeometry(const IntRect& clippingBox, const IntRect& localCompositingBounds)
776 {
777     if (!m_childContainmentLayer)
778         return;
779
780     m_childContainmentLayer->setPosition(FloatPoint(clippingBox.location() - localCompositingBounds.location() + roundedIntSize(m_owningLayer.subpixelAccumulation())));
781     m_childContainmentLayer->setSize(clippingBox.size());
782     m_childContainmentLayer->setOffsetFromRenderer(toIntSize(clippingBox.location()));
783     if (m_childClippingMaskLayer && !m_scrollingLayer && !renderer()->style()->clipPath()) {
784         m_childClippingMaskLayer->setPosition(m_childContainmentLayer->position());
785         m_childClippingMaskLayer->setSize(m_childContainmentLayer->size());
786         m_childClippingMaskLayer->setOffsetFromRenderer(m_childContainmentLayer->offsetFromRenderer());
787     }
788 }
789
790 void CompositedLayerMapping::updateChildTransformLayerGeometry()
791 {
792     if (!m_childTransformLayer)
793         return;
794     const IntRect borderBox = toRenderBox(m_owningLayer.renderer())->pixelSnappedBorderBoxRect();
795     m_childTransformLayer->setSize(borderBox.size());
796     m_childTransformLayer->setPosition(FloatPoint(contentOffsetInCompositingLayer()));
797 }
798
799 void CompositedLayerMapping::updateMaskLayerGeometry()
800 {
801     if (!m_maskLayer)
802         return;
803
804     if (m_maskLayer->size() != m_graphicsLayer->size()) {
805         m_maskLayer->setSize(m_graphicsLayer->size());
806         m_maskLayer->setNeedsDisplay();
807     }
808     m_maskLayer->setPosition(FloatPoint());
809     m_maskLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
810 }
811
812 void CompositedLayerMapping::updateTransformGeometry(const IntPoint& snappedOffsetFromCompositedAncestor, const IntRect& relativeCompositingBounds)
813 {
814     if (m_owningLayer.hasTransform()) {
815         const LayoutRect borderBox = toRenderBox(renderer())->borderBoxRect();
816
817         // Get layout bounds in the coords of compositingContainer to match relativeCompositingBounds.
818         IntRect layerBounds = pixelSnappedIntRect(toLayoutPoint(m_owningLayer.subpixelAccumulation()), borderBox.size());
819         layerBounds.moveBy(snappedOffsetFromCompositedAncestor);
820
821         // Update properties that depend on layer dimensions
822         FloatPoint3D transformOrigin = computeTransformOrigin(IntRect(IntPoint(), layerBounds.size()));
823
824         // |transformOrigin| is in the local space of this layer. layerBounds - relativeCompositingBounds converts to the space of the
825         // compositing bounds relative to the composited ancestor. This does not apply to the z direction, since the page is 2D.
826         FloatPoint3D compositedTransformOrigin(
827             layerBounds.x() - relativeCompositingBounds.x() + transformOrigin.x(),
828             layerBounds.y() - relativeCompositingBounds.y() + transformOrigin.y(),
829             transformOrigin.z());
830         m_graphicsLayer->setTransformOrigin(compositedTransformOrigin);
831     } else {
832         FloatPoint3D compositedTransformOrigin(
833             relativeCompositingBounds.width() * 0.5f,
834             relativeCompositingBounds.height() * 0.5f,
835             0.f);
836         m_graphicsLayer->setTransformOrigin(compositedTransformOrigin);
837     }
838 }
839
840 void CompositedLayerMapping::updateReflectionLayerGeometry(Vector<RenderLayer*>& layersNeedingPaintInvalidation)
841 {
842     if (!m_owningLayer.reflectionInfo() || !m_owningLayer.reflectionInfo()->reflectionLayer()->hasCompositedLayerMapping())
843         return;
844
845     CompositedLayerMapping* reflectionCompositedLayerMapping = m_owningLayer.reflectionInfo()->reflectionLayer()->compositedLayerMapping();
846     reflectionCompositedLayerMapping->updateGraphicsLayerGeometry(&m_owningLayer, &m_owningLayer, layersNeedingPaintInvalidation);
847 }
848
849 void CompositedLayerMapping::updateScrollingLayerGeometry(const IntRect& localCompositingBounds)
850 {
851     if (!m_scrollingLayer)
852         return;
853
854     ASSERT(m_scrollingContentsLayer);
855     RenderBox* renderBox = toRenderBox(renderer());
856     IntRect clientBox = enclosingIntRect(renderBox->clientBoxRect());
857
858     IntSize adjustedScrollOffset = m_owningLayer.scrollableArea()->adjustedScrollOffset();
859     m_scrollingLayer->setPosition(FloatPoint(clientBox.location() - localCompositingBounds.location() + roundedIntSize(m_owningLayer.subpixelAccumulation())));
860     m_scrollingLayer->setSize(clientBox.size());
861
862     IntSize oldScrollingLayerOffset = m_scrollingLayer->offsetFromRenderer();
863     m_scrollingLayer->setOffsetFromRenderer(-toIntSize(clientBox.location()));
864
865     if (m_childClippingMaskLayer && !renderer()->style()->clipPath()) {
866         m_childClippingMaskLayer->setPosition(m_scrollingLayer->position());
867         m_childClippingMaskLayer->setSize(m_scrollingLayer->size());
868         m_childClippingMaskLayer->setOffsetFromRenderer(toIntSize(clientBox.location()));
869     }
870
871     bool clientBoxOffsetChanged = oldScrollingLayerOffset != m_scrollingLayer->offsetFromRenderer();
872
873     IntSize scrollSize(renderBox->scrollWidth(), renderBox->scrollHeight());
874     if (scrollSize != m_scrollingContentsLayer->size() || clientBoxOffsetChanged)
875         m_scrollingContentsLayer->setNeedsDisplay();
876
877     IntSize scrollingContentsOffset = toIntSize(clientBox.location() - adjustedScrollOffset);
878     if (scrollingContentsOffset != m_scrollingContentsLayer->offsetFromRenderer() || scrollSize != m_scrollingContentsLayer->size()) {
879         bool coordinatorHandlesOffset = compositor()->scrollingLayerDidChange(&m_owningLayer);
880         m_scrollingContentsLayer->setPosition(coordinatorHandlesOffset ? FloatPoint() : FloatPoint(-adjustedScrollOffset));
881     }
882
883     m_scrollingContentsLayer->setSize(scrollSize);
884     // FIXME: The paint offset and the scroll offset should really be separate concepts.
885     m_scrollingContentsLayer->setOffsetFromRenderer(scrollingContentsOffset, GraphicsLayer::DontSetNeedsDisplay);
886
887     if (m_foregroundLayer) {
888         if (m_foregroundLayer->size() != m_scrollingContentsLayer->size())
889             m_foregroundLayer->setSize(m_scrollingContentsLayer->size());
890         m_foregroundLayer->setNeedsDisplay();
891         m_foregroundLayer->setOffsetFromRenderer(m_scrollingContentsLayer->offsetFromRenderer());
892     }
893
894     updateScrollingBlockSelection();
895 }
896
897 void CompositedLayerMapping::updateChildClippingMaskLayerGeometry()
898 {
899     if (!m_childClippingMaskLayer || !renderer()->style()->clipPath())
900         return;
901     RenderBox* renderBox = toRenderBox(renderer());
902     IntRect clientBox = enclosingIntRect(renderBox->clientBoxRect());
903
904     m_childClippingMaskLayer->setPosition(m_graphicsLayer->position());
905     m_childClippingMaskLayer->setSize(m_graphicsLayer->size());
906     m_childClippingMaskLayer->setOffsetFromRenderer(toIntSize(clientBox.location()));
907
908     // NOTE: also some stuff happening in updateChildContainmentLayerGeometry().
909 }
910
911 void CompositedLayerMapping::updateForegroundLayerGeometry(const FloatSize& relativeCompositingBoundsSize, const IntRect& clippingBox)
912 {
913     if (!m_foregroundLayer)
914         return;
915
916     FloatSize foregroundSize = relativeCompositingBoundsSize;
917     IntSize foregroundOffset = m_graphicsLayer->offsetFromRenderer();
918     m_foregroundLayer->setPosition(FloatPoint());
919
920     if (hasClippingLayer()) {
921         // If we have a clipping layer (which clips descendants), then the foreground layer is a child of it,
922         // so that it gets correctly sorted with children. In that case, position relative to the clipping layer.
923         foregroundSize = FloatSize(clippingBox.size());
924         foregroundOffset = toIntSize(clippingBox.location());
925     } else if (m_childTransformLayer) {
926         // Things are different if we have a child transform layer rather
927         // than a clipping layer. In this case, we want to actually change
928         // the position of the layer (to compensate for our ancestor
929         // compositing layer's position) rather than leave the position the
930         // same and use offset-from-renderer + size to describe a clipped
931         // "window" onto the clipped layer.
932
933         m_foregroundLayer->setPosition(-m_childTransformLayer->position());
934     }
935
936     if (foregroundSize != m_foregroundLayer->size()) {
937         m_foregroundLayer->setSize(foregroundSize);
938         m_foregroundLayer->setNeedsDisplay();
939     }
940     m_foregroundLayer->setOffsetFromRenderer(foregroundOffset);
941
942     // NOTE: there is some more configuring going on in updateScrollingLayerGeometry().
943 }
944
945 void CompositedLayerMapping::updateBackgroundLayerGeometry(const FloatSize& relativeCompositingBoundsSize)
946 {
947     if (!m_backgroundLayer)
948         return;
949
950     FloatSize backgroundSize = relativeCompositingBoundsSize;
951     if (backgroundLayerPaintsFixedRootBackground()) {
952         FrameView* frameView = toRenderView(renderer())->frameView();
953         backgroundSize = frameView->visibleContentRect().size();
954     }
955     m_backgroundLayer->setPosition(FloatPoint());
956     if (backgroundSize != m_backgroundLayer->size()) {
957         m_backgroundLayer->setSize(backgroundSize);
958         m_backgroundLayer->setNeedsDisplay();
959     }
960     m_backgroundLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
961 }
962
963 void CompositedLayerMapping::registerScrollingLayers()
964 {
965     // Register fixed position layers and their containers with the scrolling coordinator.
966     ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer);
967     if (!scrollingCoordinator)
968         return;
969
970     scrollingCoordinator->updateLayerPositionConstraint(&m_owningLayer);
971
972     // Page scale is applied as a transform on the root render view layer. Because the scroll
973     // layer is further up in the hierarchy, we need to avoid marking the root render view
974     // layer as a container.
975     bool isContainer = m_owningLayer.hasTransform() && !m_owningLayer.isRootLayer();
976     // FIXME: we should make certain that childForSuperLayers will never be the m_squashingContainmentLayer here
977     scrollingCoordinator->setLayerIsContainerForFixedPositionLayers(childForSuperlayers(), isContainer);
978 }
979
980 void CompositedLayerMapping::updateInternalHierarchy()
981 {
982     // m_foregroundLayer has to be inserted in the correct order with child layers,
983     // so it's not inserted here.
984     if (m_ancestorClippingLayer)
985         m_ancestorClippingLayer->removeAllChildren();
986
987     m_graphicsLayer->removeFromParent();
988
989     if (m_ancestorClippingLayer)
990         m_ancestorClippingLayer->addChild(m_graphicsLayer.get());
991
992     if (m_childContainmentLayer)
993         m_graphicsLayer->addChild(m_childContainmentLayer.get());
994     else if (m_childTransformLayer)
995         m_graphicsLayer->addChild(m_childTransformLayer.get());
996
997     if (m_scrollingLayer) {
998         GraphicsLayer* superLayer = m_graphicsLayer.get();
999
1000         if (m_childContainmentLayer)
1001             superLayer = m_childContainmentLayer.get();
1002
1003         if (m_childTransformLayer)
1004             superLayer = m_childTransformLayer.get();
1005
1006         superLayer->addChild(m_scrollingLayer.get());
1007     }
1008
1009     // The clip for child layers does not include space for overflow controls, so they exist as
1010     // siblings of the clipping layer if we have one. Normal children of this layer are set as
1011     // children of the clipping layer.
1012     if (m_overflowControlsClippingLayer) {
1013         ASSERT(m_overflowControlsHostLayer);
1014         m_graphicsLayer->addChild(m_overflowControlsClippingLayer.get());
1015         m_overflowControlsClippingLayer->addChild(m_overflowControlsHostLayer.get());
1016     } else if (m_overflowControlsHostLayer) {
1017         m_graphicsLayer->addChild(m_overflowControlsHostLayer.get());
1018     }
1019
1020     if (m_layerForHorizontalScrollbar)
1021         m_overflowControlsHostLayer->addChild(m_layerForHorizontalScrollbar.get());
1022     if (m_layerForVerticalScrollbar)
1023         m_overflowControlsHostLayer->addChild(m_layerForVerticalScrollbar.get());
1024     if (m_layerForScrollCorner)
1025         m_overflowControlsHostLayer->addChild(m_layerForScrollCorner.get());
1026
1027     // The squashing containment layer, if it exists, becomes a no-op parent.
1028     if (m_squashingLayer) {
1029         ASSERT(compositor()->layerSquashingEnabled());
1030         ASSERT((m_ancestorClippingLayer && !m_squashingContainmentLayer) || (!m_ancestorClippingLayer && m_squashingContainmentLayer));
1031
1032         if (m_squashingContainmentLayer) {
1033             m_squashingContainmentLayer->removeAllChildren();
1034             m_squashingContainmentLayer->addChild(m_graphicsLayer.get());
1035             m_squashingContainmentLayer->addChild(m_squashingLayer.get());
1036         } else {
1037             // The ancestor clipping layer is already set up and has m_graphicsLayer under it.
1038             m_ancestorClippingLayer->addChild(m_squashingLayer.get());
1039         }
1040     }
1041 }
1042
1043 void CompositedLayerMapping::updatePaintingPhases()
1044 {
1045     m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
1046     if (m_scrollingContentsLayer) {
1047         GraphicsLayerPaintingPhase paintPhase = GraphicsLayerPaintOverflowContents | GraphicsLayerPaintCompositedScroll;
1048         if (!m_foregroundLayer)
1049             paintPhase |= GraphicsLayerPaintForeground;
1050         m_scrollingContentsLayer->setPaintingPhase(paintPhase);
1051         m_scrollingBlockSelectionLayer->setPaintingPhase(paintPhase);
1052     }
1053 }
1054
1055 void CompositedLayerMapping::updateContentsRect()
1056 {
1057     m_graphicsLayer->setContentsRect(pixelSnappedIntRect(contentsBox()));
1058 }
1059
1060 void CompositedLayerMapping::updateScrollingBlockSelection()
1061 {
1062     if (!m_scrollingBlockSelectionLayer)
1063         return;
1064
1065     if (!m_scrollingContentsAreEmpty) {
1066         // In this case, the selection will be painted directly into m_scrollingContentsLayer.
1067         m_scrollingBlockSelectionLayer->setDrawsContent(false);
1068         return;
1069     }
1070
1071     const IntRect blockSelectionGapsBounds = m_owningLayer.blockSelectionGapsBounds();
1072     const bool shouldDrawContent = !blockSelectionGapsBounds.isEmpty();
1073     m_scrollingBlockSelectionLayer->setDrawsContent(shouldDrawContent);
1074     if (!shouldDrawContent)
1075         return;
1076
1077     const IntPoint position = blockSelectionGapsBounds.location() + m_owningLayer.scrollableArea()->adjustedScrollOffset();
1078     if (m_scrollingBlockSelectionLayer->size() == blockSelectionGapsBounds.size() && m_scrollingBlockSelectionLayer->position() == position)
1079         return;
1080
1081     m_scrollingBlockSelectionLayer->setPosition(position);
1082     m_scrollingBlockSelectionLayer->setSize(blockSelectionGapsBounds.size());
1083     m_scrollingBlockSelectionLayer->setOffsetFromRenderer(toIntSize(blockSelectionGapsBounds.location()), GraphicsLayer::SetNeedsDisplay);
1084 }
1085
1086 void CompositedLayerMapping::updateDrawsContent()
1087 {
1088     if (m_scrollingLayer) {
1089         // We don't have to consider overflow controls, because we know that the scrollbars are drawn elsewhere.
1090         // m_graphicsLayer only needs backing store if the non-scrolling parts (background, outlines, borders, shadows etc) need to paint.
1091         // m_scrollingLayer never has backing store.
1092         // m_scrollingContentsLayer only needs backing store if the scrolled contents need to paint.
1093         bool hasNonScrollingPaintedContent = m_owningLayer.hasVisibleContent() && m_owningLayer.hasBoxDecorationsOrBackground();
1094         m_graphicsLayer->setDrawsContent(hasNonScrollingPaintedContent);
1095
1096         m_scrollingContentsAreEmpty = !m_owningLayer.hasVisibleContent() || !(renderer()->hasBackground() || paintsChildren());
1097         m_scrollingContentsLayer->setDrawsContent(!m_scrollingContentsAreEmpty);
1098
1099         updateScrollingBlockSelection();
1100         return;
1101     }
1102
1103     bool hasPaintedContent = containsPaintedContent();
1104     if (hasPaintedContent && isAcceleratedCanvas(renderer())) {
1105         CanvasRenderingContext* context = toHTMLCanvasElement(renderer()->node())->renderingContext();
1106         // Content layer may be null if context is lost.
1107         if (WebLayer* contentLayer = context->platformLayer()) {
1108             Color bgColor(Color::transparent);
1109             if (contentLayerSupportsDirectBackgroundComposition(renderer())) {
1110                 bgColor = rendererBackgroundColor();
1111             }
1112             contentLayer->setBackgroundColor(bgColor.rgb());
1113         }
1114     }
1115
1116     // FIXME: we could refine this to only allocate backings 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 void CompositedLayerMapping::updateChildrenTransform()
1126 {
1127     if (GraphicsLayer* childTransformLayer = layerForChildrenTransform()) {
1128         childTransformLayer->setTransform(owningLayer().perspectiveTransform());
1129         childTransformLayer->setTransformOrigin(FloatPoint3D(childTransformLayer->size().width() * 0.5f, childTransformLayer->size().height() * 0.5f, 0.f));
1130     }
1131
1132     updateShouldFlattenTransform();
1133 }
1134
1135 // Return true if the layers changed.
1136 bool CompositedLayerMapping::updateClippingLayers(bool needsAncestorClip, bool needsDescendantClip)
1137 {
1138     bool layersChanged = false;
1139
1140     if (needsAncestorClip) {
1141         if (!m_ancestorClippingLayer) {
1142             m_ancestorClippingLayer = createGraphicsLayer(CompositingReasonLayerForAncestorClip);
1143             m_ancestorClippingLayer->setMasksToBounds(true);
1144             layersChanged = true;
1145         }
1146     } else if (m_ancestorClippingLayer) {
1147         m_ancestorClippingLayer->removeFromParent();
1148         m_ancestorClippingLayer = nullptr;
1149         layersChanged = true;
1150     }
1151
1152     if (needsDescendantClip) {
1153         // We don't need a child containment layer if we're the main frame render view
1154         // layer. It's redundant as the frame clip above us will handle this clipping.
1155         if (!m_childContainmentLayer && !m_isMainFrameRenderViewLayer) {
1156             m_childContainmentLayer = createGraphicsLayer(CompositingReasonLayerForDescendantClip);
1157             m_childContainmentLayer->setMasksToBounds(true);
1158             layersChanged = true;
1159         }
1160     } else if (hasClippingLayer()) {
1161         m_childContainmentLayer->removeFromParent();
1162         m_childContainmentLayer = nullptr;
1163         layersChanged = true;
1164     }
1165
1166     return layersChanged;
1167 }
1168
1169 bool CompositedLayerMapping::updateChildTransformLayer(bool needsChildTransformLayer)
1170 {
1171     bool layersChanged = false;
1172
1173     if (needsChildTransformLayer) {
1174         if (!m_childTransformLayer) {
1175             m_childTransformLayer = createGraphicsLayer(CompositingReasonLayerForPerspective);
1176             m_childTransformLayer->setDrawsContent(false);
1177             layersChanged = true;
1178         }
1179     } else if (m_childTransformLayer) {
1180         m_childTransformLayer->removeFromParent();
1181         m_childTransformLayer = nullptr;
1182         layersChanged = true;
1183     }
1184
1185     return layersChanged;
1186 }
1187
1188 void CompositedLayerMapping::setBackgroundLayerPaintsFixedRootBackground(bool backgroundLayerPaintsFixedRootBackground)
1189 {
1190     m_backgroundLayerPaintsFixedRootBackground = backgroundLayerPaintsFixedRootBackground;
1191 }
1192
1193 // Only a member function so it can call createGraphicsLayer.
1194 bool CompositedLayerMapping::toggleScrollbarLayerIfNeeded(OwnPtr<GraphicsLayer>& layer, bool needsLayer, CompositingReasons reason)
1195 {
1196     if (needsLayer == !!layer)
1197         return false;
1198     layer = needsLayer ? createGraphicsLayer(reason) : nullptr;
1199     return true;
1200 }
1201
1202 bool CompositedLayerMapping::updateOverflowControlsLayers(bool needsHorizontalScrollbarLayer, bool needsVerticalScrollbarLayer, bool needsScrollCornerLayer, bool needsAncestorClip)
1203 {
1204     bool horizontalScrollbarLayerChanged = toggleScrollbarLayerIfNeeded(m_layerForHorizontalScrollbar, needsHorizontalScrollbarLayer, CompositingReasonLayerForHorizontalScrollbar);
1205     bool verticalScrollbarLayerChanged = toggleScrollbarLayerIfNeeded(m_layerForVerticalScrollbar, needsVerticalScrollbarLayer, CompositingReasonLayerForVerticalScrollbar);
1206     bool scrollCornerLayerChanged = toggleScrollbarLayerIfNeeded(m_layerForScrollCorner, needsScrollCornerLayer, CompositingReasonLayerForScrollCorner);
1207
1208     bool needsOverflowControlsHostLayer = needsHorizontalScrollbarLayer || needsVerticalScrollbarLayer || needsScrollCornerLayer;
1209     toggleScrollbarLayerIfNeeded(m_overflowControlsHostLayer, needsOverflowControlsHostLayer, CompositingReasonLayerForOverflowControlsHost);
1210     bool needsOverflowClipLayer = needsOverflowControlsHostLayer && needsAncestorClip;
1211     toggleScrollbarLayerIfNeeded(m_overflowControlsClippingLayer, needsOverflowClipLayer, CompositingReasonLayerForOverflowControlsHost);
1212
1213     if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer)) {
1214         if (horizontalScrollbarLayerChanged)
1215             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_owningLayer.scrollableArea(), HorizontalScrollbar);
1216         if (verticalScrollbarLayerChanged)
1217             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_owningLayer.scrollableArea(), VerticalScrollbar);
1218     }
1219
1220     return horizontalScrollbarLayerChanged || verticalScrollbarLayerChanged || scrollCornerLayerChanged;
1221 }
1222
1223 void CompositedLayerMapping::positionOverflowControlsLayers(const IntSize& offsetFromRoot)
1224 {
1225     IntSize offsetFromRenderer = m_graphicsLayer->offsetFromRenderer() - roundedIntSize(m_owningLayer.subpixelAccumulation());
1226     if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
1227         Scrollbar* hBar = m_owningLayer.scrollableArea()->horizontalScrollbar();
1228         if (hBar) {
1229             layer->setPosition(hBar->frameRect().location() - offsetFromRoot - offsetFromRenderer);
1230             layer->setSize(hBar->frameRect().size());
1231             if (layer->hasContentsLayer())
1232                 layer->setContentsRect(IntRect(IntPoint(), hBar->frameRect().size()));
1233         }
1234         layer->setDrawsContent(hBar && !layer->hasContentsLayer());
1235     }
1236
1237     if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
1238         Scrollbar* vBar = m_owningLayer.scrollableArea()->verticalScrollbar();
1239         if (vBar) {
1240             layer->setPosition(vBar->frameRect().location() - offsetFromRoot - offsetFromRenderer);
1241             layer->setSize(vBar->frameRect().size());
1242             if (layer->hasContentsLayer())
1243                 layer->setContentsRect(IntRect(IntPoint(), vBar->frameRect().size()));
1244         }
1245         layer->setDrawsContent(vBar && !layer->hasContentsLayer());
1246     }
1247
1248     if (GraphicsLayer* layer = layerForScrollCorner()) {
1249         const LayoutRect& scrollCornerAndResizer = m_owningLayer.scrollableArea()->scrollCornerAndResizerRect();
1250         layer->setPosition(scrollCornerAndResizer.location() - offsetFromRenderer);
1251         layer->setSize(scrollCornerAndResizer.size());
1252         layer->setDrawsContent(!scrollCornerAndResizer.isEmpty());
1253     }
1254 }
1255
1256 bool CompositedLayerMapping::hasUnpositionedOverflowControlsLayers() const
1257 {
1258     if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
1259         if (!layer->drawsContent())
1260             return true;
1261     }
1262
1263     if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
1264         if (!layer->drawsContent())
1265             return true;
1266     }
1267
1268     if (GraphicsLayer* layer = layerForScrollCorner()) {
1269         if (!layer->drawsContent())
1270             return true;
1271     }
1272
1273     return false;
1274 }
1275
1276 enum ApplyToGraphicsLayersModeFlags {
1277     ApplyToCoreLayers = (1 << 0),
1278     ApplyToSquashingLayer = (1 << 1),
1279     ApplyToScrollbarLayers = (1 << 2),
1280     ApplyToBackgroundLayer = (1 << 3),
1281     ApplyToMaskLayers = (1 << 4),
1282     ApplyToContentLayers = (1 << 5),
1283     ApplyToAllGraphicsLayers = (ApplyToSquashingLayer | ApplyToScrollbarLayers | ApplyToBackgroundLayer | ApplyToMaskLayers | ApplyToCoreLayers | ApplyToContentLayers)
1284 };
1285 typedef unsigned ApplyToGraphicsLayersMode;
1286
1287 template <typename Func>
1288 static void ApplyToGraphicsLayers(const CompositedLayerMapping* mapping, const Func& f, ApplyToGraphicsLayersMode mode)
1289 {
1290     ASSERT(mode);
1291
1292     if ((mode & ApplyToCoreLayers) && mapping->squashingContainmentLayer())
1293         f(mapping->squashingContainmentLayer());
1294     if ((mode & ApplyToCoreLayers) && mapping->childTransformLayer())
1295         f(mapping->childTransformLayer());
1296     if ((mode & ApplyToCoreLayers) && mapping->ancestorClippingLayer())
1297         f(mapping->ancestorClippingLayer());
1298     if (((mode & ApplyToCoreLayers) || (mode & ApplyToContentLayers)) && mapping->mainGraphicsLayer())
1299         f(mapping->mainGraphicsLayer());
1300     if ((mode & ApplyToCoreLayers) && mapping->clippingLayer())
1301         f(mapping->clippingLayer());
1302     if ((mode & ApplyToCoreLayers) && mapping->scrollingLayer())
1303         f(mapping->scrollingLayer());
1304     if ((mode & ApplyToCoreLayers) && mapping->scrollingBlockSelectionLayer())
1305         f(mapping->scrollingBlockSelectionLayer());
1306     if (((mode & ApplyToCoreLayers) || (mode & ApplyToContentLayers)) && mapping->scrollingContentsLayer())
1307         f(mapping->scrollingContentsLayer());
1308     if (((mode & ApplyToCoreLayers) || (mode & ApplyToContentLayers)) && mapping->foregroundLayer())
1309         f(mapping->foregroundLayer());
1310
1311     if ((mode & ApplyToSquashingLayer) && mapping->squashingLayer())
1312         f(mapping->squashingLayer());
1313
1314     if (((mode & ApplyToMaskLayers) || (mode & ApplyToContentLayers)) && mapping->maskLayer())
1315         f(mapping->maskLayer());
1316     if (((mode & ApplyToMaskLayers) || (mode & ApplyToContentLayers)) && mapping->childClippingMaskLayer())
1317         f(mapping->childClippingMaskLayer());
1318
1319     if (((mode & ApplyToBackgroundLayer) || (mode & ApplyToContentLayers)) && mapping->backgroundLayer())
1320         f(mapping->backgroundLayer());
1321
1322     if ((mode & ApplyToScrollbarLayers) && mapping->layerForHorizontalScrollbar())
1323         f(mapping->layerForHorizontalScrollbar());
1324     if ((mode & ApplyToScrollbarLayers) && mapping->layerForVerticalScrollbar())
1325         f(mapping->layerForVerticalScrollbar());
1326     if ((mode & ApplyToScrollbarLayers) && mapping->layerForScrollCorner())
1327         f(mapping->layerForScrollCorner());
1328 }
1329
1330 struct UpdateRenderingContextFunctor {
1331     void operator() (GraphicsLayer* layer) const { layer->setRenderingContext(renderingContext); }
1332     int renderingContext;
1333 };
1334
1335 void CompositedLayerMapping::updateRenderingContext()
1336 {
1337     // All layers but the squashing layer (which contains 'alien' content) should be included in this
1338     // rendering context.
1339     int id = 0;
1340
1341     // NB, it is illegal at this point to query an ancestor's compositing state. Some compositing
1342     // reasons depend on the compositing state of ancestors. So if we want a rendering context id
1343     // for the context root, we cannot ask for the id of its associated WebLayer now; it may not have
1344     // one yet. We could do a second past after doing the compositing updates to get these ids,
1345     // but this would actually be harmful. We do not want to attach any semantic meaning to
1346     // the context id other than the fact that they group a number of layers together for the
1347     // sake of 3d sorting. So instead we will ask the compositor to vend us an arbitrary, but
1348     // consistent id.
1349     if (RenderLayer* root = m_owningLayer.renderingContextRoot()) {
1350         if (Node* node = root->renderer()->node())
1351             id = static_cast<int>(WTF::PtrHash<Node*>::hash(node));
1352     }
1353
1354     UpdateRenderingContextFunctor functor = { id };
1355     ApplyToGraphicsLayersMode mode = ApplyToAllGraphicsLayers & ~ApplyToSquashingLayer;
1356     ApplyToGraphicsLayers<UpdateRenderingContextFunctor>(this, functor, mode);
1357 }
1358
1359 struct UpdateShouldFlattenTransformFunctor {
1360     void operator() (GraphicsLayer* layer) const { layer->setShouldFlattenTransform(shouldFlatten); }
1361     bool shouldFlatten;
1362 };
1363
1364 void CompositedLayerMapping::updateShouldFlattenTransform()
1365 {
1366     // All CLM-managed layers that could affect a descendant layer should update their
1367     // should-flatten-transform value (the other layers' transforms don't matter here).
1368     UpdateShouldFlattenTransformFunctor functor = { !m_owningLayer.shouldPreserve3D() };
1369     ApplyToGraphicsLayersMode mode = ApplyToCoreLayers;
1370     ApplyToGraphicsLayers(this, functor, mode);
1371
1372     // Note, if we apply perspective, we have to set should flatten differently
1373     // so that the transform propagates to child layers correctly.
1374     if (GraphicsLayer* childTransformLayer = layerForChildrenTransform()) {
1375         bool hasPerspective = false;
1376         if (RenderStyle* style = m_owningLayer.renderer()->style())
1377             hasPerspective = style->hasPerspective();
1378         if (hasPerspective)
1379             childTransformLayer->setShouldFlattenTransform(false);
1380
1381         // Note, if the target is the scrolling layer, we need to ensure that the
1382         // scrolling content layer doesn't flatten the transform. (It would be nice
1383         // if we could apply transform to the scrolling content layer, but that's
1384         // too late, we need the children transform to be applied _before_ the
1385         // scrolling offset.)
1386         if (childTransformLayer == m_scrollingLayer.get()) {
1387             m_scrollingContentsLayer->setShouldFlattenTransform(false);
1388             m_scrollingBlockSelectionLayer->setShouldFlattenTransform(false);
1389         }
1390     }
1391 }
1392
1393 bool CompositedLayerMapping::updateForegroundLayer(bool needsForegroundLayer)
1394 {
1395     bool layerChanged = false;
1396     if (needsForegroundLayer) {
1397         if (!m_foregroundLayer) {
1398             m_foregroundLayer = createGraphicsLayer(CompositingReasonLayerForForeground);
1399             m_foregroundLayer->setDrawsContent(true);
1400             m_foregroundLayer->setPaintingPhase(GraphicsLayerPaintForeground);
1401             layerChanged = true;
1402         }
1403     } else if (m_foregroundLayer) {
1404         m_foregroundLayer->removeFromParent();
1405         m_foregroundLayer = nullptr;
1406         layerChanged = true;
1407     }
1408
1409     return layerChanged;
1410 }
1411
1412 bool CompositedLayerMapping::updateBackgroundLayer(bool needsBackgroundLayer)
1413 {
1414     bool layerChanged = false;
1415     if (needsBackgroundLayer) {
1416         if (!m_backgroundLayer) {
1417             m_backgroundLayer = createGraphicsLayer(CompositingReasonLayerForBackground);
1418             m_backgroundLayer->setDrawsContent(true);
1419             m_backgroundLayer->setTransformOrigin(FloatPoint3D());
1420             m_backgroundLayer->setPaintingPhase(GraphicsLayerPaintBackground);
1421 #if !OS(ANDROID)
1422             m_backgroundLayer->contentLayer()->setDrawCheckerboardForMissingTiles(true);
1423             m_graphicsLayer->contentLayer()->setDrawCheckerboardForMissingTiles(false);
1424 #endif
1425             layerChanged = true;
1426         }
1427     } else {
1428         if (m_backgroundLayer) {
1429             m_backgroundLayer->removeFromParent();
1430             m_backgroundLayer = nullptr;
1431 #if !OS(ANDROID)
1432             m_graphicsLayer->contentLayer()->setDrawCheckerboardForMissingTiles(true);
1433 #endif
1434             layerChanged = true;
1435         }
1436     }
1437
1438     if (layerChanged && !m_owningLayer.renderer()->documentBeingDestroyed())
1439         compositor()->rootFixedBackgroundsChanged();
1440
1441     return layerChanged;
1442 }
1443
1444 bool CompositedLayerMapping::updateMaskLayer(bool needsMaskLayer)
1445 {
1446     bool layerChanged = false;
1447     if (needsMaskLayer) {
1448         if (!m_maskLayer) {
1449             m_maskLayer = createGraphicsLayer(CompositingReasonLayerForMask);
1450             m_maskLayer->setDrawsContent(true);
1451             m_maskLayer->setPaintingPhase(GraphicsLayerPaintMask);
1452             layerChanged = true;
1453         }
1454     } else if (m_maskLayer) {
1455         m_maskLayer = nullptr;
1456         layerChanged = true;
1457     }
1458
1459     return layerChanged;
1460 }
1461
1462 bool CompositedLayerMapping::updateClippingMaskLayers(bool needsChildClippingMaskLayer)
1463 {
1464     bool layerChanged = false;
1465     if (needsChildClippingMaskLayer) {
1466         if (!m_childClippingMaskLayer) {
1467             m_childClippingMaskLayer = createGraphicsLayer(CompositingReasonLayerForClippingMask);
1468             m_childClippingMaskLayer->setDrawsContent(true);
1469             m_childClippingMaskLayer->setPaintingPhase(GraphicsLayerPaintChildClippingMask);
1470             layerChanged = true;
1471         }
1472     } else if (m_childClippingMaskLayer) {
1473         m_childClippingMaskLayer = nullptr;
1474         layerChanged = true;
1475     }
1476     return layerChanged;
1477 }
1478
1479 bool CompositedLayerMapping::updateScrollingLayers(bool needsScrollingLayers)
1480 {
1481     ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer);
1482
1483     bool layerChanged = false;
1484     if (needsScrollingLayers) {
1485         if (!m_scrollingLayer) {
1486             // Outer layer which corresponds with the scroll view.
1487             m_scrollingLayer = createGraphicsLayer(CompositingReasonLayerForScrollingContainer);
1488             m_scrollingLayer->setDrawsContent(false);
1489             m_scrollingLayer->setMasksToBounds(true);
1490
1491             // Inner layer which renders the content that scrolls.
1492             m_scrollingContentsLayer = createGraphicsLayer(CompositingReasonLayerForScrollingContents);
1493             m_scrollingContentsLayer->setDrawsContent(true);
1494             m_scrollingLayer->addChild(m_scrollingContentsLayer.get());
1495
1496             m_scrollingBlockSelectionLayer = createGraphicsLayer(CompositingReasonLayerForScrollingBlockSelection);
1497             m_scrollingBlockSelectionLayer->setDrawsContent(true);
1498             m_scrollingContentsLayer->addChild(m_scrollingBlockSelectionLayer.get());
1499
1500             layerChanged = true;
1501             if (scrollingCoordinator)
1502                 scrollingCoordinator->scrollableAreaScrollLayerDidChange(m_owningLayer.scrollableArea());
1503         }
1504     } else if (m_scrollingLayer) {
1505         m_scrollingLayer = nullptr;
1506         m_scrollingContentsLayer = nullptr;
1507         m_scrollingBlockSelectionLayer = nullptr;
1508         layerChanged = true;
1509         if (scrollingCoordinator)
1510             scrollingCoordinator->scrollableAreaScrollLayerDidChange(m_owningLayer.scrollableArea());
1511     }
1512
1513     return layerChanged;
1514 }
1515
1516 static void updateScrollParentForGraphicsLayer(GraphicsLayer* layer, GraphicsLayer* topmostLayer, RenderLayer* scrollParent, ScrollingCoordinator* scrollingCoordinator)
1517 {
1518     if (!layer)
1519         return;
1520
1521     // Only the topmost layer has a scroll parent. All other layers have a null scroll parent.
1522     if (layer != topmostLayer)
1523         scrollParent = 0;
1524
1525     scrollingCoordinator->updateScrollParentForGraphicsLayer(layer, scrollParent);
1526 }
1527
1528 void CompositedLayerMapping::updateScrollParent(RenderLayer* scrollParent)
1529 {
1530     if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer)) {
1531         GraphicsLayer* topmostLayer = childForSuperlayers();
1532         updateScrollParentForGraphicsLayer(m_squashingContainmentLayer.get(), topmostLayer, scrollParent, scrollingCoordinator);
1533         updateScrollParentForGraphicsLayer(m_ancestorClippingLayer.get(), topmostLayer, scrollParent, scrollingCoordinator);
1534         updateScrollParentForGraphicsLayer(m_graphicsLayer.get(), topmostLayer, scrollParent, scrollingCoordinator);
1535     }
1536 }
1537
1538 void CompositedLayerMapping::updateClipParent()
1539 {
1540     if (owningLayerClippedByLayerNotAboveCompositedAncestor())
1541         return;
1542
1543     RenderLayer* clipParent = m_owningLayer.clipParent();
1544     if (clipParent)
1545         clipParent = clipParent->enclosingLayerWithCompositedLayerMapping(IncludeSelf);
1546
1547     if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer))
1548         scrollingCoordinator->updateClipParentForGraphicsLayer(m_graphicsLayer.get(), clipParent);
1549 }
1550
1551 bool CompositedLayerMapping::updateSquashingLayers(bool needsSquashingLayers)
1552 {
1553     bool layersChanged = false;
1554
1555     if (needsSquashingLayers) {
1556         ASSERT(compositor()->layerSquashingEnabled());
1557
1558         if (!m_squashingLayer) {
1559             m_squashingLayer = createGraphicsLayer(CompositingReasonLayerForSquashingContents);
1560             m_squashingLayer->setDrawsContent(true);
1561             layersChanged = true;
1562         }
1563
1564         if (m_ancestorClippingLayer) {
1565             if (m_squashingContainmentLayer) {
1566                 m_squashingContainmentLayer->removeFromParent();
1567                 m_squashingContainmentLayer = nullptr;
1568                 layersChanged = true;
1569             }
1570         } else {
1571             if (!m_squashingContainmentLayer) {
1572                 m_squashingContainmentLayer = createGraphicsLayer(CompositingReasonLayerForSquashingContainer);
1573                 layersChanged = true;
1574             }
1575         }
1576
1577         ASSERT((m_ancestorClippingLayer && !m_squashingContainmentLayer) || (!m_ancestorClippingLayer && m_squashingContainmentLayer));
1578         ASSERT(m_squashingLayer);
1579     } else {
1580         if (m_squashingLayer) {
1581             m_squashingLayer->removeFromParent();
1582             m_squashingLayer = nullptr;
1583             layersChanged = true;
1584         }
1585         if (m_squashingContainmentLayer) {
1586             m_squashingContainmentLayer->removeFromParent();
1587             m_squashingContainmentLayer = nullptr;
1588             layersChanged = true;
1589         }
1590         ASSERT(!m_squashingLayer && !m_squashingContainmentLayer);
1591     }
1592
1593     return layersChanged;
1594 }
1595
1596 GraphicsLayerPaintingPhase CompositedLayerMapping::paintingPhaseForPrimaryLayer() const
1597 {
1598     unsigned phase = 0;
1599     if (!m_backgroundLayer)
1600         phase |= GraphicsLayerPaintBackground;
1601     if (!m_foregroundLayer)
1602         phase |= GraphicsLayerPaintForeground;
1603     if (!m_maskLayer)
1604         phase |= GraphicsLayerPaintMask;
1605
1606     if (m_scrollingContentsLayer) {
1607         phase &= ~GraphicsLayerPaintForeground;
1608         phase |= GraphicsLayerPaintCompositedScroll;
1609     }
1610
1611     return static_cast<GraphicsLayerPaintingPhase>(phase);
1612 }
1613
1614 float CompositedLayerMapping::compositingOpacity(float rendererOpacity) const
1615 {
1616     float finalOpacity = rendererOpacity;
1617
1618     for (RenderLayer* curr = m_owningLayer.parent(); curr; curr = curr->parent()) {
1619         // We only care about parents that are stacking contexts.
1620         // Recall that opacity creates stacking context.
1621         if (!curr->stackingNode()->isStackingContext())
1622             continue;
1623
1624         // If we found a composited layer, regardless of whether it actually
1625         // paints into it, we want to compute opacity relative to it. So we can
1626         // break here.
1627         //
1628         // FIXME: with grouped backings, a composited descendant will have to
1629         // continue past the grouped (squashed) layers that its parents may
1630         // contribute to. This whole confusion can be avoided by specifying
1631         // explicitly the composited ancestor where we would stop accumulating
1632         // opacity.
1633         if (curr->compositingState() == PaintsIntoOwnBacking || curr->compositingState() == HasOwnBackingButPaintsIntoAncestor)
1634             break;
1635
1636         finalOpacity *= curr->renderer()->opacity();
1637     }
1638
1639     return finalOpacity;
1640 }
1641
1642 Color CompositedLayerMapping::rendererBackgroundColor() const
1643 {
1644     RenderObject* backgroundRenderer = renderer();
1645     if (backgroundRenderer->isDocumentElement())
1646         backgroundRenderer = backgroundRenderer->rendererForRootBackground();
1647
1648     return backgroundRenderer->resolveColor(CSSPropertyBackgroundColor);
1649 }
1650
1651 void CompositedLayerMapping::updateBackgroundColor()
1652 {
1653     m_graphicsLayer->setBackgroundColor(rendererBackgroundColor());
1654 }
1655
1656 bool CompositedLayerMapping::paintsChildren() const
1657 {
1658     if (m_owningLayer.hasVisibleContent() && m_owningLayer.hasNonEmptyChildRenderers())
1659         return true;
1660
1661     if (hasVisibleNonCompositingDescendant(&m_owningLayer))
1662         return true;
1663
1664     return false;
1665 }
1666
1667 static bool isCompositedPlugin(RenderObject* renderer)
1668 {
1669     return renderer->isEmbeddedObject() && toRenderEmbeddedObject(renderer)->requiresAcceleratedCompositing();
1670 }
1671
1672 bool CompositedLayerMapping::hasVisibleNonCompositingDescendant(RenderLayer* parent)
1673 {
1674     if (!parent->hasVisibleDescendant())
1675         return false;
1676
1677     // FIXME: We shouldn't be called with a stale z-order lists. See bug 85512.
1678     parent->stackingNode()->updateLayerListsIfNeeded();
1679
1680 #if ENABLE(ASSERT)
1681     LayerListMutationDetector mutationChecker(parent->stackingNode());
1682 #endif
1683
1684     RenderLayerStackingNodeIterator normalFlowIterator(*parent->stackingNode(), AllChildren);
1685     while (RenderLayerStackingNode* curNode = normalFlowIterator.next()) {
1686         RenderLayer* curLayer = curNode->layer();
1687         if (curLayer->hasCompositedLayerMapping())
1688             continue;
1689         if (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(curLayer))
1690             return true;
1691     }
1692
1693     return false;
1694 }
1695
1696 bool CompositedLayerMapping::containsPaintedContent() const
1697 {
1698     if (paintsIntoCompositedAncestor() || m_owningLayer.isReflection())
1699         return false;
1700
1701     if (isDirectlyCompositedImage())
1702         return false;
1703
1704     RenderObject* renderObject = renderer();
1705     // FIXME: we could optimize cases where the image, video or canvas is known to fill the border box entirely,
1706     // and set background color on the layer in that case, instead of allocating backing store and painting.
1707     if (renderObject->isVideo() && toRenderVideo(renderer())->shouldDisplayVideo())
1708         return m_owningLayer.hasBoxDecorationsOrBackground();
1709
1710     if (m_owningLayer.hasVisibleBoxDecorations())
1711         return true;
1712
1713     if (renderObject->hasMask()) // masks require special treatment
1714         return true;
1715
1716     if (renderObject->isReplaced() && !isCompositedPlugin(renderObject))
1717         return true;
1718
1719     if (renderObject->isRenderRegion())
1720         return true;
1721
1722     if (renderObject->node() && renderObject->node()->isDocumentNode()) {
1723         // Look to see if the root object has a non-simple background
1724         RenderObject* rootObject = renderObject->document().documentElement() ? renderObject->document().documentElement()->renderer() : 0;
1725         // Reject anything that has a border, a border-radius or outline,
1726         // or is not a simple background (no background, or solid color).
1727         if (rootObject && hasBoxDecorationsOrBackgroundImage(rootObject->style()))
1728             return true;
1729
1730         // Now look at the body's renderer.
1731         HTMLElement* body = renderObject->document().body();
1732         RenderObject* bodyObject = isHTMLBodyElement(body) ? body->renderer() : 0;
1733         if (bodyObject && hasBoxDecorationsOrBackgroundImage(bodyObject->style()))
1734             return true;
1735     }
1736
1737     // FIXME: it's O(n^2). A better solution is needed.
1738     return paintsChildren();
1739 }
1740
1741 // An image can be directly compositing if it's the sole content of the layer, and has no box decorations
1742 // that require painting. Direct compositing saves backing store.
1743 bool CompositedLayerMapping::isDirectlyCompositedImage() const
1744 {
1745     RenderObject* renderObject = renderer();
1746
1747     if (!renderObject->isImage() || m_owningLayer.hasBoxDecorationsOrBackground() || renderObject->hasClip())
1748         return false;
1749
1750     RenderImage* imageRenderer = toRenderImage(renderObject);
1751     if (ImageResource* cachedImage = imageRenderer->cachedImage()) {
1752         if (!cachedImage->hasImage())
1753             return false;
1754
1755         Image* image = cachedImage->imageForRenderer(imageRenderer);
1756         return image->isBitmapImage();
1757     }
1758
1759     return false;
1760 }
1761
1762 void CompositedLayerMapping::contentChanged(ContentChangeType changeType)
1763 {
1764     if ((changeType == ImageChanged) && isDirectlyCompositedImage()) {
1765         updateImageContents();
1766         return;
1767     }
1768
1769     if (changeType == CanvasChanged && isAcceleratedCanvas(renderer())) {
1770         m_graphicsLayer->setContentsNeedsDisplay();
1771         return;
1772     }
1773 }
1774
1775 void CompositedLayerMapping::updateImageContents()
1776 {
1777     ASSERT(renderer()->isImage());
1778     RenderImage* imageRenderer = toRenderImage(renderer());
1779
1780     ImageResource* cachedImage = imageRenderer->cachedImage();
1781     if (!cachedImage)
1782         return;
1783
1784     Image* image = cachedImage->imageForRenderer(imageRenderer);
1785     if (!image)
1786         return;
1787
1788     // We have to wait until the image is fully loaded before setting it on the layer.
1789     if (!cachedImage->isLoaded())
1790         return;
1791
1792     // This is a no-op if the layer doesn't have an inner layer for the image.
1793     m_graphicsLayer->setContentsToImage(image);
1794     updateDrawsContent();
1795
1796     // Image animation is "lazy", in that it automatically stops unless someone is drawing
1797     // the image. So we have to kick the animation each time; this has the downside that the
1798     // image will keep animating, even if its layer is not visible.
1799     image->startAnimation();
1800 }
1801
1802 FloatPoint3D CompositedLayerMapping::computeTransformOrigin(const IntRect& borderBox) const
1803 {
1804     RenderStyle* style = renderer()->style();
1805
1806     FloatPoint3D origin;
1807     origin.setX(floatValueForLength(style->transformOriginX(), borderBox.width()));
1808     origin.setY(floatValueForLength(style->transformOriginY(), borderBox.height()));
1809     origin.setZ(style->transformOriginZ());
1810
1811     return origin;
1812 }
1813
1814 // Return the offset from the top-left of this compositing layer at which the renderer's contents are painted.
1815 LayoutSize CompositedLayerMapping::contentOffsetInCompositingLayer() const
1816 {
1817     return LayoutSize(-m_compositedBounds.x(), -m_compositedBounds.y());
1818 }
1819
1820 LayoutRect CompositedLayerMapping::contentsBox() const
1821 {
1822     LayoutRect contentsBox = contentsRect(renderer());
1823     contentsBox.move(contentOffsetInCompositingLayer());
1824     return contentsBox;
1825 }
1826
1827 bool CompositedLayerMapping::needsToReparentOverflowControls() const
1828 {
1829     return m_owningLayer.scrollableArea()
1830         && m_owningLayer.scrollableArea()->hasOverlayScrollbars()
1831         && m_owningLayer.scrollableArea()->topmostScrollChild();
1832 }
1833
1834 GraphicsLayer* CompositedLayerMapping::detachLayerForOverflowControls(const RenderLayer& enclosingLayer)
1835 {
1836     GraphicsLayer* host = m_overflowControlsClippingLayer.get();
1837     if (!host)
1838         host = m_overflowControlsHostLayer.get();
1839     host->removeFromParent();
1840     return host;
1841 }
1842
1843 GraphicsLayer* CompositedLayerMapping::parentForSublayers() const
1844 {
1845     if (m_scrollingBlockSelectionLayer)
1846         return m_scrollingBlockSelectionLayer.get();
1847
1848     if (m_scrollingContentsLayer)
1849         return m_scrollingContentsLayer.get();
1850
1851     if (m_childContainmentLayer)
1852         return m_childContainmentLayer.get();
1853
1854     if (m_childTransformLayer)
1855         return m_childTransformLayer.get();
1856
1857     return m_graphicsLayer.get();
1858 }
1859
1860 GraphicsLayer* CompositedLayerMapping::childForSuperlayers() const
1861 {
1862     if (m_squashingContainmentLayer)
1863         return m_squashingContainmentLayer.get();
1864
1865     if (m_ancestorClippingLayer)
1866         return m_ancestorClippingLayer.get();
1867
1868     return m_graphicsLayer.get();
1869 }
1870
1871 GraphicsLayer* CompositedLayerMapping::layerForChildrenTransform() const
1872 {
1873     if (GraphicsLayer* clipLayer = clippingLayer())
1874         return clipLayer;
1875     if (m_scrollingLayer)
1876         return m_scrollingLayer.get();
1877     return m_childTransformLayer.get();
1878 }
1879
1880 bool CompositedLayerMapping::updateRequiresOwnBackingStoreForAncestorReasons(const RenderLayer* compositingAncestorLayer)
1881 {
1882     unsigned previousRequiresOwnBackingStoreForAncestorReasons = m_requiresOwnBackingStoreForAncestorReasons;
1883     bool previousPaintsIntoCompositedAncestor = paintsIntoCompositedAncestor();
1884     bool canPaintIntoAncestor = compositingAncestorLayer
1885         && (compositingAncestorLayer->compositedLayerMapping()->mainGraphicsLayer()->drawsContent()
1886             || compositingAncestorLayer->compositedLayerMapping()->paintsIntoCompositedAncestor());
1887
1888     if (paintsIntoCompositedAncestor() != previousPaintsIntoCompositedAncestor)
1889         compositor()->paintInvalidationOnCompositingChange(&m_owningLayer);
1890
1891     // FIXME: this is bogus. We need to make this assignment before the check above.
1892     m_requiresOwnBackingStoreForAncestorReasons = !canPaintIntoAncestor;
1893
1894     return m_requiresOwnBackingStoreForAncestorReasons != previousRequiresOwnBackingStoreForAncestorReasons;
1895 }
1896
1897 bool CompositedLayerMapping::updateRequiresOwnBackingStoreForIntrinsicReasons()
1898 {
1899     unsigned previousRequiresOwnBackingStoreForIntrinsicReasons = m_requiresOwnBackingStoreForIntrinsicReasons;
1900     bool previousPaintsIntoCompositedAncestor = paintsIntoCompositedAncestor();
1901     RenderObject* renderer = m_owningLayer.renderer();
1902     m_requiresOwnBackingStoreForIntrinsicReasons = m_owningLayer.isRootLayer()
1903         || (m_owningLayer.compositingReasons() & CompositingReasonComboReasonsThatRequireOwnBacking)
1904         || m_owningLayer.transform()
1905         || m_owningLayer.clipsCompositingDescendantsWithBorderRadius() // FIXME: Revisit this if the paintsIntoCompositedAncestor state is removed.
1906         || renderer->isTransparent()
1907         || renderer->hasMask()
1908         || renderer->hasReflection()
1909         || renderer->hasFilter();
1910
1911     if (paintsIntoCompositedAncestor() != previousPaintsIntoCompositedAncestor)
1912         compositor()->paintInvalidationOnCompositingChange(&m_owningLayer);
1913
1914     return m_requiresOwnBackingStoreForIntrinsicReasons != previousRequiresOwnBackingStoreForIntrinsicReasons;
1915 }
1916
1917 void CompositedLayerMapping::setBlendMode(WebBlendMode blendMode)
1918 {
1919     if (m_ancestorClippingLayer) {
1920         m_ancestorClippingLayer->setBlendMode(blendMode);
1921         m_graphicsLayer->setBlendMode(WebBlendModeNormal);
1922     } else {
1923         m_graphicsLayer->setBlendMode(blendMode);
1924     }
1925 }
1926
1927 GraphicsLayerUpdater::UpdateType CompositedLayerMapping::updateTypeForChildren(GraphicsLayerUpdater::UpdateType updateType) const
1928 {
1929     if (m_pendingUpdateScope >= GraphicsLayerUpdateSubtree)
1930         return GraphicsLayerUpdater::ForceUpdate;
1931     return updateType;
1932 }
1933
1934 struct SetContentsNeedsDisplayFunctor {
1935     void operator() (GraphicsLayer* layer) const
1936     {
1937         if (layer->drawsContent())
1938             layer->setNeedsDisplay();
1939     }
1940 };
1941
1942 void CompositedLayerMapping::setSquashingContentsNeedDisplay()
1943 {
1944     ApplyToGraphicsLayers(this, SetContentsNeedsDisplayFunctor(), ApplyToSquashingLayer);
1945 }
1946
1947 void CompositedLayerMapping::setContentsNeedDisplay()
1948 {
1949     // FIXME: need to split out paint invalidations for the background.
1950     ASSERT(!paintsIntoCompositedAncestor());
1951     ApplyToGraphicsLayers(this, SetContentsNeedsDisplayFunctor(), ApplyToContentLayers);
1952 }
1953
1954 struct SetContentsNeedsDisplayInRectFunctor {
1955     void operator() (GraphicsLayer* layer) const
1956     {
1957         if (layer->drawsContent()) {
1958             IntRect layerDirtyRect = r;
1959             layerDirtyRect.move(-layer->offsetFromRenderer());
1960             layer->setNeedsDisplayInRect(layerDirtyRect);
1961         }
1962     }
1963
1964     IntRect r;
1965 };
1966
1967 // r is in the coordinate space of the layer's render object
1968 void CompositedLayerMapping::setContentsNeedDisplayInRect(const LayoutRect& r)
1969 {
1970     // FIXME: need to split out paint invalidations for the background.
1971     ASSERT(!paintsIntoCompositedAncestor());
1972
1973     SetContentsNeedsDisplayInRectFunctor functor = {
1974         pixelSnappedIntRect(r.location() + m_owningLayer.subpixelAccumulation(), r.size())
1975     };
1976     ApplyToGraphicsLayers(this, functor, ApplyToContentLayers);
1977 }
1978
1979 const GraphicsLayerPaintInfo* CompositedLayerMapping::containingSquashedLayer(const RenderObject* renderObject, const Vector<GraphicsLayerPaintInfo>& layers)
1980 {
1981     for (size_t i = 0; i < layers.size(); ++i) {
1982         if (renderObject->isDescendantOf(layers[i].renderLayer->renderer()))
1983             return &layers[i];
1984     }
1985     return 0;
1986 }
1987
1988 const GraphicsLayerPaintInfo* CompositedLayerMapping::containingSquashedLayer(const RenderObject* renderObject)
1989 {
1990     return CompositedLayerMapping::containingSquashedLayer(renderObject, m_squashedLayers);
1991 }
1992
1993 IntRect CompositedLayerMapping::localClipRectForSquashedLayer(const RenderLayer& referenceLayer, const GraphicsLayerPaintInfo& paintInfo, const Vector<GraphicsLayerPaintInfo>& layers)
1994 {
1995     const RenderObject* clippingContainer = paintInfo.renderLayer->clippingContainer();
1996     if (clippingContainer == referenceLayer.clippingContainer())
1997         return PaintInfo::infiniteRect();
1998
1999     ASSERT(clippingContainer);
2000
2001     const GraphicsLayerPaintInfo* ancestorPaintInfo = containingSquashedLayer(clippingContainer, layers);
2002     // Must be there, otherwise CompositingLayerAssigner::canSquashIntoCurrentSquashingOwner would have disallowed squashing.
2003     ASSERT(ancestorPaintInfo);
2004
2005     // FIXME: this is a potential performance issue. We shoudl consider caching these clip rects or otherwise optimizing.
2006     ClipRectsContext clipRectsContext(ancestorPaintInfo->renderLayer, UncachedClipRects);
2007     IntRect parentClipRect = pixelSnappedIntRect(paintInfo.renderLayer->clipper().backgroundClipRect(clipRectsContext).rect());
2008     ASSERT(parentClipRect != PaintInfo::infiniteRect());
2009
2010     // Convert from ancestor to local coordinates.
2011     IntSize ancestorToLocalOffset = paintInfo.offsetFromRenderer - ancestorPaintInfo->offsetFromRenderer;
2012     parentClipRect.move(ancestorToLocalOffset);
2013     return parentClipRect;
2014 }
2015
2016 void CompositedLayerMapping::doPaintTask(const GraphicsLayerPaintInfo& paintInfo, const PaintLayerFlags& paintLayerFlags, GraphicsContext* context,
2017     const IntRect& clip) // In the coords of rootLayer.
2018 {
2019     RELEASE_ASSERT(paintInfo.renderLayer->compositingState() == PaintsIntoGroupedBacking || !paintsIntoCompositedAncestor());
2020
2021     FontCachePurgePreventer fontCachePurgePreventer;
2022
2023     // Note carefully: in theory it is appropriate to invoke context->save() here
2024     // and restore the context after painting. For efficiency, we are assuming that
2025     // it is equivalent to manually undo this offset translation, which means we are
2026     // assuming that the context's space was not affected by the RenderLayer
2027     // painting code.
2028
2029     IntSize offset = paintInfo.offsetFromRenderer;
2030     context->translate(-offset.width(), -offset.height());
2031
2032     // The dirtyRect is in the coords of the painting root.
2033     IntRect dirtyRect(clip);
2034     dirtyRect.move(offset);
2035
2036     if (!(paintLayerFlags & PaintLayerPaintingOverflowContents)) {
2037         LayoutRect bounds = paintInfo.compositedBounds;
2038         bounds.move(paintInfo.renderLayer->subpixelAccumulation());
2039         dirtyRect.intersect(pixelSnappedIntRect(bounds));
2040     } else {
2041         dirtyRect.move(roundedIntSize(paintInfo.renderLayer->subpixelAccumulation()));
2042     }
2043
2044 #if ENABLE(ASSERT)
2045     paintInfo.renderLayer->renderer()->assertSubtreeIsLaidOut();
2046 #endif
2047
2048     if (paintInfo.renderLayer->compositingState() != PaintsIntoGroupedBacking) {
2049         // FIXME: GraphicsLayers need a way to split for RenderRegions.
2050         LayerPaintingInfo paintingInfo(paintInfo.renderLayer, dirtyRect, PaintBehaviorNormal, paintInfo.renderLayer->subpixelAccumulation());
2051         paintInfo.renderLayer->paintLayerContents(context, paintingInfo, paintLayerFlags);
2052
2053         if (paintInfo.renderLayer->containsDirtyOverlayScrollbars())
2054             paintInfo.renderLayer->paintLayerContents(context, paintingInfo, paintLayerFlags | PaintLayerPaintingOverlayScrollbars);
2055     } else {
2056         ASSERT(compositor()->layerSquashingEnabled());
2057         LayerPaintingInfo paintingInfo(paintInfo.renderLayer, dirtyRect, PaintBehaviorNormal, paintInfo.renderLayer->subpixelAccumulation());
2058
2059         // RenderLayer::paintLayer assumes that the caller clips to the passed rect. Squashed layers need to do this clipping in software,
2060         // since there is no graphics layer to clip them precisely. Furthermore, in some cases we squash layers that need clipping in software
2061         // from clipping ancestors (see CompositedLayerMapping::localClipRectForSquashedLayer()).
2062         context->save();
2063         dirtyRect.intersect(paintInfo.localClipRectForSquashedLayer);
2064         context->clip(dirtyRect);
2065         paintInfo.renderLayer->paintLayer(context, paintingInfo, paintLayerFlags);
2066         context->restore();
2067     }
2068
2069     ASSERT(!paintInfo.renderLayer->usedTransparency());
2070
2071     // Manually restore the context to its original state by applying the opposite translation.
2072     context->translate(offset.width(), offset.height());
2073 }
2074
2075 static void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
2076 {
2077     if (!scrollbar)
2078         return;
2079
2080     context.save();
2081     const IntRect& scrollbarRect = scrollbar->frameRect();
2082     context.translate(-scrollbarRect.x(), -scrollbarRect.y());
2083     IntRect transformedClip = clip;
2084     transformedClip.moveBy(scrollbarRect.location());
2085     scrollbar->paint(&context, transformedClip);
2086     context.restore();
2087 }
2088
2089 // Up-call from compositing layer drawing callback.
2090 void CompositedLayerMapping::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, GraphicsLayerPaintingPhase graphicsLayerPaintingPhase, const IntRect& clip)
2091 {
2092     // https://code.google.com/p/chromium/issues/detail?id=343772
2093     DisableCompositingQueryAsserts disabler;
2094 #if ENABLE(ASSERT)
2095     // FIXME: once the state machine is ready, this can be removed and we can refer to that instead.
2096     if (Page* page = renderer()->frame()->page())
2097         page->setIsPainting(true);
2098 #endif
2099     TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "Paint", "data", InspectorPaintEvent::data(m_owningLayer.renderer(), clip, graphicsLayer));
2100     TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
2101     // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
2102     InspectorInstrumentation::willPaint(m_owningLayer.renderer(), graphicsLayer);
2103
2104     PaintLayerFlags paintLayerFlags = 0;
2105     if (graphicsLayerPaintingPhase & GraphicsLayerPaintBackground)
2106         paintLayerFlags |= PaintLayerPaintingCompositingBackgroundPhase;
2107     if (graphicsLayerPaintingPhase & GraphicsLayerPaintForeground)
2108         paintLayerFlags |= PaintLayerPaintingCompositingForegroundPhase;
2109     if (graphicsLayerPaintingPhase & GraphicsLayerPaintMask)
2110         paintLayerFlags |= PaintLayerPaintingCompositingMaskPhase;
2111     if (graphicsLayerPaintingPhase & GraphicsLayerPaintChildClippingMask)
2112         paintLayerFlags |= PaintLayerPaintingChildClippingMaskPhase;
2113     if (graphicsLayerPaintingPhase & GraphicsLayerPaintOverflowContents)
2114         paintLayerFlags |= PaintLayerPaintingOverflowContents;
2115     if (graphicsLayerPaintingPhase & GraphicsLayerPaintCompositedScroll)
2116         paintLayerFlags |= PaintLayerPaintingCompositingScrollingPhase;
2117
2118     if (graphicsLayer == m_backgroundLayer)
2119         paintLayerFlags |= (PaintLayerPaintingRootBackgroundOnly | PaintLayerPaintingCompositingForegroundPhase); // Need PaintLayerPaintingCompositingForegroundPhase to walk child layers.
2120     else if (compositor()->fixedRootBackgroundLayer())
2121         paintLayerFlags |= PaintLayerPaintingSkipRootBackground;
2122
2123     if (graphicsLayer == m_graphicsLayer.get()
2124         || graphicsLayer == m_foregroundLayer.get()
2125         || graphicsLayer == m_backgroundLayer.get()
2126         || graphicsLayer == m_maskLayer.get()
2127         || graphicsLayer == m_childClippingMaskLayer.get()
2128         || graphicsLayer == m_scrollingContentsLayer.get()
2129         || graphicsLayer == m_scrollingBlockSelectionLayer.get()) {
2130
2131         GraphicsLayerPaintInfo paintInfo;
2132         paintInfo.renderLayer = &m_owningLayer;
2133         paintInfo.compositedBounds = compositedBounds();
2134         paintInfo.offsetFromRenderer = graphicsLayer->offsetFromRenderer();
2135
2136         // We have to use the same root as for hit testing, because both methods can compute and cache clipRects.
2137         doPaintTask(paintInfo, paintLayerFlags, &context, clip);
2138     } else if (graphicsLayer == m_squashingLayer.get()) {
2139         ASSERT(compositor()->layerSquashingEnabled());
2140         for (size_t i = 0; i < m_squashedLayers.size(); ++i)
2141             doPaintTask(m_squashedLayers[i], paintLayerFlags, &context, clip);
2142     } else if (graphicsLayer == layerForHorizontalScrollbar()) {
2143         paintScrollbar(m_owningLayer.scrollableArea()->horizontalScrollbar(), context, clip);
2144     } else if (graphicsLayer == layerForVerticalScrollbar()) {
2145         paintScrollbar(m_owningLayer.scrollableArea()->verticalScrollbar(), context, clip);
2146     } else if (graphicsLayer == layerForScrollCorner()) {
2147         const IntRect& scrollCornerAndResizer = m_owningLayer.scrollableArea()->scrollCornerAndResizerRect();
2148         context.save();
2149         context.translate(-scrollCornerAndResizer.x(), -scrollCornerAndResizer.y());
2150         IntRect transformedClip = clip;
2151         transformedClip.moveBy(scrollCornerAndResizer.location());
2152         m_owningLayer.scrollableArea()->paintScrollCorner(&context, IntPoint(), transformedClip);
2153         m_owningLayer.scrollableArea()->paintResizer(&context, IntPoint(), transformedClip);
2154         context.restore();
2155     }
2156     InspectorInstrumentation::didPaint(m_owningLayer.renderer(), graphicsLayer, &context, clip);
2157 #if ENABLE(ASSERT)
2158     if (Page* page = renderer()->frame()->page())
2159         page->setIsPainting(false);
2160 #endif
2161 }
2162
2163 bool CompositedLayerMapping::isTrackingPaintInvalidations() const
2164 {
2165     GraphicsLayerClient* client = compositor();
2166     return client ? client->isTrackingPaintInvalidations() : false;
2167 }
2168
2169 #if ENABLE(ASSERT)
2170 void CompositedLayerMapping::verifyNotPainting()
2171 {
2172     ASSERT(!renderer()->frame()->page() || !renderer()->frame()->page()->isPainting());
2173 }
2174 #endif
2175
2176 void CompositedLayerMapping::notifyAnimationStarted(const GraphicsLayer*, double monotonicTime)
2177 {
2178     renderer()->node()->document().compositorPendingAnimations().notifyCompositorAnimationStarted(monotonicTime);
2179 }
2180
2181 IntRect CompositedLayerMapping::pixelSnappedCompositedBounds() const
2182 {
2183     LayoutRect bounds = m_compositedBounds;
2184     bounds.move(m_owningLayer.subpixelAccumulation());
2185     return pixelSnappedIntRect(bounds);
2186 }
2187
2188 bool CompositedLayerMapping::updateSquashingLayerAssignment(RenderLayer* squashedLayer, const RenderLayer& owningLayer, size_t nextSquashedLayerIndex)
2189 {
2190     ASSERT(compositor()->layerSquashingEnabled());
2191
2192     GraphicsLayerPaintInfo paintInfo;
2193     paintInfo.renderLayer = squashedLayer;
2194     // NOTE: composited bounds are updated elsewhere
2195     // NOTE: offsetFromRenderer is updated elsewhere
2196
2197     // Change tracking on squashing layers: at the first sign of something changed, just invalidate the layer.
2198     // FIXME: Perhaps we can find a tighter more clever mechanism later.
2199     bool updatedAssignment = false;
2200     if (nextSquashedLayerIndex < m_squashedLayers.size()) {
2201         if (paintInfo.renderLayer != m_squashedLayers[nextSquashedLayerIndex].renderLayer) {
2202             compositor()->paintInvalidationOnCompositingChange(squashedLayer);
2203             updatedAssignment = true;
2204             m_squashedLayers[nextSquashedLayerIndex] = paintInfo;
2205         }
2206     } else {
2207         compositor()->paintInvalidationOnCompositingChange(squashedLayer);
2208         m_squashedLayers.append(paintInfo);
2209         updatedAssignment = true;
2210     }
2211     squashedLayer->setGroupedMapping(this);
2212     return updatedAssignment;
2213 }
2214
2215 void CompositedLayerMapping::removeRenderLayerFromSquashingGraphicsLayer(const RenderLayer* layer)
2216 {
2217     size_t layerIndex = kNotFound;
2218
2219     for (size_t i = 0; i < m_squashedLayers.size(); ++i) {
2220         if (m_squashedLayers[i].renderLayer == layer) {
2221             layerIndex = i;
2222             break;
2223         }
2224     }
2225
2226     if (layerIndex == kNotFound)
2227         return;
2228
2229     m_squashedLayers.remove(layerIndex);
2230 }
2231
2232 void CompositedLayerMapping::finishAccumulatingSquashingLayers(size_t nextSquashedLayerIndex)
2233 {
2234     ASSERT(compositor()->layerSquashingEnabled());
2235
2236     // Any additional squashed RenderLayers in the array no longer exist, and removing invalidates the squashingLayer contents.
2237     if (nextSquashedLayerIndex < m_squashedLayers.size())
2238         m_squashedLayers.remove(nextSquashedLayerIndex, m_squashedLayers.size() - nextSquashedLayerIndex);
2239 }
2240
2241 String CompositedLayerMapping::debugName(const GraphicsLayer* graphicsLayer)
2242 {
2243     String name;
2244     if (graphicsLayer == m_graphicsLayer.get()) {
2245         name = m_owningLayer.debugName();
2246     } else if (graphicsLayer == m_squashingContainmentLayer.get()) {
2247         name = "Squashing Containment Layer";
2248     } else if (graphicsLayer == m_squashingLayer.get()) {
2249         name = "Squashing Layer";
2250     } else if (graphicsLayer == m_ancestorClippingLayer.get()) {
2251         name = "Ancestor Clipping Layer";
2252     } else if (graphicsLayer == m_foregroundLayer.get()) {
2253         name = m_owningLayer.debugName() + " (foreground) Layer";
2254     } else if (graphicsLayer == m_backgroundLayer.get()) {
2255         name = m_owningLayer.debugName() + " (background) Layer";
2256     } else if (graphicsLayer == m_childContainmentLayer.get()) {
2257         name = "Child Containment Layer";
2258     } else if (graphicsLayer == m_childTransformLayer.get()) {
2259         name = "Child Transform Layer";
2260     } else if (graphicsLayer == m_maskLayer.get()) {
2261         name = "Mask Layer";
2262     } else if (graphicsLayer == m_childClippingMaskLayer.get()) {
2263         name = "Child Clipping Mask Layer";
2264     } else if (graphicsLayer == m_layerForHorizontalScrollbar.get()) {
2265         name = "Horizontal Scrollbar Layer";
2266     } else if (graphicsLayer == m_layerForVerticalScrollbar.get()) {
2267         name = "Vertical Scrollbar Layer";
2268     } else if (graphicsLayer == m_layerForScrollCorner.get()) {
2269         name = "Scroll Corner Layer";
2270     } else if (graphicsLayer == m_overflowControlsHostLayer.get()) {
2271         name = "Overflow Controls Host Layer";
2272     } else if (graphicsLayer == m_overflowControlsClippingLayer.get()) {
2273         name = "Overflow Controls ClipLayer Layer";
2274     } else if (graphicsLayer == m_scrollingLayer.get()) {
2275         name = "Scrolling Layer";
2276     } else if (graphicsLayer == m_scrollingContentsLayer.get()) {
2277         name = "Scrolling Contents Layer";
2278     } else if (graphicsLayer == m_scrollingBlockSelectionLayer.get()) {
2279         name = "Scrolling Block Selection Layer";
2280     } else {
2281         ASSERT_NOT_REACHED();
2282     }
2283
2284     return name;
2285 }
2286
2287 } // namespace blink