Compositing overlap testing can throw layers into compositing when they should not be.
[WebKit-https.git] / Source / 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 "CanvasRenderingContext.h"
33 #include "CSSPropertyNames.h"
34 #include "Chrome.h"
35 #include "ChromeClient.h"
36 #include "Frame.h"
37 #include "FrameView.h"
38 #include "GraphicsLayer.h"
39 #include "HTMLCanvasElement.h"
40 #include "HTMLIFrameElement.h"
41 #include "HTMLNames.h"
42 #include "HitTestResult.h"
43 #include "NodeList.h"
44 #include "Page.h"
45 #include "RenderApplet.h"
46 #include "RenderEmbeddedObject.h"
47 #include "RenderFullScreen.h"
48 #include "RenderIFrame.h"
49 #include "RenderLayerBacking.h"
50 #include "RenderReplica.h"
51 #include "RenderVideo.h"
52 #include "RenderView.h"
53 #include "ScrollbarTheme.h"
54 #include "ScrollingCoordinator.h"
55 #include "Settings.h"
56
57 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
58 #include "HTMLMediaElement.h"
59 #endif
60
61 #if PROFILE_LAYER_REBUILD
62 #include <wtf/CurrentTime.h>
63 #endif
64
65 #ifndef NDEBUG
66 #include "RenderTreeAsText.h"
67 #endif
68
69 #if ENABLE(3D_RENDERING)
70 // This symbol is used to determine from a script whether 3D rendering is enabled (via 'nm').
71 bool WebCoreHas3DRendering = true;
72 #endif
73
74 namespace WebCore {
75
76 using namespace HTMLNames;
77
78 class RenderLayerCompositor::OverlapMap {
79     WTF_MAKE_NONCOPYABLE(OverlapMap);
80 public:
81     OverlapMap()
82     {
83         // Begin assuming the root layer will be composited so that there is
84         // something on the stack. The root layer should also never get an
85         // popCompositingContainer call.
86         pushCompositingContainer();
87     }
88
89     void add(const RenderLayer* layer, const IntRect& bounds)
90     {
91         // Layers do not contribute to overlap immediately--instead, they will
92         // contribute to overlap as soon as their composited ancestor has been
93         // recursively processed and popped off the stack.
94         ASSERT(m_overlapStack.size() >= 2);
95         m_overlapStack[m_overlapStack.size() - 2].unite(bounds);
96         m_layers.add(layer);
97     }
98
99     bool contains(const RenderLayer* layer)
100     {
101         return m_layers.contains(layer);
102     }
103
104     bool overlapsLayers(const IntRect& bounds) const
105     {
106         return m_overlapStack.last().intersects(bounds);
107     }
108
109     bool isEmpty()
110     {
111         return m_layers.isEmpty();
112     }
113
114     void pushCompositingContainer()
115     {
116         m_overlapStack.append(Region());
117     }
118
119     void popCompositingContainer()
120     {
121         m_overlapStack[m_overlapStack.size() - 2].unite(m_overlapStack.last());
122         m_overlapStack.removeLast();
123     }
124
125 private:
126     Vector<Region> m_overlapStack;
127     HashSet<const RenderLayer*> m_layers;
128 };
129
130 struct CompositingState {
131     CompositingState(RenderLayer* compAncestor)
132         : m_compositingAncestor(compAncestor)
133         , m_subtreeIsCompositing(false)
134 #ifndef NDEBUG
135         , m_depth(0)
136 #endif
137     {
138     }
139     
140     RenderLayer* m_compositingAncestor;
141     bool m_subtreeIsCompositing;
142 #ifndef NDEBUG
143     int m_depth;
144 #endif
145 };
146
147 RenderLayerCompositor::RenderLayerCompositor(RenderView* renderView)
148     : m_renderView(renderView)
149     , m_updateCompositingLayersTimer(this, &RenderLayerCompositor::updateCompositingLayersTimerFired)
150     , m_hasAcceleratedCompositing(true)
151     , m_compositingTriggers(static_cast<ChromeClient::CompositingTriggerFlags>(ChromeClient::AllTriggers))
152     , m_compositedLayerCount(0)
153     , m_showDebugBorders(false)
154     , m_showRepaintCounter(false)
155     , m_compositingConsultsOverlap(true)
156     , m_compositingDependsOnGeometry(false)
157     , m_compositingNeedsUpdate(false)
158     , m_compositing(false)
159     , m_compositingLayersNeedRebuild(false)
160     , m_flushingLayers(false)
161     , m_forceCompositingMode(false)
162     , m_rootLayerAttachment(RootLayerUnattached)
163 #if PROFILE_LAYER_REBUILD
164     , m_rootLayerUpdateCount(0)
165 #endif // PROFILE_LAYER_REBUILD
166 {
167 }
168
169 RenderLayerCompositor::~RenderLayerCompositor()
170 {
171     ASSERT(m_rootLayerAttachment == RootLayerUnattached);
172 }
173
174 void RenderLayerCompositor::enableCompositingMode(bool enable /* = true */)
175 {
176     if (enable != m_compositing) {
177         m_compositing = enable;
178         
179         if (m_compositing) {
180             ensureRootLayer();
181             notifyIFramesOfCompositingChange();
182         } else
183             destroyRootLayer();
184     }
185 }
186
187 void RenderLayerCompositor::cacheAcceleratedCompositingFlags()
188 {
189     bool hasAcceleratedCompositing = false;
190     bool showDebugBorders = false;
191     bool showRepaintCounter = false;
192     bool forceCompositingMode = false;
193
194     if (Settings* settings = m_renderView->document()->settings()) {
195         hasAcceleratedCompositing = settings->acceleratedCompositingEnabled();
196
197         // We allow the chrome to override the settings, in case the page is rendered
198         // on a chrome that doesn't allow accelerated compositing.
199         if (hasAcceleratedCompositing) {
200             Frame* frame = m_renderView->frameView()->frame();
201             Page* page = frame ? frame->page() : 0;
202             if (page) {
203                 ChromeClient* chromeClient = page->chrome()->client();
204                 m_compositingTriggers = chromeClient->allowedCompositingTriggers();
205                 hasAcceleratedCompositing = m_compositingTriggers;
206             }
207         }
208
209         showDebugBorders = settings->showDebugBorders();
210         showRepaintCounter = settings->showRepaintCounter();
211         forceCompositingMode = settings->forceCompositingMode() && hasAcceleratedCompositing;
212
213         if (forceCompositingMode && m_renderView->document()->ownerElement())
214             forceCompositingMode = settings->acceleratedCompositingForScrollableFramesEnabled() && requiresCompositingForScrollableFrame();
215     }
216
217
218     if (hasAcceleratedCompositing != m_hasAcceleratedCompositing || showDebugBorders != m_showDebugBorders || showRepaintCounter != m_showRepaintCounter || forceCompositingMode != m_forceCompositingMode)
219         setCompositingLayersNeedRebuild();
220
221     m_hasAcceleratedCompositing = hasAcceleratedCompositing;
222     m_showDebugBorders = showDebugBorders;
223     m_showRepaintCounter = showRepaintCounter;
224     m_forceCompositingMode = forceCompositingMode;
225 }
226
227 bool RenderLayerCompositor::canRender3DTransforms() const
228 {
229     return hasAcceleratedCompositing() && (m_compositingTriggers & ChromeClient::ThreeDTransformTrigger);
230 }
231
232 void RenderLayerCompositor::setCompositingLayersNeedRebuild(bool needRebuild)
233 {
234     if (inCompositingMode())
235         m_compositingLayersNeedRebuild = needRebuild;
236 }
237
238 void RenderLayerCompositor::scheduleLayerFlush()
239 {
240     Frame* frame = m_renderView->frameView()->frame();
241     Page* page = frame ? frame->page() : 0;
242     if (!page)
243         return;
244
245     page->chrome()->client()->scheduleCompositingLayerSync();
246 }
247
248 void RenderLayerCompositor::flushPendingLayerChanges(bool isFlushRoot)
249 {
250     // FrameView::syncCompositingStateIncludingSubframes() flushes each subframe,
251     // but GraphicsLayer::syncCompositingState() will cross frame boundaries
252     // if the GraphicsLayers are connected (the RootLayerAttachedViaEnclosingFrame case).
253     // As long as we're not the root of the flush, we can bail.
254     if (!isFlushRoot && rootLayerAttachment() == RootLayerAttachedViaEnclosingFrame)
255         return;
256     
257     ASSERT(!m_flushingLayers);
258     m_flushingLayers = true;
259
260     if (GraphicsLayer* rootLayer = rootGraphicsLayer()) {
261         FrameView* frameView = m_renderView ? m_renderView->frameView() : 0;
262         if (frameView) {
263             // FIXME: Passing frameRect() is correct only when RenderLayerCompositor uses a ScrollLayer (as in WebKit2)
264             // otherwise, the passed clip rect needs to take scrolling into account
265             rootLayer->syncCompositingState(frameView->frameRect());
266         }
267     }
268     
269     ASSERT(m_flushingLayers);
270     m_flushingLayers = false;
271 }
272
273 void RenderLayerCompositor::didFlushChangesForLayer(RenderLayer*)
274 {
275 }
276
277 RenderLayerCompositor* RenderLayerCompositor::enclosingCompositorFlushingLayers() const
278 {
279     if (!m_renderView->frameView())
280         return 0;
281
282     for (Frame* frame = m_renderView->frameView()->frame(); frame; frame = frame->tree()->parent()) {
283         RenderLayerCompositor* compositor = frame->contentRenderer() ? frame->contentRenderer()->compositor() : 0;
284         if (compositor->isFlushingLayers())
285             return compositor;
286     }
287     
288     return 0;
289 }
290
291 void RenderLayerCompositor::scheduleCompositingLayerUpdate()
292 {
293     if (!m_updateCompositingLayersTimer.isActive())
294         m_updateCompositingLayersTimer.startOneShot(0);
295 }
296
297 void RenderLayerCompositor::updateCompositingLayersTimerFired(Timer<RenderLayerCompositor>*)
298 {
299     updateCompositingLayers();
300 }
301
302 bool RenderLayerCompositor::hasAnyAdditionalCompositedLayers(const RenderLayer* rootLayer) const
303 {
304     return m_compositedLayerCount > (rootLayer->isComposited() ? 1 : 0);
305 }
306
307 void RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType updateType, RenderLayer* updateRoot)
308 {
309     m_updateCompositingLayersTimer.stop();
310     
311     // Compositing layers will be updated in Document::implicitClose() if suppressed here.
312     if (!m_renderView->document()->visualUpdatesAllowed())
313         return;
314
315     if (m_forceCompositingMode && !m_compositing)
316         enableCompositingMode(true);
317
318     if (!m_compositingDependsOnGeometry && !m_compositing && !m_compositingNeedsUpdate)
319         return;
320
321     bool checkForHierarchyUpdate = m_compositingDependsOnGeometry;
322     bool needGeometryUpdate = false;
323
324     switch (updateType) {
325     case CompositingUpdateAfterLayoutOrStyleChange:
326     case CompositingUpdateOnHitTest:
327         checkForHierarchyUpdate = true;
328         break;
329     case CompositingUpdateOnScroll:
330         if (m_compositingConsultsOverlap)
331             checkForHierarchyUpdate = true; // Overlap can change with scrolling, so need to check for hierarchy updates.
332
333         needGeometryUpdate = true;
334         break;
335     }
336
337     if (!checkForHierarchyUpdate && !needGeometryUpdate)
338         return;
339
340     bool needHierarchyUpdate = m_compositingLayersNeedRebuild;
341     if (!updateRoot || m_compositingConsultsOverlap) {
342         // Only clear the flag if we're updating the entire hierarchy.
343         m_compositingLayersNeedRebuild = false;
344         updateRoot = rootRenderLayer();
345     }
346
347 #if PROFILE_LAYER_REBUILD
348     ++m_rootLayerUpdateCount;
349     
350     double startTime = WTF::currentTime();
351 #endif        
352
353     if (checkForHierarchyUpdate) {
354         // Go through the layers in presentation order, so that we can compute which RenderLayers need compositing layers.
355         // FIXME: we could maybe do this and the hierarchy udpate in one pass, but the parenting logic would be more complex.
356         CompositingState compState(updateRoot);
357         bool layersChanged = false;
358         if (m_compositingConsultsOverlap) {
359             OverlapMap overlapTestRequestMap;
360             computeCompositingRequirements(updateRoot, &overlapTestRequestMap, compState, layersChanged);
361         } else
362             computeCompositingRequirements(updateRoot, 0, compState, layersChanged);
363         
364         needHierarchyUpdate |= layersChanged;
365     }
366
367     if (needHierarchyUpdate) {
368         // Update the hierarchy of the compositing layers.
369         Vector<GraphicsLayer*> childList;
370         rebuildCompositingLayerTree(updateRoot, childList);
371
372         // Host the document layer in the RenderView's root layer.
373         if (updateRoot == rootRenderLayer()) {
374             // Even when childList is empty, don't drop out of compositing mode if there are
375             // composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
376             if (childList.isEmpty() && !hasAnyAdditionalCompositedLayers(updateRoot))
377                 destroyRootLayer();
378             else
379                 m_rootContentLayer->setChildren(childList);
380         }
381     } else if (needGeometryUpdate) {
382         // We just need to do a geometry update. This is only used for position:fixed scrolling;
383         // most of the time, geometry is updated via RenderLayer::styleChanged().
384         updateLayerTreeGeometry(updateRoot);
385     }
386     
387 #if PROFILE_LAYER_REBUILD
388     double endTime = WTF::currentTime();
389     if (updateRoot == rootRenderLayer())
390         fprintf(stderr, "Update %d: computeCompositingRequirements for the world took %fms\n",
391                     m_rootLayerUpdateCount, 1000.0 * (endTime - startTime));
392 #endif
393     ASSERT(updateRoot || !m_compositingLayersNeedRebuild);
394
395     if (!hasAcceleratedCompositing())
396         enableCompositingMode(false);
397
398     m_compositingNeedsUpdate = false;
399 }
400
401 bool RenderLayerCompositor::updateBacking(RenderLayer* layer, CompositingChangeRepaint shouldRepaint)
402 {
403     bool layerChanged = false;
404
405     if (needsToBeComposited(layer)) {
406         enableCompositingMode();
407         
408         // Non-identity 3D transforms turn off the testing of overlap.
409         if (hasNonIdentity3DTransform(layer->renderer()))
410             setCompositingConsultsOverlap(false);
411
412         if (!layer->backing()) {
413
414             // If we need to repaint, do so before making backing
415             if (shouldRepaint == CompositingChangeRepaintNow)
416                 repaintOnCompositingChange(layer);
417
418             layer->ensureBacking();
419
420 #if PLATFORM(MAC) && USE(CA)
421             Settings* settings = m_renderView->document()->settings();
422             if (settings && settings->acceleratedDrawingEnabled())
423                 layer->backing()->graphicsLayer()->setAcceleratesDrawing(true);
424             else if (layer->renderer()->isCanvas()) {
425                 HTMLCanvasElement* canvas = static_cast<HTMLCanvasElement*>(layer->renderer()->node());
426                 if (canvas->shouldAccelerate(canvas->size()))
427                     layer->backing()->graphicsLayer()->setAcceleratesDrawing(true);
428             }
429 #endif
430             layerChanged = true;
431         }
432     } else {
433         if (layer->backing()) {
434             // If we're removing backing on a reflection, clear the source GraphicsLayer's pointer to
435             // its replica GraphicsLayer. In practice this should never happen because reflectee and reflection 
436             // are both either composited, or not composited.
437             if (layer->isReflection()) {
438                 RenderLayer* sourceLayer = toRenderBoxModelObject(layer->renderer()->parent())->layer();
439                 if (RenderLayerBacking* backing = sourceLayer->backing()) {
440                     ASSERT(backing->graphicsLayer()->replicaLayer() == layer->backing()->graphicsLayer());
441                     backing->graphicsLayer()->setReplicatedByLayer(0);
442                 }
443             }
444             
445             layer->clearBacking();
446             layerChanged = true;
447
448             // The layer's cached repaints rects are relative to the repaint container, so change when
449             // compositing changes; we need to update them here.
450             layer->computeRepaintRects();
451
452             // If we need to repaint, do so now that we've removed the backing
453             if (shouldRepaint == CompositingChangeRepaintNow)
454                 repaintOnCompositingChange(layer);
455         }
456     }
457     
458 #if ENABLE(VIDEO)
459     if (layerChanged && layer->renderer()->isVideo()) {
460         // If it's a video, give the media player a chance to hook up to the layer.
461         RenderVideo* video = toRenderVideo(layer->renderer());
462         video->acceleratedRenderingStateChanged();
463     }
464 #endif
465
466     if (layerChanged && layer->renderer()->isRenderPart()) {
467         RenderLayerCompositor* innerCompositor = frameContentsCompositor(toRenderPart(layer->renderer()));
468         if (innerCompositor && innerCompositor->inCompositingMode())
469             innerCompositor->updateRootLayerAttachment();
470     }
471
472     return layerChanged;
473 }
474
475 bool RenderLayerCompositor::updateLayerCompositingState(RenderLayer* layer, CompositingChangeRepaint shouldRepaint)
476 {
477     bool layerChanged = updateBacking(layer, shouldRepaint);
478
479     // See if we need content or clipping layers. Methods called here should assume
480     // that the compositing state of descendant layers has not been updated yet.
481     if (layer->backing() && layer->backing()->updateGraphicsLayerConfiguration())
482         layerChanged = true;
483
484     return layerChanged;
485 }
486
487 void RenderLayerCompositor::repaintOnCompositingChange(RenderLayer* layer)
488 {
489     // If the renderer is not attached yet, no need to repaint.
490     if (layer->renderer() != m_renderView && !layer->renderer()->parent())
491         return;
492
493     RenderBoxModelObject* repaintContainer = layer->renderer()->containerForRepaint();
494     if (!repaintContainer)
495         repaintContainer = m_renderView;
496
497     layer->repaintIncludingNonCompositingDescendants(repaintContainer);
498     if (repaintContainer == m_renderView) {
499         // The contents of this layer may be moving between the window
500         // and a GraphicsLayer, so we need to make sure the window system
501         // synchronizes those changes on the screen.
502         m_renderView->frameView()->setNeedsOneShotDrawingSynchronization();
503     }
504 }
505
506 // The bounds of the GraphicsLayer created for a compositing layer is the union of the bounds of all the descendant
507 // RenderLayers that are rendered by the composited RenderLayer.
508 IntRect RenderLayerCompositor::calculateCompositedBounds(const RenderLayer* layer, const RenderLayer* ancestorLayer)
509 {
510     if (!canBeComposited(layer))
511         return IntRect();
512
513     LayoutRect boundingBoxRect = layer->localBoundingBox();
514     if (layer->renderer()->isRoot()) {
515         // If the root layer becomes composited (e.g. because some descendant with negative z-index is composited),
516         // then it has to be big enough to cover the viewport in order to display the background. This is akin
517         // to the code in RenderBox::paintRootBoxFillLayers().
518         if (m_renderView->frameView()) {
519             LayoutUnit rw = m_renderView->frameView()->contentsWidth();
520             LayoutUnit rh = m_renderView->frameView()->contentsHeight();
521             
522             boundingBoxRect.setWidth(max(boundingBoxRect.width(), rw - boundingBoxRect.x()));
523             boundingBoxRect.setHeight(max(boundingBoxRect.height(), rh - boundingBoxRect.y()));
524         }
525     }
526     
527     LayoutRect unionBounds = boundingBoxRect;
528     
529     if (layer->renderer()->hasOverflowClip() || layer->renderer()->hasMask()) {
530         LayoutPoint ancestorRelOffset;
531         layer->convertToLayerCoords(ancestorLayer, ancestorRelOffset);
532         boundingBoxRect.moveBy(ancestorRelOffset);
533         return pixelSnappedIntRect(boundingBoxRect);
534     }
535
536     if (RenderLayer* reflection = layer->reflectionLayer()) {
537         if (!reflection->isComposited()) {
538             LayoutRect childUnionBounds = calculateCompositedBounds(reflection, layer);
539             unionBounds.unite(childUnionBounds);
540         }
541     }
542     
543     ASSERT(layer->isStackingContext() || (!layer->m_posZOrderList || layer->m_posZOrderList->size() == 0));
544
545     if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
546         size_t listSize = negZOrderList->size();
547         for (size_t i = 0; i < listSize; ++i) {
548             RenderLayer* curLayer = negZOrderList->at(i);
549             if (!curLayer->isComposited()) {
550                 LayoutRect childUnionBounds = calculateCompositedBounds(curLayer, layer);
551                 unionBounds.unite(childUnionBounds);
552             }
553         }
554     }
555
556     if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
557         size_t listSize = posZOrderList->size();
558         for (size_t i = 0; i < listSize; ++i) {
559             RenderLayer* curLayer = posZOrderList->at(i);
560             if (!curLayer->isComposited()) {
561                 LayoutRect childUnionBounds = calculateCompositedBounds(curLayer, layer);
562                 unionBounds.unite(childUnionBounds);
563             }
564         }
565     }
566
567     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
568         size_t listSize = normalFlowList->size();
569         for (size_t i = 0; i < listSize; ++i) {
570             RenderLayer* curLayer = normalFlowList->at(i);
571             if (!curLayer->isComposited()) {
572                 LayoutRect curAbsBounds = calculateCompositedBounds(curLayer, layer);
573                 unionBounds.unite(curAbsBounds);
574             }
575         }
576     }
577
578     if (layer->paintsWithTransform(PaintBehaviorNormal)) {
579         TransformationMatrix* affineTrans = layer->transform();
580         boundingBoxRect = affineTrans->mapRect(boundingBoxRect);
581         unionBounds = affineTrans->mapRect(unionBounds);
582     }
583
584     LayoutPoint ancestorRelOffset;
585     layer->convertToLayerCoords(ancestorLayer, ancestorRelOffset);
586     unionBounds.moveBy(ancestorRelOffset);
587
588     return pixelSnappedIntRect(unionBounds);
589 }
590
591 void RenderLayerCompositor::layerWasAdded(RenderLayer* /*parent*/, RenderLayer* /*child*/)
592 {
593     setCompositingLayersNeedRebuild();
594 }
595
596 void RenderLayerCompositor::layerWillBeRemoved(RenderLayer* parent, RenderLayer* child)
597 {
598     if (!child->isComposited() || parent->renderer()->documentBeingDestroyed())
599         return;
600
601     setCompositingParent(child, 0);
602     
603     RenderLayer* compLayer = parent->enclosingCompositingLayer();
604     if (compLayer) {
605         ASSERT(compLayer->backing());
606         LayoutRect compBounds = child->backing()->compositedBounds();
607
608         LayoutPoint offset;
609         child->convertToLayerCoords(compLayer, offset);
610         compBounds.moveBy(offset);
611
612         compLayer->setBackingNeedsRepaintInRect(compBounds);
613
614         // The contents of this layer may be moving from a GraphicsLayer to the window,
615         // so we need to make sure the window system synchronizes those changes on the screen.
616         m_renderView->frameView()->setNeedsOneShotDrawingSynchronization();
617     }
618
619     setCompositingLayersNeedRebuild();
620 }
621
622 RenderLayer* RenderLayerCompositor::enclosingNonStackingClippingLayer(const RenderLayer* layer) const
623 {
624     for (RenderLayer* curr = layer->parent(); curr != 0; curr = curr->parent()) {
625         if (curr->isStackingContext())
626             return 0;
627
628         if (curr->renderer()->hasOverflowClip() || curr->renderer()->hasClip())
629             return curr;
630     }
631     return 0;
632 }
633
634 void RenderLayerCompositor::addToOverlapMap(OverlapMap& overlapMap, RenderLayer* layer, IntRect& layerBounds, bool& boundsComputed)
635 {
636     if (layer->isRootLayer())
637         return;
638
639     if (!boundsComputed) {
640         layerBounds = layer->renderer()->localToAbsoluteQuad(FloatRect(layer->localBoundingBox())).enclosingBoundingBox();
641         // Empty rects never intersect, but we need them to for the purposes of overlap testing.
642         if (layerBounds.isEmpty())
643             layerBounds.setSize(IntSize(1, 1));
644         boundsComputed = true;
645     }
646
647     IntRect clipRect = pixelSnappedIntRect(layer->backgroundClipRect(rootRenderLayer(), 0, true).rect()); // FIXME: Incorrect for CSS regions.
648     clipRect.scale(pageScaleFactor());
649     clipRect.intersect(layerBounds);
650     overlapMap.add(layer, clipRect);
651 }
652
653 void RenderLayerCompositor::addToOverlapMapRecursive(OverlapMap& overlapMap, RenderLayer* layer)
654 {
655     if (!canBeComposited(layer) || overlapMap.contains(layer))
656         return;
657
658     IntRect bounds;
659     bool haveComputedBounds = false;
660     addToOverlapMap(overlapMap, layer, bounds, haveComputedBounds);
661
662     if (layer->isStackingContext()) {
663         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
664             size_t listSize = negZOrderList->size();
665             for (size_t i = 0; i < listSize; ++i) {
666                 RenderLayer* curLayer = negZOrderList->at(i);
667                 addToOverlapMapRecursive(overlapMap, curLayer);
668             }
669         }
670     }
671
672     ASSERT(!layer->m_normalFlowListDirty);
673     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
674         size_t listSize = normalFlowList->size();
675         for (size_t i = 0; i < listSize; ++i) {
676             RenderLayer* curLayer = normalFlowList->at(i);
677             addToOverlapMapRecursive(overlapMap, curLayer);
678         }
679     }
680
681     if (layer->isStackingContext()) {
682         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
683             size_t listSize = posZOrderList->size();
684             for (size_t i = 0; i < listSize; ++i) {
685                 RenderLayer* curLayer = posZOrderList->at(i);
686                 addToOverlapMapRecursive(overlapMap, curLayer);
687             }
688         }
689     }
690 }
691
692 //  Recurse through the layers in z-index and overflow order (which is equivalent to painting order)
693 //  For the z-order children of a compositing layer:
694 //      If a child layers has a compositing layer, then all subsequent layers must
695 //      be compositing in order to render above that layer.
696 //
697 //      If a child in the negative z-order list is compositing, then the layer itself
698 //      must be compositing so that its contents render over that child.
699 //      This implies that its positive z-index children must also be compositing.
700 //
701 void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* layer, OverlapMap* overlapMap, struct CompositingState& compositingState, bool& layersChanged)
702 {
703     layer->updateLayerPosition();
704     layer->updateZOrderLists();
705     layer->updateNormalFlowList();
706     
707     // Clear the flag
708     layer->setHasCompositingDescendant(false);
709     
710     bool mustOverlapCompositedLayers = compositingState.m_subtreeIsCompositing;
711
712     bool haveComputedBounds = false;
713     IntRect absBounds;
714     if (overlapMap && !overlapMap->isEmpty()) {
715         // If we're testing for overlap, we only need to composite if we overlap something that is already composited.
716         absBounds = layer->renderer()->localToAbsoluteQuad(FloatRect(layer->localBoundingBox())).enclosingBoundingBox();
717         // Empty rects never intersect, but we need them to for the purposes of overlap testing.
718         if (absBounds.isEmpty())
719             absBounds.setSize(IntSize(1, 1));
720         haveComputedBounds = true;
721         mustOverlapCompositedLayers = overlapMap->overlapsLayers(absBounds);
722     }
723     
724     layer->setMustOverlapCompositedLayers(mustOverlapCompositedLayers);
725     
726     // The children of this layer don't need to composite, unless there is
727     // a compositing layer among them, so start by inheriting the compositing
728     // ancestor with m_subtreeIsCompositing set to false.
729     CompositingState childState(compositingState.m_compositingAncestor);
730 #ifndef NDEBUG
731     childState.m_depth = compositingState.m_depth + 1;
732 #endif
733
734     bool willBeComposited = needsToBeComposited(layer);
735     if (willBeComposited) {
736         // Tell the parent it has compositing descendants.
737         compositingState.m_subtreeIsCompositing = true;
738         // This layer now acts as the ancestor for kids.
739         childState.m_compositingAncestor = layer;
740
741         if (overlapMap)
742             overlapMap->pushCompositingContainer();
743     }
744
745 #if ENABLE(VIDEO)
746     // Video is special. It's a replaced element with a content layer, but has shadow content
747     // for the controller that must render in front. Without this, the controls fail to show
748     // when the video element is a stacking context (e.g. due to opacity or transform).
749     if (willBeComposited && layer->renderer()->isVideo())
750         childState.m_subtreeIsCompositing = true;
751 #endif
752
753     if (layer->isStackingContext()) {
754         ASSERT(!layer->m_zOrderListsDirty);
755         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
756             size_t listSize = negZOrderList->size();
757             for (size_t i = 0; i < listSize; ++i) {
758                 RenderLayer* curLayer = negZOrderList->at(i);
759                 computeCompositingRequirements(curLayer, overlapMap, childState, layersChanged);
760
761                 // If we have to make a layer for this child, make one now so we can have a contents layer
762                 // (since we need to ensure that the -ve z-order child renders underneath our contents).
763                 if (!willBeComposited && childState.m_subtreeIsCompositing) {
764                     // make layer compositing
765                     layer->setMustOverlapCompositedLayers(true);
766                     childState.m_compositingAncestor = layer;
767                     if (overlapMap)
768                         overlapMap->pushCompositingContainer();
769                     willBeComposited = true;
770                 }
771             }
772         }
773     }
774     
775     ASSERT(!layer->m_normalFlowListDirty);
776     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
777         size_t listSize = normalFlowList->size();
778         for (size_t i = 0; i < listSize; ++i) {
779             RenderLayer* curLayer = normalFlowList->at(i);
780             computeCompositingRequirements(curLayer, overlapMap, childState, layersChanged);
781         }
782     }
783
784     if (layer->isStackingContext()) {
785         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
786             size_t listSize = posZOrderList->size();
787             for (size_t i = 0; i < listSize; ++i) {
788                 RenderLayer* curLayer = posZOrderList->at(i);
789                 computeCompositingRequirements(curLayer, overlapMap, childState, layersChanged);
790             }
791         }
792     }
793     
794     // If we just entered compositing mode, the root will have become composited (as long as accelerated compositing is enabled).
795     if (layer->isRootLayer()) {
796         if (inCompositingMode() && m_hasAcceleratedCompositing)
797             willBeComposited = true;
798     }
799     
800     ASSERT(willBeComposited == needsToBeComposited(layer));
801
802     // All layers (even ones that aren't being composited) need to get added to
803     // the overlap map. Layers that do not composite will draw into their
804     // compositing ancestor's backing, and so are still considered for overlap.
805     if (overlapMap && childState.m_compositingAncestor && !childState.m_compositingAncestor->isRootLayer())
806         addToOverlapMap(*overlapMap, layer, absBounds, haveComputedBounds);
807
808     // If we have a software transform, and we have layers under us, we need to also
809     // be composited. Also, if we have opacity < 1, then we need to be a layer so that
810     // the child layers are opaque, then rendered with opacity on this layer.
811     if (!willBeComposited && canBeComposited(layer) && childState.m_subtreeIsCompositing && requiresCompositingWhenDescendantsAreCompositing(layer->renderer())) {
812         layer->setMustOverlapCompositedLayers(true);
813         childState.m_compositingAncestor = layer;
814         if (overlapMap) {
815             overlapMap->pushCompositingContainer();
816             addToOverlapMapRecursive(*overlapMap, layer);
817         }
818         willBeComposited = true;
819     }
820
821     ASSERT(willBeComposited == needsToBeComposited(layer));
822     if (layer->reflectionLayer())
823         layer->reflectionLayer()->setMustOverlapCompositedLayers(willBeComposited);
824
825     // Subsequent layers in the parent stacking context also need to composite.
826     if (childState.m_subtreeIsCompositing)
827         compositingState.m_subtreeIsCompositing = true;
828
829     // Set the flag to say that this SC has compositing children.
830     layer->setHasCompositingDescendant(childState.m_subtreeIsCompositing);
831
832     // setHasCompositingDescendant() may have changed the answer to needsToBeComposited() when clipping,
833     // so test that again.
834     if (!willBeComposited && canBeComposited(layer) && clipsCompositingDescendants(layer)) {
835         childState.m_compositingAncestor = layer;
836         if (overlapMap) {
837             overlapMap->pushCompositingContainer();
838             addToOverlapMapRecursive(*overlapMap, layer);
839         }
840         willBeComposited = true;
841     }
842
843     if (overlapMap && childState.m_compositingAncestor == layer && !layer->isRootLayer())
844         overlapMap->popCompositingContainer();
845
846     // If we're back at the root, and no other layers need to be composited, and the root layer itself doesn't need
847     // to be composited, then we can drop out of compositing mode altogether. However, don't drop out of compositing mode
848     // if there are composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
849     if (layer->isRootLayer() && !childState.m_subtreeIsCompositing && !requiresCompositingLayer(layer) && !m_forceCompositingMode && !hasAnyAdditionalCompositedLayers(layer)) {
850         enableCompositingMode(false);
851         willBeComposited = false;
852     }
853     
854     // If the layer is going into compositing mode, repaint its old location.
855     ASSERT(willBeComposited == needsToBeComposited(layer));
856     if (!layer->isComposited() && willBeComposited)
857         repaintOnCompositingChange(layer);
858
859     // Update backing now, so that we can use isComposited() reliably during tree traversal in rebuildCompositingLayerTree().
860     if (updateBacking(layer, CompositingChangeRepaintNow))
861         layersChanged = true;
862
863     if (layer->reflectionLayer() && updateLayerCompositingState(layer->reflectionLayer(), CompositingChangeRepaintNow))
864         layersChanged = true;
865 }
866
867 void RenderLayerCompositor::setCompositingParent(RenderLayer* childLayer, RenderLayer* parentLayer)
868 {
869     ASSERT(!parentLayer || childLayer->ancestorCompositingLayer() == parentLayer);
870     ASSERT(childLayer->isComposited());
871
872     // It's possible to be called with a parent that isn't yet composited when we're doing
873     // partial updates as required by painting or hit testing. Just bail in that case;
874     // we'll do a full layer update soon.
875     if (!parentLayer || !parentLayer->isComposited())
876         return;
877
878     if (parentLayer) {
879         GraphicsLayer* hostingLayer = parentLayer->backing()->parentForSublayers();
880         GraphicsLayer* hostedLayer = childLayer->backing()->childForSuperlayers();
881         
882         hostingLayer->addChild(hostedLayer);
883     } else
884         childLayer->backing()->childForSuperlayers()->removeFromParent();
885 }
886
887 void RenderLayerCompositor::removeCompositedChildren(RenderLayer* layer)
888 {
889     ASSERT(layer->isComposited());
890
891     GraphicsLayer* hostingLayer = layer->backing()->parentForSublayers();
892     hostingLayer->removeAllChildren();
893 }
894
895 #if ENABLE(VIDEO)
896 bool RenderLayerCompositor::canAccelerateVideoRendering(RenderVideo* o) const
897 {
898     if (!m_hasAcceleratedCompositing)
899         return false;
900
901     return o->supportsAcceleratedRendering();
902 }
903 #endif
904
905 void RenderLayerCompositor::rebuildCompositingLayerTree(RenderLayer* layer, Vector<GraphicsLayer*>& childLayersOfEnclosingLayer)
906 {
907     // Make the layer compositing if necessary, and set up clipping and content layers.
908     // Note that we can only do work here that is independent of whether the descendant layers
909     // have been processed. computeCompositingRequirements() will already have done the repaint if necessary.
910     
911     RenderLayerBacking* layerBacking = layer->backing();
912     if (layerBacking) {
913         // The compositing state of all our children has been updated already, so now
914         // we can compute and cache the composited bounds for this layer.
915         layerBacking->updateCompositedBounds();
916
917         if (RenderLayer* reflection = layer->reflectionLayer()) {
918             if (reflection->backing())
919                 reflection->backing()->updateCompositedBounds();
920         }
921
922         layerBacking->updateGraphicsLayerConfiguration();
923         layerBacking->updateGraphicsLayerGeometry();
924
925         if (!layer->parent())
926             updateRootLayerPosition();
927     }
928
929     // If this layer has backing, then we are collecting its children, otherwise appending
930     // to the compositing child list of an enclosing layer.
931     Vector<GraphicsLayer*> layerChildren;
932     Vector<GraphicsLayer*>& childList = layerBacking ? layerChildren : childLayersOfEnclosingLayer;
933
934     if (layer->isStackingContext()) {
935         ASSERT(!layer->m_zOrderListsDirty);
936
937         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
938             size_t listSize = negZOrderList->size();
939             for (size_t i = 0; i < listSize; ++i) {
940                 RenderLayer* curLayer = negZOrderList->at(i);
941                 rebuildCompositingLayerTree(curLayer, childList);
942             }
943         }
944
945         // If a negative z-order child is compositing, we get a foreground layer which needs to get parented.
946         if (layerBacking && layerBacking->foregroundLayer())
947             childList.append(layerBacking->foregroundLayer());
948     }
949
950     ASSERT(!layer->m_normalFlowListDirty);
951     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
952         size_t listSize = normalFlowList->size();
953         for (size_t i = 0; i < listSize; ++i) {
954             RenderLayer* curLayer = normalFlowList->at(i);
955             rebuildCompositingLayerTree(curLayer, childList);
956         }
957     }
958     
959     if (layer->isStackingContext()) {
960         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
961             size_t listSize = posZOrderList->size();
962             for (size_t i = 0; i < listSize; ++i) {
963                 RenderLayer* curLayer = posZOrderList->at(i);
964                 rebuildCompositingLayerTree(curLayer, childList);
965             }
966         }
967     }
968     
969     if (layerBacking) {
970         bool parented = false;
971         if (layer->renderer()->isRenderPart())
972             parented = parentFrameContentLayers(toRenderPart(layer->renderer()));
973
974         if (!parented)
975             layerBacking->parentForSublayers()->setChildren(layerChildren);
976
977         // If the layer has a clipping layer the overflow controls layers will be siblings of the clipping layer.
978         // Otherwise, the overflow control layers are normal children.
979         if (!layerBacking->hasClippingLayer()) {
980             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForHorizontalScrollbar()) {
981                 overflowControlLayer->removeFromParent();
982                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
983             }
984
985             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForVerticalScrollbar()) {
986                 overflowControlLayer->removeFromParent();
987                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
988             }
989
990             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForScrollCorner()) {
991                 overflowControlLayer->removeFromParent();
992                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
993             }
994         }
995
996 #if ENABLE(FULLSCREEN_API)
997         // For the sake of clients of the full screen renderer, don't reparent
998         // the full screen layer out from under them if they're in the middle of
999         // animating.
1000         if (layer->renderer()->isRenderFullScreen() && m_renderView->document()->isAnimatingFullScreen())
1001             return;
1002 #endif
1003         childLayersOfEnclosingLayer.append(layerBacking->childForSuperlayers());
1004     }
1005 }
1006
1007 void RenderLayerCompositor::frameViewDidChangeLocation(const IntPoint& contentsOffset)
1008 {
1009     if (m_overflowControlsHostLayer)
1010         m_overflowControlsHostLayer->setPosition(contentsOffset);
1011 }
1012
1013 void RenderLayerCompositor::frameViewDidChangeSize()
1014 {
1015     if (m_clipLayer) {
1016         FrameView* frameView = m_renderView->frameView();
1017         m_clipLayer->setSize(frameView->visibleContentRect(false /* exclude scrollbars */).size());
1018
1019         frameViewDidScroll();
1020         updateOverflowControlsLayers();
1021
1022 #if ENABLE(RUBBER_BANDING)
1023         if (m_layerForOverhangAreas)
1024             m_layerForOverhangAreas->setSize(frameView->frameRect().size());
1025 #endif
1026     }
1027 }
1028
1029 void RenderLayerCompositor::frameViewDidScroll()
1030 {
1031     FrameView* frameView = m_renderView->frameView();
1032     IntPoint scrollPosition = frameView->scrollPosition();
1033
1034     if (RenderLayerBacking* backing = rootRenderLayer()->backing())
1035         backing->graphicsLayer()->visibleRectChanged(frameView->visibleContentRect(false /* exclude scrollbars */));
1036
1037     if (!m_scrollLayer)
1038         return;
1039
1040     // If there's a scrolling coordinator that manages scrolling for this frame view,
1041     // it will also manage updating the scroll layer position.
1042     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator()) {
1043         if (scrollingCoordinator->coordinatesScrollingForFrameView(frameView))
1044             return;
1045     }
1046
1047     m_scrollLayer->setPosition(FloatPoint(-scrollPosition.x(), -scrollPosition.y()));
1048 }
1049
1050 String RenderLayerCompositor::layerTreeAsText(bool showDebugInfo)
1051 {
1052     updateCompositingLayers();
1053
1054     if (!m_rootContentLayer)
1055         return String();
1056
1057     // We skip dumping the scroll and clip layers to keep layerTreeAsText output
1058     // similar between platforms.
1059     return m_rootContentLayer->layerTreeAsText(showDebugInfo ? LayerTreeAsTextDebug : LayerTreeAsTextBehaviorNormal);
1060 }
1061
1062 RenderLayerCompositor* RenderLayerCompositor::frameContentsCompositor(RenderPart* renderer)
1063 {
1064     if (!renderer->node()->isFrameOwnerElement())
1065         return 0;
1066         
1067     HTMLFrameOwnerElement* element = static_cast<HTMLFrameOwnerElement*>(renderer->node());
1068     if (Document* contentDocument = element->contentDocument()) {
1069         if (RenderView* view = contentDocument->renderView())
1070             return view->compositor();
1071     }
1072     return 0;
1073 }
1074
1075 bool RenderLayerCompositor::parentFrameContentLayers(RenderPart* renderer)
1076 {
1077     RenderLayerCompositor* innerCompositor = frameContentsCompositor(renderer);
1078     if (!innerCompositor || !innerCompositor->inCompositingMode() || innerCompositor->rootLayerAttachment() != RootLayerAttachedViaEnclosingFrame)
1079         return false;
1080     
1081     RenderLayer* layer = renderer->layer();
1082     if (!layer->isComposited())
1083         return false;
1084
1085     RenderLayerBacking* backing = layer->backing();
1086     GraphicsLayer* hostingLayer = backing->parentForSublayers();
1087     GraphicsLayer* rootLayer = innerCompositor->rootGraphicsLayer();
1088     if (hostingLayer->children().size() != 1 || hostingLayer->children()[0] != rootLayer) {
1089         hostingLayer->removeAllChildren();
1090         hostingLayer->addChild(rootLayer);
1091     }
1092     return true;
1093 }
1094
1095 // This just updates layer geometry without changing the hierarchy.
1096 void RenderLayerCompositor::updateLayerTreeGeometry(RenderLayer* layer)
1097 {
1098     if (RenderLayerBacking* layerBacking = layer->backing()) {
1099         // The compositing state of all our children has been updated already, so now
1100         // we can compute and cache the composited bounds for this layer.
1101         layerBacking->updateCompositedBounds();
1102
1103         if (RenderLayer* reflection = layer->reflectionLayer()) {
1104             if (reflection->backing())
1105                 reflection->backing()->updateCompositedBounds();
1106         }
1107
1108         layerBacking->updateGraphicsLayerConfiguration();
1109         layerBacking->updateGraphicsLayerGeometry();
1110
1111         if (!layer->parent())
1112             updateRootLayerPosition();
1113     }
1114
1115     if (layer->isStackingContext()) {
1116         ASSERT(!layer->m_zOrderListsDirty);
1117
1118         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
1119             size_t listSize = negZOrderList->size();
1120             for (size_t i = 0; i < listSize; ++i)
1121                 updateLayerTreeGeometry(negZOrderList->at(i));
1122         }
1123     }
1124
1125     ASSERT(!layer->m_normalFlowListDirty);
1126     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
1127         size_t listSize = normalFlowList->size();
1128         for (size_t i = 0; i < listSize; ++i)
1129             updateLayerTreeGeometry(normalFlowList->at(i));
1130     }
1131     
1132     if (layer->isStackingContext()) {
1133         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
1134             size_t listSize = posZOrderList->size();
1135             for (size_t i = 0; i < listSize; ++i)
1136                 updateLayerTreeGeometry(posZOrderList->at(i));
1137         }
1138     }
1139 }
1140
1141 // Recurs down the RenderLayer tree until its finds the compositing descendants of compositingAncestor and updates their geometry.
1142 void RenderLayerCompositor::updateCompositingDescendantGeometry(RenderLayer* compositingAncestor, RenderLayer* layer, RenderLayerBacking::UpdateDepth updateDepth)
1143 {
1144     if (layer != compositingAncestor) {
1145         if (RenderLayerBacking* layerBacking = layer->backing()) {
1146             layerBacking->updateCompositedBounds();
1147
1148             if (RenderLayer* reflection = layer->reflectionLayer()) {
1149                 if (reflection->backing())
1150                     reflection->backing()->updateCompositedBounds();
1151             }
1152
1153             layerBacking->updateGraphicsLayerGeometry();
1154             if (updateDepth == RenderLayerBacking::CompositingChildren)
1155                 return;
1156         }
1157     }
1158
1159     if (layer->reflectionLayer())
1160         updateCompositingDescendantGeometry(compositingAncestor, layer->reflectionLayer(), updateDepth);
1161
1162     if (!layer->hasCompositingDescendant())
1163         return;
1164     
1165     if (layer->isStackingContext()) {
1166         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
1167             size_t listSize = negZOrderList->size();
1168             for (size_t i = 0; i < listSize; ++i)
1169                 updateCompositingDescendantGeometry(compositingAncestor, negZOrderList->at(i), updateDepth);
1170         }
1171     }
1172
1173     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
1174         size_t listSize = normalFlowList->size();
1175         for (size_t i = 0; i < listSize; ++i)
1176             updateCompositingDescendantGeometry(compositingAncestor, normalFlowList->at(i), updateDepth);
1177     }
1178     
1179     if (layer->isStackingContext()) {
1180         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
1181             size_t listSize = posZOrderList->size();
1182             for (size_t i = 0; i < listSize; ++i)
1183                 updateCompositingDescendantGeometry(compositingAncestor, posZOrderList->at(i), updateDepth);
1184         }
1185     }
1186 }
1187
1188
1189 void RenderLayerCompositor::repaintCompositedLayersAbsoluteRect(const IntRect& absRect)
1190 {
1191     recursiveRepaintLayerRect(rootRenderLayer(), absRect);
1192 }
1193
1194 void RenderLayerCompositor::recursiveRepaintLayerRect(RenderLayer* layer, const IntRect& rect)
1195 {
1196     // FIXME: This method does not work correctly with transforms.
1197     if (layer->isComposited())
1198         layer->setBackingNeedsRepaintInRect(rect);
1199
1200     if (layer->hasCompositingDescendant()) {
1201         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
1202             size_t listSize = negZOrderList->size();
1203             for (size_t i = 0; i < listSize; ++i) {
1204                 RenderLayer* curLayer = negZOrderList->at(i);
1205                 IntRect childRect(rect);
1206                 curLayer->convertToPixelSnappedLayerCoords(layer, childRect);
1207                 recursiveRepaintLayerRect(curLayer, childRect);
1208             }
1209         }
1210
1211         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
1212             size_t listSize = posZOrderList->size();
1213             for (size_t i = 0; i < listSize; ++i) {
1214                 RenderLayer* curLayer = posZOrderList->at(i);
1215                 IntRect childRect(rect);
1216                 curLayer->convertToPixelSnappedLayerCoords(layer, childRect);
1217                 recursiveRepaintLayerRect(curLayer, childRect);
1218             }
1219         }
1220     }
1221     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
1222         size_t listSize = normalFlowList->size();
1223         for (size_t i = 0; i < listSize; ++i) {
1224             RenderLayer* curLayer = normalFlowList->at(i);
1225             IntRect childRect(rect);
1226             curLayer->convertToPixelSnappedLayerCoords(layer, childRect);
1227             recursiveRepaintLayerRect(curLayer, childRect);
1228         }
1229     }
1230 }
1231
1232 RenderLayer* RenderLayerCompositor::rootRenderLayer() const
1233 {
1234     return m_renderView->layer();
1235 }
1236
1237 GraphicsLayer* RenderLayerCompositor::rootGraphicsLayer() const
1238 {
1239     if (m_overflowControlsHostLayer)
1240         return m_overflowControlsHostLayer.get();
1241     return m_rootContentLayer.get();
1242 }
1243
1244 GraphicsLayer* RenderLayerCompositor::scrollLayer() const
1245 {
1246     return m_scrollLayer.get();
1247 }
1248
1249 void RenderLayerCompositor::didMoveOnscreen()
1250 {
1251     if (!inCompositingMode() || m_rootLayerAttachment != RootLayerUnattached)
1252         return;
1253
1254     RootLayerAttachment attachment = shouldPropagateCompositingToEnclosingFrame() ? RootLayerAttachedViaEnclosingFrame : RootLayerAttachedViaChromeClient;
1255     attachRootLayer(attachment);
1256 }
1257
1258 void RenderLayerCompositor::willMoveOffscreen()
1259 {
1260     if (!inCompositingMode() || m_rootLayerAttachment == RootLayerUnattached)
1261         return;
1262
1263     detachRootLayer();
1264 }
1265
1266 void RenderLayerCompositor::clearBackingForLayerIncludingDescendants(RenderLayer* layer)
1267 {
1268     if (!layer)
1269         return;
1270
1271     if (layer->isComposited())
1272         layer->clearBacking();
1273     
1274     for (RenderLayer* currLayer = layer->firstChild(); currLayer; currLayer = currLayer->nextSibling())
1275         clearBackingForLayerIncludingDescendants(currLayer);
1276 }
1277
1278 void RenderLayerCompositor::clearBackingForAllLayers()
1279 {
1280     clearBackingForLayerIncludingDescendants(m_renderView->layer());
1281 }
1282
1283 void RenderLayerCompositor::updateRootLayerPosition()
1284 {
1285     if (m_rootContentLayer) {
1286         const IntRect& documentRect = m_renderView->documentRect();
1287         m_rootContentLayer->setSize(documentRect.size());
1288         m_rootContentLayer->setPosition(documentRect.location());
1289     }
1290     if (m_clipLayer) {
1291         FrameView* frameView = m_renderView->frameView();
1292         m_clipLayer->setSize(frameView->visibleContentRect(false /* exclude scrollbars */).size());
1293     }
1294
1295 #if ENABLE(RUBBER_BANDING)
1296     if (m_contentShadowLayer) {
1297         m_contentShadowLayer->setPosition(m_rootContentLayer->position());
1298
1299         FloatSize rootContentLayerSize = m_rootContentLayer->size();
1300         if (m_contentShadowLayer->size() != rootContentLayerSize) {
1301             m_contentShadowLayer->setSize(rootContentLayerSize);
1302             ScrollbarTheme::theme()->setUpContentShadowLayer(m_contentShadowLayer.get());
1303         }
1304     }
1305 #endif
1306 }
1307
1308 void RenderLayerCompositor::didStartAcceleratedAnimation(CSSPropertyID property)
1309 {
1310     // If an accelerated animation or transition runs, we have to turn off overlap checking because
1311     // we don't do layout for every frame, but we have to ensure that the layering is
1312     // correct between the animating object and other objects on the page.
1313     if (property == CSSPropertyWebkitTransform)
1314         setCompositingConsultsOverlap(false);
1315 }
1316
1317 bool RenderLayerCompositor::has3DContent() const
1318 {
1319     return layerHas3DContent(rootRenderLayer());
1320 }
1321
1322 bool RenderLayerCompositor::allowsIndependentlyCompositedFrames(const FrameView* view)
1323 {
1324 #if PLATFORM(MAC)
1325     // frames are only independently composited in Mac pre-WebKit2.
1326     return view->platformWidget();
1327 #endif
1328     return false;
1329 }
1330
1331 bool RenderLayerCompositor::shouldPropagateCompositingToEnclosingFrame() const
1332 {
1333     // Parent document content needs to be able to render on top of a composited frame, so correct behavior
1334     // is to have the parent document become composited too. However, this can cause problems on platforms that
1335     // use native views for frames (like Mac), so disable that behavior on those platforms for now.
1336     HTMLFrameOwnerElement* ownerElement = m_renderView->document()->ownerElement();
1337     RenderObject* renderer = ownerElement ? ownerElement->renderer() : 0;
1338
1339     // If we are the top-level frame, don't propagate.
1340     if (!ownerElement)
1341         return false;
1342
1343     if (!allowsIndependentlyCompositedFrames(m_renderView->frameView()))
1344         return true;
1345
1346     if (!renderer || !renderer->isRenderPart())
1347         return false;
1348
1349     // On Mac, only propagate compositing if the frame is overlapped in the parent
1350     // document, or the parent is already compositing, or the main frame is scaled.
1351     Frame* frame = m_renderView->frameView()->frame();
1352     Page* page = frame ? frame->page() : 0;
1353     if (page && page->pageScaleFactor() != 1)
1354         return true;
1355     
1356     RenderPart* frameRenderer = toRenderPart(renderer);
1357     if (frameRenderer->widget()) {
1358         ASSERT(frameRenderer->widget()->isFrameView());
1359         FrameView* view = static_cast<FrameView*>(frameRenderer->widget());
1360         if (view->isOverlappedIncludingAncestors() || view->hasCompositingAncestor())
1361             return true;
1362     }
1363
1364     return false;
1365 }
1366
1367 bool RenderLayerCompositor::needsToBeComposited(const RenderLayer* layer) const
1368 {
1369     if (!canBeComposited(layer))
1370         return false;
1371
1372     return requiresCompositingLayer(layer) || layer->mustOverlapCompositedLayers() || (inCompositingMode() && layer->isRootLayer());
1373 }
1374
1375 // Note: this specifies whether the RL needs a compositing layer for intrinsic reasons.
1376 // Use needsToBeComposited() to determine if a RL actually needs a compositing layer.
1377 // static
1378 bool RenderLayerCompositor::requiresCompositingLayer(const RenderLayer* layer) const
1379 {
1380     RenderObject* renderer = layer->renderer();
1381     // The compositing state of a reflection should match that of its reflected layer.
1382     if (layer->isReflection()) {
1383         renderer = renderer->parent(); // The RenderReplica's parent is the object being reflected.
1384         layer = toRenderBoxModelObject(renderer)->layer();
1385     }
1386     // The root layer always has a compositing layer, but it may not have backing.
1387     return requiresCompositingForTransform(renderer)
1388              || requiresCompositingForVideo(renderer)
1389              || requiresCompositingForCanvas(renderer)
1390              || requiresCompositingForPlugin(renderer)
1391              || requiresCompositingForFrame(renderer)
1392              || (canRender3DTransforms() && renderer->style()->backfaceVisibility() == BackfaceVisibilityHidden)
1393              || clipsCompositingDescendants(layer)
1394              || requiresCompositingForAnimation(renderer)
1395              || requiresCompositingForFullScreen(renderer)
1396              || requiresCompositingForFilters(renderer)
1397              || requiresCompositingForPosition(renderer, layer);
1398 }
1399
1400 bool RenderLayerCompositor::canBeComposited(const RenderLayer* layer) const
1401 {
1402     return m_hasAcceleratedCompositing && layer->isSelfPaintingLayer();
1403 }
1404
1405 // Return true if the given layer has some ancestor in the RenderLayer hierarchy that clips,
1406 // up to the enclosing compositing ancestor. This is required because compositing layers are parented
1407 // according to the z-order hierarchy, yet clipping goes down the renderer hierarchy.
1408 // Thus, a RenderLayer can be clipped by a RenderLayer that is an ancestor in the renderer hierarchy,
1409 // but a sibling in the z-order hierarchy.
1410 bool RenderLayerCompositor::clippedByAncestor(RenderLayer* layer) const
1411 {
1412     if (!layer->isComposited() || !layer->parent())
1413         return false;
1414
1415     RenderLayer* compositingAncestor = layer->ancestorCompositingLayer();
1416     if (!compositingAncestor)
1417         return false;
1418
1419     // If the compositingAncestor clips, that will be taken care of by clipsCompositingDescendants(),
1420     // so we only care about clipping between its first child that is our ancestor (the computeClipRoot),
1421     // and layer.
1422     RenderLayer* computeClipRoot = 0;
1423     RenderLayer* curr = layer;
1424     while (curr) {
1425         RenderLayer* next = curr->parent();
1426         if (next == compositingAncestor) {
1427             computeClipRoot = curr;
1428             break;
1429         }
1430         curr = next;
1431     }
1432     
1433     if (!computeClipRoot || computeClipRoot == layer)
1434         return false;
1435
1436     return layer->backgroundClipRect(computeClipRoot, 0, true).rect() != PaintInfo::infiniteRect(); // FIXME: Incorrect for CSS regions.
1437 }
1438
1439 // Return true if the given layer is a stacking context and has compositing child
1440 // layers that it needs to clip. In this case we insert a clipping GraphicsLayer
1441 // into the hierarchy between this layer and its children in the z-order hierarchy.
1442 bool RenderLayerCompositor::clipsCompositingDescendants(const RenderLayer* layer) const
1443 {
1444     return layer->hasCompositingDescendant() &&
1445            (layer->renderer()->hasOverflowClip() || layer->renderer()->hasClip());
1446 }
1447
1448 bool RenderLayerCompositor::requiresCompositingForScrollableFrame() const
1449 {
1450     // Need this done first to determine overflow.
1451     ASSERT(!m_renderView->needsLayout());
1452
1453     ScrollView* scrollView = m_renderView->frameView();
1454     return scrollView->verticalScrollbar() || scrollView->horizontalScrollbar();
1455 }
1456
1457 bool RenderLayerCompositor::requiresCompositingForTransform(RenderObject* renderer) const
1458 {
1459     if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
1460         return false;
1461
1462     RenderStyle* style = renderer->style();
1463     // Note that we ask the renderer if it has a transform, because the style may have transforms,
1464     // but the renderer may be an inline that doesn't suppport them.
1465     return renderer->hasTransform() && (style->transform().has3DOperation() || style->transformStyle3D() == TransformStyle3DPreserve3D || style->hasPerspective());
1466 }
1467
1468 bool RenderLayerCompositor::requiresCompositingForVideo(RenderObject* renderer) const
1469 {
1470     if (!(m_compositingTriggers & ChromeClient::VideoTrigger))
1471         return false;
1472 #if ENABLE(VIDEO)
1473     if (renderer->isVideo()) {
1474         RenderVideo* video = toRenderVideo(renderer);
1475         return video->shouldDisplayVideo() && canAccelerateVideoRendering(video);
1476     }
1477 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
1478     else if (renderer->isRenderPart()) {
1479         if (!m_hasAcceleratedCompositing)
1480             return false;
1481
1482         Node* node = renderer->node();
1483         if (!node || (!node->hasTagName(HTMLNames::videoTag) && !node->hasTagName(HTMLNames::audioTag)))
1484             return false;
1485
1486         HTMLMediaElement* mediaElement = static_cast<HTMLMediaElement*>(node);
1487         return mediaElement->player() ? mediaElement->player()->supportsAcceleratedRendering() : false;
1488     }
1489 #endif // ENABLE(PLUGIN_PROXY_FOR_VIDEO)
1490 #else
1491     UNUSED_PARAM(renderer);
1492 #endif
1493     return false;
1494 }
1495
1496 bool RenderLayerCompositor::requiresCompositingForCanvas(RenderObject* renderer) const
1497 {
1498     if (!(m_compositingTriggers & ChromeClient::CanvasTrigger))
1499         return false;
1500
1501     if (renderer->isCanvas()) {
1502         HTMLCanvasElement* canvas = static_cast<HTMLCanvasElement*>(renderer->node());
1503         return canvas->renderingContext() && canvas->renderingContext()->isAccelerated();
1504     }
1505     return false;
1506 }
1507
1508 bool RenderLayerCompositor::requiresCompositingForPlugin(RenderObject* renderer) const
1509 {
1510     if (!(m_compositingTriggers & ChromeClient::PluginTrigger))
1511         return false;
1512
1513     bool composite = (renderer->isEmbeddedObject() && toRenderEmbeddedObject(renderer)->allowsAcceleratedCompositing())
1514                   || (renderer->isApplet() && toRenderApplet(renderer)->allowsAcceleratedCompositing());
1515     if (!composite)
1516         return false;
1517
1518     m_compositingDependsOnGeometry = true;
1519     
1520     RenderWidget* pluginRenderer = toRenderWidget(renderer);
1521     // If we can't reliably know the size of the plugin yet, don't change compositing state.
1522     if (pluginRenderer->needsLayout())
1523         return pluginRenderer->hasLayer() && pluginRenderer->layer()->isComposited();
1524
1525     // Don't go into compositing mode if height or width are zero, or size is 1x1.
1526     IntRect contentBox = pixelSnappedIntRect(pluginRenderer->contentBoxRect());
1527     return contentBox.height() * contentBox.width() > 1;
1528 }
1529
1530 bool RenderLayerCompositor::requiresCompositingForFrame(RenderObject* renderer) const
1531 {
1532     if (!renderer->isRenderPart())
1533         return false;
1534     
1535     RenderPart* frameRenderer = toRenderPart(renderer);
1536
1537     if (!frameRenderer->requiresAcceleratedCompositing())
1538         return false;
1539
1540     m_compositingDependsOnGeometry = true;
1541
1542     RenderLayerCompositor* innerCompositor = frameContentsCompositor(frameRenderer);
1543     if (!innerCompositor || !innerCompositor->shouldPropagateCompositingToEnclosingFrame())
1544         return false;
1545
1546     // If we can't reliably know the size of the iframe yet, don't change compositing state.
1547     if (renderer->needsLayout())
1548         return frameRenderer->hasLayer() && frameRenderer->layer()->isComposited();
1549     
1550     // Don't go into compositing mode if height or width are zero.
1551     IntRect contentBox = pixelSnappedIntRect(frameRenderer->contentBoxRect());
1552     return contentBox.height() * contentBox.width() > 0;
1553 }
1554
1555 bool RenderLayerCompositor::requiresCompositingForAnimation(RenderObject* renderer) const
1556 {
1557     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
1558         return false;
1559
1560     if (AnimationController* animController = renderer->animation()) {
1561         return (animController->isRunningAnimationOnRenderer(renderer, CSSPropertyOpacity) && inCompositingMode())
1562             || animController->isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitTransform);
1563     }
1564     return false;
1565 }
1566
1567 bool RenderLayerCompositor::requiresCompositingWhenDescendantsAreCompositing(RenderObject* renderer) const
1568 {
1569     return renderer->hasTransform() || renderer->isTransparent() || renderer->hasMask() || renderer->hasReflection() || renderer->hasFilter();
1570 }
1571     
1572 bool RenderLayerCompositor::requiresCompositingForFullScreen(RenderObject* renderer) const
1573 {
1574 #if ENABLE(FULLSCREEN_API)
1575     return renderer->isRenderFullScreen() && m_renderView->document()->isAnimatingFullScreen();
1576 #else
1577     UNUSED_PARAM(renderer);
1578     return false;
1579 #endif
1580 }
1581
1582 bool RenderLayerCompositor::requiresCompositingForFilters(RenderObject* renderer) const
1583 {
1584 #if ENABLE(CSS_FILTERS)
1585     if (!(m_compositingTriggers & ChromeClient::FilterTrigger))
1586         return false;
1587
1588     return renderer->hasFilter();
1589 #else
1590     UNUSED_PARAM(renderer);
1591     return false;
1592 #endif
1593 }
1594
1595 bool RenderLayerCompositor::requiresCompositingForPosition(RenderObject* renderer, const RenderLayer* layer) const
1596 {
1597     // position:fixed elements that create their own stacking context (e.g. have an explicit z-index,
1598     // opacity, transform) can get their own composited layer. A stacking context is required otherwise
1599     // z-index and clipping will be broken.
1600     if (!(renderer->isPositioned() && renderer->style()->position() == FixedPosition && layer->isStackingContext()))
1601         return false;
1602
1603     if (Settings* settings = m_renderView->document()->settings())
1604         if (!settings->acceleratedCompositingForFixedPositionEnabled())
1605             return false;
1606
1607     RenderObject* container = renderer->container();
1608     // If the renderer is not hooked up yet then we have to wait until it is.
1609     if (!container) {
1610         m_compositingNeedsUpdate = true;
1611         return false;
1612     }
1613
1614     // Don't promote fixed position elements that are descendants of transformed elements.
1615     // They will stay fixed wrt the transformed element rather than the enclosing frame.
1616     if (container != m_renderView)
1617         return false;
1618
1619     // Fixed position elements that are invisible in the current view don't get their own layer.
1620     FrameView* frameView = m_renderView->frameView();
1621     if (frameView && !layer->absoluteBoundingBox().intersects(LayoutRect(frameView->scrollXForFixedPosition(), frameView->scrollYForFixedPosition(), frameView->layoutWidth(), frameView->layoutHeight())))
1622         return false;
1623
1624     return true;
1625 }
1626
1627 bool RenderLayerCompositor::hasNonIdentity3DTransform(RenderObject* renderer) const
1628 {
1629     if (!renderer->hasTransform())
1630         return false;
1631     
1632     if (renderer->style()->hasPerspective())
1633         return true;
1634
1635     if (TransformationMatrix* transform = toRenderBoxModelObject(renderer)->layer()->transform())
1636         return !transform->isAffine();
1637     
1638     return false;
1639 }
1640
1641 // If an element has negative z-index children, those children render in front of the 
1642 // layer background, so we need an extra 'contents' layer for the foreground of the layer
1643 // object.
1644 bool RenderLayerCompositor::needsContentsCompositingLayer(const RenderLayer* layer) const
1645 {
1646     return (layer->m_negZOrderList && layer->m_negZOrderList->size() > 0);
1647 }
1648
1649 bool RenderLayerCompositor::requiresScrollLayer(RootLayerAttachment attachment) const
1650 {
1651     // This applies when the application UI handles scrolling, in which case RenderLayerCompositor doesn't need to manage it.
1652     if (m_renderView->frameView()->delegatesScrolling())
1653         return false;
1654
1655     // We need to handle our own scrolling if we're:
1656     return !m_renderView->frameView()->platformWidget() // viewless (i.e. non-Mac, or Mac in WebKit2)
1657         || attachment == RootLayerAttachedViaEnclosingFrame; // a composited frame on Mac
1658 }
1659
1660 static void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
1661 {
1662     if (!scrollbar)
1663         return;
1664
1665     context.save();
1666     const IntRect& scrollbarRect = scrollbar->frameRect();
1667     context.translate(-scrollbarRect.x(), -scrollbarRect.y());
1668     IntRect transformedClip = clip;
1669     transformedClip.moveBy(scrollbarRect.location());
1670     scrollbar->paint(&context, transformedClip);
1671     context.restore();
1672 }
1673
1674 void RenderLayerCompositor::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, GraphicsLayerPaintingPhase, const IntRect& clip)
1675 {
1676     if (graphicsLayer == layerForHorizontalScrollbar())
1677         paintScrollbar(m_renderView->frameView()->horizontalScrollbar(), context, clip);
1678     else if (graphicsLayer == layerForVerticalScrollbar())
1679         paintScrollbar(m_renderView->frameView()->verticalScrollbar(), context, clip);
1680     else if (graphicsLayer == layerForScrollCorner()) {
1681         const IntRect& scrollCorner = m_renderView->frameView()->scrollCornerRect();
1682         context.save();
1683         context.translate(-scrollCorner.x(), -scrollCorner.y());
1684         IntRect transformedClip = clip;
1685         transformedClip.moveBy(scrollCorner.location());
1686         m_renderView->frameView()->paintScrollCorner(&context, transformedClip);
1687         context.restore();
1688 #if PLATFORM(CHROMIUM) && ENABLE(RUBBER_BANDING)
1689     } else if (graphicsLayer == layerForOverhangAreas()) {
1690         ScrollView* view = m_renderView->frameView();
1691         view->calculateAndPaintOverhangAreas(&context, clip);
1692 #endif
1693     }
1694 }
1695
1696 void RenderLayerCompositor::documentBackgroundColorDidChange()
1697 {
1698     RenderLayerBacking* backing = rootRenderLayer()->backing();
1699     if (!backing)
1700         return;
1701
1702     GraphicsLayer* graphicsLayer = backing->graphicsLayer();
1703     if (!graphicsLayer->client()->shouldUseTileCache(graphicsLayer))
1704         return;
1705
1706     Color backgroundColor = m_renderView->frameView()->documentBackgroundColor();
1707     if (!backgroundColor.isValid() || backgroundColor.hasAlpha())
1708         backgroundColor = Color::white;
1709
1710     graphicsLayer->setBackgroundColor(backgroundColor);
1711 }
1712
1713 bool RenderLayerCompositor::showDebugBorders(const GraphicsLayer* layer) const
1714 {
1715     if (layer == m_layerForHorizontalScrollbar || layer == m_layerForVerticalScrollbar || layer == m_layerForScrollCorner)
1716         return m_showDebugBorders;
1717
1718     return false;
1719 }
1720
1721 bool RenderLayerCompositor::showRepaintCounter(const GraphicsLayer* layer) const
1722 {
1723     if (layer == m_layerForHorizontalScrollbar || layer == m_layerForVerticalScrollbar || layer == m_layerForScrollCorner)
1724         return m_showDebugBorders;
1725
1726     return false;
1727 }
1728
1729 float RenderLayerCompositor::deviceScaleFactor() const
1730 {
1731     Frame* frame = m_renderView->frameView()->frame();
1732     if (!frame)
1733         return 1;
1734     Page* page = frame->page();
1735     if (!page)
1736         return 1;
1737     return page->deviceScaleFactor();
1738 }
1739
1740 float RenderLayerCompositor::pageScaleFactor() const
1741 {
1742     Frame* frame = m_renderView->frameView()->frame();
1743     if (!frame)
1744         return 1;
1745     Page* page = frame->page();
1746     if (!page)
1747         return 1;
1748     return page->pageScaleFactor();
1749 }
1750
1751 void RenderLayerCompositor::didCommitChangesForLayer(const GraphicsLayer*) const
1752 {
1753     // Nothing to do here yet.
1754 }
1755
1756 bool RenderLayerCompositor::keepLayersPixelAligned() const
1757 {
1758     // When scaling, attempt to align compositing layers to pixel boundaries.
1759     return true;
1760 }
1761
1762 static bool shouldCompositeOverflowControls(FrameView* view)
1763 {
1764     if (view->platformWidget())
1765         return false;
1766
1767     if (Page* page = view->frame()->page()) {
1768         if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1769             if (scrollingCoordinator->coordinatesScrollingForFrameView(view))
1770                 return true;
1771     }
1772
1773 #if !PLATFORM(CHROMIUM)
1774     if (!view->hasOverlayScrollbars())
1775         return false;
1776 #endif
1777     return true;
1778 }
1779
1780 bool RenderLayerCompositor::requiresHorizontalScrollbarLayer() const
1781 {
1782     FrameView* view = m_renderView->frameView();
1783     return shouldCompositeOverflowControls(view) && view->horizontalScrollbar();
1784 }
1785
1786 bool RenderLayerCompositor::requiresVerticalScrollbarLayer() const
1787 {
1788     FrameView* view = m_renderView->frameView();
1789     return shouldCompositeOverflowControls(view) && view->verticalScrollbar();
1790 }
1791
1792 bool RenderLayerCompositor::requiresScrollCornerLayer() const
1793 {
1794     FrameView* view = m_renderView->frameView();
1795     return shouldCompositeOverflowControls(view) && view->isScrollCornerVisible();
1796 }
1797
1798 #if ENABLE(RUBBER_BANDING)
1799 bool RenderLayerCompositor::requiresOverhangAreasLayer() const
1800 {
1801     // We don't want a layer if this is a subframe.
1802     if (m_renderView->document()->ownerElement())
1803         return false;
1804
1805     // We do want a layer if we have a scrolling coordinator.
1806     if (scrollingCoordinator())
1807         return true;
1808
1809     // Chromium always wants a layer.
1810 #if PLATFORM(CHROMIUM)
1811     return true;
1812 #endif
1813
1814     return false;
1815 }
1816
1817 bool RenderLayerCompositor::requiresContentShadowLayer() const
1818 {
1819     // We don't want a layer if this is a subframe.
1820     if (m_renderView->document()->ownerElement())
1821         return false;
1822
1823 #if PLATFORM(MAC)
1824     // On Mac, we want a content shadow layer if we have a scrolling coordinator.
1825     if (scrollingCoordinator())
1826         return true;
1827 #endif
1828
1829     return false;
1830 }
1831 #endif
1832
1833 void RenderLayerCompositor::updateOverflowControlsLayers()
1834 {
1835 #if ENABLE(RUBBER_BANDING)
1836     if (requiresOverhangAreasLayer()) {
1837         if (!m_layerForOverhangAreas) {
1838             m_layerForOverhangAreas = GraphicsLayer::create(this);
1839 #ifndef NDEBUG
1840             m_layerForOverhangAreas->setName("overhang areas");
1841 #endif
1842             m_layerForOverhangAreas->setDrawsContent(false);
1843             m_layerForOverhangAreas->setSize(m_renderView->frameView()->frameRect().size());
1844
1845             ScrollbarTheme::theme()->setUpOverhangAreasLayerContents(m_layerForOverhangAreas.get());
1846
1847             // We want the overhang areas layer to be positioned below the frame contents,
1848             // so insert it below the clip layer.
1849             m_overflowControlsHostLayer->addChildBelow(m_layerForOverhangAreas.get(), m_clipLayer.get());
1850         }
1851     } else if (m_layerForOverhangAreas) {
1852         m_layerForOverhangAreas->removeFromParent();
1853         m_layerForOverhangAreas = nullptr;
1854     }
1855
1856     if (requiresContentShadowLayer()) {
1857         if (!m_contentShadowLayer) {
1858             m_contentShadowLayer = GraphicsLayer::create(this);
1859 #ifndef NDEBUG
1860             m_contentShadowLayer->setName("content shadow");
1861 #endif
1862             m_contentShadowLayer->setSize(m_rootContentLayer->size());
1863             m_contentShadowLayer->setPosition(m_rootContentLayer->position());
1864             ScrollbarTheme::theme()->setUpContentShadowLayer(m_contentShadowLayer.get());
1865
1866             m_scrollLayer->addChildBelow(m_contentShadowLayer.get(), m_rootContentLayer.get());
1867         }
1868     } else if (m_contentShadowLayer) {
1869         m_contentShadowLayer->removeFromParent();
1870         m_contentShadowLayer = nullptr;
1871     }
1872 #endif
1873
1874     if (requiresHorizontalScrollbarLayer()) {
1875         if (!m_layerForHorizontalScrollbar) {
1876             m_layerForHorizontalScrollbar = GraphicsLayer::create(this);
1877     #ifndef NDEBUG
1878             m_layerForHorizontalScrollbar->setName("horizontal scrollbar");
1879     #endif
1880             m_overflowControlsHostLayer->addChild(m_layerForHorizontalScrollbar.get());
1881
1882             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
1883                 scrollingCoordinator->frameViewHorizontalScrollbarLayerDidChange(m_renderView->frameView(), m_layerForHorizontalScrollbar.get());
1884         }
1885     } else if (m_layerForHorizontalScrollbar) {
1886         m_layerForHorizontalScrollbar->removeFromParent();
1887         m_layerForHorizontalScrollbar = nullptr;
1888
1889         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
1890             scrollingCoordinator->frameViewHorizontalScrollbarLayerDidChange(m_renderView->frameView(), 0);
1891     }
1892
1893     if (requiresVerticalScrollbarLayer()) {
1894         if (!m_layerForVerticalScrollbar) {
1895             m_layerForVerticalScrollbar = GraphicsLayer::create(this);
1896     #ifndef NDEBUG
1897             m_layerForVerticalScrollbar->setName("vertical scrollbar");
1898     #endif
1899             m_overflowControlsHostLayer->addChild(m_layerForVerticalScrollbar.get());
1900
1901             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
1902                 scrollingCoordinator->frameViewVerticalScrollbarLayerDidChange(m_renderView->frameView(), m_layerForVerticalScrollbar.get());
1903         }
1904     } else if (m_layerForVerticalScrollbar) {
1905         m_layerForVerticalScrollbar->removeFromParent();
1906         m_layerForVerticalScrollbar = nullptr;
1907
1908         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
1909             scrollingCoordinator->frameViewVerticalScrollbarLayerDidChange(m_renderView->frameView(), 0);
1910     }
1911
1912     if (requiresScrollCornerLayer()) {
1913         if (!m_layerForScrollCorner) {
1914             m_layerForScrollCorner = GraphicsLayer::create(this);
1915     #ifndef NDEBUG
1916             m_layerForScrollCorner->setName("scroll corner");
1917     #endif
1918             m_overflowControlsHostLayer->addChild(m_layerForScrollCorner.get());
1919         }
1920     } else if (m_layerForScrollCorner) {
1921         m_layerForScrollCorner->removeFromParent();
1922         m_layerForScrollCorner = nullptr;
1923     }
1924
1925     m_renderView->frameView()->positionScrollbarLayers();
1926 }
1927
1928 void RenderLayerCompositor::ensureRootLayer()
1929 {
1930     RootLayerAttachment expectedAttachment = shouldPropagateCompositingToEnclosingFrame() ? RootLayerAttachedViaEnclosingFrame : RootLayerAttachedViaChromeClient;
1931     if (expectedAttachment == m_rootLayerAttachment)
1932          return;
1933
1934     if (!m_rootContentLayer) {
1935         m_rootContentLayer = GraphicsLayer::create(this);
1936 #ifndef NDEBUG
1937         m_rootContentLayer->setName("content root");
1938 #endif
1939         IntRect overflowRect = m_renderView->pixelSnappedLayoutOverflowRect();
1940         m_rootContentLayer->setSize(FloatSize(overflowRect.maxX(), overflowRect.maxY()));
1941         m_rootContentLayer->setPosition(FloatPoint());
1942
1943         // Need to clip to prevent transformed content showing outside this frame
1944         m_rootContentLayer->setMasksToBounds(true);
1945     }
1946
1947     if (requiresScrollLayer(expectedAttachment)) {
1948         if (!m_overflowControlsHostLayer) {
1949             ASSERT(!m_scrollLayer);
1950             ASSERT(!m_clipLayer);
1951
1952             // Create a layer to host the clipping layer and the overflow controls layers.
1953             m_overflowControlsHostLayer = GraphicsLayer::create(this);
1954 #ifndef NDEBUG
1955             m_overflowControlsHostLayer->setName("overflow controls host");
1956 #endif
1957
1958             // Create a clipping layer if this is an iframe
1959             m_clipLayer = GraphicsLayer::create(this);
1960 #ifndef NDEBUG
1961             m_clipLayer->setName("frame clipping");
1962 #endif
1963             m_clipLayer->setMasksToBounds(true);
1964             
1965             m_scrollLayer = GraphicsLayer::create(this);
1966 #ifndef NDEBUG
1967             m_scrollLayer->setName("frame scrolling");
1968 #endif
1969
1970             // Hook them up
1971             m_overflowControlsHostLayer->addChild(m_clipLayer.get());
1972             m_clipLayer->addChild(m_scrollLayer.get());
1973             m_scrollLayer->addChild(m_rootContentLayer.get());
1974
1975             frameViewDidChangeSize();
1976             frameViewDidScroll();
1977         }
1978     } else {
1979         if (m_overflowControlsHostLayer) {
1980             m_overflowControlsHostLayer = nullptr;
1981             m_clipLayer = nullptr;
1982             m_scrollLayer = nullptr;
1983         }
1984     }
1985
1986     // Check to see if we have to change the attachment
1987     if (m_rootLayerAttachment != RootLayerUnattached)
1988         detachRootLayer();
1989
1990     attachRootLayer(expectedAttachment);
1991 }
1992
1993 void RenderLayerCompositor::destroyRootLayer()
1994 {
1995     if (!m_rootContentLayer)
1996         return;
1997
1998     detachRootLayer();
1999
2000 #if ENABLE(RUBBER_BANDING)
2001     if (m_layerForOverhangAreas) {
2002         m_layerForOverhangAreas->removeFromParent();
2003         m_layerForOverhangAreas = nullptr;
2004     }
2005 #endif
2006
2007     if (m_layerForHorizontalScrollbar) {
2008         m_layerForHorizontalScrollbar->removeFromParent();
2009         m_layerForHorizontalScrollbar = nullptr;
2010         if (Scrollbar* horizontalScrollbar = m_renderView->frameView()->verticalScrollbar())
2011             m_renderView->frameView()->invalidateScrollbar(horizontalScrollbar, IntRect(IntPoint(0, 0), horizontalScrollbar->frameRect().size()));
2012     }
2013
2014     if (m_layerForVerticalScrollbar) {
2015         m_layerForVerticalScrollbar->removeFromParent();
2016         m_layerForVerticalScrollbar = nullptr;
2017         if (Scrollbar* verticalScrollbar = m_renderView->frameView()->verticalScrollbar())
2018             m_renderView->frameView()->invalidateScrollbar(verticalScrollbar, IntRect(IntPoint(0, 0), verticalScrollbar->frameRect().size()));
2019     }
2020
2021     if (m_layerForScrollCorner) {
2022         m_layerForScrollCorner = nullptr;
2023         m_renderView->frameView()->invalidateScrollCorner(m_renderView->frameView()->scrollCornerRect());
2024     }
2025
2026     if (m_overflowControlsHostLayer) {
2027         m_overflowControlsHostLayer = nullptr;
2028         m_clipLayer = nullptr;
2029         m_scrollLayer = nullptr;
2030     }
2031     ASSERT(!m_scrollLayer);
2032     m_rootContentLayer = nullptr;
2033 }
2034
2035 void RenderLayerCompositor::attachRootLayer(RootLayerAttachment attachment)
2036 {
2037     if (!m_rootContentLayer)
2038         return;
2039
2040     switch (attachment) {
2041         case RootLayerUnattached:
2042             ASSERT_NOT_REACHED();
2043             break;
2044         case RootLayerAttachedViaChromeClient: {
2045             Frame* frame = m_renderView->frameView()->frame();
2046             Page* page = frame ? frame->page() : 0;
2047             if (!page)
2048                 return;
2049
2050             page->chrome()->client()->attachRootGraphicsLayer(frame, rootGraphicsLayer());
2051             break;
2052         }
2053         case RootLayerAttachedViaEnclosingFrame: {
2054             // The layer will get hooked up via RenderLayerBacking::updateGraphicsLayerConfiguration()
2055             // for the frame's renderer in the parent document.
2056             m_renderView->document()->ownerElement()->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
2057             break;
2058         }
2059     }
2060
2061     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2062         scrollingCoordinator->frameViewRootLayerDidChange(m_renderView->frameView());
2063
2064     m_rootLayerAttachment = attachment;
2065     rootLayerAttachmentChanged();
2066 }
2067
2068 void RenderLayerCompositor::detachRootLayer()
2069 {
2070     if (!m_rootContentLayer || m_rootLayerAttachment == RootLayerUnattached)
2071         return;
2072
2073     switch (m_rootLayerAttachment) {
2074     case RootLayerAttachedViaEnclosingFrame: {
2075         // The layer will get unhooked up via RenderLayerBacking::updateGraphicsLayerConfiguration()
2076         // for the frame's renderer in the parent document.
2077         if (m_overflowControlsHostLayer)
2078             m_overflowControlsHostLayer->removeFromParent();
2079         else
2080             m_rootContentLayer->removeFromParent();
2081
2082         if (HTMLFrameOwnerElement* ownerElement = m_renderView->document()->ownerElement())
2083             ownerElement->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
2084         break;
2085     }
2086     case RootLayerAttachedViaChromeClient: {
2087         Frame* frame = m_renderView->frameView()->frame();
2088         Page* page = frame ? frame->page() : 0;
2089         if (!page)
2090             return;
2091
2092         page->chrome()->client()->attachRootGraphicsLayer(frame, 0);
2093     }
2094     break;
2095     case RootLayerUnattached:
2096         break;
2097     }
2098
2099     m_rootLayerAttachment = RootLayerUnattached;
2100     rootLayerAttachmentChanged();
2101 }
2102
2103 void RenderLayerCompositor::updateRootLayerAttachment()
2104 {
2105     ensureRootLayer();
2106 }
2107
2108 void RenderLayerCompositor::rootLayerAttachmentChanged()
2109 {
2110     // The attachment can affect whether the RenderView layer's paintingGoesToWindow() behavior,
2111     // so call updateGraphicsLayerGeometry() to udpate that.
2112     RenderLayer* layer = m_renderView->layer();
2113     if (RenderLayerBacking* backing = layer ? layer->backing() : 0)
2114         backing->updateDrawsContent();
2115 }
2116
2117 // IFrames are special, because we hook compositing layers together across iframe boundaries
2118 // when both parent and iframe content are composited. So when this frame becomes composited, we have
2119 // to use a synthetic style change to get the iframes into RenderLayers in order to allow them to composite.
2120 void RenderLayerCompositor::notifyIFramesOfCompositingChange()
2121 {
2122     Frame* frame = m_renderView->frameView() ? m_renderView->frameView()->frame() : 0;
2123     if (!frame)
2124         return;
2125
2126     for (Frame* child = frame->tree()->firstChild(); child; child = child->tree()->traverseNext(frame)) {
2127         if (child->document() && child->document()->ownerElement())
2128             child->document()->ownerElement()->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
2129     }
2130     
2131     // Compositing also affects the answer to RenderIFrame::requiresAcceleratedCompositing(), so 
2132     // we need to schedule a style recalc in our parent document.
2133     if (HTMLFrameOwnerElement* ownerElement = m_renderView->document()->ownerElement())
2134         ownerElement->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
2135 }
2136
2137 bool RenderLayerCompositor::layerHas3DContent(const RenderLayer* layer) const
2138 {
2139     const RenderStyle* style = layer->renderer()->style();
2140
2141     if (style && 
2142         (style->transformStyle3D() == TransformStyle3DPreserve3D ||
2143          style->hasPerspective() ||
2144          style->transform().has3DOperation()))
2145         return true;
2146
2147     if (layer->isStackingContext()) {
2148         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
2149             size_t listSize = negZOrderList->size();
2150             for (size_t i = 0; i < listSize; ++i) {
2151                 RenderLayer* curLayer = negZOrderList->at(i);
2152                 if (layerHas3DContent(curLayer))
2153                     return true;
2154             }
2155         }
2156
2157         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
2158             size_t listSize = posZOrderList->size();
2159             for (size_t i = 0; i < listSize; ++i) {
2160                 RenderLayer* curLayer = posZOrderList->at(i);
2161                 if (layerHas3DContent(curLayer))
2162                     return true;
2163             }
2164         }
2165     }
2166
2167     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
2168         size_t listSize = normalFlowList->size();
2169         for (size_t i = 0; i < listSize; ++i) {
2170             RenderLayer* curLayer = normalFlowList->at(i);
2171             if (layerHas3DContent(curLayer))
2172                 return true;
2173         }
2174     }
2175     return false;
2176 }
2177
2178 void RenderLayerCompositor::deviceOrPageScaleFactorChanged()
2179 {
2180     // Start at the RenderView's layer, since that's where the scale is applied.
2181     RenderLayer* viewLayer = m_renderView->layer();
2182     if (!viewLayer->isComposited())
2183         return;
2184
2185     if (GraphicsLayer* rootLayer = viewLayer->backing()->graphicsLayer())
2186         rootLayer->noteDeviceOrPageScaleFactorChangedIncludingDescendants();
2187 }
2188
2189 ScrollingCoordinator* RenderLayerCompositor::scrollingCoordinator() const
2190 {
2191     if (Frame* frame = m_renderView->frameView()->frame()) {
2192         if (Page* page = frame->page())
2193             return page->scrollingCoordinator();
2194     }
2195
2196     return 0;
2197 }
2198
2199 } // namespace WebCore
2200
2201 #endif // USE(ACCELERATED_COMPOSITING)