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