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