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