1e44442e2dab2157345b25c1236744b4abfa20f3
[WebKit-https.git] / Source / WebCore / rendering / RenderLayerCompositor.cpp
1 /*
2  * Copyright (C) 2009, 2010 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27
28 #if USE(ACCELERATED_COMPOSITING)
29 #include "RenderLayerCompositor.h"
30
31 #include "AnimationController.h"
32 #include "CanvasRenderingContext.h"
33 #include "CSSPropertyNames.h"
34 #include "Chrome.h"
35 #include "ChromeClient.h"
36 #include "Frame.h"
37 #include "FrameView.h"
38 #include "GraphicsLayer.h"
39 #include "HTMLCanvasElement.h"
40 #include "HTMLIFrameElement.h"
41 #include "HTMLNames.h"
42 #include "HitTestResult.h"
43 #include "InspectorInstrumentation.h"
44 #include "Logging.h"
45 #include "NodeList.h"
46 #include "Page.h"
47 #include "RenderApplet.h"
48 #include "RenderEmbeddedObject.h"
49 #include "RenderFullScreen.h"
50 #include "RenderGeometryMap.h"
51 #include "RenderIFrame.h"
52 #include "RenderLayerBacking.h"
53 #include "RenderReplica.h"
54 #include "RenderVideo.h"
55 #include "RenderView.h"
56 #include "ScrollbarTheme.h"
57 #include "ScrollingConstraints.h"
58 #include "ScrollingCoordinator.h"
59 #include "Settings.h"
60 #include "TiledBacking.h"
61 #include "TransformState.h"
62 #include "WebCoreMemoryInstrumentation.h"
63
64 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
65 #include "HTMLMediaElement.h"
66 #endif
67
68 #if !LOG_DISABLED
69 #include <wtf/CurrentTime.h>
70 #endif
71
72 #ifndef NDEBUG
73 #include "RenderTreeAsText.h"
74 #endif
75
76 #if ENABLE(3D_RENDERING)
77 // This symbol is used to determine from a script whether 3D rendering is enabled (via 'nm').
78 bool WebCoreHas3DRendering = true;
79 #endif
80
81 namespace WebCore {
82
83 using namespace HTMLNames;
84
85 class RenderLayerCompositor::OverlapMap {
86     WTF_MAKE_NONCOPYABLE(OverlapMap);
87 public:
88     OverlapMap()
89         : m_geometryMap(UseTransforms)
90     {
91         // Begin assuming the root layer will be composited so that there is
92         // something on the stack. The root layer should also never get an
93         // popCompositingContainer call.
94         pushCompositingContainer();
95     }
96
97     void add(const RenderLayer* layer, const IntRect& bounds)
98     {
99         // Layers do not contribute to overlap immediately--instead, they will
100         // contribute to overlap as soon as their composited ancestor has been
101         // recursively processed and popped off the stack.
102         ASSERT(m_overlapStack.size() >= 2);
103         m_overlapStack[m_overlapStack.size() - 2].append(bounds);
104         m_layers.add(layer);
105     }
106
107     bool contains(const RenderLayer* layer)
108     {
109         return m_layers.contains(layer);
110     }
111
112     bool overlapsLayers(const IntRect& bounds) const
113     {
114         const RectList& layerRects = m_overlapStack.last();
115         for (unsigned i = 0; i < layerRects.size(); i++) {
116             if (layerRects[i].intersects(bounds))
117                 return true;
118         }
119         return false;
120     }
121
122     bool isEmpty()
123     {
124         return m_layers.isEmpty();
125     }
126
127     void pushCompositingContainer()
128     {
129         m_overlapStack.append(RectList());
130     }
131
132     void popCompositingContainer()
133     {
134         m_overlapStack[m_overlapStack.size() - 2].append(m_overlapStack.last());
135         m_overlapStack.removeLast();
136     }
137
138     RenderGeometryMap& geometryMap() { return m_geometryMap; }
139
140 private:
141     typedef Vector<IntRect> RectList;
142     Vector<RectList> m_overlapStack;
143     HashSet<const RenderLayer*> m_layers;
144     RenderGeometryMap m_geometryMap;
145 };
146
147 struct CompositingState {
148     CompositingState(RenderLayer* compAncestor, bool testOverlap)
149         : m_compositingAncestor(compAncestor)
150         , m_subtreeIsCompositing(false)
151         , m_testingOverlap(testOverlap)
152 #ifndef NDEBUG
153         , m_depth(0)
154 #endif
155     {
156     }
157     
158     CompositingState(const CompositingState& other)
159         : m_compositingAncestor(other.m_compositingAncestor)
160         , m_subtreeIsCompositing(other.m_subtreeIsCompositing)
161         , m_testingOverlap(other.m_testingOverlap)
162 #ifndef NDEBUG
163         , m_depth(other.m_depth + 1)
164 #endif
165     {
166     }
167     
168     RenderLayer* m_compositingAncestor;
169     bool m_subtreeIsCompositing;
170     bool m_testingOverlap;
171 #ifndef NDEBUG
172     int m_depth;
173 #endif
174 };
175
176
177 static inline bool compositingLogEnabled()
178 {
179 #if !LOG_DISABLED
180     return LogCompositing.state == WTFLogChannelOn;
181 #else
182     return false;
183 #endif
184 }
185
186 RenderLayerCompositor::RenderLayerCompositor(RenderView* renderView)
187     : m_renderView(renderView)
188     , m_updateCompositingLayersTimer(this, &RenderLayerCompositor::updateCompositingLayersTimerFired)
189     , m_hasAcceleratedCompositing(true)
190     , m_compositingTriggers(static_cast<ChromeClient::CompositingTriggerFlags>(ChromeClient::AllTriggers))
191     , m_compositedLayerCount(0)
192     , m_showDebugBorders(false)
193     , m_showRepaintCounter(false)
194     , m_acceleratedDrawingEnabled(false)
195     , m_compositingConsultsOverlap(true)
196     , m_reevaluateCompositingAfterLayout(false)
197     , m_compositing(false)
198     , m_compositingLayersNeedRebuild(false)
199     , m_flushingLayers(false)
200     , m_shouldFlushOnReattach(false)
201     , m_forceCompositingMode(false)
202     , m_isTrackingRepaints(false)
203     , m_rootLayerAttachment(RootLayerUnattached)
204 #if !LOG_DISABLED
205     , m_rootLayerUpdateCount(0)
206     , m_obligateCompositedLayerCount(0)
207     , m_secondaryCompositedLayerCount(0)
208     , m_obligatoryBackingStoreBytes(0)
209     , m_secondaryBackingStoreBytes(0)
210 #endif
211 {
212 }
213
214 RenderLayerCompositor::~RenderLayerCompositor()
215 {
216     ASSERT(m_rootLayerAttachment == RootLayerUnattached);
217 }
218
219 void RenderLayerCompositor::enableCompositingMode(bool enable /* = true */)
220 {
221     if (enable != m_compositing) {
222         m_compositing = enable;
223         
224         if (m_compositing) {
225             ensureRootLayer();
226             notifyIFramesOfCompositingChange();
227         } else
228             destroyRootLayer();
229     }
230 }
231
232 void RenderLayerCompositor::cacheAcceleratedCompositingFlags()
233 {
234     bool hasAcceleratedCompositing = false;
235     bool showDebugBorders = false;
236     bool showRepaintCounter = false;
237     bool forceCompositingMode = false;
238     bool acceleratedDrawingEnabled = false;
239
240     if (Settings* settings = m_renderView->document()->settings()) {
241         hasAcceleratedCompositing = settings->acceleratedCompositingEnabled();
242
243         // We allow the chrome to override the settings, in case the page is rendered
244         // on a chrome that doesn't allow accelerated compositing.
245         if (hasAcceleratedCompositing) {
246             if (Page* page = this->page()) {
247                 ChromeClient* chromeClient = page->chrome()->client();
248                 m_compositingTriggers = chromeClient->allowedCompositingTriggers();
249                 hasAcceleratedCompositing = m_compositingTriggers;
250             }
251         }
252
253         showDebugBorders = settings->showDebugBorders();
254         showRepaintCounter = settings->showRepaintCounter();
255         forceCompositingMode = settings->forceCompositingMode() && hasAcceleratedCompositing;
256
257         if (forceCompositingMode && m_renderView->document()->ownerElement())
258             forceCompositingMode = settings->acceleratedCompositingForScrollableFramesEnabled() && requiresCompositingForScrollableFrame();
259
260         acceleratedDrawingEnabled = settings->acceleratedDrawingEnabled();
261     }
262
263     if (hasAcceleratedCompositing != m_hasAcceleratedCompositing || showDebugBorders != m_showDebugBorders || showRepaintCounter != m_showRepaintCounter || forceCompositingMode != m_forceCompositingMode)
264         setCompositingLayersNeedRebuild();
265
266     bool debugBordersChanged = m_showDebugBorders != showDebugBorders;
267     m_hasAcceleratedCompositing = hasAcceleratedCompositing;
268     m_showDebugBorders = showDebugBorders;
269     m_showRepaintCounter = showRepaintCounter;
270     m_forceCompositingMode = forceCompositingMode;
271     m_acceleratedDrawingEnabled = acceleratedDrawingEnabled;
272     
273     if (debugBordersChanged) {
274         if (m_layerForHorizontalScrollbar)
275             m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
276
277         if (m_layerForVerticalScrollbar)
278             m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
279
280         if (m_layerForScrollCorner)
281             m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
282     }
283 }
284
285 bool RenderLayerCompositor::canRender3DTransforms() const
286 {
287     return hasAcceleratedCompositing() && (m_compositingTriggers & ChromeClient::ThreeDTransformTrigger);
288 }
289
290 void RenderLayerCompositor::setCompositingLayersNeedRebuild(bool needRebuild)
291 {
292     if (inCompositingMode())
293         m_compositingLayersNeedRebuild = needRebuild;
294 }
295
296 void RenderLayerCompositor::scheduleLayerFlush()
297 {
298     if (Page* page = this->page())
299         page->chrome()->client()->scheduleCompositingLayerFlush();
300 }
301
302 void RenderLayerCompositor::flushPendingLayerChanges(bool isFlushRoot)
303 {
304     // FrameView::flushCompositingStateIncludingSubframes() flushes each subframe,
305     // but GraphicsLayer::flushCompositingState() will cross frame boundaries
306     // if the GraphicsLayers are connected (the RootLayerAttachedViaEnclosingFrame case).
307     // As long as we're not the root of the flush, we can bail.
308     if (!isFlushRoot && rootLayerAttachment() == RootLayerAttachedViaEnclosingFrame)
309         return;
310     
311     if (rootLayerAttachment() == RootLayerUnattached) {
312         m_shouldFlushOnReattach = true;
313         return;
314     }
315
316     AnimationUpdateBlock animationUpdateBlock(m_renderView->frameView()->frame()->animation());
317
318     ASSERT(!m_flushingLayers);
319     m_flushingLayers = true;
320
321     if (GraphicsLayer* rootLayer = rootGraphicsLayer()) {
322         FrameView* frameView = m_renderView ? m_renderView->frameView() : 0;
323         if (frameView) {
324             // Having a m_clipLayer indicates that we're doing scrolling via GraphicsLayers.
325             IntRect visibleRect = m_clipLayer ? IntRect(IntPoint(), frameView->contentsSize()) : frameView->visibleContentRect();
326             rootLayer->flushCompositingState(visibleRect);
327         }
328     }
329     
330     ASSERT(m_flushingLayers);
331     m_flushingLayers = false;
332
333     if (!m_viewportConstrainedLayersNeedingUpdate.isEmpty()) {
334         HashSet<RenderLayer*>::const_iterator end = m_viewportConstrainedLayersNeedingUpdate.end();
335         for (HashSet<RenderLayer*>::const_iterator it = m_viewportConstrainedLayersNeedingUpdate.begin(); it != end; ++it)
336             registerOrUpdateViewportConstrainedLayer(*it);
337         
338         m_viewportConstrainedLayersNeedingUpdate.clear();
339     }
340 }
341
342 void RenderLayerCompositor::didFlushChangesForLayer(RenderLayer* layer)
343 {
344     if (m_viewportConstrainedLayers.contains(layer))
345         m_viewportConstrainedLayersNeedingUpdate.add(layer);
346 }
347
348 void RenderLayerCompositor::notifyFlushBeforeDisplayRefresh(const GraphicsLayer*)
349 {
350     if (!m_layerUpdater) {
351         PlatformDisplayID displayID = 0;
352         if (Page* page = this->page())
353             displayID = page->displayID();
354
355         m_layerUpdater = adoptPtr(new GraphicsLayerUpdater(this, displayID));
356     }
357     
358     m_layerUpdater->scheduleUpdate();
359 }
360
361 void RenderLayerCompositor::flushLayers(GraphicsLayerUpdater*)
362 {
363     flushPendingLayerChanges(true); // FIXME: deal with iframes
364 }
365
366 RenderLayerCompositor* RenderLayerCompositor::enclosingCompositorFlushingLayers() const
367 {
368     if (!m_renderView->frameView())
369         return 0;
370
371     for (Frame* frame = m_renderView->frameView()->frame(); frame; frame = frame->tree()->parent()) {
372         RenderLayerCompositor* compositor = frame->contentRenderer() ? frame->contentRenderer()->compositor() : 0;
373         if (compositor->isFlushingLayers())
374             return compositor;
375     }
376     
377     return 0;
378 }
379
380 void RenderLayerCompositor::scheduleCompositingLayerUpdate()
381 {
382     if (!m_updateCompositingLayersTimer.isActive())
383         m_updateCompositingLayersTimer.startOneShot(0);
384 }
385
386 void RenderLayerCompositor::updateCompositingLayersTimerFired(Timer<RenderLayerCompositor>*)
387 {
388     updateCompositingLayers(CompositingUpdateAfterLayout);
389 }
390
391 bool RenderLayerCompositor::hasAnyAdditionalCompositedLayers(const RenderLayer* rootLayer) const
392 {
393     return m_compositedLayerCount > (rootLayer->isComposited() ? 1 : 0);
394 }
395
396 void RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType updateType, RenderLayer* updateRoot)
397 {
398     m_updateCompositingLayersTimer.stop();
399     
400     // Compositing layers will be updated in Document::implicitClose() if suppressed here.
401     if (!m_renderView->document()->visualUpdatesAllowed())
402         return;
403
404     if (m_forceCompositingMode && !m_compositing)
405         enableCompositingMode(true);
406
407     if (!m_reevaluateCompositingAfterLayout && !m_compositing)
408         return;
409
410     AnimationUpdateBlock animationUpdateBlock(m_renderView->frameView()->frame()->animation());
411
412     bool checkForHierarchyUpdate = m_reevaluateCompositingAfterLayout;
413     bool needGeometryUpdate = false;
414
415     switch (updateType) {
416     case CompositingUpdateAfterStyleChange:
417     case CompositingUpdateAfterLayout:
418     case CompositingUpdateOnHitTest:
419         checkForHierarchyUpdate = true;
420         break;
421     case CompositingUpdateOnScroll:
422         if (m_compositingConsultsOverlap)
423             checkForHierarchyUpdate = true; // Overlap can change with scrolling, so need to check for hierarchy updates.
424
425         needGeometryUpdate = true;
426         break;
427     }
428
429     if (!checkForHierarchyUpdate && !needGeometryUpdate)
430         return;
431
432     bool needHierarchyUpdate = m_compositingLayersNeedRebuild;
433     bool isFullUpdate = !updateRoot;
434     if (!updateRoot || m_compositingConsultsOverlap) {
435         // Only clear the flag if we're updating the entire hierarchy.
436         m_compositingLayersNeedRebuild = false;
437         updateRoot = rootRenderLayer();
438     }
439
440     if (isFullUpdate && updateType == CompositingUpdateAfterLayout)
441         m_reevaluateCompositingAfterLayout = false;
442
443 #if !LOG_DISABLED
444     double startTime = 0;
445     if (compositingLogEnabled()) {
446         ++m_rootLayerUpdateCount;
447         startTime = currentTime();
448     }
449 #endif
450
451     if (checkForHierarchyUpdate) {
452         // Go through the layers in presentation order, so that we can compute which RenderLayers need compositing layers.
453         // FIXME: we could maybe do this and the hierarchy udpate in one pass, but the parenting logic would be more complex.
454         CompositingState compState(updateRoot, m_compositingConsultsOverlap);
455         bool layersChanged = false;
456         bool saw3DTransform = false;
457         m_fixedPositionLayerNotCompositedReasonMap.clear();
458         if (m_compositingConsultsOverlap) {
459             OverlapMap overlapTestRequestMap;
460             computeCompositingRequirements(0, updateRoot, &overlapTestRequestMap, compState, layersChanged, saw3DTransform);
461         } else
462             computeCompositingRequirements(0, updateRoot, 0, compState, layersChanged, saw3DTransform);
463         
464         needHierarchyUpdate |= layersChanged;
465     }
466
467 #if !LOG_DISABLED
468     if (compositingLogEnabled() && isFullUpdate && (needHierarchyUpdate || needGeometryUpdate)) {
469         m_obligateCompositedLayerCount = 0;
470         m_secondaryCompositedLayerCount = 0;
471         m_obligatoryBackingStoreBytes = 0;
472         m_secondaryBackingStoreBytes = 0;
473
474         Frame* frame = m_renderView->frameView()->frame();
475         bool isMainFrame = !m_renderView->document()->ownerElement();
476         LOG(Compositing, "\nUpdate %d of %s. Overlap testing is %s\n", m_rootLayerUpdateCount, isMainFrame ? "main frame" : frame->tree()->uniqueName().string().utf8().data(),
477             m_compositingConsultsOverlap ? "on" : "off");
478     }
479 #endif
480
481     if (needHierarchyUpdate) {
482         // Update the hierarchy of the compositing layers.
483         Vector<GraphicsLayer*> childList;
484         rebuildCompositingLayerTree(updateRoot, childList, 0);
485
486         // Host the document layer in the RenderView's root layer.
487         if (isFullUpdate) {
488             // Even when childList is empty, don't drop out of compositing mode if there are
489             // composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
490             if (childList.isEmpty() && !hasAnyAdditionalCompositedLayers(updateRoot))
491                 destroyRootLayer();
492             else
493                 m_rootContentLayer->setChildren(childList);
494         }
495     } else if (needGeometryUpdate) {
496         // We just need to do a geometry update. This is only used for position:fixed scrolling;
497         // most of the time, geometry is updated via RenderLayer::styleChanged().
498         updateLayerTreeGeometry(updateRoot, 0);
499     }
500     
501 #if !LOG_DISABLED
502     if (compositingLogEnabled() && isFullUpdate && (needHierarchyUpdate || needGeometryUpdate)) {
503         double endTime = currentTime();
504         LOG(Compositing, "Total layers   primary   secondary   obligatory backing (KB)   secondary backing(KB)   total backing (KB)  update time (ms)\n");
505
506         LOG(Compositing, "%8d %11d %9d %20.2f %22.2f %22.2f %18.2f\n",
507             m_obligateCompositedLayerCount + m_secondaryCompositedLayerCount, m_obligateCompositedLayerCount,
508             m_secondaryCompositedLayerCount, m_obligatoryBackingStoreBytes / 1024, m_secondaryBackingStoreBytes / 1024, (m_obligatoryBackingStoreBytes + m_secondaryBackingStoreBytes) / 1024, 1000.0 * (endTime - startTime));
509     }
510 #endif
511     ASSERT(updateRoot || !m_compositingLayersNeedRebuild);
512
513     if (!hasAcceleratedCompositing())
514         enableCompositingMode(false);
515
516     // Inform the inspector that the layer tree has changed.
517     InspectorInstrumentation::layerTreeDidChange(page());
518 }
519
520 void RenderLayerCompositor::layerBecameNonComposited(const RenderLayer* renderLayer)
521 {
522     // Inform the inspector that the given RenderLayer was destroyed.
523     InspectorInstrumentation::renderLayerDestroyed(page(), renderLayer);
524
525     ASSERT(m_compositedLayerCount > 0);
526     --m_compositedLayerCount;
527 }
528
529 #if !LOG_DISABLED
530 void RenderLayerCompositor::logLayerInfo(const RenderLayer* layer, int depth)
531 {
532     if (!compositingLogEnabled())
533         return;
534         
535     RenderLayerBacking* backing = layer->backing();
536     if (requiresCompositingLayer(layer) || layer->isRootLayer()) {
537         ++m_obligateCompositedLayerCount;
538         m_obligatoryBackingStoreBytes += backing->backingStoreMemoryEstimate();
539     } else {
540         ++m_secondaryCompositedLayerCount;
541         m_secondaryBackingStoreBytes += backing->backingStoreMemoryEstimate();
542     }
543
544     LOG(Compositing, "%*p %dx%d %.2fKB (%s) %s\n", 12 + depth * 2, layer, backing->compositedBounds().width(), backing->compositedBounds().height(),
545         backing->backingStoreMemoryEstimate() / 1024,
546         reasonForCompositing(layer), layer->backing()->nameForLayer().utf8().data());
547 }
548 #endif
549
550 bool RenderLayerCompositor::updateBacking(RenderLayer* layer, CompositingChangeRepaint shouldRepaint)
551 {
552     bool layerChanged = false;
553
554     if (needsToBeComposited(layer)) {
555         enableCompositingMode();
556         
557         if (!layer->backing()) {
558             // If we need to repaint, do so before making backing
559             if (shouldRepaint == CompositingChangeRepaintNow)
560                 repaintOnCompositingChange(layer);
561
562             layer->ensureBacking();
563
564             // At this time, the ScrollingCooridnator only supports the top-level frame.
565             if (layer->isRootLayer() && !m_renderView->document()->ownerElement()) {
566                 layer->backing()->attachToScrollingCoordinator(0);
567                 if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
568                     scrollingCoordinator->frameViewRootLayerDidChange(m_renderView->frameView());
569             }
570
571             // This layer and all of its descendants have cached repaints rects that are relative to
572             // the repaint container, so change when compositing changes; we need to update them here.
573             if (layer->parent())
574                 layer->computeRepaintRectsIncludingDescendants();
575
576             layerChanged = true;
577         }
578
579         // Need to add for every compositing layer, because a composited layer may change from being non-fixed to fixed.
580         updateViewportConstraintStatus(layer);
581     } else {
582         if (layer->backing()) {
583             // If we're removing backing on a reflection, clear the source GraphicsLayer's pointer to
584             // its replica GraphicsLayer. In practice this should never happen because reflectee and reflection 
585             // are both either composited, or not composited.
586             if (layer->isReflection()) {
587                 RenderLayer* sourceLayer = toRenderLayerModelObject(layer->renderer()->parent())->layer();
588                 if (RenderLayerBacking* backing = sourceLayer->backing()) {
589                     ASSERT(backing->graphicsLayer()->replicaLayer() == layer->backing()->graphicsLayer());
590                     backing->graphicsLayer()->setReplicatedByLayer(0);
591                 }
592             }
593
594             removeViewportConstrainedLayer(layer);
595             
596             layer->clearBacking();
597             layerChanged = true;
598
599             // This layer and all of its descendants have cached repaints rects that are relative to
600             // the repaint container, so change when compositing changes; we need to update them here.
601             layer->computeRepaintRectsIncludingDescendants();
602
603             // If we need to repaint, do so now that we've removed the backing
604             if (shouldRepaint == CompositingChangeRepaintNow)
605                 repaintOnCompositingChange(layer);
606         }
607     }
608     
609 #if ENABLE(VIDEO)
610     if (layerChanged && layer->renderer()->isVideo()) {
611         // If it's a video, give the media player a chance to hook up to the layer.
612         RenderVideo* video = toRenderVideo(layer->renderer());
613         video->acceleratedRenderingStateChanged();
614     }
615 #endif
616
617     if (layerChanged && layer->renderer()->isRenderPart()) {
618         RenderLayerCompositor* innerCompositor = frameContentsCompositor(toRenderPart(layer->renderer()));
619         if (innerCompositor && innerCompositor->inCompositingMode())
620             innerCompositor->updateRootLayerAttachment();
621     }
622     
623     if (layerChanged)
624         layer->clearClipRectsIncludingDescendants(PaintingClipRects);
625
626     // If a fixed position layer gained/lost a backing, the scrolling coordinator needs to recalculate whether it can do fast scrolling.
627     if (layerChanged && layer->renderer()->style()->position() == FixedPosition) {
628         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
629             scrollingCoordinator->frameViewFixedObjectsDidChange(m_renderView->frameView());
630     }
631     
632     if (layer->backing())
633         layer->backing()->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
634
635     return layerChanged;
636 }
637
638 bool RenderLayerCompositor::updateLayerCompositingState(RenderLayer* layer, CompositingChangeRepaint shouldRepaint)
639 {
640     bool layerChanged = updateBacking(layer, shouldRepaint);
641
642     // See if we need content or clipping layers. Methods called here should assume
643     // that the compositing state of descendant layers has not been updated yet.
644     if (layer->backing() && layer->backing()->updateGraphicsLayerConfiguration())
645         layerChanged = true;
646
647     return layerChanged;
648 }
649
650 void RenderLayerCompositor::repaintOnCompositingChange(RenderLayer* layer)
651 {
652     // If the renderer is not attached yet, no need to repaint.
653     if (layer->renderer() != m_renderView && !layer->renderer()->parent())
654         return;
655
656     RenderLayerModelObject* repaintContainer = layer->renderer()->containerForRepaint();
657     if (!repaintContainer)
658         repaintContainer = m_renderView;
659
660     layer->repaintIncludingNonCompositingDescendants(repaintContainer);
661     if (repaintContainer == m_renderView) {
662         // The contents of this layer may be moving between the window
663         // and a GraphicsLayer, so we need to make sure the window system
664         // synchronizes those changes on the screen.
665         m_renderView->frameView()->setNeedsOneShotDrawingSynchronization();
666     }
667 }
668
669 // This method assumes that layout is up-to-date, unlike repaintOnCompositingChange().
670 void RenderLayerCompositor::repaintInCompositedAncestor(RenderLayer* layer, const LayoutRect& rect)
671 {
672     RenderLayer* compositedAncestor = layer->enclosingCompositingLayerForRepaint(false /*exclude self*/);
673     if (compositedAncestor) {
674         ASSERT(compositedAncestor->backing());
675
676         LayoutPoint offset;
677         layer->convertToLayerCoords(compositedAncestor, offset);
678
679         LayoutRect repaintRect = rect;
680         repaintRect.moveBy(offset);
681
682         compositedAncestor->setBackingNeedsRepaintInRect(repaintRect);
683     }
684
685     // The contents of this layer may be moving from a GraphicsLayer to the window,
686     // so we need to make sure the window system synchronizes those changes on the screen.
687     if (compositedAncestor == m_renderView->layer())
688         m_renderView->frameView()->setNeedsOneShotDrawingSynchronization();
689 }
690
691 // The bounds of the GraphicsLayer created for a compositing layer is the union of the bounds of all the descendant
692 // RenderLayers that are rendered by the composited RenderLayer.
693 IntRect RenderLayerCompositor::calculateCompositedBounds(const RenderLayer* layer, const RenderLayer* ancestorLayer) const
694 {
695     if (!canBeComposited(layer))
696         return IntRect();
697     return layer->calculateLayerBounds(ancestorLayer, 0, RenderLayer::DefaultCalculateLayerBoundsFlags | RenderLayer::ExcludeHiddenDescendants | RenderLayer::DontConstrainForMask);
698 }
699
700 void RenderLayerCompositor::layerWasAdded(RenderLayer* /*parent*/, RenderLayer* /*child*/)
701 {
702     setCompositingLayersNeedRebuild();
703 }
704
705 void RenderLayerCompositor::layerWillBeRemoved(RenderLayer* parent, RenderLayer* child)
706 {
707     if (!child->isComposited() || parent->renderer()->documentBeingDestroyed())
708         return;
709
710     removeViewportConstrainedLayer(child);
711     repaintInCompositedAncestor(child, child->backing()->compositedBounds());
712
713     setCompositingParent(child, 0);
714     setCompositingLayersNeedRebuild();
715 }
716
717 RenderLayer* RenderLayerCompositor::enclosingNonStackingClippingLayer(const RenderLayer* layer) const
718 {
719     for (RenderLayer* curr = layer->parent(); curr != 0; curr = curr->parent()) {
720         if (curr->isStackingContext())
721             return 0;
722
723         if (curr->renderer()->hasClipOrOverflowClip())
724             return curr;
725     }
726     return 0;
727 }
728
729 void RenderLayerCompositor::addToOverlapMap(OverlapMap& overlapMap, RenderLayer* layer, IntRect& layerBounds, bool& boundsComputed)
730 {
731     if (layer->isRootLayer())
732         return;
733
734     if (!boundsComputed) {
735         layerBounds = enclosingIntRect(overlapMap.geometryMap().absoluteRect(layer->localBoundingBox()));
736         // Empty rects never intersect, but we need them to for the purposes of overlap testing.
737         if (layerBounds.isEmpty())
738             layerBounds.setSize(IntSize(1, 1));
739         boundsComputed = true;
740     }
741
742     IntRect clipRect = pixelSnappedIntRect(layer->backgroundClipRect(RenderLayer::ClipRectsContext(rootRenderLayer(), 0, AbsoluteClipRects)).rect()); // FIXME: Incorrect for CSS regions.
743     clipRect.scale(pageScaleFactor());
744     clipRect.intersect(layerBounds);
745     overlapMap.add(layer, clipRect);
746 }
747
748 void RenderLayerCompositor::addToOverlapMapRecursive(OverlapMap& overlapMap, RenderLayer* layer, RenderLayer* ancestorLayer)
749 {
750     if (!canBeComposited(layer) || overlapMap.contains(layer))
751         return;
752
753     // A null ancestorLayer is an indication that 'layer' has already been pushed.
754     if (ancestorLayer)
755         overlapMap.geometryMap().pushMappingsToAncestor(layer, ancestorLayer);
756     
757     IntRect bounds;
758     bool haveComputedBounds = false;
759     addToOverlapMap(overlapMap, layer, bounds, haveComputedBounds);
760
761 #if !ASSERT_DISABLED
762     LayerListMutationDetector mutationChecker(layer);
763 #endif
764
765     if (layer->isStackingContext()) {
766         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
767             size_t listSize = negZOrderList->size();
768             for (size_t i = 0; i < listSize; ++i) {
769                 RenderLayer* curLayer = negZOrderList->at(i);
770                 addToOverlapMapRecursive(overlapMap, curLayer, layer);
771             }
772         }
773     }
774
775     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
776         size_t listSize = normalFlowList->size();
777         for (size_t i = 0; i < listSize; ++i) {
778             RenderLayer* curLayer = normalFlowList->at(i);
779             addToOverlapMapRecursive(overlapMap, curLayer, layer);
780         }
781     }
782
783     if (layer->isStackingContext()) {
784         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
785             size_t listSize = posZOrderList->size();
786             for (size_t i = 0; i < listSize; ++i) {
787                 RenderLayer* curLayer = posZOrderList->at(i);
788                 addToOverlapMapRecursive(overlapMap, curLayer, layer);
789             }
790         }
791     }
792     
793     if (ancestorLayer)
794         overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
795 }
796
797 //  Recurse through the layers in z-index and overflow order (which is equivalent to painting order)
798 //  For the z-order children of a compositing layer:
799 //      If a child layers has a compositing layer, then all subsequent layers must
800 //      be compositing in order to render above that layer.
801 //
802 //      If a child in the negative z-order list is compositing, then the layer itself
803 //      must be compositing so that its contents render over that child.
804 //      This implies that its positive z-index children must also be compositing.
805 //
806 void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer* layer, OverlapMap* overlapMap, CompositingState& compositingState, bool& layersChanged, bool& descendantHas3DTransform)
807 {
808     layer->updateLayerListsIfNeeded();
809     
810     if (overlapMap)
811         overlapMap->geometryMap().pushMappingsToAncestor(layer, ancestorLayer);
812     
813     // Clear the flag
814     layer->setHasCompositingDescendant(false);
815     
816     RenderLayer::IndirectCompositingReason compositingReason = compositingState.m_subtreeIsCompositing ? RenderLayer::IndirectCompositingForStacking : RenderLayer::NoIndirectCompositingReason;
817
818     bool haveComputedBounds = false;
819     IntRect absBounds;
820     if (overlapMap && !overlapMap->isEmpty() && compositingState.m_testingOverlap) {
821         // If we're testing for overlap, we only need to composite if we overlap something that is already composited.
822         absBounds = enclosingIntRect(overlapMap->geometryMap().absoluteRect(layer->localBoundingBox()));
823
824         // Empty rects never intersect, but we need them to for the purposes of overlap testing.
825         if (absBounds.isEmpty())
826             absBounds.setSize(IntSize(1, 1));
827         haveComputedBounds = true;
828         compositingReason = overlapMap->overlapsLayers(absBounds) ? RenderLayer::IndirectCompositingForOverlap : RenderLayer::NoIndirectCompositingReason;
829     }
830
831 #if ENABLE(VIDEO)
832     // Video is special. It's the only RenderLayer type that can both have
833     // RenderLayer children and whose children can't use its backing to render
834     // into. These children (the controls) always need to be promoted into their
835     // own layers to draw on top of the accelerated video.
836     if (compositingState.m_compositingAncestor && compositingState.m_compositingAncestor->renderer()->isVideo())
837         compositingReason = RenderLayer::IndirectCompositingForOverlap;
838 #endif
839
840     layer->setIndirectCompositingReason(compositingReason);
841
842     // The children of this layer don't need to composite, unless there is
843     // a compositing layer among them, so start by inheriting the compositing
844     // ancestor with m_subtreeIsCompositing set to false.
845     CompositingState childState(compositingState);
846     childState.m_subtreeIsCompositing = false;
847
848     FixedPositionLayerNotCompositedReason fixedPositionLayerNotCompositedReason = NoReason;
849     bool willBeComposited = needsToBeComposited(layer, &fixedPositionLayerNotCompositedReason);
850     if (willBeComposited) {
851         // Tell the parent it has compositing descendants.
852         compositingState.m_subtreeIsCompositing = true;
853         // This layer now acts as the ancestor for kids.
854         childState.m_compositingAncestor = layer;
855
856         if (overlapMap)
857             overlapMap->pushCompositingContainer();
858     } else if (fixedPositionLayerNotCompositedReason != NoReason)
859         m_fixedPositionLayerNotCompositedReasonMap.set(layer, fixedPositionLayerNotCompositedReason);
860
861 #if !ASSERT_DISABLED
862     LayerListMutationDetector mutationChecker(layer);
863 #endif
864
865     bool anyDescendantHas3DTransform = false;
866
867     if (layer->isStackingContext()) {
868         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
869             size_t listSize = negZOrderList->size();
870             for (size_t i = 0; i < listSize; ++i) {
871                 RenderLayer* curLayer = negZOrderList->at(i);
872                 computeCompositingRequirements(layer, curLayer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
873
874                 // If we have to make a layer for this child, make one now so we can have a contents layer
875                 // (since we need to ensure that the -ve z-order child renders underneath our contents).
876                 if (!willBeComposited && childState.m_subtreeIsCompositing) {
877                     // make layer compositing
878                     layer->setIndirectCompositingReason(RenderLayer::IndirectCompositingForBackgroundLayer);
879                     childState.m_compositingAncestor = layer;
880                     if (overlapMap)
881                         overlapMap->pushCompositingContainer();
882                     willBeComposited = true;
883                 }
884             }
885         }
886     }
887     
888     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
889         size_t listSize = normalFlowList->size();
890         for (size_t i = 0; i < listSize; ++i) {
891             RenderLayer* curLayer = normalFlowList->at(i);
892             computeCompositingRequirements(layer, curLayer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
893         }
894     }
895
896     if (layer->isStackingContext()) {
897         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
898             size_t listSize = posZOrderList->size();
899             for (size_t i = 0; i < listSize; ++i) {
900                 RenderLayer* curLayer = posZOrderList->at(i);
901                 computeCompositingRequirements(layer, curLayer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
902             }
903         }
904     }
905     
906     // If we just entered compositing mode, the root will have become composited (as long as accelerated compositing is enabled).
907     if (layer->isRootLayer()) {
908         if (inCompositingMode() && m_hasAcceleratedCompositing)
909             willBeComposited = true;
910     }
911     
912     ASSERT(willBeComposited == needsToBeComposited(layer));
913
914     // All layers (even ones that aren't being composited) need to get added to
915     // the overlap map. Layers that do not composite will draw into their
916     // compositing ancestor's backing, and so are still considered for overlap.
917     if (overlapMap && childState.m_compositingAncestor && !childState.m_compositingAncestor->isRootLayer())
918         addToOverlapMap(*overlapMap, layer, absBounds, haveComputedBounds);
919
920     // Now check for reasons to become composited that depend on the state of descendant layers.
921     RenderLayer::IndirectCompositingReason indirectCompositingReason;
922     if (!willBeComposited && canBeComposited(layer)
923         && requiresCompositingForIndirectReason(layer->renderer(), childState.m_subtreeIsCompositing, anyDescendantHas3DTransform, indirectCompositingReason)) {
924         layer->setIndirectCompositingReason(indirectCompositingReason);
925         childState.m_compositingAncestor = layer;
926         if (overlapMap) {
927             overlapMap->pushCompositingContainer();
928             addToOverlapMapRecursive(*overlapMap, layer);
929         }
930         willBeComposited = true;
931     }
932     
933     ASSERT(willBeComposited == needsToBeComposited(layer));
934     if (layer->reflectionLayer()) {
935         // FIXME: Shouldn't we call computeCompositingRequirements to handle a reflection overlapping with another renderer?
936         layer->reflectionLayer()->setIndirectCompositingReason(willBeComposited ? RenderLayer::IndirectCompositingForStacking : RenderLayer::NoIndirectCompositingReason);
937     }
938
939     // Subsequent layers in the parent stacking context also need to composite.
940     if (childState.m_subtreeIsCompositing)
941         compositingState.m_subtreeIsCompositing = true;
942
943     // Turn overlap testing off for later layers if it's already off, or if we have a 3D transform or an animating transform.
944     if (!childState.m_testingOverlap || layer->has3DTransform() || isRunningAcceleratedTransformAnimation(layer->renderer()))
945         compositingState.m_testingOverlap = false;
946
947     // Set the flag to say that this SC has compositing children.
948     layer->setHasCompositingDescendant(childState.m_subtreeIsCompositing);
949
950     // setHasCompositingDescendant() may have changed the answer to needsToBeComposited() when clipping,
951     // so test that again.
952     if (canBeComposited(layer) && clipsCompositingDescendants(layer)) {
953         if (!willBeComposited) {
954             childState.m_compositingAncestor = layer;
955             if (overlapMap) {
956                 overlapMap->pushCompositingContainer();
957                 addToOverlapMapRecursive(*overlapMap, layer);
958             }
959             willBeComposited = true;
960          }
961
962         // We're done processing an element that clips. The container can keep testing overlap.
963         compositingState.m_testingOverlap = true;
964     }
965
966     if (overlapMap && childState.m_compositingAncestor == layer && !layer->isRootLayer())
967         overlapMap->popCompositingContainer();
968
969     // If we're back at the root, and no other layers need to be composited, and the root layer itself doesn't need
970     // to be composited, then we can drop out of compositing mode altogether. However, don't drop out of compositing mode
971     // if there are composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
972     if (layer->isRootLayer() && !childState.m_subtreeIsCompositing && !requiresCompositingLayer(layer) && !m_forceCompositingMode && !hasAnyAdditionalCompositedLayers(layer)) {
973         enableCompositingMode(false);
974         willBeComposited = false;
975     }
976     
977     // If the layer is going into compositing mode, repaint its old location.
978     ASSERT(willBeComposited == needsToBeComposited(layer));
979     if (!layer->isComposited() && willBeComposited)
980         repaintOnCompositingChange(layer);
981
982     // Update backing now, so that we can use isComposited() reliably during tree traversal in rebuildCompositingLayerTree().
983     if (updateBacking(layer, CompositingChangeRepaintNow))
984         layersChanged = true;
985
986     if (layer->reflectionLayer() && updateLayerCompositingState(layer->reflectionLayer(), CompositingChangeRepaintNow))
987         layersChanged = true;
988
989     descendantHas3DTransform |= anyDescendantHas3DTransform || layer->has3DTransform();
990
991     if (overlapMap)
992         overlapMap->geometryMap().popMappingsToAncestor(ancestorLayer);
993 }
994
995 void RenderLayerCompositor::setCompositingParent(RenderLayer* childLayer, RenderLayer* parentLayer)
996 {
997     ASSERT(!parentLayer || childLayer->ancestorCompositingLayer() == parentLayer);
998     ASSERT(childLayer->isComposited());
999
1000     // It's possible to be called with a parent that isn't yet composited when we're doing
1001     // partial updates as required by painting or hit testing. Just bail in that case;
1002     // we'll do a full layer update soon.
1003     if (!parentLayer || !parentLayer->isComposited())
1004         return;
1005
1006     if (parentLayer) {
1007         GraphicsLayer* hostingLayer = parentLayer->backing()->parentForSublayers();
1008         GraphicsLayer* hostedLayer = childLayer->backing()->childForSuperlayers();
1009         
1010         hostingLayer->addChild(hostedLayer);
1011     } else
1012         childLayer->backing()->childForSuperlayers()->removeFromParent();
1013 }
1014
1015 void RenderLayerCompositor::removeCompositedChildren(RenderLayer* layer)
1016 {
1017     ASSERT(layer->isComposited());
1018
1019     GraphicsLayer* hostingLayer = layer->backing()->parentForSublayers();
1020     hostingLayer->removeAllChildren();
1021 }
1022
1023 #if ENABLE(VIDEO)
1024 bool RenderLayerCompositor::canAccelerateVideoRendering(RenderVideo* o) const
1025 {
1026     if (!m_hasAcceleratedCompositing)
1027         return false;
1028
1029     return o->supportsAcceleratedRendering();
1030 }
1031 #endif
1032
1033 void RenderLayerCompositor::rebuildCompositingLayerTree(RenderLayer* layer, Vector<GraphicsLayer*>& childLayersOfEnclosingLayer, int depth)
1034 {
1035     // Make the layer compositing if necessary, and set up clipping and content layers.
1036     // Note that we can only do work here that is independent of whether the descendant layers
1037     // have been processed. computeCompositingRequirements() will already have done the repaint if necessary.
1038     
1039     RenderLayerBacking* layerBacking = layer->backing();
1040     if (layerBacking) {
1041         // The compositing state of all our children has been updated already, so now
1042         // we can compute and cache the composited bounds for this layer.
1043         layerBacking->updateCompositedBounds();
1044
1045         if (RenderLayer* reflection = layer->reflectionLayer()) {
1046             if (reflection->backing())
1047                 reflection->backing()->updateCompositedBounds();
1048         }
1049
1050         layerBacking->updateGraphicsLayerConfiguration();
1051         layerBacking->updateGraphicsLayerGeometry();
1052
1053         if (!layer->parent())
1054             updateRootLayerPosition();
1055
1056 #if !LOG_DISABLED
1057         logLayerInfo(layer, depth);
1058 #else
1059         UNUSED_PARAM(depth);
1060 #endif
1061     }
1062
1063     // If this layer has backing, then we are collecting its children, otherwise appending
1064     // to the compositing child list of an enclosing layer.
1065     Vector<GraphicsLayer*> layerChildren;
1066     Vector<GraphicsLayer*>& childList = layerBacking ? layerChildren : childLayersOfEnclosingLayer;
1067
1068 #if !ASSERT_DISABLED
1069     LayerListMutationDetector mutationChecker(layer);
1070 #endif
1071
1072     if (layer->isStackingContext()) {
1073         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
1074             size_t listSize = negZOrderList->size();
1075             for (size_t i = 0; i < listSize; ++i) {
1076                 RenderLayer* curLayer = negZOrderList->at(i);
1077                 rebuildCompositingLayerTree(curLayer, childList, depth + 1);
1078             }
1079         }
1080
1081         // If a negative z-order child is compositing, we get a foreground layer which needs to get parented.
1082         if (layerBacking && layerBacking->foregroundLayer())
1083             childList.append(layerBacking->foregroundLayer());
1084     }
1085
1086     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
1087         size_t listSize = normalFlowList->size();
1088         for (size_t i = 0; i < listSize; ++i) {
1089             RenderLayer* curLayer = normalFlowList->at(i);
1090             rebuildCompositingLayerTree(curLayer, childList, depth + 1);
1091         }
1092     }
1093     
1094     if (layer->isStackingContext()) {
1095         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
1096             size_t listSize = posZOrderList->size();
1097             for (size_t i = 0; i < listSize; ++i) {
1098                 RenderLayer* curLayer = posZOrderList->at(i);
1099                 rebuildCompositingLayerTree(curLayer, childList, depth + 1);
1100             }
1101         }
1102     }
1103     
1104     if (layerBacking) {
1105         bool parented = false;
1106         if (layer->renderer()->isRenderPart())
1107             parented = parentFrameContentLayers(toRenderPart(layer->renderer()));
1108
1109         if (!parented)
1110             layerBacking->parentForSublayers()->setChildren(layerChildren);
1111
1112         // If the layer has a clipping layer the overflow controls layers will be siblings of the clipping layer.
1113         // Otherwise, the overflow control layers are normal children.
1114         if (!layerBacking->hasClippingLayer() && !layerBacking->hasScrollingLayer()) {
1115             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForHorizontalScrollbar()) {
1116                 overflowControlLayer->removeFromParent();
1117                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
1118             }
1119
1120             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForVerticalScrollbar()) {
1121                 overflowControlLayer->removeFromParent();
1122                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
1123             }
1124
1125             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForScrollCorner()) {
1126                 overflowControlLayer->removeFromParent();
1127                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
1128             }
1129         }
1130
1131         childLayersOfEnclosingLayer.append(layerBacking->childForSuperlayers());
1132     }
1133 }
1134
1135 void RenderLayerCompositor::frameViewDidChangeLocation(const IntPoint& contentsOffset)
1136 {
1137     if (m_overflowControlsHostLayer)
1138         m_overflowControlsHostLayer->setPosition(contentsOffset);
1139 }
1140
1141 void RenderLayerCompositor::frameViewDidChangeSize()
1142 {
1143     if (m_clipLayer) {
1144         FrameView* frameView = m_renderView->frameView();
1145         m_clipLayer->setSize(frameView->visibleContentRect(false /* exclude scrollbars */).size());
1146
1147         frameViewDidScroll();
1148         updateOverflowControlsLayers();
1149
1150 #if ENABLE(RUBBER_BANDING)
1151         if (m_layerForOverhangAreas)
1152             m_layerForOverhangAreas->setSize(frameView->frameRect().size());
1153 #endif
1154     }
1155 }
1156
1157 void RenderLayerCompositor::frameViewDidScroll()
1158 {
1159     FrameView* frameView = m_renderView->frameView();
1160     IntPoint scrollPosition = frameView->scrollPosition();
1161
1162     if (!m_scrollLayer)
1163         return;
1164
1165     // If there's a scrolling coordinator that manages scrolling for this frame view,
1166     // it will also manage updating the scroll layer position.
1167     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator()) {
1168         if (scrollingCoordinator->coordinatesScrollingForFrameView(frameView))
1169             return;
1170     }
1171
1172     m_scrollLayer->setPosition(FloatPoint(-scrollPosition.x(), -scrollPosition.y()));
1173 }
1174
1175 void RenderLayerCompositor::frameViewDidLayout()
1176 {
1177     RenderLayerBacking* renderViewBacking = m_renderView->layer()->backing();
1178     if (renderViewBacking)
1179         renderViewBacking->adjustTileCacheCoverage();
1180 }
1181
1182 void RenderLayerCompositor::scrollingLayerDidChange(RenderLayer* layer)
1183 {
1184     RenderLayerBacking* backing = layer->backing();
1185     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
1186         scrollingCoordinator->scrollableAreaScrollLayerDidChange(layer, backing ? backing->scrollingContentsLayer() : 0);
1187 }
1188
1189 String RenderLayerCompositor::layerTreeAsText(LayerTreeFlags flags)
1190 {
1191     updateCompositingLayers(CompositingUpdateAfterLayout);
1192
1193     if (!m_rootContentLayer)
1194         return String();
1195
1196     flushPendingLayerChanges(true);
1197
1198     LayerTreeAsTextBehavior layerTreeBehavior = LayerTreeAsTextBehaviorNormal;
1199     if (flags & LayerTreeFlagsIncludeDebugInfo)
1200         layerTreeBehavior |= LayerTreeAsTextDebug;
1201     if (flags & LayerTreeFlagsIncludeVisibleRects)
1202         layerTreeBehavior |= LayerTreeAsTextIncludeVisibleRects;
1203     if (flags & LayerTreeFlagsIncludeTileCaches)
1204         layerTreeBehavior |= LayerTreeAsTextIncludeTileCaches;
1205     if (flags & LayerTreeFlagsIncludeRepaintRects)
1206         layerTreeBehavior |= LayerTreeAsTextIncludeRepaintRects;
1207
1208     // We skip dumping the scroll and clip layers to keep layerTreeAsText output
1209     // similar between platforms.
1210     String layerTreeText = m_rootContentLayer->layerTreeAsText(layerTreeBehavior);
1211
1212     // The true root layer is not included in the dump, so if we want to report
1213     // its repaint rects, they must be included here.
1214     if (flags & LayerTreeFlagsIncludeRepaintRects) {
1215         String layerTreeTextWithRootRepaintRects = m_renderView->frameView()->trackedRepaintRectsAsText();
1216         layerTreeTextWithRootRepaintRects.append(layerTreeText);
1217         return layerTreeTextWithRootRepaintRects;
1218     }
1219
1220     return layerTreeText;
1221 }
1222
1223 RenderLayerCompositor* RenderLayerCompositor::frameContentsCompositor(RenderPart* renderer)
1224 {
1225     if (!renderer->node()->isFrameOwnerElement())
1226         return 0;
1227         
1228     HTMLFrameOwnerElement* element = static_cast<HTMLFrameOwnerElement*>(renderer->node());
1229     if (Document* contentDocument = element->contentDocument()) {
1230         if (RenderView* view = contentDocument->renderView())
1231             return view->compositor();
1232     }
1233     return 0;
1234 }
1235
1236 bool RenderLayerCompositor::parentFrameContentLayers(RenderPart* renderer)
1237 {
1238     RenderLayerCompositor* innerCompositor = frameContentsCompositor(renderer);
1239     if (!innerCompositor || !innerCompositor->inCompositingMode() || innerCompositor->rootLayerAttachment() != RootLayerAttachedViaEnclosingFrame)
1240         return false;
1241     
1242     RenderLayer* layer = renderer->layer();
1243     if (!layer->isComposited())
1244         return false;
1245
1246     RenderLayerBacking* backing = layer->backing();
1247     GraphicsLayer* hostingLayer = backing->parentForSublayers();
1248     GraphicsLayer* rootLayer = innerCompositor->rootGraphicsLayer();
1249     if (hostingLayer->children().size() != 1 || hostingLayer->children()[0] != rootLayer) {
1250         hostingLayer->removeAllChildren();
1251         hostingLayer->addChild(rootLayer);
1252     }
1253     return true;
1254 }
1255
1256 // This just updates layer geometry without changing the hierarchy.
1257 void RenderLayerCompositor::updateLayerTreeGeometry(RenderLayer* layer, int depth)
1258 {
1259     if (RenderLayerBacking* layerBacking = layer->backing()) {
1260         // The compositing state of all our children has been updated already, so now
1261         // we can compute and cache the composited bounds for this layer.
1262         layerBacking->updateCompositedBounds();
1263
1264         if (RenderLayer* reflection = layer->reflectionLayer()) {
1265             if (reflection->backing())
1266                 reflection->backing()->updateCompositedBounds();
1267         }
1268
1269         layerBacking->updateGraphicsLayerConfiguration();
1270         layerBacking->updateGraphicsLayerGeometry();
1271
1272         if (!layer->parent())
1273             updateRootLayerPosition();
1274
1275 #if !LOG_DISABLED
1276         logLayerInfo(layer, depth);
1277 #else
1278         UNUSED_PARAM(depth);
1279 #endif
1280     }
1281
1282 #if !ASSERT_DISABLED
1283     LayerListMutationDetector mutationChecker(layer);
1284 #endif
1285
1286     if (layer->isStackingContext()) {
1287         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
1288             size_t listSize = negZOrderList->size();
1289             for (size_t i = 0; i < listSize; ++i)
1290                 updateLayerTreeGeometry(negZOrderList->at(i), depth + 1);
1291         }
1292     }
1293
1294     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
1295         size_t listSize = normalFlowList->size();
1296         for (size_t i = 0; i < listSize; ++i)
1297             updateLayerTreeGeometry(normalFlowList->at(i), depth + 1);
1298     }
1299     
1300     if (layer->isStackingContext()) {
1301         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
1302             size_t listSize = posZOrderList->size();
1303             for (size_t i = 0; i < listSize; ++i)
1304                 updateLayerTreeGeometry(posZOrderList->at(i), depth + 1);
1305         }
1306     }
1307 }
1308
1309 // Recurs down the RenderLayer tree until its finds the compositing descendants of compositingAncestor and updates their geometry.
1310 void RenderLayerCompositor::updateCompositingDescendantGeometry(RenderLayer* compositingAncestor, RenderLayer* layer, RenderLayerBacking::UpdateDepth updateDepth)
1311 {
1312     if (layer != compositingAncestor) {
1313         if (RenderLayerBacking* layerBacking = layer->backing()) {
1314             layerBacking->updateCompositedBounds();
1315
1316             if (RenderLayer* reflection = layer->reflectionLayer()) {
1317                 if (reflection->backing())
1318                     reflection->backing()->updateCompositedBounds();
1319             }
1320
1321             layerBacking->updateGraphicsLayerGeometry();
1322             if (updateDepth == RenderLayerBacking::CompositingChildren)
1323                 return;
1324         }
1325     }
1326
1327     if (layer->reflectionLayer())
1328         updateCompositingDescendantGeometry(compositingAncestor, layer->reflectionLayer(), updateDepth);
1329
1330     if (!layer->hasCompositingDescendant())
1331         return;
1332
1333 #if !ASSERT_DISABLED
1334     LayerListMutationDetector mutationChecker(layer);
1335 #endif
1336     
1337     if (layer->isStackingContext()) {
1338         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
1339             size_t listSize = negZOrderList->size();
1340             for (size_t i = 0; i < listSize; ++i)
1341                 updateCompositingDescendantGeometry(compositingAncestor, negZOrderList->at(i), updateDepth);
1342         }
1343     }
1344
1345     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
1346         size_t listSize = normalFlowList->size();
1347         for (size_t i = 0; i < listSize; ++i)
1348             updateCompositingDescendantGeometry(compositingAncestor, normalFlowList->at(i), updateDepth);
1349     }
1350     
1351     if (layer->isStackingContext()) {
1352         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
1353             size_t listSize = posZOrderList->size();
1354             for (size_t i = 0; i < listSize; ++i)
1355                 updateCompositingDescendantGeometry(compositingAncestor, posZOrderList->at(i), updateDepth);
1356         }
1357     }
1358 }
1359
1360
1361 void RenderLayerCompositor::repaintCompositedLayers(const IntRect* absRect)
1362 {
1363     recursiveRepaintLayer(rootRenderLayer(), absRect);
1364 }
1365
1366 void RenderLayerCompositor::recursiveRepaintLayer(RenderLayer* layer, const IntRect* rect)
1367 {
1368     // FIXME: This method does not work correctly with transforms.
1369     if (layer->isComposited() && !layer->backing()->paintsIntoCompositedAncestor()) {
1370         if (rect)
1371             layer->setBackingNeedsRepaintInRect(*rect);
1372         else
1373             layer->setBackingNeedsRepaint();
1374     }
1375
1376 #if !ASSERT_DISABLED
1377     LayerListMutationDetector mutationChecker(layer);
1378 #endif
1379
1380     if (layer->hasCompositingDescendant()) {
1381         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
1382             size_t listSize = negZOrderList->size();
1383             for (size_t i = 0; i < listSize; ++i) {
1384                 RenderLayer* curLayer = negZOrderList->at(i);
1385                 if (rect) {
1386                     IntRect childRect(*rect);
1387                     curLayer->convertToPixelSnappedLayerCoords(layer, childRect);
1388                     recursiveRepaintLayer(curLayer, &childRect);
1389                 } else
1390                     recursiveRepaintLayer(curLayer);
1391             }
1392         }
1393
1394         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
1395             size_t listSize = posZOrderList->size();
1396             for (size_t i = 0; i < listSize; ++i) {
1397                 RenderLayer* curLayer = posZOrderList->at(i);
1398                 if (rect) {
1399                     IntRect childRect(*rect);
1400                     curLayer->convertToPixelSnappedLayerCoords(layer, childRect);
1401                     recursiveRepaintLayer(curLayer, &childRect);
1402                 } else
1403                     recursiveRepaintLayer(curLayer);
1404             }
1405         }
1406     }
1407     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
1408         size_t listSize = normalFlowList->size();
1409         for (size_t i = 0; i < listSize; ++i) {
1410             RenderLayer* curLayer = normalFlowList->at(i);
1411             if (rect) {
1412                 IntRect childRect(*rect);
1413                 curLayer->convertToPixelSnappedLayerCoords(layer, childRect);
1414                 recursiveRepaintLayer(curLayer, &childRect);
1415             } else
1416                 recursiveRepaintLayer(curLayer);
1417         }
1418     }
1419 }
1420
1421 RenderLayer* RenderLayerCompositor::rootRenderLayer() const
1422 {
1423     return m_renderView->layer();
1424 }
1425
1426 GraphicsLayer* RenderLayerCompositor::rootGraphicsLayer() const
1427 {
1428     if (m_overflowControlsHostLayer)
1429         return m_overflowControlsHostLayer.get();
1430     return m_rootContentLayer.get();
1431 }
1432
1433 GraphicsLayer* RenderLayerCompositor::scrollLayer() const
1434 {
1435     return m_scrollLayer.get();
1436 }
1437
1438 TiledBacking* RenderLayerCompositor::pageTiledBacking() const
1439 {
1440     RenderLayerBacking* renderViewBacking = m_renderView->layer()->backing();
1441     return renderViewBacking ? renderViewBacking->tiledBacking() : 0;
1442 }
1443
1444 void RenderLayerCompositor::didMoveOnscreen()
1445 {
1446     if (TiledBacking* tiledBacking = pageTiledBacking())
1447         tiledBacking->setIsInWindow(true);
1448
1449     if (!inCompositingMode() || m_rootLayerAttachment != RootLayerUnattached)
1450         return;
1451
1452     RootLayerAttachment attachment = shouldPropagateCompositingToEnclosingFrame() ? RootLayerAttachedViaEnclosingFrame : RootLayerAttachedViaChromeClient;
1453     attachRootLayer(attachment);
1454 }
1455
1456 void RenderLayerCompositor::willMoveOffscreen()
1457 {
1458     if (TiledBacking* tiledBacking = pageTiledBacking())
1459         tiledBacking->setIsInWindow(false);
1460
1461     if (!inCompositingMode() || m_rootLayerAttachment == RootLayerUnattached)
1462         return;
1463
1464     detachRootLayer();
1465 }
1466
1467 void RenderLayerCompositor::clearBackingForLayerIncludingDescendants(RenderLayer* layer)
1468 {
1469     if (!layer)
1470         return;
1471
1472     if (layer->isComposited()) {
1473         removeViewportConstrainedLayer(layer);
1474         layer->clearBacking();
1475     }
1476     
1477     for (RenderLayer* currLayer = layer->firstChild(); currLayer; currLayer = currLayer->nextSibling())
1478         clearBackingForLayerIncludingDescendants(currLayer);
1479 }
1480
1481 void RenderLayerCompositor::clearBackingForAllLayers()
1482 {
1483     clearBackingForLayerIncludingDescendants(m_renderView->layer());
1484 }
1485
1486 void RenderLayerCompositor::updateRootLayerPosition()
1487 {
1488     if (m_rootContentLayer) {
1489         const IntRect& documentRect = m_renderView->documentRect();
1490         m_rootContentLayer->setSize(documentRect.size());
1491         m_rootContentLayer->setPosition(documentRect.location());
1492     }
1493     if (m_clipLayer) {
1494         FrameView* frameView = m_renderView->frameView();
1495         m_clipLayer->setSize(frameView->visibleContentRect(false /* exclude scrollbars */).size());
1496     }
1497
1498 #if ENABLE(RUBBER_BANDING)
1499     if (m_contentShadowLayer) {
1500         m_contentShadowLayer->setPosition(m_rootContentLayer->position());
1501
1502         FloatSize rootContentLayerSize = m_rootContentLayer->size();
1503         if (m_contentShadowLayer->size() != rootContentLayerSize) {
1504             m_contentShadowLayer->setSize(rootContentLayerSize);
1505             ScrollbarTheme::theme()->setUpContentShadowLayer(m_contentShadowLayer.get());
1506         }
1507     }
1508 #endif
1509 }
1510
1511 bool RenderLayerCompositor::has3DContent() const
1512 {
1513     return layerHas3DContent(rootRenderLayer());
1514 }
1515
1516 bool RenderLayerCompositor::allowsIndependentlyCompositedFrames(const FrameView* view)
1517 {
1518 #if PLATFORM(MAC)
1519     // frames are only independently composited in Mac pre-WebKit2.
1520     return view->platformWidget();
1521 #else
1522     UNUSED_PARAM(view);
1523 #endif
1524     return false;
1525 }
1526
1527 bool RenderLayerCompositor::shouldPropagateCompositingToEnclosingFrame() const
1528 {
1529     // Parent document content needs to be able to render on top of a composited frame, so correct behavior
1530     // is to have the parent document become composited too. However, this can cause problems on platforms that
1531     // use native views for frames (like Mac), so disable that behavior on those platforms for now.
1532     HTMLFrameOwnerElement* ownerElement = m_renderView->document()->ownerElement();
1533     RenderObject* renderer = ownerElement ? ownerElement->renderer() : 0;
1534
1535     // If we are the top-level frame, don't propagate.
1536     if (!ownerElement)
1537         return false;
1538
1539     if (!allowsIndependentlyCompositedFrames(m_renderView->frameView()))
1540         return true;
1541
1542     if (!renderer || !renderer->isRenderPart())
1543         return false;
1544
1545     // On Mac, only propagate compositing if the frame is overlapped in the parent
1546     // document, or the parent is already compositing, or the main frame is scaled.
1547     Page* page = this->page();
1548     if (page && page->pageScaleFactor() != 1)
1549         return true;
1550     
1551     RenderPart* frameRenderer = toRenderPart(renderer);
1552     if (frameRenderer->widget()) {
1553         ASSERT(frameRenderer->widget()->isFrameView());
1554         FrameView* view = static_cast<FrameView*>(frameRenderer->widget());
1555         if (view->isOverlappedIncludingAncestors() || view->hasCompositingAncestor())
1556             return true;
1557     }
1558
1559     return false;
1560 }
1561
1562 bool RenderLayerCompositor::needsToBeComposited(const RenderLayer* layer, FixedPositionLayerNotCompositedReason* fixedPositionLayerNotCompositedReason) const
1563 {
1564     if (!canBeComposited(layer))
1565         return false;
1566
1567     return requiresCompositingLayer(layer, fixedPositionLayerNotCompositedReason) || layer->mustCompositeForIndirectReasons() || (inCompositingMode() && layer->isRootLayer());
1568 }
1569
1570 // Note: this specifies whether the RL needs a compositing layer for intrinsic reasons.
1571 // Use needsToBeComposited() to determine if a RL actually needs a compositing layer.
1572 // static
1573 bool RenderLayerCompositor::requiresCompositingLayer(const RenderLayer* layer, FixedPositionLayerNotCompositedReason* fixedPositionLayerNotCompositedReason) const
1574 {
1575     RenderObject* renderer = layer->renderer();
1576     // The compositing state of a reflection should match that of its reflected layer.
1577     if (layer->isReflection()) {
1578         renderer = renderer->parent(); // The RenderReplica's parent is the object being reflected.
1579         layer = toRenderLayerModelObject(renderer)->layer();
1580     }
1581     // The root layer always has a compositing layer, but it may not have backing.
1582     return requiresCompositingForTransform(renderer)
1583         || requiresCompositingForVideo(renderer)
1584         || requiresCompositingForCanvas(renderer)
1585         || requiresCompositingForPlugin(renderer)
1586         || requiresCompositingForFrame(renderer)
1587         || (canRender3DTransforms() && renderer->style()->backfaceVisibility() == BackfaceVisibilityHidden)
1588         || clipsCompositingDescendants(layer)
1589         || requiresCompositingForAnimation(renderer)
1590         || requiresCompositingForFilters(renderer)
1591         || requiresCompositingForPosition(renderer, layer, fixedPositionLayerNotCompositedReason)
1592         || requiresCompositingForOverflowScrolling(layer)
1593         || requiresCompositingForBlending(renderer);
1594 }
1595
1596 bool RenderLayerCompositor::canBeComposited(const RenderLayer* layer) const
1597 {
1598     // FIXME: We disable accelerated compositing for elements in a RenderFlowThread as it doesn't work properly.
1599     // See http://webkit.org/b/84900 to re-enable it.
1600     return m_hasAcceleratedCompositing && layer->isSelfPaintingLayer() && !layer->renderer()->inRenderFlowThread();
1601 }
1602
1603 bool RenderLayerCompositor::requiresOwnBackingStore(const RenderLayer* layer, const RenderLayer* compositingAncestorLayer) const
1604 {
1605     RenderObject* renderer = layer->renderer();
1606     if (compositingAncestorLayer
1607         && !(compositingAncestorLayer->backing()->graphicsLayer()->drawsContent()
1608             || compositingAncestorLayer->backing()->paintsIntoWindow()
1609             || compositingAncestorLayer->backing()->paintsIntoCompositedAncestor()))
1610         return true;
1611
1612     if (layer->isRootLayer()
1613         || layer->transform() // note: excludes perspective and transformStyle3D.
1614         || requiresCompositingForVideo(renderer)
1615         || requiresCompositingForCanvas(renderer)
1616         || requiresCompositingForPlugin(renderer)
1617         || requiresCompositingForFrame(renderer)
1618         || (canRender3DTransforms() && renderer->style()->backfaceVisibility() == BackfaceVisibilityHidden)
1619         || requiresCompositingForAnimation(renderer)
1620         || requiresCompositingForFilters(renderer)
1621         || requiresCompositingForBlending(renderer)
1622         || requiresCompositingForPosition(renderer, layer)
1623         || requiresCompositingForOverflowScrolling(layer)
1624         || renderer->isTransparent()
1625         || renderer->hasMask()
1626         || renderer->hasReflection()
1627         || renderer->hasFilter())
1628         return true;
1629         
1630     
1631     if (layer->mustCompositeForIndirectReasons()) {
1632         RenderLayer::IndirectCompositingReason reason = layer->indirectCompositingReason();
1633         return reason == RenderLayer::IndirectCompositingForOverlap
1634             || reason == RenderLayer::IndirectCompositingForStacking
1635             || reason == RenderLayer::IndirectCompositingForBackgroundLayer
1636             || reason == RenderLayer::IndirectCompositingForGraphicalEffect
1637             || reason == RenderLayer::IndirectCompositingForPreserve3D; // preserve-3d has to create backing store to ensure that 3d-transformed elements intersect.
1638     }
1639     return false;
1640 }
1641
1642 #if !LOG_DISABLED
1643 const char* RenderLayerCompositor::reasonForCompositing(const RenderLayer* layer)
1644 {
1645     RenderObject* renderer = layer->renderer();
1646     if (layer->isReflection()) {
1647         renderer = renderer->parent();
1648         layer = toRenderLayerModelObject(renderer)->layer();
1649     }
1650
1651     if (requiresCompositingForTransform(renderer))
1652         return "3D transform";
1653
1654     if (requiresCompositingForVideo(renderer))
1655         return "video";
1656
1657     if (requiresCompositingForCanvas(renderer))
1658         return "canvas";
1659
1660     if (requiresCompositingForPlugin(renderer))
1661         return "plugin";
1662
1663     if (requiresCompositingForFrame(renderer))
1664         return "iframe";
1665     
1666     if ((canRender3DTransforms() && renderer->style()->backfaceVisibility() == BackfaceVisibilityHidden))
1667         return "backface-visibility: hidden";
1668
1669     if (clipsCompositingDescendants(layer))
1670         return "clips compositing descendants";
1671
1672     if (requiresCompositingForAnimation(renderer))
1673         return "animation";
1674
1675     if (requiresCompositingForFilters(renderer))
1676         return "filters";
1677
1678     if (requiresCompositingForPosition(renderer, layer))
1679         return "position: fixed";
1680
1681     if (requiresCompositingForOverflowScrolling(layer))
1682         return "-webkit-overflow-scrolling: touch";
1683
1684     if (layer->indirectCompositingReason() == RenderLayer::IndirectCompositingForStacking)
1685         return "stacking";
1686
1687     if (layer->indirectCompositingReason() == RenderLayer::IndirectCompositingForOverlap)
1688         return "overlap";
1689
1690     if (layer->indirectCompositingReason() == RenderLayer::IndirectCompositingForBackgroundLayer)
1691         return "negative z-index children";
1692
1693     if (layer->indirectCompositingReason() == RenderLayer::IndirectCompositingForGraphicalEffect) {
1694         if (layer->transform())
1695             return "transform with composited descendants";
1696
1697         if (renderer->isTransparent())
1698             return "opacity with composited descendants";
1699
1700         if (renderer->hasMask())
1701             return "mask with composited descendants";
1702
1703         if (renderer->hasReflection())
1704             return "reflection with composited descendants";
1705
1706         if (renderer->hasFilter())
1707             return "filter with composited descendants";
1708             
1709         if (renderer->hasBlendMode())
1710             return "blending with composited descendants";
1711     }
1712
1713     if (layer->indirectCompositingReason() == RenderLayer::IndirectCompositingForPerspective)
1714         return "perspective";
1715
1716     if (layer->indirectCompositingReason() == RenderLayer::IndirectCompositingForPreserve3D)
1717         return "preserve-3d";
1718
1719     if (inCompositingMode() && layer->isRootLayer())
1720         return "root";
1721
1722     return "";
1723 }
1724 #endif
1725
1726 // Return true if the given layer has some ancestor in the RenderLayer hierarchy that clips,
1727 // up to the enclosing compositing ancestor. This is required because compositing layers are parented
1728 // according to the z-order hierarchy, yet clipping goes down the renderer hierarchy.
1729 // Thus, a RenderLayer can be clipped by a RenderLayer that is an ancestor in the renderer hierarchy,
1730 // but a sibling in the z-order hierarchy.
1731 bool RenderLayerCompositor::clippedByAncestor(RenderLayer* layer) const
1732 {
1733     if (!layer->isComposited() || !layer->parent())
1734         return false;
1735
1736     RenderLayer* compositingAncestor = layer->ancestorCompositingLayer();
1737     if (!compositingAncestor)
1738         return false;
1739
1740     // If the compositingAncestor clips, that will be taken care of by clipsCompositingDescendants(),
1741     // so we only care about clipping between its first child that is our ancestor (the computeClipRoot),
1742     // and layer.
1743     RenderLayer* computeClipRoot = 0;
1744     RenderLayer* curr = layer;
1745     while (curr) {
1746         RenderLayer* next = curr->parent();
1747         if (next == compositingAncestor) {
1748             computeClipRoot = curr;
1749             break;
1750         }
1751         curr = next;
1752     }
1753     
1754     if (!computeClipRoot || computeClipRoot == layer)
1755         return false;
1756
1757     return layer->backgroundClipRect(RenderLayer::ClipRectsContext(computeClipRoot, 0, TemporaryClipRects)).rect() != PaintInfo::infiniteRect(); // FIXME: Incorrect for CSS regions.
1758 }
1759
1760 // Return true if the given layer is a stacking context and has compositing child
1761 // layers that it needs to clip. In this case we insert a clipping GraphicsLayer
1762 // into the hierarchy between this layer and its children in the z-order hierarchy.
1763 bool RenderLayerCompositor::clipsCompositingDescendants(const RenderLayer* layer) const
1764 {
1765     return layer->hasCompositingDescendant() && layer->renderer()->hasClipOrOverflowClip();
1766 }
1767
1768 // Return true if there is an ancestor layer that is fixed positioned to the view.
1769 // Note that if the ancestor has a stacking context and is fixed position then this method
1770 // will return false.
1771 bool RenderLayerCompositor::fixedPositionedByAncestor(const RenderLayer* layer) const
1772 {
1773     if (!layer->isComposited() || !layer->parent())
1774         return false;
1775
1776     const RenderLayer* compositingAncestor = layer->ancestorCompositingLayer();
1777     if (!compositingAncestor)
1778         return false;
1779
1780     const RenderLayer* curr = layer;
1781     while (curr) {
1782         const RenderLayer* next = curr->parent();
1783         if (next == compositingAncestor)
1784             return false;
1785
1786         if (next && next->renderer()->style()->position() == FixedPosition)
1787             return true;
1788         curr = next;
1789     }
1790     return false;
1791 }
1792
1793 bool RenderLayerCompositor::requiresCompositingForScrollableFrame() const
1794 {
1795     // Need this done first to determine overflow.
1796     ASSERT(!m_renderView->needsLayout());
1797
1798     ScrollView* scrollView = m_renderView->frameView();
1799     return scrollView->verticalScrollbar() || scrollView->horizontalScrollbar();
1800 }
1801
1802 bool RenderLayerCompositor::requiresCompositingForTransform(RenderObject* renderer) const
1803 {
1804     if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
1805         return false;
1806
1807     RenderStyle* style = renderer->style();
1808     // Note that we ask the renderer if it has a transform, because the style may have transforms,
1809     // but the renderer may be an inline that doesn't suppport them.
1810     return renderer->hasTransform() && style->transform().has3DOperation();
1811 }
1812
1813 bool RenderLayerCompositor::requiresCompositingForVideo(RenderObject* renderer) const
1814 {
1815     if (!(m_compositingTriggers & ChromeClient::VideoTrigger))
1816         return false;
1817 #if ENABLE(VIDEO)
1818     if (renderer->isVideo()) {
1819         RenderVideo* video = toRenderVideo(renderer);
1820         return video->shouldDisplayVideo() && canAccelerateVideoRendering(video);
1821     }
1822 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
1823     else if (renderer->isRenderPart()) {
1824         if (!m_hasAcceleratedCompositing)
1825             return false;
1826
1827         Node* node = renderer->node();
1828         if (!node || (!node->hasTagName(HTMLNames::videoTag) && !node->hasTagName(HTMLNames::audioTag)))
1829             return false;
1830
1831         HTMLMediaElement* mediaElement = static_cast<HTMLMediaElement*>(node);
1832         return mediaElement->player() ? mediaElement->player()->supportsAcceleratedRendering() : false;
1833     }
1834 #endif // ENABLE(PLUGIN_PROXY_FOR_VIDEO)
1835 #else
1836     UNUSED_PARAM(renderer);
1837 #endif
1838     return false;
1839 }
1840
1841 bool RenderLayerCompositor::requiresCompositingForCanvas(RenderObject* renderer) const
1842 {
1843     if (!(m_compositingTriggers & ChromeClient::CanvasTrigger))
1844         return false;
1845
1846     if (renderer->isCanvas()) {
1847         HTMLCanvasElement* canvas = static_cast<HTMLCanvasElement*>(renderer->node());
1848         return canvas->renderingContext() && canvas->renderingContext()->isAccelerated();
1849     }
1850     return false;
1851 }
1852
1853 bool RenderLayerCompositor::requiresCompositingForPlugin(RenderObject* renderer) const
1854 {
1855     if (!(m_compositingTriggers & ChromeClient::PluginTrigger))
1856         return false;
1857
1858     bool composite = renderer->isEmbeddedObject() && toRenderEmbeddedObject(renderer)->allowsAcceleratedCompositing();
1859     if (!composite)
1860         return false;
1861
1862     m_reevaluateCompositingAfterLayout = true;
1863     
1864     RenderWidget* pluginRenderer = toRenderWidget(renderer);
1865     // If we can't reliably know the size of the plugin yet, don't change compositing state.
1866     if (pluginRenderer->needsLayout())
1867         return pluginRenderer->hasLayer() && pluginRenderer->layer()->isComposited();
1868
1869     // Don't go into compositing mode if height or width are zero, or size is 1x1.
1870     IntRect contentBox = pixelSnappedIntRect(pluginRenderer->contentBoxRect());
1871     return contentBox.height() * contentBox.width() > 1;
1872 }
1873
1874 bool RenderLayerCompositor::requiresCompositingForFrame(RenderObject* renderer) const
1875 {
1876     if (!renderer->isRenderPart())
1877         return false;
1878     
1879     RenderPart* frameRenderer = toRenderPart(renderer);
1880
1881     if (!frameRenderer->requiresAcceleratedCompositing())
1882         return false;
1883
1884     m_reevaluateCompositingAfterLayout = true;
1885
1886     RenderLayerCompositor* innerCompositor = frameContentsCompositor(frameRenderer);
1887     if (!innerCompositor || !innerCompositor->shouldPropagateCompositingToEnclosingFrame())
1888         return false;
1889
1890     // If we can't reliably know the size of the iframe yet, don't change compositing state.
1891     if (renderer->needsLayout())
1892         return frameRenderer->hasLayer() && frameRenderer->layer()->isComposited();
1893     
1894     // Don't go into compositing mode if height or width are zero.
1895     IntRect contentBox = pixelSnappedIntRect(frameRenderer->contentBoxRect());
1896     return contentBox.height() * contentBox.width() > 0;
1897 }
1898
1899 bool RenderLayerCompositor::requiresCompositingForAnimation(RenderObject* renderer) const
1900 {
1901     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
1902         return false;
1903
1904     if (AnimationController* animController = renderer->animation()) {
1905         return (animController->isRunningAnimationOnRenderer(renderer, CSSPropertyOpacity) && inCompositingMode())
1906 #if ENABLE(CSS_FILTERS)
1907 #if !PLATFORM(MAC) || (!PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080)
1908             // <rdar://problem/10907251> - WebKit2 doesn't support CA animations of CI filters on Lion and below
1909             || animController->isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitFilter)
1910 #endif // !PLATFORM(MAC) || (!PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080)
1911 #endif // CSS_FILTERS
1912             || animController->isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitTransform);
1913     }
1914     return false;
1915 }
1916
1917 bool RenderLayerCompositor::requiresCompositingForIndirectReason(RenderObject* renderer, bool hasCompositedDescendants, bool has3DTransformedDescendants, RenderLayer::IndirectCompositingReason& reason) const
1918 {
1919     RenderLayer* layer = toRenderBoxModelObject(renderer)->layer();
1920
1921     // When a layer has composited descendants, some effects, like 2d transforms, filters, masks etc must be implemented
1922     // via compositing so that they also apply to those composited descdendants.
1923     if (hasCompositedDescendants && (layer->transform() || renderer->createsGroup() || renderer->hasReflection())) {
1924         reason = RenderLayer::IndirectCompositingForGraphicalEffect;
1925         return true;
1926     }
1927
1928     // A layer with preserve-3d or perspective only needs to be composited if there are descendant layers that
1929     // will be affected by the preserve-3d or perspective.
1930     if (has3DTransformedDescendants) {
1931         if (renderer->style()->transformStyle3D() == TransformStyle3DPreserve3D) {
1932             reason = RenderLayer::IndirectCompositingForPreserve3D;
1933             return true;
1934         }
1935     
1936         if (renderer->style()->hasPerspective()) {
1937             reason = RenderLayer::IndirectCompositingForPerspective;
1938             return true;
1939         }
1940     }
1941
1942     reason = RenderLayer::NoIndirectCompositingReason;
1943     return false;
1944 }
1945
1946 bool RenderLayerCompositor::requiresCompositingForFilters(RenderObject* renderer) const
1947 {
1948 #if ENABLE(CSS_FILTERS)
1949     if (!(m_compositingTriggers & ChromeClient::FilterTrigger))
1950         return false;
1951
1952     return renderer->hasFilter();
1953 #else
1954     UNUSED_PARAM(renderer);
1955     return false;
1956 #endif
1957 }
1958
1959 bool RenderLayerCompositor::requiresCompositingForBlending(RenderObject* renderer) const
1960 {
1961 #if ENABLE(CSS_COMPOSITING)
1962     return renderer->hasBlendMode();
1963 #else
1964     UNUSED_PARAM(renderer);
1965     return false;
1966 #endif
1967 }
1968
1969 bool RenderLayerCompositor::requiresCompositingForPosition(RenderObject* renderer, const RenderLayer* layer, FixedPositionLayerNotCompositedReason* fixedPositionLayerNotCompositedReason) const
1970 {
1971     // position:fixed elements that create their own stacking context (e.g. have an explicit z-index,
1972     // opacity, transform) can get their own composited layer. A stacking context is required otherwise
1973     // z-index and clipping will be broken.
1974     if (!(renderer->isOutOfFlowPositioned() && renderer->style()->position() == FixedPosition && layer->isStackingContext()))
1975         return false;
1976
1977     if (Settings* settings = m_renderView->document()->settings())
1978         if (!settings->acceleratedCompositingForFixedPositionEnabled())
1979             return false;
1980
1981     RenderObject* container = renderer->container();
1982     // If the renderer is not hooked up yet then we have to wait until it is.
1983     if (!container) {
1984         m_reevaluateCompositingAfterLayout = true;
1985         return false;
1986     }
1987
1988     // Don't promote fixed position elements that are descendants of transformed elements.
1989     // They will stay fixed wrt the transformed element rather than the enclosing frame.
1990     if (container != m_renderView) {
1991         if (fixedPositionLayerNotCompositedReason)
1992             *fixedPositionLayerNotCompositedReason = DescendantOfTransformedElement;
1993         return false;
1994     }
1995
1996     // Fixed position elements that are invisible in the current view don't get their own layer.
1997     if (FrameView* frameView = m_renderView->frameView()) {
1998         IntRect viewBounds = frameView->visibleContentRect();
1999         LayoutRect layerBounds = layer->calculateLayerBounds(rootRenderLayer(), 0, RenderLayer::DefaultCalculateLayerBoundsFlags
2000             | RenderLayer::ExcludeHiddenDescendants | RenderLayer::DontConstrainForMask | RenderLayer::IncludeCompositedDescendants);
2001         layerBounds.scale(frameView->frame()->frameScaleFactor());
2002         if (!viewBounds.intersects(enclosingIntRect(layerBounds))) {
2003             if (fixedPositionLayerNotCompositedReason)
2004                 *fixedPositionLayerNotCompositedReason = LayerBoundsOutOfView;
2005             return false;
2006         }
2007     }
2008
2009     return true;
2010 }
2011
2012 bool RenderLayerCompositor::requiresCompositingForOverflowScrolling(const RenderLayer* layer) const
2013 {
2014     return layer->usesCompositedScrolling();
2015 }
2016
2017 bool RenderLayerCompositor::isRunningAcceleratedTransformAnimation(RenderObject* renderer) const
2018 {
2019     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
2020         return false;
2021
2022     if (AnimationController* animController = renderer->animation())
2023         return animController->isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitTransform);
2024
2025     return false;
2026 }
2027
2028 // If an element has negative z-index children, those children render in front of the 
2029 // layer background, so we need an extra 'contents' layer for the foreground of the layer
2030 // object.
2031 bool RenderLayerCompositor::needsContentsCompositingLayer(const RenderLayer* layer) const
2032 {
2033     return layer->hasNegativeZOrderList();
2034 }
2035
2036 bool RenderLayerCompositor::requiresScrollLayer(RootLayerAttachment attachment) const
2037 {
2038     // This applies when the application UI handles scrolling, in which case RenderLayerCompositor doesn't need to manage it.
2039     if (m_renderView->frameView()->delegatesScrolling())
2040         return false;
2041
2042     // We need to handle our own scrolling if we're:
2043     return !m_renderView->frameView()->platformWidget() // viewless (i.e. non-Mac, or Mac in WebKit2)
2044         || attachment == RootLayerAttachedViaEnclosingFrame; // a composited frame on Mac
2045 }
2046
2047 static void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
2048 {
2049     if (!scrollbar)
2050         return;
2051
2052     context.save();
2053     const IntRect& scrollbarRect = scrollbar->frameRect();
2054     context.translate(-scrollbarRect.x(), -scrollbarRect.y());
2055     IntRect transformedClip = clip;
2056     transformedClip.moveBy(scrollbarRect.location());
2057     scrollbar->paint(&context, transformedClip);
2058     context.restore();
2059 }
2060
2061 void RenderLayerCompositor::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, GraphicsLayerPaintingPhase, const IntRect& clip)
2062 {
2063     if (graphicsLayer == layerForHorizontalScrollbar())
2064         paintScrollbar(m_renderView->frameView()->horizontalScrollbar(), context, clip);
2065     else if (graphicsLayer == layerForVerticalScrollbar())
2066         paintScrollbar(m_renderView->frameView()->verticalScrollbar(), context, clip);
2067     else if (graphicsLayer == layerForScrollCorner()) {
2068         const IntRect& scrollCorner = m_renderView->frameView()->scrollCornerRect();
2069         context.save();
2070         context.translate(-scrollCorner.x(), -scrollCorner.y());
2071         IntRect transformedClip = clip;
2072         transformedClip.moveBy(scrollCorner.location());
2073         m_renderView->frameView()->paintScrollCorner(&context, transformedClip);
2074         context.restore();
2075 #if PLATFORM(CHROMIUM) && ENABLE(RUBBER_BANDING)
2076     } else if (graphicsLayer == layerForOverhangAreas()) {
2077         ScrollView* view = m_renderView->frameView();
2078         view->calculateAndPaintOverhangAreas(&context, clip);
2079 #endif
2080     }
2081 }
2082
2083 static void resetTrackedRepaintRectsRecursive(GraphicsLayer* graphicsLayer)
2084 {
2085     if (!graphicsLayer)
2086         return;
2087
2088     graphicsLayer->resetTrackedRepaints();
2089
2090     for (size_t i = 0; i < graphicsLayer->children().size(); ++i)
2091         resetTrackedRepaintRectsRecursive(graphicsLayer->children()[i]);
2092
2093     if (GraphicsLayer* replicaLayer = graphicsLayer->replicaLayer())
2094         resetTrackedRepaintRectsRecursive(replicaLayer);
2095
2096     if (GraphicsLayer* maskLayer = graphicsLayer->maskLayer())
2097         resetTrackedRepaintRectsRecursive(maskLayer);
2098 }
2099
2100 void RenderLayerCompositor::resetTrackedRepaintRects()
2101 {
2102     if (GraphicsLayer* rootLayer = rootGraphicsLayer())
2103         resetTrackedRepaintRectsRecursive(rootLayer);
2104 }
2105
2106 void RenderLayerCompositor::setTracksRepaints(bool tracksRepaints)
2107 {
2108     m_isTrackingRepaints = tracksRepaints;
2109 }
2110
2111 bool RenderLayerCompositor::isTrackingRepaints() const
2112 {
2113     return m_isTrackingRepaints;
2114 }
2115
2116 float RenderLayerCompositor::deviceScaleFactor() const
2117 {
2118     Page* page = this->page();
2119     return page ? page->deviceScaleFactor() : 1;
2120 }
2121
2122 float RenderLayerCompositor::pageScaleFactor() const
2123 {
2124     Page* page = this->page();
2125     return page ? page->pageScaleFactor() : 1;
2126 }
2127
2128 void RenderLayerCompositor::didCommitChangesForLayer(const GraphicsLayer*) const
2129 {
2130     // Nothing to do here yet.
2131 }
2132
2133 bool RenderLayerCompositor::keepLayersPixelAligned() const
2134 {
2135     // When scaling, attempt to align compositing layers to pixel boundaries.
2136     return true;
2137 }
2138
2139 static bool shouldCompositeOverflowControls(FrameView* view)
2140 {
2141     if (view->platformWidget())
2142         return false;
2143
2144     if (Page* page = view->frame()->page()) {
2145         if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
2146             if (scrollingCoordinator->coordinatesScrollingForFrameView(view))
2147                 return true;
2148     }
2149
2150 #if !PLATFORM(CHROMIUM)
2151     if (!view->hasOverlayScrollbars())
2152         return false;
2153 #endif
2154     return true;
2155 }
2156
2157 bool RenderLayerCompositor::requiresHorizontalScrollbarLayer() const
2158 {
2159     FrameView* view = m_renderView->frameView();
2160     return shouldCompositeOverflowControls(view) && view->horizontalScrollbar();
2161 }
2162
2163 bool RenderLayerCompositor::requiresVerticalScrollbarLayer() const
2164 {
2165     FrameView* view = m_renderView->frameView();
2166     return shouldCompositeOverflowControls(view) && view->verticalScrollbar();
2167 }
2168
2169 bool RenderLayerCompositor::requiresScrollCornerLayer() const
2170 {
2171     FrameView* view = m_renderView->frameView();
2172     return shouldCompositeOverflowControls(view) && view->isScrollCornerVisible();
2173 }
2174
2175 #if ENABLE(RUBBER_BANDING)
2176 bool RenderLayerCompositor::requiresOverhangAreasLayer() const
2177 {
2178     // We don't want a layer if this is a subframe.
2179     if (m_renderView->document()->ownerElement())
2180         return false;
2181
2182     // We do want a layer if we have a scrolling coordinator.
2183     if (scrollingCoordinator())
2184         return true;
2185
2186     // Chromium always wants a layer.
2187 #if PLATFORM(CHROMIUM)
2188     return true;
2189 #endif
2190
2191     return false;
2192 }
2193
2194 bool RenderLayerCompositor::requiresContentShadowLayer() const
2195 {
2196     // We don't want a layer if this is a subframe.
2197     if (m_renderView->document()->ownerElement())
2198         return false;
2199
2200 #if PLATFORM(MAC)
2201     // On Mac, we want a content shadow layer if we have a scrolling coordinator.
2202     if (scrollingCoordinator())
2203         return true;
2204 #endif
2205
2206     return false;
2207 }
2208 #endif
2209
2210 void RenderLayerCompositor::updateOverflowControlsLayers()
2211 {
2212 #if ENABLE(RUBBER_BANDING)
2213     if (requiresOverhangAreasLayer()) {
2214         if (!m_layerForOverhangAreas) {
2215             m_layerForOverhangAreas = GraphicsLayer::create(graphicsLayerFactory(), this);
2216 #ifndef NDEBUG
2217             m_layerForOverhangAreas->setName("overhang areas");
2218 #endif
2219             m_layerForOverhangAreas->setDrawsContent(false);
2220             m_layerForOverhangAreas->setSize(m_renderView->frameView()->frameRect().size());
2221
2222             ScrollbarTheme::theme()->setUpOverhangAreasLayerContents(m_layerForOverhangAreas.get());
2223
2224             // We want the overhang areas layer to be positioned below the frame contents,
2225             // so insert it below the clip layer.
2226             m_overflowControlsHostLayer->addChildBelow(m_layerForOverhangAreas.get(), m_clipLayer.get());
2227         }
2228     } else if (m_layerForOverhangAreas) {
2229         m_layerForOverhangAreas->removeFromParent();
2230         m_layerForOverhangAreas = nullptr;
2231     }
2232
2233     if (requiresContentShadowLayer()) {
2234         if (!m_contentShadowLayer) {
2235             m_contentShadowLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
2236 #ifndef NDEBUG
2237             m_contentShadowLayer->setName("content shadow");
2238 #endif
2239             m_contentShadowLayer->setSize(m_rootContentLayer->size());
2240             m_contentShadowLayer->setPosition(m_rootContentLayer->position());
2241             ScrollbarTheme::theme()->setUpContentShadowLayer(m_contentShadowLayer.get());
2242
2243             m_scrollLayer->addChildBelow(m_contentShadowLayer.get(), m_rootContentLayer.get());
2244         }
2245     } else if (m_contentShadowLayer) {
2246         m_contentShadowLayer->removeFromParent();
2247         m_contentShadowLayer = nullptr;
2248     }
2249 #endif
2250
2251     if (requiresHorizontalScrollbarLayer()) {
2252         if (!m_layerForHorizontalScrollbar) {
2253             m_layerForHorizontalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), this);
2254             m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
2255 #ifndef NDEBUG
2256             m_layerForHorizontalScrollbar->setName("horizontal scrollbar");
2257 #endif
2258 #if PLATFORM(MAC) && USE(CA)
2259             m_layerForHorizontalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
2260 #endif
2261             m_overflowControlsHostLayer->addChild(m_layerForHorizontalScrollbar.get());
2262
2263             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2264                 scrollingCoordinator->frameViewHorizontalScrollbarLayerDidChange(m_renderView->frameView(), m_layerForHorizontalScrollbar.get());
2265         }
2266     } else if (m_layerForHorizontalScrollbar) {
2267         m_layerForHorizontalScrollbar->removeFromParent();
2268         m_layerForHorizontalScrollbar = nullptr;
2269
2270         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2271             scrollingCoordinator->frameViewHorizontalScrollbarLayerDidChange(m_renderView->frameView(), 0);
2272     }
2273
2274     if (requiresVerticalScrollbarLayer()) {
2275         if (!m_layerForVerticalScrollbar) {
2276             m_layerForVerticalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), this);
2277             m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
2278 #ifndef NDEBUG
2279             m_layerForVerticalScrollbar->setName("vertical scrollbar");
2280 #endif
2281 #if PLATFORM(MAC) && USE(CA)
2282         m_layerForVerticalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
2283 #endif
2284             m_overflowControlsHostLayer->addChild(m_layerForVerticalScrollbar.get());
2285
2286             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2287                 scrollingCoordinator->frameViewVerticalScrollbarLayerDidChange(m_renderView->frameView(), m_layerForVerticalScrollbar.get());
2288         }
2289     } else if (m_layerForVerticalScrollbar) {
2290         m_layerForVerticalScrollbar->removeFromParent();
2291         m_layerForVerticalScrollbar = nullptr;
2292
2293         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2294             scrollingCoordinator->frameViewVerticalScrollbarLayerDidChange(m_renderView->frameView(), 0);
2295     }
2296
2297     if (requiresScrollCornerLayer()) {
2298         if (!m_layerForScrollCorner) {
2299             m_layerForScrollCorner = GraphicsLayer::create(graphicsLayerFactory(), this);
2300             m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
2301 #ifndef NDEBUG
2302             m_layerForScrollCorner->setName("scroll corner");
2303 #endif
2304 #if PLATFORM(MAC) && USE(CA)
2305             m_layerForScrollCorner->setAcceleratesDrawing(acceleratedDrawingEnabled());
2306 #endif
2307             m_overflowControlsHostLayer->addChild(m_layerForScrollCorner.get());
2308         }
2309     } else if (m_layerForScrollCorner) {
2310         m_layerForScrollCorner->removeFromParent();
2311         m_layerForScrollCorner = nullptr;
2312     }
2313
2314     m_renderView->frameView()->positionScrollbarLayers();
2315 }
2316
2317 void RenderLayerCompositor::ensureRootLayer()
2318 {
2319     RootLayerAttachment expectedAttachment = shouldPropagateCompositingToEnclosingFrame() ? RootLayerAttachedViaEnclosingFrame : RootLayerAttachedViaChromeClient;
2320     if (expectedAttachment == m_rootLayerAttachment)
2321          return;
2322
2323     if (!m_rootContentLayer) {
2324         m_rootContentLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
2325 #ifndef NDEBUG
2326         m_rootContentLayer->setName("content root");
2327 #endif
2328         IntRect overflowRect = m_renderView->pixelSnappedLayoutOverflowRect();
2329         m_rootContentLayer->setSize(FloatSize(overflowRect.maxX(), overflowRect.maxY()));
2330         m_rootContentLayer->setPosition(FloatPoint());
2331
2332         // Need to clip to prevent transformed content showing outside this frame
2333         m_rootContentLayer->setMasksToBounds(true);
2334     }
2335
2336     if (requiresScrollLayer(expectedAttachment)) {
2337         if (!m_overflowControlsHostLayer) {
2338             ASSERT(!m_scrollLayer);
2339             ASSERT(!m_clipLayer);
2340
2341             // Create a layer to host the clipping layer and the overflow controls layers.
2342             m_overflowControlsHostLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
2343 #ifndef NDEBUG
2344             m_overflowControlsHostLayer->setName("overflow controls host");
2345 #endif
2346
2347             // Create a clipping layer if this is an iframe
2348             m_clipLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
2349 #ifndef NDEBUG
2350             m_clipLayer->setName("frame clipping");
2351 #endif
2352             m_clipLayer->setMasksToBounds(true);
2353             
2354             m_scrollLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
2355 #ifndef NDEBUG
2356             m_scrollLayer->setName("frame scrolling");
2357 #endif
2358             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2359                 scrollingCoordinator->setLayerIsContainerForFixedPositionLayers(m_scrollLayer.get(), true);
2360
2361             // Hook them up
2362             m_overflowControlsHostLayer->addChild(m_clipLayer.get());
2363             m_clipLayer->addChild(m_scrollLayer.get());
2364             m_scrollLayer->addChild(m_rootContentLayer.get());
2365
2366             frameViewDidChangeSize();
2367             frameViewDidScroll();
2368         }
2369     } else {
2370         if (m_overflowControlsHostLayer) {
2371             m_overflowControlsHostLayer = nullptr;
2372             m_clipLayer = nullptr;
2373             m_scrollLayer = nullptr;
2374         }
2375     }
2376
2377     // Check to see if we have to change the attachment
2378     if (m_rootLayerAttachment != RootLayerUnattached)
2379         detachRootLayer();
2380
2381     attachRootLayer(expectedAttachment);
2382 }
2383
2384 void RenderLayerCompositor::destroyRootLayer()
2385 {
2386     if (!m_rootContentLayer)
2387         return;
2388
2389     detachRootLayer();
2390
2391 #if ENABLE(RUBBER_BANDING)
2392     if (m_layerForOverhangAreas) {
2393         m_layerForOverhangAreas->removeFromParent();
2394         m_layerForOverhangAreas = nullptr;
2395     }
2396 #endif
2397
2398     if (m_layerForHorizontalScrollbar) {
2399         m_layerForHorizontalScrollbar->removeFromParent();
2400         m_layerForHorizontalScrollbar = nullptr;
2401         if (Scrollbar* horizontalScrollbar = m_renderView->frameView()->verticalScrollbar())
2402             m_renderView->frameView()->invalidateScrollbar(horizontalScrollbar, IntRect(IntPoint(0, 0), horizontalScrollbar->frameRect().size()));
2403     }
2404
2405     if (m_layerForVerticalScrollbar) {
2406         m_layerForVerticalScrollbar->removeFromParent();
2407         m_layerForVerticalScrollbar = nullptr;
2408         if (Scrollbar* verticalScrollbar = m_renderView->frameView()->verticalScrollbar())
2409             m_renderView->frameView()->invalidateScrollbar(verticalScrollbar, IntRect(IntPoint(0, 0), verticalScrollbar->frameRect().size()));
2410     }
2411
2412     if (m_layerForScrollCorner) {
2413         m_layerForScrollCorner = nullptr;
2414         m_renderView->frameView()->invalidateScrollCorner(m_renderView->frameView()->scrollCornerRect());
2415     }
2416
2417     if (m_overflowControlsHostLayer) {
2418         m_overflowControlsHostLayer = nullptr;
2419         m_clipLayer = nullptr;
2420         m_scrollLayer = nullptr;
2421     }
2422     ASSERT(!m_scrollLayer);
2423     m_rootContentLayer = nullptr;
2424
2425     m_layerUpdater = nullptr;
2426 }
2427
2428 void RenderLayerCompositor::attachRootLayer(RootLayerAttachment attachment)
2429 {
2430     if (!m_rootContentLayer)
2431         return;
2432
2433     switch (attachment) {
2434         case RootLayerUnattached:
2435             ASSERT_NOT_REACHED();
2436             break;
2437         case RootLayerAttachedViaChromeClient: {
2438             Frame* frame = m_renderView->frameView()->frame();
2439             Page* page = frame ? frame->page() : 0;
2440             if (!page)
2441                 return;
2442
2443             page->chrome()->client()->attachRootGraphicsLayer(frame, rootGraphicsLayer());
2444             break;
2445         }
2446         case RootLayerAttachedViaEnclosingFrame: {
2447             // The layer will get hooked up via RenderLayerBacking::updateGraphicsLayerConfiguration()
2448             // for the frame's renderer in the parent document.
2449             m_renderView->document()->ownerElement()->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
2450             break;
2451         }
2452     }
2453
2454     m_rootLayerAttachment = attachment;
2455     rootLayerAttachmentChanged();
2456     
2457     if (m_shouldFlushOnReattach) {
2458         flushPendingLayerChanges(true);
2459         m_shouldFlushOnReattach = false;
2460     }
2461 }
2462
2463 void RenderLayerCompositor::detachRootLayer()
2464 {
2465     if (!m_rootContentLayer || m_rootLayerAttachment == RootLayerUnattached)
2466         return;
2467
2468     switch (m_rootLayerAttachment) {
2469     case RootLayerAttachedViaEnclosingFrame: {
2470         // The layer will get unhooked up via RenderLayerBacking::updateGraphicsLayerConfiguration()
2471         // for the frame's renderer in the parent document.
2472         if (m_overflowControlsHostLayer)
2473             m_overflowControlsHostLayer->removeFromParent();
2474         else
2475             m_rootContentLayer->removeFromParent();
2476
2477         if (HTMLFrameOwnerElement* ownerElement = m_renderView->document()->ownerElement())
2478             ownerElement->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
2479         break;
2480     }
2481     case RootLayerAttachedViaChromeClient: {
2482         Frame* frame = m_renderView->frameView()->frame();
2483         Page* page = frame ? frame->page() : 0;
2484         if (!page)
2485             return;
2486
2487         page->chrome()->client()->attachRootGraphicsLayer(frame, 0);
2488     }
2489     break;
2490     case RootLayerUnattached:
2491         break;
2492     }
2493
2494     m_rootLayerAttachment = RootLayerUnattached;
2495     rootLayerAttachmentChanged();
2496 }
2497
2498 void RenderLayerCompositor::updateRootLayerAttachment()
2499 {
2500     ensureRootLayer();
2501 }
2502
2503 void RenderLayerCompositor::rootLayerAttachmentChanged()
2504 {
2505     // The attachment can affect whether the RenderView layer's paintsIntoWindow() behavior,
2506     // so call updateGraphicsLayerGeometry() to udpate that.
2507     RenderLayer* layer = m_renderView->layer();
2508     if (RenderLayerBacking* backing = layer ? layer->backing() : 0)
2509         backing->updateDrawsContent();
2510 }
2511
2512 // IFrames are special, because we hook compositing layers together across iframe boundaries
2513 // when both parent and iframe content are composited. So when this frame becomes composited, we have
2514 // to use a synthetic style change to get the iframes into RenderLayers in order to allow them to composite.
2515 void RenderLayerCompositor::notifyIFramesOfCompositingChange()
2516 {
2517     Frame* frame = m_renderView->frameView() ? m_renderView->frameView()->frame() : 0;
2518     if (!frame)
2519         return;
2520
2521     for (Frame* child = frame->tree()->firstChild(); child; child = child->tree()->traverseNext(frame)) {
2522         if (child->document() && child->document()->ownerElement())
2523             child->document()->ownerElement()->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
2524     }
2525     
2526     // Compositing also affects the answer to RenderIFrame::requiresAcceleratedCompositing(), so 
2527     // we need to schedule a style recalc in our parent document.
2528     if (HTMLFrameOwnerElement* ownerElement = m_renderView->document()->ownerElement())
2529         ownerElement->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
2530 }
2531
2532 bool RenderLayerCompositor::layerHas3DContent(const RenderLayer* layer) const
2533 {
2534     const RenderStyle* style = layer->renderer()->style();
2535
2536     if (style && 
2537         (style->transformStyle3D() == TransformStyle3DPreserve3D ||
2538          style->hasPerspective() ||
2539          style->transform().has3DOperation()))
2540         return true;
2541
2542     const_cast<RenderLayer*>(layer)->updateLayerListsIfNeeded();
2543
2544 #if !ASSERT_DISABLED
2545     LayerListMutationDetector mutationChecker(const_cast<RenderLayer*>(layer));
2546 #endif
2547
2548     if (layer->isStackingContext()) {
2549         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
2550             size_t listSize = negZOrderList->size();
2551             for (size_t i = 0; i < listSize; ++i) {
2552                 RenderLayer* curLayer = negZOrderList->at(i);
2553                 if (layerHas3DContent(curLayer))
2554                     return true;
2555             }
2556         }
2557
2558         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
2559             size_t listSize = posZOrderList->size();
2560             for (size_t i = 0; i < listSize; ++i) {
2561                 RenderLayer* curLayer = posZOrderList->at(i);
2562                 if (layerHas3DContent(curLayer))
2563                     return true;
2564             }
2565         }
2566     }
2567
2568     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
2569         size_t listSize = normalFlowList->size();
2570         for (size_t i = 0; i < listSize; ++i) {
2571             RenderLayer* curLayer = normalFlowList->at(i);
2572             if (layerHas3DContent(curLayer))
2573                 return true;
2574         }
2575     }
2576     return false;
2577 }
2578
2579 void RenderLayerCompositor::deviceOrPageScaleFactorChanged()
2580 {
2581     // Start at the RenderView's layer, since that's where the scale is applied.
2582     RenderLayer* viewLayer = m_renderView->layer();
2583     if (!viewLayer->isComposited())
2584         return;
2585
2586     if (GraphicsLayer* rootLayer = viewLayer->backing()->graphicsLayer())
2587         rootLayer->noteDeviceOrPageScaleFactorChangedIncludingDescendants();
2588 }
2589
2590 static bool isRootmostFixedOrStickyLayer(RenderLayer* layer)
2591 {
2592     if (layer->renderer()->isStickyPositioned())
2593         return true;
2594
2595     if (layer->renderer()->style()->position() != FixedPosition)
2596         return false;
2597
2598     for (RenderLayer* stackingContext = layer->stackingContext(); stackingContext; stackingContext = stackingContext->stackingContext()) {
2599         if (stackingContext->isComposited() && stackingContext->renderer()->style()->position() == FixedPosition)
2600             return false;
2601     }
2602
2603     return true;
2604 }
2605
2606 void RenderLayerCompositor::updateViewportConstraintStatus(RenderLayer* layer)
2607 {
2608     if (isRootmostFixedOrStickyLayer(layer))
2609         addViewportConstrainedLayer(layer);
2610     else
2611         removeViewportConstrainedLayer(layer);
2612 }
2613
2614 void RenderLayerCompositor::addViewportConstrainedLayer(RenderLayer* layer)
2615 {
2616     m_viewportConstrainedLayers.add(layer);
2617     registerOrUpdateViewportConstrainedLayer(layer);
2618 }
2619
2620 void RenderLayerCompositor::removeViewportConstrainedLayer(RenderLayer* layer)
2621 {
2622     if (!m_viewportConstrainedLayers.contains(layer))
2623         return;
2624
2625     unregisterViewportConstrainedLayer(layer);
2626     m_viewportConstrainedLayers.remove(layer);
2627 }
2628
2629 const FixedPositionViewportConstraints RenderLayerCompositor::computeFixedViewportConstraints(RenderLayer* layer)
2630 {
2631     ASSERT(layer->isComposited());
2632
2633     FrameView* frameView = m_renderView->frameView();
2634
2635     LayoutRect viewportRect = frameView->visibleContentRect();
2636     viewportRect.setLocation(toPoint(frameView->scrollOffsetForFixedPosition()));
2637
2638     FixedPositionViewportConstraints constraints = FixedPositionViewportConstraints();
2639
2640     GraphicsLayer* graphicsLayer = layer->backing()->graphicsLayer();
2641
2642     constraints.setLayerPositionAtLastLayout(graphicsLayer->position());
2643     constraints.setViewportRectAtLastLayout(viewportRect);
2644         
2645     RenderStyle* style = layer->renderer()->style();
2646     if (!style->left().isAuto())
2647         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeLeft);
2648
2649     if (!style->right().isAuto())
2650         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeRight);
2651
2652     if (!style->top().isAuto())
2653         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeTop);
2654
2655     if (!style->bottom().isAuto())
2656         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeBottom);
2657
2658     // If left and right are auto, use left.
2659     if (style->left().isAuto() && style->right().isAuto())
2660         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeLeft);
2661
2662     // If top and bottom are auto, use top.
2663     if (style->top().isAuto() && style->bottom().isAuto())
2664         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeTop);
2665         
2666     return constraints;
2667 }
2668
2669 const StickyPositionViewportConstraints RenderLayerCompositor::computeStickyViewportConstraints(RenderLayer* layer)
2670 {
2671     ASSERT(layer->isComposited());
2672
2673     FrameView* frameView = m_renderView->frameView();
2674     LayoutRect viewportRect = frameView->visibleContentRect();
2675
2676     StickyPositionViewportConstraints constraints = StickyPositionViewportConstraints();
2677
2678     RenderBoxModelObject* renderer = toRenderBoxModelObject(layer->renderer());
2679
2680     renderer->computeStickyPositionConstraints(constraints, viewportRect);
2681
2682     GraphicsLayer* graphicsLayer = layer->backing()->graphicsLayer();
2683
2684     constraints.setLayerPositionAtLastLayout(graphicsLayer->position());
2685     constraints.setStickyOffsetAtLastLayout(renderer->stickyPositionOffset());
2686
2687     return constraints;
2688 }
2689
2690 static RenderLayerBacking* nearestScrollingCoordinatorAncestor(RenderLayer* layer)
2691 {
2692     RenderLayer* ancestor = layer->parent();
2693     while (ancestor) {
2694         if (RenderLayerBacking* backing = ancestor->backing()) {
2695             if (backing->scrollLayerID() && !ancestor->scrollsOverflow())
2696                 return backing;
2697         }
2698         ancestor = ancestor->parent();
2699     }
2700
2701     return 0;
2702 }
2703
2704 void RenderLayerCompositor::registerOrUpdateViewportConstrainedLayer(RenderLayer* layer)
2705 {
2706     // FIXME: We should support sticky position here! And we should eventuall support fixed/sticky elements
2707     // that are inside non-main frames once we get non-main frames scrolling with the ScrollingCoordinator.
2708     if (layer->renderer()->isStickyPositioned() || m_renderView->document()->ownerElement())
2709         return;
2710
2711     ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator();
2712     if (!scrollingCoordinator)
2713         return;
2714
2715     if (!scrollingCoordinator->supportsFixedPositionLayers() || !layer->parent())
2716         return;
2717
2718     ASSERT(layer->renderer()->style()->position() == FixedPosition);
2719     ASSERT(m_viewportConstrainedLayers.contains(layer));
2720     ASSERT(layer->isComposited());
2721
2722     RenderLayerBacking* backing = layer->backing();
2723     if (!backing)
2724         return;
2725
2726     ScrollingNodeID nodeID = backing->scrollLayerID();
2727     if (!nodeID) {
2728         RenderLayerBacking* parent = nearestScrollingCoordinatorAncestor(layer);
2729         if (!parent)
2730             return;
2731         backing->attachToScrollingCoordinator(parent);
2732         nodeID = backing->scrollLayerID();
2733     }
2734
2735     if (layer->renderer()->isStickyPositioned())
2736         scrollingCoordinator->updateViewportConstrainedNode(nodeID, computeStickyViewportConstraints(layer), backing->graphicsLayer());
2737     else
2738         scrollingCoordinator->updateViewportConstrainedNode(nodeID, computeFixedViewportConstraints(layer), backing->graphicsLayer());
2739 }
2740
2741 void RenderLayerCompositor::unregisterViewportConstrainedLayer(RenderLayer* layer)
2742 {
2743     ASSERT(m_viewportConstrainedLayers.contains(layer));
2744
2745     if (RenderLayerBacking* backing = layer->backing())
2746         backing->detachFromScrollingCoordinator();
2747 }
2748
2749 void RenderLayerCompositor::windowScreenDidChange(PlatformDisplayID displayID)
2750 {
2751     if (m_layerUpdater)
2752         m_layerUpdater->screenDidChange(displayID);
2753 }
2754
2755 ScrollingCoordinator* RenderLayerCompositor::scrollingCoordinator() const
2756 {
2757     if (Page* page = this->page())
2758         return page->scrollingCoordinator();
2759
2760     return 0;
2761 }
2762
2763 GraphicsLayerFactory* RenderLayerCompositor::graphicsLayerFactory() const
2764 {
2765     if (Page* page = this->page())
2766         return page->chrome()->client()->graphicsLayerFactory();
2767
2768     return 0;
2769 }
2770
2771 Page* RenderLayerCompositor::page() const
2772 {
2773     if (Frame* frame = m_renderView->frameView()->frame())
2774         return frame->page();
2775     
2776     return 0;
2777 }
2778
2779 void RenderLayerCompositor::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
2780 {
2781     MemoryClassInfo info(memoryObjectInfo, this, PlatformMemoryTypes::Rendering);
2782     info.addWeakPointer(m_renderView);
2783     info.addMember(m_rootContentLayer);
2784     info.addMember(m_updateCompositingLayersTimer);
2785     info.addMember(m_clipLayer);
2786     info.addMember(m_scrollLayer);
2787     info.addMember(m_viewportConstrainedLayers);
2788     info.addMember(m_viewportConstrainedLayersNeedingUpdate);
2789     info.addMember(m_overflowControlsHostLayer);
2790     info.addMember(m_layerForHorizontalScrollbar);
2791     info.addMember(m_layerForVerticalScrollbar);
2792     info.addMember(m_layerForScrollCorner);
2793 #if ENABLE(RUBBER_BANDING)
2794     info.addMember(m_layerForOverhangAreas);
2795     info.addMember(m_contentShadowLayer);
2796 #endif
2797     info.addMember(m_layerUpdater);
2798 }
2799
2800 } // namespace WebCore
2801
2802 #endif // USE(ACCELERATED_COMPOSITING)