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