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