Unreviewed Chromium build fix after http://trac.webkit.org/changeset/116799.
[WebKit-https.git] / Source / WebCore / rendering / RenderLayerBacking.cpp
1 /*
2  * Copyright (C) 2009, 2010, 2011 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE 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 "CSSPropertyNames.h"
35 #include "Chrome.h"
36 #include "FontCache.h"
37 #include "FrameView.h"
38 #include "GraphicsContext.h"
39 #include "GraphicsLayer.h"
40 #include "HTMLCanvasElement.h"
41 #include "HTMLIFrameElement.h"
42 #include "HTMLMediaElement.h"
43 #include "HTMLNames.h"
44 #include "InspectorInstrumentation.h"
45 #include "KeyframeList.h"
46 #include "PluginViewBase.h"
47 #include "RenderApplet.h"
48 #include "RenderIFrame.h"
49 #include "RenderImage.h"
50 #include "RenderLayerCompositor.h"
51 #include "RenderEmbeddedObject.h"
52 #include "RenderVideo.h"
53 #include "RenderView.h"
54 #include "StyleResolver.h"
55 #include "TiledBacking.h"
56
57 #include <wtf/CurrentTime.h>
58
59 #if ENABLE(CSS_FILTERS)
60 #include "FilterEffectRenderer.h"
61 #endif
62
63 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
64 #include "GraphicsContext3D.h"
65 #endif
66
67 using namespace std;
68
69 namespace WebCore {
70
71 using namespace HTMLNames;
72
73 static bool hasBoxDecorations(const RenderStyle*);
74 static bool hasBoxDecorationsOrBackground(const RenderObject*);
75 static bool hasBoxDecorationsOrBackgroundImage(const RenderStyle*);
76 static IntRect clipBox(RenderBox* renderer);
77
78 static inline bool isAcceleratedCanvas(RenderObject* renderer)
79 {
80 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
81     if (renderer->isCanvas()) {
82         HTMLCanvasElement* canvas = static_cast<HTMLCanvasElement*>(renderer->node());
83         if (CanvasRenderingContext* context = canvas->renderingContext())
84             return context->isAccelerated();
85     }
86 #else
87     UNUSED_PARAM(renderer);
88 #endif
89     return false;
90 }
91
92 RenderLayerBacking::RenderLayerBacking(RenderLayer* layer)
93     : m_owningLayer(layer)
94     , m_artificiallyInflatedBounds(false)
95     , m_isMainFrameRenderViewLayer(false)
96     , m_usingTiledCacheLayer(false)
97     , m_requiresOwnBackingStore(true)
98 #if ENABLE(CSS_FILTERS)
99     , m_canCompositeFilters(false)
100 #endif
101 {
102     if (renderer()->isRenderView()) {
103         Frame* frame = toRenderView(renderer())->frameView()->frame();
104         Page* page = frame ? frame->page() : 0;
105         if (page && frame && page->mainFrame() == frame) {
106             m_isMainFrameRenderViewLayer = true;
107
108 #if PLATFORM(MAC)
109             // FIXME: It's a little weird that we base this decision on whether there's a scrolling coordinator or not.
110             if (page->scrollingCoordinator())
111                 m_usingTiledCacheLayer = true;
112 #endif
113         }
114     }
115     
116     createPrimaryGraphicsLayer();
117
118     if (m_usingTiledCacheLayer) {
119         if (Page* page = renderer()->frame()->page()) {
120             if (TiledBacking* tiledBacking = m_graphicsLayer->tiledBacking()) {
121                 tiledBacking->setIsInWindow(page->isOnscreen());
122                 tiledBacking->setCanHaveScrollbars(renderer()->frame()->view()->canHaveScrollbars());
123             }
124         }
125     }
126 }
127
128 RenderLayerBacking::~RenderLayerBacking()
129 {
130     updateClippingLayers(false, false);
131     updateOverflowControlsLayers(false, false, false);
132     updateForegroundLayer(false);
133     updateMaskLayer(false);
134     destroyGraphicsLayers();
135 }
136
137 PassOwnPtr<GraphicsLayer> RenderLayerBacking::createGraphicsLayer(const String& name)
138 {
139     OwnPtr<GraphicsLayer> graphicsLayer = GraphicsLayer::create(this);
140 #ifndef NDEBUG
141     graphicsLayer->setName(name);
142 #else
143     UNUSED_PARAM(name);
144 #endif
145     graphicsLayer->setMaintainsPixelAlignment(compositor()->keepLayersPixelAligned());
146
147 #if PLATFORM(MAC) && USE(CA)
148     graphicsLayer->setAcceleratesDrawing(compositor()->acceleratedDrawingEnabled());
149 #endif    
150     
151     return graphicsLayer.release();
152 }
153
154 bool RenderLayerBacking::shouldUseTileCache(const GraphicsLayer*) const
155 {
156     return m_usingTiledCacheLayer;
157 }
158
159 void RenderLayerBacking::createPrimaryGraphicsLayer()
160 {
161     String layerName;
162 #ifndef NDEBUG
163     layerName = nameForLayer();
164 #endif
165     m_graphicsLayer = createGraphicsLayer(layerName);
166
167     if (m_isMainFrameRenderViewLayer) {
168         m_graphicsLayer->setContentsOpaque(true);
169         m_graphicsLayer->setAppliesPageScale();
170     }
171
172 #if PLATFORM(MAC) && USE(CA)
173     if (!compositor()->acceleratedDrawingEnabled() && renderer()->isCanvas()) {
174         HTMLCanvasElement* canvas = static_cast<HTMLCanvasElement*>(renderer()->node());
175         if (canvas->shouldAccelerate(canvas->size()))
176             m_graphicsLayer->setAcceleratesDrawing(true);
177     }
178 #endif    
179     
180     updateLayerOpacity(renderer()->style());
181     updateLayerTransform(renderer()->style());
182 #if ENABLE(CSS_FILTERS)
183     updateLayerFilters(renderer()->style());
184 #endif
185 }
186
187 void RenderLayerBacking::destroyGraphicsLayers()
188 {
189     if (m_graphicsLayer)
190         m_graphicsLayer->removeFromParent();
191
192     m_graphicsLayer = nullptr;
193     m_foregroundLayer = nullptr;
194     m_clippingLayer = nullptr;
195     m_maskLayer = nullptr;
196 }
197
198 void RenderLayerBacking::updateLayerOpacity(const RenderStyle* style)
199 {
200     m_graphicsLayer->setOpacity(compositingOpacity(style->opacity()));
201 }
202
203 void RenderLayerBacking::updateLayerTransform(const RenderStyle* style)
204 {
205     // FIXME: This could use m_owningLayer->transform(), but that currently has transform-origin
206     // baked into it, and we don't want that.
207     TransformationMatrix t;
208     if (m_owningLayer->hasTransform()) {
209         style->applyTransform(t, toRenderBox(renderer())->borderBoxRect().size(), RenderStyle::ExcludeTransformOrigin);
210         makeMatrixRenderable(t, compositor()->canRender3DTransforms());
211     }
212     
213     m_graphicsLayer->setTransform(t);
214 }
215
216 #if ENABLE(CSS_FILTERS)
217 void RenderLayerBacking::updateLayerFilters(const RenderStyle* style)
218 {
219     m_canCompositeFilters = m_graphicsLayer->setFilters(style->filter());
220 }
221 #endif
222
223 static bool hasNonZeroTransformOrigin(const RenderObject* renderer)
224 {
225     RenderStyle* style = renderer->style();
226     return (style->transformOriginX().type() == Fixed && style->transformOriginX().value())
227         || (style->transformOriginY().type() == Fixed && style->transformOriginY().value());
228 }
229
230 static bool layerOrAncestorIsTransformed(RenderLayer* layer)
231 {
232     for (RenderLayer* curr = layer; curr; curr = curr->parent()) {
233         if (curr->hasTransform())
234             return true;
235     }
236     
237     return false;
238 }
239
240 bool RenderLayerBacking::shouldClipCompositedBounds() const
241 {
242     if (m_usingTiledCacheLayer)
243         return true;
244
245     if (!compositor()->compositingConsultsOverlap())
246         return false;
247
248     if (layerOrAncestorIsTransformed(m_owningLayer))
249         return false;
250
251     return true;
252 }
253
254
255 void RenderLayerBacking::updateCompositedBounds()
256 {
257     IntRect layerBounds = compositor()->calculateCompositedBounds(m_owningLayer, m_owningLayer);
258
259     // Clip to the size of the document or enclosing overflow-scroll layer.
260     // If this or an ancestor is transformed, we can't currently compute the correct rect to intersect with.
261     // We'd need RenderObject::convertContainerToLocalQuad(), which doesn't yet exist.
262     if (shouldClipCompositedBounds()) {
263         RenderView* view = m_owningLayer->renderer()->view();
264         RenderLayer* rootLayer = view->layer();
265
266         // Start by clipping to the view's bounds.
267         LayoutRect clippingBounds = view->unscaledDocumentRect();
268
269         if (m_owningLayer != rootLayer)
270             clippingBounds.intersect(m_owningLayer->backgroundClipRect(rootLayer, 0, true).rect()); // FIXME: Incorrect for CSS regions.
271
272         LayoutPoint delta;
273         m_owningLayer->convertToLayerCoords(rootLayer, delta);
274         clippingBounds.move(-delta.x(), -delta.y());
275
276         layerBounds.intersect(pixelSnappedIntRect(clippingBounds));
277     }
278     
279     // If the element has a transform-origin that has fixed lengths, and the renderer has zero size,
280     // then we need to ensure that the compositing layer has non-zero size so that we can apply
281     // the transform-origin via the GraphicsLayer anchorPoint (which is expressed as a fractional value).
282     if (layerBounds.isEmpty() && hasNonZeroTransformOrigin(renderer())) {
283         layerBounds.setWidth(1);
284         layerBounds.setHeight(1);
285         m_artificiallyInflatedBounds = true;
286     } else
287         m_artificiallyInflatedBounds = false;
288
289     setCompositedBounds(layerBounds);
290 }
291
292 void RenderLayerBacking::updateAfterWidgetResize()
293 {
294     if (renderer()->isRenderPart()) {
295         if (RenderLayerCompositor* innerCompositor = RenderLayerCompositor::frameContentsCompositor(toRenderPart(renderer()))) {
296             innerCompositor->frameViewDidChangeSize();
297             innerCompositor->frameViewDidChangeLocation(contentsBox().location());
298         }
299     }
300 }
301
302 void RenderLayerBacking::updateAfterLayout(UpdateDepth updateDepth, bool isUpdateRoot)
303 {
304     RenderLayerCompositor* layerCompositor = compositor();
305     if (!layerCompositor->compositingLayersNeedRebuild()) {
306         // Calling updateGraphicsLayerGeometry() here gives incorrect results, because the
307         // position of this layer's GraphicsLayer depends on the position of our compositing
308         // ancestor's GraphicsLayer. That cannot be determined until all the descendant 
309         // RenderLayers of that ancestor have been processed via updateLayerPositions().
310         //
311         // The solution is to update compositing children of this layer here,
312         // via updateCompositingChildrenGeometry().
313         updateCompositedBounds();
314         layerCompositor->updateCompositingDescendantGeometry(m_owningLayer, m_owningLayer, updateDepth);
315         
316         if (isUpdateRoot) {
317             updateGraphicsLayerGeometry();
318             layerCompositor->updateRootLayerPosition();
319         }
320     }
321 }
322
323 bool RenderLayerBacking::updateGraphicsLayerConfiguration()
324 {
325     RenderLayerCompositor* compositor = this->compositor();
326     RenderObject* renderer = this->renderer();
327
328     bool layerConfigChanged = false;
329     if (updateForegroundLayer(compositor->needsContentsCompositingLayer(m_owningLayer)))
330         layerConfigChanged = true;
331     
332     if (updateClippingLayers(compositor->clippedByAncestor(m_owningLayer), compositor->clipsCompositingDescendants(m_owningLayer)))
333         layerConfigChanged = true;
334
335     if (updateOverflowControlsLayers(requiresHorizontalScrollbarLayer(), requiresVerticalScrollbarLayer(), requiresScrollCornerLayer()))
336         layerConfigChanged = true;
337
338     if (layerConfigChanged)
339         updateInternalHierarchy();
340
341     if (updateMaskLayer(renderer->hasMask()))
342         m_graphicsLayer->setMaskLayer(m_maskLayer.get());
343
344     if (m_owningLayer->hasReflection()) {
345         if (m_owningLayer->reflectionLayer()->backing()) {
346             GraphicsLayer* reflectionLayer = m_owningLayer->reflectionLayer()->backing()->graphicsLayer();
347             m_graphicsLayer->setReplicatedByLayer(reflectionLayer);
348         }
349     } else
350         m_graphicsLayer->setReplicatedByLayer(0);
351
352     if (isDirectlyCompositedImage())
353         updateImageContents();
354
355     if ((renderer->isEmbeddedObject() && toRenderEmbeddedObject(renderer)->allowsAcceleratedCompositing())
356         || (renderer->isApplet() && toRenderApplet(renderer)->allowsAcceleratedCompositing())) {
357         PluginViewBase* pluginViewBase = static_cast<PluginViewBase*>(toRenderWidget(renderer)->widget());
358         m_graphicsLayer->setContentsToMedia(pluginViewBase->platformLayer());
359     }
360 #if ENABLE(VIDEO)
361     else if (renderer->isVideo()) {
362         HTMLMediaElement* mediaElement = static_cast<HTMLMediaElement*>(renderer->node());
363         m_graphicsLayer->setContentsToMedia(mediaElement->platformLayer());
364     }
365 #endif
366 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
367     else if (isAcceleratedCanvas(renderer)) {
368         HTMLCanvasElement* canvas = static_cast<HTMLCanvasElement*>(renderer->node());
369         if (CanvasRenderingContext* context = canvas->renderingContext())
370             m_graphicsLayer->setContentsToCanvas(context->platformLayer());
371         layerConfigChanged = true;
372     }
373 #endif
374 #if ENABLE(FULLSCREEN_API)
375     else if (renderer->isRenderFullScreen()) {
376         // RenderFullScreen renderers have no content, and only a solid
377         // background color.  They also can be large enough to trigger the
378         // creation of a tiled-layer, which can cause flashing problems
379         // during repainting.  Special case the RenderFullScreen case because
380         // we know its style does not come from CSS and it is therefore will
381         // not contain paintable content (e.g. background images, gradients,
382         // etc), so safe to set the layer's background color to the renderer's 
383         // style's background color.
384         updateBackgroundColor();
385     }
386 #endif
387     if (renderer->isRenderPart())
388         layerConfigChanged = RenderLayerCompositor::parentFrameContentLayers(toRenderPart(renderer));
389
390     return layerConfigChanged;
391 }
392
393 static IntRect clipBox(RenderBox* renderer)
394 {
395     LayoutRect result = PaintInfo::infiniteRect();
396     if (renderer->hasOverflowClip())
397         result = renderer->overflowClipRect(LayoutPoint(), 0); // FIXME: Incorrect for CSS regions.
398
399     if (renderer->hasClip())
400         result.intersect(renderer->clipRect(LayoutPoint(), 0)); // FIXME: Incorrect for CSS regions.
401
402     return pixelSnappedIntRect(result);
403 }
404
405 void RenderLayerBacking::updateGraphicsLayerGeometry()
406 {
407     // If we haven't built z-order lists yet, wait until later.
408     if (m_owningLayer->isStackingContext() && m_owningLayer->m_zOrderListsDirty)
409         return;
410
411     // Set transform property, if it is not animating. We have to do this here because the transform
412     // is affected by the layer dimensions.
413     if (!renderer()->animation()->isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyWebkitTransform))
414         updateLayerTransform(renderer()->style());
415
416     // Set opacity, if it is not animating.
417     if (!renderer()->animation()->isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyOpacity))
418         updateLayerOpacity(renderer()->style());
419         
420 #if ENABLE(CSS_FILTERS)
421     updateLayerFilters(renderer()->style());
422 #endif
423     
424     m_owningLayer->updateVisibilityStatus();
425
426     // m_graphicsLayer is the corresponding GraphicsLayer for this RenderLayer and its non-compositing
427     // descendants. So, the visibility flag for m_graphicsLayer should be true if there are any
428     // non-compositing visible layers.
429     m_graphicsLayer->setContentsVisible(m_owningLayer->hasVisibleContent() || hasVisibleNonCompositingDescendantLayers());
430
431     RenderStyle* style = renderer()->style();
432     m_graphicsLayer->setPreserves3D(style->transformStyle3D() == TransformStyle3DPreserve3D && !renderer()->hasReflection());
433     m_graphicsLayer->setBackfaceVisibility(style->backfaceVisibility() == BackfaceVisibilityVisible);
434
435     RenderLayer* compAncestor = m_owningLayer->ancestorCompositingLayer();
436     
437     // We compute everything relative to the enclosing compositing layer.
438     IntRect ancestorCompositingBounds;
439     if (compAncestor) {
440         ASSERT(compAncestor->backing());
441         ancestorCompositingBounds = pixelSnappedIntRect(compAncestor->backing()->compositedBounds());
442     }
443
444     IntRect localCompositingBounds = pixelSnappedIntRect(compositedBounds());
445
446     IntRect relativeCompositingBounds(localCompositingBounds);
447     IntPoint delta;
448     m_owningLayer->convertToPixelSnappedLayerCoords(compAncestor, delta);
449     relativeCompositingBounds.moveBy(delta);
450
451     IntPoint graphicsLayerParentLocation;
452     if (compAncestor && compAncestor->backing()->hasClippingLayer()) {
453         // If the compositing ancestor has a layer to clip children, we parent in that, and therefore
454         // position relative to it.
455         IntRect clippingBox = clipBox(toRenderBox(compAncestor->renderer()));
456         graphicsLayerParentLocation = clippingBox.location();
457     } else if (compAncestor)
458         graphicsLayerParentLocation = ancestorCompositingBounds.location();
459     else
460         graphicsLayerParentLocation = renderer()->view()->documentRect().location();
461     
462     if (compAncestor && m_ancestorClippingLayer) {
463         // Call calculateRects to get the backgroundRect which is what is used to clip the contents of this
464         // layer. Note that we call it with temporaryClipRects = true because normally when computing clip rects
465         // for a compositing layer, rootLayer is the layer itself.
466         IntRect parentClipRect = pixelSnappedIntRect(m_owningLayer->backgroundClipRect(compAncestor, 0, true).rect()); // FIXME: Incorrect for CSS regions.
467         ASSERT(parentClipRect != PaintInfo::infiniteRect());
468         m_ancestorClippingLayer->setPosition(FloatPoint() + (parentClipRect.location() - graphicsLayerParentLocation));
469         m_ancestorClippingLayer->setSize(parentClipRect.size());
470
471         // backgroundRect is relative to compAncestor, so subtract deltaX/deltaY to get back to local coords.
472         m_ancestorClippingLayer->setOffsetFromRenderer(parentClipRect.location() - delta);
473
474         // The primary layer is then parented in, and positioned relative to this clipping layer.
475         graphicsLayerParentLocation = parentClipRect.location();
476     }
477
478     m_graphicsLayer->setPosition(FloatPoint() + (relativeCompositingBounds.location() - graphicsLayerParentLocation));
479     m_graphicsLayer->setOffsetFromRenderer(localCompositingBounds.location() - IntPoint());
480     
481     FloatSize oldSize = m_graphicsLayer->size();
482     FloatSize newSize = relativeCompositingBounds.size();
483     if (oldSize != newSize) {
484         m_graphicsLayer->setSize(newSize);
485         // A bounds change will almost always require redisplay. Usually that redisplay
486         // will happen because of a repaint elsewhere, but not always:
487         // e.g. see RenderView::setMaximalOutlineSize()
488         m_graphicsLayer->setNeedsDisplay();
489     }
490
491     // If we have a layer that clips children, position it.
492     IntRect clippingBox;
493     if (m_clippingLayer) {
494         clippingBox = clipBox(toRenderBox(renderer()));
495         m_clippingLayer->setPosition(FloatPoint() + (clippingBox.location() - localCompositingBounds.location()));
496         m_clippingLayer->setSize(clippingBox.size());
497         m_clippingLayer->setOffsetFromRenderer(clippingBox.location() - IntPoint());
498     }
499     
500     if (m_maskLayer) {
501         if (m_maskLayer->size() != m_graphicsLayer->size()) {
502             m_maskLayer->setSize(m_graphicsLayer->size());
503             m_maskLayer->setNeedsDisplay();
504         }
505         m_maskLayer->setPosition(FloatPoint());
506         m_maskLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
507     }
508     
509     if (m_owningLayer->hasTransform()) {
510         const IntRect borderBox = toRenderBox(renderer())->pixelSnappedBorderBoxRect();
511
512         // Get layout bounds in the coords of compAncestor to match relativeCompositingBounds.
513         IntRect layerBounds = IntRect(delta, borderBox.size());
514
515         // Update properties that depend on layer dimensions
516         FloatPoint3D transformOrigin = computeTransformOrigin(borderBox);
517         // Compute the anchor point, which is in the center of the renderer box unless transform-origin is set.
518         FloatPoint3D anchor(relativeCompositingBounds.width()  != 0.0f ? ((layerBounds.x() - relativeCompositingBounds.x()) + transformOrigin.x()) / relativeCompositingBounds.width()  : 0.5f,
519                             relativeCompositingBounds.height() != 0.0f ? ((layerBounds.y() - relativeCompositingBounds.y()) + transformOrigin.y()) / relativeCompositingBounds.height() : 0.5f,
520                             transformOrigin.z());
521         m_graphicsLayer->setAnchorPoint(anchor);
522
523         RenderStyle* style = renderer()->style();
524         if (style->hasPerspective()) {
525             TransformationMatrix t = owningLayer()->perspectiveTransform();
526             
527             if (m_clippingLayer) {
528                 m_clippingLayer->setChildrenTransform(t);
529                 m_graphicsLayer->setChildrenTransform(TransformationMatrix());
530             }
531             else
532                 m_graphicsLayer->setChildrenTransform(t);
533         } else {
534             if (m_clippingLayer)
535                 m_clippingLayer->setChildrenTransform(TransformationMatrix());
536             else
537                 m_graphicsLayer->setChildrenTransform(TransformationMatrix());
538         }
539     } else {
540         m_graphicsLayer->setAnchorPoint(FloatPoint3D(0.5f, 0.5f, 0));
541     }
542
543     if (m_foregroundLayer) {
544         FloatPoint foregroundPosition;
545         FloatSize foregroundSize = newSize;
546         IntSize foregroundOffset = m_graphicsLayer->offsetFromRenderer();
547         if (m_clippingLayer) {
548             // If we have a clipping layer (which clips descendants), then the foreground layer is a child of it,
549             // so that it gets correctly sorted with children. In that case, position relative to the clipping layer.
550             foregroundSize = FloatSize(clippingBox.size());
551             foregroundOffset = clippingBox.location() - IntPoint();
552         }
553
554         m_foregroundLayer->setPosition(foregroundPosition);
555         m_foregroundLayer->setSize(foregroundSize);
556         m_foregroundLayer->setOffsetFromRenderer(foregroundOffset);
557     }
558
559     if (m_owningLayer->reflectionLayer() && m_owningLayer->reflectionLayer()->isComposited()) {
560         RenderLayerBacking* reflectionBacking = m_owningLayer->reflectionLayer()->backing();
561         reflectionBacking->updateGraphicsLayerGeometry();
562         
563         // The reflection layer has the bounds of m_owningLayer->reflectionLayer(),
564         // but the reflected layer is the bounds of this layer, so we need to position it appropriately.
565         FloatRect layerBounds = compositedBounds();
566         FloatRect reflectionLayerBounds = reflectionBacking->compositedBounds();
567         reflectionBacking->graphicsLayer()->setReplicatedLayerPosition(FloatPoint() + (layerBounds.location() - reflectionLayerBounds.location()));
568     }
569
570     m_graphicsLayer->setContentsRect(contentsBox());
571
572     // If this layer was created just for clipping or to apply perspective, it doesn't need its own backing store.
573     setRequiresOwnBackingStore(compositor()->requiresOwnBackingStore(m_owningLayer, compAncestor));
574
575     updateDrawsContent();
576     updateAfterWidgetResize();
577 }
578
579 void RenderLayerBacking::updateInternalHierarchy()
580 {
581     // m_foregroundLayer has to be inserted in the correct order with child layers,
582     // so it's not inserted here.
583     if (m_ancestorClippingLayer) {
584         m_ancestorClippingLayer->removeAllChildren();
585         m_graphicsLayer->removeFromParent();
586         m_ancestorClippingLayer->addChild(m_graphicsLayer.get());
587     }
588
589     if (m_clippingLayer) {
590         m_clippingLayer->removeFromParent();
591         m_graphicsLayer->addChild(m_clippingLayer.get());
592
593         // The clip for child layers does not include space for overflow controls, so they exist as
594         // siblings of the clipping layer if we have one. Normal children of this layer are set as
595         // children of the clipping layer.
596         if (m_layerForHorizontalScrollbar) {
597             m_layerForHorizontalScrollbar->removeFromParent();
598             m_graphicsLayer->addChild(m_layerForHorizontalScrollbar.get());
599         }
600         if (m_layerForVerticalScrollbar) {
601             m_layerForVerticalScrollbar->removeFromParent();
602             m_graphicsLayer->addChild(m_layerForVerticalScrollbar.get());
603         }
604         if (m_layerForScrollCorner) {
605             m_layerForScrollCorner->removeFromParent();
606             m_graphicsLayer->addChild(m_layerForScrollCorner.get());
607         }
608     }
609 }
610
611 void RenderLayerBacking::updateDrawsContent()
612 {
613     bool hasPaintedContent = containsPaintedContent();
614
615     // FIXME: we could refine this to only allocate backing for one of these layers if possible.
616     m_graphicsLayer->setDrawsContent(hasPaintedContent);
617     if (m_foregroundLayer)
618         m_foregroundLayer->setDrawsContent(hasPaintedContent);
619 }
620
621 // Return true if the layers changed.
622 bool RenderLayerBacking::updateClippingLayers(bool needsAncestorClip, bool needsDescendantClip)
623 {
624     bool layersChanged = false;
625
626     if (needsAncestorClip) {
627         if (!m_ancestorClippingLayer) {
628             m_ancestorClippingLayer = createGraphicsLayer("Ancestor clipping Layer");
629             m_ancestorClippingLayer->setMasksToBounds(true);
630             layersChanged = true;
631         }
632     } else if (m_ancestorClippingLayer) {
633         m_ancestorClippingLayer->removeFromParent();
634         m_ancestorClippingLayer = nullptr;
635         layersChanged = true;
636     }
637     
638     if (needsDescendantClip) {
639         if (!m_clippingLayer) {
640             m_clippingLayer = createGraphicsLayer("Child clipping Layer");
641             m_clippingLayer->setMasksToBounds(true);
642             layersChanged = true;
643         }
644     } else if (m_clippingLayer) {
645         m_clippingLayer->removeFromParent();
646         m_clippingLayer = nullptr;
647         layersChanged = true;
648     }
649     
650     return layersChanged;
651 }
652
653 bool RenderLayerBacking::requiresHorizontalScrollbarLayer() const
654 {
655 #if !PLATFORM(CHROMIUM)
656     if (!m_owningLayer->hasOverlayScrollbars())
657         return false;
658 #endif
659     return m_owningLayer->horizontalScrollbar();
660 }
661
662 bool RenderLayerBacking::requiresVerticalScrollbarLayer() const
663 {
664 #if !PLATFORM(CHROMIUM)
665     if (!m_owningLayer->hasOverlayScrollbars())
666         return false;
667 #endif
668     return m_owningLayer->verticalScrollbar();
669 }
670
671 bool RenderLayerBacking::requiresScrollCornerLayer() const
672 {
673 #if !PLATFORM(CHROMIUM)
674     if (!m_owningLayer->hasOverlayScrollbars())
675         return false;
676 #endif
677     return !m_owningLayer->scrollCornerAndResizerRect().isEmpty();
678 }
679
680 bool RenderLayerBacking::updateOverflowControlsLayers(bool needsHorizontalScrollbarLayer, bool needsVerticalScrollbarLayer, bool needsScrollCornerLayer)
681 {
682     bool layersChanged = false;
683     if (needsHorizontalScrollbarLayer) {
684         if (!m_layerForHorizontalScrollbar) {
685             m_layerForHorizontalScrollbar = createGraphicsLayer("horizontal scrollbar");
686             layersChanged = true;
687         }
688     } else if (m_layerForHorizontalScrollbar) {
689         m_layerForHorizontalScrollbar.clear();
690         layersChanged = true;
691     }
692
693     if (needsVerticalScrollbarLayer) {
694         if (!m_layerForVerticalScrollbar) {
695             m_layerForVerticalScrollbar = createGraphicsLayer("vertical scrollbar");
696             layersChanged = true;
697         }
698     } else if (m_layerForVerticalScrollbar) {
699         m_layerForVerticalScrollbar.clear();
700         layersChanged = true;
701     }
702
703     if (needsScrollCornerLayer) {
704         if (!m_layerForScrollCorner) {
705             m_layerForScrollCorner = createGraphicsLayer("scroll corner");
706             layersChanged = true;
707         }
708     } else if (m_layerForScrollCorner) {
709         m_layerForScrollCorner.clear();
710         layersChanged = true;
711     }
712
713     return layersChanged;
714 }
715
716 bool RenderLayerBacking::updateForegroundLayer(bool needsForegroundLayer)
717 {
718     bool layerChanged = false;
719     if (needsForegroundLayer) {
720         if (!m_foregroundLayer) {
721             String layerName;
722 #ifndef NDEBUG
723             layerName = nameForLayer() + " (foreground)";
724 #endif
725             m_foregroundLayer = createGraphicsLayer(layerName);
726             m_foregroundLayer->setDrawsContent(true);
727             m_foregroundLayer->setPaintingPhase(GraphicsLayerPaintForeground);
728             layerChanged = true;
729         }
730     } else if (m_foregroundLayer) {
731         m_foregroundLayer->removeFromParent();
732         m_foregroundLayer = nullptr;
733         layerChanged = true;
734     }
735
736     if (layerChanged)
737         m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
738
739     return layerChanged;
740 }
741
742 bool RenderLayerBacking::updateMaskLayer(bool needsMaskLayer)
743 {
744     bool layerChanged = false;
745     if (needsMaskLayer) {
746         if (!m_maskLayer) {
747             m_maskLayer = createGraphicsLayer("Mask");
748             m_maskLayer->setDrawsContent(true);
749             m_maskLayer->setPaintingPhase(GraphicsLayerPaintMask);
750             layerChanged = true;
751         }
752     } else if (m_maskLayer) {
753         m_maskLayer = nullptr;
754         layerChanged = true;
755     }
756
757     if (layerChanged)
758         m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
759
760     return layerChanged;
761 }
762
763 GraphicsLayerPaintingPhase RenderLayerBacking::paintingPhaseForPrimaryLayer() const
764 {
765     unsigned phase = GraphicsLayerPaintBackground;
766     if (!m_foregroundLayer)
767         phase |= GraphicsLayerPaintForeground;
768     if (!m_maskLayer)
769         phase |= GraphicsLayerPaintMask;
770
771     return static_cast<GraphicsLayerPaintingPhase>(phase);
772 }
773
774 float RenderLayerBacking::compositingOpacity(float rendererOpacity) const
775 {
776     float finalOpacity = rendererOpacity;
777     
778     for (RenderLayer* curr = m_owningLayer->parent(); curr; curr = curr->parent()) {
779         // We only care about parents that are stacking contexts.
780         // Recall that opacity creates stacking context.
781         if (!curr->isStackingContext())
782             continue;
783         
784         // If we found a compositing layer, we want to compute opacity
785         // relative to it. So we can break here.
786         if (curr->isComposited())
787             break;
788         
789         finalOpacity *= curr->renderer()->opacity();
790     }
791
792     return finalOpacity;
793 }
794
795 static bool hasBoxDecorations(const RenderStyle* style)
796 {
797     return style->hasBorder() || style->hasBorderRadius() || style->hasOutline() || style->hasAppearance() || style->boxShadow() || style->hasFilter();
798 }
799
800 static bool hasBoxDecorationsOrBackground(const RenderObject* renderer)
801 {
802     return hasBoxDecorations(renderer->style()) || renderer->hasBackground();
803 }
804
805 static bool hasBoxDecorationsOrBackgroundImage(const RenderStyle* style)
806 {
807     return hasBoxDecorations(style) || style->hasBackgroundImage();
808 }
809
810 Color RenderLayerBacking::rendererBackgroundColor() const
811 {
812     RenderObject* backgroundRenderer = renderer();
813     if (backgroundRenderer->isRoot())
814         backgroundRenderer = backgroundRenderer->rendererForRootBackground();
815
816     return backgroundRenderer->style()->visitedDependentColor(CSSPropertyBackgroundColor);
817 }
818
819 void RenderLayerBacking::updateBackgroundColor()
820 {
821     m_graphicsLayer->setContentsToBackgroundColor(rendererBackgroundColor());
822 }
823
824 bool RenderLayerBacking::paintsBoxDecorations() const
825 {
826     if (!m_owningLayer->hasVisibleContent())
827         return false;
828
829     if (hasBoxDecorationsOrBackground(renderer()))
830         return true;
831
832     if (m_owningLayer->hasOverflowControls())
833         return true;
834
835     return false;
836 }
837
838 bool RenderLayerBacking::paintsChildren() const
839 {
840     if (m_owningLayer->hasVisibleContent() && containsNonEmptyRenderers())
841         return true;
842         
843     if (hasVisibleNonCompositingDescendantLayers())
844         return true;
845
846     return false;
847 }
848
849 // A "simple container layer" is a RenderLayer which has no visible content to render.
850 // It may have no children, or all its children may be themselves composited.
851 // This is a useful optimization, because it allows us to avoid allocating backing store.
852 bool RenderLayerBacking::isSimpleContainerCompositingLayer() const
853 {
854     RenderObject* renderObject = renderer();
855     if (renderObject->isReplaced() ||       // replaced objects are not containers
856         renderObject->hasMask())            // masks require special treatment
857         return false;
858
859     if (paintsBoxDecorations() || paintsChildren())
860         return false;
861     
862     if (renderObject->node() && renderObject->node()->isDocumentNode()) {
863         // Look to see if the root object has a non-simple background
864         RenderObject* rootObject = renderObject->document()->documentElement() ? renderObject->document()->documentElement()->renderer() : 0;
865         if (!rootObject)
866             return false;
867         
868         RenderStyle* style = rootObject->style();
869         
870         // Reject anything that has a border, a border-radius or outline,
871         // or is not a simple background (no background, or solid color).
872         if (hasBoxDecorationsOrBackgroundImage(style))
873             return false;
874         
875         // Now look at the body's renderer.
876         HTMLElement* body = renderObject->document()->body();
877         RenderObject* bodyObject = (body && body->hasLocalName(bodyTag)) ? body->renderer() : 0;
878         if (!bodyObject)
879             return false;
880         
881         style = bodyObject->style();
882         
883         if (hasBoxDecorationsOrBackgroundImage(style))
884             return false;
885     }
886
887     return true;
888 }
889
890 bool RenderLayerBacking::containsNonEmptyRenderers() const
891 {
892     // Some HTML can cause whitespace text nodes to have renderers, like:
893     // <div>
894     // <img src=...>
895     // </div>
896     // so test for 0x0 RenderTexts here
897     for (RenderObject* child = renderer()->firstChild(); child; child = child->nextSibling()) {
898         if (!child->hasLayer()) {
899             if (child->isRenderInline() || !child->isBox())
900                 return true;
901             
902             if (toRenderBox(child)->width() > 0 || toRenderBox(child)->height() > 0)
903                 return true;
904         }
905     }
906     return false;
907 }
908
909 // Conservative test for having no rendered children.
910 bool RenderLayerBacking::hasVisibleNonCompositingDescendantLayers() const
911 {
912     // FIXME: We shouldn't be called with a stale z-order lists. See bug 85512.
913     m_owningLayer->updateLayerListsIfNeeded();
914
915 #if !ASSERT_DISABLED
916     LayerListMutationDetector mutationChecker(m_owningLayer);
917 #endif
918
919     if (Vector<RenderLayer*>* normalFlowList = m_owningLayer->normalFlowList()) {
920         size_t listSize = normalFlowList->size();
921         for (size_t i = 0; i < listSize; ++i) {
922             RenderLayer* curLayer = normalFlowList->at(i);
923             if (!curLayer->isComposited() && curLayer->hasVisibleContent())
924                 return true;
925         }
926     }
927
928     if (m_owningLayer->isStackingContext()) {
929         if (!m_owningLayer->hasVisibleDescendant())
930             return false;
931
932         // Use the m_hasCompositingDescendant bit to optimize?
933         if (Vector<RenderLayer*>* negZOrderList = m_owningLayer->negZOrderList()) {
934             size_t listSize = negZOrderList->size();
935             for (size_t i = 0; i < listSize; ++i) {
936                 RenderLayer* curLayer = negZOrderList->at(i);
937                 if (!curLayer->isComposited() && curLayer->hasVisibleContent())
938                     return true;
939             }
940         }
941
942         if (Vector<RenderLayer*>* posZOrderList = m_owningLayer->posZOrderList()) {
943             size_t listSize = posZOrderList->size();
944             for (size_t i = 0; i < listSize; ++i) {
945                 RenderLayer* curLayer = posZOrderList->at(i);
946                 if (!curLayer->isComposited() && curLayer->hasVisibleContent())
947                     return true;
948             }
949         }
950     }
951
952     return false;
953 }
954
955 bool RenderLayerBacking::containsPaintedContent() const
956 {
957     if (isSimpleContainerCompositingLayer() || paintsIntoWindow() || paintsIntoCompositedAncestor() || m_artificiallyInflatedBounds || m_owningLayer->isReflection())
958         return false;
959
960     if (isDirectlyCompositedImage())
961         return false;
962
963     // FIXME: we could optimize cases where the image, video or canvas is known to fill the border box entirely,
964     // and set background color on the layer in that case, instead of allocating backing store and painting.
965 #if ENABLE(VIDEO)
966     if (renderer()->isVideo() && toRenderVideo(renderer())->shouldDisplayVideo())
967         return hasBoxDecorationsOrBackground(renderer());
968 #endif
969 #if PLATFORM(MAC) && USE(CA) && !defined(BUILDING_ON_LEOPARD) && !defined(BUILDING_ON_SNOW_LEOPARD)
970 #elif ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
971     if (isAcceleratedCanvas(renderer()))
972         return hasBoxDecorationsOrBackground(renderer());
973 #endif
974
975     return true;
976 }
977
978 // An image can be directly compositing if it's the sole content of the layer, and has no box decorations
979 // that require painting. Direct compositing saves backing store.
980 bool RenderLayerBacking::isDirectlyCompositedImage() const
981 {
982     RenderObject* renderObject = renderer();
983     
984     if (!renderObject->isImage() || hasBoxDecorationsOrBackground(renderObject) || renderObject->hasClip())
985         return false;
986
987     RenderImage* imageRenderer = toRenderImage(renderObject);
988     if (CachedImage* cachedImage = imageRenderer->cachedImage()) {
989         if (cachedImage->hasImage())
990             return cachedImage->imageForRenderer(imageRenderer)->isBitmapImage();
991     }
992
993     return false;
994 }
995
996 void RenderLayerBacking::contentChanged(ContentChangeType changeType)
997 {
998     if ((changeType == ImageChanged) && isDirectlyCompositedImage()) {
999         updateImageContents();
1000         return;
1001     }
1002     
1003     if ((changeType == MaskImageChanged) && m_maskLayer) {
1004         // The composited layer bounds relies on box->maskClipRect(), which changes
1005         // when the mask image becomes available.
1006         bool isUpdateRoot = true;
1007         updateAfterLayout(CompositingChildren, isUpdateRoot);
1008     }
1009
1010 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
1011     if ((changeType == CanvasChanged) && isAcceleratedCanvas(renderer())) {
1012         m_graphicsLayer->setContentsNeedsDisplay();
1013         return;
1014     }
1015 #endif
1016 }
1017
1018 void RenderLayerBacking::updateImageContents()
1019 {
1020     ASSERT(renderer()->isImage());
1021     RenderImage* imageRenderer = toRenderImage(renderer());
1022
1023     CachedImage* cachedImage = imageRenderer->cachedImage();
1024     if (!cachedImage)
1025         return;
1026
1027     Image* image = cachedImage->imageForRenderer(imageRenderer);
1028     if (!image)
1029         return;
1030
1031     // We have to wait until the image is fully loaded before setting it on the layer.
1032     if (!cachedImage->isLoaded())
1033         return;
1034
1035     // This is a no-op if the layer doesn't have an inner layer for the image.
1036     m_graphicsLayer->setContentsToImage(image);
1037     updateDrawsContent();
1038     
1039     // Image animation is "lazy", in that it automatically stops unless someone is drawing
1040     // the image. So we have to kick the animation each time; this has the downside that the
1041     // image will keep animating, even if its layer is not visible.
1042     image->startAnimation();
1043 }
1044
1045 FloatPoint3D RenderLayerBacking::computeTransformOrigin(const IntRect& borderBox) const
1046 {
1047     RenderStyle* style = renderer()->style();
1048
1049     FloatPoint3D origin;
1050     origin.setX(floatValueForLength(style->transformOriginX(), borderBox.width()));
1051     origin.setY(floatValueForLength(style->transformOriginY(), borderBox.height()));
1052     origin.setZ(style->transformOriginZ());
1053
1054     return origin;
1055 }
1056
1057 FloatPoint RenderLayerBacking::computePerspectiveOrigin(const IntRect& borderBox) const
1058 {
1059     RenderStyle* style = renderer()->style();
1060
1061     float boxWidth = borderBox.width();
1062     float boxHeight = borderBox.height();
1063
1064     FloatPoint origin;
1065     origin.setX(floatValueForLength(style->perspectiveOriginX(), boxWidth));
1066     origin.setY(floatValueForLength(style->perspectiveOriginY(), boxHeight));
1067
1068     return origin;
1069 }
1070
1071 // Return the offset from the top-left of this compositing layer at which the renderer's contents are painted.
1072 IntSize RenderLayerBacking::contentOffsetInCompostingLayer() const
1073 {
1074     return IntSize(-m_compositedBounds.x(), -m_compositedBounds.y());
1075 }
1076
1077 IntRect RenderLayerBacking::contentsBox() const
1078 {
1079     if (!renderer()->isBox())
1080         return IntRect();
1081
1082     IntRect contentsRect;
1083 #if ENABLE(VIDEO)
1084     if (renderer()->isVideo()) {
1085         RenderVideo* videoRenderer = toRenderVideo(renderer());
1086         contentsRect = videoRenderer->videoBox();
1087     } else
1088 #endif
1089         contentsRect = pixelSnappedIntRect(toRenderBox(renderer())->contentBoxRect());
1090
1091     IntSize contentOffset = contentOffsetInCompostingLayer();
1092     contentsRect.move(contentOffset);
1093     return contentsRect;
1094 }
1095
1096 bool RenderLayerBacking::paintsIntoWindow() const
1097 {
1098     if (m_usingTiledCacheLayer)
1099         return false;
1100
1101     if (m_owningLayer->isRootLayer()) {
1102 #if PLATFORM(BLACKBERRY)
1103         if (compositor()->inForcedCompositingMode())
1104             return false;
1105 #endif
1106
1107         return compositor()->rootLayerAttachment() != RenderLayerCompositor::RootLayerAttachedViaEnclosingFrame;
1108     }
1109     
1110     return false;
1111 }
1112
1113 void RenderLayerBacking::setContentsNeedDisplay()
1114 {
1115     ASSERT(!paintsIntoCompositedAncestor());
1116     
1117     if (m_graphicsLayer && m_graphicsLayer->drawsContent())
1118         m_graphicsLayer->setNeedsDisplay();
1119     
1120     if (m_foregroundLayer && m_foregroundLayer->drawsContent())
1121         m_foregroundLayer->setNeedsDisplay();
1122
1123     if (m_maskLayer && m_maskLayer->drawsContent())
1124         m_maskLayer->setNeedsDisplay();
1125 }
1126
1127 // r is in the coordinate space of the layer's render object
1128 void RenderLayerBacking::setContentsNeedDisplayInRect(const IntRect& r)
1129 {
1130     ASSERT(!paintsIntoCompositedAncestor());
1131
1132     if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
1133         IntRect layerDirtyRect = r;
1134         layerDirtyRect.move(-m_graphicsLayer->offsetFromRenderer());
1135         m_graphicsLayer->setNeedsDisplayInRect(layerDirtyRect);
1136     }
1137
1138     if (m_foregroundLayer && m_foregroundLayer->drawsContent()) {
1139         IntRect layerDirtyRect = r;
1140         layerDirtyRect.move(-m_foregroundLayer->offsetFromRenderer());
1141         m_foregroundLayer->setNeedsDisplayInRect(layerDirtyRect);
1142     }
1143
1144     if (m_maskLayer && m_maskLayer->drawsContent()) {
1145         IntRect layerDirtyRect = r;
1146         layerDirtyRect.move(-m_maskLayer->offsetFromRenderer());
1147         m_maskLayer->setNeedsDisplayInRect(layerDirtyRect);
1148     }
1149 }
1150
1151 void RenderLayerBacking::paintIntoLayer(RenderLayer* rootLayer, GraphicsContext* context,
1152                     const IntRect& paintDirtyRect, // In the coords of rootLayer.
1153                     PaintBehavior paintBehavior, GraphicsLayerPaintingPhase paintingPhase,
1154                     RenderObject* paintingRoot)
1155 {
1156     if (paintsIntoWindow() || paintsIntoCompositedAncestor()) {
1157         ASSERT_NOT_REACHED();
1158         return;
1159     }
1160
1161     FontCachePurgePreventer fontCachePurgePreventer;
1162     
1163     RenderLayer::PaintLayerFlags paintFlags = 0;
1164     if (paintingPhase & GraphicsLayerPaintBackground)
1165         paintFlags |= RenderLayer::PaintLayerPaintingCompositingBackgroundPhase;
1166     if (paintingPhase & GraphicsLayerPaintForeground)
1167         paintFlags |= RenderLayer::PaintLayerPaintingCompositingForegroundPhase;
1168     if (paintingPhase & GraphicsLayerPaintMask)
1169         paintFlags |= RenderLayer::PaintLayerPaintingCompositingMaskPhase;
1170         
1171     // FIXME: GraphicsLayers need a way to split for RenderRegions.
1172     m_owningLayer->paintLayerContents(rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, 0, 0, paintFlags);
1173
1174     if (m_owningLayer->containsDirtyOverlayScrollbars())
1175         m_owningLayer->paintOverlayScrollbars(context, paintDirtyRect, paintBehavior, paintingRoot);
1176
1177     ASSERT(!m_owningLayer->m_usedTransparency);
1178 }
1179
1180 static void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
1181 {
1182     if (!scrollbar)
1183         return;
1184
1185     context.save();
1186     const IntRect& scrollbarRect = scrollbar->frameRect();
1187     context.translate(-scrollbarRect.x(), -scrollbarRect.y());
1188     IntRect transformedClip = clip;
1189     transformedClip.moveBy(scrollbarRect.location());
1190     scrollbar->paint(&context, transformedClip);
1191     context.restore();
1192 }
1193
1194 // Up-call from compositing layer drawing callback.
1195 void RenderLayerBacking::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, GraphicsLayerPaintingPhase paintingPhase, const IntRect& clip)
1196 {
1197 #ifndef NDEBUG
1198     if (Page* page = renderer()->frame()->page())
1199         page->setIsPainting(true);
1200 #endif
1201     if (graphicsLayer == m_graphicsLayer.get() || graphicsLayer == m_foregroundLayer.get() || graphicsLayer == m_maskLayer.get()) {
1202         InspectorInstrumentationCookie cookie = InspectorInstrumentation::willPaint(m_owningLayer->renderer()->frame(), &context, clip);
1203
1204         // The dirtyRect is in the coords of the painting root.
1205         IntRect dirtyRect = compositedBounds();
1206         dirtyRect.intersect(clip);
1207
1208         // We have to use the same root as for hit testing, because both methods can compute and cache clipRects.
1209         paintIntoLayer(m_owningLayer, &context, dirtyRect, PaintBehaviorNormal, paintingPhase, renderer());
1210
1211         if (m_usingTiledCacheLayer)
1212             m_owningLayer->renderer()->frame()->view()->setLastPaintTime(currentTime());
1213
1214         InspectorInstrumentation::didPaint(cookie);
1215     } else if (graphicsLayer == layerForHorizontalScrollbar()) {
1216         paintScrollbar(m_owningLayer->horizontalScrollbar(), context, clip);
1217     } else if (graphicsLayer == layerForVerticalScrollbar()) {
1218         paintScrollbar(m_owningLayer->verticalScrollbar(), context, clip);
1219     } else if (graphicsLayer == layerForScrollCorner()) {
1220         const IntRect& scrollCornerAndResizer = m_owningLayer->scrollCornerAndResizerRect();
1221         context.save();
1222         context.translate(-scrollCornerAndResizer.x(), -scrollCornerAndResizer.y());
1223         IntRect transformedClip = clip;
1224         transformedClip.moveBy(scrollCornerAndResizer.location());
1225         m_owningLayer->paintScrollCorner(&context, IntPoint(), transformedClip);
1226         m_owningLayer->paintResizer(&context, IntPoint(), transformedClip);
1227         context.restore();
1228     }
1229 #ifndef NDEBUG
1230     if (Page* page = renderer()->frame()->page())
1231         page->setIsPainting(false);
1232 #endif
1233 }
1234
1235 float RenderLayerBacking::pageScaleFactor() const
1236 {
1237     return compositor()->pageScaleFactor();
1238 }
1239
1240 float RenderLayerBacking::deviceScaleFactor() const
1241 {
1242     return compositor()->deviceScaleFactor();
1243 }
1244
1245 void RenderLayerBacking::didCommitChangesForLayer(const GraphicsLayer*) const
1246 {
1247     compositor()->didFlushChangesForLayer(m_owningLayer);
1248 }
1249
1250 bool RenderLayerBacking::showDebugBorders(const GraphicsLayer*) const
1251 {
1252     return compositor() ? compositor()->compositorShowDebugBorders() : false;
1253 }
1254
1255 bool RenderLayerBacking::showRepaintCounter(const GraphicsLayer*) const
1256 {
1257     return compositor() ? compositor()->compositorShowRepaintCounter() : false;
1258 }
1259
1260 #ifndef NDEBUG
1261 void RenderLayerBacking::verifyNotPainting()
1262 {
1263     ASSERT(!renderer()->frame()->page() || !renderer()->frame()->page()->isPainting());
1264 }
1265 #endif
1266
1267 bool RenderLayerBacking::startAnimation(double timeOffset, const Animation* anim, const KeyframeList& keyframes)
1268 {
1269     bool hasOpacity = keyframes.containsProperty(CSSPropertyOpacity);
1270     bool hasTransform = renderer()->isBox() && keyframes.containsProperty(CSSPropertyWebkitTransform);
1271 #if ENABLE(CSS_FILTERS)
1272     bool hasFilter = keyframes.containsProperty(CSSPropertyWebkitFilter);
1273 #else
1274     bool hasFilter = false;
1275 #endif
1276
1277     if (!hasOpacity && !hasTransform && !hasFilter)
1278         return false;
1279     
1280     KeyframeValueList transformVector(AnimatedPropertyWebkitTransform);
1281     KeyframeValueList opacityVector(AnimatedPropertyOpacity);
1282 #if ENABLE(CSS_FILTERS)
1283     KeyframeValueList filterVector(AnimatedPropertyWebkitFilter);
1284 #endif
1285
1286     size_t numKeyframes = keyframes.size();
1287     for (size_t i = 0; i < numKeyframes; ++i) {
1288         const KeyframeValue& currentKeyframe = keyframes[i];
1289         const RenderStyle* keyframeStyle = currentKeyframe.style();
1290         float key = currentKeyframe.key();
1291
1292         if (!keyframeStyle)
1293             continue;
1294             
1295         // Get timing function.
1296         RefPtr<TimingFunction> tf = keyframeStyle->hasAnimations() ? (*keyframeStyle->animations()).animation(0)->timingFunction() : 0;
1297         
1298         bool isFirstOrLastKeyframe = key == 0 || key == 1;
1299         if ((hasTransform && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitTransform))
1300             transformVector.insert(new TransformAnimationValue(key, &(keyframeStyle->transform()), tf));
1301         
1302         if ((hasOpacity && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyOpacity))
1303             opacityVector.insert(new FloatAnimationValue(key, keyframeStyle->opacity(), tf));
1304
1305 #if ENABLE(CSS_FILTERS)
1306         if ((hasFilter && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitFilter))
1307             filterVector.insert(new FilterAnimationValue(key, &(keyframeStyle->filter()), tf));
1308 #endif
1309     }
1310
1311     bool didAnimateTransform = false;
1312     bool didAnimateOpacity = false;
1313 #if ENABLE(CSS_FILTERS)
1314     bool didAnimateFilter = false;
1315 #endif
1316     
1317     if (hasTransform && m_graphicsLayer->addAnimation(transformVector, toRenderBox(renderer())->pixelSnappedBorderBoxRect().size(), anim, keyframes.animationName(), timeOffset))
1318         didAnimateTransform = true;
1319
1320     if (hasOpacity && m_graphicsLayer->addAnimation(opacityVector, IntSize(), anim, keyframes.animationName(), timeOffset))
1321         didAnimateOpacity = true;
1322
1323 #if ENABLE(CSS_FILTERS)
1324     if (hasFilter && m_graphicsLayer->addAnimation(filterVector, IntSize(), anim, keyframes.animationName(), timeOffset))
1325         didAnimateFilter = true;
1326 #endif
1327
1328 #if ENABLE(CSS_FILTERS)
1329     return didAnimateTransform || didAnimateOpacity || didAnimateFilter;
1330 #else
1331     return didAnimateTransform || didAnimateOpacity;
1332 #endif
1333 }
1334
1335 void RenderLayerBacking::animationPaused(double timeOffset, const String& animationName)
1336 {
1337     m_graphicsLayer->pauseAnimation(animationName, timeOffset);
1338 }
1339
1340 void RenderLayerBacking::animationFinished(const String& animationName)
1341 {
1342     m_graphicsLayer->removeAnimation(animationName);
1343 }
1344
1345 bool RenderLayerBacking::startTransition(double timeOffset, CSSPropertyID property, const RenderStyle* fromStyle, const RenderStyle* toStyle)
1346 {
1347     bool didAnimateOpacity = false;
1348     bool didAnimateTransform = false;
1349 #if ENABLE(CSS_FILTERS)
1350     bool didAnimateFilter = false;
1351 #endif
1352
1353     ASSERT(property != CSSPropertyInvalid);
1354
1355     if (property == CSSPropertyOpacity) {
1356         const Animation* opacityAnim = toStyle->transitionForProperty(CSSPropertyOpacity);
1357         if (opacityAnim && !opacityAnim->isEmptyOrZeroDuration()) {
1358             KeyframeValueList opacityVector(AnimatedPropertyOpacity);
1359             opacityVector.insert(new FloatAnimationValue(0, compositingOpacity(fromStyle->opacity())));
1360             opacityVector.insert(new FloatAnimationValue(1, compositingOpacity(toStyle->opacity())));
1361             // The boxSize param is only used for transform animations (which can only run on RenderBoxes), so we pass an empty size here.
1362             if (m_graphicsLayer->addAnimation(opacityVector, IntSize(), opacityAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyOpacity), timeOffset)) {
1363                 // To ensure that the correct opacity is visible when the animation ends, also set the final opacity.
1364                 updateLayerOpacity(toStyle);
1365                 didAnimateOpacity = true;
1366             }
1367         }
1368     }
1369
1370     if (property == CSSPropertyWebkitTransform && m_owningLayer->hasTransform()) {
1371         const Animation* transformAnim = toStyle->transitionForProperty(CSSPropertyWebkitTransform);
1372         if (transformAnim && !transformAnim->isEmptyOrZeroDuration()) {
1373             KeyframeValueList transformVector(AnimatedPropertyWebkitTransform);
1374             transformVector.insert(new TransformAnimationValue(0, &fromStyle->transform()));
1375             transformVector.insert(new TransformAnimationValue(1, &toStyle->transform()));
1376             if (m_graphicsLayer->addAnimation(transformVector, toRenderBox(renderer())->pixelSnappedBorderBoxRect().size(), transformAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyWebkitTransform), timeOffset)) {
1377                 // To ensure that the correct transform is visible when the animation ends, also set the final transform.
1378                 updateLayerTransform(toStyle);
1379                 didAnimateTransform = true;
1380             }
1381         }
1382     }
1383
1384 #if ENABLE(CSS_FILTERS)
1385     if (property == CSSPropertyWebkitFilter && m_owningLayer->hasFilter()) {
1386         const Animation* filterAnim = toStyle->transitionForProperty(CSSPropertyWebkitFilter);
1387         if (filterAnim && !filterAnim->isEmptyOrZeroDuration()) {
1388             KeyframeValueList filterVector(AnimatedPropertyWebkitFilter);
1389             filterVector.insert(new FilterAnimationValue(0, &fromStyle->filter()));
1390             filterVector.insert(new FilterAnimationValue(1, &toStyle->filter()));
1391             if (m_graphicsLayer->addAnimation(filterVector, IntSize(), filterAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyWebkitFilter), timeOffset)) {
1392                 // To ensure that the correct filter is visible when the animation ends, also set the final filter.
1393                 updateLayerFilters(toStyle);
1394                 didAnimateFilter = true;
1395             }
1396         }
1397     }
1398 #endif
1399
1400 #if ENABLE(CSS_FILTERS)
1401     return didAnimateOpacity || didAnimateTransform || didAnimateFilter;
1402 #else
1403     return didAnimateOpacity || didAnimateTransform;
1404 #endif
1405 }
1406
1407 void RenderLayerBacking::transitionPaused(double timeOffset, CSSPropertyID property)
1408 {
1409     AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
1410     if (animatedProperty != AnimatedPropertyInvalid)
1411         m_graphicsLayer->pauseAnimation(GraphicsLayer::animationNameForTransition(animatedProperty), timeOffset);
1412 }
1413
1414 void RenderLayerBacking::transitionFinished(CSSPropertyID property)
1415 {
1416     AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
1417     if (animatedProperty != AnimatedPropertyInvalid)
1418         m_graphicsLayer->removeAnimation(GraphicsLayer::animationNameForTransition(animatedProperty));
1419 }
1420
1421 void RenderLayerBacking::notifyAnimationStarted(const GraphicsLayer*, double time)
1422 {
1423     renderer()->animation()->notifyAnimationStarted(renderer(), time);
1424 }
1425
1426 void RenderLayerBacking::notifySyncRequired(const GraphicsLayer*)
1427 {
1428     if (!renderer()->documentBeingDestroyed())
1429         compositor()->scheduleLayerFlush();
1430 }
1431
1432 // This is used for the 'freeze' API, for testing only.
1433 void RenderLayerBacking::suspendAnimations(double time)
1434 {
1435     m_graphicsLayer->suspendAnimations(time);
1436 }
1437
1438 void RenderLayerBacking::resumeAnimations()
1439 {
1440     m_graphicsLayer->resumeAnimations();
1441 }
1442
1443 IntRect RenderLayerBacking::compositedBounds() const
1444 {
1445     return m_compositedBounds;
1446 }
1447
1448 void RenderLayerBacking::setCompositedBounds(const IntRect& bounds)
1449 {
1450     m_compositedBounds = bounds;
1451 }
1452
1453 CSSPropertyID RenderLayerBacking::graphicsLayerToCSSProperty(AnimatedPropertyID property)
1454 {
1455     CSSPropertyID cssProperty = CSSPropertyInvalid;
1456     switch (property) {
1457         case AnimatedPropertyWebkitTransform:
1458             cssProperty = CSSPropertyWebkitTransform;
1459             break;
1460         case AnimatedPropertyOpacity:
1461             cssProperty = CSSPropertyOpacity;
1462             break;
1463         case AnimatedPropertyBackgroundColor:
1464             cssProperty = CSSPropertyBackgroundColor;
1465             break;
1466         case AnimatedPropertyWebkitFilter:
1467 #if ENABLE(CSS_FILTERS)
1468             cssProperty = CSSPropertyWebkitFilter;
1469 #else
1470             ASSERT_NOT_REACHED();
1471 #endif
1472             break;
1473         case AnimatedPropertyInvalid:
1474             ASSERT_NOT_REACHED();
1475     }
1476     return cssProperty;
1477 }
1478
1479 AnimatedPropertyID RenderLayerBacking::cssToGraphicsLayerProperty(CSSPropertyID cssProperty)
1480 {
1481     switch (cssProperty) {
1482         case CSSPropertyWebkitTransform:
1483             return AnimatedPropertyWebkitTransform;
1484         case CSSPropertyOpacity:
1485             return AnimatedPropertyOpacity;
1486         case CSSPropertyBackgroundColor:
1487             return AnimatedPropertyBackgroundColor;
1488 #if ENABLE(CSS_FILTERS)
1489         case CSSPropertyWebkitFilter:
1490             return AnimatedPropertyWebkitFilter;
1491 #endif
1492         default:
1493             // It's fine if we see other css properties here; they are just not accelerated.
1494             break;
1495     }
1496     return AnimatedPropertyInvalid;
1497 }
1498
1499 String RenderLayerBacking::nameForLayer() const
1500 {
1501     String name = renderer()->renderName();
1502     if (Node* node = renderer()->node()) {
1503         if (node->isElementNode())
1504             name += " " + static_cast<Element*>(node)->tagName();
1505         if (node->hasID())
1506             name += " \'" + static_cast<Element*>(node)->getIdAttribute() + "\'";
1507     }
1508
1509     if (m_owningLayer->isReflection())
1510         name += " (reflection)";
1511
1512     return name;
1513 }
1514
1515 CompositingLayerType RenderLayerBacking::compositingLayerType() const
1516 {
1517     if (m_graphicsLayer->hasContentsLayer())
1518         return MediaCompositingLayer;
1519
1520     if (m_graphicsLayer->drawsContent())
1521         return m_graphicsLayer->usingTiledLayer() ? TiledCompositingLayer : NormalCompositingLayer;
1522     
1523     return ContainerCompositingLayer;
1524 }
1525
1526 double RenderLayerBacking::backingStoreArea() const
1527 {
1528     double backingArea;
1529     
1530     // m_ancestorClippingLayer and m_clippingLayer are just used for masking, so have no backing.
1531     backingArea = m_graphicsLayer->backingStoreArea();
1532     if (m_foregroundLayer)
1533         backingArea += m_foregroundLayer->backingStoreArea();
1534     if (m_maskLayer)
1535         backingArea += m_maskLayer->backingStoreArea();
1536
1537     if (m_layerForHorizontalScrollbar)
1538         backingArea += m_layerForHorizontalScrollbar->backingStoreArea();
1539
1540     if (m_layerForVerticalScrollbar)
1541         backingArea += m_layerForVerticalScrollbar->backingStoreArea();
1542
1543     if (m_layerForScrollCorner)
1544         backingArea += m_layerForScrollCorner->backingStoreArea();
1545     
1546     return backingArea;
1547 }
1548
1549 } // namespace WebCore
1550
1551 #endif // USE(ACCELERATED_COMPOSITING)
1552