OSDN Git Service

Merge WebKit at r78450: Initial merge by git.
[android-x86/external-webkit.git] / Source / WebCore / rendering / RenderLayerBacking.cpp
1 /*
2  * Copyright (C) 2009 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 #if USE(ACCELERATED_COMPOSITING)
29
30 #include "RenderLayerBacking.h"
31
32 #include "AnimationController.h"
33 #include "CanvasRenderingContext.h"
34 #include "CanvasRenderingContext2D.h"
35 #include "CSSPropertyNames.h"
36 #include "CSSStyleSelector.h"
37 #include "FrameView.h"
38 #include "GraphicsContext.h"
39 #include "GraphicsContext3D.h"
40 #include "GraphicsLayer.h"
41 #include "HTMLCanvasElement.h"
42 #include "HTMLElement.h"
43 #include "HTMLIFrameElement.h"
44 #include "HTMLMediaElement.h"
45 #include "HTMLNames.h"
46 #include "InspectorInstrumentation.h"
47 #include "KeyframeList.h"
48 #include "PluginViewBase.h"
49 #include "RenderApplet.h"
50 #include "RenderBox.h"
51 #include "RenderIFrame.h"
52 #include "RenderImage.h"
53 #include "RenderLayerCompositor.h"
54 #include "RenderEmbeddedObject.h"
55 #include "RenderVideo.h"
56 #include "RenderView.h"
57 #include "Settings.h"
58 #include "WebGLRenderingContext.h"
59
60 using namespace std;
61
62 namespace WebCore {
63
64 using namespace HTMLNames;
65
66 static bool hasBorderOutlineOrShadow(const RenderStyle*);
67 static bool hasBoxDecorationsOrBackground(const RenderObject*);
68 static bool hasBoxDecorationsOrBackgroundImage(const RenderStyle*);
69 static IntRect clipBox(RenderBox* renderer);
70
71 static inline bool isAcceleratedCanvas(RenderObject* renderer)
72 {
73 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
74     if (renderer->isCanvas()) {
75         HTMLCanvasElement* canvas = static_cast<HTMLCanvasElement*>(renderer->node());
76         if (CanvasRenderingContext* context = canvas->renderingContext())
77             return context->isAccelerated();
78     }
79 #else
80     UNUSED_PARAM(renderer);
81 #endif
82     return false;
83 }
84
85 RenderLayerBacking::RenderLayerBacking(RenderLayer* layer)
86     : m_owningLayer(layer)
87     , m_artificiallyInflatedBounds(false)
88 {
89     createGraphicsLayer();
90 }
91
92 RenderLayerBacking::~RenderLayerBacking()
93 {
94     updateClippingLayers(false, false);
95     updateForegroundLayer(false);
96     updateMaskLayer(false);
97     destroyGraphicsLayer();
98 }
99
100 void RenderLayerBacking::createGraphicsLayer()
101 {
102     m_graphicsLayer = GraphicsLayer::create(this);
103     
104 #ifndef NDEBUG
105     m_graphicsLayer->setName(nameForLayer());
106 #endif  // NDEBUG
107
108 #if USE(ACCELERATED_COMPOSITING)
109     ASSERT(renderer() && renderer()->document() && renderer()->document()->frame());
110     if (Frame* frame = renderer()->document()->frame())
111         m_graphicsLayer->setContentsScale(frame->pageScaleFactor());
112 #endif
113
114     updateLayerOpacity(renderer()->style());
115     updateLayerTransform(renderer()->style());
116 }
117
118 void RenderLayerBacking::destroyGraphicsLayer()
119 {
120     if (m_graphicsLayer)
121         m_graphicsLayer->removeFromParent();
122
123     m_graphicsLayer = 0;
124     m_foregroundLayer = 0;
125     m_clippingLayer = 0;
126     m_maskLayer = 0;
127 }
128
129 void RenderLayerBacking::updateLayerOpacity(const RenderStyle* style)
130 {
131     m_graphicsLayer->setOpacity(compositingOpacity(style->opacity()));
132 }
133
134 void RenderLayerBacking::updateLayerTransform(const RenderStyle* style)
135 {
136     // FIXME: This could use m_owningLayer->transform(), but that currently has transform-origin
137     // baked into it, and we don't want that.
138     TransformationMatrix t;
139     if (m_owningLayer->hasTransform()) {
140         style->applyTransform(t, toRenderBox(renderer())->borderBoxRect().size(), RenderStyle::ExcludeTransformOrigin);
141         makeMatrixRenderable(t, compositor()->canRender3DTransforms());
142     }
143     
144     m_graphicsLayer->setTransform(t);
145 }
146
147 static bool hasNonZeroTransformOrigin(const RenderObject* renderer)
148 {
149     RenderStyle* style = renderer->style();
150     return (style->transformOriginX().type() == Fixed && style->transformOriginX().value())
151         || (style->transformOriginY().type() == Fixed && style->transformOriginY().value());
152 }
153
154 static bool layerOrAncestorIsTransformed(RenderLayer* layer)
155 {
156     for (RenderLayer* curr = layer; curr; curr = curr->parent()) {
157         if (curr->hasTransform())
158             return true;
159     }
160     
161     return false;
162 }
163     
164 #if ENABLE(FULLSCREEN_API)
165 static bool layerOrAncestorIsFullScreen(RenderLayer* layer)
166 {
167     // Don't traverse through the render layer tree if we do not yet have a full screen renderer.        
168     if (!layer->renderer()->document()->fullScreenRenderer())
169         return false;
170
171     for (RenderLayer* curr = layer; curr; curr = curr->parent()) {
172         if (curr->renderer()->isRenderFullScreen())
173             return true;
174     }
175     
176     return false;
177 }
178 #endif
179
180 void RenderLayerBacking::updateCompositedBounds()
181 {
182     IntRect layerBounds = compositor()->calculateCompositedBounds(m_owningLayer, m_owningLayer);
183
184     // Clip to the size of the document or enclosing overflow-scroll layer.
185     // If this or an ancestor is transformed, we can't currently compute the correct rect to intersect with.
186     // We'd need RenderObject::convertContainerToLocalQuad(), which doesn't yet exist.  If this
187     // is a fullscreen renderer, don't clip to the viewport, as the renderer will be asked to
188     // display outside of the viewport bounds.
189     if (compositor()->compositingConsultsOverlap() && !layerOrAncestorIsTransformed(m_owningLayer) 
190 #if ENABLE(FULLSCREEN_API)
191         && !layerOrAncestorIsFullScreen(m_owningLayer)
192 #endif
193         ) {
194         RenderView* view = m_owningLayer->renderer()->view();
195         RenderLayer* rootLayer = view->layer();
196
197         // Start by clipping to the view's bounds.
198         IntRect clippingBounds = view->layoutOverflowRect();
199
200         if (m_owningLayer != rootLayer)
201             clippingBounds.intersect(m_owningLayer->backgroundClipRect(rootLayer, true));
202
203         int deltaX = 0;
204         int deltaY = 0;
205         m_owningLayer->convertToLayerCoords(rootLayer, deltaX, deltaY);
206         clippingBounds.move(-deltaX, -deltaY);
207
208         layerBounds.intersect(clippingBounds);
209     }
210     
211     // If the element has a transform-origin that has fixed lengths, and the renderer has zero size,
212     // then we need to ensure that the compositing layer has non-zero size so that we can apply
213     // the transform-origin via the GraphicsLayer anchorPoint (which is expressed as a fractional value).
214     if (layerBounds.isEmpty() && hasNonZeroTransformOrigin(renderer())) {
215         layerBounds.setWidth(1);
216         layerBounds.setHeight(1);
217         m_artificiallyInflatedBounds = true;
218     } else
219         m_artificiallyInflatedBounds = false;
220
221     setCompositedBounds(layerBounds);
222 }
223
224 void RenderLayerBacking::updateAfterWidgetResize()
225 {
226     if (renderer()->isRenderIFrame()) {
227         if (RenderLayerCompositor* innerCompositor = RenderLayerCompositor::iframeContentsCompositor(toRenderIFrame(renderer())))
228             innerCompositor->frameViewDidChangeSize(contentsBox().location());
229     }
230 }
231
232 void RenderLayerBacking::updateAfterLayout(UpdateDepth updateDepth, bool isUpdateRoot)
233 {
234     RenderLayerCompositor* layerCompositor = compositor();
235     if (!layerCompositor->compositingLayersNeedRebuild()) {
236         // Calling updateGraphicsLayerGeometry() here gives incorrect results, because the
237         // position of this layer's GraphicsLayer depends on the position of our compositing
238         // ancestor's GraphicsLayer. That cannot be determined until all the descendant 
239         // RenderLayers of that ancestor have been processed via updateLayerPositions().
240         //
241         // The solution is to update compositing children of this layer here,
242         // via updateCompositingChildrenGeometry().
243         updateCompositedBounds();
244         layerCompositor->updateCompositingDescendantGeometry(m_owningLayer, m_owningLayer, updateDepth);
245         
246         if (isUpdateRoot) {
247             updateGraphicsLayerGeometry();
248             layerCompositor->updateRootLayerPosition();
249         }
250     }
251 }
252
253 bool RenderLayerBacking::updateGraphicsLayerConfiguration()
254 {
255     RenderLayerCompositor* compositor = this->compositor();
256     RenderObject* renderer = this->renderer();
257
258     bool layerConfigChanged = false;
259     if (updateForegroundLayer(compositor->needsContentsCompositingLayer(m_owningLayer)))
260         layerConfigChanged = true;
261     
262     if (updateClippingLayers(compositor->clippedByAncestor(m_owningLayer), compositor->clipsCompositingDescendants(m_owningLayer)))
263         layerConfigChanged = true;
264
265     if (updateMaskLayer(renderer->hasMask()))
266         m_graphicsLayer->setMaskLayer(m_maskLayer.get());
267
268     if (m_owningLayer->hasReflection()) {
269         if (m_owningLayer->reflectionLayer()->backing()) {
270             GraphicsLayer* reflectionLayer = m_owningLayer->reflectionLayer()->backing()->graphicsLayer();
271             m_graphicsLayer->setReplicatedByLayer(reflectionLayer);
272         }
273     } else
274         m_graphicsLayer->setReplicatedByLayer(0);
275
276     if (isDirectlyCompositedImage())
277         updateImageContents();
278
279     if ((renderer->isEmbeddedObject() && toRenderEmbeddedObject(renderer)->allowsAcceleratedCompositing())
280         || (renderer->isApplet() && toRenderApplet(renderer)->allowsAcceleratedCompositing())) {
281         PluginViewBase* pluginViewBase = static_cast<PluginViewBase*>(toRenderWidget(renderer)->widget());
282         m_graphicsLayer->setContentsToMedia(pluginViewBase->platformLayer());
283     }
284 #if ENABLE(VIDEO)
285     else if (renderer->isVideo()) {
286         HTMLMediaElement* mediaElement = static_cast<HTMLMediaElement*>(renderer->node());
287         m_graphicsLayer->setContentsToMedia(mediaElement->platformLayer());
288     }
289 #endif
290 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
291     else if (isAcceleratedCanvas(renderer)) {
292         HTMLCanvasElement* canvas = static_cast<HTMLCanvasElement*>(renderer->node());
293         if (CanvasRenderingContext* context = canvas->renderingContext())
294             m_graphicsLayer->setContentsToCanvas(context->platformLayer());
295         layerConfigChanged = true;
296     }
297 #endif
298
299     if (renderer->isRenderIFrame())
300         layerConfigChanged = RenderLayerCompositor::parentIFrameContentLayers(toRenderIFrame(renderer));
301
302     return layerConfigChanged;
303 }
304
305 static IntRect clipBox(RenderBox* renderer)
306 {
307     IntRect result = PaintInfo::infiniteRect();
308     if (renderer->hasOverflowClip())
309         result = renderer->overflowClipRect(0, 0);
310
311     if (renderer->hasClip())
312         result.intersect(renderer->clipRect(0, 0));
313
314     return result;
315 }
316
317 void RenderLayerBacking::updateGraphicsLayerGeometry()
318 {
319     // If we haven't built z-order lists yet, wait until later.
320     if (m_owningLayer->isStackingContext() && m_owningLayer->m_zOrderListsDirty)
321         return;
322
323     // Set transform property, if it is not animating. We have to do this here because the transform
324     // is affected by the layer dimensions.
325     if (!renderer()->animation()->isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyWebkitTransform))
326         updateLayerTransform(renderer()->style());
327
328     // Set opacity, if it is not animating.
329     if (!renderer()->animation()->isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyOpacity))
330         updateLayerOpacity(renderer()->style());
331     
332     RenderStyle* style = renderer()->style();
333     m_graphicsLayer->setPreserves3D(style->transformStyle3D() == TransformStyle3DPreserve3D && !renderer()->hasReflection());
334     m_graphicsLayer->setBackfaceVisibility(style->backfaceVisibility() == BackfaceVisibilityVisible);
335
336     RenderLayer* compAncestor = m_owningLayer->ancestorCompositingLayer();
337     
338     // We compute everything relative to the enclosing compositing layer.
339     IntRect ancestorCompositingBounds;
340     if (compAncestor) {
341         ASSERT(compAncestor->backing());
342         ancestorCompositingBounds = compAncestor->backing()->compositedBounds();
343     }
344
345     IntRect localCompositingBounds = compositedBounds();
346
347     IntRect relativeCompositingBounds(localCompositingBounds);
348     int deltaX = 0, deltaY = 0;
349     m_owningLayer->convertToLayerCoords(compAncestor, deltaX, deltaY);
350     relativeCompositingBounds.move(deltaX, deltaY);
351
352     IntPoint graphicsLayerParentLocation;
353     if (compAncestor && compAncestor->backing()->hasClippingLayer()) {
354         // If the compositing ancestor has a layer to clip children, we parent in that, and therefore
355         // position relative to it.
356         IntRect clippingBox = clipBox(toRenderBox(compAncestor->renderer()));
357         graphicsLayerParentLocation = clippingBox.location();
358     } else
359         graphicsLayerParentLocation = ancestorCompositingBounds.location();
360     
361     if (compAncestor && m_ancestorClippingLayer) {
362         // Call calculateRects to get the backgroundRect which is what is used to clip the contents of this
363         // layer. Note that we call it with temporaryClipRects = true because normally when computing clip rects
364         // for a compositing layer, rootLayer is the layer itself.
365         IntRect parentClipRect = m_owningLayer->backgroundClipRect(compAncestor, true);
366         m_ancestorClippingLayer->setPosition(FloatPoint() + (parentClipRect.location() - graphicsLayerParentLocation));
367         m_ancestorClippingLayer->setSize(parentClipRect.size());
368
369         // backgroundRect is relative to compAncestor, so subtract deltaX/deltaY to get back to local coords.
370         IntSize rendererOffset(parentClipRect.location().x() - deltaX, parentClipRect.location().y() - deltaY);
371         m_ancestorClippingLayer->setOffsetFromRenderer(rendererOffset);
372
373         // The primary layer is then parented in, and positioned relative to this clipping layer.
374         graphicsLayerParentLocation = parentClipRect.location();
375     }
376
377     m_graphicsLayer->setPosition(FloatPoint() + (relativeCompositingBounds.location() - graphicsLayerParentLocation));
378     
379     IntSize oldOffsetFromRenderer = m_graphicsLayer->offsetFromRenderer();
380     m_graphicsLayer->setOffsetFromRenderer(localCompositingBounds.location() - IntPoint());
381     // If the compositing layer offset changes, we need to repaint.
382     if (oldOffsetFromRenderer != m_graphicsLayer->offsetFromRenderer())
383         m_graphicsLayer->setNeedsDisplay();
384     
385     FloatSize oldSize = m_graphicsLayer->size();
386     FloatSize newSize = relativeCompositingBounds.size();
387     if (oldSize != newSize) {
388         m_graphicsLayer->setSize(newSize);
389         // A bounds change will almost always require redisplay. Usually that redisplay
390         // will happen because of a repaint elsewhere, but not always:
391         // e.g. see RenderView::setMaximalOutlineSize()
392         m_graphicsLayer->setNeedsDisplay();
393     }
394
395     // If we have a layer that clips children, position it.
396     IntRect clippingBox;
397     if (m_clippingLayer) {
398         clippingBox = clipBox(toRenderBox(renderer()));
399         m_clippingLayer->setPosition(FloatPoint() + (clippingBox.location() - localCompositingBounds.location()));
400         m_clippingLayer->setSize(clippingBox.size());
401         m_clippingLayer->setOffsetFromRenderer(clippingBox.location() - IntPoint());
402     }
403     
404     if (m_maskLayer) {
405         if (m_maskLayer->size() != m_graphicsLayer->size()) {
406             m_maskLayer->setSize(m_graphicsLayer->size());
407             m_maskLayer->setNeedsDisplay();
408         }
409         m_maskLayer->setPosition(FloatPoint());
410     }
411     
412     if (m_owningLayer->hasTransform()) {
413         const IntRect borderBox = toRenderBox(renderer())->borderBoxRect();
414
415         // Get layout bounds in the coords of compAncestor to match relativeCompositingBounds.
416         IntRect layerBounds = IntRect(deltaX, deltaY, borderBox.width(), borderBox.height());
417
418         // Update properties that depend on layer dimensions
419         FloatPoint3D transformOrigin = computeTransformOrigin(borderBox);
420         // Compute the anchor point, which is in the center of the renderer box unless transform-origin is set.
421         FloatPoint3D anchor(relativeCompositingBounds.width()  != 0.0f ? ((layerBounds.x() - relativeCompositingBounds.x()) + transformOrigin.x()) / relativeCompositingBounds.width()  : 0.5f,
422                             relativeCompositingBounds.height() != 0.0f ? ((layerBounds.y() - relativeCompositingBounds.y()) + transformOrigin.y()) / relativeCompositingBounds.height() : 0.5f,
423                             transformOrigin.z());
424         m_graphicsLayer->setAnchorPoint(anchor);
425
426         RenderStyle* style = renderer()->style();
427         if (style->hasPerspective()) {
428             TransformationMatrix t = owningLayer()->perspectiveTransform();
429             
430             if (m_clippingLayer) {
431                 m_clippingLayer->setChildrenTransform(t);
432                 m_graphicsLayer->setChildrenTransform(TransformationMatrix());
433             }
434             else
435                 m_graphicsLayer->setChildrenTransform(t);
436         } else {
437             if (m_clippingLayer)
438                 m_clippingLayer->setChildrenTransform(TransformationMatrix());
439             else
440                 m_graphicsLayer->setChildrenTransform(TransformationMatrix());
441         }
442     } else {
443         m_graphicsLayer->setAnchorPoint(FloatPoint3D(0.5f, 0.5f, 0));
444     }
445
446     if (m_foregroundLayer) {
447         FloatPoint foregroundPosition;
448         FloatSize foregroundSize = newSize;
449         IntSize foregroundOffset = m_graphicsLayer->offsetFromRenderer();
450         // If we have a clipping layer (which clips descendants), then the foreground layer is a child of it,
451         // so that it gets correctly sorted with children. In that case, position relative to the clipping layer.
452         if (m_clippingLayer) {
453             foregroundPosition = FloatPoint() + (localCompositingBounds.location() - clippingBox.location());
454             foregroundSize = FloatSize(clippingBox.size());
455             foregroundOffset = clippingBox.location() - IntPoint();
456         }
457
458         m_foregroundLayer->setPosition(foregroundPosition);
459         m_foregroundLayer->setSize(foregroundSize);
460         m_foregroundLayer->setOffsetFromRenderer(foregroundOffset);
461     }
462
463     if (m_owningLayer->reflectionLayer() && m_owningLayer->reflectionLayer()->isComposited()) {
464         RenderLayerBacking* reflectionBacking = m_owningLayer->reflectionLayer()->backing();
465         reflectionBacking->updateGraphicsLayerGeometry();
466         
467         // The reflection layer has the bounds of m_owningLayer->reflectionLayer(),
468         // but the reflected layer is the bounds of this layer, so we need to position it appropriately.
469         FloatRect layerBounds = compositedBounds();
470         FloatRect reflectionLayerBounds = reflectionBacking->compositedBounds();
471         reflectionBacking->graphicsLayer()->setReplicatedLayerPosition(FloatPoint() + (layerBounds.location() - reflectionLayerBounds.location()));
472     }
473
474     m_graphicsLayer->setContentsRect(contentsBox());
475     updateDrawsContent();
476     updateAfterWidgetResize();
477 }
478
479 void RenderLayerBacking::updateInternalHierarchy()
480 {
481     // m_foregroundLayer has to be inserted in the correct order with child layers,
482     // so it's not inserted here.
483     if (m_ancestorClippingLayer) {
484         m_ancestorClippingLayer->removeAllChildren();
485         m_graphicsLayer->removeFromParent();
486         m_ancestorClippingLayer->addChild(m_graphicsLayer.get());
487     }
488
489     if (m_clippingLayer) {
490         m_clippingLayer->removeFromParent();
491         m_graphicsLayer->addChild(m_clippingLayer.get());
492     }
493 }
494
495 void RenderLayerBacking::updateDrawsContent()
496 {
497     m_graphicsLayer->setDrawsContent(containsPaintedContent());
498 }
499
500 // Return true if the layers changed.
501 bool RenderLayerBacking::updateClippingLayers(bool needsAncestorClip, bool needsDescendantClip)
502 {
503     bool layersChanged = false;
504
505     if (needsAncestorClip) {
506         if (!m_ancestorClippingLayer) {
507             m_ancestorClippingLayer = GraphicsLayer::create(this);
508 #ifndef NDEBUG
509             m_ancestorClippingLayer->setName("Ancestor clipping Layer");
510 #endif
511             m_ancestorClippingLayer->setMasksToBounds(true);
512             layersChanged = true;
513         }
514     } else if (m_ancestorClippingLayer) {
515         m_ancestorClippingLayer->removeFromParent();
516         m_ancestorClippingLayer = 0;
517         layersChanged = true;
518     }
519     
520     if (needsDescendantClip) {
521         if (!m_clippingLayer) {
522             m_clippingLayer = GraphicsLayer::create(this);
523 #ifndef NDEBUG
524             m_clippingLayer->setName("Child clipping Layer");
525 #endif
526             m_clippingLayer->setMasksToBounds(true);
527             layersChanged = true;
528         }
529     } else if (m_clippingLayer) {
530         m_clippingLayer->removeFromParent();
531         m_clippingLayer = 0;
532         layersChanged = true;
533     }
534     
535     if (layersChanged)
536         updateInternalHierarchy();
537
538     return layersChanged;
539 }
540
541 bool RenderLayerBacking::updateForegroundLayer(bool needsForegroundLayer)
542 {
543     bool layerChanged = false;
544     if (needsForegroundLayer) {
545         if (!m_foregroundLayer) {
546             m_foregroundLayer = GraphicsLayer::create(this);
547 #ifndef NDEBUG
548             m_foregroundLayer->setName(nameForLayer() + " (foreground)");
549 #endif
550             m_foregroundLayer->setDrawsContent(true);
551             m_foregroundLayer->setPaintingPhase(GraphicsLayerPaintForeground);
552             if (Frame* frame = renderer()->document()->frame())
553                 m_foregroundLayer->setContentsScale(frame->pageScaleFactor());
554             layerChanged = true;
555         }
556     } else if (m_foregroundLayer) {
557         m_foregroundLayer->removeFromParent();
558         m_foregroundLayer = 0;
559         layerChanged = true;
560     }
561
562     if (layerChanged)
563         m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
564
565     return layerChanged;
566 }
567
568 bool RenderLayerBacking::updateMaskLayer(bool needsMaskLayer)
569 {
570     bool layerChanged = false;
571     if (needsMaskLayer) {
572         if (!m_maskLayer) {
573             m_maskLayer = GraphicsLayer::create(this);
574 #ifndef NDEBUG
575             m_maskLayer->setName("Mask");
576 #endif
577             m_maskLayer->setDrawsContent(true);
578             m_maskLayer->setPaintingPhase(GraphicsLayerPaintMask);
579             if (Frame* frame = renderer()->document()->frame())
580                 m_maskLayer->setContentsScale(frame->pageScaleFactor());
581             layerChanged = true;
582         }
583     } else if (m_maskLayer) {
584         m_maskLayer = 0;
585         layerChanged = true;
586     }
587
588     if (layerChanged)
589         m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
590
591     return layerChanged;
592 }
593
594 GraphicsLayerPaintingPhase RenderLayerBacking::paintingPhaseForPrimaryLayer() const
595 {
596     unsigned phase = GraphicsLayerPaintBackground;
597     if (!m_foregroundLayer)
598         phase |= GraphicsLayerPaintForeground;
599     if (!m_maskLayer)
600         phase |= GraphicsLayerPaintMask;
601
602     return static_cast<GraphicsLayerPaintingPhase>(phase);
603 }
604
605 float RenderLayerBacking::compositingOpacity(float rendererOpacity) const
606 {
607     float finalOpacity = rendererOpacity;
608     
609     for (RenderLayer* curr = m_owningLayer->parent(); curr; curr = curr->parent()) {
610         // We only care about parents that are stacking contexts.
611         // Recall that opacity creates stacking context.
612         if (!curr->isStackingContext())
613             continue;
614         
615         // If we found a compositing layer, we want to compute opacity
616         // relative to it. So we can break here.
617         if (curr->isComposited())
618             break;
619         
620         finalOpacity *= curr->renderer()->opacity();
621     }
622
623     return finalOpacity;
624 }
625
626 static bool hasBorderOutlineOrShadow(const RenderStyle* style)
627 {
628     return style->hasBorder() || style->hasBorderRadius() || style->hasOutline() || style->hasAppearance() || style->boxShadow();
629 }
630
631 static bool hasBoxDecorationsOrBackground(const RenderObject* renderer)
632 {
633     return hasBorderOutlineOrShadow(renderer->style()) || renderer->hasBackground();
634 }
635
636 static bool hasBoxDecorationsOrBackgroundImage(const RenderStyle* style)
637 {
638     return hasBorderOutlineOrShadow(style) || style->hasBackgroundImage();
639 }
640
641 bool RenderLayerBacking::rendererHasBackground() const
642 {
643     // FIXME: share more code here
644     if (renderer()->node() && renderer()->node()->isDocumentNode()) {
645         RenderObject* htmlObject = renderer()->firstChild();
646         if (!htmlObject)
647             return false;
648         
649         if (htmlObject->hasBackground())
650             return true;
651         
652         RenderObject* bodyObject = htmlObject->firstChild();
653         if (!bodyObject)
654             return false;
655         
656         return bodyObject->hasBackground();
657     }
658     
659     return renderer()->hasBackground();
660 }
661
662 const Color RenderLayerBacking::rendererBackgroundColor() const
663 {
664     // FIXME: share more code here
665     if (renderer()->node() && renderer()->node()->isDocumentNode()) {
666         RenderObject* htmlObject = renderer()->firstChild();
667         if (htmlObject->hasBackground())
668             return htmlObject->style()->visitedDependentColor(CSSPropertyBackgroundColor);
669
670         RenderObject* bodyObject = htmlObject->firstChild();
671         return bodyObject->style()->visitedDependentColor(CSSPropertyBackgroundColor);
672     }
673
674     return renderer()->style()->visitedDependentColor(CSSPropertyBackgroundColor);
675 }
676
677 // A "simple container layer" is a RenderLayer which has no visible content to render.
678 // It may have no children, or all its children may be themselves composited.
679 // This is a useful optimization, because it allows us to avoid allocating backing store.
680 bool RenderLayerBacking::isSimpleContainerCompositingLayer() const
681 {
682     RenderObject* renderObject = renderer();
683     if (renderObject->isReplaced() ||       // replaced objects are not containers
684         renderObject->hasMask())            // masks require special treatment
685         return false;
686
687     RenderStyle* style = renderObject->style();
688
689     // Reject anything that has a border, a border-radius or outline,
690     // or any background (color or image).
691     // FIXME: we could optimize layers for simple backgrounds.
692     if (hasBoxDecorationsOrBackground(renderObject))
693         return false;
694
695     if (m_owningLayer->hasOverflowControls())
696         return false;
697
698     // If we have got this far and the renderer has no children, then we're ok.
699     if (!renderObject->firstChild())
700         return true;
701     
702     if (renderObject->node() && renderObject->node()->isDocumentNode()) {
703         // Look to see if the root object has a non-simple backgound
704         RenderObject* rootObject = renderObject->document()->documentElement()->renderer();
705         if (!rootObject)
706             return false;
707         
708         style = rootObject->style();
709         
710         // Reject anything that has a border, a border-radius or outline,
711         // or is not a simple background (no background, or solid color).
712         if (hasBoxDecorationsOrBackgroundImage(style))
713             return false;
714         
715         // Now look at the body's renderer.
716         HTMLElement* body = renderObject->document()->body();
717         RenderObject* bodyObject = (body && body->hasLocalName(bodyTag)) ? body->renderer() : 0;
718         if (!bodyObject)
719             return false;
720         
721         style = bodyObject->style();
722         
723         if (hasBoxDecorationsOrBackgroundImage(style))
724             return false;
725
726         // Check to see if all the body's children are compositing layers.
727         if (hasNonCompositingDescendants())
728             return false;
729         
730         return true;
731     }
732
733     // Check to see if all the renderer's children are compositing layers.
734     if (hasNonCompositingDescendants())
735         return false;
736     
737     return true;
738 }
739
740 // Conservative test for having no rendered children.
741 bool RenderLayerBacking::hasNonCompositingDescendants() const
742 {
743     // Some HTML can cause whitespace text nodes to have renderers, like:
744     // <div>
745     // <img src=...>
746     // </div>
747     // so test for 0x0 RenderTexts here
748     for (RenderObject* child = renderer()->firstChild(); child; child = child->nextSibling()) {
749         if (!child->hasLayer()) {
750             if (child->isRenderInline() || !child->isBox())
751                 return true;
752             
753             if (toRenderBox(child)->width() > 0 || toRenderBox(child)->height() > 0)
754                 return true;
755         }
756     }
757
758     if (m_owningLayer->isStackingContext()) {
759         // Use the m_hasCompositingDescendant bit to optimize?
760         if (Vector<RenderLayer*>* negZOrderList = m_owningLayer->negZOrderList()) {
761             size_t listSize = negZOrderList->size();
762             for (size_t i = 0; i < listSize; ++i) {
763                 RenderLayer* curLayer = negZOrderList->at(i);
764                 if (!curLayer->isComposited())
765                     return true;
766             }
767         }
768
769         if (Vector<RenderLayer*>* posZOrderList = m_owningLayer->posZOrderList()) {
770             size_t listSize = posZOrderList->size();
771             for (size_t i = 0; i < listSize; ++i) {
772                 RenderLayer* curLayer = posZOrderList->at(i);
773                 if (!curLayer->isComposited())
774                     return true;
775             }
776         }
777     }
778
779     if (Vector<RenderLayer*>* normalFlowList = m_owningLayer->normalFlowList()) {
780         size_t listSize = normalFlowList->size();
781         for (size_t i = 0; i < listSize; ++i) {
782             RenderLayer* curLayer = normalFlowList->at(i);
783             if (!curLayer->isComposited())
784                 return true;
785         }
786     }
787
788     return false;
789 }
790
791 bool RenderLayerBacking::containsPaintedContent() const
792 {
793     if (isSimpleContainerCompositingLayer() || paintingGoesToWindow() || m_artificiallyInflatedBounds || m_owningLayer->isReflection())
794         return false;
795
796     if (isDirectlyCompositedImage())
797         return false;
798
799     // FIXME: we could optimize cases where the image, video or canvas is known to fill the border box entirely,
800     // and set background color on the layer in that case, instead of allocating backing store and painting.
801 #if ENABLE(VIDEO)
802     if (renderer()->isVideo() && toRenderVideo(renderer())->shouldDisplayVideo())
803         return hasBoxDecorationsOrBackground(renderer());
804 #endif
805 #if PLATFORM(MAC) && PLATFORM(CA) && !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD) && !defined(BUILDING_ON_SNOW_LEOPARD)
806 #elif ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
807     if (isAcceleratedCanvas(renderer()))
808         return hasBoxDecorationsOrBackground(renderer());
809 #endif
810
811     return true;
812 }
813
814 // An image can be directly compositing if it's the sole content of the layer, and has no box decorations
815 // that require painting. Direct compositing saves backing store.
816 bool RenderLayerBacking::isDirectlyCompositedImage() const
817 {
818     RenderObject* renderObject = renderer();
819     
820     if (!renderObject->isImage() || hasBoxDecorationsOrBackground(renderObject) || renderObject->hasClip())
821         return false;
822
823     RenderImage* imageRenderer = toRenderImage(renderObject);
824     if (CachedImage* cachedImage = imageRenderer->cachedImage()) {
825         if (cachedImage->hasImage())
826             return cachedImage->image()->isBitmapImage();
827     }
828
829     return false;
830 }
831
832 void RenderLayerBacking::contentChanged(RenderLayer::ContentChangeType changeType)
833 {
834     if ((changeType == RenderLayer::ImageChanged) && isDirectlyCompositedImage()) {
835         updateImageContents();
836         return;
837     }
838     
839     if ((changeType == RenderLayer::MaskImageChanged) && m_maskLayer) {
840         // The composited layer bounds relies on box->maskClipRect(), which changes
841         // when the mask image becomes available.
842         bool isUpdateRoot = true;
843         updateAfterLayout(CompositingChildren, isUpdateRoot);
844     }
845
846 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
847     if ((changeType == RenderLayer::CanvasChanged) && isAcceleratedCanvas(renderer())) {
848         m_graphicsLayer->setContentsNeedsDisplay();
849         return;
850     }
851 #endif
852 }
853
854 void RenderLayerBacking::updateImageContents()
855 {
856     ASSERT(renderer()->isImage());
857     RenderImage* imageRenderer = toRenderImage(renderer());
858
859     CachedImage* cachedImage = imageRenderer->cachedImage();
860     if (!cachedImage)
861         return;
862
863     Image* image = cachedImage->image();
864     if (!image)
865         return;
866
867     // We have to wait until the image is fully loaded before setting it on the layer.
868     if (!cachedImage->isLoaded())
869         return;
870
871     // This is a no-op if the layer doesn't have an inner layer for the image.
872     m_graphicsLayer->setContentsToImage(image);
873     
874     // Image animation is "lazy", in that it automatically stops unless someone is drawing
875     // the image. So we have to kick the animation each time; this has the downside that the
876     // image will keep animating, even if its layer is not visible.
877     image->startAnimation();
878 }
879
880 FloatPoint3D RenderLayerBacking::computeTransformOrigin(const IntRect& borderBox) const
881 {
882     RenderStyle* style = renderer()->style();
883
884     FloatPoint3D origin;
885     origin.setX(style->transformOriginX().calcFloatValue(borderBox.width()));
886     origin.setY(style->transformOriginY().calcFloatValue(borderBox.height()));
887     origin.setZ(style->transformOriginZ());
888
889     return origin;
890 }
891
892 FloatPoint RenderLayerBacking::computePerspectiveOrigin(const IntRect& borderBox) const
893 {
894     RenderStyle* style = renderer()->style();
895
896     float boxWidth = borderBox.width();
897     float boxHeight = borderBox.height();
898
899     FloatPoint origin;
900     origin.setX(style->perspectiveOriginX().calcFloatValue(boxWidth));
901     origin.setY(style->perspectiveOriginY().calcFloatValue(boxHeight));
902
903     return origin;
904 }
905
906 // Return the offset from the top-left of this compositing layer at which the renderer's contents are painted.
907 IntSize RenderLayerBacking::contentOffsetInCompostingLayer() const
908 {
909     return IntSize(-m_compositedBounds.x(), -m_compositedBounds.y());
910 }
911
912 IntRect RenderLayerBacking::contentsBox() const
913 {
914     if (!renderer()->isBox())
915         return IntRect();
916
917     IntRect contentsRect;
918 #if ENABLE(VIDEO)
919     if (renderer()->isVideo()) {
920         RenderVideo* videoRenderer = toRenderVideo(renderer());
921         contentsRect = videoRenderer->videoBox();
922     } else
923 #endif
924         contentsRect = toRenderBox(renderer())->contentBoxRect();
925
926     IntSize contentOffset = contentOffsetInCompostingLayer();
927     contentsRect.move(contentOffset);
928     return contentsRect;
929 }
930
931 // Map the given point from coordinates in the GraphicsLayer to RenderLayer coordinates.
932 FloatPoint RenderLayerBacking::graphicsLayerToContentsCoordinates(const GraphicsLayer* graphicsLayer, const FloatPoint& point)
933 {
934     return point + FloatSize(graphicsLayer->offsetFromRenderer());
935 }
936
937 // Map the given point from coordinates in the RenderLayer to GraphicsLayer coordinates.
938 FloatPoint RenderLayerBacking::contentsToGraphicsLayerCoordinates(const GraphicsLayer* graphicsLayer, const FloatPoint& point)
939 {
940     return point - FloatSize(graphicsLayer->offsetFromRenderer());
941 }
942
943 bool RenderLayerBacking::paintingGoesToWindow() const
944 {
945     if (m_owningLayer->isRootLayer())
946         return compositor()->rootLayerAttachment() != RenderLayerCompositor::RootLayerAttachedViaEnclosingIframe;
947     
948     return false;
949 }
950
951 void RenderLayerBacking::setContentsNeedDisplay()
952 {
953     if (m_graphicsLayer && m_graphicsLayer->drawsContent())
954         m_graphicsLayer->setNeedsDisplay();
955     
956     if (m_foregroundLayer && m_foregroundLayer->drawsContent())
957         m_foregroundLayer->setNeedsDisplay();
958
959     if (m_maskLayer && m_maskLayer->drawsContent())
960         m_maskLayer->setNeedsDisplay();
961 }
962
963 // r is in the coordinate space of the layer's render object
964 void RenderLayerBacking::setContentsNeedDisplayInRect(const IntRect& r)
965 {
966     if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
967         FloatPoint dirtyOrigin = contentsToGraphicsLayerCoordinates(m_graphicsLayer.get(), FloatPoint(r.x(), r.y()));
968         FloatRect dirtyRect(dirtyOrigin, r.size());
969         FloatRect bounds(FloatPoint(), m_graphicsLayer->size());
970         if (bounds.intersects(dirtyRect))
971             m_graphicsLayer->setNeedsDisplayInRect(dirtyRect);
972     }
973
974     if (m_foregroundLayer && m_foregroundLayer->drawsContent()) {
975         // FIXME: do incremental repaint
976         m_foregroundLayer->setNeedsDisplay();
977     }
978
979     if (m_maskLayer && m_maskLayer->drawsContent()) {
980         // FIXME: do incremental repaint
981         m_maskLayer->setNeedsDisplay();
982     }
983 }
984
985 static void setClip(GraphicsContext* p, const IntRect& paintDirtyRect, const IntRect& clipRect)
986 {
987     if (paintDirtyRect == clipRect)
988         return;
989     p->save();
990     p->clip(clipRect);
991 }
992
993 static void restoreClip(GraphicsContext* p, const IntRect& paintDirtyRect, const IntRect& clipRect)
994 {
995     if (paintDirtyRect == clipRect)
996         return;
997     p->restore();
998 }
999
1000 // Share this with RenderLayer::paintLayer, which would have to be educated about GraphicsLayerPaintingPhase?
1001 void RenderLayerBacking::paintIntoLayer(RenderLayer* rootLayer, GraphicsContext* context,
1002                     const IntRect& paintDirtyRect,      // in the coords of rootLayer
1003                     PaintBehavior paintBehavior, GraphicsLayerPaintingPhase paintingPhase,
1004                     RenderObject* paintingRoot)
1005 {
1006     if (paintingGoesToWindow()) {
1007         ASSERT_NOT_REACHED();
1008         return;
1009     }
1010     
1011     m_owningLayer->updateLayerListsIfNeeded();
1012     
1013     // Calculate the clip rects we should use.
1014     IntRect layerBounds, damageRect, clipRectToApply, outlineRect;
1015     m_owningLayer->calculateRects(rootLayer, paintDirtyRect, layerBounds, damageRect, clipRectToApply, outlineRect);
1016     
1017     int x = layerBounds.x();        // layerBounds is computed relative to rootLayer
1018     int y = layerBounds.y();
1019     int tx = x - m_owningLayer->renderBoxX();
1020     int ty = y - m_owningLayer->renderBoxY();
1021
1022     // If this layer's renderer is a child of the paintingRoot, we render unconditionally, which
1023     // is done by passing a nil paintingRoot down to our renderer (as if no paintingRoot was ever set).
1024     // Else, our renderer tree may or may not contain the painting root, so we pass that root along
1025     // so it will be tested against as we decend through the renderers.
1026     RenderObject *paintingRootForRenderer = 0;
1027     if (paintingRoot && !renderer()->isDescendantOf(paintingRoot))
1028         paintingRootForRenderer = paintingRoot;
1029
1030     bool shouldPaint = (m_owningLayer->hasVisibleContent() || m_owningLayer->hasVisibleDescendant()) && m_owningLayer->isSelfPaintingLayer();
1031
1032     if (shouldPaint && (paintingPhase & GraphicsLayerPaintBackground)) {
1033         // Paint our background first, before painting any child layers.
1034         // Establish the clip used to paint our background.
1035         setClip(context, paintDirtyRect, damageRect);
1036         
1037         PaintInfo info(context, damageRect, PaintPhaseBlockBackground, false, paintingRootForRenderer, 0);
1038         renderer()->paint(info, tx, ty);
1039
1040         // Our scrollbar widgets paint exactly when we tell them to, so that they work properly with
1041         // z-index.  We paint after we painted the background/border, so that the scrollbars will
1042         // sit above the background/border.
1043         m_owningLayer->paintOverflowControls(context, x, y, damageRect);
1044         
1045         // Restore the clip.
1046         restoreClip(context, paintDirtyRect, damageRect);
1047 #if ENABLE(ANDROID_OVERFLOW_SCROLL)
1048         // Paint the outline as part of the background phase in order for the
1049         // outline to not be a part of the scrollable content.
1050         if (!outlineRect.isEmpty()) {
1051             // Paint our own outline
1052             PaintInfo paintInfo(context, outlineRect, PaintPhaseSelfOutline, false, paintingRootForRenderer, 0);
1053             setClip(context, paintDirtyRect, outlineRect);
1054             renderer()->paint(paintInfo, tx, ty);
1055             restoreClip(context, paintDirtyRect, outlineRect);
1056         }
1057 #endif
1058
1059         // Now walk the sorted list of children with negative z-indices. Only RenderLayers without compositing layers will paint.
1060         m_owningLayer->paintList(m_owningLayer->negZOrderList(), rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, 0, 0);
1061     }
1062                 
1063     bool forceBlackText = paintBehavior & PaintBehaviorForceBlackText;
1064     bool selectionOnly  = paintBehavior & PaintBehaviorSelectionOnly;
1065
1066     if (shouldPaint && (paintingPhase & GraphicsLayerPaintForeground)) {
1067         // Set up the clip used when painting our children.
1068         setClip(context, paintDirtyRect, clipRectToApply);
1069         PaintInfo paintInfo(context, clipRectToApply, 
1070                                           selectionOnly ? PaintPhaseSelection : PaintPhaseChildBlockBackgrounds,
1071                                           forceBlackText, paintingRootForRenderer, 0);
1072         renderer()->paint(paintInfo, tx, ty);
1073
1074         if (!selectionOnly) {
1075             paintInfo.phase = PaintPhaseFloat;
1076             renderer()->paint(paintInfo, tx, ty);
1077
1078             paintInfo.phase = PaintPhaseForeground;
1079             renderer()->paint(paintInfo, tx, ty);
1080
1081             paintInfo.phase = PaintPhaseChildOutlines;
1082             renderer()->paint(paintInfo, tx, ty);
1083         }
1084
1085         // Now restore our clip.
1086         restoreClip(context, paintDirtyRect, clipRectToApply);
1087
1088 #if !ENABLE(ANDROID_OVERFLOW_SCROLL)
1089         // Do not paint the outline as part of the foreground since it will
1090         // appear inside the scrollable content.
1091         if (!outlineRect.isEmpty()) {
1092             // Paint our own outline
1093             PaintInfo paintInfo(context, outlineRect, PaintPhaseSelfOutline, false, paintingRootForRenderer, 0);
1094             setClip(context, paintDirtyRect, outlineRect);
1095             renderer()->paint(paintInfo, tx, ty);
1096             restoreClip(context, paintDirtyRect, outlineRect);
1097         }
1098 #endif
1099
1100         // Paint any child layers that have overflow.
1101         m_owningLayer->paintList(m_owningLayer->normalFlowList(), rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, 0, 0);
1102
1103         // Now walk the sorted list of children with positive z-indices.
1104         m_owningLayer->paintList(m_owningLayer->posZOrderList(), rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, 0, 0);
1105     }
1106     
1107     if (shouldPaint && (paintingPhase & GraphicsLayerPaintMask)) {
1108         if (renderer()->hasMask() && !selectionOnly && !damageRect.isEmpty()) {
1109             setClip(context, paintDirtyRect, damageRect);
1110
1111             // Paint the mask.
1112             PaintInfo paintInfo(context, damageRect, PaintPhaseMask, false, paintingRootForRenderer, 0);
1113             renderer()->paint(paintInfo, tx, ty);
1114             
1115             // Restore the clip.
1116             restoreClip(context, paintDirtyRect, damageRect);
1117         }
1118     }
1119
1120     ASSERT(!m_owningLayer->m_usedTransparency);
1121 }
1122
1123 // Up-call from compositing layer drawing callback.
1124 void RenderLayerBacking::paintContents(const GraphicsLayer*, GraphicsContext& context, GraphicsLayerPaintingPhase paintingPhase, const IntRect& clip)
1125 {
1126     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willPaint(m_owningLayer->renderer()->frame(), clip);
1127
1128     // We have to use the same root as for hit testing, because both methods
1129     // can compute and cache clipRects.
1130     IntRect enclosingBBox = compositedBounds();
1131 #if ENABLE(ANDROID_OVERFLOW_SCROLL)
1132     // If we encounter a scrollable layer, layers inside the scrollable layer
1133     // will need their entire content recorded.
1134     if (m_owningLayer->hasOverflowParent())
1135         enclosingBBox.setSize(clip.size());
1136 #endif
1137
1138     IntRect clipRect(clip);
1139     
1140     // Set up the coordinate space to be in the layer's rendering coordinates.
1141     context.translate(-enclosingBBox.x(), -enclosingBBox.y());
1142
1143     // Offset the clip.
1144     clipRect.move(enclosingBBox.x(), enclosingBBox.y());
1145     
1146     // The dirtyRect is in the coords of the painting root.
1147     IntRect dirtyRect = enclosingBBox;
1148     dirtyRect.intersect(clipRect);
1149
1150     paintIntoLayer(m_owningLayer, &context, dirtyRect, PaintBehaviorNormal, paintingPhase, renderer());
1151
1152     InspectorInstrumentation::didPaint(cookie);
1153 }
1154
1155 bool RenderLayerBacking::showDebugBorders() const
1156 {
1157     return compositor() ? compositor()->compositorShowDebugBorders() : false;
1158 }
1159
1160 bool RenderLayerBacking::showRepaintCounter() const
1161 {
1162     return compositor() ? compositor()->compositorShowRepaintCounter() : false;
1163 }
1164
1165 bool RenderLayerBacking::startAnimation(double timeOffset, const Animation* anim, const KeyframeList& keyframes)
1166 {
1167     bool hasOpacity = keyframes.containsProperty(CSSPropertyOpacity);
1168     bool hasTransform = renderer()->isBox() && keyframes.containsProperty(CSSPropertyWebkitTransform);
1169     
1170     if (!hasOpacity && !hasTransform)
1171         return false;
1172     
1173     KeyframeValueList transformVector(AnimatedPropertyWebkitTransform);
1174     KeyframeValueList opacityVector(AnimatedPropertyOpacity);
1175
1176     size_t numKeyframes = keyframes.size();
1177     for (size_t i = 0; i < numKeyframes; ++i) {
1178         const KeyframeValue& currentKeyframe = keyframes[i];
1179         const RenderStyle* keyframeStyle = currentKeyframe.style();
1180         float key = currentKeyframe.key();
1181
1182         if (!keyframeStyle)
1183             continue;
1184             
1185         // Get timing function.
1186         RefPtr<TimingFunction> tf = keyframeStyle->hasAnimations() ? (*keyframeStyle->animations()).animation(0)->timingFunction() : 0;
1187         
1188         bool isFirstOrLastKeyframe = key == 0 || key == 1;
1189         if ((hasTransform && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitTransform))
1190             transformVector.insert(new TransformAnimationValue(key, &(keyframeStyle->transform()), tf));
1191         
1192         if ((hasOpacity && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyOpacity))
1193             opacityVector.insert(new FloatAnimationValue(key, keyframeStyle->opacity(), tf));
1194     }
1195
1196     bool didAnimateTransform = false;
1197     bool didAnimateOpacity = false;
1198     
1199     if (hasTransform && m_graphicsLayer->addAnimation(transformVector, toRenderBox(renderer())->borderBoxRect().size(), anim, keyframes.animationName(), timeOffset)) {
1200         didAnimateTransform = true;
1201         compositor()->didStartAcceleratedAnimation(CSSPropertyWebkitTransform);
1202     }
1203
1204     if (hasOpacity && m_graphicsLayer->addAnimation(opacityVector, IntSize(), anim, keyframes.animationName(), timeOffset)) {
1205         didAnimateOpacity = true;
1206         compositor()->didStartAcceleratedAnimation(CSSPropertyOpacity);
1207     }
1208
1209     return didAnimateTransform || didAnimateOpacity;
1210 }
1211
1212 void RenderLayerBacking::animationPaused(double timeOffset, const String& animationName)
1213 {
1214     m_graphicsLayer->pauseAnimation(animationName, timeOffset);
1215 }
1216
1217 void RenderLayerBacking::animationFinished(const String& animationName)
1218 {
1219     m_graphicsLayer->removeAnimation(animationName);
1220 }
1221
1222 bool RenderLayerBacking::startTransition(double timeOffset, int property, const RenderStyle* fromStyle, const RenderStyle* toStyle)
1223 {
1224     bool didAnimateOpacity = false;
1225     bool didAnimateTransform = false;
1226     ASSERT(property != cAnimateAll);
1227
1228     if (property == (int)CSSPropertyOpacity) {
1229         const Animation* opacityAnim = toStyle->transitionForProperty(CSSPropertyOpacity);
1230         if (opacityAnim && !opacityAnim->isEmptyOrZeroDuration()) {
1231             KeyframeValueList opacityVector(AnimatedPropertyOpacity);
1232             opacityVector.insert(new FloatAnimationValue(0, compositingOpacity(fromStyle->opacity())));
1233             opacityVector.insert(new FloatAnimationValue(1, compositingOpacity(toStyle->opacity())));
1234             // The boxSize param is only used for transform animations (which can only run on RenderBoxes), so we pass an empty size here.
1235             if (m_graphicsLayer->addAnimation(opacityVector, IntSize(), opacityAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyOpacity), timeOffset)) {
1236                 // To ensure that the correct opacity is visible when the animation ends, also set the final opacity.
1237                 updateLayerOpacity(toStyle);
1238                 didAnimateOpacity = true;
1239             }
1240         }
1241     }
1242
1243     if (property == (int)CSSPropertyWebkitTransform && m_owningLayer->hasTransform()) {
1244         const Animation* transformAnim = toStyle->transitionForProperty(CSSPropertyWebkitTransform);
1245         if (transformAnim && !transformAnim->isEmptyOrZeroDuration()) {
1246             KeyframeValueList transformVector(AnimatedPropertyWebkitTransform);
1247             transformVector.insert(new TransformAnimationValue(0, &fromStyle->transform()));
1248             transformVector.insert(new TransformAnimationValue(1, &toStyle->transform()));
1249             if (m_graphicsLayer->addAnimation(transformVector, toRenderBox(renderer())->borderBoxRect().size(), transformAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyWebkitTransform), timeOffset)) {
1250                 // To ensure that the correct transform is visible when the animation ends, also set the final opacity.
1251                 updateLayerTransform(toStyle);
1252                 didAnimateTransform = true;
1253             }
1254         }
1255     }
1256
1257     if (didAnimateOpacity)
1258         compositor()->didStartAcceleratedAnimation(CSSPropertyOpacity);
1259
1260     if (didAnimateTransform)
1261         compositor()->didStartAcceleratedAnimation(CSSPropertyWebkitTransform);
1262     
1263     return didAnimateOpacity || didAnimateTransform;
1264 }
1265
1266 void RenderLayerBacking::transitionPaused(double timeOffset, int property)
1267 {
1268     AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
1269     if (animatedProperty != AnimatedPropertyInvalid)
1270         m_graphicsLayer->pauseAnimation(GraphicsLayer::animationNameForTransition(animatedProperty), timeOffset);
1271 }
1272
1273 void RenderLayerBacking::transitionFinished(int property)
1274 {
1275     AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
1276     if (animatedProperty != AnimatedPropertyInvalid)
1277         m_graphicsLayer->removeAnimation(GraphicsLayer::animationNameForTransition(animatedProperty));
1278 }
1279
1280 void RenderLayerBacking::notifyAnimationStarted(const GraphicsLayer*, double time)
1281 {
1282     renderer()->animation()->notifyAnimationStarted(renderer(), time);
1283 }
1284
1285 void RenderLayerBacking::notifySyncRequired(const GraphicsLayer*)
1286 {
1287     if (!renderer()->documentBeingDestroyed())
1288         compositor()->scheduleLayerFlush();
1289 }
1290
1291 // This is used for the 'freeze' API, for testing only.
1292 void RenderLayerBacking::suspendAnimations(double time)
1293 {
1294     m_graphicsLayer->suspendAnimations(time);
1295 }
1296
1297 void RenderLayerBacking::resumeAnimations()
1298 {
1299     m_graphicsLayer->resumeAnimations();
1300 }
1301
1302 IntRect RenderLayerBacking::compositedBounds() const
1303 {
1304     return m_compositedBounds;
1305 }
1306
1307 void RenderLayerBacking::setCompositedBounds(const IntRect& bounds)
1308 {
1309     m_compositedBounds = bounds;
1310
1311 }
1312 int RenderLayerBacking::graphicsLayerToCSSProperty(AnimatedPropertyID property)
1313 {
1314     int cssProperty = CSSPropertyInvalid;
1315     switch (property) {
1316         case AnimatedPropertyWebkitTransform:
1317             cssProperty = CSSPropertyWebkitTransform;
1318             break;
1319         case AnimatedPropertyOpacity:
1320             cssProperty = CSSPropertyOpacity;
1321             break;
1322         case AnimatedPropertyBackgroundColor:
1323             cssProperty = CSSPropertyBackgroundColor;
1324             break;
1325         case AnimatedPropertyInvalid:
1326             ASSERT_NOT_REACHED();
1327     }
1328     return cssProperty;
1329 }
1330
1331 AnimatedPropertyID RenderLayerBacking::cssToGraphicsLayerProperty(int cssProperty)
1332 {
1333     switch (cssProperty) {
1334         case CSSPropertyWebkitTransform:
1335             return AnimatedPropertyWebkitTransform;
1336         case CSSPropertyOpacity:
1337             return AnimatedPropertyOpacity;
1338         case CSSPropertyBackgroundColor:
1339             return AnimatedPropertyBackgroundColor;
1340         // It's fine if we see other css properties here; they are just not accelerated.
1341     }
1342     return AnimatedPropertyInvalid;
1343 }
1344
1345 #ifndef NDEBUG
1346 String RenderLayerBacking::nameForLayer() const
1347 {
1348     String name = renderer()->renderName();
1349     if (Node* node = renderer()->node()) {
1350         if (node->isElementNode())
1351             name += " " + static_cast<Element*>(node)->tagName();
1352         if (node->hasID())
1353             name += " \'" + static_cast<Element*>(node)->getIdAttribute() + "\'";
1354     }
1355
1356     if (m_owningLayer->isReflection())
1357         name += " (reflection)";
1358
1359     return name;
1360 }
1361 #endif
1362
1363 CompositingLayerType RenderLayerBacking::compositingLayerType() const
1364 {
1365     if (m_graphicsLayer->hasContentsLayer())
1366         return MediaCompositingLayer;
1367
1368     if (m_graphicsLayer->drawsContent())
1369         return m_graphicsLayer->usingTiledLayer() ? TiledCompositingLayer : NormalCompositingLayer;
1370     
1371     return ContainerCompositingLayer;
1372 }
1373
1374 void RenderLayerBacking::updateContentsScale(float scale)
1375 {
1376     if (m_graphicsLayer)
1377         m_graphicsLayer->setContentsScale(scale);
1378
1379     if (m_foregroundLayer)
1380         m_foregroundLayer->setContentsScale(scale);
1381
1382     if (m_maskLayer)
1383         m_maskLayer->setContentsScale(scale);
1384 }
1385
1386 } // namespace WebCore
1387
1388 #endif // USE(ACCELERATED_COMPOSITING)