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