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