97893cd19f7a15bf0bf8c1f1ba4515561e299672
[WebKit-https.git] / Source / WebCore / rendering / RenderLayerBacking.cpp
1 /*
2  * Copyright (C) 2009, 2010, 2011 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27
28 #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     // Device pixel fractions get accumulated through ancestor layers. Our painting offset is layout offset + parent's painting offset.
743     offsetFromParent = offsetFromParent + (compAncestor ? compAncestor->backing()->devicePixelFractionFromRenderer() : LayoutSize());
744     relativeCompositingBounds.moveBy(offsetFromParent);
745
746     LayoutRect enclosingRelativeCompositingBounds = LayoutRect(enclosingRectForPainting(relativeCompositingBounds, deviceScaleFactor));
747     LayoutSize subpixelOffsetAdjustment = enclosingRelativeCompositingBounds.location() - relativeCompositingBounds.location();
748     LayoutSize rendererOffsetFromGraphicsLayer =  toLayoutSize(localCompositingBounds.location()) + subpixelOffsetAdjustment;
749
750     FloatSize devicePixelOffsetFromRenderer;
751     LayoutSize devicePixelFractionFromRenderer;
752     calculateDevicePixelOffsetFromRenderer(rendererOffsetFromGraphicsLayer, devicePixelOffsetFromRenderer, devicePixelFractionFromRenderer, deviceScaleFactor);
753     m_devicePixelFractionFromRenderer = LayoutSize(fabs(devicePixelFractionFromRenderer.width().toFloat()), fabs(devicePixelFractionFromRenderer.height().toFloat()));
754
755     adjustAncestorCompositingBoundsForFlowThread(ancestorCompositingBounds, compAncestor);
756
757     LayoutPoint graphicsLayerParentLocation;
758     if (compAncestor && compAncestor->backing()->hasClippingLayer()) {
759         // If the compositing ancestor has a layer to clip children, we parent in that, and therefore
760         // position relative to it.
761         LayoutRect clippingBox = clipBox(toRenderBox(compAncestor->renderer()));
762         graphicsLayerParentLocation = clippingBox.location();
763     } else if (compAncestor)
764         graphicsLayerParentLocation = ancestorCompositingBounds.location();
765     else
766         graphicsLayerParentLocation = renderer().view().documentRect().location();
767
768 #if PLATFORM(IOS)
769     if (compAncestor && compAncestor->hasAcceleratedTouchScrolling()) {
770         RenderBox* renderBox = toRenderBox(&compAncestor->renderer());
771         LayoutRect paddingBox(renderBox->borderLeft(), renderBox->borderTop(),
772             renderBox->width() - renderBox->borderLeft() - renderBox->borderRight(),
773             renderBox->height() - renderBox->borderTop() - renderBox->borderBottom());
774
775         LayoutSize scrollOffset = compAncestor->scrolledContentOffset();
776         graphicsLayerParentLocation = paddingBox.location() - scrollOffset;
777     }
778 #endif
779
780     if (compAncestor && compAncestor->needsCompositedScrolling()) {
781         RenderBox& renderBox = toRenderBox(compAncestor->renderer());
782         LayoutSize scrollOffset = compAncestor->scrolledContentOffset();
783         LayoutPoint scrollOrigin(renderBox.borderLeft(), renderBox.borderTop());
784         graphicsLayerParentLocation = scrollOrigin - scrollOffset;
785     }
786     
787     if (compAncestor && m_ancestorClippingLayer) {
788         // Call calculateRects to get the backgroundRect which is what is used to clip the contents of this
789         // layer. Note that we call it with temporaryClipRects = true because normally when computing clip rects
790         // for a compositing layer, rootLayer is the layer itself.
791         RenderLayer::ClipRectsContext clipRectsContext(compAncestor, 0, TemporaryClipRects, IgnoreOverlayScrollbarSize, IgnoreOverflowClip);
792         LayoutRect parentClipRect = m_owningLayer.backgroundClipRect(clipRectsContext).rect(); // FIXME: Incorrect for CSS regions.
793         ASSERT(parentClipRect != LayoutRect::infiniteRect());
794         m_ancestorClippingLayer->setPosition(FloatPoint(parentClipRect.location() - graphicsLayerParentLocation));
795         m_ancestorClippingLayer->setSize(parentClipRect.size());
796
797         // backgroundRect is relative to compAncestor, so subtract deltaX/deltaY to get back to local coords.
798         m_ancestorClippingLayer->setOffsetFromRenderer(parentClipRect.location() - offsetFromParent);
799
800         // The primary layer is then parented in, and positioned relative to this clipping layer.
801         graphicsLayerParentLocation = parentClipRect.location();
802     }
803
804     LayoutSize contentsSize = enclosingRelativeCompositingBounds.size();
805     
806     if (m_contentsContainmentLayer) {
807         m_contentsContainmentLayer->setPreserves3D(preserves3D);
808         m_contentsContainmentLayer->setPosition(FloatPoint(enclosingRelativeCompositingBounds.location() - graphicsLayerParentLocation));
809         // Use the same size as m_graphicsLayer so transforms behave correctly.
810         m_contentsContainmentLayer->setSize(contentsSize);
811         graphicsLayerParentLocation = enclosingRelativeCompositingBounds.location();
812     }
813
814     m_graphicsLayer->setPosition(FloatPoint(enclosingRelativeCompositingBounds.location() - graphicsLayerParentLocation));
815     m_graphicsLayer->setSize(contentsSize);
816     if (devicePixelOffsetFromRenderer != m_graphicsLayer->offsetFromRenderer()) {
817         m_graphicsLayer->setOffsetFromRenderer(devicePixelOffsetFromRenderer);
818         positionOverflowControlsLayers();
819     }
820
821     if (!m_isMainFrameRenderViewLayer) {
822         // For non-root layers, background is always painted by the primary graphics layer.
823         ASSERT(!m_backgroundLayer);
824         bool hadSubpixelRounding = !m_devicePixelFractionFromRenderer.isZero();
825         m_graphicsLayer->setContentsOpaque(!hadSubpixelRounding && m_owningLayer.backgroundIsKnownToBeOpaqueInRect(localCompositingBounds));
826     }
827
828     // If we have a layer that clips children, position it.
829     LayoutRect clippingBox;
830     if (GraphicsLayer* clipLayer = clippingLayer()) {
831         clippingBox = clipBox(toRenderBox(renderer()));
832         clipLayer->setPosition(FloatPoint(clippingBox.location() - localCompositingBounds.location()));
833         clipLayer->setSize(clippingBox.size());
834         clipLayer->setOffsetFromRenderer(toFloatSize(clippingBox.location()));
835     }
836     
837     if (m_maskLayer) {
838         m_maskLayer->setSize(m_graphicsLayer->size());
839         m_maskLayer->setPosition(FloatPoint());
840         m_maskLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
841     }
842     
843     if (m_owningLayer.hasTransform()) {
844         const LayoutRect borderBox = toRenderBox(renderer()).pixelSnappedBorderBoxRect();
845
846         // Get layout bounds in the coords of compAncestor to match relativeCompositingBounds.
847         LayoutRect layerBounds(offsetFromParent, borderBox.size());
848
849         // Update properties that depend on layer dimensions
850         FloatPoint3D transformOrigin = computeTransformOrigin(borderBox);
851         // Compute the anchor point, which is in the center of the renderer box unless transform-origin is set.
852         FloatPoint3D anchor(enclosingRelativeCompositingBounds.width() != 0.0f ? ((layerBounds.x() - enclosingRelativeCompositingBounds.x()) + transformOrigin.x())
853             / enclosingRelativeCompositingBounds.width() : 0.5f, enclosingRelativeCompositingBounds.height() != 0.0f ? ((layerBounds.y() - enclosingRelativeCompositingBounds.y())
854             + transformOrigin.y()) / enclosingRelativeCompositingBounds.height() : 0.5f, transformOrigin.z());
855         if (m_contentsContainmentLayer)
856             m_contentsContainmentLayer->setAnchorPoint(anchor);
857         else
858             m_graphicsLayer->setAnchorPoint(anchor);
859
860         const RenderStyle& style = renderer().style();
861         GraphicsLayer* clipLayer = clippingLayer();
862         if (style.hasPerspective()) {
863             TransformationMatrix t = owningLayer().perspectiveTransform();
864             
865             if (clipLayer) {
866                 clipLayer->setChildrenTransform(t);
867                 m_graphicsLayer->setChildrenTransform(TransformationMatrix());
868             }
869             else
870                 m_graphicsLayer->setChildrenTransform(t);
871         } else {
872             if (clipLayer)
873                 clipLayer->setChildrenTransform(TransformationMatrix());
874             else
875                 m_graphicsLayer->setChildrenTransform(TransformationMatrix());
876         }
877     } else {
878         m_graphicsLayer->setAnchorPoint(FloatPoint3D(0.5f, 0.5f, 0));
879         if (m_contentsContainmentLayer)
880             m_contentsContainmentLayer->setAnchorPoint(FloatPoint3D(0.5f, 0.5f, 0));
881     }
882
883     if (m_foregroundLayer) {
884         FloatPoint foregroundPosition;
885         FloatSize foregroundSize = contentsSize;
886         FloatSize foregroundOffset = m_graphicsLayer->offsetFromRenderer();
887         if (hasClippingLayer()) {
888             // If we have a clipping layer (which clips descendants), then the foreground layer is a child of it,
889             // so that it gets correctly sorted with children. In that case, position relative to the clipping layer.
890             foregroundSize = FloatSize(clippingBox.size());
891             foregroundOffset = toFloatSize(clippingBox.location());
892         }
893
894         m_foregroundLayer->setPosition(foregroundPosition);
895         m_foregroundLayer->setSize(foregroundSize);
896         m_foregroundLayer->setOffsetFromRenderer(foregroundOffset);
897     }
898
899     if (m_backgroundLayer) {
900         FloatPoint backgroundPosition;
901         FloatSize backgroundSize = contentsSize;
902         if (backgroundLayerPaintsFixedRootBackground()) {
903             const FrameView& frameView = renderer().view().frameView();
904             backgroundPosition = toLayoutPoint(frameView.scrollOffsetForFixedPosition());
905             backgroundSize = frameView.visibleContentRect().size();
906         }
907         m_backgroundLayer->setPosition(backgroundPosition);
908         m_backgroundLayer->setSize(backgroundSize);
909         m_backgroundLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
910     }
911
912     if (m_owningLayer.reflectionLayer() && m_owningLayer.reflectionLayer()->isComposited()) {
913         RenderLayerBacking* reflectionBacking = m_owningLayer.reflectionLayer()->backing();
914         reflectionBacking->updateGraphicsLayerGeometry();
915         
916         // The reflection layer has the bounds of m_owningLayer.reflectionLayer(),
917         // but the reflected layer is the bounds of this layer, so we need to position it appropriately.
918         FloatRect layerBounds = compositedBounds();
919         FloatRect reflectionLayerBounds = reflectionBacking->compositedBounds();
920         reflectionBacking->graphicsLayer()->setReplicatedLayerPosition(FloatPoint(layerBounds.location() - reflectionLayerBounds.location()));
921     }
922
923     if (m_scrollingLayer) {
924         ASSERT(m_scrollingContentsLayer);
925         RenderBox& renderBox = toRenderBox(renderer());
926         LayoutRect paddingBox(renderBox.borderLeft(), renderBox.borderTop(), renderBox.width() - renderBox.borderLeft() - renderBox.borderRight(), renderBox.height() - renderBox.borderTop() - renderBox.borderBottom());
927         LayoutSize scrollOffset = m_owningLayer.scrollOffset();
928
929         m_scrollingLayer->setPosition(FloatPoint(paddingBox.location() - localCompositingBounds.location()));
930
931         m_scrollingLayer->setSize(paddingBox.size());
932 #if PLATFORM(IOS)
933         FloatSize oldScrollingLayerOffset = m_scrollingLayer->offsetFromRenderer();
934         m_scrollingLayer->setOffsetFromRenderer(FloatPoint() - paddingBox.location());
935         bool paddingBoxOffsetChanged = oldScrollingLayerOffset != m_scrollingLayer->offsetFromRenderer();
936
937         if (m_owningLayer.isInUserScroll()) {
938             // If scrolling is happening externally, we don't want to touch the layer bounds origin here because that will cause
939             // jitter. Set a flag to ensure that we sync up later.
940             m_owningLayer.setRequiresScrollBoundsOriginUpdate(true);
941         } else {
942             // Note that we implement the contents offset via the bounds origin on this layer, rather than a position on the sublayer.
943             m_scrollingLayer->setBoundsOrigin(FloatPoint(scrollOffset.width(), scrollOffset.height()));
944             m_owningLayer.setRequiresScrollBoundsOriginUpdate(false);
945         }
946         
947         IntSize scrollSize(m_owningLayer.scrollWidth(), m_owningLayer.scrollHeight());
948
949         m_scrollingContentsLayer->setPosition(FloatPoint());
950         
951         if (scrollSize != m_scrollingContentsLayer->size() || paddingBoxOffsetChanged)
952             m_scrollingContentsLayer->setNeedsDisplay();
953
954         m_scrollingContentsLayer->setSize(scrollSize);
955         // Scrolling the content layer does not need to trigger a repaint. The offset will be compensated away during painting.
956         // FIXME: The paint offset and the scroll offset should really be separate concepts.
957         m_scrollingContentsLayer->setOffsetFromRenderer(paddingBox.location() - IntPoint() - scrollOffset, GraphicsLayer::DontSetNeedsDisplay);
958 #else
959         m_scrollingContentsLayer->setPosition(FloatPoint(-scrollOffset.width(), -scrollOffset.height()));
960
961         FloatSize oldScrollingLayerOffset = m_scrollingLayer->offsetFromRenderer();
962         m_scrollingLayer->setOffsetFromRenderer(-toFloatSize(paddingBox.location()));
963
964         bool paddingBoxOffsetChanged = oldScrollingLayerOffset != m_scrollingLayer->offsetFromRenderer();
965
966         IntSize scrollSize(m_owningLayer.scrollWidth(), m_owningLayer.scrollHeight());
967         if (scrollSize != m_scrollingContentsLayer->size() || paddingBoxOffsetChanged)
968             m_scrollingContentsLayer->setNeedsDisplay();
969
970         LayoutSize scrollingContentsOffset = toLayoutSize(paddingBox.location() - scrollOffset);
971         if (scrollingContentsOffset != m_scrollingContentsLayer->offsetFromRenderer() || scrollSize != m_scrollingContentsLayer->size())
972             compositor().scrollingLayerDidChange(m_owningLayer);
973
974         m_scrollingContentsLayer->setSize(scrollSize);
975         // FIXME: The paint offset and the scroll offset should really be separate concepts.
976         m_scrollingContentsLayer->setOffsetFromRenderer(scrollingContentsOffset, GraphicsLayer::DontSetNeedsDisplay);
977 #endif
978
979         if (m_foregroundLayer) {
980             m_foregroundLayer->setSize(m_scrollingContentsLayer->size());
981             m_foregroundLayer->setOffsetFromRenderer(m_scrollingContentsLayer->offsetFromRenderer());
982         }
983     }
984
985     // If this layer was created just for clipping or to apply perspective, it doesn't need its own backing store.
986     setRequiresOwnBackingStore(compositor().requiresOwnBackingStore(m_owningLayer, compAncestor, enclosingRelativeCompositingBounds, ancestorCompositingBounds));
987
988     bool didUpdateContentsRect = false;
989     updateDirectlyCompositedContents(isSimpleContainer, didUpdateContentsRect);
990     if (!didUpdateContentsRect && m_graphicsLayer->hasContentsLayer())
991         resetContentsRect();
992
993     updateDrawsContent(isSimpleContainer);
994     updateAfterWidgetResize();
995
996     compositor().updateScrollCoordinatedStatus(m_owningLayer);
997 }
998
999 void RenderLayerBacking::adjustAncestorCompositingBoundsForFlowThread(LayoutRect& ancestorCompositingBounds, const RenderLayer* compositingAncestor) const
1000 {
1001     if (!m_owningLayer.isInsideFlowThread())
1002         return;
1003
1004     RenderLayer* flowThreadLayer = m_owningLayer.isInsideOutOfFlowThread() ? m_owningLayer.stackingContainer() : m_owningLayer.enclosingFlowThreadAncestor();
1005     if (flowThreadLayer && flowThreadLayer->isRenderFlowThread()) {
1006         if (m_owningLayer.isFlowThreadCollectingGraphicsLayersUnderRegions()) {
1007             // The RenderNamedFlowThread is not composited, as we need it to paint the 
1008             // background layer of the regions. We need to compensate for that by manually
1009             // subtracting the position of the flow-thread.
1010             IntPoint flowPosition;
1011             flowThreadLayer->convertToPixelSnappedLayerCoords(compositingAncestor, flowPosition);
1012             ancestorCompositingBounds.moveBy(flowPosition);
1013         }
1014
1015         // Move the ancestor position at the top of the region where the composited layer is going to display.
1016         RenderFlowThread& flowThread = toRenderFlowThread(flowThreadLayer->renderer());
1017         RenderNamedFlowFragment* parentRegion = flowThread.cachedRegionForCompositedLayer(m_owningLayer);
1018         if (!parentRegion)
1019             return;
1020
1021         IntPoint flowDelta;
1022         m_owningLayer.convertToPixelSnappedLayerCoords(flowThreadLayer, flowDelta);
1023         parentRegion->adjustRegionBoundsFromFlowThreadPortionRect(flowDelta, ancestorCompositingBounds);
1024         RenderBoxModelObject& layerOwner = toRenderBoxModelObject(parentRegion->layerOwner());
1025         RenderLayerBacking* layerOwnerBacking = layerOwner.layer()->backing();
1026         if (!layerOwnerBacking)
1027             return;
1028
1029         // Make sure that the region propagates its borders, paddings, outlines or box-shadows to layers inside it.
1030         // Note that the composited bounds of the RenderRegion are already calculated because
1031         // RenderLayerCompositor::rebuildCompositingLayerTree will only iterate on the content of the region after the
1032         // region itself is computed.
1033         ancestorCompositingBounds.moveBy(roundedIntPoint(layerOwnerBacking->compositedBounds().location()));
1034         ancestorCompositingBounds.move(-layerOwner.borderAndPaddingStart(), -layerOwner.borderAndPaddingBefore());
1035
1036         // If there's a clipping GraphicsLayer on the hierarchy (region graphics layer -> clipping graphics layer ->
1037         // composited content graphics layer), substract the offset of the clipping layer, since it's its parent
1038         // that positions us (the graphics layer of the region).
1039         if (layerOwnerBacking->clippingLayer())
1040             ancestorCompositingBounds.moveBy(roundedIntPoint(layerOwnerBacking->clippingLayer()->position()));
1041     }
1042 }
1043
1044 void RenderLayerBacking::updateDirectlyCompositedContents(bool isSimpleContainer, bool& didUpdateContentsRect)
1045 {
1046     if (!m_owningLayer.hasVisibleContent())
1047         return;
1048
1049     // The order of operations here matters, since the last valid type of contents needs
1050     // to also update the contentsRect.
1051     updateDirectlyCompositedBackgroundColor(isSimpleContainer, didUpdateContentsRect);
1052     updateDirectlyCompositedBackgroundImage(isSimpleContainer, didUpdateContentsRect);
1053 }
1054
1055 void RenderLayerBacking::updateInternalHierarchy()
1056 {
1057     // m_foregroundLayer has to be inserted in the correct order with child layers,
1058     // so it's not inserted here.
1059     if (m_ancestorClippingLayer)
1060         m_ancestorClippingLayer->removeAllChildren();
1061     
1062     if (m_contentsContainmentLayer) {
1063         m_contentsContainmentLayer->removeAllChildren();
1064         if (m_ancestorClippingLayer)
1065             m_ancestorClippingLayer->addChild(m_contentsContainmentLayer.get());
1066     }
1067     
1068     if (m_backgroundLayer)
1069         m_contentsContainmentLayer->addChild(m_backgroundLayer.get());
1070
1071     if (m_contentsContainmentLayer)
1072         m_contentsContainmentLayer->addChild(m_graphicsLayer.get());
1073     else if (m_ancestorClippingLayer)
1074         m_ancestorClippingLayer->addChild(m_graphicsLayer.get());
1075
1076     if (m_childContainmentLayer) {
1077         m_childContainmentLayer->removeFromParent();
1078         m_graphicsLayer->addChild(m_childContainmentLayer.get());
1079     }
1080
1081     if (m_scrollingLayer) {
1082         GraphicsLayer* superlayer = m_childContainmentLayer ? m_childContainmentLayer.get() : m_graphicsLayer.get();
1083         m_scrollingLayer->removeFromParent();
1084         superlayer->addChild(m_scrollingLayer.get());
1085     }
1086
1087     // The clip for child layers does not include space for overflow controls, so they exist as
1088     // siblings of the clipping layer if we have one. Normal children of this layer are set as
1089     // children of the clipping layer.
1090     if (m_layerForHorizontalScrollbar) {
1091         m_layerForHorizontalScrollbar->removeFromParent();
1092         m_graphicsLayer->addChild(m_layerForHorizontalScrollbar.get());
1093     }
1094     if (m_layerForVerticalScrollbar) {
1095         m_layerForVerticalScrollbar->removeFromParent();
1096         m_graphicsLayer->addChild(m_layerForVerticalScrollbar.get());
1097     }
1098     if (m_layerForScrollCorner) {
1099         m_layerForScrollCorner->removeFromParent();
1100         m_graphicsLayer->addChild(m_layerForScrollCorner.get());
1101     }
1102 }
1103
1104 void RenderLayerBacking::resetContentsRect()
1105 {
1106     m_graphicsLayer->setContentsRect(pixelSnappedIntRect(contentsBox()));
1107     
1108     LayoutRect contentsClippingRect;
1109     if (renderer().isBox())
1110         contentsClippingRect = toRenderBox(renderer()).contentBoxRect();
1111
1112     contentsClippingRect.move(contentOffsetInCompostingLayer());
1113     m_graphicsLayer->setContentsClippingRect(pixelSnappedIntRect(contentsClippingRect));
1114
1115     m_graphicsLayer->setContentsTileSize(IntSize());
1116     m_graphicsLayer->setContentsTilePhase(IntPoint());
1117 }
1118
1119 void RenderLayerBacking::updateDrawsContent()
1120 {
1121     updateDrawsContent(isSimpleContainerCompositingLayer());
1122 }
1123
1124 void RenderLayerBacking::updateDrawsContent(bool isSimpleContainer)
1125 {
1126     if (m_scrollingLayer) {
1127         // We don't have to consider overflow controls, because we know that the scrollbars are drawn elsewhere.
1128         // m_graphicsLayer only needs backing store if the non-scrolling parts (background, outlines, borders, shadows etc) need to paint.
1129         // m_scrollingLayer never has backing store.
1130         // m_scrollingContentsLayer only needs backing store if the scrolled contents need to paint.
1131         bool hasNonScrollingPaintedContent = m_owningLayer.hasVisibleContent() && m_owningLayer.hasBoxDecorationsOrBackground();
1132         m_graphicsLayer->setDrawsContent(hasNonScrollingPaintedContent);
1133
1134         bool hasScrollingPaintedContent = m_owningLayer.hasVisibleContent() && (renderer().hasBackground() || paintsChildren());
1135         m_scrollingContentsLayer->setDrawsContent(hasScrollingPaintedContent);
1136         return;
1137     }
1138
1139     bool hasPaintedContent = containsPaintedContent(isSimpleContainer);
1140
1141     // FIXME: we could refine this to only allocate backing for one of these layers if possible.
1142     m_graphicsLayer->setDrawsContent(hasPaintedContent);
1143     if (m_foregroundLayer)
1144         m_foregroundLayer->setDrawsContent(hasPaintedContent);
1145
1146     if (m_backgroundLayer)
1147         m_backgroundLayer->setDrawsContent(hasPaintedContent);
1148 }
1149
1150 // Return true if the layer changed.
1151 bool RenderLayerBacking::updateAncestorClippingLayer(bool needsAncestorClip)
1152 {
1153     bool layersChanged = false;
1154
1155     if (needsAncestorClip) {
1156         if (!m_ancestorClippingLayer) {
1157             m_ancestorClippingLayer = createGraphicsLayer("Ancestor clipping Layer");
1158             m_ancestorClippingLayer->setMasksToBounds(true);
1159             layersChanged = true;
1160         }
1161     } else if (hasAncestorClippingLayer()) {
1162         willDestroyLayer(m_ancestorClippingLayer.get());
1163         m_ancestorClippingLayer->removeFromParent();
1164         m_ancestorClippingLayer = nullptr;
1165         layersChanged = true;
1166     }
1167     
1168     return layersChanged;
1169 }
1170
1171 // Return true if the layer changed.
1172 bool RenderLayerBacking::updateDescendantClippingLayer(bool needsDescendantClip)
1173 {
1174     bool layersChanged = false;
1175
1176     if (needsDescendantClip) {
1177         if (!m_childContainmentLayer && !m_usingTiledCacheLayer) {
1178             m_childContainmentLayer = createGraphicsLayer("Child clipping Layer");
1179             m_childContainmentLayer->setMasksToBounds(true);
1180             layersChanged = true;
1181         }
1182     } else if (hasClippingLayer()) {
1183         willDestroyLayer(m_childContainmentLayer.get());
1184         m_childContainmentLayer->removeFromParent();
1185         m_childContainmentLayer = nullptr;
1186         layersChanged = true;
1187     }
1188     
1189     return layersChanged;
1190 }
1191
1192 void RenderLayerBacking::setBackgroundLayerPaintsFixedRootBackground(bool backgroundLayerPaintsFixedRootBackground)
1193 {
1194     m_backgroundLayerPaintsFixedRootBackground = backgroundLayerPaintsFixedRootBackground;
1195 }
1196
1197 bool RenderLayerBacking::requiresHorizontalScrollbarLayer() const
1198 {
1199     if (!m_owningLayer.hasOverlayScrollbars() && !m_owningLayer.needsCompositedScrolling())
1200         return false;
1201     return m_owningLayer.horizontalScrollbar();
1202 }
1203
1204 bool RenderLayerBacking::requiresVerticalScrollbarLayer() const
1205 {
1206     if (!m_owningLayer.hasOverlayScrollbars() && !m_owningLayer.needsCompositedScrolling())
1207         return false;
1208     return m_owningLayer.verticalScrollbar();
1209 }
1210
1211 bool RenderLayerBacking::requiresScrollCornerLayer() const
1212 {
1213     if (!m_owningLayer.hasOverlayScrollbars() && !m_owningLayer.needsCompositedScrolling())
1214         return false;
1215     return !m_owningLayer.scrollCornerAndResizerRect().isEmpty();
1216 }
1217
1218 bool RenderLayerBacking::updateOverflowControlsLayers(bool needsHorizontalScrollbarLayer, bool needsVerticalScrollbarLayer, bool needsScrollCornerLayer)
1219 {
1220     bool horizontalScrollbarLayerChanged = false;
1221     if (needsHorizontalScrollbarLayer) {
1222         if (!m_layerForHorizontalScrollbar) {
1223             m_layerForHorizontalScrollbar = createGraphicsLayer("horizontal scrollbar");
1224             horizontalScrollbarLayerChanged = true;
1225         }
1226     } else if (m_layerForHorizontalScrollbar) {
1227         willDestroyLayer(m_layerForHorizontalScrollbar.get());
1228         m_layerForHorizontalScrollbar = nullptr;
1229         horizontalScrollbarLayerChanged = true;
1230     }
1231
1232     bool verticalScrollbarLayerChanged = false;
1233     if (needsVerticalScrollbarLayer) {
1234         if (!m_layerForVerticalScrollbar) {
1235             m_layerForVerticalScrollbar = createGraphicsLayer("vertical scrollbar");
1236             verticalScrollbarLayerChanged = true;
1237         }
1238     } else if (m_layerForVerticalScrollbar) {
1239         willDestroyLayer(m_layerForVerticalScrollbar.get());
1240         m_layerForVerticalScrollbar = nullptr;
1241         verticalScrollbarLayerChanged = true;
1242     }
1243
1244     bool scrollCornerLayerChanged = false;
1245     if (needsScrollCornerLayer) {
1246         if (!m_layerForScrollCorner) {
1247             m_layerForScrollCorner = createGraphicsLayer("scroll corner");
1248             scrollCornerLayerChanged = true;
1249         }
1250     } else if (m_layerForScrollCorner) {
1251         willDestroyLayer(m_layerForScrollCorner.get());
1252         m_layerForScrollCorner = nullptr;
1253         scrollCornerLayerChanged = true;
1254     }
1255
1256     if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer)) {
1257         if (horizontalScrollbarLayerChanged)
1258             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_owningLayer, HorizontalScrollbar);
1259         if (verticalScrollbarLayerChanged)
1260             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_owningLayer, VerticalScrollbar);
1261     }
1262
1263     return horizontalScrollbarLayerChanged || verticalScrollbarLayerChanged || scrollCornerLayerChanged;
1264 }
1265
1266 void RenderLayerBacking::positionOverflowControlsLayers()
1267 {
1268     if (!m_owningLayer.hasScrollbars())
1269         return;
1270
1271     const IntRect borderBox = toRenderBox(renderer()).pixelSnappedBorderBoxRect();
1272
1273     FloatSize offsetFromRenderer = m_graphicsLayer->offsetFromRenderer();
1274     if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
1275         IntRect hBarRect = m_owningLayer.rectForHorizontalScrollbar(borderBox);
1276         layer->setPosition(hBarRect.location() - offsetFromRenderer);
1277         layer->setSize(hBarRect.size());
1278         if (layer->hasContentsLayer()) {
1279             IntRect barRect = IntRect(IntPoint(), hBarRect.size());
1280             layer->setContentsRect(barRect);
1281             layer->setContentsClippingRect(barRect);
1282         }
1283         layer->setDrawsContent(m_owningLayer.horizontalScrollbar() && !layer->hasContentsLayer());
1284     }
1285     
1286     if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
1287         IntRect vBarRect = m_owningLayer.rectForVerticalScrollbar(borderBox);
1288         layer->setPosition(vBarRect.location() - offsetFromRenderer);
1289         layer->setSize(vBarRect.size());
1290         if (layer->hasContentsLayer()) {
1291             IntRect barRect = IntRect(IntPoint(), vBarRect.size());
1292             layer->setContentsRect(barRect);
1293             layer->setContentsClippingRect(barRect);
1294         }
1295         layer->setDrawsContent(m_owningLayer.verticalScrollbar() && !layer->hasContentsLayer());
1296     }
1297
1298     if (GraphicsLayer* layer = layerForScrollCorner()) {
1299         const LayoutRect& scrollCornerAndResizer = m_owningLayer.scrollCornerAndResizerRect();
1300         layer->setPosition(scrollCornerAndResizer.location() - offsetFromRenderer);
1301         layer->setSize(scrollCornerAndResizer.size());
1302         layer->setDrawsContent(!scrollCornerAndResizer.isEmpty());
1303     }
1304 }
1305
1306 bool RenderLayerBacking::hasUnpositionedOverflowControlsLayers() const
1307 {
1308     if (GraphicsLayer* layer = layerForHorizontalScrollbar())
1309         if (!layer->drawsContent())
1310             return true;
1311
1312     if (GraphicsLayer* layer = layerForVerticalScrollbar())
1313         if (!layer->drawsContent())
1314             return true;
1315
1316     if (GraphicsLayer* layer = layerForScrollCorner())
1317         if (!layer->drawsContent())
1318             return true;
1319
1320     return false;
1321 }
1322
1323 bool RenderLayerBacking::updateForegroundLayer(bool needsForegroundLayer)
1324 {
1325     bool layerChanged = false;
1326     if (needsForegroundLayer) {
1327         if (!m_foregroundLayer) {
1328             String layerName;
1329 #ifndef NDEBUG
1330             layerName = m_owningLayer.name() + " (foreground)";
1331 #endif
1332             m_foregroundLayer = createGraphicsLayer(layerName);
1333             m_foregroundLayer->setDrawsContent(true);
1334             m_foregroundLayer->setPaintingPhase(GraphicsLayerPaintForeground);
1335             layerChanged = true;
1336         }
1337     } else if (m_foregroundLayer) {
1338         willDestroyLayer(m_foregroundLayer.get());
1339         m_foregroundLayer->removeFromParent();
1340         m_foregroundLayer = nullptr;
1341         layerChanged = true;
1342     }
1343
1344     if (layerChanged) {
1345         m_graphicsLayer->setNeedsDisplay();
1346         m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
1347     }
1348
1349     return layerChanged;
1350 }
1351
1352 bool RenderLayerBacking::updateBackgroundLayer(bool needsBackgroundLayer)
1353 {
1354     bool layerChanged = false;
1355     if (needsBackgroundLayer) {
1356         if (!m_backgroundLayer) {
1357             String layerName;
1358 #ifndef NDEBUG
1359             layerName = m_owningLayer.name() + " (background)";
1360 #endif
1361             m_backgroundLayer = createGraphicsLayer(layerName);
1362             m_backgroundLayer->setDrawsContent(true);
1363             m_backgroundLayer->setAnchorPoint(FloatPoint3D());
1364             m_backgroundLayer->setPaintingPhase(GraphicsLayerPaintBackground);
1365             layerChanged = true;
1366         }
1367         
1368         if (!m_contentsContainmentLayer) {
1369             String layerName;
1370 #ifndef NDEBUG
1371             layerName = m_owningLayer.name() + " (contents containment)";
1372 #endif
1373             m_contentsContainmentLayer = createGraphicsLayer(layerName);
1374             m_contentsContainmentLayer->setAppliesPageScale(true);
1375             m_graphicsLayer->setAppliesPageScale(false);
1376             layerChanged = true;
1377         }
1378     } else {
1379         if (m_backgroundLayer) {
1380             willDestroyLayer(m_backgroundLayer.get());
1381             m_backgroundLayer->removeFromParent();
1382             m_backgroundLayer = nullptr;
1383             layerChanged = true;
1384         }
1385         if (m_contentsContainmentLayer) {
1386             willDestroyLayer(m_contentsContainmentLayer.get());
1387             m_contentsContainmentLayer->removeFromParent();
1388             m_contentsContainmentLayer = nullptr;
1389             layerChanged = true;
1390             m_graphicsLayer->setAppliesPageScale(true);
1391         }
1392     }
1393     
1394     if (layerChanged) {
1395         m_graphicsLayer->setNeedsDisplay();
1396         // This assumes that the background layer is only used for fixed backgrounds, which is currently a correct assumption.
1397         compositor().fixedRootBackgroundLayerChanged();
1398     }
1399     
1400     return layerChanged;
1401 }
1402
1403 bool RenderLayerBacking::updateMaskLayer(bool needsMaskLayer)
1404 {
1405     bool layerChanged = false;
1406     if (needsMaskLayer) {
1407         if (!m_maskLayer) {
1408             m_maskLayer = createGraphicsLayer("Mask");
1409             m_maskLayer->setDrawsContent(true);
1410             m_maskLayer->setPaintingPhase(GraphicsLayerPaintMask);
1411             layerChanged = true;
1412         }
1413     } else if (m_maskLayer) {
1414         willDestroyLayer(m_maskLayer.get());
1415         m_maskLayer = nullptr;
1416         layerChanged = true;
1417     }
1418
1419     if (layerChanged)
1420         m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
1421
1422     return layerChanged;
1423 }
1424
1425 bool RenderLayerBacking::updateScrollingLayers(bool needsScrollingLayers)
1426 {
1427     if (needsScrollingLayers == !!m_scrollingLayer)
1428         return false;
1429
1430     if (!m_scrollingLayer) {
1431         // Outer layer which corresponds with the scroll view.
1432         m_scrollingLayer = createGraphicsLayer("Scrolling container");
1433         m_scrollingLayer->setDrawsContent(false);
1434         m_scrollingLayer->setMasksToBounds(true);
1435
1436         // Inner layer which renders the content that scrolls.
1437         m_scrollingContentsLayer = createGraphicsLayer("Scrolled Contents");
1438         m_scrollingContentsLayer->setDrawsContent(true);
1439         GraphicsLayerPaintingPhase paintPhase = GraphicsLayerPaintOverflowContents | GraphicsLayerPaintCompositedScroll;
1440         if (!m_foregroundLayer)
1441             paintPhase |= GraphicsLayerPaintForeground;
1442         m_scrollingContentsLayer->setPaintingPhase(paintPhase);
1443         m_scrollingLayer->addChild(m_scrollingContentsLayer.get());
1444     } else {
1445         compositor().willRemoveScrollingLayer(m_owningLayer);
1446
1447         willDestroyLayer(m_scrollingLayer.get());
1448         willDestroyLayer(m_scrollingContentsLayer.get());
1449         m_scrollingLayer = nullptr;
1450         m_scrollingContentsLayer = nullptr;
1451     }
1452
1453     updateInternalHierarchy();
1454     m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
1455     m_graphicsLayer->setNeedsDisplay(); // Because painting phases changed.
1456
1457     if (m_scrollingLayer)
1458         compositor().didAddScrollingLayer(m_owningLayer);
1459     
1460     return true;
1461 }
1462
1463 void RenderLayerBacking::detachFromScrollingCoordinator()
1464 {
1465     if (!m_scrollingNodeID && !m_viewportConstrainedNodeID)
1466         return;
1467
1468     ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer);
1469     if (!scrollingCoordinator)
1470         return;
1471
1472     if (m_scrollingNodeID)
1473         scrollingCoordinator->detachFromStateTree(m_scrollingNodeID);
1474
1475     if (m_viewportConstrainedNodeID)
1476         scrollingCoordinator->detachFromStateTree(m_viewportConstrainedNodeID);
1477
1478     m_scrollingNodeID = 0;
1479     m_viewportConstrainedNodeID = 0;
1480 }
1481
1482 GraphicsLayerPaintingPhase RenderLayerBacking::paintingPhaseForPrimaryLayer() const
1483 {
1484     unsigned phase = 0;
1485     if (!m_backgroundLayer)
1486         phase |= GraphicsLayerPaintBackground;
1487     if (!m_foregroundLayer)
1488         phase |= GraphicsLayerPaintForeground;
1489     if (!m_maskLayer)
1490         phase |= GraphicsLayerPaintMask;
1491
1492     if (m_scrollingContentsLayer) {
1493         phase &= ~GraphicsLayerPaintForeground;
1494         phase |= GraphicsLayerPaintCompositedScroll;
1495     }
1496
1497     return static_cast<GraphicsLayerPaintingPhase>(phase);
1498 }
1499
1500 float RenderLayerBacking::compositingOpacity(float rendererOpacity) const
1501 {
1502     float finalOpacity = rendererOpacity;
1503     
1504     for (RenderLayer* curr = m_owningLayer.parent(); curr; curr = curr->parent()) {
1505         // We only care about parents that are stacking contexts.
1506         // Recall that opacity creates stacking context.
1507         if (!curr->isStackingContainer())
1508             continue;
1509         
1510         // If we found a compositing layer, we want to compute opacity
1511         // relative to it. So we can break here.
1512         if (curr->isComposited())
1513             break;
1514         
1515         finalOpacity *= curr->renderer().opacity();
1516     }
1517
1518     return finalOpacity;
1519 }
1520
1521 static bool hasBoxDecorations(const RenderStyle* style)
1522 {
1523     return style->hasBorder() || style->hasBorderRadius() || style->hasOutline() || style->hasAppearance() || style->boxShadow() || style->hasFilter();
1524 }
1525
1526 static bool canCreateTiledImage(const RenderStyle*);
1527
1528 static bool hasBoxDecorationsOrBackgroundImage(const RenderStyle* style)
1529 {
1530     if (hasBoxDecorations(style))
1531         return true;
1532
1533     if (!style->hasBackgroundImage())
1534         return false;
1535
1536     return !GraphicsLayer::supportsContentsTiling() || !canCreateTiledImage(style);
1537 }
1538
1539 static bool hasPerspectiveOrPreserves3D(const RenderStyle* style)
1540 {
1541     return style->hasPerspective() || style->preserves3D();
1542 }
1543
1544 Color RenderLayerBacking::rendererBackgroundColor() const
1545 {
1546     const auto& backgroundRenderer = renderer().isRoot() ? renderer().rendererForRootBackground() : renderer();
1547     return backgroundRenderer.style().visitedDependentColor(CSSPropertyBackgroundColor);
1548 }
1549
1550 void RenderLayerBacking::updateDirectlyCompositedBackgroundColor(bool isSimpleContainer, bool& didUpdateContentsRect)
1551 {
1552     if (!isSimpleContainer) {
1553         m_graphicsLayer->setContentsToSolidColor(Color());
1554         return;
1555     }
1556
1557     Color backgroundColor = rendererBackgroundColor();
1558
1559     // An unset (invalid) color will remove the solid color.
1560     m_graphicsLayer->setContentsToSolidColor(backgroundColor);
1561     FloatRect contentsRect = backgroundBoxForPainting();
1562     m_graphicsLayer->setContentsRect(contentsRect);
1563     m_graphicsLayer->setContentsClippingRect(contentsRect);
1564     didUpdateContentsRect = true;
1565 }
1566
1567 bool canCreateTiledImage(const RenderStyle* style)
1568 {
1569     const FillLayer* fillLayer = style->backgroundLayers();
1570     if (fillLayer->next())
1571         return false;
1572
1573     if (!fillLayer->imagesAreLoaded())
1574         return false;
1575
1576     if (fillLayer->attachment() != ScrollBackgroundAttachment)
1577         return false;
1578
1579     Color color = style->visitedDependentColor(CSSPropertyBackgroundColor);
1580
1581     // FIXME: Allow color+image compositing when it makes sense.
1582     // For now bailing out.
1583     if (color.isValid() && color.alpha())
1584         return false;
1585
1586     StyleImage* styleImage = fillLayer->image();
1587
1588     // FIXME: support gradients with isGeneratedImage.
1589     if (!styleImage->isCachedImage())
1590         return false;
1591
1592     Image* image = styleImage->cachedImage()->image();
1593     if (!image->isBitmapImage())
1594         return false;
1595
1596     return true;
1597 }
1598
1599 void RenderLayerBacking::updateDirectlyCompositedBackgroundImage(bool isSimpleContainer, bool& didUpdateContentsRect)
1600 {
1601     if (!GraphicsLayer::supportsContentsTiling())
1602         return;
1603
1604     if (isDirectlyCompositedImage())
1605         return;
1606
1607     const RenderStyle& style = renderer().style();
1608
1609     if (!isSimpleContainer || !style.hasBackgroundImage()) {
1610         m_graphicsLayer->setContentsToImage(0);
1611         return;
1612     }
1613
1614     IntRect destRect = pixelSnappedIntRect(LayoutRect(backgroundBoxForPainting()));
1615     IntPoint phase;
1616     IntSize tileSize;
1617
1618     RefPtr<Image> image = style.backgroundLayers()->image()->cachedImage()->image();
1619     toRenderBox(renderer()).getGeometryForBackgroundImage(&m_owningLayer.renderer(), destRect, phase, tileSize);
1620     m_graphicsLayer->setContentsTileSize(tileSize);
1621     m_graphicsLayer->setContentsTilePhase(phase);
1622     m_graphicsLayer->setContentsRect(destRect);
1623     m_graphicsLayer->setContentsClippingRect(destRect);
1624     m_graphicsLayer->setContentsToImage(image.get());
1625     didUpdateContentsRect = true;
1626 }
1627
1628 void RenderLayerBacking::updateRootLayerConfiguration()
1629 {
1630     if (!m_usingTiledCacheLayer)
1631         return;
1632
1633     Color backgroundColor;
1634     bool viewIsTransparent = compositor().viewHasTransparentBackground(&backgroundColor);
1635
1636     if (m_backgroundLayerPaintsFixedRootBackground && m_backgroundLayer) {
1637         m_backgroundLayer->setBackgroundColor(backgroundColor);
1638         m_backgroundLayer->setContentsOpaque(!viewIsTransparent);
1639
1640         m_graphicsLayer->setBackgroundColor(Color());
1641         m_graphicsLayer->setContentsOpaque(false);
1642     } else {
1643         m_graphicsLayer->setBackgroundColor(backgroundColor);
1644         m_graphicsLayer->setContentsOpaque(!viewIsTransparent);
1645     }
1646 }
1647
1648 static bool supportsDirectBoxDecorationsComposition(const RenderLayerModelObject& renderer)
1649 {
1650     if (!GraphicsLayer::supportsBackgroundColorContent())
1651         return false;
1652
1653     if (renderer.hasClip())
1654         return false;
1655
1656     if (hasBoxDecorationsOrBackgroundImage(&renderer.style()))
1657         return false;
1658
1659     // FIXME: We can't create a directly composited background if this
1660     // layer will have children that intersect with the background layer.
1661     // A better solution might be to introduce a flattening layer if
1662     // we do direct box decoration composition.
1663     // https://bugs.webkit.org/show_bug.cgi?id=119461
1664     if (hasPerspectiveOrPreserves3D(&renderer.style()))
1665         return false;
1666
1667     // FIXME: we should be able to allow backgroundComposite; However since this is not a common use case it has been deferred for now.
1668     if (renderer.style().backgroundComposite() != CompositeSourceOver)
1669         return false;
1670
1671     if (renderer.style().backgroundClip() == TextFillBox)
1672         return false;
1673
1674     return true;
1675 }
1676
1677 bool RenderLayerBacking::paintsBoxDecorations() const
1678 {
1679     if (!m_owningLayer.hasVisibleBoxDecorations())
1680         return false;
1681
1682     if (!supportsDirectBoxDecorationsComposition(renderer()))
1683         return true;
1684
1685     return false;
1686 }
1687
1688 bool RenderLayerBacking::paintsChildren() const
1689 {
1690     if (m_owningLayer.hasVisibleContent() && m_owningLayer.hasNonEmptyChildRenderers())
1691         return true;
1692
1693     if (hasVisibleNonCompositingDescendantLayers())
1694         return true;
1695
1696     return false;
1697 }
1698
1699 static bool isRestartedPlugin(RenderObject* renderer)
1700 {
1701     if (!renderer->isEmbeddedObject())
1702         return false;
1703
1704     Element* element = toElement(renderer->node());
1705     if (!element || !element->isPluginElement())
1706         return false;
1707
1708     return toHTMLPlugInElement(element)->isRestartedPlugin();
1709 }
1710
1711 static bool isCompositedPlugin(RenderObject* renderer)
1712 {
1713     return renderer->isEmbeddedObject() && toRenderEmbeddedObject(renderer)->allowsAcceleratedCompositing();
1714 }
1715
1716 // A "simple container layer" is a RenderLayer which has no visible content to render.
1717 // It may have no children, or all its children may be themselves composited.
1718 // This is a useful optimization, because it allows us to avoid allocating backing store.
1719 bool RenderLayerBacking::isSimpleContainerCompositingLayer() const
1720 {
1721     if (renderer().hasMask()) // masks require special treatment
1722         return false;
1723
1724     if (renderer().isReplaced() && (!isCompositedPlugin(&renderer()) || isRestartedPlugin(&renderer())))
1725         return false;
1726
1727     if (paintsBoxDecorations() || paintsChildren())
1728         return false;
1729
1730     if (renderer().isRenderNamedFlowFragmentContainer())
1731         return false;
1732
1733     if (renderer().isRenderView()) {
1734         // Look to see if the root object has a non-simple background
1735         RenderObject* rootObject = renderer().document().documentElement() ? renderer().document().documentElement()->renderer() : 0;
1736         if (!rootObject)
1737             return false;
1738         
1739         RenderStyle* style = &rootObject->style();
1740         
1741         // Reject anything that has a border, a border-radius or outline,
1742         // or is not a simple background (no background, or solid color).
1743         if (hasBoxDecorationsOrBackgroundImage(style))
1744             return false;
1745         
1746         // Now look at the body's renderer.
1747         HTMLElement* body = renderer().document().body();
1748         RenderObject* bodyObject = (body && body->hasLocalName(bodyTag)) ? body->renderer() : 0;
1749         if (!bodyObject)
1750             return false;
1751         
1752         style = &bodyObject->style();
1753         
1754         if (hasBoxDecorationsOrBackgroundImage(style))
1755             return false;
1756     }
1757
1758     return true;
1759 }
1760
1761 static bool hasVisibleNonCompositingDescendant(RenderLayer& parent)
1762 {
1763     // FIXME: We shouldn't be called with a stale z-order lists. See bug 85512.
1764     parent.updateLayerListsIfNeeded();
1765
1766 #if !ASSERT_DISABLED
1767     LayerListMutationDetector mutationChecker(&parent);
1768 #endif
1769
1770     if (Vector<RenderLayer*>* normalFlowList = parent.normalFlowList()) {
1771         size_t listSize = normalFlowList->size();
1772         for (size_t i = 0; i < listSize; ++i) {
1773             RenderLayer* curLayer = normalFlowList->at(i);
1774             if (!curLayer->isComposited()
1775                 && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(*curLayer)))
1776                 return true;
1777         }
1778     }
1779
1780     if (parent.isStackingContainer()) {
1781         if (!parent.hasVisibleDescendant())
1782             return false;
1783
1784         // Use the m_hasCompositingDescendant bit to optimize?
1785         if (Vector<RenderLayer*>* negZOrderList = parent.negZOrderList()) {
1786             size_t listSize = negZOrderList->size();
1787             for (size_t i = 0; i < listSize; ++i) {
1788                 RenderLayer* curLayer = negZOrderList->at(i);
1789                 if (!curLayer->isComposited()
1790                     && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(*curLayer)))
1791                     return true;
1792             }
1793         }
1794
1795         if (Vector<RenderLayer*>* posZOrderList = parent.posZOrderList()) {
1796             size_t listSize = posZOrderList->size();
1797             for (size_t i = 0; i < listSize; ++i) {
1798                 RenderLayer* curLayer = posZOrderList->at(i);
1799                 if (!curLayer->isComposited()
1800                     && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(*curLayer)))
1801                     return true;
1802             }
1803         }
1804     }
1805
1806     return false;
1807 }
1808
1809 // Conservative test for having no rendered children.
1810 bool RenderLayerBacking::hasVisibleNonCompositingDescendantLayers() const
1811 {
1812     return hasVisibleNonCompositingDescendant(m_owningLayer);
1813 }
1814
1815 bool RenderLayerBacking::containsPaintedContent(bool isSimpleContainer) const
1816 {
1817     if (isSimpleContainer || paintsIntoWindow() || paintsIntoCompositedAncestor() || m_artificiallyInflatedBounds || m_owningLayer.isReflection())
1818         return false;
1819
1820     if (isDirectlyCompositedImage())
1821         return false;
1822
1823     // FIXME: we could optimize cases where the image, video or canvas is known to fill the border box entirely,
1824     // and set background color on the layer in that case, instead of allocating backing store and painting.
1825 #if ENABLE(VIDEO)
1826     if (renderer().isVideo() && toRenderVideo(renderer()).shouldDisplayVideo())
1827         return m_owningLayer.hasBoxDecorationsOrBackground();
1828 #endif
1829
1830 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
1831     if (renderer().isCanvas() && canvasCompositingStrategy(renderer()) == CanvasAsLayerContents)
1832         return m_owningLayer.hasBoxDecorationsOrBackground();
1833 #endif
1834
1835     return true;
1836 }
1837
1838 // An image can be directly compositing if it's the sole content of the layer, and has no box decorations
1839 // that require painting. Direct compositing saves backing store.
1840 bool RenderLayerBacking::isDirectlyCompositedImage() const
1841 {
1842     if (!renderer().isRenderImage() || m_owningLayer.hasBoxDecorationsOrBackground() || renderer().hasClip())
1843         return false;
1844
1845     RenderImage& imageRenderer = toRenderImage(renderer());
1846     if (CachedImage* cachedImage = imageRenderer.cachedImage()) {
1847         if (!cachedImage->hasImage())
1848             return false;
1849
1850         Image* image = cachedImage->imageForRenderer(&imageRenderer);
1851         if (!image->isBitmapImage())
1852             return false;
1853
1854         if (image->orientationForCurrentFrame() != DefaultImageOrientation)
1855             return false;
1856
1857         return m_graphicsLayer->shouldDirectlyCompositeImage(image);
1858     }
1859
1860     return false;
1861 }
1862
1863 void RenderLayerBacking::contentChanged(ContentChangeType changeType)
1864 {
1865     if ((changeType == ImageChanged) && isDirectlyCompositedImage()) {
1866         updateImageContents();
1867         return;
1868     }
1869
1870     if ((changeType == BackgroundImageChanged) && canCreateTiledImage(&renderer().style()))
1871         updateGraphicsLayerGeometry();
1872
1873     if ((changeType == MaskImageChanged) && m_maskLayer) {
1874         // The composited layer bounds relies on box->maskClipRect(), which changes
1875         // when the mask image becomes available.
1876         updateAfterLayout(CompositingChildrenOnly | IsUpdateRoot);
1877     }
1878
1879 #if ENABLE(WEBGL) || ENABLE(ACCELERATED_2D_CANVAS)
1880     if ((changeType == CanvasChanged || changeType == CanvasPixelsChanged) && renderer().isCanvas() && canvasCompositingStrategy(renderer()) == CanvasAsLayerContents) {
1881         m_graphicsLayer->setContentsNeedsDisplay();
1882         return;
1883     }
1884 #endif
1885 }
1886
1887 void RenderLayerBacking::updateImageContents()
1888 {
1889     ASSERT(renderer().isRenderImage());
1890     RenderImage& imageRenderer = toRenderImage(renderer());
1891
1892     CachedImage* cachedImage = imageRenderer.cachedImage();
1893     if (!cachedImage)
1894         return;
1895
1896     Image* image = cachedImage->imageForRenderer(&imageRenderer);
1897     if (!image)
1898         return;
1899
1900     // We have to wait until the image is fully loaded before setting it on the layer.
1901     if (!cachedImage->isLoaded())
1902         return;
1903
1904     // This is a no-op if the layer doesn't have an inner layer for the image.
1905     m_graphicsLayer->setContentsRect(pixelSnappedIntRect(contentsBox()));
1906
1907     LayoutRect contentsClippingRect = imageRenderer.contentBoxRect();
1908     contentsClippingRect.move(contentOffsetInCompostingLayer());
1909     m_graphicsLayer->setContentsClippingRect(pixelSnappedIntRect(contentsClippingRect));
1910
1911     m_graphicsLayer->setContentsToImage(image);
1912     bool isSimpleContainer = false;
1913     updateDrawsContent(isSimpleContainer);
1914     
1915     // Image animation is "lazy", in that it automatically stops unless someone is drawing
1916     // the image. So we have to kick the animation each time; this has the downside that the
1917     // image will keep animating, even if its layer is not visible.
1918     image->startAnimation();
1919 }
1920
1921 FloatPoint3D RenderLayerBacking::computeTransformOrigin(const LayoutRect& borderBox) const
1922 {
1923     const RenderStyle& style = renderer().style();
1924
1925     FloatPoint3D origin;
1926     origin.setX(floatValueForLength(style.transformOriginX(), borderBox.width()));
1927     origin.setY(floatValueForLength(style.transformOriginY(), borderBox.height()));
1928     origin.setZ(style.transformOriginZ());
1929
1930     return origin;
1931 }
1932
1933 FloatPoint RenderLayerBacking::computePerspectiveOrigin(const LayoutRect& borderBox) const
1934 {
1935     const RenderStyle& style = renderer().style();
1936
1937     float boxWidth = borderBox.width();
1938     float boxHeight = borderBox.height();
1939
1940     FloatPoint origin;
1941     origin.setX(floatValueForLength(style.perspectiveOriginX(), boxWidth));
1942     origin.setY(floatValueForLength(style.perspectiveOriginY(), boxHeight));
1943
1944     return origin;
1945 }
1946
1947 // Return the offset from the top-left of this compositing layer at which the renderer's contents are painted.
1948 LayoutSize RenderLayerBacking::contentOffsetInCompostingLayer() const
1949 {
1950     return LayoutSize(-m_compositedBounds.x(), -m_compositedBounds.y()) + m_devicePixelFractionFromRenderer;
1951 }
1952
1953 LayoutRect RenderLayerBacking::contentsBox() const
1954 {
1955     if (!renderer().isBox())
1956         return LayoutRect();
1957
1958     RenderBox& renderBox = toRenderBox(renderer());
1959     LayoutRect contentsRect;
1960 #if ENABLE(VIDEO)
1961     if (renderBox.isVideo())
1962         contentsRect = toRenderVideo(renderBox).videoBox();
1963     else
1964 #endif
1965     if (renderBox.isRenderReplaced()) {
1966         RenderReplaced& renderReplaced = *toRenderReplaced(&renderBox);
1967         contentsRect = renderReplaced.replacedContentRect(renderBox.intrinsicSize());
1968     } else
1969         contentsRect = renderBox.contentBoxRect();
1970
1971     contentsRect.move(contentOffsetInCompostingLayer());
1972     return contentsRect;
1973 }
1974
1975 static LayoutRect backgroundRectForBox(const RenderBox& box)
1976 {
1977     switch (box.style().backgroundClip()) {
1978     case BorderFillBox:
1979         return box.borderBoxRect();
1980     case PaddingFillBox:
1981         return box.paddingBoxRect();
1982     case ContentFillBox:
1983         return box.contentBoxRect();
1984     case TextFillBox:
1985         break;
1986     }
1987
1988     ASSERT_NOT_REACHED();
1989     return LayoutRect();
1990 }
1991
1992 FloatRect RenderLayerBacking::backgroundBoxForPainting() const
1993 {
1994     if (!renderer().isBox())
1995         return FloatRect();
1996
1997     LayoutRect backgroundBox = backgroundRectForBox(toRenderBox(renderer()));
1998     backgroundBox.move(contentOffsetInCompostingLayer());
1999     return pixelSnappedForPainting(backgroundBox, deviceScaleFactor());
2000 }
2001
2002 GraphicsLayer* RenderLayerBacking::parentForSublayers() const
2003 {
2004     if (m_scrollingContentsLayer)
2005         return m_scrollingContentsLayer.get();
2006
2007 #if PLATFORM(IOS)
2008     // FIXME: Can we remove this iOS-specific code path?
2009     if (GraphicsLayer* clippingLayer = this->clippingLayer())
2010         return clippingLayer;
2011     return m_graphicsLayer.get();
2012 #else
2013     return m_childContainmentLayer ? m_childContainmentLayer.get() : m_graphicsLayer.get();
2014 #endif
2015 }
2016
2017 GraphicsLayer* RenderLayerBacking::childForSuperlayers() const
2018 {
2019     if (m_ancestorClippingLayer)
2020         return m_ancestorClippingLayer.get();
2021
2022     if (m_contentsContainmentLayer)
2023         return m_contentsContainmentLayer.get();
2024     
2025     return m_graphicsLayer.get();
2026 }
2027
2028 bool RenderLayerBacking::paintsIntoWindow() const
2029 {
2030     if (m_usingTiledCacheLayer)
2031         return false;
2032
2033     if (m_owningLayer.isRootLayer()) {
2034 #if PLATFORM(IOS) || USE(COORDINATED_GRAPHICS)
2035         if (compositor().inForcedCompositingMode())
2036             return false;
2037 #endif
2038
2039         return compositor().rootLayerAttachment() != RenderLayerCompositor::RootLayerAttachedViaEnclosingFrame;
2040     }
2041     
2042     return false;
2043 }
2044
2045 void RenderLayerBacking::setRequiresOwnBackingStore(bool requiresOwnBacking)
2046 {
2047     if (requiresOwnBacking == m_requiresOwnBackingStore)
2048         return;
2049     
2050     m_requiresOwnBackingStore = requiresOwnBacking;
2051
2052     // This affects the answer to paintsIntoCompositedAncestor(), which in turn affects
2053     // cached clip rects, so when it changes we have to clear clip rects on descendants.
2054     m_owningLayer.clearClipRectsIncludingDescendants(PaintingClipRects);
2055     m_owningLayer.computeRepaintRectsIncludingDescendants();
2056     
2057     compositor().repaintInCompositedAncestor(m_owningLayer, compositedBounds());
2058 }
2059
2060 #if ENABLE(CSS_COMPOSITING)
2061 void RenderLayerBacking::setBlendMode(BlendMode blendMode)
2062 {
2063     m_graphicsLayer->setBlendMode(blendMode);
2064 }
2065 #endif
2066
2067 void RenderLayerBacking::setContentsNeedDisplay(GraphicsLayer::ShouldClipToLayer shouldClip)
2068 {
2069     ASSERT(!paintsIntoCompositedAncestor());
2070
2071     FrameView& frameView = owningLayer().renderer().view().frameView();
2072     if (m_isMainFrameRenderViewLayer && frameView.isTrackingRepaints())
2073         frameView.addTrackedRepaintRect(owningLayer().absoluteBoundingBoxForPainting());
2074     
2075     if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
2076         // By default, setNeedsDisplay will clip to the size of the GraphicsLayer, which does not include margin tiles.
2077         // So if the TiledBacking has a margin that needs to be invalidated, we need to send in a rect to setNeedsDisplayInRect
2078         // that is large enough to include the margin. TiledBacking::bounds() includes the margin.
2079         TiledBacking* tiledBacking = this->tiledBacking();
2080         FloatRect rectToRepaint = tiledBacking ? tiledBacking->bounds() : FloatRect(FloatPoint(0, 0), m_graphicsLayer->size());
2081         m_graphicsLayer->setNeedsDisplayInRect(rectToRepaint, shouldClip);
2082     }
2083     
2084     if (m_foregroundLayer && m_foregroundLayer->drawsContent())
2085         m_foregroundLayer->setNeedsDisplay();
2086
2087     if (m_backgroundLayer && m_backgroundLayer->drawsContent())
2088         m_backgroundLayer->setNeedsDisplay();
2089
2090     if (m_maskLayer && m_maskLayer->drawsContent())
2091         m_maskLayer->setNeedsDisplay();
2092
2093     if (m_scrollingContentsLayer && m_scrollingContentsLayer->drawsContent())
2094         m_scrollingContentsLayer->setNeedsDisplay();
2095 }
2096
2097 // r is in the coordinate space of the layer's render object
2098 void RenderLayerBacking::setContentsNeedDisplayInRect(const LayoutRect& r, GraphicsLayer::ShouldClipToLayer shouldClip)
2099 {
2100     ASSERT(!paintsIntoCompositedAncestor());
2101
2102     FloatRect pixelSnappedRectForPainting = pixelSnappedForPainting(r, deviceScaleFactor());
2103     FrameView& frameView = owningLayer().renderer().view().frameView();
2104     if (m_isMainFrameRenderViewLayer && frameView.isTrackingRepaints())
2105         frameView.addTrackedRepaintRect(pixelSnappedRectForPainting);
2106
2107     if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
2108         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2109         layerDirtyRect.move(-m_graphicsLayer->offsetFromRenderer() + m_devicePixelFractionFromRenderer);
2110         m_graphicsLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2111     }
2112
2113     if (m_foregroundLayer && m_foregroundLayer->drawsContent()) {
2114         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2115         layerDirtyRect.move(-m_foregroundLayer->offsetFromRenderer() + m_devicePixelFractionFromRenderer);
2116         m_foregroundLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2117     }
2118
2119     // FIXME: need to split out repaints for the background.
2120     if (m_backgroundLayer && m_backgroundLayer->drawsContent()) {
2121         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2122         layerDirtyRect.move(-m_backgroundLayer->offsetFromRenderer() + m_devicePixelFractionFromRenderer);
2123         m_backgroundLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2124     }
2125
2126     if (m_maskLayer && m_maskLayer->drawsContent()) {
2127         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2128         layerDirtyRect.move(-m_maskLayer->offsetFromRenderer() + m_devicePixelFractionFromRenderer);
2129         m_maskLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2130     }
2131
2132     if (m_scrollingContentsLayer && m_scrollingContentsLayer->drawsContent()) {
2133         FloatRect layerDirtyRect = pixelSnappedRectForPainting;
2134         layerDirtyRect.move(-m_scrollingContentsLayer->offsetFromRenderer() + m_devicePixelFractionFromRenderer);
2135 #if PLATFORM(IOS)
2136         // Account for the fact that RenderLayerBacking::updateGraphicsLayerGeometry() bakes scrollOffset into offsetFromRenderer on iOS.
2137         layerDirtyRect.move(-m_owningLayer.scrollOffset() + m_devicePixelFractionFromRenderer);
2138 #endif
2139         m_scrollingContentsLayer->setNeedsDisplayInRect(layerDirtyRect, shouldClip);
2140     }
2141 }
2142
2143 void RenderLayerBacking::paintIntoLayer(const GraphicsLayer* graphicsLayer, GraphicsContext* context,
2144     const IntRect& paintDirtyRect, // In the coords of rootLayer.
2145     PaintBehavior paintBehavior, GraphicsLayerPaintingPhase paintingPhase)
2146 {
2147     if (paintsIntoWindow() || paintsIntoCompositedAncestor()) {
2148 #if !PLATFORM(IOS)
2149         // FIXME: Looks like the CALayer tree is out of sync with the GraphicsLayer heirarchy
2150         // when pages are restored from the PageCache.
2151         // <rdar://problem/8712587> ASSERT: When Going Back to Page with Plugins in PageCache
2152         ASSERT_NOT_REACHED();
2153 #endif
2154         return;
2155     }
2156
2157     FontCachePurgePreventer fontCachePurgePreventer;
2158     
2159     RenderLayer::PaintLayerFlags paintFlags = 0;
2160     if (paintingPhase & GraphicsLayerPaintBackground)
2161         paintFlags |= RenderLayer::PaintLayerPaintingCompositingBackgroundPhase;
2162     if (paintingPhase & GraphicsLayerPaintForeground)
2163         paintFlags |= RenderLayer::PaintLayerPaintingCompositingForegroundPhase;
2164     if (paintingPhase & GraphicsLayerPaintMask)
2165         paintFlags |= RenderLayer::PaintLayerPaintingCompositingMaskPhase;
2166     if (paintingPhase & GraphicsLayerPaintOverflowContents)
2167         paintFlags |= RenderLayer::PaintLayerPaintingOverflowContents;
2168     if (paintingPhase & GraphicsLayerPaintCompositedScroll)
2169         paintFlags |= RenderLayer::PaintLayerPaintingCompositingScrollingPhase;
2170
2171     if (graphicsLayer == m_backgroundLayer.get())
2172         paintFlags |= (RenderLayer::PaintLayerPaintingRootBackgroundOnly | RenderLayer::PaintLayerPaintingCompositingForegroundPhase); // Need PaintLayerPaintingCompositingForegroundPhase to walk child layers.
2173     else if (compositor().fixedRootBackgroundLayer())
2174         paintFlags |= RenderLayer::PaintLayerPaintingSkipRootBackground;
2175     
2176     // FIXME: GraphicsLayers need a way to split for RenderRegions.
2177     RenderLayer::LayerPaintingInfo paintingInfo(&m_owningLayer, paintDirtyRect, paintBehavior, m_devicePixelFractionFromRenderer);
2178     m_owningLayer.paintLayerContents(context, paintingInfo, paintFlags);
2179
2180     if (m_owningLayer.containsDirtyOverlayScrollbars())
2181         m_owningLayer.paintLayerContents(context, paintingInfo, paintFlags | RenderLayer::PaintLayerPaintingOverlayScrollbars);
2182
2183     compositor().didPaintBacking(this);
2184
2185     ASSERT(!m_owningLayer.m_usedTransparency);
2186 }
2187
2188 static void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
2189 {
2190     if (!scrollbar)
2191         return;
2192
2193     context.save();
2194     const IntRect& scrollbarRect = scrollbar->frameRect();
2195     context.translate(-scrollbarRect.x(), -scrollbarRect.y());
2196     IntRect transformedClip = clip;
2197     transformedClip.moveBy(scrollbarRect.location());
2198     scrollbar->paint(&context, transformedClip);
2199     context.restore();
2200 }
2201
2202 // Up-call from compositing layer drawing callback.
2203 void RenderLayerBacking::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, GraphicsLayerPaintingPhase paintingPhase, const FloatRect& clip)
2204 {
2205 #ifndef NDEBUG
2206     if (Page* page = renderer().frame().page())
2207         page->setIsPainting(true);
2208 #endif
2209
2210     // The dirtyRect is in the coords of the painting root.
2211     IntRect dirtyRect = enclosingIntRect(clip);
2212
2213     if (graphicsLayer == m_graphicsLayer.get()
2214         || graphicsLayer == m_foregroundLayer.get()
2215         || graphicsLayer == m_backgroundLayer.get()
2216         || graphicsLayer == m_maskLayer.get()
2217         || graphicsLayer == m_scrollingContentsLayer.get()) {
2218         InspectorInstrumentation::willPaint(&renderer());
2219
2220         if (!(paintingPhase & GraphicsLayerPaintOverflowContents))
2221             dirtyRect.intersect(enclosingIntRect(compositedBoundsIncludingMargin()));
2222
2223         // We have to use the same root as for hit testing, because both methods can compute and cache clipRects.
2224         paintIntoLayer(graphicsLayer, &context, dirtyRect, PaintBehaviorNormal, paintingPhase);
2225
2226         InspectorInstrumentation::didPaint(&renderer(), &context, dirtyRect);
2227     } else if (graphicsLayer == layerForHorizontalScrollbar()) {
2228         paintScrollbar(m_owningLayer.horizontalScrollbar(), context, dirtyRect);
2229     } else if (graphicsLayer == layerForVerticalScrollbar()) {
2230         paintScrollbar(m_owningLayer.verticalScrollbar(), context, dirtyRect);
2231     } else if (graphicsLayer == layerForScrollCorner()) {
2232         const LayoutRect& scrollCornerAndResizer = m_owningLayer.scrollCornerAndResizerRect();
2233         context.save();
2234         context.translate(-scrollCornerAndResizer.x(), -scrollCornerAndResizer.y());
2235         LayoutRect transformedClip = LayoutRect(clip);
2236         transformedClip.moveBy(scrollCornerAndResizer.location());
2237         m_owningLayer.paintScrollCorner(&context, IntPoint(), pixelSnappedIntRect(transformedClip));
2238         m_owningLayer.paintResizer(&context, IntPoint(), transformedClip);
2239         context.restore();
2240     }
2241 #ifndef NDEBUG
2242     if (Page* page = renderer().frame().page())
2243         page->setIsPainting(false);
2244 #endif
2245 }
2246
2247 float RenderLayerBacking::pageScaleFactor() const
2248 {
2249     return compositor().pageScaleFactor();
2250 }
2251
2252 float RenderLayerBacking::deviceScaleFactor() const
2253 {
2254     return compositor().deviceScaleFactor();
2255 }
2256
2257 float RenderLayerBacking::contentsScaleMultiplierForNewTiles(const GraphicsLayer* layer) const
2258 {
2259     return compositor().contentsScaleMultiplierForNewTiles(layer);
2260 }
2261
2262 void RenderLayerBacking::didCommitChangesForLayer(const GraphicsLayer* layer) const
2263 {
2264     compositor().didFlushChangesForLayer(m_owningLayer, layer);
2265 }
2266
2267 bool RenderLayerBacking::getCurrentTransform(const GraphicsLayer* graphicsLayer, TransformationMatrix& transform) const
2268 {
2269     GraphicsLayer* transformedLayer = m_contentsContainmentLayer.get() ? m_contentsContainmentLayer.get() : m_graphicsLayer.get();
2270     if (graphicsLayer != transformedLayer)
2271         return false;
2272
2273     if (m_owningLayer.hasTransform()) {
2274         transform = m_owningLayer.currentTransform(RenderStyle::ExcludeTransformOrigin);
2275         return true;
2276     }
2277     return false;
2278 }
2279
2280 bool RenderLayerBacking::isTrackingRepaints() const
2281 {
2282     return static_cast<GraphicsLayerClient&>(compositor()).isTrackingRepaints();
2283 }
2284
2285 bool RenderLayerBacking::shouldSkipLayerInDump(const GraphicsLayer* layer) const
2286 {
2287     // Skip the root tile cache's flattening layer.
2288     return m_isMainFrameRenderViewLayer && layer && layer == m_childContainmentLayer.get();
2289 }
2290
2291 bool RenderLayerBacking::shouldDumpPropertyForLayer(const GraphicsLayer* layer, const char* propertyName) const
2292 {
2293     // For backwards compatibility with WebKit1 and other platforms,
2294     // skip some properties on the root tile cache.
2295     if (m_isMainFrameRenderViewLayer && layer == m_graphicsLayer.get()) {
2296         if (!strcmp(propertyName, "drawsContent"))
2297             return false;
2298
2299         // Background color could be of interest to tests or other dumpers if it's non-white.
2300         if (!strcmp(propertyName, "backgroundColor") && layer->backgroundColor() == Color::white)
2301             return false;
2302
2303         // The root tile cache's repaints will show up at the top with FrameView's,
2304         // so don't dump them twice.
2305         if (!strcmp(propertyName, "repaintRects"))
2306             return false;
2307     }
2308
2309     return true;
2310 }
2311
2312 #ifndef NDEBUG
2313 void RenderLayerBacking::verifyNotPainting()
2314 {
2315     ASSERT(!renderer().frame().page() || !renderer().frame().page()->isPainting());
2316 }
2317 #endif
2318
2319 bool RenderLayerBacking::startAnimation(double timeOffset, const Animation* anim, const KeyframeList& keyframes)
2320 {
2321     bool hasOpacity = keyframes.containsProperty(CSSPropertyOpacity);
2322     bool hasTransform = renderer().isBox() && keyframes.containsProperty(CSSPropertyWebkitTransform);
2323 #if ENABLE(CSS_FILTERS)
2324     bool hasFilter = keyframes.containsProperty(CSSPropertyWebkitFilter);
2325 #else
2326     bool hasFilter = false;
2327 #endif
2328
2329     if (!hasOpacity && !hasTransform && !hasFilter)
2330         return false;
2331     
2332     KeyframeValueList transformVector(AnimatedPropertyWebkitTransform);
2333     KeyframeValueList opacityVector(AnimatedPropertyOpacity);
2334 #if ENABLE(CSS_FILTERS)
2335     KeyframeValueList filterVector(AnimatedPropertyWebkitFilter);
2336 #endif
2337
2338     size_t numKeyframes = keyframes.size();
2339     for (size_t i = 0; i < numKeyframes; ++i) {
2340         const KeyframeValue& currentKeyframe = keyframes[i];
2341         const RenderStyle* keyframeStyle = currentKeyframe.style();
2342         double key = currentKeyframe.key();
2343
2344         if (!keyframeStyle)
2345             continue;
2346             
2347         // Get timing function.
2348         RefPtr<TimingFunction> tf = keyframeStyle->hasAnimations() ? (*keyframeStyle->animations()).animation(0).timingFunction() : 0;
2349         
2350         bool isFirstOrLastKeyframe = key == 0 || key == 1;
2351         if ((hasTransform && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitTransform))
2352             transformVector.insert(TransformAnimationValue::create(key, keyframeStyle->transform(), tf));
2353
2354         if ((hasOpacity && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyOpacity))
2355             opacityVector.insert(FloatAnimationValue::create(key, keyframeStyle->opacity(), tf));
2356
2357 #if ENABLE(CSS_FILTERS)
2358         if ((hasFilter && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitFilter))
2359             filterVector.insert(FilterAnimationValue::create(key, keyframeStyle->filter(), tf));
2360 #endif
2361     }
2362
2363     if (renderer().frame().page() && !renderer().frame().page()->settings().acceleratedCompositedAnimationsEnabled())
2364         return false;
2365
2366     bool didAnimate = false;
2367
2368     if (hasTransform && m_graphicsLayer->addAnimation(transformVector, toRenderBox(renderer()).pixelSnappedBorderBoxRect().size(), anim, keyframes.animationName(), timeOffset))
2369         didAnimate = true;
2370
2371     if (hasOpacity && m_graphicsLayer->addAnimation(opacityVector, IntSize(), anim, keyframes.animationName(), timeOffset))
2372         didAnimate = true;
2373
2374 #if ENABLE(CSS_FILTERS)
2375     if (hasFilter && m_graphicsLayer->addAnimation(filterVector, IntSize(), anim, keyframes.animationName(), timeOffset))
2376         didAnimate = true;
2377 #endif
2378
2379     return didAnimate;
2380 }
2381
2382 void RenderLayerBacking::animationPaused(double timeOffset, const String& animationName)
2383 {
2384     m_graphicsLayer->pauseAnimation(animationName, timeOffset);
2385 }
2386
2387 void RenderLayerBacking::animationFinished(const String& animationName)
2388 {
2389     m_graphicsLayer->removeAnimation(animationName);
2390 }
2391
2392 bool RenderLayerBacking::startTransition(double timeOffset, CSSPropertyID property, const RenderStyle* fromStyle, const RenderStyle* toStyle)
2393 {
2394     bool didAnimate = false;
2395
2396     ASSERT(property != CSSPropertyInvalid);
2397
2398     if (property == CSSPropertyOpacity) {
2399         const Animation* opacityAnim = toStyle->transitionForProperty(CSSPropertyOpacity);
2400         if (opacityAnim && !opacityAnim->isEmptyOrZeroDuration()) {
2401             KeyframeValueList opacityVector(AnimatedPropertyOpacity);
2402             opacityVector.insert(FloatAnimationValue::create(0, compositingOpacity(fromStyle->opacity())));
2403             opacityVector.insert(FloatAnimationValue::create(1, compositingOpacity(toStyle->opacity())));
2404             // The boxSize param is only used for transform animations (which can only run on RenderBoxes), so we pass an empty size here.
2405             if (m_graphicsLayer->addAnimation(opacityVector, FloatSize(), opacityAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyOpacity), timeOffset)) {
2406                 // To ensure that the correct opacity is visible when the animation ends, also set the final opacity.
2407                 updateOpacity(toStyle);
2408                 didAnimate = true;
2409             }
2410         }
2411     }
2412
2413     if (property == CSSPropertyWebkitTransform && m_owningLayer.hasTransform()) {
2414         const Animation* transformAnim = toStyle->transitionForProperty(CSSPropertyWebkitTransform);
2415         if (transformAnim && !transformAnim->isEmptyOrZeroDuration()) {
2416             KeyframeValueList transformVector(AnimatedPropertyWebkitTransform);
2417             transformVector.insert(TransformAnimationValue::create(0, fromStyle->transform()));
2418             transformVector.insert(TransformAnimationValue::create(1, toStyle->transform()));
2419             if (m_graphicsLayer->addAnimation(transformVector, toRenderBox(renderer()).pixelSnappedBorderBoxRect().size(), transformAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyWebkitTransform), timeOffset)) {
2420                 // To ensure that the correct transform is visible when the animation ends, also set the final transform.
2421                 updateTransform(toStyle);
2422                 didAnimate = true;
2423             }
2424         }
2425     }
2426
2427 #if ENABLE(CSS_FILTERS)
2428     if (property == CSSPropertyWebkitFilter && m_owningLayer.hasFilter()) {
2429         const Animation* filterAnim = toStyle->transitionForProperty(CSSPropertyWebkitFilter);
2430         if (filterAnim && !filterAnim->isEmptyOrZeroDuration()) {
2431             KeyframeValueList filterVector(AnimatedPropertyWebkitFilter);
2432             filterVector.insert(FilterAnimationValue::create(0, fromStyle->filter()));
2433             filterVector.insert(FilterAnimationValue::create(1, toStyle->filter()));
2434             if (m_graphicsLayer->addAnimation(filterVector, FloatSize(), filterAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyWebkitFilter), timeOffset)) {
2435                 // To ensure that the correct filter is visible when the animation ends, also set the final filter.
2436                 updateFilters(toStyle);
2437                 didAnimate = true;
2438             }
2439         }
2440     }
2441 #endif
2442
2443     return didAnimate;
2444 }
2445
2446 void RenderLayerBacking::transitionPaused(double timeOffset, CSSPropertyID property)
2447 {
2448     AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
2449     if (animatedProperty != AnimatedPropertyInvalid)
2450         m_graphicsLayer->pauseAnimation(GraphicsLayer::animationNameForTransition(animatedProperty), timeOffset);
2451 }
2452
2453 void RenderLayerBacking::transitionFinished(CSSPropertyID property)
2454 {
2455     AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
2456     if (animatedProperty != AnimatedPropertyInvalid)
2457         m_graphicsLayer->removeAnimation(GraphicsLayer::animationNameForTransition(animatedProperty));
2458 }
2459
2460 void RenderLayerBacking::notifyAnimationStarted(const GraphicsLayer*, double time)
2461 {
2462     renderer().animation().notifyAnimationStarted(&renderer(), time);
2463 }
2464
2465 void RenderLayerBacking::notifyFlushRequired(const GraphicsLayer* layer)
2466 {
2467     if (renderer().documentBeingDestroyed())
2468         return;
2469     compositor().scheduleLayerFlush(layer->canThrottleLayerFlush());
2470 }
2471
2472 void RenderLayerBacking::notifyFlushBeforeDisplayRefresh(const GraphicsLayer* layer)
2473 {
2474     compositor().notifyFlushBeforeDisplayRefresh(layer);
2475 }
2476
2477 // This is used for the 'freeze' API, for testing only.
2478 void RenderLayerBacking::suspendAnimations(double time)
2479 {
2480     m_graphicsLayer->suspendAnimations(time);
2481 }
2482
2483 void RenderLayerBacking::resumeAnimations()
2484 {
2485     m_graphicsLayer->resumeAnimations();
2486 }
2487
2488 LayoutRect RenderLayerBacking::compositedBounds() const
2489 {
2490     return m_compositedBounds;
2491 }
2492
2493 void RenderLayerBacking::setCompositedBounds(const LayoutRect& bounds)
2494 {
2495     m_compositedBounds = bounds;
2496 }
2497
2498 LayoutRect RenderLayerBacking::compositedBoundsIncludingMargin() const
2499 {
2500     TiledBacking* tiledBacking = this->tiledBacking();
2501     if (!tiledBacking || !tiledBacking->hasMargins())
2502         return compositedBounds();
2503
2504     LayoutRect boundsIncludingMargin = compositedBounds();
2505     LayoutUnit leftMarginWidth = tiledBacking->leftMarginWidth();
2506     LayoutUnit topMarginHeight = tiledBacking->topMarginHeight();
2507
2508     boundsIncludingMargin.moveBy(LayoutPoint(-leftMarginWidth, -topMarginHeight));
2509     boundsIncludingMargin.expand(leftMarginWidth + tiledBacking->rightMarginWidth(), topMarginHeight + tiledBacking->bottomMarginHeight());
2510
2511     return boundsIncludingMargin;
2512 }
2513
2514 CSSPropertyID RenderLayerBacking::graphicsLayerToCSSProperty(AnimatedPropertyID property)
2515 {
2516     CSSPropertyID cssProperty = CSSPropertyInvalid;
2517     switch (property) {
2518         case AnimatedPropertyWebkitTransform:
2519             cssProperty = CSSPropertyWebkitTransform;
2520             break;
2521         case AnimatedPropertyOpacity:
2522             cssProperty = CSSPropertyOpacity;
2523             break;
2524         case AnimatedPropertyBackgroundColor:
2525             cssProperty = CSSPropertyBackgroundColor;
2526             break;
2527         case AnimatedPropertyWebkitFilter:
2528 #if ENABLE(CSS_FILTERS)
2529             cssProperty = CSSPropertyWebkitFilter;
2530 #else
2531             ASSERT_NOT_REACHED();
2532 #endif
2533             break;
2534         case AnimatedPropertyInvalid:
2535             ASSERT_NOT_REACHED();
2536     }
2537     return cssProperty;
2538 }
2539
2540 AnimatedPropertyID RenderLayerBacking::cssToGraphicsLayerProperty(CSSPropertyID cssProperty)
2541 {
2542     switch (cssProperty) {
2543         case CSSPropertyWebkitTransform:
2544             return AnimatedPropertyWebkitTransform;
2545         case CSSPropertyOpacity:
2546             return AnimatedPropertyOpacity;
2547         case CSSPropertyBackgroundColor:
2548             return AnimatedPropertyBackgroundColor;
2549 #if ENABLE(CSS_FILTERS)
2550         case CSSPropertyWebkitFilter:
2551             return AnimatedPropertyWebkitFilter;
2552 #endif
2553         default:
2554             // It's fine if we see other css properties here; they are just not accelerated.
2555             break;
2556     }
2557     return AnimatedPropertyInvalid;
2558 }
2559
2560 CompositingLayerType RenderLayerBacking::compositingLayerType() const
2561 {
2562     if (m_graphicsLayer->hasContentsLayer())
2563         return MediaCompositingLayer;
2564
2565     if (m_graphicsLayer->drawsContent())
2566         return m_graphicsLayer->usingTiledBacking() ? TiledCompositingLayer : NormalCompositingLayer;
2567     
2568     return ContainerCompositingLayer;
2569 }
2570
2571 double RenderLayerBacking::backingStoreMemoryEstimate() const
2572 {
2573     double backingMemory;
2574     
2575     // m_ancestorClippingLayer, m_contentsContainmentLayer and m_childContainmentLayer are just used for masking or containment, so have no backing.
2576     backingMemory = m_graphicsLayer->backingStoreMemoryEstimate();
2577     if (m_foregroundLayer)
2578         backingMemory += m_foregroundLayer->backingStoreMemoryEstimate();
2579     if (m_backgroundLayer)
2580         backingMemory += m_backgroundLayer->backingStoreMemoryEstimate();
2581     if (m_maskLayer)
2582         backingMemory += m_maskLayer->backingStoreMemoryEstimate();
2583
2584     if (m_scrollingContentsLayer)
2585         backingMemory += m_scrollingContentsLayer->backingStoreMemoryEstimate();
2586
2587     if (m_layerForHorizontalScrollbar)
2588         backingMemory += m_layerForHorizontalScrollbar->backingStoreMemoryEstimate();
2589
2590     if (m_layerForVerticalScrollbar)
2591         backingMemory += m_layerForVerticalScrollbar->backingStoreMemoryEstimate();
2592
2593     if (m_layerForScrollCorner)
2594         backingMemory += m_layerForScrollCorner->backingStoreMemoryEstimate();
2595     
2596     return backingMemory;
2597 }
2598
2599 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
2600 bool RenderLayerBacking::mediaLayerMustBeUpdatedOnMainThread() const
2601 {
2602     return renderer().frame().page() && renderer().frame().page()->settings().isVideoPluginProxyEnabled();
2603 }
2604 #endif
2605
2606 } // namespace WebCore