[iOS][WebKit2] Mark layer contents as being opaque if they are
[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 INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27
28 #include "RenderLayerBacking.h"
29
30 #include "AnimationController.h"
31 #include "CanvasRenderingContext.h"
32 #include "CSSPropertyNames.h"
33 #include "CachedImage.h"
34 #include "Chrome.h"
35 #include "FontCache.h"
36 #include "FrameView.h"
37 #include "GraphicsContext.h"
38 #include "GraphicsLayer.h"
39 #include "HTMLCanvasElement.h"
40 #include "HTMLIFrameElement.h"
41 #include "HTMLMediaElement.h"
42 #include "HTMLNames.h"
43 #include "HTMLPlugInElement.h"
44 #include "InspectorInstrumentation.h"
45 #include "KeyframeList.h"
46 #include "MainFrame.h"
47 #include "PluginViewBase.h"
48 #include "ProgressTracker.h"
49 #include "RenderFlowThread.h"
50 #include "RenderIFrame.h"
51 #include "RenderImage.h"
52 #include "RenderLayerCompositor.h"
53 #include "RenderEmbeddedObject.h"
54 #include "RenderNamedFlowFragment.h"
55 #include "RenderRegion.h"
56 #include "RenderVideo.h"
57 #include "RenderView.h"
58 #include "ScrollingCoordinator.h"
59 #include "Settings.h"
60 #include "StyleResolver.h"
61 #include "TiledBacking.h"
62 #include <wtf/text/StringBuilder.h>
63
64 #if ENABLE(CSS_FILTERS)
65 #include "FilterEffectRenderer.h"
66 #endif
67
68 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
69 #include "GraphicsContext3D.h"
70 #endif
71
72 namespace WebCore {
73
74 using namespace HTMLNames;
75
76 static bool hasBoxDecorationsOrBackgroundImage(const RenderStyle*);
77 static LayoutRect clipBox(RenderBox& renderer);
78
79 CanvasCompositingStrategy canvasCompositingStrategy(const RenderObject& renderer)
80 {
81     ASSERT(renderer.isCanvas());
82     
83     const HTMLCanvasElement* canvas = toHTMLCanvasElement(renderer.node());
84     CanvasRenderingContext* context = canvas->renderingContext();
85     if (!context || !context->isAccelerated())
86         return UnacceleratedCanvas;
87     
88     if (context->is3d())
89         return CanvasAsLayerContents;
90
91 #if ENABLE(ACCELERATED_2D_CANVAS)
92     return CanvasAsLayerContents;
93 #else
94     return CanvasPaintedToLayer; // On Mac and iOS we paint accelerated canvases into their layers.
95 #endif
96 }
97
98 // Get the scrolling coordinator in a way that works inside RenderLayerBacking's destructor.
99 static ScrollingCoordinator* scrollingCoordinatorFromLayer(RenderLayer& layer)
100 {
101     Page* page = layer.renderer().frame().page();
102     if (!page)
103         return 0;
104
105     return page->scrollingCoordinator();
106 }
107
108 bool RenderLayerBacking::m_creatingPrimaryGraphicsLayer = false;
109
110 RenderLayerBacking::RenderLayerBacking(RenderLayer& layer)
111     : m_owningLayer(layer)
112     , m_viewportConstrainedNodeID(0)
113     , m_scrollingNodeID(0)
114     , m_artificiallyInflatedBounds(false)
115     , m_isMainFrameRenderViewLayer(false)
116     , m_usingTiledCacheLayer(false)
117     , m_requiresOwnBackingStore(true)
118 #if ENABLE(CSS_FILTERS)
119     , m_canCompositeFilters(false)
120 #endif
121     , m_backgroundLayerPaintsFixedRootBackground(false)
122 {
123     Page* page = renderer().frame().page();
124
125     if (layer.isRootLayer() && page) {
126         if (renderer().frame().isMainFrame())
127             m_isMainFrameRenderViewLayer = true;
128
129         m_usingTiledCacheLayer = page->chrome().client().shouldUseTiledBackingForFrameView(renderer().frame().view());
130     }
131     
132     createPrimaryGraphicsLayer();
133
134     if (m_usingTiledCacheLayer && page) {
135         TiledBacking* tiledBacking = this->tiledBacking();
136
137         tiledBacking->setIsInWindow(page->isInWindow());
138
139         if (m_isMainFrameRenderViewLayer) {
140             tiledBacking->setExposedRect(renderer().frame().view()->exposedRect());
141             tiledBacking->setUnparentsOffscreenTiles(true);
142         }
143
144         tiledBacking->setScrollingPerformanceLoggingEnabled(page->settings().scrollingPerformanceLoggingEnabled());
145         adjustTiledBackingCoverage();
146     }
147 }
148
149 RenderLayerBacking::~RenderLayerBacking()
150 {
151     updateAncestorClippingLayer(false);
152     updateDescendantClippingLayer(false);
153     updateOverflowControlsLayers(false, false, false);
154     updateForegroundLayer(false);
155     updateBackgroundLayer(false);
156     updateMaskLayer(false);
157     updateScrollingLayers(false);
158     detachFromScrollingCoordinator();
159     destroyGraphicsLayers();
160 }
161
162 void RenderLayerBacking::willDestroyLayer(const GraphicsLayer* layer)
163 {
164     if (layer && layer->usingTiledBacking())
165         compositor().layerTiledBackingUsageChanged(layer, false);
166 }
167
168 std::unique_ptr<GraphicsLayer> RenderLayerBacking::createGraphicsLayer(const String& name)
169 {
170     GraphicsLayerFactory* graphicsLayerFactory = 0;
171     if (Page* page = renderer().frame().page())
172         graphicsLayerFactory = page->chrome().client().graphicsLayerFactory();
173
174     std::unique_ptr<GraphicsLayer> graphicsLayer = GraphicsLayer::create(graphicsLayerFactory, this);
175
176 #ifndef NDEBUG
177     graphicsLayer->setName(name);
178 #else
179     UNUSED_PARAM(name);
180 #endif
181     graphicsLayer->setMaintainsPixelAlignment(compositor().keepLayersPixelAligned());
182
183 #if PLATFORM(COCOA) && USE(CA)
184     graphicsLayer->setAcceleratesDrawing(compositor().acceleratedDrawingEnabled());
185 #endif    
186     
187     return graphicsLayer;
188 }
189
190 bool RenderLayerBacking::shouldUseTiledBacking(const GraphicsLayer*) const
191 {
192     return m_usingTiledCacheLayer && m_creatingPrimaryGraphicsLayer;
193 }
194
195 void RenderLayerBacking::tiledBackingUsageChanged(const GraphicsLayer* layer, bool usingTiledBacking)
196 {
197     compositor().layerTiledBackingUsageChanged(layer, usingTiledBacking);
198 }
199
200 TiledBacking* RenderLayerBacking::tiledBacking() const
201 {
202     return m_graphicsLayer->tiledBacking();
203 }
204
205 static TiledBacking::TileCoverage computeTileCoverage(RenderLayerBacking* backing)
206 {
207     // FIXME: When we use TiledBacking for overflow, this should look at RenderView scrollability.
208     FrameView& frameView = backing->owningLayer().renderer().view().frameView();
209
210     TiledBacking::TileCoverage tileCoverage = TiledBacking::CoverageForVisibleArea;
211     bool useMinimalTilesDuringLiveResize = frameView.inLiveResize();
212     if (frameView.speculativeTilingEnabled() && !useMinimalTilesDuringLiveResize) {
213         bool clipsToExposedRect = !frameView.exposedRect().isInfinite();
214         if (frameView.horizontalScrollbarMode() != ScrollbarAlwaysOff || clipsToExposedRect)
215             tileCoverage |= TiledBacking::CoverageForHorizontalScrolling;
216
217         if (frameView.verticalScrollbarMode() != ScrollbarAlwaysOff || clipsToExposedRect)
218             tileCoverage |= TiledBacking::CoverageForVerticalScrolling;
219     }
220     return tileCoverage;
221 }
222
223 void RenderLayerBacking::adjustTiledBackingCoverage()
224 {
225     if (!m_usingTiledCacheLayer)
226         return;
227
228     TiledBacking::TileCoverage tileCoverage = computeTileCoverage(this);
229     tiledBacking()->setTileCoverage(tileCoverage);
230 }
231
232 void RenderLayerBacking::setTiledBackingHasMargins(bool hasExtendedBackgroundRect)
233 {
234     if (!m_usingTiledCacheLayer)
235         return;
236
237     int marginLeftAndRightSize = hasExtendedBackgroundRect ? defaultTileWidth : 0;
238     int marginTopAndBottomSize = hasExtendedBackgroundRect ? defaultTileHeight : 0;
239     tiledBacking()->setTileMargins(marginTopAndBottomSize, marginTopAndBottomSize, marginLeftAndRightSize, marginLeftAndRightSize);
240 }
241
242 void RenderLayerBacking::updateDebugIndicators(bool showBorder, bool showRepaintCounter)
243 {
244     m_graphicsLayer->setShowDebugBorder(showBorder);
245     m_graphicsLayer->setShowRepaintCounter(showRepaintCounter);
246     
247     if (m_ancestorClippingLayer)
248         m_ancestorClippingLayer->setShowDebugBorder(showBorder);
249
250     if (m_foregroundLayer) {
251         m_foregroundLayer->setShowDebugBorder(showBorder);
252         m_foregroundLayer->setShowRepaintCounter(showRepaintCounter);
253     }
254     
255     if (m_contentsContainmentLayer)
256         m_contentsContainmentLayer->setShowDebugBorder(showBorder);
257     
258     if (m_backgroundLayer) {
259         m_backgroundLayer->setShowDebugBorder(showBorder);
260         m_backgroundLayer->setShowRepaintCounter(showRepaintCounter);
261     }
262
263     if (m_maskLayer) {
264         m_maskLayer->setShowDebugBorder(showBorder);
265         m_maskLayer->setShowRepaintCounter(showRepaintCounter);
266     }
267
268     if (m_layerForHorizontalScrollbar)
269         m_layerForHorizontalScrollbar->setShowDebugBorder(showBorder);
270
271     if (m_layerForVerticalScrollbar)
272         m_layerForVerticalScrollbar->setShowDebugBorder(showBorder);
273
274     if (m_layerForScrollCorner)
275         m_layerForScrollCorner->setShowDebugBorder(showBorder);
276
277     if (m_scrollingLayer)
278         m_scrollingLayer->setShowDebugBorder(showBorder);
279
280     if (m_scrollingContentsLayer) {
281         m_scrollingContentsLayer->setShowDebugBorder(showBorder);
282         m_scrollingContentsLayer->setShowRepaintCounter(showRepaintCounter);
283     }
284 }
285
286 void RenderLayerBacking::createPrimaryGraphicsLayer()
287 {
288     String layerName;
289 #ifndef NDEBUG
290     layerName = m_owningLayer.name();
291 #endif
292     
293     // The call to createGraphicsLayer ends calling back into here as
294     // a GraphicsLayerClient to ask if it shouldUseTiledBacking(). We only want
295     // the tile cache on our main layer. This is pretty ugly, but saves us from
296     // exposing the API to all clients.
297
298     m_creatingPrimaryGraphicsLayer = true;
299     m_graphicsLayer = createGraphicsLayer(layerName);
300     m_creatingPrimaryGraphicsLayer = false;
301
302     if (m_usingTiledCacheLayer)
303         m_childContainmentLayer = createGraphicsLayer("TiledBacking Flattening Layer");
304
305     if (m_isMainFrameRenderViewLayer) {
306 #if !PLATFORM(IOS)
307         // Page scale is applied above the RenderView on iOS.
308         m_graphicsLayer->setContentsOpaque(true);
309         m_graphicsLayer->setAppliesPageScale();
310 #endif
311     }
312
313 #if PLATFORM(COCOA) && USE(CA)
314     if (!compositor().acceleratedDrawingEnabled() && renderer().isCanvas()) {
315         const HTMLCanvasElement* canvas = toHTMLCanvasElement(renderer().element());
316         if (canvas->shouldAccelerate(canvas->size()))
317             m_graphicsLayer->setAcceleratesDrawing(true);
318     }
319 #endif    
320     
321     updateOpacity(&renderer().style());
322     updateTransform(&renderer().style());
323 #if ENABLE(CSS_FILTERS)
324     updateFilters(&renderer().style());
325 #endif
326 #if ENABLE(CSS_COMPOSITING)
327     updateBlendMode(&renderer().style());
328 #endif
329 }
330
331 #if PLATFORM(IOS)
332 void RenderLayerBacking::layerWillBeDestroyed()
333 {
334     RenderObject& renderer = this->renderer();
335     if (renderer.isEmbeddedObject() && toRenderEmbeddedObject(renderer).allowsAcceleratedCompositing()) {
336         PluginViewBase* pluginViewBase = toPluginViewBase(toRenderWidget(renderer).widget());
337         if (pluginViewBase && m_graphicsLayer->contentsLayerForMedia())
338             pluginViewBase->detachPluginLayer();
339     }
340 }
341 #endif
342
343 void RenderLayerBacking::destroyGraphicsLayers()
344 {
345     if (m_graphicsLayer) {
346         willDestroyLayer(m_graphicsLayer.get());
347         m_graphicsLayer->removeFromParent();
348     }
349
350     m_ancestorClippingLayer = nullptr;
351     m_contentsContainmentLayer = nullptr;
352     m_graphicsLayer = nullptr;
353     m_foregroundLayer = nullptr;
354     m_backgroundLayer = nullptr;
355     m_childContainmentLayer = nullptr;
356     m_maskLayer = nullptr;
357
358     m_scrollingLayer = nullptr;
359     m_scrollingContentsLayer = nullptr;
360 }
361
362 void RenderLayerBacking::updateOpacity(const RenderStyle* style)
363 {
364     m_graphicsLayer->setOpacity(compositingOpacity(style->opacity()));
365 }
366
367 void RenderLayerBacking::updateTransform(const RenderStyle* style)
368 {
369     // FIXME: This could use m_owningLayer.transform(), but that currently has transform-origin
370     // baked into it, and we don't want that.
371     TransformationMatrix t;
372     if (m_owningLayer.hasTransform()) {
373         style->applyTransform(t, toRenderBox(renderer()).pixelSnappedBorderBoxRect().size(), RenderStyle::ExcludeTransformOrigin);
374         makeMatrixRenderable(t, compositor().canRender3DTransforms());
375     }
376     
377     if (m_contentsContainmentLayer) {
378         m_contentsContainmentLayer->setTransform(t);
379         m_graphicsLayer->setTransform(TransformationMatrix());
380     } else
381         m_graphicsLayer->setTransform(t);
382 }
383
384 #if ENABLE(CSS_FILTERS)
385 void RenderLayerBacking::updateFilters(const RenderStyle* style)
386 {
387     m_canCompositeFilters = m_graphicsLayer->setFilters(style->filter());
388 }
389 #endif
390
391 #if ENABLE(CSS_COMPOSITING)
392 void RenderLayerBacking::updateBlendMode(const RenderStyle* style)
393 {
394     if (m_ancestorClippingLayer)
395         m_ancestorClippingLayer->setBlendMode(style->blendMode());
396     else
397         m_graphicsLayer->setBlendMode(style->blendMode());
398 }
399 #endif
400
401 static bool hasNonZeroTransformOrigin(const RenderObject& renderer)
402 {
403     const RenderStyle& style = renderer.style();
404     return (style.transformOriginX().type() == Fixed && style.transformOriginX().value())
405         || (style.transformOriginY().type() == Fixed && style.transformOriginY().value());
406 }
407
408 #if PLATFORM(IOS)
409 // FIXME: We should merge the concept of RenderLayer::{hasAcceleratedTouchScrolling, needsCompositedScrolling}()
410 // so that we can remove this iOS-specific variant.
411 static bool layerOrAncestorIsTransformedOrScrolling(RenderLayer& layer)
412 {
413     for (RenderLayer* curr = &layer; curr; curr = curr->parent()) {
414         if (curr->hasTransform() || curr->hasAcceleratedTouchScrolling())
415             return true;
416     }
417
418     return false;
419 }
420 #else
421 static bool layerOrAncestorIsTransformedOrUsingCompositedScrolling(RenderLayer& layer)
422 {
423     for (RenderLayer* curr = &layer; curr; curr = curr->parent()) {
424         if (curr->hasTransform() || curr->needsCompositedScrolling())
425             return true;
426     }
427
428     return false;
429 }
430 #endif
431     
432 bool RenderLayerBacking::shouldClipCompositedBounds() const
433 {
434 #if !PLATFORM(IOS)
435     // Scrollbar layers use this layer for relative positioning, so don't clip.
436     if (layerForHorizontalScrollbar() || layerForVerticalScrollbar())
437         return false;
438 #endif
439
440     if (m_usingTiledCacheLayer)
441         return false;
442
443 #if !PLATFORM(IOS)
444     if (layerOrAncestorIsTransformedOrUsingCompositedScrolling(m_owningLayer))
445         return false;
446 #else
447     if (layerOrAncestorIsTransformedOrScrolling(m_owningLayer))
448         return false;
449 #endif
450
451     if (m_owningLayer.isFlowThreadCollectingGraphicsLayersUnderRegions())
452         return false;
453
454     return true;
455 }
456
457 void RenderLayerBacking::updateCompositedBounds()
458 {
459     LayoutRect layerBounds = compositor().calculateCompositedBounds(m_owningLayer, m_owningLayer);
460
461     // Clip to the size of the document or enclosing overflow-scroll layer.
462     // If this or an ancestor is transformed, we can't currently compute the correct rect to intersect with.
463     // We'd need RenderObject::convertContainerToLocalQuad(), which doesn't yet exist.
464     if (shouldClipCompositedBounds()) {
465         RenderView& view = m_owningLayer.renderer().view();
466         RenderLayer* rootLayer = view.layer();
467
468         LayoutRect clippingBounds;
469         if (renderer().style().position() == FixedPosition && renderer().container() == &view)
470             clippingBounds = view.frameView().viewportConstrainedExtentRect();
471         else
472             clippingBounds = view.unscaledDocumentRect();
473
474         if (&m_owningLayer != rootLayer)
475             clippingBounds.intersect(m_owningLayer.backgroundClipRect(RenderLayer::ClipRectsContext(rootLayer, 0, AbsoluteClipRects)).rect()); // FIXME: Incorrect for CSS regions.
476
477         LayoutPoint delta;
478         m_owningLayer.convertToLayerCoords(rootLayer, delta, RenderLayer::AdjustForColumns);
479         clippingBounds.move(-delta.x(), -delta.y());
480
481         layerBounds.intersect(clippingBounds);
482     }
483     
484     // If the element has a transform-origin that has fixed lengths, and the renderer has zero size,
485     // then we need to ensure that the compositing layer has non-zero size so that we can apply
486     // the transform-origin via the GraphicsLayer anchorPoint (which is expressed as a fractional value).
487     if (layerBounds.isEmpty() && hasNonZeroTransformOrigin(renderer())) {
488         layerBounds.setWidth(1);
489         layerBounds.setHeight(1);
490         m_artificiallyInflatedBounds = true;
491     } else
492         m_artificiallyInflatedBounds = false;
493
494     setCompositedBounds(layerBounds);
495 }
496
497 void RenderLayerBacking::updateAfterWidgetResize()
498 {
499     if (!renderer().isWidget())
500         return;
501     if (RenderLayerCompositor* innerCompositor = RenderLayerCompositor::frameContentsCompositor(toRenderWidget(&renderer()))) {
502         innerCompositor->frameViewDidChangeSize();
503         innerCompositor->frameViewDidChangeLocation(flooredIntPoint(contentsBox().location()));
504     }
505 }
506
507 void RenderLayerBacking::updateAfterLayout(UpdateAfterLayoutFlags flags)
508 {
509     if (!compositor().compositingLayersNeedRebuild()) {
510         // Calling updateGraphicsLayerGeometry() here gives incorrect results, because the
511         // position of this layer's GraphicsLayer depends on the position of our compositing
512         // ancestor's GraphicsLayer. That cannot be determined until all the descendant 
513         // RenderLayers of that ancestor have been processed via updateLayerPositions().
514         //
515         // The solution is to update compositing children of this layer here,
516         // via updateCompositingChildrenGeometry().
517         updateCompositedBounds();
518         compositor().updateCompositingDescendantGeometry(m_owningLayer, m_owningLayer, flags & CompositingChildrenOnly);
519         
520         if (flags & IsUpdateRoot) {
521             updateGraphicsLayerGeometry();
522             compositor().updateRootLayerPosition();
523             RenderLayer* stackingContainer = m_owningLayer.enclosingStackingContainer();
524             if (!compositor().compositingLayersNeedRebuild() && stackingContainer && (stackingContainer != &m_owningLayer))
525                 compositor().updateCompositingDescendantGeometry(*stackingContainer, *stackingContainer, flags & CompositingChildrenOnly);
526         }
527     }
528     
529     if (flags & NeedsFullRepaint && !paintsIntoWindow() && !paintsIntoCompositedAncestor())
530         setContentsNeedDisplay();
531 }
532
533 bool RenderLayerBacking::updateGraphicsLayerConfiguration()
534 {
535     m_owningLayer.updateDescendantDependentFlags();
536     m_owningLayer.updateZOrderLists();
537
538     bool layerConfigChanged = false;
539     setBackgroundLayerPaintsFixedRootBackground(compositor().needsFixedRootBackgroundLayer(m_owningLayer));
540     
541     // The background layer is currently only used for fixed root backgrounds.
542     if (updateBackgroundLayer(m_backgroundLayerPaintsFixedRootBackground))
543         layerConfigChanged = true;
544
545     if (updateForegroundLayer(compositor().needsContentsCompositingLayer(m_owningLayer)))
546         layerConfigChanged = true;
547     
548     bool needsDescendentsClippingLayer = compositor().clipsCompositingDescendants(m_owningLayer);
549
550 #if PLATFORM(IOS)
551     // Our scrolling layer will clip.
552     if (m_owningLayer.hasAcceleratedTouchScrolling())
553         needsDescendentsClippingLayer = false;
554 #else
555     // Our scrolling layer will clip.
556     if (m_owningLayer.needsCompositedScrolling())
557         needsDescendentsClippingLayer = false;
558 #endif // PLATFORM(IOS)
559
560     if (updateAncestorClippingLayer(compositor().clippedByAncestor(m_owningLayer)))
561         layerConfigChanged = true;
562
563     if (updateDescendantClippingLayer(needsDescendentsClippingLayer))
564         layerConfigChanged = true;
565
566     if (updateOverflowControlsLayers(requiresHorizontalScrollbarLayer(), requiresVerticalScrollbarLayer(), requiresScrollCornerLayer()))
567         layerConfigChanged = true;
568
569 #if PLATFORM(IOS)
570     if (updateScrollingLayers(m_owningLayer.hasAcceleratedTouchScrolling()))
571         layerConfigChanged = true;
572 #else
573     if (updateScrollingLayers(m_owningLayer.needsCompositedScrolling()))
574         layerConfigChanged = true;
575 #endif // PLATFORM(IOS)
576
577     if (layerConfigChanged)
578         updateInternalHierarchy();
579
580     if (GraphicsLayer* flatteningLayer = tileCacheFlatteningLayer()) {
581         if (layerConfigChanged || flatteningLayer->parent() != m_graphicsLayer.get())
582             m_graphicsLayer->addChild(flatteningLayer);
583     }
584
585     if (updateMaskLayer(renderer().hasMask()))
586         m_graphicsLayer->setMaskLayer(m_maskLayer.get());
587
588     if (m_owningLayer.hasReflection()) {
589         if (m_owningLayer.reflectionLayer()->backing()) {
590             GraphicsLayer* reflectionLayer = m_owningLayer.reflectionLayer()->backing()->graphicsLayer();
591             m_graphicsLayer->setReplicatedByLayer(reflectionLayer);
592         }
593     } else
594         m_graphicsLayer->setReplicatedByLayer(0);
595
596     bool isSimpleContainer = isSimpleContainerCompositingLayer();
597     bool didUpdateContentsRect = false;
598     updateDirectlyCompositedContents(isSimpleContainer, didUpdateContentsRect);
599
600     updateRootLayerConfiguration();
601     
602     if (isDirectlyCompositedImage())
603         updateImageContents();
604
605     if (renderer().isEmbeddedObject() && toRenderEmbeddedObject(&renderer())->allowsAcceleratedCompositing()) {
606         PluginViewBase* pluginViewBase = toPluginViewBase(toRenderWidget(&renderer())->widget());
607 #if PLATFORM(IOS)
608         if (pluginViewBase && !m_graphicsLayer->contentsLayerForMedia()) {
609             pluginViewBase->detachPluginLayer();
610             pluginViewBase->attachPluginLayer();
611         }
612 #else
613         if (!pluginViewBase->shouldNotAddLayer())
614             m_graphicsLayer->setContentsToMedia(pluginViewBase->platformLayer());
615 #endif
616     }
617 #if ENABLE(VIDEO)
618     else if (renderer().isVideo()) {
619         HTMLMediaElement* mediaElement = toHTMLMediaElement(renderer().element());
620         m_graphicsLayer->setContentsToMedia(mediaElement->platformLayer());
621     }
622 #endif
623 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
624     else if (renderer().isCanvas() && canvasCompositingStrategy(renderer()) == CanvasAsLayerContents) {
625         const HTMLCanvasElement* canvas = toHTMLCanvasElement(renderer().element());
626         if (CanvasRenderingContext* context = canvas->renderingContext())
627             m_graphicsLayer->setContentsToCanvas(context->platformLayer());
628         layerConfigChanged = true;
629     }
630 #endif
631     if (renderer().isWidget())
632         layerConfigChanged = RenderLayerCompositor::parentFrameContentLayers(toRenderWidget(&renderer()));
633
634     return layerConfigChanged;
635 }
636
637 static LayoutRect clipBox(RenderBox& renderer)
638 {
639     LayoutRect result = LayoutRect::infiniteRect();
640     if (renderer.hasOverflowClip())
641         result = renderer.overflowClipRect(LayoutPoint(), 0); // FIXME: Incorrect for CSS regions.
642
643     if (renderer.hasClip())
644         result.intersect(renderer.clipRect(LayoutPoint(), 0)); // FIXME: Incorrect for CSS regions.
645
646     return result;
647 }
648
649 static FloatSize pixelFractionForLayerPainting(const LayoutPoint& point, float pixelSnappingFactor)
650 {
651     LayoutUnit x = point.x();
652     LayoutUnit y = point.y();
653     x = x >= 0 ? floorToDevicePixel(x, pixelSnappingFactor) : ceilToDevicePixel(x, pixelSnappingFactor);
654     y = y >= 0 ? floorToDevicePixel(y, pixelSnappingFactor) : ceilToDevicePixel(y, pixelSnappingFactor);
655     return point - LayoutPoint(x, y);
656 }
657
658 static void calculateDevicePixelOffsetFromRenderer(const LayoutSize& rendererOffsetFromGraphicsLayer, FloatSize& devicePixelOffsetFromRenderer,
659     LayoutSize& devicePixelFractionFromRenderer, float deviceScaleFactor)
660 {
661     devicePixelFractionFromRenderer = LayoutSize(pixelFractionForLayerPainting(toLayoutPoint(rendererOffsetFromGraphicsLayer), deviceScaleFactor));
662     devicePixelOffsetFromRenderer = rendererOffsetFromGraphicsLayer - devicePixelFractionFromRenderer;
663 }
664
665 void RenderLayerBacking::updateGraphicsLayerGeometry()
666 {
667     // If we haven't built z-order lists yet, wait until later.
668     if (m_owningLayer.isStackingContainer() && m_owningLayer.m_zOrderListsDirty)
669         return;
670
671     // Set transform property, if it is not animating. We have to do this here because the transform
672     // is affected by the layer dimensions.
673     if (!renderer().animation().isRunningAcceleratedAnimationOnRenderer(&renderer(), CSSPropertyWebkitTransform))
674         updateTransform(&renderer().style());
675
676     // Set opacity, if it is not animating.
677     if (!renderer().animation().isRunningAcceleratedAnimationOnRenderer(&renderer(), CSSPropertyOpacity))
678         updateOpacity(&renderer().style());
679         
680 #if ENABLE(CSS_FILTERS)
681     updateFilters(&renderer().style());
682 #endif
683
684 #if ENABLE(CSS_COMPOSITING)
685     updateBlendMode(&renderer().style());
686 #endif
687
688     bool isSimpleContainer = isSimpleContainerCompositingLayer();
689     
690     m_owningLayer.updateDescendantDependentFlags();
691
692     // m_graphicsLayer is the corresponding GraphicsLayer for this RenderLayer and its non-compositing
693     // descendants. So, the visibility flag for m_graphicsLayer should be true if there are any
694     // non-compositing visible layers.
695     m_graphicsLayer->setContentsVisible(m_owningLayer.hasVisibleContent() || hasVisibleNonCompositingDescendantLayers());
696
697     const RenderStyle& style = renderer().style();
698     // FIXME: reflections should force transform-style to be flat in the style: https://bugs.webkit.org/show_bug.cgi?id=106959
699     bool preserves3D = style.transformStyle3D() == TransformStyle3DPreserve3D && !renderer().hasReflection();
700     m_graphicsLayer->setPreserves3D(preserves3D);
701     m_graphicsLayer->setBackfaceVisibility(style.backfaceVisibility() == BackfaceVisibilityVisible);
702
703     RenderLayer* compAncestor = m_owningLayer.ancestorCompositingLayer();
704     
705     // We compute everything relative to the enclosing compositing layer.
706     LayoutRect ancestorCompositingBounds;
707     if (compAncestor) {
708         ASSERT(compAncestor->backing());
709         ancestorCompositingBounds = compAncestor->backing()->compositedBounds();
710     }
711
712     /*
713     * GraphicsLayer: device pixel positioned. Floored, enclosing rect.
714     * RenderLayer: subpixel positioned.
715     * Offset from renderer (GraphicsLayer <-> RenderLayer::renderer()): subpixel based offset.
716     *
717     *     relativeCompositingBounds
718     *      _______________________________________
719     *     |\          GraphicsLayer               |
720     *     | \                                     |
721     *     |  \ offset from renderer: (device pixel + subpixel)
722     *     |   \                                   |
723     *     |    \______________________________    |
724     *     |    | localCompositingBounds       |   |
725     *     |    |                              |   |
726     *     |    |   RenderLayer::renderer()    |   |
727     *     |    |                              |   |
728     *
729     * localCompositingBounds: this RenderLayer relative to its renderer().
730     * relativeCompositingBounds: this RenderLayer relative to its parent compositing layer.
731     * enclosingRelativeCompositingBounds: this RenderLayer relative to its parent but floored to device pixel position.
732     * rendererOffsetFromGraphicsLayer: RenderLayer::renderer()'s offset from its enclosing GraphicsLayer.
733     * devicePixelOffsetFromRenderer: rendererOffsetFromGraphicsLayer's device pixel part. (6.9px -> 6.5px in case of 2x display)
734     * devicePixelFractionFromRenderer: rendererOffsetFromGraphicsLayer's fractional part (6.9px -> 0.4px in case of 2x display)
735     */
736     float deviceScaleFactor = this->deviceScaleFactor();
737     LayoutRect localCompositingBounds = compositedBounds();
738     LayoutRect relativeCompositingBounds(localCompositingBounds);
739
740     LayoutPoint offsetFromParent;
741     m_owningLayer.convertToLayerCoords(compAncestor, offsetFromParent, RenderLayer::AdjustForColumns);
742     relativeCompositingBounds.moveBy(offsetFromParent);
743
744     LayoutRect enclosingRelativeCompositingBounds = LayoutRect(enclosingRectForPainting(relativeCompositingBounds, deviceScaleFactor));
745     LayoutSize subpixelOffsetAdjustment = enclosingRelativeCompositingBounds.location() - relativeCompositingBounds.location();
746     LayoutSize rendererOffsetFromGraphicsLayer =  toLayoutSize(localCompositingBounds.location()) + subpixelOffsetAdjustment;
747
748     FloatSize devicePixelOffsetFromRenderer;
749     LayoutSize devicePixelFractionFromRenderer;
750     calculateDevicePixelOffsetFromRenderer(rendererOffsetFromGraphicsLayer, devicePixelOffsetFromRenderer, devicePixelFractionFromRenderer, deviceScaleFactor);
751     m_devicePixelFractionFromRenderer = LayoutSize(fabs(devicePixelFractionFromRenderer.width().toFloat()), fabs(devicePixelFractionFromRenderer.height().toFloat()));
752
753     adjustAncestorCompositingBoundsForFlowThread(ancestorCompositingBounds, compAncestor);
754
755     LayoutPoint graphicsLayerParentLocation;
756     if (compAncestor && compAncestor->backing()->hasClippingLayer()) {
757         // If the compositing ancestor has a layer to clip children, we parent in that, and therefore
758         // position relative to it.
759         LayoutRect clippingBox = clipBox(toRenderBox(compAncestor->renderer()));
760         graphicsLayerParentLocation = clippingBox.location();
761     } else if (compAncestor)
762         graphicsLayerParentLocation = ancestorCompositingBounds.location();
763     else
764         graphicsLayerParentLocation = renderer().view().documentRect().location();
765
766 #if PLATFORM(IOS)
767     if (compAncestor && compAncestor->hasAcceleratedTouchScrolling()) {
768         RenderBox* renderBox = toRenderBox(&compAncestor->renderer());
769         LayoutRect paddingBox(renderBox->borderLeft(), renderBox->borderTop(),
770             renderBox->width() - renderBox->borderLeft() - renderBox->borderRight(),
771             renderBox->height() - renderBox->borderTop() - renderBox->borderBottom());
772
773         LayoutSize scrollOffset = compAncestor->scrolledContentOffset();
774         graphicsLayerParentLocation = paddingBox.location() - scrollOffset;
775     }
776 #endif
777
778     if (compAncestor && compAncestor->needsCompositedScrolling()) {
779         RenderBox& renderBox = toRenderBox(compAncestor->renderer());
780         LayoutSize scrollOffset = compAncestor->scrolledContentOffset();
781         LayoutPoint scrollOrigin(renderBox.borderLeft(), renderBox.borderTop());
782         graphicsLayerParentLocation = scrollOrigin - scrollOffset;
783     }
784     
785     if (compAncestor && m_ancestorClippingLayer) {
786         // Call calculateRects to get the backgroundRect which is what is used to clip the contents of this
787         // layer. Note that we call it with temporaryClipRects = true because normally when computing clip rects
788         // for a compositing layer, rootLayer is the layer itself.
789         RenderLayer::ClipRectsContext clipRectsContext(compAncestor, 0, TemporaryClipRects, IgnoreOverlayScrollbarSize, IgnoreOverflowClip);
790         LayoutRect parentClipRect = m_owningLayer.backgroundClipRect(clipRectsContext).rect(); // FIXME: Incorrect for CSS regions.
791         ASSERT(parentClipRect != LayoutRect::infiniteRect());
792         m_ancestorClippingLayer->setPosition(FloatPoint(parentClipRect.location() - graphicsLayerParentLocation));
793         m_ancestorClippingLayer->setSize(parentClipRect.size());
794
795         // backgroundRect is relative to compAncestor, so subtract deltaX/deltaY to get back to local coords.
796         m_ancestorClippingLayer->setOffsetFromRenderer(parentClipRect.location() - offsetFromParent);
797
798         // The primary layer is then parented in, and positioned relative to this clipping layer.
799         graphicsLayerParentLocation = parentClipRect.location();
800     }
801
802     LayoutSize contentsSize = enclosingRelativeCompositingBounds.size();
803     
804     if (m_contentsContainmentLayer) {
805         m_contentsContainmentLayer->setPreserves3D(preserves3D);
806         m_contentsContainmentLayer->setPosition(FloatPoint(enclosingRelativeCompositingBounds.location() - graphicsLayerParentLocation));
807         // Use the same size as m_graphicsLayer so transforms behave correctly.
808         m_contentsContainmentLayer->setSize(contentsSize);
809         graphicsLayerParentLocation = enclosingRelativeCompositingBounds.location();
810     }
811
812     m_graphicsLayer->setPosition(FloatPoint(enclosingRelativeCompositingBounds.location() - graphicsLayerParentLocation));
813     m_graphicsLayer->setSize(contentsSize);
814     if (devicePixelOffsetFromRenderer != m_graphicsLayer->offsetFromRenderer()) {
815         m_graphicsLayer->setOffsetFromRenderer(devicePixelOffsetFromRenderer);
816         positionOverflowControlsLayers();
817     }
818
819     if (!m_isMainFrameRenderViewLayer) {
820         // For non-root layers, background is always painted by the primary graphics layer.
821         ASSERT(!m_backgroundLayer);
822         bool hadSubpixelRounding = !m_devicePixelFractionFromRenderer.isZero();
823         m_graphicsLayer->setContentsOpaque(!hadSubpixelRounding && m_owningLayer.backgroundIsKnownToBeOpaqueInRect(localCompositingBounds));
824     }
825
826     // If we have a layer that clips children, position it.
827     LayoutRect clippingBox;
828     if (GraphicsLayer* clipLayer = clippingLayer()) {
829         clippingBox = clipBox(toRenderBox(renderer()));
830         clipLayer->setPosition(FloatPoint(clippingBox.location() - localCompositingBounds.location()));
831         clipLayer->setSize(clippingBox.size());
832         clipLayer->setOffsetFromRenderer(toFloatSize(clippingBox.location()));
833     }
834     
835     if (m_maskLayer) {
836         m_maskLayer->setSize(m_graphicsLayer->size());
837         m_maskLayer->setPosition(FloatPoint());
838         m_maskLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
839     }
840     
841     if (m_owningLayer.hasTransform()) {
842         const LayoutRect borderBox = toRenderBox(renderer()).pixelSnappedBorderBoxRect();
843
844         // Get layout bounds in the coords of compAncestor to match relativeCompositingBounds.
845         LayoutRect layerBounds(offsetFromParent, borderBox.size());
846
847         // Update properties that depend on layer dimensions
848         FloatPoint3D transformOrigin = computeTransformOrigin(borderBox);
849         // Compute the anchor point, which is in the center of the renderer box unless transform-origin is set.
850         FloatPoint3D anchor(enclosingRelativeCompositingBounds.width() != 0.0f ? ((layerBounds.x() - enclosingRelativeCompositingBounds.x()) + transformOrigin.x())
851             / enclosingRelativeCompositingBounds.width() : 0.5f, enclosingRelativeCompositingBounds.height() != 0.0f ? ((layerBounds.y() - enclosingRelativeCompositingBounds.y())
852             + transformOrigin.y()) / enclosingRelativeCompositingBounds.height() : 0.5f, transformOrigin.z());
853         if (m_contentsContainmentLayer)
854             m_contentsContainmentLayer->setAnchorPoint(anchor);
855         else
856             m_graphicsLayer->setAnchorPoint(anchor);
857
858         const RenderStyle& style = renderer().style();
859         GraphicsLayer* clipLayer = clippingLayer();
860         if (style.hasPerspective()) {
861             TransformationMatrix t = owningLayer().perspectiveTransform();
862             
863             if (clipLayer) {
864                 clipLayer->setChildrenTransform(t);
865                 m_graphicsLayer->setChildrenTransform(TransformationMatrix());
866             }
867             else
868                 m_graphicsLayer->setChildrenTransform(t);
869         } else {
870             if (clipLayer)
871                 clipLayer->setChildrenTransform(TransformationMatrix());
872             else
873                 m_graphicsLayer->setChildrenTransform(TransformationMatrix());
874         }
875     } else {
876         m_graphicsLayer->setAnchorPoint(FloatPoint3D(0.5f, 0.5f, 0));
877         if (m_contentsContainmentLayer)
878             m_contentsContainmentLayer->setAnchorPoint(FloatPoint3D(0.5f, 0.5f, 0));
879     }
880
881     if (m_foregroundLayer) {
882         FloatPoint foregroundPosition;
883         FloatSize foregroundSize = contentsSize;
884         FloatSize foregroundOffset = m_graphicsLayer->offsetFromRenderer();
885         if (hasClippingLayer()) {
886             // If we have a clipping layer (which clips descendants), then the foreground layer is a child of it,
887             // so that it gets correctly sorted with children. In that case, position relative to the clipping layer.
888             foregroundSize = FloatSize(clippingBox.size());
889             foregroundOffset = toFloatSize(clippingBox.location());
890         }
891
892         m_foregroundLayer->setPosition(foregroundPosition);
893         m_foregroundLayer->setSize(foregroundSize);
894         m_foregroundLayer->setOffsetFromRenderer(foregroundOffset);
895     }
896
897     if (m_backgroundLayer) {
898         FloatPoint backgroundPosition;
899         FloatSize backgroundSize = contentsSize;
900         if (backgroundLayerPaintsFixedRootBackground()) {
901             const FrameView& frameView = renderer().view().frameView();
902             backgroundPosition = toLayoutPoint(frameView.scrollOffsetForFixedPosition());
903             backgroundSize = frameView.visibleContentRect().size();
904         }
905         m_backgroundLayer->setPosition(backgroundPosition);
906         m_backgroundLayer->setSize(backgroundSize);
907         m_backgroundLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
908     }
909
910     if (m_owningLayer.reflectionLayer() && m_owningLayer.reflectionLayer()->isComposited()) {
911         RenderLayerBacking* reflectionBacking = m_owningLayer.reflectionLayer()->backing();
912         reflectionBacking->updateGraphicsLayerGeometry();
913         
914         // The reflection layer has the bounds of m_owningLayer.reflectionLayer(),
915         // but the reflected layer is the bounds of this layer, so we need to position it appropriately.
916         FloatRect layerBounds = compositedBounds();
917         FloatRect reflectionLayerBounds = reflectionBacking->compositedBounds();
918         reflectionBacking->graphicsLayer()->setReplicatedLayerPosition(FloatPoint(layerBounds.location() - reflectionLayerBounds.location()));
919     }
920
921     if (m_scrollingLayer) {
922         ASSERT(m_scrollingContentsLayer);
923         RenderBox& renderBox = toRenderBox(renderer());
924         LayoutRect paddingBox(renderBox.borderLeft(), renderBox.borderTop(), renderBox.width() - renderBox.borderLeft() - renderBox.borderRight(), renderBox.height() - renderBox.borderTop() - renderBox.borderBottom());
925         LayoutSize scrollOffset = m_owningLayer.scrollOffset();
926
927         m_scrollingLayer->setPosition(FloatPoint(paddingBox.location() - localCompositingBounds.location()));
928
929         m_scrollingLayer->setSize(paddingBox.size());
930 #if PLATFORM(IOS)
931         FloatSize oldScrollingLayerOffset = m_scrollingLayer->offsetFromRenderer();
932         m_scrollingLayer->setOffsetFromRenderer(FloatPoint() - paddingBox.location());
933         bool paddingBoxOffsetChanged = oldScrollingLayerOffset != m_scrollingLayer->offsetFromRenderer();
934
935         if (m_owningLayer.isInUserScroll()) {
936             // If scrolling is happening externally, we don't want to touch the layer bounds origin here because that will cause
937             // jitter. Set a flag to ensure that we sync up later.
938             m_owningLayer.setRequiresScrollBoundsOriginUpdate(true);
939         } else {
940             // Note that we implement the contents offset via the bounds origin on this layer, rather than a position on the sublayer.
941             m_scrollingLayer->setBoundsOrigin(FloatPoint(scrollOffset.width(), scrollOffset.height()));
942             m_owningLayer.setRequiresScrollBoundsOriginUpdate(false);
943         }
944         
945         IntSize scrollSize(m_owningLayer.scrollWidth(), m_owningLayer.scrollHeight());
946
947         m_scrollingContentsLayer->setPosition(FloatPoint());
948         
949         if (scrollSize != m_scrollingContentsLayer->size() || paddingBoxOffsetChanged)
950             m_scrollingContentsLayer->setNeedsDisplay();
951
952         m_scrollingContentsLayer->setSize(scrollSize);
953         // Scrolling the content layer does not need to trigger a repaint. The offset will be compensated away during painting.
954         // FIXME: The paint offset and the scroll offset should really be separate concepts.
955         m_scrollingContentsLayer->setOffsetFromRenderer(paddingBox.location() - IntPoint() - scrollOffset, GraphicsLayer::DontSetNeedsDisplay);
956 #else
957         m_scrollingContentsLayer->setPosition(FloatPoint(-scrollOffset.width(), -scrollOffset.height()));
958
959         FloatSize oldScrollingLayerOffset = m_scrollingLayer->offsetFromRenderer();
960         m_scrollingLayer->setOffsetFromRenderer(-toFloatSize(paddingBox.location()));
961
962         bool paddingBoxOffsetChanged = oldScrollingLayerOffset != m_scrollingLayer->offsetFromRenderer();
963
964         IntSize scrollSize(m_owningLayer.scrollWidth(), m_owningLayer.scrollHeight());
965         if (scrollSize != m_scrollingContentsLayer->size() || paddingBoxOffsetChanged)
966             m_scrollingContentsLayer->setNeedsDisplay();
967
968         LayoutSize scrollingContentsOffset = toLayoutSize(paddingBox.location() - scrollOffset);
969         if (scrollingContentsOffset != m_scrollingContentsLayer->offsetFromRenderer() || scrollSize != m_scrollingContentsLayer->size())
970             compositor().scrollingLayerDidChange(m_owningLayer);
971
972         m_scrollingContentsLayer->setSize(scrollSize);
973         // FIXME: The paint offset and the scroll offset should really be separate concepts.
974         m_scrollingContentsLayer->setOffsetFromRenderer(scrollingContentsOffset, GraphicsLayer::DontSetNeedsDisplay);
975 #endif
976
977         if (m_foregroundLayer) {
978             m_foregroundLayer->setSize(m_scrollingContentsLayer->size());
979             m_foregroundLayer->setOffsetFromRenderer(m_scrollingContentsLayer->offsetFromRenderer());
980         }
981     }
982
983     // If this layer was created just for clipping or to apply perspective, it doesn't need its own backing store.
984     setRequiresOwnBackingStore(compositor().requiresOwnBackingStore(m_owningLayer, compAncestor, enclosingRelativeCompositingBounds, ancestorCompositingBounds));
985
986     bool didUpdateContentsRect = false;
987     updateDirectlyCompositedContents(isSimpleContainer, didUpdateContentsRect);
988     if (!didUpdateContentsRect && m_graphicsLayer->hasContentsLayer())
989         resetContentsRect();
990
991     updateDrawsContent(isSimpleContainer);
992     updateAfterWidgetResize();
993
994     compositor().updateScrollCoordinatedStatus(m_owningLayer);
995 }
996
997 void RenderLayerBacking::adjustAncestorCompositingBoundsForFlowThread(LayoutRect& ancestorCompositingBounds, const RenderLayer* compositingAncestor) const
998 {
999     if (!m_owningLayer.isInsideFlowThread())
1000         return;
1001
1002     RenderLayer* flowThreadLayer = m_owningLayer.isInsideOutOfFlowThread() ? m_owningLayer.stackingContainer() : m_owningLayer.enclosingFlowThreadAncestor();
1003     if (flowThreadLayer && flowThreadLayer->isRenderFlowThread()) {
1004         if (m_owningLayer.isFlowThreadCollectingGraphicsLayersUnderRegions()) {
1005             // The RenderNamedFlowThread is not composited, as we need it to paint the 
1006             // background layer of the regions. We need to compensate for that by manually
1007             // subtracting the position of the flow-thread.
1008             IntPoint flowPosition;
1009             flowThreadLayer->convertToPixelSnappedLayerCoords(compositingAncestor, flowPosition);
1010             ancestorCompositingBounds.moveBy(flowPosition);
1011         }
1012
1013         // Move the ancestor position at the top of the region where the composited layer is going to display.
1014         RenderFlowThread& flowThread = toRenderFlowThread(flowThreadLayer->renderer());
1015         RenderNamedFlowFragment* parentRegion = flowThread.cachedRegionForCompositedLayer(m_owningLayer);
1016         if (!parentRegion)
1017             return;
1018
1019         IntPoint flowDelta;
1020         m_owningLayer.convertToPixelSnappedLayerCoords(flowThreadLayer, flowDelta);
1021         parentRegion->adjustRegionBoundsFromFlowThreadPortionRect(flowDelta, ancestorCompositingBounds);
1022         RenderBoxModelObject& layerOwner = toRenderBoxModelObject(parentRegion->layerOwner());
1023         RenderLayerBacking* layerOwnerBacking = layerOwner.layer()->backing();
1024         if (!layerOwnerBacking)
1025             return;
1026
1027         // Make sure that the region propagates its borders, paddings, outlines or box-shadows to layers inside it.
1028         // Note that the composited bounds of the RenderRegion are already calculated because
1029         // RenderLayerCompositor::rebuildCompositingLayerTree will only iterate on the content of the region after the
1030         // region itself is computed.
1031         ancestorCompositingBounds.moveBy(roundedIntPoint(layerOwnerBacking->compositedBounds().location()));
1032         ancestorCompositingBounds.move(-layerOwner.borderAndPaddingStart(), -layerOwner.borderAndPaddingBefore());
1033
1034         // If there's a clipping GraphicsLayer on the hierarchy (region graphics layer -> clipping graphics layer ->
1035         // composited content graphics layer), substract the offset of the clipping layer, since it's its parent
1036         // that positions us (the graphics layer of the region).
1037         if (layerOwnerBacking->clippingLayer())
1038             ancestorCompositingBounds.moveBy(roundedIntPoint(layerOwnerBacking->clippingLayer()->position()));
1039     }
1040 }
1041
1042 void RenderLayerBacking::updateDirectlyCompositedContents(bool isSimpleContainer, bool& didUpdateContentsRect)
1043 {
1044     if (!m_owningLayer.hasVisibleContent())
1045         return;
1046
1047     // The order of operations here matters, since the last valid type of contents needs
1048     // to also update the contentsRect.
1049     updateDirectlyCompositedBackgroundColor(isSimpleContainer, didUpdateContentsRect);
1050     updateDirectlyCompositedBackgroundImage(isSimpleContainer, didUpdateContentsRect);
1051 }
1052
1053 void RenderLayerBacking::updateInternalHierarchy()
1054 {
1055     // m_foregroundLayer has to be inserted in the correct order with child layers,
1056     // so it's not inserted here.
1057     if (m_ancestorClippingLayer)
1058         m_ancestorClippingLayer->removeAllChildren();
1059     
1060     if (m_contentsContainmentLayer) {
1061         m_contentsContainmentLayer->removeAllChildren();
1062         if (m_ancestorClippingLayer)
1063             m_ancestorClippingLayer->addChild(m_contentsContainmentLayer.get());
1064     }
1065     
1066     if (m_backgroundLayer)
1067         m_contentsContainmentLayer->addChild(m_backgroundLayer.get());
1068
1069     if (m_contentsContainmentLayer)
1070         m_contentsContainmentLayer->addChild(m_graphicsLayer.get());
1071     else if (m_ancestorClippingLayer)
1072         m_ancestorClippingLayer->addChild(m_graphicsLayer.get());
1073
1074     if (m_childContainmentLayer) {
1075         m_childContainmentLayer->removeFromParent();
1076         m_graphicsLayer->addChild(m_childContainmentLayer.get());
1077     }
1078
1079     if (m_scrollingLayer) {
1080         GraphicsLayer* superlayer = m_childContainmentLayer ? m_childContainmentLayer.get() : m_graphicsLayer.get();
1081         m_scrollingLayer->removeFromParent();
1082         superlayer->addChild(m_scrollingLayer.get());
1083     }
1084
1085     // The clip for child layers does not include space for overflow controls, so they exist as
1086     // siblings of the clipping layer if we have one. Normal children of this layer are set as
1087     // children of the clipping layer.
1088     if (m_layerForHorizontalScrollbar) {
1089         m_layerForHorizontalScrollbar->removeFromParent();
1090         m_graphicsLayer->addChild(m_layerForHorizontalScrollbar.get());
1091     }
1092     if (m_layerForVerticalScrollbar) {
1093         m_layerForVerticalScrollbar->removeFromParent();
1094         m_graphicsLayer->addChild(m_layerForVerticalScrollbar.get());
1095     }
1096     if (m_layerForScrollCorner) {
1097         m_layerForScrollCorner->removeFromParent();
1098         m_graphicsLayer->addChild(m_layerForScrollCorner.get());
1099     }
1100 }
1101
1102 void RenderLayerBacking::resetContentsRect()
1103 {
1104     m_graphicsLayer->setContentsRect(pixelSnappedIntRect(contentsBox()));
1105     
1106     LayoutRect contentsClippingRect;
1107     if (renderer().isBox())
1108         contentsClippingRect = toRenderBox(renderer()).contentBoxRect();
1109
1110     contentsClippingRect.move(contentOffsetInCompostingLayer());
1111     m_graphicsLayer->setContentsClippingRect(pixelSnappedIntRect(contentsClippingRect));
1112
1113     m_graphicsLayer->setContentsTileSize(IntSize());
1114     m_graphicsLayer->setContentsTilePhase(IntPoint());
1115 }
1116
1117 void RenderLayerBacking::updateDrawsContent()
1118 {
1119     updateDrawsContent(isSimpleContainerCompositingLayer());
1120 }
1121
1122 void RenderLayerBacking::updateDrawsContent(bool isSimpleContainer)
1123 {
1124     if (m_scrollingLayer) {
1125         // We don't have to consider overflow controls, because we know that the scrollbars are drawn elsewhere.
1126         // m_graphicsLayer only needs backing store if the non-scrolling parts (background, outlines, borders, shadows etc) need to paint.
1127         // m_scrollingLayer never has backing store.
1128         // m_scrollingContentsLayer only needs backing store if the scrolled contents need to paint.
1129         bool hasNonScrollingPaintedContent = m_owningLayer.hasVisibleContent() && m_owningLayer.hasBoxDecorationsOrBackground();
1130         m_graphicsLayer->setDrawsContent(hasNonScrollingPaintedContent);
1131
1132         bool hasScrollingPaintedContent = m_owningLayer.hasVisibleContent() && (renderer().hasBackground() || paintsChildren());
1133         m_scrollingContentsLayer->setDrawsContent(hasScrollingPaintedContent);
1134         return;
1135     }
1136
1137     bool hasPaintedContent = containsPaintedContent(isSimpleContainer);
1138
1139     // FIXME: we could refine this to only allocate backing for one of these layers if possible.
1140     m_graphicsLayer->setDrawsContent(hasPaintedContent);
1141     if (m_foregroundLayer)
1142         m_foregroundLayer->setDrawsContent(hasPaintedContent);
1143
1144     if (m_backgroundLayer)
1145         m_backgroundLayer->setDrawsContent(hasPaintedContent);
1146 }
1147
1148 // Return true if the layer changed.
1149 bool RenderLayerBacking::updateAncestorClippingLayer(bool needsAncestorClip)
1150 {
1151     bool layersChanged = false;
1152
1153     if (needsAncestorClip) {
1154         if (!m_ancestorClippingLayer) {
1155             m_ancestorClippingLayer = createGraphicsLayer("Ancestor clipping Layer");
1156             m_ancestorClippingLayer->setMasksToBounds(true);
1157             layersChanged = true;
1158         }
1159     } else if (hasAncestorClippingLayer()) {
1160         willDestroyLayer(m_ancestorClippingLayer.get());
1161         m_ancestorClippingLayer->removeFromParent();
1162         m_ancestorClippingLayer = nullptr;
1163         layersChanged = true;
1164     }
1165     
1166     return layersChanged;
1167 }
1168
1169 // Return true if the layer changed.
1170 bool RenderLayerBacking::updateDescendantClippingLayer(bool needsDescendantClip)
1171 {
1172     bool layersChanged = false;
1173
1174     if (needsDescendantClip) {
1175         if (!m_childContainmentLayer && !m_usingTiledCacheLayer) {
1176             m_childContainmentLayer = createGraphicsLayer("Child clipping Layer");
1177             m_childContainmentLayer->setMasksToBounds(true);
1178             layersChanged = true;
1179         }
1180     } else if (hasClippingLayer()) {
1181         willDestroyLayer(m_childContainmentLayer.get());
1182         m_childContainmentLayer->removeFromParent();
1183         m_childContainmentLayer = nullptr;
1184         layersChanged = true;
1185     }
1186     
1187     return layersChanged;
1188 }
1189
1190 void RenderLayerBacking::setBackgroundLayerPaintsFixedRootBackground(bool backgroundLayerPaintsFixedRootBackground)
1191 {
1192     m_backgroundLayerPaintsFixedRootBackground = backgroundLayerPaintsFixedRootBackground;
1193 }
1194
1195 bool RenderLayerBacking::requiresHorizontalScrollbarLayer() const
1196 {
1197     if (!m_owningLayer.hasOverlayScrollbars() && !m_owningLayer.needsCompositedScrolling())
1198         return false;
1199     return m_owningLayer.horizontalScrollbar();
1200 }
1201
1202 bool RenderLayerBacking::requiresVerticalScrollbarLayer() const
1203 {
1204     if (!m_owningLayer.hasOverlayScrollbars() && !m_owningLayer.needsCompositedScrolling())
1205         return false;
1206     return m_owningLayer.verticalScrollbar();
1207 }
1208
1209 bool RenderLayerBacking::requiresScrollCornerLayer() const
1210 {
1211     if (!m_owningLayer.hasOverlayScrollbars() && !m_owningLayer.needsCompositedScrolling())
1212         return false;
1213     return !m_owningLayer.scrollCornerAndResizerRect().isEmpty();
1214 }
1215
1216 bool RenderLayerBacking::updateOverflowControlsLayers(bool needsHorizontalScrollbarLayer, bool needsVerticalScrollbarLayer, bool needsScrollCornerLayer)
1217 {
1218     bool horizontalScrollbarLayerChanged = false;
1219     if (needsHorizontalScrollbarLayer) {
1220         if (!m_layerForHorizontalScrollbar) {
1221             m_layerForHorizontalScrollbar = createGraphicsLayer("horizontal scrollbar");
1222             horizontalScrollbarLayerChanged = true;
1223         }
1224     } else if (m_layerForHorizontalScrollbar) {
1225         willDestroyLayer(m_layerForHorizontalScrollbar.get());
1226         m_layerForHorizontalScrollbar = nullptr;
1227         horizontalScrollbarLayerChanged = true;
1228     }
1229
1230     bool verticalScrollbarLayerChanged = false;
1231     if (needsVerticalScrollbarLayer) {
1232         if (!m_layerForVerticalScrollbar) {
1233             m_layerForVerticalScrollbar = createGraphicsLayer("vertical scrollbar");
1234             verticalScrollbarLayerChanged = true;
1235         }
1236     } else if (m_layerForVerticalScrollbar) {
1237         willDestroyLayer(m_layerForVerticalScrollbar.get());
1238         m_layerForVerticalScrollbar = nullptr;
1239         verticalScrollbarLayerChanged = true;
1240     }
1241
1242     bool scrollCornerLayerChanged = false;
1243     if (needsScrollCornerLayer) {
1244         if (!m_layerForScrollCorner) {
1245             m_layerForScrollCorner = createGraphicsLayer("scroll corner");
1246             scrollCornerLayerChanged = true;
1247         }
1248     } else if (m_layerForScrollCorner) {
1249         willDestroyLayer(m_layerForScrollCorner.get());
1250         m_layerForScrollCorner = nullptr;
1251         scrollCornerLayerChanged = true;
1252     }
1253
1254     if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer)) {
1255         if (horizontalScrollbarLayerChanged)
1256             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_owningLayer, HorizontalScrollbar);
1257         if (verticalScrollbarLayerChanged)
1258             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_owningLayer, VerticalScrollbar);
1259     }
1260
1261     return horizontalScrollbarLayerChanged || verticalScrollbarLayerChanged || scrollCornerLayerChanged;
1262 }
1263
1264 void RenderLayerBacking::positionOverflowControlsLayers()
1265 {
1266     if (!m_owningLayer.hasScrollbars())
1267         return;
1268
1269     const IntRect borderBox = toRenderBox(renderer()).pixelSnappedBorderBoxRect();
1270
1271     FloatSize offsetFromRenderer = m_graphicsLayer->offsetFromRenderer();
1272     if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
1273         IntRect hBarRect = m_owningLayer.rectForHorizontalScrollbar(borderBox);
1274         layer->setPosition(hBarRect.location() - offsetFromRenderer);
1275         layer->setSize(hBarRect.size());
1276         if (layer->hasContentsLayer()) {
1277             IntRect barRect = IntRect(IntPoint(), hBarRect.size());
1278             layer->setContentsRect(barRect);
1279             layer->setContentsClippingRect(barRect);
1280         }
1281         layer->setDrawsContent(m_owningLayer.horizontalScrollbar() && !layer->hasContentsLayer());
1282     }
1283     
1284     if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
1285         IntRect vBarRect = m_owningLayer.rectForVerticalScrollbar(borderBox);
1286         layer->setPosition(vBarRect.location() - offsetFromRenderer);
1287         layer->setSize(vBarRect.size());
1288         if (layer->hasContentsLayer()) {
1289             IntRect barRect = IntRect(IntPoint(), vBarRect.size());
1290             layer->setContentsRect(barRect);
1291             layer->setContentsClippingRect(barRect);
1292         }
1293         layer->setDrawsContent(m_owningLayer.verticalScrollbar() && !layer->hasContentsLayer());
1294     }
1295
1296     if (GraphicsLayer* layer = layerForScrollCorner()) {
1297         const LayoutRect& scrollCornerAndResizer = m_owningLayer.scrollCornerAndResizerRect();
1298         layer->setPosition(scrollCornerAndResizer.location() - offsetFromRenderer);
1299         layer->setSize(scrollCornerAndResizer.size());
1300         layer->setDrawsContent(!scrollCornerAndResizer.isEmpty());
1301     }
1302 }
1303
1304 bool RenderLayerBacking::hasUnpositionedOverflowControlsLayers() const
1305 {
1306     if (GraphicsLayer* layer = layerForHorizontalScrollbar())
1307         if (!layer->drawsContent())
1308             return true;
1309
1310     if (GraphicsLayer* layer = layerForVerticalScrollbar())
1311         if (!layer->drawsContent())
1312             return true;
1313
1314     if (GraphicsLayer* layer = layerForScrollCorner())
1315         if (!layer->drawsContent())
1316             return true;
1317
1318     return false;
1319 }
1320
1321 bool RenderLayerBacking::updateForegroundLayer(bool needsForegroundLayer)
1322 {
1323     bool layerChanged = false;
1324     if (needsForegroundLayer) {
1325         if (!m_foregroundLayer) {
1326             String layerName;
1327 #ifndef NDEBUG
1328             layerName = m_owningLayer.name() + " (foreground)";
1329 #endif
1330             m_foregroundLayer = createGraphicsLayer(layerName);
1331             m_foregroundLayer->setDrawsContent(true);
1332             m_foregroundLayer->setPaintingPhase(GraphicsLayerPaintForeground);
1333             layerChanged = true;
1334         }
1335     } else if (m_foregroundLayer) {
1336         willDestroyLayer(m_foregroundLayer.get());
1337         m_foregroundLayer->removeFromParent();
1338         m_foregroundLayer = nullptr;
1339         layerChanged = true;
1340     }
1341
1342     if (layerChanged) {
1343         m_graphicsLayer->setNeedsDisplay();
1344         m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
1345     }
1346
1347     return layerChanged;
1348 }
1349
1350 bool RenderLayerBacking::updateBackgroundLayer(bool needsBackgroundLayer)
1351 {
1352     bool layerChanged = false;
1353     if (needsBackgroundLayer) {
1354         if (!m_backgroundLayer) {
1355             String layerName;
1356 #ifndef NDEBUG
1357             layerName = m_owningLayer.name() + " (background)";
1358 #endif
1359             m_backgroundLayer = createGraphicsLayer(layerName);
1360             m_backgroundLayer->setDrawsContent(true);
1361             m_backgroundLayer->setAnchorPoint(FloatPoint3D());
1362             m_backgroundLayer->setPaintingPhase(GraphicsLayerPaintBackground);
1363             layerChanged = true;
1364         }
1365         
1366         if (!m_contentsContainmentLayer) {
1367             String layerName;
1368 #ifndef NDEBUG
1369             layerName = m_owningLayer.name() + " (contents containment)";
1370 #endif
1371             m_contentsContainmentLayer = createGraphicsLayer(layerName);
1372             m_contentsContainmentLayer->setAppliesPageScale(true);
1373             m_graphicsLayer->setAppliesPageScale(false);
1374             layerChanged = true;
1375         }
1376     } else {
1377         if (m_backgroundLayer) {
1378             willDestroyLayer(m_backgroundLayer.get());
1379             m_backgroundLayer->removeFromParent();
1380             m_backgroundLayer = nullptr;
1381             layerChanged = true;
1382         }
1383         if (m_contentsContainmentLayer) {
1384             willDestroyLayer(m_contentsContainmentLayer.get());
1385             m_contentsContainmentLayer->removeFromParent();
1386             m_contentsContainmentLayer = nullptr;
1387             layerChanged = true;
1388             m_graphicsLayer->setAppliesPageScale(true);
1389         }
1390     }
1391     
1392     if (layerChanged) {
1393         m_graphicsLayer->setNeedsDisplay();
1394         // This assumes that the background layer is only used for fixed backgrounds, which is currently a correct assumption.
1395         compositor().fixedRootBackgroundLayerChanged();
1396     }
1397     
1398     return layerChanged;
1399 }
1400
1401 bool RenderLayerBacking::updateMaskLayer(bool needsMaskLayer)
1402 {
1403     bool layerChanged = false;
1404     if (needsMaskLayer) {
1405         if (!m_maskLayer) {
1406             m_maskLayer = createGraphicsLayer("Mask");
1407             m_maskLayer->setDrawsContent(true);
1408             m_maskLayer->setPaintingPhase(GraphicsLayerPaintMask);
1409             layerChanged = true;
1410         }
1411     } else if (m_maskLayer) {
1412         willDestroyLayer(m_maskLayer.get());
1413         m_maskLayer = nullptr;
1414         layerChanged = true;
1415     }
1416
1417     if (layerChanged)
1418         m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
1419
1420     return layerChanged;
1421 }
1422
1423 bool RenderLayerBacking::updateScrollingLayers(bool needsScrollingLayers)
1424 {
1425     if (needsScrollingLayers == !!m_scrollingLayer)
1426         return false;
1427
1428     if (!m_scrollingLayer) {
1429         // Outer layer which corresponds with the scroll view.
1430         m_scrollingLayer = createGraphicsLayer("Scrolling container");
1431         m_scrollingLayer->setDrawsContent(false);
1432         m_scrollingLayer->setMasksToBounds(true);
1433
1434         // Inner layer which renders the content that scrolls.
1435         m_scrollingContentsLayer = createGraphicsLayer("Scrolled Contents");
1436         m_scrollingContentsLayer->setDrawsContent(true);
1437         GraphicsLayerPaintingPhase paintPhase = GraphicsLayerPaintOverflowContents | GraphicsLayerPaintCompositedScroll;
1438         if (!m_foregroundLayer)
1439             paintPhase |= GraphicsLayerPaintForeground;
1440         m_scrollingContentsLayer->setPaintingPhase(paintPhase);
1441         m_scrollingLayer->addChild(m_scrollingContentsLayer.get());
1442     } else {
1443         compositor().willRemoveScrollingLayer(m_owningLayer);
1444
1445         willDestroyLayer(m_scrollingLayer.get());
1446         willDestroyLayer(m_scrollingContentsLayer.get());
1447         m_scrollingLayer = nullptr;
1448         m_scrollingContentsLayer = nullptr;
1449     }
1450
1451     updateInternalHierarchy();
1452     m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
1453     m_graphicsLayer->setNeedsDisplay(); // Because painting phases changed.
1454
1455     if (m_scrollingLayer)
1456         compositor().didAddScrollingLayer(m_owningLayer);
1457     
1458     return true;
1459 }
1460
1461 void RenderLayerBacking::detachFromScrollingCoordinator()
1462 {
1463     if (!m_scrollingNodeID && !m_viewportConstrainedNodeID)
1464         return;
1465
1466     ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer);
1467     if (!scrollingCoordinator)
1468         return;
1469
1470     if (m_scrollingNodeID)
1471         scrollingCoordinator->detachFromStateTree(m_scrollingNodeID);
1472
1473     if (m_viewportConstrainedNodeID)
1474         scrollingCoordinator->detachFromStateTree(m_viewportConstrainedNodeID);
1475
1476     m_scrollingNodeID = 0;
1477     m_viewportConstrainedNodeID = 0;
1478 }
1479
1480 GraphicsLayerPaintingPhase RenderLayerBacking::paintingPhaseForPrimaryLayer() const
1481 {
1482     unsigned phase = 0;
1483     if (!m_backgroundLayer)
1484         phase |= GraphicsLayerPaintBackground;
1485     if (!m_foregroundLayer)
1486         phase |= GraphicsLayerPaintForeground;
1487     if (!m_maskLayer)
1488         phase |= GraphicsLayerPaintMask;
1489
1490     if (m_scrollingContentsLayer) {
1491         phase &= ~GraphicsLayerPaintForeground;
1492         phase |= GraphicsLayerPaintCompositedScroll;
1493     }
1494
1495     return static_cast<GraphicsLayerPaintingPhase>(phase);
1496 }
1497
1498 float RenderLayerBacking::compositingOpacity(float rendererOpacity) const
1499 {
1500     float finalOpacity = rendererOpacity;
1501     
1502     for (RenderLayer* curr = m_owningLayer.parent(); curr; curr = curr->parent()) {
1503         // We only care about parents that are stacking contexts.
1504         // Recall that opacity creates stacking context.
1505         if (!curr->isStackingContainer())
1506             continue;
1507         
1508         // If we found a compositing layer, we want to compute opacity
1509         // relative to it. So we can break here.
1510         if (curr->isComposited())
1511             break;
1512         
1513         finalOpacity *= curr->renderer().opacity();
1514     }
1515
1516     return finalOpacity;
1517 }
1518
1519 static bool hasBoxDecorations(const RenderStyle* style)
1520 {
1521     return style->hasBorder() || style->hasBorderRadius() || style->hasOutline() || style->hasAppearance() || style->boxShadow() || style->hasFilter();
1522 }
1523
1524 static bool canCreateTiledImage(const RenderStyle*);
1525
1526 static bool hasBoxDecorationsOrBackgroundImage(const RenderStyle* style)
1527 {
1528     if (hasBoxDecorations(style))
1529         return true;
1530
1531     if (!style->hasBackgroundImage())
1532         return false;
1533
1534     return !GraphicsLayer::supportsContentsTiling() || !canCreateTiledImage(style);
1535 }
1536
1537 static bool hasPerspectiveOrPreserves3D(const RenderStyle* style)
1538 {
1539     return style->hasPerspective() || style->preserves3D();
1540 }
1541
1542 Color RenderLayerBacking::rendererBackgroundColor() const
1543 {
1544     const auto& backgroundRenderer = renderer().isRoot() ? renderer().rendererForRootBackground() : renderer();
1545     return backgroundRenderer.style().visitedDependentColor(CSSPropertyBackgroundColor);
1546 }
1547
1548 void RenderLayerBacking::updateDirectlyCompositedBackgroundColor(bool isSimpleContainer, bool& didUpdateContentsRect)
1549 {
1550     if (!isSimpleContainer) {
1551         m_graphicsLayer->setContentsToSolidColor(Color());
1552         return;
1553     }
1554
1555     Color backgroundColor = rendererBackgroundColor();
1556
1557     // An unset (invalid) color will remove the solid color.
1558     m_graphicsLayer->setContentsToSolidColor(backgroundColor);
1559     FloatRect contentsRect = backgroundBoxForPainting();
1560     m_graphicsLayer->setContentsRect(contentsRect);
1561     m_graphicsLayer->setContentsClippingRect(contentsRect);
1562     didUpdateContentsRect = true;
1563 }
1564
1565 bool canCreateTiledImage(const RenderStyle* style)
1566 {
1567     const FillLayer* fillLayer = style->backgroundLayers();
1568     if (fillLayer->next())
1569         return false;
1570
1571     if (!fillLayer->imagesAreLoaded())
1572         return false;
1573
1574     if (fillLayer->attachment() != ScrollBackgroundAttachment)
1575         return false;
1576
1577     Color color = style->visitedDependentColor(CSSPropertyBackgroundColor);
1578
1579     // FIXME: Allow color+image compositing when it makes sense.
1580     // For now bailing out.
1581     if (color.isValid() && color.alpha())
1582         return false;
1583
1584     StyleImage* styleImage = fillLayer->image();
1585
1586     // FIXME: support gradients with isGeneratedImage.
1587     if (!styleImage->isCachedImage())
1588         return false;
1589
1590     Image* image = styleImage->cachedImage()->image();
1591     if (!image->isBitmapImage())
1592         return false;
1593
1594     return true;
1595 }
1596
1597 void RenderLayerBacking::updateDirectlyCompositedBackgroundImage(bool isSimpleContainer, bool& didUpdateContentsRect)
1598 {
1599     if (!GraphicsLayer::supportsContentsTiling())
1600         return;
1601
1602     if (isDirectlyCompositedImage())
1603         return;
1604
1605     const RenderStyle& style = renderer().style();
1606
1607     if (!isSimpleContainer || !style.hasBackgroundImage()) {
1608         m_graphicsLayer->setContentsToImage(0);
1609         return;
1610     }
1611
1612     IntRect destRect = pixelSnappedIntRect(LayoutRect(backgroundBoxForPainting()));
1613     IntPoint phase;
1614     IntSize tileSize;
1615
1616     RefPtr<Image> image = style.backgroundLayers()->image()->cachedImage()->image();
1617     toRenderBox(renderer()).getGeometryForBackgroundImage(&m_owningLayer.renderer(), destRect, phase, tileSize);
1618     m_graphicsLayer->setContentsTileSize(tileSize);
1619     m_graphicsLayer->setContentsTilePhase(phase);
1620     m_graphicsLayer->setContentsRect(destRect);
1621     m_graphicsLayer->setContentsClippingRect(destRect);
1622     m_graphicsLayer->setContentsToImage(image.get());
1623     didUpdateContentsRect = true;
1624 }
1625
1626 void RenderLayerBacking::updateRootLayerConfiguration()
1627 {
1628     if (!m_usingTiledCacheLayer)
1629         return;
1630
1631     Color backgroundColor;
1632     bool viewIsTransparent = compositor().viewHasTransparentBackground(&backgroundColor);
1633
1634     if (m_backgroundLayerPaintsFixedRootBackground && m_backgroundLayer) {
1635         m_backgroundLayer->setBackgroundColor(backgroundColor);
1636         m_backgroundLayer->setContentsOpaque(!viewIsTransparent);
1637
1638         m_graphicsLayer->setBackgroundColor(Color());
1639         m_graphicsLayer->setContentsOpaque(false);
1640     } else {
1641         m_graphicsLayer->setBackgroundColor(backgroundColor);
1642         m_graphicsLayer->setContentsOpaque(!viewIsTransparent);
1643     }
1644 }
1645
1646 static bool supportsDirectBoxDecorationsComposition(const RenderLayerModelObject& renderer)
1647 {
1648     if (!GraphicsLayer::supportsBackgroundColorContent())
1649         return false;
1650
1651     if (renderer.hasClip())
1652         return false;
1653
1654     if (hasBoxDecorationsOrBackgroundImage(&renderer.style()))
1655         return false;
1656
1657     // FIXME: We can't create a directly composited background if this
1658     // layer will have children that intersect with the background layer.
1659     // A better solution might be to introduce a flattening layer if
1660     // we do direct box decoration composition.
1661     // https://bugs.webkit.org/show_bug.cgi?id=119461
1662     if (hasPerspectiveOrPreserves3D(&renderer.style()))
1663         return false;
1664
1665     // FIXME: we should be able to allow backgroundComposite; However since this is not a common use case it has been deferred for now.
1666     if (renderer.style().backgroundComposite() != CompositeSourceOver)
1667         return false;
1668
1669     if (renderer.style().backgroundClip() == TextFillBox)
1670         return false;
1671
1672     return true;
1673 }
1674
1675 bool RenderLayerBacking::paintsBoxDecorations() const
1676 {
1677     if (!m_owningLayer.hasVisibleBoxDecorations())
1678         return false;
1679
1680     if (!supportsDirectBoxDecorationsComposition(renderer()))
1681         return true;
1682
1683     return false;
1684 }
1685
1686 bool RenderLayerBacking::paintsChildren() const
1687 {
1688     if (m_owningLayer.hasVisibleContent() && m_owningLayer.hasNonEmptyChildRenderers())
1689         return true;
1690
1691     if (hasVisibleNonCompositingDescendantLayers())
1692         return true;
1693
1694     return false;
1695 }
1696
1697 static bool isRestartedPlugin(RenderObject* renderer)
1698 {
1699     if (!renderer->isEmbeddedObject())
1700         return false;
1701
1702     Element* element = toElement(renderer->node());
1703     if (!element || !element->isPluginElement())
1704         return false;
1705
1706     return toHTMLPlugInElement(element)->isRestartedPlugin();
1707 }
1708
1709 static bool isCompositedPlugin(RenderObject* renderer)
1710 {
1711     return renderer->isEmbeddedObject() && toRenderEmbeddedObject(renderer)->allowsAcceleratedCompositing();
1712 }
1713
1714 // A "simple container layer" is a RenderLayer which has no visible content to render.
1715 // It may have no children, or all its children may be themselves composited.
1716 // This is a useful optimization, because it allows us to avoid allocating backing store.
1717 bool RenderLayerBacking::isSimpleContainerCompositingLayer() const
1718 {
1719     if (renderer().hasMask()) // masks require special treatment
1720         return false;
1721
1722     if (renderer().isReplaced() && (!isCompositedPlugin(&renderer()) || isRestartedPlugin(&renderer())))
1723         return false;
1724
1725     if (paintsBoxDecorations() || paintsChildren())
1726         return false;
1727
1728     if (renderer().isRenderNamedFlowFragmentContainer())
1729         return false;
1730
1731     if (renderer().isRenderView()) {
1732         // Look to see if the root object has a non-simple background
1733         RenderObject* rootObject = renderer().document().documentElement() ? renderer().document().documentElement()->renderer() : 0;
1734         if (!rootObject)
1735             return false;
1736         
1737         RenderStyle* style = &rootObject->style();
1738         
1739         // Reject anything that has a border, a border-radius or outline,
1740         // or is not a simple background (no background, or solid color).
1741         if (hasBoxDecorationsOrBackgroundImage(style))
1742             return false;
1743         
1744         // Now look at the body's renderer.
1745         HTMLElement* body = renderer().document().body();
1746         RenderObject* bodyObject = (body && body->hasTagName(bodyTag)) ? body->renderer() : 0;
1747         if (!bodyObject)
1748             return false;
1749         
1750         style = &bodyObject->style();
1751         
1752         if (hasBoxDecorationsOrBackgroundImage(style))
1753             return false;
1754     }
1755
1756     return true;
1757 }
1758
1759 static bool hasVisibleNonCompositingDescendant(RenderLayer& parent)
1760 {
1761     // FIXME: We shouldn't be called with a stale z-order lists. See bug 85512.
1762     parent.updateLayerListsIfNeeded();
1763
1764 #if !ASSERT_DISABLED
1765     LayerListMutationDetector mutationChecker(&parent);
1766 #endif
1767
1768     if (Vector<RenderLayer*>* normalFlowList = parent.normalFlowList()) {
1769         size_t listSize = normalFlowList->size();
1770         for (size_t i = 0; i < listSize; ++i) {
1771             RenderLayer* curLayer = normalFlowList->at(i);
1772             if (!curLayer->isComposited()
1773                 && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(*curLayer)))
1774                 return true;
1775         }
1776     }
1777
1778     if (parent.isStackingContainer()) {
1779         if (!parent.hasVisibleDescendant())
1780             return false;
1781
1782         // Use the m_hasCompositingDescendant bit to optimize?
1783         if (Vector<RenderLayer*>* negZOrderList = parent.negZOrderList()) {
1784             size_t listSize = negZOrderList->size();
1785             for (size_t i = 0; i < listSize; ++i) {
1786                 RenderLayer* curLayer = negZOrderList->at(i);
1787                 if (!curLayer->isComposited()
1788                     && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(*curLayer)))
1789                     return true;
1790             }
1791         }
1792
1793         if (Vector<RenderLayer*>* posZOrderList = parent.posZOrderList()) {
1794             size_t listSize = posZOrderList->size();
1795             for (size_t i = 0; i < listSize; ++i) {
1796                 RenderLayer* curLayer = posZOrderList->at(i);
1797                 if (!curLayer->isComposited()
1798                     && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(*curLayer)))
1799                     return true;
1800             }
1801         }
1802     }
1803
1804     return false;
1805 }
1806
1807 // Conservative test for having no rendered children.
1808 bool RenderLayerBacking::hasVisibleNonCompositingDescendantLayers() const
1809 {
1810     return hasVisibleNonCompositingDescendant(m_owningLayer);
1811 }
1812
1813 bool RenderLayerBacking::containsPaintedContent(bool isSimpleContainer) const
1814 {
1815     if (isSimpleContainer || paintsIntoWindow() || paintsIntoCompositedAncestor() || m_artificiallyInflatedBounds || m_owningLayer.isReflection())
1816         return false;
1817
1818     if (isDirectlyCompositedImage())
1819         return false;
1820
1821     // FIXME: we could optimize cases where the image, video or canvas is known to fill the border box entirely,
1822     // and set background color on the layer in that case, instead of allocating backing store and painting.
1823 #if ENABLE(VIDEO)
1824     if (renderer().isVideo() && toRenderVideo(renderer()).shouldDisplayVideo())
1825         return m_owningLayer.hasBoxDecorationsOrBackground();
1826 #endif
1827
1828 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
1829     if (renderer().isCanvas() && canvasCompositingStrategy(renderer()) == CanvasAsLayerContents)
1830         return m_owningLayer.hasBoxDecorationsOrBackground();
1831 #endif
1832
1833     return true;
1834 }
1835
1836 // An image can be directly compositing if it's the sole content of the layer, and has no box decorations
1837 // that require painting. Direct compositing saves backing store.
1838 bool RenderLayerBacking::isDirectlyCompositedImage() const
1839 {
1840     if (!renderer().isRenderImage() || m_owningLayer.hasBoxDecorationsOrBackground() || renderer().hasClip())
1841         return false;
1842
1843     RenderImage& imageRenderer = toRenderImage(renderer());
1844     if (CachedImage* cachedImage = imageRenderer.cachedImage()) {
1845         if (!cachedImage->hasImage())
1846             return false;
1847
1848         Image* image = cachedImage->imageForRenderer(&imageRenderer);
1849         if (!image->isBitmapImage())
1850             return false;
1851
1852         if (image->orientationForCurrentFrame() != DefaultImageOrientation)
1853             return false;
1854
1855         return m_graphicsLayer->shouldDirectlyCompositeImage(image);
1856     }
1857
1858     return false;
1859 }
1860
1861 void RenderLayerBacking::contentChanged(ContentChangeType changeType)
1862 {
1863     if ((changeType == ImageChanged) && isDirectlyCompositedImage()) {
1864         updateImageContents();
1865         return;
1866     }
1867
1868     if ((changeType == BackgroundImageChanged) && canCreateTiledImage(&renderer().style()))
1869         updateGraphicsLayerGeometry();
1870
1871     if ((changeType == MaskImageChanged) && m_maskLayer) {
1872         // The composited layer bounds relies on box->maskClipRect(), which changes
1873         // when the mask image becomes available.
1874         updateAfterLayout(CompositingChildrenOnly | IsUpdateRoot);
1875     }
1876
1877 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
1878     if ((changeType == CanvasChanged || changeType == CanvasPixelsChanged) && renderer().isCanvas() && canvasCompositingStrategy(renderer()) == CanvasAsLayerContents) {
1879         m_graphicsLayer->setContentsNeedsDisplay();
1880         return;
1881     }
1882 #endif
1883 }
1884
1885 void RenderLayerBacking::updateImageContents()
1886 {
1887     ASSERT(renderer().isRenderImage());
1888     RenderImage& imageRenderer = toRenderImage(renderer());
1889
1890     CachedImage* cachedImage = imageRenderer.cachedImage();
1891     if (!cachedImage)
1892         return;
1893
1894     Image* image = cachedImage->imageForRenderer(&imageRenderer);
1895     if (!image)
1896         return;
1897
1898     // We have to wait until the image is fully loaded before setting it on the layer.
1899     if (!cachedImage->isLoaded())
1900         return;
1901
1902     // This is a no-op if the layer doesn't have an inner layer for the image.
1903     m_graphicsLayer->setContentsRect(pixelSnappedIntRect(contentsBox()));
1904
1905     LayoutRect contentsClippingRect = imageRenderer.contentBoxRect();
1906     contentsClippingRect.move(contentOffsetInCompostingLayer());
1907     m_graphicsLayer->setContentsClippingRect(pixelSnappedIntRect(contentsClippingRect));
1908
1909     m_graphicsLayer->setContentsToImage(image);
1910     bool isSimpleContainer = false;
1911     updateDrawsContent(isSimpleContainer);
1912     
1913     // Image animation is "lazy", in that it automatically stops unless someone is drawing
1914     // the image. So we have to kick the animation each time; this has the downside that the
1915     // image will keep animating, even if its layer is not visible.
1916     image->startAnimation();
1917 }
1918
1919 FloatPoint3D RenderLayerBacking::computeTransformOrigin(const LayoutRect& borderBox) const
1920 {
1921     const RenderStyle& style = renderer().style();
1922
1923     FloatPoint3D origin;
1924     origin.setX(floatValueForLength(style.transformOriginX(), borderBox.width()));
1925     origin.setY(floatValueForLength(style.transformOriginY(), borderBox.height()));
1926     origin.setZ(style.transformOriginZ());
1927
1928     return origin;
1929 }
1930
1931 FloatPoint RenderLayerBacking::computePerspectiveOrigin(const LayoutRect& borderBox) const
1932 {
1933     const RenderStyle& style = renderer().style();
1934
1935     float boxWidth = borderBox.width();
1936     float boxHeight = borderBox.height();
1937
1938     FloatPoint origin;
1939     origin.setX(floatValueForLength(style.perspectiveOriginX(), boxWidth));
1940     origin.setY(floatValueForLength(style.perspectiveOriginY(), boxHeight));
1941
1942     return origin;
1943 }
1944
1945 // Return the offset from the top-left of this compositing layer at which the renderer's contents are painted.
1946 LayoutSize RenderLayerBacking::contentOffsetInCompostingLayer() const
1947 {
1948     return LayoutSize(-m_compositedBounds.x(), -m_compositedBounds.y()) + m_devicePixelFractionFromRenderer;
1949 }
1950
1951 LayoutRect RenderLayerBacking::contentsBox() const
1952 {
1953     if (!renderer().isBox())
1954         return LayoutRect();
1955
1956     RenderBox& renderBox = toRenderBox(renderer());
1957     LayoutRect contentsRect;
1958 #if ENABLE(VIDEO)
1959     if (renderBox.isVideo())
1960         contentsRect = toRenderVideo(renderBox).videoBox();
1961     else
1962 #endif
1963     if (renderBox.isRenderReplaced()) {
1964         RenderReplaced& renderReplaced = *toRenderReplaced(&renderBox);
1965         contentsRect = renderReplaced.replacedContentRect(renderBox.intrinsicSize());
1966     } else
1967         contentsRect = renderBox.contentBoxRect();
1968
1969     contentsRect.move(contentOffsetInCompostingLayer());
1970     return contentsRect;
1971 }
1972
1973 static LayoutRect backgroundRectForBox(const RenderBox& box)
1974 {
1975     switch (box.style().backgroundClip()) {
1976     case BorderFillBox:
1977         return box.borderBoxRect();
1978     case PaddingFillBox:
1979         return box.paddingBoxRect();
1980     case ContentFillBox:
1981         return box.contentBoxRect();
1982     case TextFillBox:
1983         break;
1984     }
1985
1986     ASSERT_NOT_REACHED();
1987     return LayoutRect();
1988 }
1989
1990 FloatRect RenderLayerBacking::backgroundBoxForPainting() const
1991 {
1992     if (!renderer().isBox())
1993         return FloatRect();
1994
1995     LayoutRect backgroundBox = backgroundRectForBox(toRenderBox(renderer()));
1996     backgroundBox.move(contentOffsetInCompostingLayer());
1997     return pixelSnappedForPainting(backgroundBox, deviceScaleFactor());
1998 }
1999
2000 GraphicsLayer* RenderLayerBacking::parentForSublayers() const
2001 {
2002     if (m_scrollingContentsLayer)
2003         return m_scrollingContentsLayer.get();
2004
2005 #if PLATFORM(IOS)
2006     // FIXME: Can we remove this iOS-specific code path?
2007     if (GraphicsLayer* clippingLayer = this->clippingLayer())
2008         return clippingLayer;
2009     return m_graphicsLayer.get();
2010 #else
2011     return m_childContainmentLayer ? m_childContainmentLayer.get() : m_graphicsLayer.get();
2012 #endif
2013 }
2014
2015 GraphicsLayer* RenderLayerBacking::childForSuperlayers() const
2016 {
2017     if (m_ancestorClippingLayer)
2018         return m_ancestorClippingLayer.get();
2019
2020     if (m_contentsContainmentLayer)
2021         return m_contentsContainmentLayer.get();
2022     
2023     return m_graphicsLayer.get();
2024 }
2025
2026 bool RenderLayerBacking::paintsIntoWindow() const
2027 {
2028     if (m_usingTiledCacheLayer)
2029         return false;
2030
2031     if (m_owningLayer.isRootLayer()) {
2032 #if PLATFORM(IOS) || USE(COORDINATED_GRAPHICS)
2033         if (compositor().inForcedCompositingMode())
2034             return false;
2035 #endif
2036
2037         return compositor().rootLayerAttachment() != RenderLayerCompositor::RootLayerAttachedViaEnclosingFrame;
2038     }
2039     
2040     return false;
2041 }
2042
2043 void RenderLayerBacking::setRequiresOwnBackingStore(bool requiresOwnBacking)
2044 {
2045     if (requiresOwnBacking == m_requiresOwnBackingStore)
2046         return;
2047     
2048     m_requiresOwnBackingStore = requiresOwnBacking;
2049
2050     // This affects the answer to paintsIntoCompositedAncestor(), which in turn affects
2051     // cached clip rects, so when it changes we have to clear clip rects on descendants.
2052     m_owningLayer.clearClipRectsIncludingDescendants(PaintingClipRects);
2053     m_owningLayer.computeRepaintRectsIncludingDescendants();
2054     
2055     compositor().repaintInCompositedAncestor(m_owningLayer, compositedBounds());
2056 }
2057
2058 #if ENABLE(CSS_COMPOSITING)
2059 void RenderLayerBacking::setBlendMode(BlendMode blendMode)
2060 {
2061     m_graphicsLayer->setBlendMode(blendMode);
2062 }
2063 #endif
2064
2065 void RenderLayerBacking::setContentsNeedDisplay(GraphicsLayer::ShouldClipToLayer shouldClip)
2066 {
2067     ASSERT(!paintsIntoCompositedAncestor());
2068
2069     FrameView& frameView = owningLayer().renderer().view().frameView();
2070     if (m_isMainFrameRenderViewLayer && frameView.isTrackingRepaints())
2071         frameView.addTrackedRepaintRect(owningLayer().absoluteBoundingBoxForPainting());
2072     
2073     if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
2074         // By default, setNeedsDisplay will clip to the size of the GraphicsLayer, which does not include margin tiles.
2075         // So if the TiledBacking has a margin that needs to be invalidated, we need to send in a rect to setNeedsDisplayInRect
2076         // that is large enough to include the margin. TiledBacking::bounds() includes the margin.
2077         TiledBacking* tiledBacking = this->tiledBacking();
2078         FloatRect rectToRepaint = tiledBacking ? tiledBacking->bounds() : FloatRect(FloatPoint(0, 0), m_graphicsLayer->size());
2079         m_graphicsLayer->setNeedsDisplayInRect(rectToRepaint, shouldClip);
2080     }
2081     
2082     if (m_foregroundLayer && m_foregroundLayer->drawsContent())
2083         m_foregroundLayer->setNeedsDisplay();
2084
2085     if (m_backgroundLayer && m_backgroundLayer->drawsContent())
2086         m_backgroundLayer->setNeedsDisplay();
2087
2088     if (m_maskLayer && m_maskLayer->drawsContent())
2089         m_maskLayer->setNeedsDisplay();
2090
2091     if (m_scrollingContentsLayer && m_scrollingContentsLayer->drawsContent())
2092         m_scrollingContentsLayer->setNeedsDisplay();
2093 }
2094
2095 // r is in the coordinate space of the layer's render object
2096 void RenderLayerBacking::setContentsNeedDisplayInRect(const LayoutRect& r, GraphicsLayer::ShouldClipToLayer shouldClip)
2097 {
2098     ASSERT(!paintsIntoCompositedAncestor());
2099
2100     FloatRect pixelSnappedRectForPainting = pixelSnappedForPainting(r, deviceScaleFactor());
2101     FrameView& frameView = owningLayer().renderer().view().frameView();
2102     if (m_isMainFrameRenderViewLayer && frameView.isTrackingRepaints())
2103         frameView.addTrackedRepaintRect(pixelSnappedRectForPainting);
2104
2105     if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
2106         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2107         layerDirtyRect.move(-m_graphicsLayer->offsetFromRenderer() + m_devicePixelFractionFromRenderer);
2108         m_graphicsLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2109     }
2110
2111     if (m_foregroundLayer && m_foregroundLayer->drawsContent()) {
2112         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2113         layerDirtyRect.move(-m_foregroundLayer->offsetFromRenderer() + m_devicePixelFractionFromRenderer);
2114         m_foregroundLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2115     }
2116
2117     // FIXME: need to split out repaints for the background.
2118     if (m_backgroundLayer && m_backgroundLayer->drawsContent()) {
2119         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2120         layerDirtyRect.move(-m_backgroundLayer->offsetFromRenderer() + m_devicePixelFractionFromRenderer);
2121         m_backgroundLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2122     }
2123
2124     if (m_maskLayer && m_maskLayer->drawsContent()) {
2125         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2126         layerDirtyRect.move(-m_maskLayer->offsetFromRenderer() + m_devicePixelFractionFromRenderer);
2127         m_maskLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2128     }
2129
2130     if (m_scrollingContentsLayer && m_scrollingContentsLayer->drawsContent()) {
2131         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2132         layerDirtyRect.move(-m_scrollingContentsLayer->offsetFromRenderer() + m_devicePixelFractionFromRenderer);
2133 #if PLATFORM(IOS)
2134         // Account for the fact that RenderLayerBacking::updateGraphicsLayerGeometry() bakes scrollOffset into offsetFromRenderer on iOS.
2135         layerDirtyRect.move(-m_owningLayer.scrollOffset() + m_devicePixelFractionFromRenderer);
2136 #endif
2137         m_scrollingContentsLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2138     }
2139 }
2140
2141 void RenderLayerBacking::paintIntoLayer(const GraphicsLayer* graphicsLayer, GraphicsContext* context,
2142     const IntRect& paintDirtyRect, // In the coords of rootLayer.
2143     PaintBehavior paintBehavior, GraphicsLayerPaintingPhase paintingPhase)
2144 {
2145     if (paintsIntoWindow() || paintsIntoCompositedAncestor()) {
2146 #if !PLATFORM(IOS)
2147         // FIXME: Looks like the CALayer tree is out of sync with the GraphicsLayer heirarchy
2148         // when pages are restored from the PageCache.
2149         // <rdar://problem/8712587> ASSERT: When Going Back to Page with Plugins in PageCache
2150         ASSERT_NOT_REACHED();
2151 #endif
2152         return;
2153     }
2154
2155     FontCachePurgePreventer fontCachePurgePreventer;
2156     
2157     RenderLayer::PaintLayerFlags paintFlags = 0;
2158     if (paintingPhase & GraphicsLayerPaintBackground)
2159         paintFlags |= RenderLayer::PaintLayerPaintingCompositingBackgroundPhase;
2160     if (paintingPhase & GraphicsLayerPaintForeground)
2161         paintFlags |= RenderLayer::PaintLayerPaintingCompositingForegroundPhase;
2162     if (paintingPhase & GraphicsLayerPaintMask)
2163         paintFlags |= RenderLayer::PaintLayerPaintingCompositingMaskPhase;
2164     if (paintingPhase & GraphicsLayerPaintOverflowContents)
2165         paintFlags |= RenderLayer::PaintLayerPaintingOverflowContents;
2166     if (paintingPhase & GraphicsLayerPaintCompositedScroll)
2167         paintFlags |= RenderLayer::PaintLayerPaintingCompositingScrollingPhase;
2168
2169     if (graphicsLayer == m_backgroundLayer.get())
2170         paintFlags |= (RenderLayer::PaintLayerPaintingRootBackgroundOnly | RenderLayer::PaintLayerPaintingCompositingForegroundPhase); // Need PaintLayerPaintingCompositingForegroundPhase to walk child layers.
2171     else if (compositor().fixedRootBackgroundLayer())
2172         paintFlags |= RenderLayer::PaintLayerPaintingSkipRootBackground;
2173     
2174     // FIXME: GraphicsLayers need a way to split for RenderRegions.
2175     RenderLayer::LayerPaintingInfo paintingInfo(&m_owningLayer, paintDirtyRect, paintBehavior, m_devicePixelFractionFromRenderer);
2176     m_owningLayer.paintLayerContents(context, paintingInfo, paintFlags);
2177
2178     if (m_owningLayer.containsDirtyOverlayScrollbars())
2179         m_owningLayer.paintLayerContents(context, paintingInfo, paintFlags | RenderLayer::PaintLayerPaintingOverlayScrollbars);
2180
2181     compositor().didPaintBacking(this);
2182
2183     ASSERT(!m_owningLayer.m_usedTransparency);
2184 }
2185
2186 static void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
2187 {
2188     if (!scrollbar)
2189         return;
2190
2191     context.save();
2192     const IntRect& scrollbarRect = scrollbar->frameRect();
2193     context.translate(-scrollbarRect.x(), -scrollbarRect.y());
2194     IntRect transformedClip = clip;
2195     transformedClip.moveBy(scrollbarRect.location());
2196     scrollbar->paint(&context, transformedClip);
2197     context.restore();
2198 }
2199
2200 // Up-call from compositing layer drawing callback.
2201 void RenderLayerBacking::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, GraphicsLayerPaintingPhase paintingPhase, const FloatRect& clip)
2202 {
2203 #ifndef NDEBUG
2204     if (Page* page = renderer().frame().page())
2205         page->setIsPainting(true);
2206 #endif
2207
2208     // The dirtyRect is in the coords of the painting root.
2209     IntRect dirtyRect = enclosingIntRect(clip);
2210
2211     if (graphicsLayer == m_graphicsLayer.get()
2212         || graphicsLayer == m_foregroundLayer.get()
2213         || graphicsLayer == m_backgroundLayer.get()
2214         || graphicsLayer == m_maskLayer.get()
2215         || graphicsLayer == m_scrollingContentsLayer.get()) {
2216         InspectorInstrumentation::willPaint(&renderer());
2217
2218         if (!(paintingPhase & GraphicsLayerPaintOverflowContents))
2219             dirtyRect.intersect(enclosingIntRect(compositedBoundsIncludingMargin()));
2220
2221         // We have to use the same root as for hit testing, because both methods can compute and cache clipRects.
2222         paintIntoLayer(graphicsLayer, &context, dirtyRect, PaintBehaviorNormal, paintingPhase);
2223
2224         InspectorInstrumentation::didPaint(&renderer(), &context, dirtyRect);
2225     } else if (graphicsLayer == layerForHorizontalScrollbar()) {
2226         paintScrollbar(m_owningLayer.horizontalScrollbar(), context, dirtyRect);
2227     } else if (graphicsLayer == layerForVerticalScrollbar()) {
2228         paintScrollbar(m_owningLayer.verticalScrollbar(), context, dirtyRect);
2229     } else if (graphicsLayer == layerForScrollCorner()) {
2230         const LayoutRect& scrollCornerAndResizer = m_owningLayer.scrollCornerAndResizerRect();
2231         context.save();
2232         context.translate(-scrollCornerAndResizer.x(), -scrollCornerAndResizer.y());
2233         LayoutRect transformedClip = LayoutRect(clip);
2234         transformedClip.moveBy(scrollCornerAndResizer.location());
2235         m_owningLayer.paintScrollCorner(&context, IntPoint(), pixelSnappedIntRect(transformedClip));
2236         m_owningLayer.paintResizer(&context, IntPoint(), transformedClip);
2237         context.restore();
2238     }
2239 #ifndef NDEBUG
2240     if (Page* page = renderer().frame().page())
2241         page->setIsPainting(false);
2242 #endif
2243 }
2244
2245 float RenderLayerBacking::pageScaleFactor() const
2246 {
2247     return compositor().pageScaleFactor();
2248 }
2249
2250 float RenderLayerBacking::deviceScaleFactor() const
2251 {
2252     return compositor().deviceScaleFactor();
2253 }
2254
2255 float RenderLayerBacking::contentsScaleMultiplierForNewTiles(const GraphicsLayer* layer) const
2256 {
2257     return compositor().contentsScaleMultiplierForNewTiles(layer);
2258 }
2259
2260 bool RenderLayerBacking::paintsOpaquelyAtNonIntegralScales(const GraphicsLayer*) const
2261 {
2262     return m_isMainFrameRenderViewLayer;
2263 }
2264
2265 void RenderLayerBacking::didCommitChangesForLayer(const GraphicsLayer* layer) const
2266 {
2267     compositor().didFlushChangesForLayer(m_owningLayer, layer);
2268 }
2269
2270 bool RenderLayerBacking::getCurrentTransform(const GraphicsLayer* graphicsLayer, TransformationMatrix& transform) const
2271 {
2272     GraphicsLayer* transformedLayer = m_contentsContainmentLayer.get() ? m_contentsContainmentLayer.get() : m_graphicsLayer.get();
2273     if (graphicsLayer != transformedLayer)
2274         return false;
2275
2276     if (m_owningLayer.hasTransform()) {
2277         transform = m_owningLayer.currentTransform(RenderStyle::ExcludeTransformOrigin);
2278         return true;
2279     }
2280     return false;
2281 }
2282
2283 bool RenderLayerBacking::isTrackingRepaints() const
2284 {
2285     return static_cast<GraphicsLayerClient&>(compositor()).isTrackingRepaints();
2286 }
2287
2288 bool RenderLayerBacking::shouldSkipLayerInDump(const GraphicsLayer* layer) const
2289 {
2290     // Skip the root tile cache's flattening layer.
2291     return m_isMainFrameRenderViewLayer && layer && layer == m_childContainmentLayer.get();
2292 }
2293
2294 bool RenderLayerBacking::shouldDumpPropertyForLayer(const GraphicsLayer* layer, const char* propertyName) const
2295 {
2296     // For backwards compatibility with WebKit1 and other platforms,
2297     // skip some properties on the root tile cache.
2298     if (m_isMainFrameRenderViewLayer && layer == m_graphicsLayer.get()) {
2299         if (!strcmp(propertyName, "drawsContent"))
2300             return false;
2301
2302         // Background color could be of interest to tests or other dumpers if it's non-white.
2303         if (!strcmp(propertyName, "backgroundColor") && layer->backgroundColor() == Color::white)
2304             return false;
2305
2306         // The root tile cache's repaints will show up at the top with FrameView's,
2307         // so don't dump them twice.
2308         if (!strcmp(propertyName, "repaintRects"))
2309             return false;
2310     }
2311
2312     return true;
2313 }
2314
2315 #ifndef NDEBUG
2316 void RenderLayerBacking::verifyNotPainting()
2317 {
2318     ASSERT(!renderer().frame().page() || !renderer().frame().page()->isPainting());
2319 }
2320 #endif
2321
2322 bool RenderLayerBacking::startAnimation(double timeOffset, const Animation* anim, const KeyframeList& keyframes)
2323 {
2324     bool hasOpacity = keyframes.containsProperty(CSSPropertyOpacity);
2325     bool hasTransform = renderer().isBox() && keyframes.containsProperty(CSSPropertyWebkitTransform);
2326 #if ENABLE(CSS_FILTERS)
2327     bool hasFilter = keyframes.containsProperty(CSSPropertyWebkitFilter);
2328 #else
2329     bool hasFilter = false;
2330 #endif
2331
2332     if (!hasOpacity && !hasTransform && !hasFilter)
2333         return false;
2334     
2335     KeyframeValueList transformVector(AnimatedPropertyWebkitTransform);
2336     KeyframeValueList opacityVector(AnimatedPropertyOpacity);
2337 #if ENABLE(CSS_FILTERS)
2338     KeyframeValueList filterVector(AnimatedPropertyWebkitFilter);
2339 #endif
2340
2341     size_t numKeyframes = keyframes.size();
2342     for (size_t i = 0; i < numKeyframes; ++i) {
2343         const KeyframeValue& currentKeyframe = keyframes[i];
2344         const RenderStyle* keyframeStyle = currentKeyframe.style();
2345         double key = currentKeyframe.key();
2346
2347         if (!keyframeStyle)
2348             continue;
2349             
2350         // Get timing function.
2351         RefPtr<TimingFunction> tf = keyframeStyle->hasAnimations() ? (*keyframeStyle->animations()).animation(0).timingFunction() : 0;
2352         
2353         bool isFirstOrLastKeyframe = key == 0 || key == 1;
2354         if ((hasTransform && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitTransform))
2355             transformVector.insert(TransformAnimationValue::create(key, keyframeStyle->transform(), tf));
2356
2357         if ((hasOpacity && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyOpacity))
2358             opacityVector.insert(FloatAnimationValue::create(key, keyframeStyle->opacity(), tf));
2359
2360 #if ENABLE(CSS_FILTERS)
2361         if ((hasFilter && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitFilter))
2362             filterVector.insert(FilterAnimationValue::create(key, keyframeStyle->filter(), tf));
2363 #endif
2364     }
2365
2366     if (renderer().frame().page() && !renderer().frame().page()->settings().acceleratedCompositedAnimationsEnabled())
2367         return false;
2368
2369     bool didAnimate = false;
2370
2371     if (hasTransform && m_graphicsLayer->addAnimation(transformVector, toRenderBox(renderer()).pixelSnappedBorderBoxRect().size(), anim, keyframes.animationName(), timeOffset))
2372         didAnimate = true;
2373
2374     if (hasOpacity && m_graphicsLayer->addAnimation(opacityVector, IntSize(), anim, keyframes.animationName(), timeOffset))
2375         didAnimate = true;
2376
2377 #if ENABLE(CSS_FILTERS)
2378     if (hasFilter && m_graphicsLayer->addAnimation(filterVector, IntSize(), anim, keyframes.animationName(), timeOffset))
2379         didAnimate = true;
2380 #endif
2381
2382     return didAnimate;
2383 }
2384
2385 void RenderLayerBacking::animationPaused(double timeOffset, const String& animationName)
2386 {
2387     m_graphicsLayer->pauseAnimation(animationName, timeOffset);
2388 }
2389
2390 void RenderLayerBacking::animationFinished(const String& animationName)
2391 {
2392     m_graphicsLayer->removeAnimation(animationName);
2393 }
2394
2395 bool RenderLayerBacking::startTransition(double timeOffset, CSSPropertyID property, const RenderStyle* fromStyle, const RenderStyle* toStyle)
2396 {
2397     bool didAnimate = false;
2398
2399     ASSERT(property != CSSPropertyInvalid);
2400
2401     if (property == CSSPropertyOpacity) {
2402         const Animation* opacityAnim = toStyle->transitionForProperty(CSSPropertyOpacity);
2403         if (opacityAnim && !opacityAnim->isEmptyOrZeroDuration()) {
2404             KeyframeValueList opacityVector(AnimatedPropertyOpacity);
2405             opacityVector.insert(FloatAnimationValue::create(0, compositingOpacity(fromStyle->opacity())));
2406             opacityVector.insert(FloatAnimationValue::create(1, compositingOpacity(toStyle->opacity())));
2407             // The boxSize param is only used for transform animations (which can only run on RenderBoxes), so we pass an empty size here.
2408             if (m_graphicsLayer->addAnimation(opacityVector, FloatSize(), opacityAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyOpacity), timeOffset)) {
2409                 // To ensure that the correct opacity is visible when the animation ends, also set the final opacity.
2410                 updateOpacity(toStyle);
2411                 didAnimate = true;
2412             }
2413         }
2414     }
2415
2416     if (property == CSSPropertyWebkitTransform && m_owningLayer.hasTransform()) {
2417         const Animation* transformAnim = toStyle->transitionForProperty(CSSPropertyWebkitTransform);
2418         if (transformAnim && !transformAnim->isEmptyOrZeroDuration()) {
2419             KeyframeValueList transformVector(AnimatedPropertyWebkitTransform);
2420             transformVector.insert(TransformAnimationValue::create(0, fromStyle->transform()));
2421             transformVector.insert(TransformAnimationValue::create(1, toStyle->transform()));
2422             if (m_graphicsLayer->addAnimation(transformVector, toRenderBox(renderer()).pixelSnappedBorderBoxRect().size(), transformAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyWebkitTransform), timeOffset)) {
2423                 // To ensure that the correct transform is visible when the animation ends, also set the final transform.
2424                 updateTransform(toStyle);
2425                 didAnimate = true;
2426             }
2427         }
2428     }
2429
2430 #if ENABLE(CSS_FILTERS)
2431     if (property == CSSPropertyWebkitFilter && m_owningLayer.hasFilter()) {
2432         const Animation* filterAnim = toStyle->transitionForProperty(CSSPropertyWebkitFilter);
2433         if (filterAnim && !filterAnim->isEmptyOrZeroDuration()) {
2434             KeyframeValueList filterVector(AnimatedPropertyWebkitFilter);
2435             filterVector.insert(FilterAnimationValue::create(0, fromStyle->filter()));
2436             filterVector.insert(FilterAnimationValue::create(1, toStyle->filter()));
2437             if (m_graphicsLayer->addAnimation(filterVector, FloatSize(), filterAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyWebkitFilter), timeOffset)) {
2438                 // To ensure that the correct filter is visible when the animation ends, also set the final filter.
2439                 updateFilters(toStyle);
2440                 didAnimate = true;
2441             }
2442         }
2443     }
2444 #endif
2445
2446     return didAnimate;
2447 }
2448
2449 void RenderLayerBacking::transitionPaused(double timeOffset, CSSPropertyID property)
2450 {
2451     AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
2452     if (animatedProperty != AnimatedPropertyInvalid)
2453         m_graphicsLayer->pauseAnimation(GraphicsLayer::animationNameForTransition(animatedProperty), timeOffset);
2454 }
2455
2456 void RenderLayerBacking::transitionFinished(CSSPropertyID property)
2457 {
2458     AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
2459     if (animatedProperty != AnimatedPropertyInvalid)
2460         m_graphicsLayer->removeAnimation(GraphicsLayer::animationNameForTransition(animatedProperty));
2461 }
2462
2463 void RenderLayerBacking::notifyAnimationStarted(const GraphicsLayer*, double time)
2464 {
2465     renderer().animation().notifyAnimationStarted(&renderer(), time);
2466 }
2467
2468 void RenderLayerBacking::notifyFlushRequired(const GraphicsLayer* layer)
2469 {
2470     if (renderer().documentBeingDestroyed())
2471         return;
2472     compositor().scheduleLayerFlush(layer->canThrottleLayerFlush());
2473 }
2474
2475 void RenderLayerBacking::notifyFlushBeforeDisplayRefresh(const GraphicsLayer* layer)
2476 {
2477     compositor().notifyFlushBeforeDisplayRefresh(layer);
2478 }
2479
2480 // This is used for the 'freeze' API, for testing only.
2481 void RenderLayerBacking::suspendAnimations(double time)
2482 {
2483     m_graphicsLayer->suspendAnimations(time);
2484 }
2485
2486 void RenderLayerBacking::resumeAnimations()
2487 {
2488     m_graphicsLayer->resumeAnimations();
2489 }
2490
2491 LayoutRect RenderLayerBacking::compositedBounds() const
2492 {
2493     return m_compositedBounds;
2494 }
2495
2496 void RenderLayerBacking::setCompositedBounds(const LayoutRect& bounds)
2497 {
2498     m_compositedBounds = bounds;
2499 }
2500
2501 LayoutRect RenderLayerBacking::compositedBoundsIncludingMargin() const
2502 {
2503     TiledBacking* tiledBacking = this->tiledBacking();
2504     if (!tiledBacking || !tiledBacking->hasMargins())
2505         return compositedBounds();
2506
2507     LayoutRect boundsIncludingMargin = compositedBounds();
2508     LayoutUnit leftMarginWidth = tiledBacking->leftMarginWidth();
2509     LayoutUnit topMarginHeight = tiledBacking->topMarginHeight();
2510
2511     boundsIncludingMargin.moveBy(LayoutPoint(-leftMarginWidth, -topMarginHeight));
2512     boundsIncludingMargin.expand(leftMarginWidth + tiledBacking->rightMarginWidth(), topMarginHeight + tiledBacking->bottomMarginHeight());
2513
2514     return boundsIncludingMargin;
2515 }
2516
2517 CSSPropertyID RenderLayerBacking::graphicsLayerToCSSProperty(AnimatedPropertyID property)
2518 {
2519     CSSPropertyID cssProperty = CSSPropertyInvalid;
2520     switch (property) {
2521         case AnimatedPropertyWebkitTransform:
2522             cssProperty = CSSPropertyWebkitTransform;
2523             break;
2524         case AnimatedPropertyOpacity:
2525             cssProperty = CSSPropertyOpacity;
2526             break;
2527         case AnimatedPropertyBackgroundColor:
2528             cssProperty = CSSPropertyBackgroundColor;
2529             break;
2530         case AnimatedPropertyWebkitFilter:
2531 #if ENABLE(CSS_FILTERS)
2532             cssProperty = CSSPropertyWebkitFilter;
2533 #else
2534             ASSERT_NOT_REACHED();
2535 #endif
2536             break;
2537         case AnimatedPropertyInvalid:
2538             ASSERT_NOT_REACHED();
2539     }
2540     return cssProperty;
2541 }
2542
2543 AnimatedPropertyID RenderLayerBacking::cssToGraphicsLayerProperty(CSSPropertyID cssProperty)
2544 {
2545     switch (cssProperty) {
2546         case CSSPropertyWebkitTransform:
2547             return AnimatedPropertyWebkitTransform;
2548         case CSSPropertyOpacity:
2549             return AnimatedPropertyOpacity;
2550         case CSSPropertyBackgroundColor:
2551             return AnimatedPropertyBackgroundColor;
2552 #if ENABLE(CSS_FILTERS)
2553         case CSSPropertyWebkitFilter:
2554             return AnimatedPropertyWebkitFilter;
2555 #endif
2556         default:
2557             // It's fine if we see other css properties here; they are just not accelerated.
2558             break;
2559     }
2560     return AnimatedPropertyInvalid;
2561 }
2562
2563 CompositingLayerType RenderLayerBacking::compositingLayerType() const
2564 {
2565     if (m_graphicsLayer->hasContentsLayer())
2566         return MediaCompositingLayer;
2567
2568     if (m_graphicsLayer->drawsContent())
2569         return m_graphicsLayer->usingTiledBacking() ? TiledCompositingLayer : NormalCompositingLayer;
2570     
2571     return ContainerCompositingLayer;
2572 }
2573
2574 double RenderLayerBacking::backingStoreMemoryEstimate() const
2575 {
2576     double backingMemory;
2577     
2578     // m_ancestorClippingLayer, m_contentsContainmentLayer and m_childContainmentLayer are just used for masking or containment, so have no backing.
2579     backingMemory = m_graphicsLayer->backingStoreMemoryEstimate();
2580     if (m_foregroundLayer)
2581         backingMemory += m_foregroundLayer->backingStoreMemoryEstimate();
2582     if (m_backgroundLayer)
2583         backingMemory += m_backgroundLayer->backingStoreMemoryEstimate();
2584     if (m_maskLayer)
2585         backingMemory += m_maskLayer->backingStoreMemoryEstimate();
2586
2587     if (m_scrollingContentsLayer)
2588         backingMemory += m_scrollingContentsLayer->backingStoreMemoryEstimate();
2589
2590     if (m_layerForHorizontalScrollbar)
2591         backingMemory += m_layerForHorizontalScrollbar->backingStoreMemoryEstimate();
2592
2593     if (m_layerForVerticalScrollbar)
2594         backingMemory += m_layerForVerticalScrollbar->backingStoreMemoryEstimate();
2595
2596     if (m_layerForScrollCorner)
2597         backingMemory += m_layerForScrollCorner->backingStoreMemoryEstimate();
2598     
2599     return backingMemory;
2600 }
2601
2602 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
2603 bool RenderLayerBacking::mediaLayerMustBeUpdatedOnMainThread() const
2604 {
2605     return renderer().frame().page() && renderer().frame().page()->settings().isVideoPluginProxyEnabled();
2606 }
2607 #endif
2608
2609 } // namespace WebCore