10bf375b7fb9e04d573980216b1cde25bfefdf1f
[WebKit-https.git] / WebCore / rendering / RenderLayerCompositor.cpp
1 /*
2  * Copyright (C) 2009, 2010 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27
28 #if USE(ACCELERATED_COMPOSITING)
29 #include "RenderLayerCompositor.h"
30
31 #include "AnimationController.h"
32 #include "Chrome.h"
33 #include "ChromeClient.h"
34 #include "CSSPropertyNames.h"
35 #include "Frame.h"
36 #include "FrameView.h"
37 #include "GraphicsLayer.h"
38 #include "HitTestResult.h"
39 #include "HTMLCanvasElement.h"
40 #include "HTMLIFrameElement.h"
41 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
42 #include "HTMLMediaElement.h"
43 #include "HTMLNames.h"
44 #endif
45 #include "NodeList.h"
46 #include "Page.h"
47 #include "RenderEmbeddedObject.h"
48 #include "RenderIFrame.h"
49 #include "RenderLayerBacking.h"
50 #include "RenderReplica.h"
51 #include "RenderVideo.h"
52 #include "RenderView.h"
53 #include "Settings.h"
54
55 #if PROFILE_LAYER_REBUILD
56 #include <wtf/CurrentTime.h>
57 #endif
58
59 #ifndef NDEBUG
60 #include "RenderTreeAsText.h"
61 #endif
62
63 #if ENABLE(3D_RENDERING)
64 // This symbol is used to determine from a script whether 3D rendering is enabled (via 'nm').
65 bool WebCoreHas3DRendering = true;
66 #endif
67
68 namespace WebCore {
69
70 using namespace HTMLNames;
71
72 struct CompositingState {
73     CompositingState(RenderLayer* compAncestor)
74         : m_compositingAncestor(compAncestor)
75         , m_subtreeIsCompositing(false)
76 #ifndef NDEBUG
77         , m_depth(0)
78 #endif
79     {
80     }
81     
82     RenderLayer* m_compositingAncestor;
83     bool m_subtreeIsCompositing;
84 #ifndef NDEBUG
85     int m_depth;
86 #endif
87 };
88
89 RenderLayerCompositor::RenderLayerCompositor(RenderView* renderView)
90     : m_renderView(renderView)
91     , m_rootPlatformLayer(0)
92     , m_hasAcceleratedCompositing(true)
93     , m_showDebugBorders(false)
94     , m_showRepaintCounter(false)
95     , m_compositingConsultsOverlap(true)
96     , m_compositing(false)
97     , m_compositingLayersNeedRebuild(false)
98     , m_rootLayerAttachment(RootLayerUnattached)
99 #if PROFILE_LAYER_REBUILD
100     , m_rootLayerUpdateCount(0)
101 #endif // PROFILE_LAYER_REBUILD
102 {
103 }
104
105 RenderLayerCompositor::~RenderLayerCompositor()
106 {
107     ASSERT(m_rootLayerAttachment == RootLayerUnattached);
108 }
109
110 void RenderLayerCompositor::enableCompositingMode(bool enable /* = true */)
111 {
112     if (enable != m_compositing) {
113         m_compositing = enable;
114         
115         if (m_compositing) {
116             ensureRootPlatformLayer();
117             notifyIFramesOfCompositingChange();
118         } else
119             destroyRootPlatformLayer();
120     }
121 }
122
123 void RenderLayerCompositor::cacheAcceleratedCompositingFlags()
124 {
125     bool hasAcceleratedCompositing = false;
126     bool showDebugBorders = false;
127     bool showRepaintCounter = false;
128     
129     if (Settings* settings = m_renderView->document()->settings()) {
130         hasAcceleratedCompositing = settings->acceleratedCompositingEnabled();
131         showDebugBorders = settings->showDebugBorders();
132         showRepaintCounter = settings->showRepaintCounter();
133     }
134
135     // We allow the chrome to override the settings, in case the page is rendered
136     // on a chrome that doesn't allow accelerated compositing.
137     if (hasAcceleratedCompositing) {
138         Frame* frame = m_renderView->frameView()->frame();
139         Page* page = frame ? frame->page() : 0;
140         if (page)
141             hasAcceleratedCompositing = page->chrome()->client()->allowsAcceleratedCompositing();
142     }
143
144     if (hasAcceleratedCompositing != m_hasAcceleratedCompositing || showDebugBorders != m_showDebugBorders || showRepaintCounter != m_showRepaintCounter)
145         setCompositingLayersNeedRebuild();
146         
147     m_hasAcceleratedCompositing = hasAcceleratedCompositing;
148     m_showDebugBorders = showDebugBorders;
149     m_showRepaintCounter = showRepaintCounter;
150 }
151
152 void RenderLayerCompositor::setCompositingLayersNeedRebuild(bool needRebuild)
153 {
154     if (inCompositingMode())
155         m_compositingLayersNeedRebuild = needRebuild;
156 }
157
158 void RenderLayerCompositor::scheduleSync()
159 {
160     Frame* frame = m_renderView->frameView()->frame();
161     Page* page = frame ? frame->page() : 0;
162     if (!page)
163         return;
164
165     page->chrome()->client()->scheduleCompositingLayerSync();
166 }
167
168 void RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType updateType, RenderLayer* updateRoot)
169 {
170     bool checkForHierarchyUpdate = false;
171     bool needGeometryUpdate = false;
172     
173     switch (updateType) {
174     case CompositingUpdateAfterLayoutOrStyleChange:
175     case CompositingUpdateOnPaitingOrHitTest:
176         checkForHierarchyUpdate = true;
177         break;
178     case CompositingUpdateOnScroll:
179         if (m_compositingConsultsOverlap)
180             checkForHierarchyUpdate = true; // Overlap can change with scrolling, so need to check for hierarchy updates.
181
182         needGeometryUpdate = true;
183         break;
184     }
185
186     if (!checkForHierarchyUpdate && !needGeometryUpdate)
187         return;
188
189     ASSERT(inCompositingMode());
190
191     bool needHierarchyUpdate = m_compositingLayersNeedRebuild;
192     if (!updateRoot) {
193         // Only clear the flag if we're updating the entire hierarchy.
194         m_compositingLayersNeedRebuild = false;
195         updateRoot = rootRenderLayer();
196     }
197
198 #if PROFILE_LAYER_REBUILD
199     ++m_rootLayerUpdateCount;
200     
201     double startTime = WTF::currentTime();
202 #endif        
203
204     if (checkForHierarchyUpdate) {
205         // Go through the layers in presentation order, so that we can compute which RenderLayers need compositing layers.
206         // FIXME: we could maybe do this and the hierarchy udpate in one pass, but the parenting logic would be more complex.
207         CompositingState compState(updateRoot);
208         bool layersChanged = false;
209         if (m_compositingConsultsOverlap) {
210             OverlapMap overlapTestRequestMap;
211             computeCompositingRequirements(updateRoot, &overlapTestRequestMap, compState, layersChanged);
212         } else
213             computeCompositingRequirements(updateRoot, 0, compState, layersChanged);
214         
215         needHierarchyUpdate |= layersChanged;
216     }
217
218     if (needHierarchyUpdate) {
219         // Update the hierarchy of the compositing layers.
220         CompositingState compState(updateRoot);
221         Vector<GraphicsLayer*> childList;
222         rebuildCompositingLayerTree(updateRoot, compState, childList);
223
224         // Host the document layer in the RenderView's root layer.
225         if (updateRoot == rootRenderLayer()) {
226             if (childList.isEmpty())
227                 destroyRootPlatformLayer();
228             else
229                 m_rootPlatformLayer->setChildren(childList);
230         }
231     } else if (needGeometryUpdate) {
232         // We just need to do a geometry update. This is only used for position:fixed scrolling;
233         // most of the time, geometry is updated via RenderLayer::styleChanged().
234         updateLayerTreeGeometry(updateRoot);
235     }
236     
237 #if PROFILE_LAYER_REBUILD
238     double endTime = WTF::currentTime();
239     if (updateRoot == rootRenderLayer())
240         fprintf(stderr, "Update %d: computeCompositingRequirements for the world took %fms\n",
241                     m_rootLayerUpdateCount, 1000.0 * (endTime - startTime));
242 #endif
243     ASSERT(updateRoot || !m_compositingLayersNeedRebuild);
244
245     if (!hasAcceleratedCompositing())
246         enableCompositingMode(false);
247 }
248
249 bool RenderLayerCompositor::updateBacking(RenderLayer* layer, CompositingChangeRepaint shouldRepaint)
250 {
251     bool layerChanged = false;
252
253     if (needsToBeComposited(layer)) {
254         enableCompositingMode();
255         
256         // 3D transforms turn off the testing of overlap.
257         if (requiresCompositingForTransform(layer->renderer()))
258             setCompositingConsultsOverlap(false);
259
260         if (!layer->backing()) {
261
262             // If we need to repaint, do so before making backing
263             if (shouldRepaint == CompositingChangeRepaintNow)
264                 repaintOnCompositingChange(layer);
265
266             layer->ensureBacking();
267             layerChanged = true;
268         }
269     } else {
270         if (layer->backing()) {
271             // If we're removing backing on a reflection, clear the source GraphicsLayer's pointer to
272             // its replica GraphicsLayer. In practice this should never happen because reflectee and reflection 
273             // are both either composited, or not composited.
274             if (layer->isReflection()) {
275                 RenderLayer* sourceLayer = toRenderBoxModelObject(layer->renderer()->parent())->layer();
276                 if (RenderLayerBacking* backing = sourceLayer->backing()) {
277                     ASSERT(backing->graphicsLayer()->replicaLayer() == layer->backing()->graphicsLayer());
278                     backing->graphicsLayer()->setReplicatedByLayer(0);
279                 }
280             }
281             
282             layer->clearBacking();
283             layerChanged = true;
284
285             // The layer's cached repaints rects are relative to the repaint container, so change when
286             // compositing changes; we need to update them here.
287             layer->computeRepaintRects();
288
289             // If we need to repaint, do so now that we've removed the backing
290             if (shouldRepaint == CompositingChangeRepaintNow)
291                 repaintOnCompositingChange(layer);
292         }
293     }
294     
295 #if ENABLE(VIDEO)
296     if (layerChanged && layer->renderer()->isVideo()) {
297         // If it's a video, give the media player a chance to hook up to the layer.
298         RenderVideo* video = toRenderVideo(layer->renderer());
299         video->acceleratedRenderingStateChanged();
300     }
301 #endif
302
303     if (layerChanged && layer->renderer()->isRenderIFrame()) {
304         RenderLayerCompositor* innerCompositor = iframeContentsCompositor(toRenderIFrame(layer->renderer()));
305         if (innerCompositor && innerCompositor->inCompositingMode())
306             innerCompositor->updateRootLayerAttachment();
307     }
308
309     return layerChanged;
310 }
311
312 bool RenderLayerCompositor::updateLayerCompositingState(RenderLayer* layer, CompositingChangeRepaint shouldRepaint)
313 {
314     bool layerChanged = updateBacking(layer, shouldRepaint);
315
316     // See if we need content or clipping layers. Methods called here should assume
317     // that the compositing state of descendant layers has not been updated yet.
318     if (layer->backing() && layer->backing()->updateGraphicsLayerConfiguration())
319         layerChanged = true;
320
321     return layerChanged;
322 }
323
324 void RenderLayerCompositor::repaintOnCompositingChange(RenderLayer* layer)
325 {
326     // If the renderer is not attached yet, no need to repaint.
327     if (layer->renderer() != m_renderView && !layer->renderer()->parent())
328         return;
329
330     RenderBoxModelObject* repaintContainer = layer->renderer()->containerForRepaint();
331     if (!repaintContainer)
332         repaintContainer = m_renderView;
333
334     layer->repaintIncludingNonCompositingDescendants(repaintContainer);
335     if (repaintContainer == m_renderView) {
336         // The contents of this layer may be moving between the window
337         // and a GraphicsLayer, so we need to make sure the window system
338         // synchronizes those changes on the screen.
339         m_renderView->frameView()->setNeedsOneShotDrawingSynchronization();
340     }
341 }
342
343 // The bounds of the GraphicsLayer created for a compositing layer is the union of the bounds of all the descendant
344 // RenderLayers that are rendered by the composited RenderLayer.
345 IntRect RenderLayerCompositor::calculateCompositedBounds(const RenderLayer* layer, const RenderLayer* ancestorLayer)
346 {
347     if (!canBeComposited(layer))
348         return IntRect();
349
350     IntRect boundingBoxRect = layer->localBoundingBox();
351     if (layer->renderer()->isRoot()) {
352         // If the root layer becomes composited (e.g. because some descendant with negative z-index is composited),
353         // then it has to be big enough to cover the viewport in order to display the background. This is akin
354         // to the code in RenderBox::paintRootBoxDecorations().
355         if (m_renderView->frameView()) {
356             int rw = m_renderView->frameView()->contentsWidth();
357             int rh = m_renderView->frameView()->contentsHeight();
358             
359             boundingBoxRect.setWidth(max(boundingBoxRect.width(), rw - boundingBoxRect.x()));
360             boundingBoxRect.setHeight(max(boundingBoxRect.height(), rh - boundingBoxRect.y()));
361         }
362     }
363     
364     IntRect unionBounds = boundingBoxRect;
365     
366     if (layer->renderer()->hasOverflowClip() || layer->renderer()->hasMask()) {
367         int ancestorRelX = 0, ancestorRelY = 0;
368         layer->convertToLayerCoords(ancestorLayer, ancestorRelX, ancestorRelY);
369         boundingBoxRect.move(ancestorRelX, ancestorRelY);
370         return boundingBoxRect;
371     }
372
373     if (RenderLayer* reflection = layer->reflectionLayer()) {
374         if (!reflection->isComposited()) {
375             IntRect childUnionBounds = calculateCompositedBounds(reflection, layer);
376             unionBounds.unite(childUnionBounds);
377         }
378     }
379     
380     ASSERT(layer->isStackingContext() || (!layer->m_posZOrderList || layer->m_posZOrderList->size() == 0));
381
382     if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
383         size_t listSize = negZOrderList->size();
384         for (size_t i = 0; i < listSize; ++i) {
385             RenderLayer* curLayer = negZOrderList->at(i);
386             if (!curLayer->isComposited()) {
387                 IntRect childUnionBounds = calculateCompositedBounds(curLayer, layer);
388                 unionBounds.unite(childUnionBounds);
389             }
390         }
391     }
392
393     if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
394         size_t listSize = posZOrderList->size();
395         for (size_t i = 0; i < listSize; ++i) {
396             RenderLayer* curLayer = posZOrderList->at(i);
397             if (!curLayer->isComposited()) {
398                 IntRect childUnionBounds = calculateCompositedBounds(curLayer, layer);
399                 unionBounds.unite(childUnionBounds);
400             }
401         }
402     }
403
404     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
405         size_t listSize = normalFlowList->size();
406         for (size_t i = 0; i < listSize; ++i) {
407             RenderLayer* curLayer = normalFlowList->at(i);
408             if (!curLayer->isComposited()) {
409                 IntRect curAbsBounds = calculateCompositedBounds(curLayer, layer);
410                 unionBounds.unite(curAbsBounds);
411             }
412         }
413     }
414
415     if (layer->paintsWithTransform(PaintBehaviorNormal)) {
416         TransformationMatrix* affineTrans = layer->transform();
417         boundingBoxRect = affineTrans->mapRect(boundingBoxRect);
418         unionBounds = affineTrans->mapRect(unionBounds);
419     }
420
421     int ancestorRelX = 0, ancestorRelY = 0;
422     layer->convertToLayerCoords(ancestorLayer, ancestorRelX, ancestorRelY);
423     unionBounds.move(ancestorRelX, ancestorRelY);
424
425     return unionBounds;
426 }
427
428 void RenderLayerCompositor::layerWasAdded(RenderLayer* /*parent*/, RenderLayer* /*child*/)
429 {
430     setCompositingLayersNeedRebuild();
431 }
432
433 void RenderLayerCompositor::layerWillBeRemoved(RenderLayer* parent, RenderLayer* child)
434 {
435     if (!child->isComposited() || parent->renderer()->documentBeingDestroyed())
436         return;
437
438     setCompositingParent(child, 0);
439     
440     RenderLayer* compLayer = parent->enclosingCompositingLayer();
441     if (compLayer) {
442         ASSERT(compLayer->backing());
443         IntRect compBounds = child->backing()->compositedBounds();
444
445         int offsetX = 0, offsetY = 0;
446         child->convertToLayerCoords(compLayer, offsetX, offsetY);
447         compBounds.move(offsetX, offsetY);
448
449         compLayer->setBackingNeedsRepaintInRect(compBounds);
450
451         // The contents of this layer may be moving from a GraphicsLayer to the window,
452         // so we need to make sure the window system synchronizes those changes on the screen.
453         m_renderView->frameView()->setNeedsOneShotDrawingSynchronization();
454     }
455
456     setCompositingLayersNeedRebuild();
457 }
458
459 RenderLayer* RenderLayerCompositor::enclosingNonStackingClippingLayer(const RenderLayer* layer) const
460 {
461     for (RenderLayer* curr = layer->parent(); curr != 0; curr = curr->parent()) {
462         if (curr->isStackingContext())
463             return 0;
464
465         if (curr->renderer()->hasOverflowClip())
466             return curr;
467     }
468     return 0;
469 }
470
471 void RenderLayerCompositor::addToOverlapMap(OverlapMap& overlapMap, RenderLayer* layer, IntRect& layerBounds, bool& boundsComputed)
472 {
473     if (layer->isRootLayer())
474         return;
475
476     if (!boundsComputed) {
477         layerBounds = layer->renderer()->localToAbsoluteQuad(FloatRect(layer->localBoundingBox())).enclosingBoundingBox();
478         // Empty rects never intersect, but we need them to for the purposes of overlap testing.
479         if (layerBounds.isEmpty())
480             layerBounds.setSize(IntSize(1, 1));
481         boundsComputed = true;
482     }
483
484     overlapMap.add(layer, layerBounds);
485 }
486
487 bool RenderLayerCompositor::overlapsCompositedLayers(OverlapMap& overlapMap, const IntRect& layerBounds)
488 {
489     RenderLayerCompositor::OverlapMap::const_iterator end = overlapMap.end();
490     for (RenderLayerCompositor::OverlapMap::const_iterator it = overlapMap.begin(); it != end; ++it) {
491         const IntRect& bounds = it->second;
492         if (layerBounds.intersects(bounds))
493             return true;
494     }
495     
496     return false;
497 }
498
499 //  Recurse through the layers in z-index and overflow order (which is equivalent to painting order)
500 //  For the z-order children of a compositing layer:
501 //      If a child layers has a compositing layer, then all subsequent layers must
502 //      be compositing in order to render above that layer.
503 //
504 //      If a child in the negative z-order list is compositing, then the layer itself
505 //      must be compositing so that its contents render over that child.
506 //      This implies that its positive z-index children must also be compositing.
507 //
508 void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* layer, OverlapMap* overlapMap, struct CompositingState& compositingState, bool& layersChanged)
509 {
510     layer->updateLayerPosition();
511     layer->updateZOrderLists();
512     layer->updateNormalFlowList();
513     
514     // Clear the flag
515     layer->setHasCompositingDescendant(false);
516     
517     bool mustOverlapCompositedLayers = compositingState.m_subtreeIsCompositing;
518
519     bool haveComputedBounds = false;
520     IntRect absBounds;
521     if (overlapMap && !overlapMap->isEmpty()) {
522         // If we're testing for overlap, we only need to composite if we overlap something that is already composited.
523         absBounds = layer->renderer()->localToAbsoluteQuad(FloatRect(layer->localBoundingBox())).enclosingBoundingBox();
524         // Empty rects never intersect, but we need them to for the purposes of overlap testing.
525         if (absBounds.isEmpty())
526             absBounds.setSize(IntSize(1, 1));
527         haveComputedBounds = true;
528         mustOverlapCompositedLayers = overlapsCompositedLayers(*overlapMap, absBounds);
529     }
530     
531     layer->setMustOverlapCompositedLayers(mustOverlapCompositedLayers);
532     
533     // The children of this layer don't need to composite, unless there is
534     // a compositing layer among them, so start by inheriting the compositing
535     // ancestor with m_subtreeIsCompositing set to false.
536     CompositingState childState(compositingState.m_compositingAncestor);
537 #ifndef NDEBUG
538     ++childState.m_depth;
539 #endif
540
541     bool willBeComposited = needsToBeComposited(layer);
542     if (willBeComposited) {
543         // Tell the parent it has compositing descendants.
544         compositingState.m_subtreeIsCompositing = true;
545         // This layer now acts as the ancestor for kids.
546         childState.m_compositingAncestor = layer;
547         if (overlapMap)
548             addToOverlapMap(*overlapMap, layer, absBounds, haveComputedBounds);
549     }
550
551 #if ENABLE(VIDEO)
552     // Video is special. It's a replaced element with a content layer, but has shadow content
553     // for the controller that must render in front. Without this, the controls fail to show
554     // when the video element is a stacking context (e.g. due to opacity or transform).
555     if (willBeComposited && layer->renderer()->isVideo())
556         childState.m_subtreeIsCompositing = true;
557 #endif
558
559     if (layer->isStackingContext()) {
560         ASSERT(!layer->m_zOrderListsDirty);
561         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
562             size_t listSize = negZOrderList->size();
563             for (size_t i = 0; i < listSize; ++i) {
564                 RenderLayer* curLayer = negZOrderList->at(i);
565                 computeCompositingRequirements(curLayer, overlapMap, childState, layersChanged);
566
567                 // If we have to make a layer for this child, make one now so we can have a contents layer
568                 // (since we need to ensure that the -ve z-order child renders underneath our contents).
569                 if (!willBeComposited && childState.m_subtreeIsCompositing) {
570                     // make layer compositing
571                     layer->setMustOverlapCompositedLayers(true);
572                     childState.m_compositingAncestor = layer;
573                     if (overlapMap)
574                         addToOverlapMap(*overlapMap, layer, absBounds, haveComputedBounds);
575                     willBeComposited = true;
576                 }
577             }
578         }
579     }
580     
581     ASSERT(!layer->m_normalFlowListDirty);
582     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
583         size_t listSize = normalFlowList->size();
584         for (size_t i = 0; i < listSize; ++i) {
585             RenderLayer* curLayer = normalFlowList->at(i);
586             computeCompositingRequirements(curLayer, overlapMap, childState, layersChanged);
587         }
588     }
589
590     if (layer->isStackingContext()) {
591         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
592             size_t listSize = posZOrderList->size();
593             for (size_t i = 0; i < listSize; ++i) {
594                 RenderLayer* curLayer = posZOrderList->at(i);
595                 computeCompositingRequirements(curLayer, overlapMap, childState, layersChanged);
596             }
597         }
598     }
599
600     ASSERT(willBeComposited == needsToBeComposited(layer));
601
602     // If we have a software transform, and we have layers under us, we need to also
603     // be composited. Also, if we have opacity < 1, then we need to be a layer so that
604     // the child layers are opaque, then rendered with opacity on this layer.
605     if (!willBeComposited && canBeComposited(layer) && childState.m_subtreeIsCompositing && requiresCompositingWhenDescendantsAreCompositing(layer->renderer())) {
606         layer->setMustOverlapCompositedLayers(true);
607         if (overlapMap)
608             addToOverlapMap(*overlapMap, layer, absBounds, haveComputedBounds);
609         willBeComposited = true;
610     }
611
612     ASSERT(willBeComposited == needsToBeComposited(layer));
613     if (layer->reflectionLayer())
614         layer->reflectionLayer()->setMustOverlapCompositedLayers(willBeComposited);
615
616     // Subsequent layers in the parent stacking context also need to composite.
617     if (childState.m_subtreeIsCompositing)
618         compositingState.m_subtreeIsCompositing = true;
619
620     // Set the flag to say that this SC has compositing children.
621     layer->setHasCompositingDescendant(childState.m_subtreeIsCompositing);
622
623     // setHasCompositingDescendant() may have changed the answer to needsToBeComposited() when clipping,
624     // so test that again.
625     if (!willBeComposited && canBeComposited(layer) && clipsCompositingDescendants(layer)) {
626         if (overlapMap)
627             addToOverlapMap(*overlapMap, layer, absBounds, haveComputedBounds);
628         willBeComposited = true;
629     }
630
631     // If we're back at the root, and no other layers need to be composited, and the root layer itself doesn't need
632     // to be composited, then we can drop out of compositing mode altogether.
633     if (layer->isRootLayer() && !childState.m_subtreeIsCompositing && !requiresCompositingLayer(layer)) {
634         m_compositing = false;
635         willBeComposited = false;
636     }
637     
638     // If the layer is going into compositing mode, repaint its old location.
639     ASSERT(willBeComposited == needsToBeComposited(layer));
640     if (!layer->isComposited() && willBeComposited)
641         repaintOnCompositingChange(layer);
642
643     // Update backing now, so that we can use isComposited() reliably during tree traversal in rebuildCompositingLayerTree().
644     if (updateBacking(layer, CompositingChangeRepaintNow))
645         layersChanged = true;
646
647     if (layer->reflectionLayer() && updateLayerCompositingState(layer->reflectionLayer(), CompositingChangeRepaintNow))
648         layersChanged = true;
649 }
650
651 void RenderLayerCompositor::setCompositingParent(RenderLayer* childLayer, RenderLayer* parentLayer)
652 {
653     ASSERT(!parentLayer || childLayer->ancestorCompositingLayer() == parentLayer);
654     ASSERT(childLayer->isComposited());
655
656     // It's possible to be called with a parent that isn't yet composited when we're doing
657     // partial updates as required by painting or hit testing. Just bail in that case;
658     // we'll do a full layer update soon.
659     if (!parentLayer || !parentLayer->isComposited())
660         return;
661
662     if (parentLayer) {
663         GraphicsLayer* hostingLayer = parentLayer->backing()->parentForSublayers();
664         GraphicsLayer* hostedLayer = childLayer->backing()->childForSuperlayers();
665         
666         hostingLayer->addChild(hostedLayer);
667     } else
668         childLayer->backing()->childForSuperlayers()->removeFromParent();
669 }
670
671 void RenderLayerCompositor::removeCompositedChildren(RenderLayer* layer)
672 {
673     ASSERT(layer->isComposited());
674
675     GraphicsLayer* hostingLayer = layer->backing()->parentForSublayers();
676     hostingLayer->removeAllChildren();
677 }
678
679 #if ENABLE(VIDEO)
680 bool RenderLayerCompositor::canAccelerateVideoRendering(RenderVideo* o) const
681 {
682     if (!m_hasAcceleratedCompositing)
683         return false;
684
685     return o->supportsAcceleratedRendering();
686 }
687 #endif
688
689 void RenderLayerCompositor::rebuildCompositingLayerTree(RenderLayer* layer, const CompositingState& compositingState, Vector<GraphicsLayer*>& childLayersOfEnclosingLayer)
690 {
691     // Make the layer compositing if necessary, and set up clipping and content layers.
692     // Note that we can only do work here that is independent of whether the descendant layers
693     // have been processed. computeCompositingRequirements() will already have done the repaint if necessary.
694     
695     RenderLayerBacking* layerBacking = layer->backing();
696     if (layerBacking) {
697         // The compositing state of all our children has been updated already, so now
698         // we can compute and cache the composited bounds for this layer.
699         layerBacking->updateCompositedBounds();
700
701         if (RenderLayer* reflection = layer->reflectionLayer()) {
702             if (reflection->backing())
703                 reflection->backing()->updateCompositedBounds();
704         }
705
706         layerBacking->updateGraphicsLayerConfiguration();
707         layerBacking->updateGraphicsLayerGeometry();
708
709         if (!layer->parent())
710             updateRootLayerPosition();
711     }
712
713     // If this layer has backing, then we are collecting its children, otherwise appending
714     // to the compositing child list of an enclosing layer.
715     Vector<GraphicsLayer*> layerChildren;
716     Vector<GraphicsLayer*>& childList = layerBacking ? layerChildren : childLayersOfEnclosingLayer;
717
718     CompositingState childState = compositingState;
719     if (layer->isComposited())
720         childState.m_compositingAncestor = layer;
721
722 #ifndef NDEBUG
723     ++childState.m_depth;
724 #endif
725
726     // The children of this stacking context don't need to composite, unless there is
727     // a compositing layer among them, so start by assuming false.
728     childState.m_subtreeIsCompositing = false;
729
730     if (layer->isStackingContext()) {
731         ASSERT(!layer->m_zOrderListsDirty);
732
733         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
734             size_t listSize = negZOrderList->size();
735             for (size_t i = 0; i < listSize; ++i) {
736                 RenderLayer* curLayer = negZOrderList->at(i);
737                 rebuildCompositingLayerTree(curLayer, childState, childList);
738             }
739         }
740
741         // If a negative z-order child is compositing, we get a foreground layer which needs to get parented.
742         if (layerBacking && layerBacking->foregroundLayer())
743             childList.append(layerBacking->foregroundLayer());
744     }
745
746     ASSERT(!layer->m_normalFlowListDirty);
747     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
748         size_t listSize = normalFlowList->size();
749         for (size_t i = 0; i < listSize; ++i) {
750             RenderLayer* curLayer = normalFlowList->at(i);
751             rebuildCompositingLayerTree(curLayer, childState, childList);
752         }
753     }
754     
755     if (layer->isStackingContext()) {
756         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
757             size_t listSize = posZOrderList->size();
758             for (size_t i = 0; i < listSize; ++i) {
759                 RenderLayer* curLayer = posZOrderList->at(i);
760                 rebuildCompositingLayerTree(curLayer, childState, childList);
761             }
762         }
763     }
764     
765     if (layerBacking) {
766         bool parented = false;
767         if (layer->renderer()->isRenderIFrame())
768             parented = parentIFrameContentLayers(toRenderIFrame(layer->renderer()));
769         
770         if (!parented)
771             layerBacking->parentForSublayers()->setChildren(layerChildren);
772
773         childLayersOfEnclosingLayer.append(layerBacking->childForSuperlayers());
774     }
775 }
776
777 void RenderLayerCompositor::setRootPlatformLayerClippingBox(const IntRect& contentsBox)
778 {
779     if (m_clippingLayer) {
780         m_clippingLayer->setPosition(FloatPoint(contentsBox.x(), contentsBox.y()));
781         m_clippingLayer->setSize(FloatSize(contentsBox.width(), contentsBox.height()));
782     }
783 }
784
785 RenderLayerCompositor* RenderLayerCompositor::iframeContentsCompositor(RenderIFrame* renderer)
786 {
787     HTMLIFrameElement* element = static_cast<HTMLIFrameElement*>(renderer->node());
788     if (Document* contentDocument = element->contentDocument()) {
789         if (RenderView* view = contentDocument->renderView())
790             return view->compositor();
791     }
792     return 0;
793 }
794
795 bool RenderLayerCompositor::parentIFrameContentLayers(RenderIFrame* renderer)
796 {
797     RenderLayerCompositor* innerCompositor = iframeContentsCompositor(renderer);
798     if (!innerCompositor || !innerCompositor->inCompositingMode() || innerCompositor->rootLayerAttachment() != RootLayerAttachedViaEnclosingIframe)
799         return false;
800     
801     RenderLayer* layer = renderer->layer();
802     if (!layer->isComposited())
803         return false;
804
805     RenderLayerBacking* backing = layer->backing();
806     GraphicsLayer* hostingLayer = backing->parentForSublayers();
807     GraphicsLayer* rootLayer = innerCompositor->rootPlatformLayer();
808     if (hostingLayer->children().size() != 1 || hostingLayer->children()[0] != rootLayer) {
809         hostingLayer->removeAllChildren();
810         hostingLayer->addChild(rootLayer);
811     }
812     return true;
813 }
814
815 // This just updates layer geometry without changing the hierarchy.
816 void RenderLayerCompositor::updateLayerTreeGeometry(RenderLayer* layer)
817 {
818     if (RenderLayerBacking* layerBacking = layer->backing()) {
819         // The compositing state of all our children has been updated already, so now
820         // we can compute and cache the composited bounds for this layer.
821         layerBacking->updateCompositedBounds();
822
823         if (RenderLayer* reflection = layer->reflectionLayer()) {
824             if (reflection->backing())
825                 reflection->backing()->updateCompositedBounds();
826         }
827
828         layerBacking->updateGraphicsLayerConfiguration();
829         layerBacking->updateGraphicsLayerGeometry();
830
831         if (!layer->parent())
832             updateRootLayerPosition();
833     }
834
835     if (layer->isStackingContext()) {
836         ASSERT(!layer->m_zOrderListsDirty);
837
838         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
839             size_t listSize = negZOrderList->size();
840             for (size_t i = 0; i < listSize; ++i)
841                 updateLayerTreeGeometry(negZOrderList->at(i));
842         }
843     }
844
845     ASSERT(!layer->m_normalFlowListDirty);
846     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
847         size_t listSize = normalFlowList->size();
848         for (size_t i = 0; i < listSize; ++i)
849             updateLayerTreeGeometry(normalFlowList->at(i));
850     }
851     
852     if (layer->isStackingContext()) {
853         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
854             size_t listSize = posZOrderList->size();
855             for (size_t i = 0; i < listSize; ++i)
856                 updateLayerTreeGeometry(posZOrderList->at(i));
857         }
858     }
859 }
860
861 // Recurs down the RenderLayer tree until its finds the compositing descendants of compositingAncestor and updates their geometry.
862 void RenderLayerCompositor::updateCompositingDescendantGeometry(RenderLayer* compositingAncestor, RenderLayer* layer, RenderLayerBacking::UpdateDepth updateDepth)
863 {
864     if (layer != compositingAncestor) {
865         if (RenderLayerBacking* layerBacking = layer->backing()) {
866             layerBacking->updateCompositedBounds();
867
868             if (RenderLayer* reflection = layer->reflectionLayer()) {
869                 if (reflection->backing())
870                     reflection->backing()->updateCompositedBounds();
871             }
872
873             layerBacking->updateGraphicsLayerGeometry();
874             if (updateDepth == RenderLayerBacking::CompositingChildren)
875                 return;
876         }
877     }
878
879     if (layer->reflectionLayer())
880         updateCompositingDescendantGeometry(compositingAncestor, layer->reflectionLayer(), updateDepth);
881
882     if (!layer->hasCompositingDescendant())
883         return;
884     
885     if (layer->isStackingContext()) {
886         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
887             size_t listSize = negZOrderList->size();
888             for (size_t i = 0; i < listSize; ++i)
889                 updateCompositingDescendantGeometry(compositingAncestor, negZOrderList->at(i), updateDepth);
890         }
891     }
892
893     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
894         size_t listSize = normalFlowList->size();
895         for (size_t i = 0; i < listSize; ++i)
896             updateCompositingDescendantGeometry(compositingAncestor, normalFlowList->at(i), updateDepth);
897     }
898     
899     if (layer->isStackingContext()) {
900         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
901             size_t listSize = posZOrderList->size();
902             for (size_t i = 0; i < listSize; ++i)
903                 updateCompositingDescendantGeometry(compositingAncestor, posZOrderList->at(i), updateDepth);
904         }
905     }
906 }
907
908
909 void RenderLayerCompositor::repaintCompositedLayersAbsoluteRect(const IntRect& absRect)
910 {
911     recursiveRepaintLayerRect(rootRenderLayer(), absRect);
912 }
913
914 void RenderLayerCompositor::recursiveRepaintLayerRect(RenderLayer* layer, const IntRect& rect)
915 {
916     // FIXME: This method does not work correctly with transforms.
917     if (layer->isComposited())
918         layer->setBackingNeedsRepaintInRect(rect);
919
920     if (layer->hasCompositingDescendant()) {
921         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
922             size_t listSize = negZOrderList->size();
923             for (size_t i = 0; i < listSize; ++i) {
924                 RenderLayer* curLayer = negZOrderList->at(i);
925                 int x = 0;
926                 int y = 0;
927                 curLayer->convertToLayerCoords(layer, x, y);
928                 IntRect childRect(rect);
929                 childRect.move(-x, -y);
930                 recursiveRepaintLayerRect(curLayer, childRect);
931             }
932         }
933
934         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
935             size_t listSize = posZOrderList->size();
936             for (size_t i = 0; i < listSize; ++i) {
937                 RenderLayer* curLayer = posZOrderList->at(i);
938                 int x = 0;
939                 int y = 0;
940                 curLayer->convertToLayerCoords(layer, x, y);
941                 IntRect childRect(rect);
942                 childRect.move(-x, -y);
943                 recursiveRepaintLayerRect(curLayer, childRect);
944             }
945         }
946     }
947     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
948         size_t listSize = normalFlowList->size();
949         for (size_t i = 0; i < listSize; ++i) {
950             RenderLayer* curLayer = normalFlowList->at(i);
951             int x = 0;
952             int y = 0;
953             curLayer->convertToLayerCoords(layer, x, y);
954             IntRect childRect(rect);
955             childRect.move(-x, -y);
956             recursiveRepaintLayerRect(curLayer, childRect);
957         }
958     }
959 }
960
961 RenderLayer* RenderLayerCompositor::rootRenderLayer() const
962 {
963     return m_renderView->layer();
964 }
965
966 GraphicsLayer* RenderLayerCompositor::rootPlatformLayer() const
967 {
968     return m_clippingLayer ? m_clippingLayer.get() : m_rootPlatformLayer.get();
969 }
970
971 void RenderLayerCompositor::didMoveOnscreen()
972 {
973     if (!inCompositingMode() || m_rootLayerAttachment != RootLayerUnattached)
974         return;
975
976     RootLayerAttachment attachment = shouldPropagateCompositingToEnclosingIFrame() ? RootLayerAttachedViaEnclosingIframe : RootLayerAttachedViaChromeClient;
977     attachRootPlatformLayer(attachment);
978 }
979
980 void RenderLayerCompositor::willMoveOffscreen()
981 {
982     if (!inCompositingMode() || m_rootLayerAttachment == RootLayerUnattached)
983         return;
984
985     detachRootPlatformLayer();
986 }
987
988 void RenderLayerCompositor::updateRootLayerPosition()
989 {
990     // Eventually we will need to account for scrolling here.
991     // https://bugs.webkit.org/show_bug.cgi?id=38518
992     if (m_rootPlatformLayer)
993         m_rootPlatformLayer->setSize(FloatSize(m_renderView->rightLayoutOverflow(), m_renderView->bottomLayoutOverflow()));
994 }
995
996 void RenderLayerCompositor::didStartAcceleratedAnimation()
997 {
998     // If an accelerated animation or transition runs, we have to turn off overlap checking because
999     // we don't do layout for every frame, but we have to ensure that the layering is
1000     // correct between the animating object and other objects on the page.
1001     setCompositingConsultsOverlap(false);
1002 }
1003
1004 bool RenderLayerCompositor::has3DContent() const
1005 {
1006     return layerHas3DContent(rootRenderLayer());
1007 }
1008
1009 bool RenderLayerCompositor::shouldPropagateCompositingToEnclosingIFrame() const
1010 {
1011     // Parent document content needs to be able to render on top of a composited iframe, so correct behavior
1012     // is to have the parent document become composited too. However, this can cause problems on platforms that
1013     // use native views for frames (like Mac), so disable that behavior on those platforms for now.
1014     Element* ownerElement = enclosingIFrameElement();
1015     RenderObject* renderer = ownerElement ? ownerElement->renderer() : 0;
1016     if (!renderer || !renderer->isRenderIFrame())
1017         return false;
1018
1019 #if !PLATFORM(MAC)
1020     // On non-Mac platforms, let compositing propagate for all iframes.
1021     return true;
1022 #else
1023     // On Mac, only propagate compositing if the iframe is overlapped in the parent
1024     // document, or the parent is already compositing.
1025     RenderIFrame* iframeRenderer = toRenderIFrame(renderer);
1026     if (iframeRenderer->widget()) {
1027         ASSERT(iframeRenderer->widget()->isFrameView());
1028         FrameView* view = static_cast<FrameView*>(iframeRenderer->widget());
1029         if (view->isOverlapped())
1030             return true;
1031         
1032         if (RenderView* view = iframeRenderer->view()) {
1033             if (view->compositor()->inCompositingMode())
1034                 return true;
1035         }
1036     }
1037
1038     return false;
1039 #endif
1040 }
1041
1042 Element* RenderLayerCompositor::enclosingIFrameElement() const
1043 {
1044     if (Element* ownerElement = m_renderView->document()->ownerElement())
1045         return ownerElement->hasTagName(iframeTag) ? ownerElement : 0;
1046
1047     return 0;
1048 }
1049
1050 bool RenderLayerCompositor::needsToBeComposited(const RenderLayer* layer) const
1051 {
1052     if (!canBeComposited(layer))
1053         return false;
1054
1055     return requiresCompositingLayer(layer) || layer->mustOverlapCompositedLayers() || (inCompositingMode() && layer->isRootLayer());
1056 }
1057
1058 // Note: this specifies whether the RL needs a compositing layer for intrinsic reasons.
1059 // Use needsToBeComposited() to determine if a RL actually needs a compositing layer.
1060 // static
1061 bool RenderLayerCompositor::requiresCompositingLayer(const RenderLayer* layer) const
1062 {
1063     RenderObject* renderer = layer->renderer();
1064     // The compositing state of a reflection should match that of its reflected layer.
1065     if (layer->isReflection()) {
1066         renderer = renderer->parent(); // The RenderReplica's parent is the object being reflected.
1067         layer = toRenderBoxModelObject(renderer)->layer();
1068     }
1069     // The root layer always has a compositing layer, but it may not have backing.
1070     return requiresCompositingForTransform(renderer)
1071              || requiresCompositingForVideo(renderer)
1072              || requiresCompositingForCanvas(renderer)
1073              || requiresCompositingForPlugin(renderer)
1074              || requiresCompositingForIFrame(renderer)
1075              || renderer->style()->backfaceVisibility() == BackfaceVisibilityHidden
1076              || clipsCompositingDescendants(layer)
1077              || requiresCompositingForAnimation(renderer);
1078 }
1079
1080 bool RenderLayerCompositor::canBeComposited(const RenderLayer* layer) const
1081 {
1082     return m_hasAcceleratedCompositing && layer->isSelfPaintingLayer();
1083 }
1084
1085 // Return true if the given layer has some ancestor in the RenderLayer hierarchy that clips,
1086 // up to the enclosing compositing ancestor. This is required because compositing layers are parented
1087 // according to the z-order hierarchy, yet clipping goes down the renderer hierarchy.
1088 // Thus, a RenderLayer can be clipped by a RenderLayer that is an ancestor in the renderer hierarchy,
1089 // but a sibling in the z-order hierarchy.
1090 bool RenderLayerCompositor::clippedByAncestor(RenderLayer* layer) const
1091 {
1092     if (!layer->isComposited() || !layer->parent())
1093         return false;
1094
1095     RenderLayer* compositingAncestor = layer->ancestorCompositingLayer();
1096     if (!compositingAncestor)
1097         return false;
1098
1099     // If the compositingAncestor clips, that will be taken care of by clipsCompositingDescendants(),
1100     // so we only care about clipping between its first child that is our ancestor (the computeClipRoot),
1101     // and layer.
1102     RenderLayer* computeClipRoot = 0;
1103     RenderLayer* curr = layer;
1104     while (curr) {
1105         RenderLayer* next = curr->parent();
1106         if (next == compositingAncestor) {
1107             computeClipRoot = curr;
1108             break;
1109         }
1110         curr = next;
1111     }
1112     
1113     if (!computeClipRoot || computeClipRoot == layer)
1114         return false;
1115
1116     IntRect backgroundRect = layer->backgroundClipRect(computeClipRoot, true);
1117     return backgroundRect != ClipRects::infiniteRect();
1118 }
1119
1120 // Return true if the given layer is a stacking context and has compositing child
1121 // layers that it needs to clip. In this case we insert a clipping GraphicsLayer
1122 // into the hierarchy between this layer and its children in the z-order hierarchy.
1123 bool RenderLayerCompositor::clipsCompositingDescendants(const RenderLayer* layer) const
1124 {
1125     // FIXME: need to look at hasClip() too eventually
1126     return layer->hasCompositingDescendant() &&
1127            layer->renderer()->hasOverflowClip();
1128 }
1129
1130 bool RenderLayerCompositor::requiresCompositingForTransform(RenderObject* renderer) const
1131 {
1132     RenderStyle* style = renderer->style();
1133     // Note that we ask the renderer if it has a transform, because the style may have transforms,
1134     // but the renderer may be an inline that doesn't suppport them.
1135     return renderer->hasTransform() && (style->transform().has3DOperation() || style->transformStyle3D() == TransformStyle3DPreserve3D || style->hasPerspective());
1136 }
1137
1138 bool RenderLayerCompositor::requiresCompositingForVideo(RenderObject* renderer) const
1139 {
1140 #if ENABLE(VIDEO)
1141     if (renderer->isVideo()) {
1142         RenderVideo* video = toRenderVideo(renderer);
1143         return canAccelerateVideoRendering(video);
1144     }
1145 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
1146     else if (renderer->isRenderPart()) {
1147         if (!m_hasAcceleratedCompositing)
1148             return false;
1149
1150         Node* node = renderer->node();
1151         if (!node || (!node->hasTagName(HTMLNames::videoTag) && !node->hasTagName(HTMLNames::audioTag)))
1152             return false;
1153
1154         HTMLMediaElement* mediaElement = static_cast<HTMLMediaElement*>(node);
1155         return mediaElement->player() ? mediaElement->player()->supportsAcceleratedRendering() : false;
1156     }
1157 #endif // ENABLE(PLUGIN_PROXY_FOR_VIDEO)
1158 #else
1159     UNUSED_PARAM(renderer);
1160 #endif
1161     return false;
1162 }
1163
1164 bool RenderLayerCompositor::requiresCompositingForCanvas(RenderObject* renderer) const
1165 {
1166 #if ENABLE(3D_CANVAS)    
1167     if (renderer->isCanvas()) {
1168         HTMLCanvasElement* canvas = static_cast<HTMLCanvasElement*>(renderer->node());
1169         return canvas->is3D();
1170     }
1171 #else
1172     UNUSED_PARAM(renderer);
1173 #endif
1174     return false;
1175 }
1176
1177 bool RenderLayerCompositor::requiresCompositingForPlugin(RenderObject* renderer) const
1178 {
1179     return renderer->isEmbeddedObject() && toRenderEmbeddedObject(renderer)->allowsAcceleratedCompositing();
1180 }
1181
1182 bool RenderLayerCompositor::requiresCompositingForIFrame(RenderObject* renderer) const
1183 {
1184     if (!renderer->isRenderIFrame())
1185         return false;
1186     
1187     RenderIFrame* iframe = toRenderIFrame(renderer);
1188
1189     if (!iframe->requiresAcceleratedCompositing())
1190         return false;
1191         
1192     RenderLayerCompositor* innerCompositor = iframeContentsCompositor(iframe);
1193     return innerCompositor->shouldPropagateCompositingToEnclosingIFrame();
1194 }
1195
1196 bool RenderLayerCompositor::requiresCompositingForAnimation(RenderObject* renderer) const
1197 {
1198     if (AnimationController* animController = renderer->animation()) {
1199         return (animController->isAnimatingPropertyOnRenderer(renderer, CSSPropertyOpacity) && inCompositingMode())
1200             || animController->isAnimatingPropertyOnRenderer(renderer, CSSPropertyWebkitTransform);
1201     }
1202     return false;
1203 }
1204
1205 bool RenderLayerCompositor::requiresCompositingWhenDescendantsAreCompositing(RenderObject* renderer) const
1206 {
1207     return renderer->hasTransform() || renderer->isTransparent() || renderer->hasMask() || renderer->hasReflection();
1208 }
1209
1210 // If an element has negative z-index children, those children render in front of the 
1211 // layer background, so we need an extra 'contents' layer for the foreground of the layer
1212 // object.
1213 bool RenderLayerCompositor::needsContentsCompositingLayer(const RenderLayer* layer) const
1214 {
1215     return (layer->m_negZOrderList && layer->m_negZOrderList->size() > 0);
1216 }
1217
1218 void RenderLayerCompositor::ensureRootPlatformLayer()
1219 {
1220     RootLayerAttachment expectedAttachment = shouldPropagateCompositingToEnclosingIFrame() ? RootLayerAttachedViaEnclosingIframe : RootLayerAttachedViaChromeClient;
1221     if (expectedAttachment == m_rootLayerAttachment)
1222          return;
1223
1224     if (!m_rootPlatformLayer) {
1225         m_rootPlatformLayer = GraphicsLayer::create(0);
1226 #ifndef NDEBUG
1227         m_rootPlatformLayer->setName("Root platform");
1228 #endif
1229         m_rootPlatformLayer->setSize(FloatSize(m_renderView->rightLayoutOverflow(), m_renderView->bottomLayoutOverflow()));
1230         m_rootPlatformLayer->setPosition(FloatPoint());
1231
1232         // Need to clip to prevent transformed content showing outside this frame
1233         m_rootPlatformLayer->setMasksToBounds(true);
1234     }
1235
1236     // The root layer does flipping if we need it on this platform.
1237     m_rootPlatformLayer->setGeometryOrientation(expectedAttachment == RootLayerAttachedViaEnclosingIframe ? GraphicsLayer::CompositingCoordinatesTopDown : GraphicsLayer::compositingCoordinatesOrientation());
1238     
1239     if (expectedAttachment == RootLayerAttachedViaEnclosingIframe) {
1240         if (!m_clippingLayer) {
1241             // Create a clipping layer if this is an iframe
1242             m_clippingLayer = GraphicsLayer::create(0);
1243 #ifndef NDEBUG
1244             m_clippingLayer->setName("iframe Clipping");
1245 #endif
1246             m_clippingLayer->setMasksToBounds(true);
1247             m_clippingLayer->addChild(m_rootPlatformLayer.get());
1248         }
1249     } else if (m_clippingLayer) {
1250         m_clippingLayer->removeAllChildren();
1251         m_clippingLayer->removeFromParent();
1252         m_clippingLayer = 0;
1253     }
1254
1255     // Check to see if we have to change the attachment
1256     if (m_rootLayerAttachment != RootLayerUnattached)
1257         detachRootPlatformLayer();
1258
1259     attachRootPlatformLayer(expectedAttachment);
1260 }
1261
1262 void RenderLayerCompositor::destroyRootPlatformLayer()
1263 {
1264     if (!m_rootPlatformLayer)
1265         return;
1266
1267     detachRootPlatformLayer();
1268     if (m_clippingLayer) {
1269         m_clippingLayer->removeAllChildren();
1270         m_clippingLayer = 0;
1271     }
1272     m_rootPlatformLayer = 0;
1273 }
1274
1275 void RenderLayerCompositor::attachRootPlatformLayer(RootLayerAttachment attachment)
1276 {
1277     if (!m_rootPlatformLayer)
1278         return;
1279
1280     switch (attachment) {
1281         case RootLayerUnattached:
1282             ASSERT_NOT_REACHED();
1283             break;
1284         case RootLayerAttachedViaChromeClient: {
1285             Frame* frame = m_renderView->frameView()->frame();
1286             Page* page = frame ? frame->page() : 0;
1287             if (!page)
1288                 return;
1289
1290             page->chrome()->client()->attachRootGraphicsLayer(frame, m_rootPlatformLayer.get());
1291             break;
1292         }
1293         case RootLayerAttachedViaEnclosingIframe: {
1294             // The layer will get hooked up via RenderLayerBacking::updateGraphicsLayerConfiguration()
1295             // for the iframe's renderer in the parent document.
1296             m_renderView->document()->ownerElement()->setNeedsStyleRecalc(SyntheticStyleChange);
1297             break;
1298         }
1299     }
1300     
1301     m_rootLayerAttachment = attachment;
1302     rootLayerAttachmentChanged();
1303 }
1304
1305 void RenderLayerCompositor::detachRootPlatformLayer()
1306 {
1307     if (!m_rootPlatformLayer || m_rootLayerAttachment == RootLayerUnattached)
1308         return;
1309
1310     switch (m_rootLayerAttachment) {
1311         case RootLayerAttachedViaEnclosingIframe: {
1312             // The layer will get unhooked up via RenderLayerBacking::updateGraphicsLayerConfiguration()
1313             // for the iframe's renderer in the parent document.
1314             if (m_clippingLayer)
1315                 m_clippingLayer->removeFromParent();
1316             else
1317                 m_rootPlatformLayer->removeFromParent();
1318
1319             m_renderView->document()->ownerElement()->setNeedsStyleRecalc(SyntheticStyleChange);
1320             break;
1321         }
1322         case RootLayerAttachedViaChromeClient: {
1323             Frame* frame = m_renderView->frameView()->frame();
1324             Page* page = frame ? frame->page() : 0;
1325             if (!page)
1326                 return;
1327
1328             page->chrome()->client()->attachRootGraphicsLayer(frame, 0);
1329         }
1330         break;
1331         case RootLayerUnattached:
1332             break;
1333     }
1334
1335     m_rootLayerAttachment = RootLayerUnattached;
1336     rootLayerAttachmentChanged();
1337 }
1338
1339 void RenderLayerCompositor::updateRootLayerAttachment()
1340 {
1341     ensureRootPlatformLayer();
1342 }
1343
1344 void RenderLayerCompositor::rootLayerAttachmentChanged()
1345 {
1346     // The attachment can affect whether the RenderView layer's paintingGoesToWindow() behavior,
1347     // so call updateGraphicsLayerGeometry() to udpate that.
1348     RenderLayer* layer = m_renderView->layer();
1349     if (RenderLayerBacking* backing = layer ? layer->backing() : 0)
1350         backing->updateDrawsContent();
1351 }
1352
1353 // IFrames are special, because we hook compositing layers together across iframe boundaries
1354 // when both parent and iframe content are composited. So when this frame becomes composited, we have
1355 // to use a synthetic style change to get the iframes into RenderLayers in order to allow them to composite.
1356 void RenderLayerCompositor::notifyIFramesOfCompositingChange()
1357 {
1358     Frame* frame = m_renderView->frameView() ? m_renderView->frameView()->frame() : 0;
1359     if (!frame)
1360         return;
1361
1362     for (Frame* child = frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
1363         if (child->document() && child->document()->ownerElement())
1364             child->document()->ownerElement()->setNeedsStyleRecalc(SyntheticStyleChange);
1365     }
1366 }
1367
1368 bool RenderLayerCompositor::layerHas3DContent(const RenderLayer* layer) const
1369 {
1370     const RenderStyle* style = layer->renderer()->style();
1371
1372     if (style && 
1373         (style->transformStyle3D() == TransformStyle3DPreserve3D ||
1374          style->hasPerspective() ||
1375          style->transform().has3DOperation()))
1376         return true;
1377
1378     if (layer->isStackingContext()) {
1379         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
1380             size_t listSize = negZOrderList->size();
1381             for (size_t i = 0; i < listSize; ++i) {
1382                 RenderLayer* curLayer = negZOrderList->at(i);
1383                 if (layerHas3DContent(curLayer))
1384                     return true;
1385             }
1386         }
1387
1388         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
1389             size_t listSize = posZOrderList->size();
1390             for (size_t i = 0; i < listSize; ++i) {
1391                 RenderLayer* curLayer = posZOrderList->at(i);
1392                 if (layerHas3DContent(curLayer))
1393                     return true;
1394             }
1395         }
1396     }
1397
1398     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
1399         size_t listSize = normalFlowList->size();
1400         for (size_t i = 0; i < listSize; ++i) {
1401             RenderLayer* curLayer = normalFlowList->at(i);
1402             if (layerHas3DContent(curLayer))
1403                 return true;
1404         }
1405     }
1406     return false;
1407 }
1408
1409 } // namespace WebCore
1410
1411 #endif // USE(ACCELERATED_COMPOSITING)
1412