Need to notify ScrollingCoordinator when frame scrollbars are destroyed
[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         logReasonsForCompositing(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     if (Settings* settings = m_renderView->document()->settings())
786         if (!settings->applyPageScaleFactorInCompositor())
787             clipRect.scale(pageScaleFactor());
788     clipRect.intersect(layerBounds);
789     overlapMap.add(layer, clipRect);
790 }
791
792 void RenderLayerCompositor::addToOverlapMapRecursive(OverlapMap& overlapMap, RenderLayer* layer, RenderLayer* ancestorLayer)
793 {
794     if (!canBeComposited(layer) || overlapMap.contains(layer))
795         return;
796
797     // A null ancestorLayer is an indication that 'layer' has already been pushed.
798     if (ancestorLayer)
799         overlapMap.geometryMap().pushMappingsToAncestor(layer, ancestorLayer);
800     
801     IntRect bounds;
802     bool haveComputedBounds = false;
803     addToOverlapMap(overlapMap, layer, bounds, haveComputedBounds);
804
805 #if !ASSERT_DISABLED
806     LayerListMutationDetector mutationChecker(layer);
807 #endif
808
809     if (layer->isStackingContainer()) {
810         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
811             size_t listSize = negZOrderList->size();
812             for (size_t i = 0; i < listSize; ++i) {
813                 RenderLayer* curLayer = negZOrderList->at(i);
814                 addToOverlapMapRecursive(overlapMap, curLayer, layer);
815             }
816         }
817     }
818
819     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
820         size_t listSize = normalFlowList->size();
821         for (size_t i = 0; i < listSize; ++i) {
822             RenderLayer* curLayer = normalFlowList->at(i);
823             addToOverlapMapRecursive(overlapMap, curLayer, layer);
824         }
825     }
826
827     if (layer->isStackingContainer()) {
828         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
829             size_t listSize = posZOrderList->size();
830             for (size_t i = 0; i < listSize; ++i) {
831                 RenderLayer* curLayer = posZOrderList->at(i);
832                 addToOverlapMapRecursive(overlapMap, curLayer, layer);
833             }
834         }
835     }
836     
837     if (ancestorLayer)
838         overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
839 }
840
841 //  Recurse through the layers in z-index and overflow order (which is equivalent to painting order)
842 //  For the z-order children of a compositing layer:
843 //      If a child layers has a compositing layer, then all subsequent layers must
844 //      be compositing in order to render above that layer.
845 //
846 //      If a child in the negative z-order list is compositing, then the layer itself
847 //      must be compositing so that its contents render over that child.
848 //      This implies that its positive z-index children must also be compositing.
849 //
850 void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer* layer, OverlapMap* overlapMap, CompositingState& compositingState, bool& layersChanged, bool& descendantHas3DTransform)
851 {
852     layer->updateLayerListsIfNeeded();
853     
854     if (overlapMap)
855         overlapMap->geometryMap().pushMappingsToAncestor(layer, ancestorLayer);
856     
857     // Clear the flag
858     layer->setHasCompositingDescendant(false);
859     
860     RenderLayer::IndirectCompositingReason compositingReason = compositingState.m_subtreeIsCompositing ? RenderLayer::IndirectCompositingForStacking : RenderLayer::NoIndirectCompositingReason;
861
862     bool haveComputedBounds = false;
863     IntRect absBounds;
864     if (overlapMap && !overlapMap->isEmpty() && compositingState.m_testingOverlap) {
865         // If we're testing for overlap, we only need to composite if we overlap something that is already composited.
866         absBounds = enclosingIntRect(overlapMap->geometryMap().absoluteRect(layer->overlapBounds()));
867
868         // Empty rects never intersect, but we need them to for the purposes of overlap testing.
869         if (absBounds.isEmpty())
870             absBounds.setSize(IntSize(1, 1));
871         haveComputedBounds = true;
872         compositingReason = overlapMap->overlapsLayers(absBounds) ? RenderLayer::IndirectCompositingForOverlap : RenderLayer::NoIndirectCompositingReason;
873     }
874
875 #if ENABLE(VIDEO)
876     // Video is special. It's the only RenderLayer type that can both have
877     // RenderLayer children and whose children can't use its backing to render
878     // into. These children (the controls) always need to be promoted into their
879     // own layers to draw on top of the accelerated video.
880     if (compositingState.m_compositingAncestor && compositingState.m_compositingAncestor->renderer()->isVideo())
881         compositingReason = RenderLayer::IndirectCompositingForOverlap;
882 #endif
883
884     layer->setIndirectCompositingReason(compositingReason);
885
886     // The children of this layer don't need to composite, unless there is
887     // a compositing layer among them, so start by inheriting the compositing
888     // ancestor with m_subtreeIsCompositing set to false.
889     CompositingState childState(compositingState);
890     childState.m_subtreeIsCompositing = false;
891
892     bool willBeComposited = needsToBeComposited(layer);
893     if (willBeComposited) {
894         // Tell the parent it has compositing descendants.
895         compositingState.m_subtreeIsCompositing = true;
896         // This layer now acts as the ancestor for kids.
897         childState.m_compositingAncestor = layer;
898
899         if (overlapMap)
900             overlapMap->pushCompositingContainer();
901         // This layer is going to be composited, so children can safely ignore the fact that there's an 
902         // animation running behind this layer, meaning they can rely on the overlap map testing again.
903         childState.m_testingOverlap = true;
904     }
905
906 #if !ASSERT_DISABLED
907     LayerListMutationDetector mutationChecker(layer);
908 #endif
909
910     bool anyDescendantHas3DTransform = false;
911
912     if (layer->isStackingContainer()) {
913         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
914             size_t listSize = negZOrderList->size();
915             for (size_t i = 0; i < listSize; ++i) {
916                 RenderLayer* curLayer = negZOrderList->at(i);
917                 computeCompositingRequirements(layer, curLayer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
918
919                 // If we have to make a layer for this child, make one now so we can have a contents layer
920                 // (since we need to ensure that the -ve z-order child renders underneath our contents).
921                 if (!willBeComposited && childState.m_subtreeIsCompositing) {
922                     // make layer compositing
923                     layer->setIndirectCompositingReason(RenderLayer::IndirectCompositingForBackgroundLayer);
924                     childState.m_compositingAncestor = layer;
925                     if (overlapMap)
926                         overlapMap->pushCompositingContainer();
927                     // This layer is going to be composited, so children can safely ignore the fact that there's an 
928                     // animation running behind this layer, meaning they can rely on the overlap map testing again
929                     childState.m_testingOverlap = true;
930                     willBeComposited = true;
931                 }
932             }
933         }
934     }
935     
936     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
937         size_t listSize = normalFlowList->size();
938         for (size_t i = 0; i < listSize; ++i) {
939             RenderLayer* curLayer = normalFlowList->at(i);
940             computeCompositingRequirements(layer, curLayer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
941         }
942     }
943
944     if (layer->isStackingContainer()) {
945         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
946             size_t listSize = posZOrderList->size();
947             for (size_t i = 0; i < listSize; ++i) {
948                 RenderLayer* curLayer = posZOrderList->at(i);
949                 computeCompositingRequirements(layer, curLayer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
950             }
951         }
952     }
953     
954     // If we just entered compositing mode, the root will have become composited (as long as accelerated compositing is enabled).
955     if (layer->isRootLayer()) {
956         if (inCompositingMode() && m_hasAcceleratedCompositing)
957             willBeComposited = true;
958     }
959     
960     ASSERT(willBeComposited == needsToBeComposited(layer));
961
962     // All layers (even ones that aren't being composited) need to get added to
963     // the overlap map. Layers that do not composite will draw into their
964     // compositing ancestor's backing, and so are still considered for overlap.
965     if (overlapMap && childState.m_compositingAncestor && !childState.m_compositingAncestor->isRootLayer())
966         addToOverlapMap(*overlapMap, layer, absBounds, haveComputedBounds);
967
968     // Now check for reasons to become composited that depend on the state of descendant layers.
969     RenderLayer::IndirectCompositingReason indirectCompositingReason;
970     if (!willBeComposited && canBeComposited(layer)
971         && requiresCompositingForIndirectReason(layer->renderer(), childState.m_subtreeIsCompositing, anyDescendantHas3DTransform, indirectCompositingReason)) {
972         layer->setIndirectCompositingReason(indirectCompositingReason);
973         childState.m_compositingAncestor = layer;
974         if (overlapMap) {
975             overlapMap->pushCompositingContainer();
976             addToOverlapMapRecursive(*overlapMap, layer);
977         }
978         willBeComposited = true;
979     }
980     
981     ASSERT(willBeComposited == needsToBeComposited(layer));
982     if (layer->reflectionLayer()) {
983         // FIXME: Shouldn't we call computeCompositingRequirements to handle a reflection overlapping with another renderer?
984         layer->reflectionLayer()->setIndirectCompositingReason(willBeComposited ? RenderLayer::IndirectCompositingForStacking : RenderLayer::NoIndirectCompositingReason);
985     }
986
987     // Subsequent layers in the parent stacking context also need to composite.
988     if (childState.m_subtreeIsCompositing)
989         compositingState.m_subtreeIsCompositing = true;
990
991     // Set the flag to say that this SC has compositing children.
992     layer->setHasCompositingDescendant(childState.m_subtreeIsCompositing);
993
994     // setHasCompositingDescendant() may have changed the answer to needsToBeComposited() when clipping,
995     // so test that again.
996     bool isCompositedClippingLayer = canBeComposited(layer) && clipsCompositingDescendants(layer);
997
998     // Turn overlap testing off for later layers if it's already off, or if we have an animating transform.
999     // Note that if the layer clips its descendants, there's no reason to propagate the child animation to the parent layers. That's because
1000     // we know for sure the animation is contained inside the clipping rectangle, which is already added to the overlap map.
1001     if ((!childState.m_testingOverlap && !isCompositedClippingLayer) || isRunningAcceleratedTransformAnimation(layer->renderer()))
1002         compositingState.m_testingOverlap = false;
1003     
1004     if (isCompositedClippingLayer) {
1005         if (!willBeComposited) {
1006             childState.m_compositingAncestor = layer;
1007             if (overlapMap) {
1008                 overlapMap->pushCompositingContainer();
1009                 addToOverlapMapRecursive(*overlapMap, layer);
1010             }
1011             willBeComposited = true;
1012          }
1013     }
1014
1015     if (overlapMap && childState.m_compositingAncestor == layer && !layer->isRootLayer())
1016         overlapMap->popCompositingContainer();
1017
1018     // If we're back at the root, and no other layers need to be composited, and the root layer itself doesn't need
1019     // to be composited, then we can drop out of compositing mode altogether. However, don't drop out of compositing mode
1020     // if there are composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
1021     if (layer->isRootLayer() && !childState.m_subtreeIsCompositing && !requiresCompositingLayer(layer) && !m_forceCompositingMode && !hasAnyAdditionalCompositedLayers(layer)) {
1022         enableCompositingMode(false);
1023         willBeComposited = false;
1024     }
1025     
1026     // If the layer is going into compositing mode, repaint its old location.
1027     ASSERT(willBeComposited == needsToBeComposited(layer));
1028     if (!layer->isComposited() && willBeComposited)
1029         repaintOnCompositingChange(layer);
1030
1031     // Update backing now, so that we can use isComposited() reliably during tree traversal in rebuildCompositingLayerTree().
1032     if (updateBacking(layer, CompositingChangeRepaintNow))
1033         layersChanged = true;
1034
1035     if (layer->reflectionLayer() && updateLayerCompositingState(layer->reflectionLayer(), CompositingChangeRepaintNow))
1036         layersChanged = true;
1037
1038     descendantHas3DTransform |= anyDescendantHas3DTransform || layer->has3DTransform();
1039
1040     if (overlapMap)
1041         overlapMap->geometryMap().popMappingsToAncestor(ancestorLayer);
1042 }
1043
1044 void RenderLayerCompositor::setCompositingParent(RenderLayer* childLayer, RenderLayer* parentLayer)
1045 {
1046     ASSERT(!parentLayer || childLayer->ancestorCompositingLayer() == parentLayer);
1047     ASSERT(childLayer->isComposited());
1048
1049     // It's possible to be called with a parent that isn't yet composited when we're doing
1050     // partial updates as required by painting or hit testing. Just bail in that case;
1051     // we'll do a full layer update soon.
1052     if (!parentLayer || !parentLayer->isComposited())
1053         return;
1054
1055     if (parentLayer) {
1056         GraphicsLayer* hostingLayer = parentLayer->backing()->parentForSublayers();
1057         GraphicsLayer* hostedLayer = childLayer->backing()->childForSuperlayers();
1058         
1059         hostingLayer->addChild(hostedLayer);
1060     } else
1061         childLayer->backing()->childForSuperlayers()->removeFromParent();
1062 }
1063
1064 void RenderLayerCompositor::removeCompositedChildren(RenderLayer* layer)
1065 {
1066     ASSERT(layer->isComposited());
1067
1068     GraphicsLayer* hostingLayer = layer->backing()->parentForSublayers();
1069     hostingLayer->removeAllChildren();
1070 }
1071
1072 #if ENABLE(VIDEO)
1073 bool RenderLayerCompositor::canAccelerateVideoRendering(RenderVideo* o) const
1074 {
1075     if (!m_hasAcceleratedCompositing)
1076         return false;
1077
1078     return o->supportsAcceleratedRendering();
1079 }
1080 #endif
1081
1082 void RenderLayerCompositor::rebuildCompositingLayerTree(RenderLayer* layer, Vector<GraphicsLayer*>& childLayersOfEnclosingLayer, int depth)
1083 {
1084     // Make the layer compositing if necessary, and set up clipping and content layers.
1085     // Note that we can only do work here that is independent of whether the descendant layers
1086     // have been processed. computeCompositingRequirements() will already have done the repaint if necessary.
1087     
1088     RenderLayerBacking* layerBacking = layer->backing();
1089     if (layerBacking) {
1090         // The compositing state of all our children has been updated already, so now
1091         // we can compute and cache the composited bounds for this layer.
1092         layerBacking->updateCompositedBounds();
1093
1094         if (RenderLayer* reflection = layer->reflectionLayer()) {
1095             if (reflection->backing())
1096                 reflection->backing()->updateCompositedBounds();
1097         }
1098
1099         if (layerBacking->updateGraphicsLayerConfiguration())
1100             layerBacking->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
1101         
1102         layerBacking->updateGraphicsLayerGeometry();
1103
1104         if (!layer->parent())
1105             updateRootLayerPosition();
1106
1107 #if !LOG_DISABLED
1108         logLayerInfo(layer, depth);
1109 #else
1110         UNUSED_PARAM(depth);
1111 #endif
1112         if (layerBacking->hasUnpositionedOverflowControlsLayers())
1113             layer->positionNewlyCreatedOverflowControls();
1114     }
1115
1116     // If this layer has backing, then we are collecting its children, otherwise appending
1117     // to the compositing child list of an enclosing layer.
1118     Vector<GraphicsLayer*> layerChildren;
1119     Vector<GraphicsLayer*>& childList = layerBacking ? layerChildren : childLayersOfEnclosingLayer;
1120
1121 #if !ASSERT_DISABLED
1122     LayerListMutationDetector mutationChecker(layer);
1123 #endif
1124
1125     if (layer->isStackingContainer()) {
1126         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
1127             size_t listSize = negZOrderList->size();
1128             for (size_t i = 0; i < listSize; ++i) {
1129                 RenderLayer* curLayer = negZOrderList->at(i);
1130                 rebuildCompositingLayerTree(curLayer, childList, depth + 1);
1131             }
1132         }
1133
1134         // If a negative z-order child is compositing, we get a foreground layer which needs to get parented.
1135         if (layerBacking && layerBacking->foregroundLayer())
1136             childList.append(layerBacking->foregroundLayer());
1137     }
1138
1139     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
1140         size_t listSize = normalFlowList->size();
1141         for (size_t i = 0; i < listSize; ++i) {
1142             RenderLayer* curLayer = normalFlowList->at(i);
1143             rebuildCompositingLayerTree(curLayer, childList, depth + 1);
1144         }
1145     }
1146     
1147     if (layer->isStackingContainer()) {
1148         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
1149             size_t listSize = posZOrderList->size();
1150             for (size_t i = 0; i < listSize; ++i) {
1151                 RenderLayer* curLayer = posZOrderList->at(i);
1152                 rebuildCompositingLayerTree(curLayer, childList, depth + 1);
1153             }
1154         }
1155     }
1156     
1157     if (layerBacking) {
1158         bool parented = false;
1159         if (layer->renderer()->isRenderPart())
1160             parented = parentFrameContentLayers(toRenderPart(layer->renderer()));
1161
1162         if (!parented)
1163             layerBacking->parentForSublayers()->setChildren(layerChildren);
1164
1165         // If the layer has a clipping layer the overflow controls layers will be siblings of the clipping layer.
1166         // Otherwise, the overflow control layers are normal children.
1167         if (!layerBacking->hasClippingLayer() && !layerBacking->hasScrollingLayer()) {
1168             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForHorizontalScrollbar()) {
1169                 overflowControlLayer->removeFromParent();
1170                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
1171             }
1172
1173             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForVerticalScrollbar()) {
1174                 overflowControlLayer->removeFromParent();
1175                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
1176             }
1177
1178             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForScrollCorner()) {
1179                 overflowControlLayer->removeFromParent();
1180                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
1181             }
1182         }
1183
1184         childLayersOfEnclosingLayer.append(layerBacking->childForSuperlayers());
1185     }
1186 }
1187
1188 void RenderLayerCompositor::frameViewDidChangeLocation(const IntPoint& contentsOffset)
1189 {
1190     if (m_overflowControlsHostLayer)
1191         m_overflowControlsHostLayer->setPosition(contentsOffset);
1192 }
1193
1194 void RenderLayerCompositor::frameViewDidChangeSize()
1195 {
1196     if (m_clipLayer) {
1197         FrameView* frameView = m_renderView->frameView();
1198         m_clipLayer->setSize(frameView->unscaledVisibleContentSize());
1199
1200         frameViewDidScroll();
1201         updateOverflowControlsLayers();
1202
1203 #if ENABLE(RUBBER_BANDING)
1204         if (m_layerForOverhangAreas)
1205             m_layerForOverhangAreas->setSize(frameView->frameRect().size());
1206 #endif
1207     }
1208 }
1209
1210 void RenderLayerCompositor::frameViewDidScroll()
1211 {
1212     FrameView* frameView = m_renderView->frameView();
1213     IntPoint scrollPosition = frameView->scrollPosition();
1214
1215     if (!m_scrollLayer)
1216         return;
1217
1218     // If there's a scrolling coordinator that manages scrolling for this frame view,
1219     // it will also manage updating the scroll layer position.
1220     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator()) {
1221         if (scrollingCoordinator->coordinatesScrollingForFrameView(frameView))
1222             return;
1223         if (Settings* settings = m_renderView->document()->settings()) {
1224             if (settings->compositedScrollingForFramesEnabled())
1225                 scrollingCoordinator->scrollableAreaScrollLayerDidChange(frameView);
1226         }
1227     }
1228
1229     m_scrollLayer->setPosition(FloatPoint(-scrollPosition.x(), -scrollPosition.y()));
1230
1231     if (GraphicsLayer* fixedBackgroundLayer = fixedRootBackgroundLayer())
1232         fixedBackgroundLayer->setPosition(IntPoint(frameView->scrollOffsetForFixedPosition()));
1233 }
1234
1235 void RenderLayerCompositor::frameViewDidLayout()
1236 {
1237     RenderLayerBacking* renderViewBacking = m_renderView->layer()->backing();
1238     if (renderViewBacking)
1239         renderViewBacking->adjustTiledBackingCoverage();
1240 }
1241
1242 void RenderLayerCompositor::rootFixedBackgroundsChanged()
1243 {
1244     RenderLayerBacking* renderViewBacking = m_renderView->layer()->backing();
1245     if (renderViewBacking && renderViewBacking->usingTiledBacking())
1246         setCompositingLayersNeedRebuild();
1247 }
1248
1249 void RenderLayerCompositor::scrollingLayerDidChange(RenderLayer* layer)
1250 {
1251     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
1252         scrollingCoordinator->scrollableAreaScrollLayerDidChange(layer);
1253 }
1254
1255 void RenderLayerCompositor::fixedRootBackgroundLayerChanged()
1256 {
1257     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator()) {
1258         RenderLayerBacking* renderViewBacking = m_renderView->layer()->backing();
1259         if (!renderViewBacking)
1260             return;
1261
1262         scrollingCoordinator->updateScrollingNode(renderViewBacking->scrollLayerID(), scrollLayer(), fixedRootBackgroundLayer());
1263     }
1264 }
1265
1266 String RenderLayerCompositor::layerTreeAsText(LayerTreeFlags flags)
1267 {
1268     updateCompositingLayers(CompositingUpdateAfterLayout);
1269
1270     if (!m_rootContentLayer)
1271         return String();
1272
1273     flushPendingLayerChanges(true);
1274
1275     LayerTreeAsTextBehavior layerTreeBehavior = LayerTreeAsTextBehaviorNormal;
1276     if (flags & LayerTreeFlagsIncludeDebugInfo)
1277         layerTreeBehavior |= LayerTreeAsTextDebug;
1278     if (flags & LayerTreeFlagsIncludeVisibleRects)
1279         layerTreeBehavior |= LayerTreeAsTextIncludeVisibleRects;
1280     if (flags & LayerTreeFlagsIncludeTileCaches)
1281         layerTreeBehavior |= LayerTreeAsTextIncludeTileCaches;
1282     if (flags & LayerTreeFlagsIncludeRepaintRects)
1283         layerTreeBehavior |= LayerTreeAsTextIncludeRepaintRects;
1284     if (flags & LayerTreeFlagsIncludePaintingPhases)
1285         layerTreeBehavior |= LayerTreeAsTextIncludePaintingPhases;
1286
1287     // We skip dumping the scroll and clip layers to keep layerTreeAsText output
1288     // similar between platforms.
1289     String layerTreeText = m_rootContentLayer->layerTreeAsText(layerTreeBehavior);
1290
1291     // The true root layer is not included in the dump, so if we want to report
1292     // its repaint rects, they must be included here.
1293     if (flags & LayerTreeFlagsIncludeRepaintRects) {
1294         String layerTreeTextWithRootRepaintRects = m_renderView->frameView()->trackedRepaintRectsAsText();
1295         layerTreeTextWithRootRepaintRects.append(layerTreeText);
1296         return layerTreeTextWithRootRepaintRects;
1297     }
1298
1299     return layerTreeText;
1300 }
1301
1302 RenderLayerCompositor* RenderLayerCompositor::frameContentsCompositor(RenderPart* renderer)
1303 {
1304     if (!renderer->node()->isFrameOwnerElement())
1305         return 0;
1306         
1307     HTMLFrameOwnerElement* element = toFrameOwnerElement(renderer->node());
1308     if (Document* contentDocument = element->contentDocument()) {
1309         if (RenderView* view = contentDocument->renderView())
1310             return view->compositor();
1311     }
1312     return 0;
1313 }
1314
1315 bool RenderLayerCompositor::parentFrameContentLayers(RenderPart* renderer)
1316 {
1317     RenderLayerCompositor* innerCompositor = frameContentsCompositor(renderer);
1318     if (!innerCompositor || !innerCompositor->inCompositingMode() || innerCompositor->rootLayerAttachment() != RootLayerAttachedViaEnclosingFrame)
1319         return false;
1320     
1321     RenderLayer* layer = renderer->layer();
1322     if (!layer->isComposited())
1323         return false;
1324
1325     RenderLayerBacking* backing = layer->backing();
1326     GraphicsLayer* hostingLayer = backing->parentForSublayers();
1327     GraphicsLayer* rootLayer = innerCompositor->rootGraphicsLayer();
1328     if (hostingLayer->children().size() != 1 || hostingLayer->children()[0] != rootLayer) {
1329         hostingLayer->removeAllChildren();
1330         hostingLayer->addChild(rootLayer);
1331     }
1332     return true;
1333 }
1334
1335 // This just updates layer geometry without changing the hierarchy.
1336 void RenderLayerCompositor::updateLayerTreeGeometry(RenderLayer* layer, int depth)
1337 {
1338     if (RenderLayerBacking* layerBacking = layer->backing()) {
1339         // The compositing state of all our children has been updated already, so now
1340         // we can compute and cache the composited bounds for this layer.
1341         layerBacking->updateCompositedBounds();
1342
1343         if (RenderLayer* reflection = layer->reflectionLayer()) {
1344             if (reflection->backing())
1345                 reflection->backing()->updateCompositedBounds();
1346         }
1347
1348         layerBacking->updateGraphicsLayerConfiguration();
1349         layerBacking->updateGraphicsLayerGeometry();
1350
1351         if (!layer->parent())
1352             updateRootLayerPosition();
1353
1354 #if !LOG_DISABLED
1355         logLayerInfo(layer, depth);
1356 #else
1357         UNUSED_PARAM(depth);
1358 #endif
1359     }
1360
1361 #if !ASSERT_DISABLED
1362     LayerListMutationDetector mutationChecker(layer);
1363 #endif
1364
1365     if (layer->isStackingContainer()) {
1366         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
1367             size_t listSize = negZOrderList->size();
1368             for (size_t i = 0; i < listSize; ++i)
1369                 updateLayerTreeGeometry(negZOrderList->at(i), depth + 1);
1370         }
1371     }
1372
1373     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
1374         size_t listSize = normalFlowList->size();
1375         for (size_t i = 0; i < listSize; ++i)
1376             updateLayerTreeGeometry(normalFlowList->at(i), depth + 1);
1377     }
1378     
1379     if (layer->isStackingContainer()) {
1380         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
1381             size_t listSize = posZOrderList->size();
1382             for (size_t i = 0; i < listSize; ++i)
1383                 updateLayerTreeGeometry(posZOrderList->at(i), depth + 1);
1384         }
1385     }
1386 }
1387
1388 // Recurs down the RenderLayer tree until its finds the compositing descendants of compositingAncestor and updates their geometry.
1389 void RenderLayerCompositor::updateCompositingDescendantGeometry(RenderLayer* compositingAncestor, RenderLayer* layer, bool compositedChildrenOnly)
1390 {
1391     if (layer != compositingAncestor) {
1392         if (RenderLayerBacking* layerBacking = layer->backing()) {
1393             layerBacking->updateCompositedBounds();
1394
1395             if (RenderLayer* reflection = layer->reflectionLayer()) {
1396                 if (reflection->backing())
1397                     reflection->backing()->updateCompositedBounds();
1398             }
1399
1400             layerBacking->updateGraphicsLayerGeometry();
1401             if (compositedChildrenOnly)
1402                 return;
1403         }
1404     }
1405
1406     if (layer->reflectionLayer())
1407         updateCompositingDescendantGeometry(compositingAncestor, layer->reflectionLayer(), compositedChildrenOnly);
1408
1409     if (!layer->hasCompositingDescendant())
1410         return;
1411
1412 #if !ASSERT_DISABLED
1413     LayerListMutationDetector mutationChecker(layer);
1414 #endif
1415     
1416     if (layer->isStackingContainer()) {
1417         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
1418             size_t listSize = negZOrderList->size();
1419             for (size_t i = 0; i < listSize; ++i)
1420                 updateCompositingDescendantGeometry(compositingAncestor, negZOrderList->at(i), compositedChildrenOnly);
1421         }
1422     }
1423
1424     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
1425         size_t listSize = normalFlowList->size();
1426         for (size_t i = 0; i < listSize; ++i)
1427             updateCompositingDescendantGeometry(compositingAncestor, normalFlowList->at(i), compositedChildrenOnly);
1428     }
1429     
1430     if (layer->isStackingContainer()) {
1431         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
1432             size_t listSize = posZOrderList->size();
1433             for (size_t i = 0; i < listSize; ++i)
1434                 updateCompositingDescendantGeometry(compositingAncestor, posZOrderList->at(i), compositedChildrenOnly);
1435         }
1436     }
1437 }
1438
1439
1440 void RenderLayerCompositor::repaintCompositedLayers(const IntRect* absRect)
1441 {
1442     recursiveRepaintLayer(rootRenderLayer(), absRect);
1443 }
1444
1445 void RenderLayerCompositor::recursiveRepaintLayer(RenderLayer* layer, const IntRect* rect)
1446 {
1447     // FIXME: This method does not work correctly with transforms.
1448     if (layer->isComposited() && !layer->backing()->paintsIntoCompositedAncestor()) {
1449         if (rect)
1450             layer->setBackingNeedsRepaintInRect(*rect);
1451         else
1452             layer->setBackingNeedsRepaint();
1453     }
1454
1455 #if !ASSERT_DISABLED
1456     LayerListMutationDetector mutationChecker(layer);
1457 #endif
1458
1459     if (layer->hasCompositingDescendant()) {
1460         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
1461             size_t listSize = negZOrderList->size();
1462             for (size_t i = 0; i < listSize; ++i) {
1463                 RenderLayer* curLayer = negZOrderList->at(i);
1464                 if (rect) {
1465                     IntRect childRect(*rect);
1466                     curLayer->convertToPixelSnappedLayerCoords(layer, childRect);
1467                     recursiveRepaintLayer(curLayer, &childRect);
1468                 } else
1469                     recursiveRepaintLayer(curLayer);
1470             }
1471         }
1472
1473         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
1474             size_t listSize = posZOrderList->size();
1475             for (size_t i = 0; i < listSize; ++i) {
1476                 RenderLayer* curLayer = posZOrderList->at(i);
1477                 if (rect) {
1478                     IntRect childRect(*rect);
1479                     curLayer->convertToPixelSnappedLayerCoords(layer, childRect);
1480                     recursiveRepaintLayer(curLayer, &childRect);
1481                 } else
1482                     recursiveRepaintLayer(curLayer);
1483             }
1484         }
1485     }
1486     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
1487         size_t listSize = normalFlowList->size();
1488         for (size_t i = 0; i < listSize; ++i) {
1489             RenderLayer* curLayer = normalFlowList->at(i);
1490             if (rect) {
1491                 IntRect childRect(*rect);
1492                 curLayer->convertToPixelSnappedLayerCoords(layer, childRect);
1493                 recursiveRepaintLayer(curLayer, &childRect);
1494             } else
1495                 recursiveRepaintLayer(curLayer);
1496         }
1497     }
1498 }
1499
1500 RenderLayer* RenderLayerCompositor::rootRenderLayer() const
1501 {
1502     return m_renderView->layer();
1503 }
1504
1505 GraphicsLayer* RenderLayerCompositor::rootGraphicsLayer() const
1506 {
1507     if (m_overflowControlsHostLayer)
1508         return m_overflowControlsHostLayer.get();
1509     return m_rootContentLayer.get();
1510 }
1511
1512 GraphicsLayer* RenderLayerCompositor::scrollLayer() const
1513 {
1514     return m_scrollLayer.get();
1515 }
1516
1517 TiledBacking* RenderLayerCompositor::pageTiledBacking() const
1518 {
1519     RenderLayerBacking* renderViewBacking = m_renderView->layer()->backing();
1520     return renderViewBacking ? renderViewBacking->tiledBacking() : 0;
1521 }
1522
1523 void RenderLayerCompositor::setIsInWindow(bool isInWindow)
1524 {
1525     if (TiledBacking* tiledBacking = pageTiledBacking())
1526         tiledBacking->setIsInWindow(isInWindow);
1527
1528     if (!inCompositingMode())
1529         return;
1530
1531     if (isInWindow) {
1532         if (m_rootLayerAttachment != RootLayerUnattached)
1533             return;
1534
1535         RootLayerAttachment attachment = shouldPropagateCompositingToEnclosingFrame() ? RootLayerAttachedViaEnclosingFrame : RootLayerAttachedViaChromeClient;
1536         attachRootLayer(attachment);
1537     } else {
1538         if (m_rootLayerAttachment == RootLayerUnattached)
1539             return;
1540
1541         detachRootLayer();
1542     }
1543 }
1544
1545 void RenderLayerCompositor::clearBackingForLayerIncludingDescendants(RenderLayer* layer)
1546 {
1547     if (!layer)
1548         return;
1549
1550     if (layer->isComposited()) {
1551         removeViewportConstrainedLayer(layer);
1552         layer->clearBacking();
1553     }
1554     
1555     for (RenderLayer* currLayer = layer->firstChild(); currLayer; currLayer = currLayer->nextSibling())
1556         clearBackingForLayerIncludingDescendants(currLayer);
1557 }
1558
1559 void RenderLayerCompositor::clearBackingForAllLayers()
1560 {
1561     clearBackingForLayerIncludingDescendants(m_renderView->layer());
1562 }
1563
1564 void RenderLayerCompositor::updateRootLayerPosition()
1565 {
1566     if (m_rootContentLayer) {
1567         const IntRect& documentRect = m_renderView->documentRect();
1568         m_rootContentLayer->setSize(documentRect.size());
1569         m_rootContentLayer->setPosition(documentRect.location());
1570     }
1571     if (m_clipLayer) {
1572         FrameView* frameView = m_renderView->frameView();
1573         m_clipLayer->setSize(frameView->unscaledVisibleContentSize());
1574     }
1575
1576 #if ENABLE(RUBBER_BANDING)
1577     if (m_contentShadowLayer) {
1578         m_contentShadowLayer->setPosition(m_rootContentLayer->position());
1579
1580         FloatSize rootContentLayerSize = m_rootContentLayer->size();
1581         if (m_contentShadowLayer->size() != rootContentLayerSize) {
1582             m_contentShadowLayer->setSize(rootContentLayerSize);
1583             ScrollbarTheme::theme()->setUpContentShadowLayer(m_contentShadowLayer.get());
1584         }
1585     }
1586
1587     updateLayerForTopOverhangArea(m_layerForTopOverhangArea);
1588     updateLayerForBottomOverhangArea(m_layerForBottomOverhangArea);
1589 #endif
1590 }
1591
1592 bool RenderLayerCompositor::has3DContent() const
1593 {
1594     return layerHas3DContent(rootRenderLayer());
1595 }
1596
1597 bool RenderLayerCompositor::allowsIndependentlyCompositedFrames(const FrameView* view)
1598 {
1599 #if PLATFORM(MAC)
1600     // frames are only independently composited in Mac pre-WebKit2.
1601     return view->platformWidget();
1602 #else
1603     UNUSED_PARAM(view);
1604 #endif
1605     return false;
1606 }
1607
1608 bool RenderLayerCompositor::shouldPropagateCompositingToEnclosingFrame() const
1609 {
1610     // Parent document content needs to be able to render on top of a composited frame, so correct behavior
1611     // is to have the parent document become composited too. However, this can cause problems on platforms that
1612     // use native views for frames (like Mac), so disable that behavior on those platforms for now.
1613     HTMLFrameOwnerElement* ownerElement = m_renderView->document()->ownerElement();
1614     RenderObject* renderer = ownerElement ? ownerElement->renderer() : 0;
1615
1616     // If we are the top-level frame, don't propagate.
1617     if (!ownerElement)
1618         return false;
1619
1620     if (!allowsIndependentlyCompositedFrames(m_renderView->frameView()))
1621         return true;
1622
1623     if (!renderer || !renderer->isRenderPart())
1624         return false;
1625
1626     // On Mac, only propagate compositing if the frame is overlapped in the parent
1627     // document, or the parent is already compositing, or the main frame is scaled.
1628     Page* page = this->page();
1629     if (page && page->pageScaleFactor() != 1)
1630         return true;
1631     
1632     RenderPart* frameRenderer = toRenderPart(renderer);
1633     if (frameRenderer->widget()) {
1634         ASSERT(frameRenderer->widget()->isFrameView());
1635         FrameView* view = static_cast<FrameView*>(frameRenderer->widget());
1636         if (view->isOverlappedIncludingAncestors() || view->hasCompositingAncestor())
1637             return true;
1638     }
1639
1640     return false;
1641 }
1642
1643 bool RenderLayerCompositor::needsToBeComposited(const RenderLayer* layer, RenderLayer::ViewportConstrainedNotCompositedReason* viewportConstrainedNotCompositedReason) const
1644 {
1645     if (!canBeComposited(layer))
1646         return false;
1647
1648     return requiresCompositingLayer(layer, viewportConstrainedNotCompositedReason) || layer->mustCompositeForIndirectReasons() || (inCompositingMode() && layer->isRootLayer());
1649 }
1650
1651 // Note: this specifies whether the RL needs a compositing layer for intrinsic reasons.
1652 // Use needsToBeComposited() to determine if a RL actually needs a compositing layer.
1653 // static
1654 bool RenderLayerCompositor::requiresCompositingLayer(const RenderLayer* layer, RenderLayer::ViewportConstrainedNotCompositedReason* viewportConstrainedNotCompositedReason) const
1655 {
1656     RenderObject* renderer = layer->renderer();
1657     // The compositing state of a reflection should match that of its reflected layer.
1658     if (layer->isReflection()) {
1659         renderer = renderer->parent(); // The RenderReplica's parent is the object being reflected.
1660         layer = toRenderLayerModelObject(renderer)->layer();
1661     }
1662     // The root layer always has a compositing layer, but it may not have backing.
1663     return requiresCompositingForTransform(renderer)
1664         || requiresCompositingForVideo(renderer)
1665         || requiresCompositingForCanvas(renderer)
1666         || requiresCompositingForPlugin(renderer)
1667         || requiresCompositingForFrame(renderer)
1668         || (canRender3DTransforms() && renderer->style()->backfaceVisibility() == BackfaceVisibilityHidden)
1669         || clipsCompositingDescendants(layer)
1670         || requiresCompositingForAnimation(renderer)
1671         || requiresCompositingForFilters(renderer)
1672         || requiresCompositingForPosition(renderer, layer, viewportConstrainedNotCompositedReason)
1673         || requiresCompositingForOverflowScrolling(layer)
1674         || requiresCompositingForBlending(renderer);
1675 }
1676
1677 bool RenderLayerCompositor::canBeComposited(const RenderLayer* layer) const
1678 {
1679     // FIXME: We disable accelerated compositing for elements in a RenderFlowThread as it doesn't work properly.
1680     // See http://webkit.org/b/84900 to re-enable it.
1681     return m_hasAcceleratedCompositing && layer->isSelfPaintingLayer() && layer->renderer()->flowThreadState() == RenderObject::NotInsideFlowThread;
1682 }
1683
1684 bool RenderLayerCompositor::requiresOwnBackingStore(const RenderLayer* layer, const RenderLayer* compositingAncestorLayer) const
1685 {
1686     RenderObject* renderer = layer->renderer();
1687     if (compositingAncestorLayer
1688         && !(compositingAncestorLayer->backing()->graphicsLayer()->drawsContent()
1689             || compositingAncestorLayer->backing()->paintsIntoWindow()
1690             || compositingAncestorLayer->backing()->paintsIntoCompositedAncestor()))
1691         return true;
1692
1693     if (layer->isRootLayer()
1694         || layer->transform() // note: excludes perspective and transformStyle3D.
1695         || requiresCompositingForVideo(renderer)
1696         || requiresCompositingForCanvas(renderer)
1697         || requiresCompositingForPlugin(renderer)
1698         || requiresCompositingForFrame(renderer)
1699         || (canRender3DTransforms() && renderer->style()->backfaceVisibility() == BackfaceVisibilityHidden)
1700         || requiresCompositingForAnimation(renderer)
1701         || requiresCompositingForFilters(renderer)
1702         || requiresCompositingForBlending(renderer)
1703         || requiresCompositingForPosition(renderer, layer)
1704         || requiresCompositingForOverflowScrolling(layer)
1705         || renderer->isTransparent()
1706         || renderer->hasMask()
1707         || renderer->hasReflection()
1708         || renderer->hasFilter())
1709         return true;
1710         
1711     
1712     if (layer->mustCompositeForIndirectReasons()) {
1713         RenderLayer::IndirectCompositingReason reason = layer->indirectCompositingReason();
1714         return reason == RenderLayer::IndirectCompositingForOverlap
1715             || reason == RenderLayer::IndirectCompositingForStacking
1716             || reason == RenderLayer::IndirectCompositingForBackgroundLayer
1717             || reason == RenderLayer::IndirectCompositingForGraphicalEffect
1718             || reason == RenderLayer::IndirectCompositingForPreserve3D; // preserve-3d has to create backing store to ensure that 3d-transformed elements intersect.
1719     }
1720     return false;
1721 }
1722
1723 CompositingReasons RenderLayerCompositor::reasonsForCompositing(const RenderLayer* layer) const
1724 {
1725     CompositingReasons reasons = CompositingReasonNone;
1726
1727     if (!layer || !layer->isComposited())
1728         return reasons;
1729
1730     RenderObject* renderer = layer->renderer();
1731     if (layer->isReflection()) {
1732         renderer = renderer->parent();
1733         layer = toRenderLayerModelObject(renderer)->layer();
1734     }
1735
1736     if (requiresCompositingForTransform(renderer))
1737         reasons |= CompositingReason3DTransform;
1738
1739     if (requiresCompositingForVideo(renderer))
1740         reasons |= CompositingReasonVideo;
1741
1742     if (requiresCompositingForCanvas(renderer))
1743         reasons |= CompositingReasonCanvas;
1744
1745     if (requiresCompositingForPlugin(renderer))
1746         reasons |= CompositingReasonPlugin;
1747
1748     if (requiresCompositingForFrame(renderer))
1749         reasons |= CompositingReasonIFrame;
1750     
1751     if ((canRender3DTransforms() && renderer->style()->backfaceVisibility() == BackfaceVisibilityHidden))
1752         reasons |= CompositingReasonBackfaceVisibilityHidden;
1753
1754     if (clipsCompositingDescendants(layer))
1755         reasons |= CompositingReasonClipsCompositingDescendants;
1756
1757     if (requiresCompositingForAnimation(renderer))
1758         reasons |= CompositingReasonAnimation;
1759
1760     if (requiresCompositingForFilters(renderer))
1761         reasons |= CompositingReasonFilters;
1762
1763     if (requiresCompositingForPosition(renderer, layer))
1764         reasons |= renderer->style()->position() == FixedPosition ? CompositingReasonPositionFixed : CompositingReasonPositionSticky;
1765
1766     if (requiresCompositingForOverflowScrolling(layer))
1767         reasons |= CompositingReasonOverflowScrollingTouch;
1768
1769     if (layer->indirectCompositingReason() == RenderLayer::IndirectCompositingForStacking)
1770         reasons |= CompositingReasonStacking;
1771     else if (layer->indirectCompositingReason() == RenderLayer::IndirectCompositingForOverlap)
1772         reasons |= CompositingReasonOverlap;
1773     else if (layer->indirectCompositingReason() == RenderLayer::IndirectCompositingForBackgroundLayer)
1774         reasons |= CompositingReasonNegativeZIndexChildren;
1775     else if (layer->indirectCompositingReason() == RenderLayer::IndirectCompositingForGraphicalEffect) {
1776         if (layer->transform())
1777             reasons |= CompositingReasonTransformWithCompositedDescendants;
1778
1779         if (renderer->isTransparent())
1780             reasons |= CompositingReasonOpacityWithCompositedDescendants;
1781
1782         if (renderer->hasMask())
1783             reasons |= CompositingReasonMaskWithCompositedDescendants;
1784
1785         if (renderer->hasReflection())
1786             reasons |= CompositingReasonReflectionWithCompositedDescendants;
1787
1788         if (renderer->hasFilter())
1789             reasons |= CompositingReasonFilterWithCompositedDescendants;
1790             
1791         if (renderer->hasBlendMode())
1792             reasons |= CompositingReasonBlendingWithCompositedDescendants;
1793     } else if (layer->indirectCompositingReason() == RenderLayer::IndirectCompositingForPerspective)
1794         reasons |= CompositingReasonPerspective;
1795     else if (layer->indirectCompositingReason() == RenderLayer::IndirectCompositingForPreserve3D)
1796         reasons |= CompositingReasonPreserve3D;
1797
1798     if (inCompositingMode() && layer->isRootLayer())
1799         reasons |= CompositingReasonRoot;
1800
1801     return reasons;
1802 }
1803
1804 #if !LOG_DISABLED
1805 const char* RenderLayerCompositor::logReasonsForCompositing(const RenderLayer* layer)
1806 {
1807     CompositingReasons reasons = reasonsForCompositing(layer);
1808
1809     if (reasons & CompositingReason3DTransform)
1810         return "3D transform";
1811
1812     if (reasons & CompositingReasonVideo)
1813         return "video";
1814
1815     if (reasons & CompositingReasonCanvas)
1816         return "canvas";
1817
1818     if (reasons & CompositingReasonPlugin)
1819         return "plugin";
1820
1821     if (reasons & CompositingReasonIFrame)
1822         return "iframe";
1823     
1824     if (reasons & CompositingReasonBackfaceVisibilityHidden)
1825         return "backface-visibility: hidden";
1826
1827     if (reasons & CompositingReasonClipsCompositingDescendants)
1828         return "clips compositing descendants";
1829
1830     if (reasons & CompositingReasonAnimation)
1831         return "animation";
1832
1833     if (reasons & CompositingReasonFilters)
1834         return "filters";
1835
1836     if (reasons & CompositingReasonPositionFixed)
1837         return "position: fixed";
1838
1839     if (reasons & CompositingReasonPositionSticky)
1840         return "position: sticky";
1841
1842     if (reasons & CompositingReasonOverflowScrollingTouch)
1843         return "-webkit-overflow-scrolling: touch";
1844
1845     if (reasons & CompositingReasonStacking)
1846         return "stacking";
1847
1848     if (reasons & CompositingReasonOverlap)
1849         return "overlap";
1850
1851     if (reasons & CompositingReasonNegativeZIndexChildren)
1852         return "negative z-index children";
1853
1854     if (reasons & CompositingReasonTransformWithCompositedDescendants)
1855         return "transform with composited descendants";
1856
1857     if (reasons & CompositingReasonOpacityWithCompositedDescendants)
1858         return "opacity with composited descendants";
1859
1860     if (reasons & CompositingReasonMaskWithCompositedDescendants)
1861         return "mask with composited descendants";
1862
1863     if (reasons & CompositingReasonReflectionWithCompositedDescendants)
1864         return "reflection with composited descendants";
1865
1866     if (reasons & CompositingReasonFilterWithCompositedDescendants)
1867         return "filter with composited descendants";
1868             
1869     if (reasons & CompositingReasonBlendingWithCompositedDescendants)
1870         return "blending with composited descendants";
1871
1872     if (reasons & CompositingReasonPerspective)
1873         return "perspective";
1874
1875     if (reasons & CompositingReasonPreserve3D)
1876         return "preserve-3d";
1877
1878     if (reasons & CompositingReasonRoot)
1879         return "root";
1880
1881     return "";
1882 }
1883 #endif
1884
1885 // Return true if the given layer has some ancestor in the RenderLayer hierarchy that clips,
1886 // up to the enclosing compositing ancestor. This is required because compositing layers are parented
1887 // according to the z-order hierarchy, yet clipping goes down the renderer hierarchy.
1888 // Thus, a RenderLayer can be clipped by a RenderLayer that is an ancestor in the renderer hierarchy,
1889 // but a sibling in the z-order hierarchy.
1890 bool RenderLayerCompositor::clippedByAncestor(RenderLayer* layer) const
1891 {
1892     if (!layer->isComposited() || !layer->parent())
1893         return false;
1894
1895     RenderLayer* compositingAncestor = layer->ancestorCompositingLayer();
1896     if (!compositingAncestor)
1897         return false;
1898
1899     // If the compositingAncestor clips, that will be taken care of by clipsCompositingDescendants(),
1900     // so we only care about clipping between its first child that is our ancestor (the computeClipRoot),
1901     // and layer.
1902     RenderLayer* computeClipRoot = 0;
1903     RenderLayer* curr = layer;
1904     while (curr) {
1905         RenderLayer* next = curr->parent();
1906         if (next == compositingAncestor) {
1907             computeClipRoot = curr;
1908             break;
1909         }
1910         curr = next;
1911     }
1912     
1913     if (!computeClipRoot || computeClipRoot == layer)
1914         return false;
1915
1916     return layer->backgroundClipRect(RenderLayer::ClipRectsContext(computeClipRoot, 0, TemporaryClipRects)).rect() != PaintInfo::infiniteRect(); // FIXME: Incorrect for CSS regions.
1917 }
1918
1919 // Return true if the given layer is a stacking context and has compositing child
1920 // layers that it needs to clip. In this case we insert a clipping GraphicsLayer
1921 // into the hierarchy between this layer and its children in the z-order hierarchy.
1922 bool RenderLayerCompositor::clipsCompositingDescendants(const RenderLayer* layer) const
1923 {
1924     return layer->hasCompositingDescendant() && layer->renderer()->hasClipOrOverflowClip();
1925 }
1926
1927 // Return true if there is an ancestor layer that is fixed positioned to the view.
1928 // Note that if the ancestor has a stacking context and is fixed position then this method
1929 // will return false.
1930 bool RenderLayerCompositor::fixedPositionedByAncestor(const RenderLayer* layer) const
1931 {
1932     if (!layer->isComposited() || !layer->parent())
1933         return false;
1934
1935     const RenderLayer* compositingAncestor = layer->ancestorCompositingLayer();
1936     if (!compositingAncestor)
1937         return false;
1938
1939     const RenderLayer* curr = layer;
1940     while (curr) {
1941         const RenderLayer* next = curr->parent();
1942         if (next == compositingAncestor)
1943             return false;
1944
1945         if (next && next->renderer()->style()->position() == FixedPosition)
1946             return true;
1947         curr = next;
1948     }
1949     return false;
1950 }
1951
1952 bool RenderLayerCompositor::requiresCompositingForScrollableFrame() const
1953 {
1954     // Need this done first to determine overflow.
1955     ASSERT(!m_renderView->needsLayout());
1956     HTMLFrameOwnerElement* ownerElement = m_renderView->document()->ownerElement();
1957     if (!ownerElement)
1958         return false;
1959
1960     if (!(m_compositingTriggers & ChromeClient::ScrollableInnerFrameTrigger))
1961         return false;
1962
1963     FrameView* frameView = m_renderView->frameView();
1964     return frameView->isScrollable();
1965 }
1966
1967 bool RenderLayerCompositor::requiresCompositingForTransform(RenderObject* renderer) const
1968 {
1969     if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
1970         return false;
1971
1972     RenderStyle* style = renderer->style();
1973     // Note that we ask the renderer if it has a transform, because the style may have transforms,
1974     // but the renderer may be an inline that doesn't suppport them.
1975     return renderer->hasTransform() && style->transform().has3DOperation();
1976 }
1977
1978 bool RenderLayerCompositor::requiresCompositingForVideo(RenderObject* renderer) const
1979 {
1980     if (!(m_compositingTriggers & ChromeClient::VideoTrigger))
1981         return false;
1982 #if ENABLE(VIDEO)
1983     if (renderer->isVideo()) {
1984         RenderVideo* video = toRenderVideo(renderer);
1985         return video->shouldDisplayVideo() && canAccelerateVideoRendering(video);
1986     }
1987 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
1988     else if (renderer->isRenderPart()) {
1989         if (!m_hasAcceleratedCompositing)
1990             return false;
1991
1992         Node* node = renderer->node();
1993         if (!node || (!node->hasTagName(HTMLNames::videoTag) && !node->hasTagName(HTMLNames::audioTag)))
1994             return false;
1995
1996         HTMLMediaElement* mediaElement = toMediaElement(node);
1997         return mediaElement->player() ? mediaElement->player()->supportsAcceleratedRendering() : false;
1998     }
1999 #endif // ENABLE(PLUGIN_PROXY_FOR_VIDEO)
2000 #else
2001     UNUSED_PARAM(renderer);
2002 #endif
2003     return false;
2004 }
2005
2006 bool RenderLayerCompositor::requiresCompositingForCanvas(RenderObject* renderer) const
2007 {
2008     if (!(m_compositingTriggers & ChromeClient::CanvasTrigger))
2009         return false;
2010
2011     if (renderer->isCanvas()) {
2012         HTMLCanvasElement* canvas = static_cast<HTMLCanvasElement*>(renderer->node());
2013 #if USE(COMPOSITING_FOR_SMALL_CANVASES)
2014         bool isCanvasLargeEnoughToForceCompositing = true;
2015 #else
2016         bool isCanvasLargeEnoughToForceCompositing = canvas->size().area() >= canvasAreaThresholdRequiringCompositing;
2017 #endif
2018         return canvas->renderingContext() && canvas->renderingContext()->isAccelerated() && (canvas->renderingContext()->is3d() || isCanvasLargeEnoughToForceCompositing);
2019     }
2020     return false;
2021 }
2022
2023 bool RenderLayerCompositor::requiresCompositingForPlugin(RenderObject* renderer) const
2024 {
2025     if (!(m_compositingTriggers & ChromeClient::PluginTrigger))
2026         return false;
2027
2028     bool composite = renderer->isEmbeddedObject() && toRenderEmbeddedObject(renderer)->allowsAcceleratedCompositing();
2029     if (!composite)
2030         return false;
2031
2032     m_reevaluateCompositingAfterLayout = true;
2033     
2034     RenderWidget* pluginRenderer = toRenderWidget(renderer);
2035     // If we can't reliably know the size of the plugin yet, don't change compositing state.
2036     if (pluginRenderer->needsLayout())
2037         return pluginRenderer->hasLayer() && pluginRenderer->layer()->isComposited();
2038
2039     // Don't go into compositing mode if height or width are zero, or size is 1x1.
2040     IntRect contentBox = pixelSnappedIntRect(pluginRenderer->contentBoxRect());
2041     return contentBox.height() * contentBox.width() > 1;
2042 }
2043
2044 bool RenderLayerCompositor::requiresCompositingForFrame(RenderObject* renderer) const
2045 {
2046     if (!renderer->isRenderPart())
2047         return false;
2048     
2049     RenderPart* frameRenderer = toRenderPart(renderer);
2050
2051     if (!frameRenderer->requiresAcceleratedCompositing())
2052         return false;
2053
2054     m_reevaluateCompositingAfterLayout = true;
2055
2056     RenderLayerCompositor* innerCompositor = frameContentsCompositor(frameRenderer);
2057     if (!innerCompositor || !innerCompositor->shouldPropagateCompositingToEnclosingFrame())
2058         return false;
2059
2060     // If we can't reliably know the size of the iframe yet, don't change compositing state.
2061     if (renderer->needsLayout())
2062         return frameRenderer->hasLayer() && frameRenderer->layer()->isComposited();
2063     
2064     // Don't go into compositing mode if height or width are zero.
2065     IntRect contentBox = pixelSnappedIntRect(frameRenderer->contentBoxRect());
2066     return contentBox.height() * contentBox.width() > 0;
2067 }
2068
2069 bool RenderLayerCompositor::requiresCompositingForAnimation(RenderObject* renderer) const
2070 {
2071     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
2072         return false;
2073
2074     if (AnimationController* animController = renderer->animation()) {
2075         return (animController->isRunningAnimationOnRenderer(renderer, CSSPropertyOpacity) && inCompositingMode())
2076 #if ENABLE(CSS_FILTERS)
2077 #if !PLATFORM(MAC) || (!PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080)
2078             // <rdar://problem/10907251> - WebKit2 doesn't support CA animations of CI filters on Lion and below
2079             || animController->isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitFilter)
2080 #endif // !PLATFORM(MAC) || (!PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080)
2081 #endif // CSS_FILTERS
2082             || animController->isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitTransform);
2083     }
2084     return false;
2085 }
2086
2087 bool RenderLayerCompositor::requiresCompositingForIndirectReason(RenderObject* renderer, bool hasCompositedDescendants, bool has3DTransformedDescendants, RenderLayer::IndirectCompositingReason& reason) const
2088 {
2089     RenderLayer* layer = toRenderBoxModelObject(renderer)->layer();
2090
2091     // When a layer has composited descendants, some effects, like 2d transforms, filters, masks etc must be implemented
2092     // via compositing so that they also apply to those composited descdendants.
2093     if (hasCompositedDescendants && (layer->transform() || renderer->createsGroup() || renderer->hasReflection())) {
2094         reason = RenderLayer::IndirectCompositingForGraphicalEffect;
2095         return true;
2096     }
2097
2098     // A layer with preserve-3d or perspective only needs to be composited if there are descendant layers that
2099     // will be affected by the preserve-3d or perspective.
2100     if (has3DTransformedDescendants) {
2101         if (renderer->style()->transformStyle3D() == TransformStyle3DPreserve3D) {
2102             reason = RenderLayer::IndirectCompositingForPreserve3D;
2103             return true;
2104         }
2105     
2106         if (renderer->style()->hasPerspective()) {
2107             reason = RenderLayer::IndirectCompositingForPerspective;
2108             return true;
2109         }
2110     }
2111
2112     reason = RenderLayer::NoIndirectCompositingReason;
2113     return false;
2114 }
2115
2116 bool RenderLayerCompositor::requiresCompositingForFilters(RenderObject* renderer) const
2117 {
2118 #if ENABLE(CSS_FILTERS)
2119     if (!(m_compositingTriggers & ChromeClient::FilterTrigger))
2120         return false;
2121
2122     return renderer->hasFilter();
2123 #else
2124     UNUSED_PARAM(renderer);
2125     return false;
2126 #endif
2127 }
2128
2129 bool RenderLayerCompositor::requiresCompositingForBlending(RenderObject* renderer) const
2130 {
2131 #if ENABLE(CSS_COMPOSITING)
2132     return renderer->hasBlendMode();
2133 #else
2134     UNUSED_PARAM(renderer);
2135     return false;
2136 #endif
2137 }
2138
2139 bool RenderLayerCompositor::requiresCompositingForPosition(RenderObject* renderer, const RenderLayer* layer, RenderLayer::ViewportConstrainedNotCompositedReason* viewportConstrainedNotCompositedReason) const
2140 {
2141     // position:fixed elements that create their own stacking context (e.g. have an explicit z-index,
2142     // opacity, transform) can get their own composited layer. A stacking context is required otherwise
2143     // z-index and clipping will be broken.
2144     if (!renderer->isPositioned())
2145         return false;
2146     
2147     EPosition position = renderer->style()->position();
2148     bool isFixed = renderer->isOutOfFlowPositioned() && position == FixedPosition;
2149     if (isFixed && !layer->isStackingContainer())
2150         return false;
2151     
2152     bool isSticky = renderer->isInFlowPositioned() && position == StickyPosition;
2153     if (!isFixed && !isSticky)
2154         return false;
2155
2156     // FIXME: acceleratedCompositingForFixedPositionEnabled should probably be renamed acceleratedCompositingForViewportConstrainedPositionEnabled().
2157     if (Settings* settings = m_renderView->document()->settings()) {
2158         if (!settings->acceleratedCompositingForFixedPositionEnabled())
2159             return false;
2160     }
2161
2162     if (isSticky)
2163         return true;
2164
2165     RenderObject* container = renderer->container();
2166     // If the renderer is not hooked up yet then we have to wait until it is.
2167     if (!container) {
2168         m_reevaluateCompositingAfterLayout = true;
2169         return false;
2170     }
2171
2172     // Don't promote fixed position elements that are descendants of a non-view container, e.g. transformed elements.
2173     // They will stay fixed wrt the container rather than the enclosing frame.
2174     if (container != m_renderView) {
2175         if (viewportConstrainedNotCompositedReason)
2176             *viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForNonViewContainer;
2177         return false;
2178     }
2179     
2180     // Subsequent tests depend on layout. If we can't tell now, just keep things the way they are until layout is done.
2181     if (!m_inPostLayoutUpdate) {
2182         m_reevaluateCompositingAfterLayout = true;
2183         return layer->isComposited();
2184     }
2185
2186     // Fixed position elements that are invisible in the current view don't get their own layer.
2187     if (FrameView* frameView = m_renderView->frameView()) {
2188         LayoutRect viewBounds = frameView->viewportConstrainedVisibleContentRect();
2189         LayoutRect layerBounds = layer->calculateLayerBounds(rootRenderLayer(), 0, RenderLayer::DefaultCalculateLayerBoundsFlags
2190             | RenderLayer::ExcludeHiddenDescendants | RenderLayer::DontConstrainForMask | RenderLayer::IncludeCompositedDescendants);
2191         if (!viewBounds.intersects(enclosingIntRect(layerBounds))) {
2192             if (viewportConstrainedNotCompositedReason)
2193                 *viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForBoundsOutOfView;
2194             return false;
2195         }
2196     }
2197     
2198     bool paintsContent = layer->isVisuallyNonEmpty() || layer->hasVisibleDescendant();
2199     if (!paintsContent)
2200         return false;
2201
2202     return true;
2203 }
2204
2205 bool RenderLayerCompositor::requiresCompositingForOverflowScrolling(const RenderLayer* layer) const
2206 {
2207     return layer->needsCompositedScrolling();
2208 }
2209
2210 bool RenderLayerCompositor::isRunningAcceleratedTransformAnimation(RenderObject* renderer) const
2211 {
2212     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
2213         return false;
2214
2215     if (AnimationController* animController = renderer->animation())
2216         return animController->isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitTransform);
2217
2218     return false;
2219 }
2220
2221 // If an element has negative z-index children, those children render in front of the 
2222 // layer background, so we need an extra 'contents' layer for the foreground of the layer
2223 // object.
2224 bool RenderLayerCompositor::needsContentsCompositingLayer(const RenderLayer* layer) const
2225 {
2226     return layer->hasNegativeZOrderList();
2227 }
2228
2229 bool RenderLayerCompositor::requiresScrollLayer(RootLayerAttachment attachment) const
2230 {
2231     // This applies when the application UI handles scrolling, in which case RenderLayerCompositor doesn't need to manage it.
2232     if (m_renderView->frameView()->delegatesScrolling())
2233         return false;
2234
2235     // We need to handle our own scrolling if we're:
2236     return !m_renderView->frameView()->platformWidget() // viewless (i.e. non-Mac, or Mac in WebKit2)
2237         || attachment == RootLayerAttachedViaEnclosingFrame; // a composited frame on Mac
2238 }
2239
2240 static void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
2241 {
2242     if (!scrollbar)
2243         return;
2244
2245     context.save();
2246     const IntRect& scrollbarRect = scrollbar->frameRect();
2247     context.translate(-scrollbarRect.x(), -scrollbarRect.y());
2248     IntRect transformedClip = clip;
2249     transformedClip.moveBy(scrollbarRect.location());
2250     scrollbar->paint(&context, transformedClip);
2251     context.restore();
2252 }
2253
2254 void RenderLayerCompositor::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, GraphicsLayerPaintingPhase, const IntRect& clip)
2255 {
2256     if (graphicsLayer == layerForHorizontalScrollbar())
2257         paintScrollbar(m_renderView->frameView()->horizontalScrollbar(), context, clip);
2258     else if (graphicsLayer == layerForVerticalScrollbar())
2259         paintScrollbar(m_renderView->frameView()->verticalScrollbar(), context, clip);
2260     else if (graphicsLayer == layerForScrollCorner()) {
2261         const IntRect& scrollCorner = m_renderView->frameView()->scrollCornerRect();
2262         context.save();
2263         context.translate(-scrollCorner.x(), -scrollCorner.y());
2264         IntRect transformedClip = clip;
2265         transformedClip.moveBy(scrollCorner.location());
2266         m_renderView->frameView()->paintScrollCorner(&context, transformedClip);
2267         context.restore();
2268 #if PLATFORM(CHROMIUM) && ENABLE(RUBBER_BANDING)
2269     } else if (graphicsLayer == layerForOverhangAreas()) {
2270         ScrollView* view = m_renderView->frameView();
2271         view->calculateAndPaintOverhangAreas(&context, clip);
2272 #endif
2273     }
2274 }
2275
2276 bool RenderLayerCompositor::supportsFixedRootBackgroundCompositing() const
2277 {
2278     RenderLayerBacking* renderViewBacking = m_renderView->layer()->backing();
2279     return renderViewBacking && renderViewBacking->usingTiledBacking();
2280 }
2281
2282 bool RenderLayerCompositor::needsFixedRootBackgroundLayer(const RenderLayer* layer) const
2283 {
2284     if (layer != m_renderView->layer())
2285         return false;
2286
2287     return supportsFixedRootBackgroundCompositing() && m_renderView->rootBackgroundIsEntirelyFixed();
2288 }
2289
2290 GraphicsLayer* RenderLayerCompositor::fixedRootBackgroundLayer() const
2291 {
2292     // Get the fixed root background from the RenderView layer's backing.
2293     RenderLayer* viewLayer = m_renderView->layer();
2294     if (!viewLayer)
2295         return 0;
2296     
2297     if (viewLayer->isComposited() && viewLayer->backing()->backgroundLayerPaintsFixedRootBackground())
2298         return viewLayer->backing()->backgroundLayer();
2299
2300     return 0;
2301 }
2302
2303 static void resetTrackedRepaintRectsRecursive(GraphicsLayer* graphicsLayer)
2304 {
2305     if (!graphicsLayer)
2306         return;
2307
2308     graphicsLayer->resetTrackedRepaints();
2309
2310     for (size_t i = 0; i < graphicsLayer->children().size(); ++i)
2311         resetTrackedRepaintRectsRecursive(graphicsLayer->children()[i]);
2312
2313     if (GraphicsLayer* replicaLayer = graphicsLayer->replicaLayer())
2314         resetTrackedRepaintRectsRecursive(replicaLayer);
2315
2316     if (GraphicsLayer* maskLayer = graphicsLayer->maskLayer())
2317         resetTrackedRepaintRectsRecursive(maskLayer);
2318 }
2319
2320 void RenderLayerCompositor::resetTrackedRepaintRects()
2321 {
2322     if (GraphicsLayer* rootLayer = rootGraphicsLayer())
2323         resetTrackedRepaintRectsRecursive(rootLayer);
2324 }
2325
2326 void RenderLayerCompositor::setTracksRepaints(bool tracksRepaints)
2327 {
2328     m_isTrackingRepaints = tracksRepaints;
2329 }
2330
2331 bool RenderLayerCompositor::isTrackingRepaints() const
2332 {
2333     return m_isTrackingRepaints;
2334 }
2335
2336 float RenderLayerCompositor::deviceScaleFactor() const
2337 {
2338     Page* page = this->page();
2339     return page ? page->deviceScaleFactor() : 1;
2340 }
2341
2342 float RenderLayerCompositor::pageScaleFactor() const
2343 {
2344     Page* page = this->page();
2345     return page ? page->pageScaleFactor() : 1;
2346 }
2347
2348 void RenderLayerCompositor::didCommitChangesForLayer(const GraphicsLayer*) const
2349 {
2350     // Nothing to do here yet.
2351 }
2352
2353 bool RenderLayerCompositor::keepLayersPixelAligned() const
2354 {
2355     // When scaling, attempt to align compositing layers to pixel boundaries.
2356     return true;
2357 }
2358
2359 static bool shouldCompositeOverflowControls(FrameView* view)
2360 {
2361     if (view->platformWidget())
2362         return false;
2363
2364     if (Page* page = view->frame()->page()) {
2365         if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
2366             if (scrollingCoordinator->coordinatesScrollingForFrameView(view))
2367                 return true;
2368     }
2369
2370 #if !PLATFORM(CHROMIUM)
2371     if (!view->hasOverlayScrollbars())
2372         return false;
2373 #endif
2374     return true;
2375 }
2376
2377 bool RenderLayerCompositor::requiresHorizontalScrollbarLayer() const
2378 {
2379     FrameView* view = m_renderView->frameView();
2380     return shouldCompositeOverflowControls(view) && view->horizontalScrollbar();
2381 }
2382
2383 bool RenderLayerCompositor::requiresVerticalScrollbarLayer() const
2384 {
2385     FrameView* view = m_renderView->frameView();
2386     return shouldCompositeOverflowControls(view) && view->verticalScrollbar();
2387 }
2388
2389 bool RenderLayerCompositor::requiresScrollCornerLayer() const
2390 {
2391     FrameView* view = m_renderView->frameView();
2392     return shouldCompositeOverflowControls(view) && view->isScrollCornerVisible();
2393 }
2394
2395 #if ENABLE(RUBBER_BANDING)
2396 bool RenderLayerCompositor::requiresOverhangAreasLayer() const
2397 {
2398     // We don't want a layer if this is a subframe.
2399     if (m_renderView->document()->ownerElement())
2400         return false;
2401
2402     // We do want a layer if we have a scrolling coordinator and can scroll.
2403     if (scrollingCoordinator() && m_renderView->frameView()->hasOpaqueBackground() && !m_renderView->frameView()->prohibitsScrolling())
2404         return true;
2405
2406     // Chromium always wants a layer.
2407 #if PLATFORM(CHROMIUM)
2408     return true;
2409 #endif
2410
2411     return false;
2412 }
2413
2414 bool RenderLayerCompositor::requiresContentShadowLayer() const
2415 {
2416     // We don't want a layer if this is a subframe.
2417     if (m_renderView->document()->ownerElement())
2418         return false;
2419
2420 #if PLATFORM(MAC)
2421     if (viewHasTransparentBackground())
2422         return false;
2423
2424     // On Mac, we want a content shadow layer if we have a scrolling coordinator and can scroll.
2425     if (scrollingCoordinator() && !m_renderView->frameView()->prohibitsScrolling())
2426         return true;
2427 #endif
2428
2429     return false;
2430 }
2431
2432 GraphicsLayer* RenderLayerCompositor::updateLayerForTopOverhangArea(bool wantsLayer)
2433 {
2434     if (m_renderView->document()->ownerElement())
2435         return 0;
2436
2437     if (!wantsLayer) {
2438         if (m_layerForTopOverhangArea) {
2439             m_layerForTopOverhangArea->removeFromParent();
2440             m_layerForTopOverhangArea = nullptr;
2441         }
2442         return 0;
2443     }
2444
2445     if (!m_layerForTopOverhangArea) {
2446         m_layerForTopOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), this);
2447 #ifndef NDEBUG
2448         m_layerForTopOverhangArea->setName("top overhang area");
2449 #endif
2450         m_scrollLayer->addChildBelow(m_layerForTopOverhangArea.get(), m_rootContentLayer.get());
2451     }
2452
2453     return m_layerForTopOverhangArea.get();
2454 }
2455
2456 GraphicsLayer* RenderLayerCompositor::updateLayerForBottomOverhangArea(bool wantsLayer)
2457 {
2458     if (m_renderView->document()->ownerElement())
2459         return 0;
2460
2461     if (!wantsLayer) {
2462         if (m_layerForBottomOverhangArea) {
2463             m_layerForBottomOverhangArea->removeFromParent();
2464             m_layerForBottomOverhangArea = nullptr;
2465         }
2466         return 0;
2467     }
2468
2469     if (!m_layerForBottomOverhangArea) {
2470         m_layerForBottomOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), this);
2471 #ifndef NDEBUG
2472         m_layerForBottomOverhangArea->setName("bottom overhang area");
2473 #endif
2474         m_scrollLayer->addChildBelow(m_layerForBottomOverhangArea.get(), m_rootContentLayer.get());
2475     }
2476
2477     m_layerForBottomOverhangArea->setPosition(FloatPoint(0, m_rootContentLayer->size().height()));
2478     return m_layerForBottomOverhangArea.get();
2479 }
2480
2481 #endif
2482
2483 bool RenderLayerCompositor::viewHasTransparentBackground(Color* backgroundColor) const
2484 {
2485     FrameView* frameView = m_renderView->frameView();
2486     if (frameView->isTransparent()) {
2487         if (backgroundColor)
2488             *backgroundColor = Color(); // Return an invalid color.
2489         return true;
2490     }
2491
2492     Color documentBackgroundColor = frameView->documentBackgroundColor();
2493     if (!documentBackgroundColor.isValid())
2494         documentBackgroundColor = Color::white;
2495
2496     if (backgroundColor)
2497         *backgroundColor = documentBackgroundColor;
2498         
2499     return documentBackgroundColor.hasAlpha();
2500 }
2501
2502 void RenderLayerCompositor::updateOverflowControlsLayers()
2503 {
2504 #if ENABLE(RUBBER_BANDING)
2505     if (requiresOverhangAreasLayer()) {
2506         if (!m_layerForOverhangAreas) {
2507             m_layerForOverhangAreas = GraphicsLayer::create(graphicsLayerFactory(), this);
2508 #ifndef NDEBUG
2509             m_layerForOverhangAreas->setName("overhang areas");
2510 #endif
2511             m_layerForOverhangAreas->setDrawsContent(false);
2512             m_layerForOverhangAreas->setSize(m_renderView->frameView()->frameRect().size());
2513
2514             ScrollbarTheme::theme()->setUpOverhangAreasLayerContents(m_layerForOverhangAreas.get(), this->page()->chrome()->client()->underlayColor());
2515
2516             // We want the overhang areas layer to be positioned below the frame contents,
2517             // so insert it below the clip layer.
2518             m_overflowControlsHostLayer->addChildBelow(m_layerForOverhangAreas.get(), m_clipLayer.get());
2519         }
2520     } else if (m_layerForOverhangAreas) {
2521         m_layerForOverhangAreas->removeFromParent();
2522         m_layerForOverhangAreas = nullptr;
2523     }
2524
2525     if (requiresContentShadowLayer()) {
2526         if (!m_contentShadowLayer) {
2527             m_contentShadowLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
2528 #ifndef NDEBUG
2529             m_contentShadowLayer->setName("content shadow");
2530 #endif
2531             m_contentShadowLayer->setSize(m_rootContentLayer->size());
2532             m_contentShadowLayer->setPosition(m_rootContentLayer->position());
2533             ScrollbarTheme::theme()->setUpContentShadowLayer(m_contentShadowLayer.get());
2534
2535             m_scrollLayer->addChildBelow(m_contentShadowLayer.get(), m_rootContentLayer.get());
2536         }
2537     } else if (m_contentShadowLayer) {
2538         m_contentShadowLayer->removeFromParent();
2539         m_contentShadowLayer = nullptr;
2540     }
2541 #endif
2542
2543     if (requiresHorizontalScrollbarLayer()) {
2544         if (!m_layerForHorizontalScrollbar) {
2545             m_layerForHorizontalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), this);
2546             m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
2547 #ifndef NDEBUG
2548             m_layerForHorizontalScrollbar->setName("horizontal scrollbar");
2549 #endif
2550 #if PLATFORM(MAC) && USE(CA)
2551             m_layerForHorizontalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
2552 #endif
2553             m_overflowControlsHostLayer->addChild(m_layerForHorizontalScrollbar.get());
2554
2555             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2556                 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView->frameView(), HorizontalScrollbar);
2557         }
2558     } else if (m_layerForHorizontalScrollbar) {
2559         m_layerForHorizontalScrollbar->removeFromParent();
2560         m_layerForHorizontalScrollbar = nullptr;
2561
2562         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2563             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView->frameView(), HorizontalScrollbar);
2564     }
2565
2566     if (requiresVerticalScrollbarLayer()) {
2567         if (!m_layerForVerticalScrollbar) {
2568             m_layerForVerticalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), this);
2569             m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
2570 #ifndef NDEBUG
2571             m_layerForVerticalScrollbar->setName("vertical scrollbar");
2572 #endif
2573 #if PLATFORM(MAC) && USE(CA)
2574         m_layerForVerticalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
2575 #endif
2576             m_overflowControlsHostLayer->addChild(m_layerForVerticalScrollbar.get());
2577
2578             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2579                 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView->frameView(), VerticalScrollbar);
2580         }
2581     } else if (m_layerForVerticalScrollbar) {
2582         m_layerForVerticalScrollbar->removeFromParent();
2583         m_layerForVerticalScrollbar = nullptr;
2584
2585         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2586             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView->frameView(), VerticalScrollbar);
2587     }
2588
2589     if (requiresScrollCornerLayer()) {
2590         if (!m_layerForScrollCorner) {
2591             m_layerForScrollCorner = GraphicsLayer::create(graphicsLayerFactory(), this);
2592             m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
2593 #ifndef NDEBUG
2594             m_layerForScrollCorner->setName("scroll corner");
2595 #endif
2596 #if PLATFORM(MAC) && USE(CA)
2597             m_layerForScrollCorner->setAcceleratesDrawing(acceleratedDrawingEnabled());
2598 #endif
2599             m_overflowControlsHostLayer->addChild(m_layerForScrollCorner.get());
2600         }
2601     } else if (m_layerForScrollCorner) {
2602         m_layerForScrollCorner->removeFromParent();
2603         m_layerForScrollCorner = nullptr;
2604     }
2605
2606     m_renderView->frameView()->positionScrollbarLayers();
2607 }
2608
2609 void RenderLayerCompositor::ensureRootLayer()
2610 {
2611     RootLayerAttachment expectedAttachment = shouldPropagateCompositingToEnclosingFrame() ? RootLayerAttachedViaEnclosingFrame : RootLayerAttachedViaChromeClient;
2612     if (expectedAttachment == m_rootLayerAttachment)
2613          return;
2614
2615     if (!m_rootContentLayer) {
2616         m_rootContentLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
2617 #ifndef NDEBUG
2618         m_rootContentLayer->setName("content root");
2619 #endif
2620         IntRect overflowRect = m_renderView->pixelSnappedLayoutOverflowRect();
2621         m_rootContentLayer->setSize(FloatSize(overflowRect.maxX(), overflowRect.maxY()));
2622         m_rootContentLayer->setPosition(FloatPoint());
2623
2624         // Need to clip to prevent transformed content showing outside this frame
2625         m_rootContentLayer->setMasksToBounds(true);
2626     }
2627
2628     if (requiresScrollLayer(expectedAttachment)) {
2629         if (!m_overflowControlsHostLayer) {
2630             ASSERT(!m_scrollLayer);
2631             ASSERT(!m_clipLayer);
2632
2633             // Create a layer to host the clipping layer and the overflow controls layers.
2634             m_overflowControlsHostLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
2635 #ifndef NDEBUG
2636             m_overflowControlsHostLayer->setName("overflow controls host");
2637 #endif
2638
2639             // Create a clipping layer if this is an iframe
2640             m_clipLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
2641 #ifndef NDEBUG
2642             m_clipLayer->setName("frame clipping");
2643 #endif
2644             m_clipLayer->setMasksToBounds(true);
2645             
2646             m_scrollLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
2647 #ifndef NDEBUG
2648             m_scrollLayer->setName("frame scrolling");
2649 #endif
2650             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2651                 scrollingCoordinator->setLayerIsContainerForFixedPositionLayers(m_scrollLayer.get(), true);
2652
2653             // Hook them up
2654             m_overflowControlsHostLayer->addChild(m_clipLayer.get());
2655             m_clipLayer->addChild(m_scrollLayer.get());
2656             m_scrollLayer->addChild(m_rootContentLayer.get());
2657
2658             frameViewDidChangeSize();
2659             frameViewDidScroll();
2660         }
2661     } else {
2662         if (m_overflowControlsHostLayer) {
2663             m_overflowControlsHostLayer = nullptr;
2664             m_clipLayer = nullptr;
2665             m_scrollLayer = nullptr;
2666         }
2667     }
2668
2669     // Check to see if we have to change the attachment
2670     if (m_rootLayerAttachment != RootLayerUnattached)
2671         detachRootLayer();
2672
2673     attachRootLayer(expectedAttachment);
2674 }
2675
2676 void RenderLayerCompositor::destroyRootLayer()
2677 {
2678     if (!m_rootContentLayer)
2679         return;
2680
2681     detachRootLayer();
2682
2683 #if ENABLE(RUBBER_BANDING)
2684     if (m_layerForOverhangAreas) {
2685         m_layerForOverhangAreas->removeFromParent();
2686         m_layerForOverhangAreas = nullptr;
2687     }
2688 #endif
2689
2690     if (m_layerForHorizontalScrollbar) {
2691         m_layerForHorizontalScrollbar->removeFromParent();
2692         m_layerForHorizontalScrollbar = nullptr;
2693         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2694             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView->frameView(), HorizontalScrollbar);
2695         if (Scrollbar* horizontalScrollbar = m_renderView->frameView()->verticalScrollbar())
2696             m_renderView->frameView()->invalidateScrollbar(horizontalScrollbar, IntRect(IntPoint(0, 0), horizontalScrollbar->frameRect().size()));
2697     }
2698
2699     if (m_layerForVerticalScrollbar) {
2700         m_layerForVerticalScrollbar->removeFromParent();
2701         m_layerForVerticalScrollbar = nullptr;
2702         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2703             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView->frameView(), VerticalScrollbar);
2704         if (Scrollbar* verticalScrollbar = m_renderView->frameView()->verticalScrollbar())
2705             m_renderView->frameView()->invalidateScrollbar(verticalScrollbar, IntRect(IntPoint(0, 0), verticalScrollbar->frameRect().size()));
2706     }
2707
2708     if (m_layerForScrollCorner) {
2709         m_layerForScrollCorner = nullptr;
2710         m_renderView->frameView()->invalidateScrollCorner(m_renderView->frameView()->scrollCornerRect());
2711     }
2712
2713     if (m_overflowControlsHostLayer) {
2714         m_overflowControlsHostLayer = nullptr;
2715         m_clipLayer = nullptr;
2716         m_scrollLayer = nullptr;
2717     }
2718     ASSERT(!m_scrollLayer);
2719     m_rootContentLayer = nullptr;
2720
2721     m_layerUpdater = nullptr;
2722 }
2723
2724 void RenderLayerCompositor::attachRootLayer(RootLayerAttachment attachment)
2725 {
2726     if (!m_rootContentLayer)
2727         return;
2728
2729     switch (attachment) {
2730         case RootLayerUnattached:
2731             ASSERT_NOT_REACHED();
2732             break;
2733         case RootLayerAttachedViaChromeClient: {
2734             Frame* frame = m_renderView->frameView()->frame();
2735             Page* page = frame ? frame->page() : 0;
2736             if (!page)
2737                 return;
2738
2739             page->chrome()->client()->attachRootGraphicsLayer(frame, rootGraphicsLayer());
2740             break;
2741         }
2742         case RootLayerAttachedViaEnclosingFrame: {
2743             // The layer will get hooked up via RenderLayerBacking::updateGraphicsLayerConfiguration()
2744             // for the frame's renderer in the parent document.
2745             m_renderView->document()->ownerElement()->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
2746             break;
2747         }
2748     }
2749
2750     m_rootLayerAttachment = attachment;
2751     rootLayerAttachmentChanged();
2752     
2753     if (m_shouldFlushOnReattach) {
2754         flushPendingLayerChanges(true);
2755         m_shouldFlushOnReattach = false;
2756     }
2757 }
2758
2759 void RenderLayerCompositor::detachRootLayer()
2760 {
2761     if (!m_rootContentLayer || m_rootLayerAttachment == RootLayerUnattached)
2762         return;
2763
2764     switch (m_rootLayerAttachment) {
2765     case RootLayerAttachedViaEnclosingFrame: {
2766         // The layer will get unhooked up via RenderLayerBacking::updateGraphicsLayerConfiguration()
2767         // for the frame's renderer in the parent document.
2768         if (m_overflowControlsHostLayer)
2769             m_overflowControlsHostLayer->removeFromParent();
2770         else
2771             m_rootContentLayer->removeFromParent();
2772
2773         if (HTMLFrameOwnerElement* ownerElement = m_renderView->document()->ownerElement())
2774             ownerElement->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
2775         break;
2776     }
2777     case RootLayerAttachedViaChromeClient: {
2778         Frame* frame = m_renderView->frameView()->frame();
2779         Page* page = frame ? frame->page() : 0;
2780         if (!page)
2781             return;
2782
2783         page->chrome()->client()->attachRootGraphicsLayer(frame, 0);
2784     }
2785     break;
2786     case RootLayerUnattached:
2787         break;
2788     }
2789
2790     m_rootLayerAttachment = RootLayerUnattached;
2791     rootLayerAttachmentChanged();
2792 }
2793
2794 void RenderLayerCompositor::updateRootLayerAttachment()
2795 {
2796     ensureRootLayer();
2797 }
2798
2799 void RenderLayerCompositor::rootLayerAttachmentChanged()
2800 {
2801     // The attachment can affect whether the RenderView layer's paintsIntoWindow() behavior,
2802     // so call updateGraphicsLayerGeometry() to udpate that.
2803     RenderLayer* layer = m_renderView->layer();
2804     if (RenderLayerBacking* backing = layer ? layer->backing() : 0)
2805         backing->updateDrawsContent();
2806 }
2807
2808 // IFrames are special, because we hook compositing layers together across iframe boundaries
2809 // when both parent and iframe content are composited. So when this frame becomes composited, we have
2810 // to use a synthetic style change to get the iframes into RenderLayers in order to allow them to composite.
2811 void RenderLayerCompositor::notifyIFramesOfCompositingChange()
2812 {
2813     Frame* frame = m_renderView->frameView() ? m_renderView->frameView()->frame() : 0;
2814     if (!frame)
2815         return;
2816
2817     for (Frame* child = frame->tree()->firstChild(); child; child = child->tree()->traverseNext(frame)) {
2818         if (child->document() && child->document()->ownerElement())
2819             child->document()->ownerElement()->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
2820     }
2821     
2822     // Compositing also affects the answer to RenderIFrame::requiresAcceleratedCompositing(), so 
2823     // we need to schedule a style recalc in our parent document.
2824     if (HTMLFrameOwnerElement* ownerElement = m_renderView->document()->ownerElement())
2825         ownerElement->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
2826 }
2827
2828 bool RenderLayerCompositor::layerHas3DContent(const RenderLayer* layer) const
2829 {
2830     const RenderStyle* style = layer->renderer()->style();
2831
2832     if (style && 
2833         (style->transformStyle3D() == TransformStyle3DPreserve3D ||
2834          style->hasPerspective() ||
2835          style->transform().has3DOperation()))
2836         return true;
2837
2838     const_cast<RenderLayer*>(layer)->updateLayerListsIfNeeded();
2839
2840 #if !ASSERT_DISABLED
2841     LayerListMutationDetector mutationChecker(const_cast<RenderLayer*>(layer));
2842 #endif
2843
2844     if (layer->isStackingContainer()) {
2845         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
2846             size_t listSize = negZOrderList->size();
2847             for (size_t i = 0; i < listSize; ++i) {
2848                 RenderLayer* curLayer = negZOrderList->at(i);
2849                 if (layerHas3DContent(curLayer))
2850                     return true;
2851             }
2852         }
2853
2854         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
2855             size_t listSize = posZOrderList->size();
2856             for (size_t i = 0; i < listSize; ++i) {
2857                 RenderLayer* curLayer = posZOrderList->at(i);
2858                 if (layerHas3DContent(curLayer))
2859                     return true;
2860             }
2861         }
2862     }
2863
2864     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
2865         size_t listSize = normalFlowList->size();
2866         for (size_t i = 0; i < listSize; ++i) {
2867             RenderLayer* curLayer = normalFlowList->at(i);
2868             if (layerHas3DContent(curLayer))
2869                 return true;
2870         }
2871     }
2872     return false;
2873 }
2874
2875 void RenderLayerCompositor::deviceOrPageScaleFactorChanged()
2876 {
2877     // Start at the RenderView's layer, since that's where the scale is applied.
2878     RenderLayer* viewLayer = m_renderView->layer();
2879     if (!viewLayer->isComposited())
2880         return;
2881
2882     if (GraphicsLayer* rootLayer = viewLayer->backing()->childForSuperlayers())
2883         rootLayer->noteDeviceOrPageScaleFactorChangedIncludingDescendants();
2884 }
2885
2886 static bool isRootmostFixedOrStickyLayer(RenderLayer* layer)
2887 {
2888     if (layer->renderer()->isStickyPositioned())
2889         return true;
2890
2891     if (layer->renderer()->style()->position() != FixedPosition)
2892         return false;
2893
2894     for (RenderLayer* stackingContainer = layer->stackingContainer(); stackingContainer; stackingContainer = stackingContainer->stackingContainer()) {
2895         if (stackingContainer->isComposited() && stackingContainer->renderer()->style()->position() == FixedPosition)
2896             return false;
2897     }
2898
2899     return true;
2900 }
2901
2902 void RenderLayerCompositor::updateViewportConstraintStatus(RenderLayer* layer)
2903 {
2904     if (isRootmostFixedOrStickyLayer(layer))
2905         addViewportConstrainedLayer(layer);
2906     else
2907         removeViewportConstrainedLayer(layer);
2908 }
2909
2910 void RenderLayerCompositor::addViewportConstrainedLayer(RenderLayer* layer)
2911 {
2912     m_viewportConstrainedLayers.add(layer);
2913     registerOrUpdateViewportConstrainedLayer(layer);
2914 }
2915
2916 void RenderLayerCompositor::removeViewportConstrainedLayer(RenderLayer* layer)
2917 {
2918     if (!m_viewportConstrainedLayers.contains(layer))
2919         return;
2920
2921     unregisterViewportConstrainedLayer(layer);
2922     m_viewportConstrainedLayers.remove(layer);
2923 }
2924
2925 FixedPositionViewportConstraints RenderLayerCompositor::computeFixedViewportConstraints(RenderLayer* layer) const
2926 {
2927     ASSERT(layer->isComposited());
2928
2929     FrameView* frameView = m_renderView->frameView();
2930     LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
2931
2932     FixedPositionViewportConstraints constraints;
2933
2934     GraphicsLayer* graphicsLayer = layer->backing()->graphicsLayer();
2935
2936     constraints.setLayerPositionAtLastLayout(graphicsLayer->position());
2937     constraints.setViewportRectAtLastLayout(viewportRect);
2938         
2939     RenderStyle* style = layer->renderer()->style();
2940     if (!style->left().isAuto())
2941         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeLeft);
2942
2943     if (!style->right().isAuto())
2944         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeRight);
2945
2946     if (!style->top().isAuto())
2947         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeTop);
2948
2949     if (!style->bottom().isAuto())
2950         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeBottom);
2951
2952     // If left and right are auto, use left.
2953     if (style->left().isAuto() && style->right().isAuto())
2954         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeLeft);
2955
2956     // If top and bottom are auto, use top.
2957     if (style->top().isAuto() && style->bottom().isAuto())
2958         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeTop);
2959         
2960     return constraints;
2961 }
2962
2963 StickyPositionViewportConstraints RenderLayerCompositor::computeStickyViewportConstraints(RenderLayer* layer) const
2964 {
2965     ASSERT(layer->isComposited());
2966
2967     FrameView* frameView = m_renderView->frameView();
2968     LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
2969
2970     StickyPositionViewportConstraints constraints;
2971
2972     RenderBoxModelObject* renderer = toRenderBoxModelObject(layer->renderer());
2973
2974     renderer->computeStickyPositionConstraints(constraints, viewportRect);
2975
2976     GraphicsLayer* graphicsLayer = layer->backing()->graphicsLayer();
2977
2978     constraints.setLayerPositionAtLastLayout(graphicsLayer->position());
2979     constraints.setStickyOffsetAtLastLayout(renderer->stickyPositionOffset());
2980
2981     return constraints;
2982 }
2983
2984 static RenderLayerBacking* nearestScrollingCoordinatorAncestor(RenderLayer* layer)
2985 {
2986     RenderLayer* ancestor = layer->parent();
2987     while (ancestor) {
2988         if (RenderLayerBacking* backing = ancestor->backing()) {
2989             if (backing->scrollLayerID() && !ancestor->scrollsOverflow())
2990                 return backing;
2991         }
2992         ancestor = ancestor->parent();
2993     }
2994
2995     return 0;
2996 }
2997
2998 void RenderLayerCompositor::registerOrUpdateViewportConstrainedLayer(RenderLayer* layer)
2999 {
3000     // FIXME: We should support sticky position here! And we should eventuall support fixed/sticky elements
3001     // that are inside non-main frames once we get non-main frames scrolling with the ScrollingCoordinator.
3002     if (m_renderView->document()->ownerElement())
3003         return;
3004
3005     ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator();
3006     if (!scrollingCoordinator)
3007         return;
3008
3009     // FIXME: rename to supportsViewportConstrainedPositionLayers()?
3010     if (!scrollingCoordinator->supportsFixedPositionLayers() || !layer->parent())
3011         return;
3012
3013     ASSERT(m_viewportConstrainedLayers.contains(layer));
3014     ASSERT(layer->isComposited());
3015
3016     RenderLayerBacking* backing = layer->backing();
3017     if (!backing)
3018         return;
3019
3020     ScrollingNodeID nodeID = backing->scrollLayerID();
3021     RenderLayerBacking* parent = nearestScrollingCoordinatorAncestor(layer);
3022     if (!parent)
3023         return;
3024
3025     // Always call this even if the backing is already attached because the parent may have changed.
3026     backing->attachToScrollingCoordinatorWithParent(parent);
3027     nodeID = backing->scrollLayerID();
3028
3029     if (layer->renderer()->isStickyPositioned())
3030         scrollingCoordinator->updateViewportConstrainedNode(nodeID, computeStickyViewportConstraints(layer), backing->graphicsLayer());
3031     else
3032         scrollingCoordinator->updateViewportConstrainedNode(nodeID, computeFixedViewportConstraints(layer), backing->graphicsLayer());
3033 }
3034
3035 void RenderLayerCompositor::unregisterViewportConstrainedLayer(RenderLayer* layer)
3036 {
3037     ASSERT(m_viewportConstrainedLayers.contains(layer));
3038
3039     if (RenderLayerBacking* backing = layer->backing())
3040         backing->detachFromScrollingCoordinator();
3041 }
3042
3043 void RenderLayerCompositor::windowScreenDidChange(PlatformDisplayID displayID)
3044 {
3045     if (m_layerUpdater)
3046         m_layerUpdater->screenDidChange(displayID);
3047 }
3048
3049 ScrollingCoordinator* RenderLayerCompositor::scrollingCoordinator() const
3050 {
3051     if (Page* page = this->page())
3052         return page->scrollingCoordinator();
3053
3054     return 0;
3055 }
3056
3057 GraphicsLayerFactory* RenderLayerCompositor::graphicsLayerFactory() const
3058 {
3059     if (Page* page = this->page())
3060         return page->chrome()->client()->graphicsLayerFactory();
3061
3062     return 0;
3063 }
3064
3065 Page* RenderLayerCompositor::page() const
3066 {
3067     if (Frame* frame = m_renderView->frameView()->frame())
3068         return frame->page();
3069     
3070     return 0;
3071 }
3072
3073 void RenderLayerCompositor::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
3074 {
3075     MemoryClassInfo info(memoryObjectInfo, this, PlatformMemoryTypes::Rendering);
3076     info.addWeakPointer(m_renderView);
3077     info.addMember(m_rootContentLayer, "rootContentLayer");
3078     info.addMember(m_updateCompositingLayersTimer, "updateCompositingLayersTimer");
3079     info.addMember(m_clipLayer, "clipLayer");
3080     info.addMember(m_scrollLayer, "scrollLayer");
3081     info.addMember(m_viewportConstrainedLayers, "viewportConstrainedLayers");
3082     info.addMember(m_viewportConstrainedLayersNeedingUpdate, "viewportConstrainedLayersNeedingUpdate");
3083     info.addMember(m_overflowControlsHostLayer, "overflowControlsHostLayer");
3084     info.addMember(m_layerForHorizontalScrollbar, "layerForHorizontalScrollbar");
3085     info.addMember(m_layerForVerticalScrollbar, "layerForVerticalScrollbar");
3086     info.addMember(m_layerForScrollCorner, "layerForScrollCorner");
3087 #if ENABLE(RUBBER_BANDING)
3088     info.addMember(m_layerForOverhangAreas, "layerForOverhangAreas");
3089     info.addMember(m_contentShadowLayer, "contentShadowLayer");
3090     info.addMember(m_layerForTopOverhangArea, "layerForTopOverhangArea");
3091     info.addMember(m_layerForBottomOverhangArea, "layerForBottomOverhangArea");
3092 #endif
3093     info.addMember(m_layerUpdater, "layerUpdater");
3094 }
3095
3096 } // namespace WebCore
3097
3098 #endif // USE(ACCELERATED_COMPOSITING)