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