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