e9cf230a990b28f4cb7f0f43a51f1b5a715332dc
[WebKit-https.git] / Source / WebCore / rendering / RenderLayerCompositor.cpp
1 /*
2  * Copyright (C) 2009, 2010 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27
28 #if USE(ACCELERATED_COMPOSITING)
29 #include "RenderLayerCompositor.h"
30
31 #include "AnimationController.h"
32 #include "CanvasRenderingContext.h"
33 #include "CSSPropertyNames.h"
34 #include "Chrome.h"
35 #include "ChromeClient.h"
36 #include "FlowThreadController.h"
37 #include "Frame.h"
38 #include "FrameView.h"
39 #include "GraphicsLayer.h"
40 #include "HTMLCanvasElement.h"
41 #include "HTMLIFrameElement.h"
42 #include "HTMLNames.h"
43 #include "HitTestResult.h"
44 #include "InspectorInstrumentation.h"
45 #include "Logging.h"
46 #include "NodeList.h"
47 #include "Page.h"
48 #include "RenderEmbeddedObject.h"
49 #include "RenderFlowThread.h"
50 #include "RenderFullScreen.h"
51 #include "RenderGeometryMap.h"
52 #include "RenderIFrame.h"
53 #include "RenderLayerBacking.h"
54 #include "RenderNamedFlowFragment.h"
55 #include "RenderReplica.h"
56 #include "RenderVideo.h"
57 #include "RenderView.h"
58 #include "ScrollingConstraints.h"
59 #include "ScrollingCoordinator.h"
60 #include "Settings.h"
61 #include "TiledBacking.h"
62 #include "TransformState.h"
63 #include <wtf/CurrentTime.h>
64 #include <wtf/TemporaryChange.h>
65 #include <wtf/text/CString.h>
66 #include <wtf/text/StringBuilder.h>
67
68 #if PLATFORM(IOS)
69 #include "MainFrame.h"
70 #include "Region.h"
71 #include "RenderScrollbar.h"
72 #include "TileCache.h"
73 #endif
74
75 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
76 #include "HTMLAudioElement.h"
77 #include "HTMLMediaElement.h"
78 #endif
79
80 #ifndef NDEBUG
81 #include "RenderTreeAsText.h"
82 #endif
83
84 #if ENABLE(3D_RENDERING)
85 // This symbol is used to determine from a script whether 3D rendering is enabled (via 'nm').
86 bool WebCoreHas3DRendering = true;
87 #endif
88
89 #if !PLATFORM(MAC) && !PLATFORM(IOS)
90 #define WTF_USE_COMPOSITING_FOR_SMALL_CANVASES 1
91 #endif
92
93 namespace WebCore {
94
95 static const int canvasAreaThresholdRequiringCompositing = 50 * 100;
96 // During page loading delay layer flushes up to this many seconds to allow them coalesce, reducing workload.
97 #if PLATFORM(IOS)
98 static const double throttledLayerFlushInitialDelay = .5;
99 static const double throttledLayerFlushDelay = 1.5;
100 #else
101 static const double throttledLayerFlushDelay = .5;
102 #endif
103
104 using namespace HTMLNames;
105
106 class RenderLayerCompositor::OverlapMap {
107     WTF_MAKE_NONCOPYABLE(OverlapMap);
108 public:
109     OverlapMap()
110         : m_geometryMap(UseTransforms)
111     {
112         // Begin assuming the root layer will be composited so that there is
113         // something on the stack. The root layer should also never get an
114         // popCompositingContainer call.
115         pushCompositingContainer();
116     }
117
118     void add(const RenderLayer* layer, const IntRect& bounds)
119     {
120         // Layers do not contribute to overlap immediately--instead, they will
121         // contribute to overlap as soon as their composited ancestor has been
122         // recursively processed and popped off the stack.
123         ASSERT(m_overlapStack.size() >= 2);
124         m_overlapStack[m_overlapStack.size() - 2].append(bounds);
125         m_layers.add(layer);
126     }
127
128     bool contains(const RenderLayer* layer)
129     {
130         return m_layers.contains(layer);
131     }
132
133     bool overlapsLayers(const IntRect& bounds) const
134     {
135         return m_overlapStack.last().intersects(bounds);
136     }
137
138     bool isEmpty()
139     {
140         return m_layers.isEmpty();
141     }
142
143     void pushCompositingContainer()
144     {
145         m_overlapStack.append(RectList());
146     }
147
148     void popCompositingContainer()
149     {
150         m_overlapStack[m_overlapStack.size() - 2].append(m_overlapStack.last());
151         m_overlapStack.removeLast();
152     }
153
154     RenderGeometryMap& geometryMap() { return m_geometryMap; }
155
156 private:
157     struct RectList {
158         Vector<IntRect> rects;
159         IntRect boundingRect;
160         
161         void append(const IntRect& rect)
162         {
163             rects.append(rect);
164             boundingRect.unite(rect);
165         }
166
167         void append(const RectList& rectList)
168         {
169             rects.appendVector(rectList.rects);
170             boundingRect.unite(rectList.boundingRect);
171         }
172         
173         bool intersects(const IntRect& rect) const
174         {
175             if (!rects.size() || !boundingRect.intersects(rect))
176                 return false;
177
178             for (unsigned i = 0; i < rects.size(); i++) {
179                 if (rects[i].intersects(rect))
180                     return true;
181             }
182             return false;
183         }
184     };
185
186     Vector<RectList> m_overlapStack;
187     HashSet<const RenderLayer*> m_layers;
188     RenderGeometryMap m_geometryMap;
189 };
190
191 struct CompositingState {
192     CompositingState(RenderLayer* compAncestor, bool testOverlap = true)
193         : m_compositingAncestor(compAncestor)
194         , m_subtreeIsCompositing(false)
195         , m_testingOverlap(testOverlap)
196         , m_subtreeHasBlending(false)
197 #ifndef NDEBUG
198         , m_depth(0)
199 #endif
200     {
201     }
202     
203     CompositingState(const CompositingState& other)
204         : m_compositingAncestor(other.m_compositingAncestor)
205         , m_subtreeIsCompositing(other.m_subtreeIsCompositing)
206         , m_testingOverlap(other.m_testingOverlap)
207         , m_subtreeHasBlending(other.m_subtreeHasBlending)
208 #ifndef NDEBUG
209         , m_depth(other.m_depth + 1)
210 #endif
211     {
212     }
213     
214     RenderLayer* m_compositingAncestor;
215     bool m_subtreeIsCompositing;
216     bool m_testingOverlap;
217     bool m_subtreeHasBlending;
218 #ifndef NDEBUG
219     int m_depth;
220 #endif
221 };
222
223
224 #if !LOG_DISABLED
225 static inline bool compositingLogEnabled()
226 {
227     return LogCompositing.state == WTFLogChannelOn;
228 }
229 #endif
230
231 RenderLayerCompositor::RenderLayerCompositor(RenderView& renderView)
232     : m_renderView(renderView)
233     , m_updateCompositingLayersTimer(this, &RenderLayerCompositor::updateCompositingLayersTimerFired)
234     , m_hasAcceleratedCompositing(true)
235     , m_compositingTriggers(static_cast<ChromeClient::CompositingTriggerFlags>(ChromeClient::AllTriggers))
236     , m_compositedLayerCount(0)
237     , m_showDebugBorders(false)
238     , m_showRepaintCounter(false)
239     , m_acceleratedDrawingEnabled(false)
240     , m_reevaluateCompositingAfterLayout(false)
241     , m_compositing(false)
242     , m_compositingLayersNeedRebuild(false)
243     , m_flushingLayers(false)
244     , m_shouldFlushOnReattach(false)
245     , m_forceCompositingMode(false)
246     , m_inPostLayoutUpdate(false)
247     , m_isTrackingRepaints(false)
248     , m_layersWithTiledBackingCount(0)
249     , m_rootLayerAttachment(RootLayerUnattached)
250     , m_layerFlushTimer(this, &RenderLayerCompositor::layerFlushTimerFired)
251     , m_layerFlushThrottlingEnabled(false)
252     , m_layerFlushThrottlingTemporarilyDisabledForInteraction(false)
253     , m_hasPendingLayerFlush(false)
254     , m_paintRelatedMilestonesTimer(this, &RenderLayerCompositor::paintRelatedMilestonesTimerFired)
255 #if !LOG_DISABLED
256     , m_rootLayerUpdateCount(0)
257     , m_obligateCompositedLayerCount(0)
258     , m_secondaryCompositedLayerCount(0)
259     , m_obligatoryBackingStoreBytes(0)
260     , m_secondaryBackingStoreBytes(0)
261 #endif
262 {
263 }
264
265 RenderLayerCompositor::~RenderLayerCompositor()
266 {
267     // Take care that the owned GraphicsLayers are deleted first as their destructors may call back here.
268     m_clipLayer = nullptr;
269     m_scrollLayer = nullptr;
270     ASSERT(m_rootLayerAttachment == RootLayerUnattached);
271 }
272
273 void RenderLayerCompositor::enableCompositingMode(bool enable /* = true */)
274 {
275     if (enable != m_compositing) {
276         m_compositing = enable;
277         
278         if (m_compositing) {
279             ensureRootLayer();
280             notifyIFramesOfCompositingChange();
281         } else
282             destroyRootLayer();
283     }
284 }
285
286 void RenderLayerCompositor::cacheAcceleratedCompositingFlags()
287 {
288     bool hasAcceleratedCompositing = false;
289     bool showDebugBorders = false;
290     bool showRepaintCounter = false;
291     bool forceCompositingMode = false;
292     bool acceleratedDrawingEnabled = false;
293
294     const Settings& settings = m_renderView.frameView().frame().settings();
295     hasAcceleratedCompositing = settings.acceleratedCompositingEnabled();
296
297     // We allow the chrome to override the settings, in case the page is rendered
298     // on a chrome that doesn't allow accelerated compositing.
299     if (hasAcceleratedCompositing) {
300         if (Page* page = this->page()) {
301             m_compositingTriggers = page->chrome().client().allowedCompositingTriggers();
302             hasAcceleratedCompositing = m_compositingTriggers;
303         }
304     }
305
306     showDebugBorders = settings.showDebugBorders();
307     showRepaintCounter = settings.showRepaintCounter();
308     forceCompositingMode = settings.forceCompositingMode() && hasAcceleratedCompositing;
309
310     if (forceCompositingMode && m_renderView.document().ownerElement())
311         forceCompositingMode = requiresCompositingForScrollableFrame();
312
313     acceleratedDrawingEnabled = settings.acceleratedDrawingEnabled();
314
315     if (hasAcceleratedCompositing != m_hasAcceleratedCompositing || showDebugBorders != m_showDebugBorders || showRepaintCounter != m_showRepaintCounter || forceCompositingMode != m_forceCompositingMode)
316         setCompositingLayersNeedRebuild();
317
318     bool debugBordersChanged = m_showDebugBorders != showDebugBorders;
319     m_hasAcceleratedCompositing = hasAcceleratedCompositing;
320     m_showDebugBorders = showDebugBorders;
321     m_showRepaintCounter = showRepaintCounter;
322     m_forceCompositingMode = forceCompositingMode;
323     m_acceleratedDrawingEnabled = acceleratedDrawingEnabled;
324     
325     if (debugBordersChanged) {
326         if (m_layerForHorizontalScrollbar)
327             m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
328
329         if (m_layerForVerticalScrollbar)
330             m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
331
332         if (m_layerForScrollCorner)
333             m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
334     }
335 }
336
337 bool RenderLayerCompositor::canRender3DTransforms() const
338 {
339     return hasAcceleratedCompositing() && (m_compositingTriggers & ChromeClient::ThreeDTransformTrigger);
340 }
341
342 void RenderLayerCompositor::setCompositingLayersNeedRebuild(bool needRebuild)
343 {
344     if (inCompositingMode())
345         m_compositingLayersNeedRebuild = needRebuild;
346 }
347
348 void RenderLayerCompositor::customPositionForVisibleRectComputation(const GraphicsLayer* graphicsLayer, FloatPoint& position) const
349 {
350     if (graphicsLayer != m_scrollLayer.get())
351         return;
352
353     FloatPoint scrollPosition = -position;
354
355     if (m_renderView.frameView().scrollBehaviorForFixedElements() == StickToDocumentBounds)
356         scrollPosition = m_renderView.frameView().constrainScrollPositionForOverhang(roundedIntPoint(scrollPosition));
357
358     position = -scrollPosition;
359 }
360
361 void RenderLayerCompositor::notifyFlushRequired(const GraphicsLayer* layer)
362 {
363     scheduleLayerFlush(layer->canThrottleLayerFlush());
364 }
365
366 void RenderLayerCompositor::scheduleLayerFlushNow()
367 {
368     m_hasPendingLayerFlush = false;
369     if (Page* page = this->page())
370         page->chrome().client().scheduleCompositingLayerFlush();
371 }
372
373 void RenderLayerCompositor::scheduleLayerFlush(bool canThrottle)
374 {
375     ASSERT(!m_flushingLayers);
376
377 #if PLATFORM(IOS)
378     if (canThrottle)
379         startInitialLayerFlushTimerIfNeeded();
380 #endif
381
382     if (canThrottle && isThrottlingLayerFlushes()) {
383         m_hasPendingLayerFlush = true;
384         return;
385     }
386     scheduleLayerFlushNow();
387 }
388
389 #if PLATFORM(IOS)
390 ChromeClient* RenderLayerCompositor::chromeClient() const
391 {
392     Page* page = m_renderView.frameView().frame().page();
393     if (!page)
394         return 0;
395     return &page->chrome().client();
396 }
397 #endif
398
399 void RenderLayerCompositor::flushPendingLayerChanges(bool isFlushRoot)
400 {
401     // FrameView::flushCompositingStateIncludingSubframes() flushes each subframe,
402     // but GraphicsLayer::flushCompositingState() will cross frame boundaries
403     // if the GraphicsLayers are connected (the RootLayerAttachedViaEnclosingFrame case).
404     // As long as we're not the root of the flush, we can bail.
405     if (!isFlushRoot && rootLayerAttachment() == RootLayerAttachedViaEnclosingFrame)
406         return;
407     
408     if (rootLayerAttachment() == RootLayerUnattached) {
409 #if PLATFORM(IOS)
410         startLayerFlushTimerIfNeeded();
411 #endif
412         m_shouldFlushOnReattach = true;
413         return;
414     }
415
416     FrameView& frameView = m_renderView.frameView();
417     AnimationUpdateBlock animationUpdateBlock(&frameView.frame().animation());
418
419     ASSERT(!m_flushingLayers);
420     m_flushingLayers = true;
421
422     if (GraphicsLayer* rootLayer = rootGraphicsLayer()) {
423 #if PLATFORM(IOS)
424         rootLayer->flushCompositingState(frameView.visibleExtentContentRect());
425 #else
426         // Having a m_clipLayer indicates that we're doing scrolling via GraphicsLayers.
427         IntRect visibleRect = m_clipLayer ? IntRect(IntPoint(), frameView.contentsSize()) : frameView.visibleContentRect();
428         rootLayer->flushCompositingState(visibleRect);
429 #endif
430     }
431     
432     ASSERT(m_flushingLayers);
433     m_flushingLayers = false;
434
435 #if PLATFORM(IOS)
436     updateCustomLayersAfterFlush();
437
438     ChromeClient* client = this->chromeClient();
439     if (client && isFlushRoot)
440         client->didFlushCompositingLayers();
441 #else
442     for (auto it = m_viewportConstrainedLayersNeedingUpdate.begin(), end = m_viewportConstrainedLayersNeedingUpdate.end(); it != end; ++it)
443         registerOrUpdateViewportConstrainedLayer(**it);
444     m_viewportConstrainedLayersNeedingUpdate.clear();
445 #endif
446     startLayerFlushTimerIfNeeded();
447 }
448
449 #if PLATFORM(IOS)
450 static bool scrollbarHasDisplayNone(Scrollbar* scrollbar)
451 {
452     if (!scrollbar || !scrollbar->isCustomScrollbar())
453         return false;
454
455     RefPtr<RenderStyle> scrollbarStyle = static_cast<RenderScrollbar*>(scrollbar)->getScrollbarPseudoStyle(ScrollbarBGPart, SCROLLBAR);
456     return scrollbarStyle && scrollbarStyle->display() == NONE;
457 }
458
459 // FIXME: Can we make |layer| const RenderLayer&?
460 static void updateScrollingLayerWithClient(RenderLayer& layer, ChromeClient* client)
461 {
462     if (!client)
463         return;
464
465     RenderLayerBacking* backing = layer.backing();
466     ASSERT(backing);
467
468     bool allowHorizontalScrollbar = !scrollbarHasDisplayNone(layer.horizontalScrollbar());
469     bool allowVerticalScrollbar = !scrollbarHasDisplayNone(layer.verticalScrollbar());
470     client->addOrUpdateScrollingLayer(layer.renderer().element(), backing->scrollingLayer()->platformLayer(), backing->scrollingContentsLayer()->platformLayer(),
471         IntSize(layer.scrollWidth(), layer.scrollHeight()), allowHorizontalScrollbar, allowVerticalScrollbar);
472 }
473
474 void RenderLayerCompositor::updateCustomLayersAfterFlush()
475 {
476     registerAllViewportConstrainedLayers();
477
478     if (!m_scrollingLayersNeedingUpdate.isEmpty()) {
479         ChromeClient* chromeClient = this->chromeClient();
480
481         for (auto it = m_scrollingLayersNeedingUpdate.begin(), end = m_scrollingLayersNeedingUpdate.end(); it != end; ++it)
482             updateScrollingLayerWithClient(**it, chromeClient);
483         m_scrollingLayersNeedingUpdate.clear();
484     }
485     m_scrollingLayersNeedingUpdate.clear();
486 }
487 #endif
488
489 void RenderLayerCompositor::didFlushChangesForLayer(RenderLayer& layer, const GraphicsLayer* graphicsLayer)
490 {
491     if (m_viewportConstrainedLayers.contains(&layer))
492         m_viewportConstrainedLayersNeedingUpdate.add(&layer);
493
494 #if PLATFORM(IOS)
495     if (m_scrollingLayers.contains(&layer))
496         m_scrollingLayersNeedingUpdate.add(&layer);
497 #endif
498
499     RenderLayerBacking* backing = layer.backing();
500     if (backing->backgroundLayerPaintsFixedRootBackground() && graphicsLayer == backing->backgroundLayer())
501         fixedRootBackgroundLayerChanged();
502 }
503
504 void RenderLayerCompositor::didPaintBacking(RenderLayerBacking*)
505 {
506     FrameView& frameView = m_renderView.frameView();
507     frameView.setLastPaintTime(monotonicallyIncreasingTime());
508     if (frameView.milestonesPendingPaint() && !m_paintRelatedMilestonesTimer.isActive())
509         m_paintRelatedMilestonesTimer.startOneShot(0);
510 }
511
512 void RenderLayerCompositor::didChangeVisibleRect()
513 {
514     GraphicsLayer* rootLayer = rootGraphicsLayer();
515     if (!rootLayer)
516         return;
517
518     const FrameView& frameView = m_renderView.frameView();
519
520 #if PLATFORM(IOS)
521     IntRect visibleRect = frameView.visibleExtentContentRect();
522 #else
523     IntRect visibleRect = m_clipLayer ? IntRect(IntPoint(), frameView.contentsSize()) : frameView.visibleContentRect();
524 #endif
525     if (!rootLayer->visibleRectChangeRequiresFlush(visibleRect))
526         return;
527     scheduleLayerFlushNow();
528 }
529
530 void RenderLayerCompositor::notifyFlushBeforeDisplayRefresh(const GraphicsLayer*)
531 {
532     if (!m_layerUpdater) {
533         PlatformDisplayID displayID = 0;
534         if (Page* page = this->page())
535             displayID = page->chrome().displayID();
536
537         m_layerUpdater = adoptPtr(new GraphicsLayerUpdater(this, displayID));
538     }
539     
540     m_layerUpdater->scheduleUpdate();
541 }
542
543 void RenderLayerCompositor::flushLayers(GraphicsLayerUpdater*)
544 {
545     flushPendingLayerChanges(true); // FIXME: deal with iframes
546 }
547
548 void RenderLayerCompositor::layerTiledBackingUsageChanged(const GraphicsLayer*, bool usingTiledBacking)
549 {
550     if (usingTiledBacking)
551         ++m_layersWithTiledBackingCount;
552     else {
553         ASSERT(m_layersWithTiledBackingCount > 0);
554         --m_layersWithTiledBackingCount;
555     }
556 }
557
558 RenderLayerCompositor* RenderLayerCompositor::enclosingCompositorFlushingLayers() const
559 {
560     for (Frame* frame = &m_renderView.frameView().frame(); frame; frame = frame->tree().parent()) {
561         RenderLayerCompositor* compositor = frame->contentRenderer() ? &frame->contentRenderer()->compositor() : 0;
562         if (compositor->isFlushingLayers())
563             return compositor;
564     }
565     
566     return 0;
567 }
568
569 void RenderLayerCompositor::scheduleCompositingLayerUpdate()
570 {
571     if (!m_updateCompositingLayersTimer.isActive())
572         m_updateCompositingLayersTimer.startOneShot(0);
573 }
574
575 void RenderLayerCompositor::updateCompositingLayersTimerFired(Timer<RenderLayerCompositor>&)
576 {
577     updateCompositingLayers(CompositingUpdateAfterLayout);
578 }
579
580 bool RenderLayerCompositor::hasAnyAdditionalCompositedLayers(const RenderLayer& rootLayer) const
581 {
582     return m_compositedLayerCount > (rootLayer.isComposited() ? 1 : 0);
583 }
584
585 void RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType updateType, RenderLayer* updateRoot)
586 {
587     m_updateCompositingLayersTimer.stop();
588     
589     // Compositing layers will be updated in Document::implicitClose() if suppressed here.
590     if (!m_renderView.document().visualUpdatesAllowed())
591         return;
592
593     // Avoid updating the layers with old values. Compositing layers will be updated after the layout is finished.
594     if (m_renderView.needsLayout())
595         return;
596
597     if (m_forceCompositingMode && !m_compositing)
598         enableCompositingMode(true);
599
600     if (!m_reevaluateCompositingAfterLayout && !m_compositing)
601         return;
602
603     AnimationUpdateBlock animationUpdateBlock(&m_renderView.frameView().frame().animation());
604
605     TemporaryChange<bool> postLayoutChange(m_inPostLayoutUpdate, true);
606     
607     bool checkForHierarchyUpdate = m_reevaluateCompositingAfterLayout;
608     bool needGeometryUpdate = false;
609
610     switch (updateType) {
611     case CompositingUpdateAfterStyleChange:
612     case CompositingUpdateAfterLayout:
613     case CompositingUpdateOnHitTest:
614         checkForHierarchyUpdate = true;
615         break;
616     case CompositingUpdateOnScroll:
617         checkForHierarchyUpdate = true; // Overlap can change with scrolling, so need to check for hierarchy updates.
618
619         needGeometryUpdate = true;
620         break;
621     case CompositingUpdateOnCompositedScroll:
622         needGeometryUpdate = true;
623         break;
624     }
625
626     if (!checkForHierarchyUpdate && !needGeometryUpdate)
627         return;
628
629     bool needHierarchyUpdate = m_compositingLayersNeedRebuild;
630     bool isFullUpdate = !updateRoot;
631
632     // Only clear the flag if we're updating the entire hierarchy.
633     m_compositingLayersNeedRebuild = false;
634     updateRoot = &rootRenderLayer();
635
636     if (isFullUpdate && updateType == CompositingUpdateAfterLayout)
637         m_reevaluateCompositingAfterLayout = false;
638
639 #if !LOG_DISABLED
640     double startTime = 0;
641     if (compositingLogEnabled()) {
642         ++m_rootLayerUpdateCount;
643         startTime = monotonicallyIncreasingTime();
644     }
645 #endif
646
647     if (checkForHierarchyUpdate) {
648         if (isFullUpdate)
649             updateRenderFlowThreadLayersIfNeeded();
650         // Go through the layers in presentation order, so that we can compute which RenderLayers need compositing layers.
651         // FIXME: we could maybe do this and the hierarchy udpate in one pass, but the parenting logic would be more complex.
652         CompositingState compState(updateRoot);
653         bool layersChanged = false;
654         bool saw3DTransform = false;
655         OverlapMap overlapTestRequestMap;
656         computeCompositingRequirements(nullptr, *updateRoot, &overlapTestRequestMap, compState, layersChanged, saw3DTransform);
657         needHierarchyUpdate |= layersChanged;
658     }
659
660 #if !LOG_DISABLED
661     if (compositingLogEnabled() && isFullUpdate && (needHierarchyUpdate || needGeometryUpdate)) {
662         m_obligateCompositedLayerCount = 0;
663         m_secondaryCompositedLayerCount = 0;
664         m_obligatoryBackingStoreBytes = 0;
665         m_secondaryBackingStoreBytes = 0;
666
667         Frame& frame = m_renderView.frameView().frame();
668         bool isMainFrame = !m_renderView.document().ownerElement();
669         LOG(Compositing, "\nUpdate %d of %s.\n", m_rootLayerUpdateCount, isMainFrame ? "main frame" : frame.tree().uniqueName().string().utf8().data());
670     }
671 #endif
672
673     if (needHierarchyUpdate) {
674         // Update the hierarchy of the compositing layers.
675         Vector<GraphicsLayer*> childList;
676         rebuildCompositingLayerTree(*updateRoot, childList, 0);
677
678         // Host the document layer in the RenderView's root layer.
679         if (isFullUpdate) {
680             // Even when childList is empty, don't drop out of compositing mode if there are
681             // composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
682             if (childList.isEmpty() && !hasAnyAdditionalCompositedLayers(*updateRoot))
683                 destroyRootLayer();
684             else
685                 m_rootContentLayer->setChildren(childList);
686         }
687     } else if (needGeometryUpdate) {
688         // We just need to do a geometry update. This is only used for position:fixed scrolling;
689         // most of the time, geometry is updated via RenderLayer::styleChanged().
690         updateLayerTreeGeometry(*updateRoot, 0);
691     }
692     
693 #if !LOG_DISABLED
694     if (compositingLogEnabled() && isFullUpdate && (needHierarchyUpdate || needGeometryUpdate)) {
695         double endTime = monotonicallyIncreasingTime();
696         LOG(Compositing, "Total layers   primary   secondary   obligatory backing (KB)   secondary backing(KB)   total backing (KB)  update time (ms)\n");
697
698         LOG(Compositing, "%8d %11d %9d %20.2f %22.2f %22.2f %18.2f\n",
699             m_obligateCompositedLayerCount + m_secondaryCompositedLayerCount, m_obligateCompositedLayerCount,
700             m_secondaryCompositedLayerCount, m_obligatoryBackingStoreBytes / 1024, m_secondaryBackingStoreBytes / 1024, (m_obligatoryBackingStoreBytes + m_secondaryBackingStoreBytes) / 1024, 1000.0 * (endTime - startTime));
701     }
702 #endif
703     ASSERT(updateRoot || !m_compositingLayersNeedRebuild);
704
705     if (!hasAcceleratedCompositing())
706         enableCompositingMode(false);
707
708     // Inform the inspector that the layer tree has changed.
709     InspectorInstrumentation::layerTreeDidChange(page());
710 }
711
712 void RenderLayerCompositor::updateRenderFlowThreadLayersIfNeeded()
713 {
714     if (m_renderView.hasRenderNamedFlowThreads())
715         m_renderView.flowThreadController().updateRenderFlowThreadLayersIfNeeded();
716 }
717
718 void RenderLayerCompositor::layerBecameNonComposited(const RenderLayer& layer)
719 {
720     // Inform the inspector that the given RenderLayer was destroyed.
721     InspectorInstrumentation::renderLayerDestroyed(page(), &layer);
722
723     ASSERT(m_compositedLayerCount > 0);
724     --m_compositedLayerCount;
725 }
726
727 #if !LOG_DISABLED
728 void RenderLayerCompositor::logLayerInfo(const RenderLayer& layer, int depth)
729 {
730     if (!compositingLogEnabled())
731         return;
732
733     RenderLayerBacking* backing = layer.backing();
734     if (requiresCompositingLayer(layer) || layer.isRootLayer()) {
735         ++m_obligateCompositedLayerCount;
736         m_obligatoryBackingStoreBytes += backing->backingStoreMemoryEstimate();
737     } else {
738         ++m_secondaryCompositedLayerCount;
739         m_secondaryBackingStoreBytes += backing->backingStoreMemoryEstimate();
740     }
741
742     StringBuilder logString;
743     logString.append(String::format("%*p %dx%d %.2fKB", 12 + depth * 2, &layer,
744         backing->compositedBounds().width().round(), backing->compositedBounds().height().round(),
745         backing->backingStoreMemoryEstimate() / 1024));
746     
747     logString.append(" (");
748     logString.append(logReasonsForCompositing(layer));
749     logString.append(") ");
750
751     if (backing->graphicsLayer()->contentsOpaque() || backing->paintsIntoCompositedAncestor()) {
752         logString.append('[');
753         if (backing->graphicsLayer()->contentsOpaque())
754             logString.append("opaque");
755         if (backing->paintsIntoCompositedAncestor())
756             logString.append("paints into ancestor");
757         logString.append("] ");
758     }
759
760     logString.append(layer.name());
761
762     LOG(Compositing, "%s", logString.toString().utf8().data());
763 }
764 #endif
765
766 bool RenderLayerCompositor::updateBacking(RenderLayer& layer, CompositingChangeRepaint shouldRepaint)
767 {
768     bool layerChanged = false;
769     RenderLayer::ViewportConstrainedNotCompositedReason viewportConstrainedNotCompositedReason = RenderLayer::NoNotCompositedReason;
770
771     if (needsToBeComposited(layer, &viewportConstrainedNotCompositedReason)) {
772         enableCompositingMode();
773         
774         if (!layer.backing()) {
775             // If we need to repaint, do so before making backing
776             if (shouldRepaint == CompositingChangeRepaintNow)
777                 repaintOnCompositingChange(layer);
778
779             layer.ensureBacking();
780
781             // At this time, the ScrollingCoordinator only supports the top-level frame.
782             if (layer.isRootLayer() && !m_renderView.document().ownerElement()) {
783                 layer.backing()->attachToScrollingCoordinatorWithParent(0);
784                 if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
785                     scrollingCoordinator->frameViewRootLayerDidChange(&m_renderView.frameView());
786 #if ENABLE(RUBBER_BANDING)
787                 if (Page* page = this->page()) {
788                     updateLayerForHeader(page->headerHeight());
789                     updateLayerForFooter(page->footerHeight());
790                 }
791 #endif
792                 if (mainFrameBackingIsTiledWithMargin())
793                     m_rootContentLayer->setMasksToBounds(false);
794             }
795
796             // This layer and all of its descendants have cached repaints rects that are relative to
797             // the repaint container, so change when compositing changes; we need to update them here.
798             if (layer.parent())
799                 layer.computeRepaintRectsIncludingDescendants();
800
801             layerChanged = true;
802         }
803     } else {
804         if (layer.backing()) {
805             // If we're removing backing on a reflection, clear the source GraphicsLayer's pointer to
806             // its replica GraphicsLayer. In practice this should never happen because reflectee and reflection 
807             // are both either composited, or not composited.
808             if (layer.isReflection()) {
809                 RenderLayer* sourceLayer = toRenderLayerModelObject(layer.renderer().parent())->layer();
810                 if (RenderLayerBacking* backing = sourceLayer->backing()) {
811                     ASSERT(backing->graphicsLayer()->replicaLayer() == layer.backing()->graphicsLayer());
812                     backing->graphicsLayer()->setReplicatedByLayer(0);
813                 }
814             }
815
816             removeViewportConstrainedLayer(layer);
817             
818             layer.clearBacking();
819             layerChanged = true;
820
821             // This layer and all of its descendants have cached repaints rects that are relative to
822             // the repaint container, so change when compositing changes; we need to update them here.
823             layer.computeRepaintRectsIncludingDescendants();
824
825             // If we need to repaint, do so now that we've removed the backing
826             if (shouldRepaint == CompositingChangeRepaintNow)
827                 repaintOnCompositingChange(layer);
828         }
829     }
830     
831 #if ENABLE(VIDEO)
832     if (layerChanged && layer.renderer().isVideo()) {
833         // If it's a video, give the media player a chance to hook up to the layer.
834         toRenderVideo(layer.renderer()).acceleratedRenderingStateChanged();
835     }
836 #endif
837
838     if (layerChanged && layer.renderer().isWidget()) {
839         RenderLayerCompositor* innerCompositor = frameContentsCompositor(toRenderWidget(&layer.renderer()));
840         if (innerCompositor && innerCompositor->inCompositingMode())
841             innerCompositor->updateRootLayerAttachment();
842     }
843     
844     if (layerChanged)
845         layer.clearClipRectsIncludingDescendants(PaintingClipRects);
846
847     // If a fixed position layer gained/lost a backing or the reason not compositing it changed,
848     // the scrolling coordinator needs to recalculate whether it can do fast scrolling.
849     if (layer.renderer().style().position() == FixedPosition) {
850         if (layer.viewportConstrainedNotCompositedReason() != viewportConstrainedNotCompositedReason) {
851             layer.setViewportConstrainedNotCompositedReason(viewportConstrainedNotCompositedReason);
852             layerChanged = true;
853         }
854         if (layerChanged) {
855             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
856                 scrollingCoordinator->frameViewFixedObjectsDidChange(&m_renderView.frameView());
857         }
858     } else
859         layer.setViewportConstrainedNotCompositedReason(RenderLayer::NoNotCompositedReason);
860     
861     if (layer.backing())
862         layer.backing()->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
863
864     return layerChanged;
865 }
866
867 bool RenderLayerCompositor::updateLayerCompositingState(RenderLayer& layer, CompositingChangeRepaint shouldRepaint)
868 {
869     bool layerChanged = updateBacking(layer, shouldRepaint);
870
871     // See if we need content or clipping layers. Methods called here should assume
872     // that the compositing state of descendant layers has not been updated yet.
873     if (layer.backing() && layer.backing()->updateGraphicsLayerConfiguration())
874         layerChanged = true;
875
876     return layerChanged;
877 }
878
879 void RenderLayerCompositor::repaintOnCompositingChange(RenderLayer& layer)
880 {
881     // If the renderer is not attached yet, no need to repaint.
882     if (&layer.renderer() != &m_renderView && !layer.renderer().parent())
883         return;
884
885     RenderLayerModelObject* repaintContainer = layer.renderer().containerForRepaint();
886     if (!repaintContainer)
887         repaintContainer = &m_renderView;
888
889     layer.repaintIncludingNonCompositingDescendants(repaintContainer);
890     if (repaintContainer == &m_renderView) {
891         // The contents of this layer may be moving between the window
892         // and a GraphicsLayer, so we need to make sure the window system
893         // synchronizes those changes on the screen.
894         m_renderView.frameView().setNeedsOneShotDrawingSynchronization();
895     }
896 }
897
898 // This method assumes that layout is up-to-date, unlike repaintOnCompositingChange().
899 void RenderLayerCompositor::repaintInCompositedAncestor(RenderLayer& layer, const LayoutRect& rect)
900 {
901     RenderLayer* compositedAncestor = layer.enclosingCompositingLayerForRepaint(ExcludeSelf);
902     if (compositedAncestor) {
903         ASSERT(compositedAncestor->backing());
904
905         LayoutPoint offset;
906         layer.convertToLayerCoords(compositedAncestor, offset);
907
908         LayoutRect repaintRect = rect;
909         repaintRect.moveBy(offset);
910
911         compositedAncestor->setBackingNeedsRepaintInRect(repaintRect);
912     }
913
914     // The contents of this layer may be moving from a GraphicsLayer to the window,
915     // so we need to make sure the window system synchronizes those changes on the screen.
916     if (compositedAncestor == m_renderView.layer())
917         m_renderView.frameView().setNeedsOneShotDrawingSynchronization();
918 }
919
920 // The bounds of the GraphicsLayer created for a compositing layer is the union of the bounds of all the descendant
921 // RenderLayers that are rendered by the composited RenderLayer.
922 LayoutRect RenderLayerCompositor::calculateCompositedBounds(const RenderLayer& layer, const RenderLayer& ancestorLayer) const
923 {
924     if (!canBeComposited(layer))
925         return LayoutRect();
926     return layer.calculateLayerBounds(&ancestorLayer, nullptr, RenderLayer::DefaultCalculateLayerBoundsFlags | RenderLayer::ExcludeHiddenDescendants | RenderLayer::DontConstrainForMask);
927 }
928
929 void RenderLayerCompositor::layerWasAdded(RenderLayer&, RenderLayer&)
930 {
931     setCompositingLayersNeedRebuild();
932 }
933
934 void RenderLayerCompositor::layerWillBeRemoved(RenderLayer& parent, RenderLayer& child)
935 {
936     if (!child.isComposited() || parent.renderer().documentBeingDestroyed())
937         return;
938
939     removeViewportConstrainedLayer(child);
940     repaintInCompositedAncestor(child, child.backing()->compositedBounds());
941
942     setCompositingParent(child, nullptr);
943     setCompositingLayersNeedRebuild();
944 }
945
946 RenderLayer* RenderLayerCompositor::enclosingNonStackingClippingLayer(const RenderLayer& layer) const
947 {
948     for (RenderLayer* parent = layer.parent(); parent; parent = parent->parent()) {
949         if (parent->isStackingContainer())
950             return nullptr;
951         if (parent->renderer().hasClipOrOverflowClip())
952             return parent;
953     }
954     return nullptr;
955 }
956
957 void RenderLayerCompositor::addToOverlapMap(OverlapMap& overlapMap, RenderLayer& layer, IntRect& layerBounds, bool& boundsComputed)
958 {
959     if (layer.isRootLayer())
960         return;
961
962     if (!boundsComputed) {
963         // FIXME: If this layer's overlap bounds include its children, we don't need to add its
964         // children's bounds to the overlap map.
965         layerBounds = enclosingIntRect(overlapMap.geometryMap().absoluteRect(layer.overlapBounds()));
966         // Empty rects never intersect, but we need them to for the purposes of overlap testing.
967         if (layerBounds.isEmpty())
968             layerBounds.setSize(IntSize(1, 1));
969         boundsComputed = true;
970     }
971
972     IntRect clipRect = pixelSnappedIntRect(layer.backgroundClipRect(RenderLayer::ClipRectsContext(&rootRenderLayer(), 0, AbsoluteClipRects)).rect()); // FIXME: Incorrect for CSS regions.
973
974     // On iOS, pageScaleFactor() is not applied by RenderView, so we should not scale here.
975     // FIXME: Set Settings::delegatesPageScaling to true for iOS.
976 #if !PLATFORM(IOS)
977     const Settings& settings = m_renderView.frameView().frame().settings();
978     if (!settings.delegatesPageScaling())
979         clipRect.scale(pageScaleFactor());
980 #endif
981     clipRect.intersect(layerBounds);
982     overlapMap.add(&layer, clipRect);
983 }
984
985 void RenderLayerCompositor::addToOverlapMapRecursive(OverlapMap& overlapMap, RenderLayer& layer, RenderLayer* ancestorLayer)
986 {
987     if (!canBeComposited(layer) || overlapMap.contains(&layer))
988         return;
989
990     // A null ancestorLayer is an indication that 'layer' has already been pushed.
991     if (ancestorLayer)
992         overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer);
993     
994     IntRect bounds;
995     bool haveComputedBounds = false;
996     addToOverlapMap(overlapMap, layer, bounds, haveComputedBounds);
997
998 #if !ASSERT_DISABLED
999     LayerListMutationDetector mutationChecker(&layer);
1000 #endif
1001
1002     if (layer.isStackingContainer()) {
1003         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1004             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i)
1005                 addToOverlapMapRecursive(overlapMap, *negZOrderList->at(i), &layer);
1006         }
1007     }
1008
1009     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1010         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i)
1011             addToOverlapMapRecursive(overlapMap, *normalFlowList->at(i), &layer);
1012     }
1013
1014     if (layer.isStackingContainer()) {
1015         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1016             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i)
1017                 addToOverlapMapRecursive(overlapMap, *posZOrderList->at(i), &layer);
1018         }
1019     }
1020     
1021     if (ancestorLayer)
1022         overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
1023 }
1024
1025 //  Recurse through the layers in z-index and overflow order (which is equivalent to painting order)
1026 //  For the z-order children of a compositing layer:
1027 //      If a child layers has a compositing layer, then all subsequent layers must
1028 //      be compositing in order to render above that layer.
1029 //
1030 //      If a child in the negative z-order list is compositing, then the layer itself
1031 //      must be compositing so that its contents render over that child.
1032 //      This implies that its positive z-index children must also be compositing.
1033 //
1034 void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer& layer, OverlapMap* overlapMap, CompositingState& compositingState, bool& layersChanged, bool& descendantHas3DTransform)
1035 {
1036     layer.updateDescendantDependentFlags();
1037     layer.updateLayerListsIfNeeded();
1038
1039     if (layer.isFlowThreadCollectingGraphicsLayersUnderRegions()) {
1040         RenderFlowThread& flowThread = toRenderFlowThread(layer.renderer());
1041         layer.setHasCompositingDescendant(flowThread.hasCompositingRegionDescendant());
1042
1043         // Before returning, we need to update the lists of all child layers. This is required because,
1044         // if this flow thread will not be painted (for instance because of having no regions, or only invalid regions),
1045         // the child layers will never have their lists updated (which would normally happen during painting).
1046         layer.updateDescendantsLayerListsIfNeeded(true);
1047
1048         return;
1049     }
1050
1051     if (overlapMap)
1052         overlapMap->geometryMap().pushMappingsToAncestor(&layer, ancestorLayer);
1053     
1054     // Clear the flag
1055     layer.setHasCompositingDescendant(false);
1056
1057     RenderLayer::IndirectCompositingReason compositingReason = compositingState.m_subtreeIsCompositing ? RenderLayer::IndirectCompositingForStacking : RenderLayer::NoIndirectCompositingReason;
1058
1059     bool haveComputedBounds = false;
1060     IntRect absBounds;
1061     if (overlapMap && !overlapMap->isEmpty() && compositingState.m_testingOverlap) {
1062         // If we're testing for overlap, we only need to composite if we overlap something that is already composited.
1063         absBounds = enclosingIntRect(overlapMap->geometryMap().absoluteRect(layer.overlapBounds()));
1064
1065         // Empty rects never intersect, but we need them to for the purposes of overlap testing.
1066         if (absBounds.isEmpty())
1067             absBounds.setSize(IntSize(1, 1));
1068         haveComputedBounds = true;
1069         compositingReason = overlapMap->overlapsLayers(absBounds) ? RenderLayer::IndirectCompositingForOverlap : RenderLayer::NoIndirectCompositingReason;
1070     }
1071
1072 #if ENABLE(VIDEO)
1073     // Video is special. It's the only RenderLayer type that can both have
1074     // RenderLayer children and whose children can't use its backing to render
1075     // into. These children (the controls) always need to be promoted into their
1076     // own layers to draw on top of the accelerated video.
1077     if (compositingState.m_compositingAncestor && compositingState.m_compositingAncestor->renderer().isVideo())
1078         compositingReason = RenderLayer::IndirectCompositingForOverlap;
1079 #endif
1080
1081     layer.setIndirectCompositingReason(compositingReason);
1082
1083     // The children of this layer don't need to composite, unless there is
1084     // a compositing layer among them, so start by inheriting the compositing
1085     // ancestor with m_subtreeIsCompositing set to false.
1086     CompositingState childState(compositingState);
1087     childState.m_subtreeIsCompositing = false;
1088
1089     bool willBeComposited = needsToBeComposited(layer);
1090     if (willBeComposited) {
1091         // Tell the parent it has compositing descendants.
1092         compositingState.m_subtreeIsCompositing = true;
1093         // This layer now acts as the ancestor for kids.
1094         childState.m_compositingAncestor = &layer;
1095
1096         if (overlapMap)
1097             overlapMap->pushCompositingContainer();
1098         // This layer is going to be composited, so children can safely ignore the fact that there's an 
1099         // animation running behind this layer, meaning they can rely on the overlap map testing again.
1100         childState.m_testingOverlap = true;
1101     }
1102
1103 #if !ASSERT_DISABLED
1104     LayerListMutationDetector mutationChecker(&layer);
1105 #endif
1106
1107     bool anyDescendantHas3DTransform = false;
1108
1109     if (layer.isStackingContainer()) {
1110         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1111             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i) {
1112                 computeCompositingRequirements(&layer, *negZOrderList->at(i), overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1113
1114                 // If we have to make a layer for this child, make one now so we can have a contents layer
1115                 // (since we need to ensure that the -ve z-order child renders underneath our contents).
1116                 if (!willBeComposited && childState.m_subtreeIsCompositing) {
1117                     // make layer compositing
1118                     layer.setIndirectCompositingReason(RenderLayer::IndirectCompositingForBackgroundLayer);
1119                     childState.m_compositingAncestor = &layer;
1120                     if (overlapMap)
1121                         overlapMap->pushCompositingContainer();
1122                     // This layer is going to be composited, so children can safely ignore the fact that there's an 
1123                     // animation running behind this layer, meaning they can rely on the overlap map testing again
1124                     childState.m_testingOverlap = true;
1125                     willBeComposited = true;
1126                 }
1127             }
1128         }
1129     }
1130
1131     if (layer.renderer().isRenderNamedFlowFragmentContainer()) {
1132         // We are going to collect layers from the RenderFlowThread into the GraphicsLayer of the parent of the
1133         // anonymous RenderRegion, but first we need to make sure that the parent itself of the region is going to
1134         // have a composited layer. We only want to make regions composited when there's an actual layer that we
1135         // need to move to that region.
1136         computeRegionCompositingRequirements(toRenderBlockFlow(layer.renderer()).renderNamedFlowFragment(), overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1137     }
1138
1139     
1140     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1141         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i)
1142             computeCompositingRequirements(&layer, *normalFlowList->at(i), overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1143     }
1144
1145     if (layer.isStackingContainer()) {
1146         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1147             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i)
1148                 computeCompositingRequirements(&layer, *posZOrderList->at(i), overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1149         }
1150     }
1151     
1152     // If we just entered compositing mode, the root will have become composited (as long as accelerated compositing is enabled).
1153     if (layer.isRootLayer()) {
1154         if (inCompositingMode() && m_hasAcceleratedCompositing)
1155             willBeComposited = true;
1156     }
1157     
1158     // If the layer composited for other reasons than blending, it is no longer needed to keep track of whether a child was blended.
1159     if (compositingState.m_subtreeHasBlending && !layer.hasBlendMode())
1160         compositingState.m_subtreeHasBlending = false;
1161
1162     ASSERT(willBeComposited == needsToBeComposited(layer));
1163
1164     // All layers (even ones that aren't being composited) need to get added to
1165     // the overlap map. Layers that do not composite will draw into their
1166     // compositing ancestor's backing, and so are still considered for overlap.
1167     if (overlapMap && childState.m_compositingAncestor && !childState.m_compositingAncestor->isRootLayer())
1168         addToOverlapMap(*overlapMap, layer, absBounds, haveComputedBounds);
1169
1170     if (childState.m_subtreeHasBlending || layer.hasBlendMode())
1171         compositingState.m_subtreeHasBlending = true;
1172
1173     // Now check for reasons to become composited that depend on the state of descendant layers.
1174     RenderLayer::IndirectCompositingReason indirectCompositingReason;
1175     if (!willBeComposited && canBeComposited(layer)
1176         && requiresCompositingForIndirectReason(layer.renderer(), childState.m_subtreeIsCompositing, compositingState.m_subtreeHasBlending, anyDescendantHas3DTransform, indirectCompositingReason)) {
1177         layer.setIndirectCompositingReason(indirectCompositingReason);
1178         childState.m_compositingAncestor = &layer;
1179         if (overlapMap) {
1180             overlapMap->pushCompositingContainer();
1181             addToOverlapMapRecursive(*overlapMap, layer);
1182         }
1183         willBeComposited = true;
1184     }
1185     
1186     ASSERT(willBeComposited == needsToBeComposited(layer));
1187     if (layer.reflectionLayer()) {
1188         // FIXME: Shouldn't we call computeCompositingRequirements to handle a reflection overlapping with another renderer?
1189         layer.reflectionLayer()->setIndirectCompositingReason(willBeComposited ? RenderLayer::IndirectCompositingForStacking : RenderLayer::NoIndirectCompositingReason);
1190     }
1191
1192     // Subsequent layers in the parent stacking context also need to composite.
1193     if (childState.m_subtreeIsCompositing)
1194         compositingState.m_subtreeIsCompositing = true;
1195
1196     // Set the flag to say that this SC has compositing children.
1197     layer.setHasCompositingDescendant(childState.m_subtreeIsCompositing);
1198
1199     // setHasCompositingDescendant() may have changed the answer to needsToBeComposited() when clipping,
1200     // so test that again.
1201     bool isCompositedClippingLayer = canBeComposited(layer) && clipsCompositingDescendants(layer);
1202
1203     // Turn overlap testing off for later layers if it's already off, or if we have an animating transform.
1204     // Note that if the layer clips its descendants, there's no reason to propagate the child animation to the parent layers. That's because
1205     // we know for sure the animation is contained inside the clipping rectangle, which is already added to the overlap map.
1206     if ((!childState.m_testingOverlap && !isCompositedClippingLayer) || isRunningAcceleratedTransformAnimation(layer.renderer()))
1207         compositingState.m_testingOverlap = false;
1208     
1209     if (isCompositedClippingLayer) {
1210         if (!willBeComposited) {
1211             childState.m_compositingAncestor = &layer;
1212             if (overlapMap) {
1213                 overlapMap->pushCompositingContainer();
1214                 addToOverlapMapRecursive(*overlapMap, layer);
1215             }
1216             willBeComposited = true;
1217          }
1218     }
1219
1220     if (overlapMap && childState.m_compositingAncestor == &layer && !layer.isRootLayer())
1221         overlapMap->popCompositingContainer();
1222
1223     // If we're back at the root, and no other layers need to be composited, and the root layer itself doesn't need
1224     // to be composited, then we can drop out of compositing mode altogether. However, don't drop out of compositing mode
1225     // if there are composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
1226     if (layer.isRootLayer() && !childState.m_subtreeIsCompositing && !requiresCompositingLayer(layer) && !m_forceCompositingMode && !hasAnyAdditionalCompositedLayers(layer)) {
1227         // Don't drop out of compositing on iOS, because we may flash. See <rdar://problem/8348337>.
1228 #if !PLATFORM(IOS)
1229         enableCompositingMode(false);
1230         willBeComposited = false;
1231 #endif
1232     }
1233     
1234     // If the layer is going into compositing mode, repaint its old location.
1235     ASSERT(willBeComposited == needsToBeComposited(layer));
1236     if (!layer.isComposited() && willBeComposited)
1237         repaintOnCompositingChange(layer);
1238
1239     // Update backing now, so that we can use isComposited() reliably during tree traversal in rebuildCompositingLayerTree().
1240     if (updateBacking(layer, CompositingChangeRepaintNow))
1241         layersChanged = true;
1242
1243     if (layer.reflectionLayer() && updateLayerCompositingState(*layer.reflectionLayer(), CompositingChangeRepaintNow))
1244         layersChanged = true;
1245
1246     descendantHas3DTransform |= anyDescendantHas3DTransform || layer.has3DTransform();
1247
1248     if (overlapMap)
1249         overlapMap->geometryMap().popMappingsToAncestor(ancestorLayer);
1250 }
1251
1252 void RenderLayerCompositor::computeRegionCompositingRequirements(RenderNamedFlowFragment* region, OverlapMap* overlapMap, CompositingState& childState, bool& layersChanged, bool& anyDescendantHas3DTransform)
1253 {
1254     if (!region->isValid())
1255         return;
1256
1257     RenderFlowThread* flowThread = region->flowThread();
1258     
1259     if (overlapMap)
1260         overlapMap->geometryMap().pushRenderFlowThread(flowThread);
1261
1262     if (const RenderLayerList* layerList = flowThread->getLayerListForRegion(region)) {
1263         for (size_t i = 0, listSize = layerList->size(); i < listSize; ++i) {
1264             RenderLayer& curLayer = *layerList->at(i);
1265             ASSERT(flowThread->regionForCompositedLayer(curLayer) == region);
1266             computeCompositingRequirements(flowThread->layer(), curLayer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform);
1267         }
1268     }
1269
1270     if (overlapMap)
1271         overlapMap->geometryMap().popMappingsToAncestor(region->layerOwner());
1272 }
1273
1274 void RenderLayerCompositor::setCompositingParent(RenderLayer& childLayer, RenderLayer* parentLayer)
1275 {
1276     ASSERT(!parentLayer || childLayer.ancestorCompositingLayer() == parentLayer);
1277     ASSERT(childLayer.isComposited());
1278
1279     // It's possible to be called with a parent that isn't yet composited when we're doing
1280     // partial updates as required by painting or hit testing. Just bail in that case;
1281     // we'll do a full layer update soon.
1282     if (!parentLayer || !parentLayer->isComposited())
1283         return;
1284
1285     if (parentLayer) {
1286         GraphicsLayer* hostingLayer = parentLayer->backing()->parentForSublayers();
1287         GraphicsLayer* hostedLayer = childLayer.backing()->childForSuperlayers();
1288         
1289         hostingLayer->addChild(hostedLayer);
1290     } else
1291         childLayer.backing()->childForSuperlayers()->removeFromParent();
1292 }
1293
1294 void RenderLayerCompositor::removeCompositedChildren(RenderLayer& layer)
1295 {
1296     ASSERT(layer.isComposited());
1297
1298     layer.backing()->parentForSublayers()->removeAllChildren();
1299 }
1300
1301 #if ENABLE(VIDEO)
1302 bool RenderLayerCompositor::canAccelerateVideoRendering(RenderVideo& video) const
1303 {
1304     if (!m_hasAcceleratedCompositing)
1305         return false;
1306
1307     return video.supportsAcceleratedRendering();
1308 }
1309 #endif
1310
1311 void RenderLayerCompositor::rebuildCompositingLayerTree(RenderLayer& layer, Vector<GraphicsLayer*>& childLayersOfEnclosingLayer, int depth)
1312 {
1313     // Make the layer compositing if necessary, and set up clipping and content layers.
1314     // Note that we can only do work here that is independent of whether the descendant layers
1315     // have been processed. computeCompositingRequirements() will already have done the repaint if necessary.
1316
1317     // Do not iterate the RenderFlowThread directly. We are going to collect composited layers as part of regions.
1318     if (layer.isFlowThreadCollectingGraphicsLayersUnderRegions())
1319         return;
1320     
1321     RenderLayerBacking* layerBacking = layer.backing();
1322     if (layerBacking) {
1323         // The compositing state of all our children has been updated already, so now
1324         // we can compute and cache the composited bounds for this layer.
1325         layerBacking->updateCompositedBounds();
1326
1327         if (RenderLayer* reflection = layer.reflectionLayer()) {
1328             if (reflection->backing())
1329                 reflection->backing()->updateCompositedBounds();
1330         }
1331
1332         if (layerBacking->updateGraphicsLayerConfiguration())
1333             layerBacking->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
1334         
1335         layerBacking->updateGraphicsLayerGeometry();
1336
1337         if (!layer.parent())
1338             updateRootLayerPosition();
1339
1340 #if !LOG_DISABLED
1341         logLayerInfo(layer, depth);
1342 #else
1343         UNUSED_PARAM(depth);
1344 #endif
1345         if (layerBacking->hasUnpositionedOverflowControlsLayers())
1346             layer.positionNewlyCreatedOverflowControls();
1347     }
1348
1349     // If this layer has backing, then we are collecting its children, otherwise appending
1350     // to the compositing child list of an enclosing layer.
1351     Vector<GraphicsLayer*> layerChildren;
1352     Vector<GraphicsLayer*>& childList = layerBacking ? layerChildren : childLayersOfEnclosingLayer;
1353
1354 #if !ASSERT_DISABLED
1355     LayerListMutationDetector mutationChecker(&layer);
1356 #endif
1357
1358     if (layer.isStackingContainer()) {
1359         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1360             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i)
1361                 rebuildCompositingLayerTree(*negZOrderList->at(i), childList, depth + 1);
1362         }
1363
1364         // If a negative z-order child is compositing, we get a foreground layer which needs to get parented.
1365         if (layerBacking && layerBacking->foregroundLayer())
1366             childList.append(layerBacking->foregroundLayer());
1367     }
1368
1369     if (layer.renderer().isRenderNamedFlowFragmentContainer())
1370         rebuildRegionCompositingLayerTree(toRenderBlockFlow(layer.renderer()).renderNamedFlowFragment(), layerChildren, depth + 1);
1371
1372     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1373         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i)
1374             rebuildCompositingLayerTree(*normalFlowList->at(i), childList, depth + 1);
1375     }
1376     
1377     if (layer.isStackingContainer()) {
1378         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1379             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i)
1380                 rebuildCompositingLayerTree(*posZOrderList->at(i), childList, depth + 1);
1381         }
1382     }
1383     
1384     if (layerBacking) {
1385         bool parented = false;
1386         if (layer.renderer().isWidget())
1387             parented = parentFrameContentLayers(toRenderWidget(&layer.renderer()));
1388
1389         if (!parented)
1390             layerBacking->parentForSublayers()->setChildren(layerChildren);
1391
1392         // If the layer has a clipping layer the overflow controls layers will be siblings of the clipping layer.
1393         // Otherwise, the overflow control layers are normal children.
1394         if (!layerBacking->hasClippingLayer() && !layerBacking->hasScrollingLayer()) {
1395             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForHorizontalScrollbar()) {
1396                 overflowControlLayer->removeFromParent();
1397                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
1398             }
1399
1400             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForVerticalScrollbar()) {
1401                 overflowControlLayer->removeFromParent();
1402                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
1403             }
1404
1405             if (GraphicsLayer* overflowControlLayer = layerBacking->layerForScrollCorner()) {
1406                 overflowControlLayer->removeFromParent();
1407                 layerBacking->parentForSublayers()->addChild(overflowControlLayer);
1408             }
1409         }
1410
1411         childLayersOfEnclosingLayer.append(layerBacking->childForSuperlayers());
1412     }
1413 }
1414
1415 void RenderLayerCompositor::rebuildRegionCompositingLayerTree(RenderNamedFlowFragment* region, Vector<GraphicsLayer*>& childList, int depth)
1416 {
1417     if (!region->isValid())
1418         return;
1419
1420     RenderFlowThread* flowThread = region->flowThread();
1421     ASSERT(flowThread->collectsGraphicsLayersUnderRegions());
1422     if (const RenderLayerList* layerList = flowThread->getLayerListForRegion(region)) {
1423         for (size_t i = 0, listSize = layerList->size(); i < listSize; ++i) {
1424             RenderLayer& curLayer = *layerList->at(i);
1425             ASSERT(flowThread->regionForCompositedLayer(curLayer) == region);
1426             rebuildCompositingLayerTree(curLayer, childList, depth + 1);
1427         }
1428     }
1429 }
1430
1431 void RenderLayerCompositor::frameViewDidChangeLocation(const IntPoint& contentsOffset)
1432 {
1433     if (m_overflowControlsHostLayer)
1434         m_overflowControlsHostLayer->setPosition(contentsOffset);
1435 }
1436
1437 void RenderLayerCompositor::frameViewDidChangeSize()
1438 {
1439     if (m_clipLayer) {
1440         const FrameView& frameView = m_renderView.frameView();
1441         m_clipLayer->setSize(frameView.unscaledVisibleContentSize());
1442
1443         frameViewDidScroll();
1444         updateOverflowControlsLayers();
1445
1446 #if ENABLE(RUBBER_BANDING)
1447         if (m_layerForOverhangAreas)
1448             m_layerForOverhangAreas->setSize(frameView.frameRect().size());
1449 #endif
1450     }
1451 }
1452
1453 bool RenderLayerCompositor::hasCoordinatedScrolling() const
1454 {
1455     ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator();
1456     return scrollingCoordinator && scrollingCoordinator->coordinatesScrollingForFrameView(&m_renderView.frameView());
1457 }
1458
1459 void RenderLayerCompositor::frameViewDidScroll()
1460 {
1461     if (!m_scrollLayer)
1462         return;
1463
1464     // If there's a scrolling coordinator that manages scrolling for this frame view,
1465     // it will also manage updating the scroll layer position.
1466     if (hasCoordinatedScrolling()) {
1467         // We have to schedule a flush in order for the main TiledBacking to update its tile coverage.
1468         scheduleLayerFlushNow();
1469         return;
1470     }
1471
1472     FrameView& frameView = m_renderView.frameView();
1473     IntPoint scrollPosition = frameView.scrollPosition();
1474
1475     const Settings& settings = m_renderView.frameView().frame().settings();
1476     if (settings.compositedScrollingForFramesEnabled()) {
1477         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
1478             scrollingCoordinator->scrollableAreaScrollLayerDidChange(&frameView);
1479     }
1480
1481     m_scrollLayer->setPosition(FloatPoint(-scrollPosition.x(), -scrollPosition.y()));
1482
1483     if (GraphicsLayer* fixedBackgroundLayer = fixedRootBackgroundLayer())
1484         fixedBackgroundLayer->setPosition(IntPoint(frameView.scrollOffsetForFixedPosition()));
1485 }
1486
1487 void RenderLayerCompositor::frameViewDidAddOrRemoveScrollbars()
1488 {
1489     updateOverflowControlsLayers();
1490 }
1491
1492 void RenderLayerCompositor::frameViewDidLayout()
1493 {
1494     RenderLayerBacking* renderViewBacking = m_renderView.layer()->backing();
1495     if (renderViewBacking)
1496         renderViewBacking->adjustTiledBackingCoverage();
1497 }
1498
1499 void RenderLayerCompositor::rootFixedBackgroundsChanged()
1500 {
1501     RenderLayerBacking* renderViewBacking = m_renderView.layer()->backing();
1502     if (renderViewBacking && renderViewBacking->usingTiledBacking())
1503         setCompositingLayersNeedRebuild();
1504 }
1505
1506 void RenderLayerCompositor::scrollingLayerDidChange(RenderLayer& layer)
1507 {
1508     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
1509         scrollingCoordinator->scrollableAreaScrollLayerDidChange(&layer);
1510 }
1511
1512 void RenderLayerCompositor::fixedRootBackgroundLayerChanged()
1513 {
1514     if (m_renderView.documentBeingDestroyed())
1515         return;
1516
1517     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator()) {
1518         RenderLayerBacking* renderViewBacking = m_renderView.layer()->backing();
1519         if (!renderViewBacking)
1520             return;
1521
1522         scrollingCoordinator->updateScrollingNode(renderViewBacking->scrollLayerID(), scrollLayer(), fixedRootBackgroundLayer());
1523     }
1524 }
1525
1526 String RenderLayerCompositor::layerTreeAsText(LayerTreeFlags flags)
1527 {
1528     updateCompositingLayers(CompositingUpdateAfterLayout);
1529
1530     if (!m_rootContentLayer)
1531         return String();
1532
1533     flushPendingLayerChanges(true);
1534
1535     LayerTreeAsTextBehavior layerTreeBehavior = LayerTreeAsTextBehaviorNormal;
1536     if (flags & LayerTreeFlagsIncludeDebugInfo)
1537         layerTreeBehavior |= LayerTreeAsTextDebug;
1538     if (flags & LayerTreeFlagsIncludeVisibleRects)
1539         layerTreeBehavior |= LayerTreeAsTextIncludeVisibleRects;
1540     if (flags & LayerTreeFlagsIncludeTileCaches)
1541         layerTreeBehavior |= LayerTreeAsTextIncludeTileCaches;
1542     if (flags & LayerTreeFlagsIncludeRepaintRects)
1543         layerTreeBehavior |= LayerTreeAsTextIncludeRepaintRects;
1544     if (flags & LayerTreeFlagsIncludePaintingPhases)
1545         layerTreeBehavior |= LayerTreeAsTextIncludePaintingPhases;
1546     if (flags & LayerTreeFlagsIncludeContentLayers)
1547         layerTreeBehavior |= LayerTreeAsTextIncludeContentLayers;
1548
1549     // We skip dumping the scroll and clip layers to keep layerTreeAsText output
1550     // similar between platforms.
1551     String layerTreeText = m_rootContentLayer->layerTreeAsText(layerTreeBehavior);
1552
1553     // Dump an empty layer tree only if the only composited layer is the main frame's tiled backing,
1554     // so that tests expecting us to drop out of accelerated compositing when there are no layers succeed.
1555     if (!hasAnyAdditionalCompositedLayers(rootRenderLayer()) && mainFrameBackingIsTiled() && !(layerTreeBehavior & LayerTreeAsTextIncludeTileCaches))
1556         layerTreeText = "";
1557
1558     // The true root layer is not included in the dump, so if we want to report
1559     // its repaint rects, they must be included here.
1560     if (flags & LayerTreeFlagsIncludeRepaintRects) {
1561         String layerTreeTextWithRootRepaintRects = m_renderView.frameView().trackedRepaintRectsAsText();
1562         layerTreeTextWithRootRepaintRects.append(layerTreeText);
1563         return layerTreeTextWithRootRepaintRects;
1564     }
1565
1566     return layerTreeText;
1567 }
1568
1569 RenderLayerCompositor* RenderLayerCompositor::frameContentsCompositor(RenderWidget* renderer)
1570 {
1571     if (Document* contentDocument = renderer->frameOwnerElement().contentDocument()) {
1572         if (RenderView* view = contentDocument->renderView())
1573             return &view->compositor();
1574     }
1575     return 0;
1576 }
1577
1578 bool RenderLayerCompositor::parentFrameContentLayers(RenderWidget* renderer)
1579 {
1580     RenderLayerCompositor* innerCompositor = frameContentsCompositor(renderer);
1581     if (!innerCompositor || !innerCompositor->inCompositingMode() || innerCompositor->rootLayerAttachment() != RootLayerAttachedViaEnclosingFrame)
1582         return false;
1583     
1584     RenderLayer* layer = renderer->layer();
1585     if (!layer->isComposited())
1586         return false;
1587
1588     RenderLayerBacking* backing = layer->backing();
1589     GraphicsLayer* hostingLayer = backing->parentForSublayers();
1590     GraphicsLayer* rootLayer = innerCompositor->rootGraphicsLayer();
1591     if (hostingLayer->children().size() != 1 || hostingLayer->children()[0] != rootLayer) {
1592         hostingLayer->removeAllChildren();
1593         hostingLayer->addChild(rootLayer);
1594     }
1595     return true;
1596 }
1597
1598 // This just updates layer geometry without changing the hierarchy.
1599 void RenderLayerCompositor::updateLayerTreeGeometry(RenderLayer& layer, int depth)
1600 {
1601     // FIXME: fixed positioned elements inside a named flow are not composited yet.
1602     if (layer.isOutOfFlowRenderFlowThread())
1603         return;
1604
1605     if (RenderLayerBacking* layerBacking = layer.backing()) {
1606         // The compositing state of all our children has been updated already, so now
1607         // we can compute and cache the composited bounds for this layer.
1608         layerBacking->updateCompositedBounds();
1609
1610         if (RenderLayer* reflection = layer.reflectionLayer()) {
1611             if (reflection->backing())
1612                 reflection->backing()->updateCompositedBounds();
1613         }
1614
1615         layerBacking->updateGraphicsLayerConfiguration();
1616         layerBacking->updateGraphicsLayerGeometry();
1617
1618         if (!layer.parent())
1619             updateRootLayerPosition();
1620
1621 #if !LOG_DISABLED
1622         logLayerInfo(layer, depth);
1623 #else
1624         UNUSED_PARAM(depth);
1625 #endif
1626     }
1627
1628 #if !ASSERT_DISABLED
1629     LayerListMutationDetector mutationChecker(&layer);
1630 #endif
1631
1632     if (layer.isStackingContainer()) {
1633         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1634             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i)
1635                 updateLayerTreeGeometry(*negZOrderList->at(i), depth + 1);
1636         }
1637     }
1638
1639     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1640         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i)
1641             updateLayerTreeGeometry(*normalFlowList->at(i), depth + 1);
1642     }
1643     
1644     if (layer.isStackingContainer()) {
1645         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1646             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i)
1647                 updateLayerTreeGeometry(*posZOrderList->at(i), depth + 1);
1648         }
1649     }
1650 }
1651
1652 // Recurs down the RenderLayer tree until its finds the compositing descendants of compositingAncestor and updates their geometry.
1653 void RenderLayerCompositor::updateCompositingDescendantGeometry(RenderLayer& compositingAncestor, RenderLayer& layer, bool compositedChildrenOnly)
1654 {
1655     if (&layer != &compositingAncestor) {
1656         if (RenderLayerBacking* layerBacking = layer.backing()) {
1657             layerBacking->updateCompositedBounds();
1658
1659             if (RenderLayer* reflection = layer.reflectionLayer()) {
1660                 if (reflection->backing())
1661                     reflection->backing()->updateCompositedBounds();
1662             }
1663
1664             layerBacking->updateGraphicsLayerGeometry();
1665             if (compositedChildrenOnly)
1666                 return;
1667         }
1668     }
1669
1670     if (layer.reflectionLayer())
1671         updateCompositingDescendantGeometry(compositingAncestor, *layer.reflectionLayer(), compositedChildrenOnly);
1672
1673     if (!layer.hasCompositingDescendant())
1674         return;
1675
1676 #if !ASSERT_DISABLED
1677     LayerListMutationDetector mutationChecker(&layer);
1678 #endif
1679     
1680     if (layer.isStackingContainer()) {
1681         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1682             size_t listSize = negZOrderList->size();
1683             for (size_t i = 0; i < listSize; ++i)
1684                 updateCompositingDescendantGeometry(compositingAncestor, *negZOrderList->at(i), compositedChildrenOnly);
1685         }
1686     }
1687
1688     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1689         size_t listSize = normalFlowList->size();
1690         for (size_t i = 0; i < listSize; ++i)
1691             updateCompositingDescendantGeometry(compositingAncestor, *normalFlowList->at(i), compositedChildrenOnly);
1692     }
1693     
1694     if (layer.isStackingContainer()) {
1695         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1696             size_t listSize = posZOrderList->size();
1697             for (size_t i = 0; i < listSize; ++i)
1698                 updateCompositingDescendantGeometry(compositingAncestor, *posZOrderList->at(i), compositedChildrenOnly);
1699         }
1700     }
1701 }
1702
1703
1704 void RenderLayerCompositor::repaintCompositedLayers(const IntRect* absRect)
1705 {
1706     recursiveRepaintLayer(rootRenderLayer(), absRect);
1707 }
1708
1709 void RenderLayerCompositor::recursiveRepaintLayer(RenderLayer& layer, const IntRect* rect)
1710 {
1711     // FIXME: This method does not work correctly with transforms.
1712     if (layer.isComposited() && !layer.backing()->paintsIntoCompositedAncestor()) {
1713         if (rect)
1714             layer.setBackingNeedsRepaintInRect(*rect);
1715         else
1716             layer.setBackingNeedsRepaint();
1717     }
1718
1719 #if !ASSERT_DISABLED
1720     LayerListMutationDetector mutationChecker(&layer);
1721 #endif
1722
1723     if (layer.hasCompositingDescendant()) {
1724         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
1725             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i) {
1726                 RenderLayer& childLayer = *negZOrderList->at(i);
1727                 if (rect) {
1728                     IntRect childRect(*rect);
1729                     childLayer.convertToPixelSnappedLayerCoords(&layer, childRect);
1730                     recursiveRepaintLayer(childLayer, &childRect);
1731                 } else
1732                     recursiveRepaintLayer(childLayer);
1733             }
1734         }
1735
1736         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
1737             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i) {
1738                 RenderLayer& childLayer = *posZOrderList->at(i);
1739                 if (rect) {
1740                     IntRect childRect(*rect);
1741                     childLayer.convertToPixelSnappedLayerCoords(&layer, childRect);
1742                     recursiveRepaintLayer(childLayer, &childRect);
1743                 } else
1744                     recursiveRepaintLayer(childLayer);
1745             }
1746         }
1747     }
1748     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
1749         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i) {
1750             RenderLayer& childLayer = *normalFlowList->at(i);
1751             if (rect) {
1752                 IntRect childRect(*rect);
1753                 childLayer.convertToPixelSnappedLayerCoords(&layer, childRect);
1754                 recursiveRepaintLayer(childLayer, &childRect);
1755             } else
1756                 recursiveRepaintLayer(childLayer);
1757         }
1758     }
1759 }
1760
1761 RenderLayer& RenderLayerCompositor::rootRenderLayer() const
1762 {
1763     return *m_renderView.layer();
1764 }
1765
1766 GraphicsLayer* RenderLayerCompositor::rootGraphicsLayer() const
1767 {
1768     if (m_overflowControlsHostLayer)
1769         return m_overflowControlsHostLayer.get();
1770     return m_rootContentLayer.get();
1771 }
1772
1773 GraphicsLayer* RenderLayerCompositor::scrollLayer() const
1774 {
1775     return m_scrollLayer.get();
1776 }
1777
1778 #if ENABLE(RUBBER_BANDING)
1779 GraphicsLayer* RenderLayerCompositor::headerLayer() const
1780 {
1781     return m_layerForHeader.get();
1782 }
1783
1784 GraphicsLayer* RenderLayerCompositor::footerLayer() const
1785 {
1786     return m_layerForFooter.get();
1787 }
1788 #endif
1789
1790 TiledBacking* RenderLayerCompositor::pageTiledBacking() const
1791 {
1792     RenderLayerBacking* renderViewBacking = m_renderView.layer()->backing();
1793     return renderViewBacking ? renderViewBacking->tiledBacking() : nullptr;
1794 }
1795
1796 void RenderLayerCompositor::setIsInWindow(bool isInWindow)
1797 {
1798     if (TiledBacking* tiledBacking = pageTiledBacking())
1799         tiledBacking->setIsInWindow(isInWindow);
1800
1801     if (!inCompositingMode())
1802         return;
1803
1804     if (isInWindow) {
1805         if (m_rootLayerAttachment != RootLayerUnattached)
1806             return;
1807
1808         RootLayerAttachment attachment = shouldPropagateCompositingToEnclosingFrame() ? RootLayerAttachedViaEnclosingFrame : RootLayerAttachedViaChromeClient;
1809         attachRootLayer(attachment);
1810 #if PLATFORM(IOS)
1811         registerAllViewportConstrainedLayers();
1812         registerAllScrollingLayers();
1813 #endif
1814     } else {
1815         if (m_rootLayerAttachment == RootLayerUnattached)
1816             return;
1817
1818         detachRootLayer();
1819 #if PLATFORM(IOS)
1820         unregisterAllViewportConstrainedLayers();
1821         unregisterAllScrollingLayers();
1822 #endif
1823     }
1824 }
1825
1826 void RenderLayerCompositor::clearBackingForLayerIncludingDescendants(RenderLayer& layer)
1827 {
1828     if (layer.isComposited()) {
1829         removeViewportConstrainedLayer(layer);
1830         layer.clearBacking();
1831     }
1832
1833     for (RenderLayer* childLayer = layer.firstChild(); childLayer; childLayer = childLayer->nextSibling())
1834         clearBackingForLayerIncludingDescendants(*childLayer);
1835 }
1836
1837 void RenderLayerCompositor::clearBackingForAllLayers()
1838 {
1839     clearBackingForLayerIncludingDescendants(*m_renderView.layer());
1840 }
1841
1842 void RenderLayerCompositor::updateRootLayerPosition()
1843 {
1844     if (m_rootContentLayer) {
1845         const IntRect& documentRect = m_renderView.documentRect();
1846         m_rootContentLayer->setSize(documentRect.size());
1847         m_rootContentLayer->setPosition(FloatPoint(documentRect.x(), documentRect.y() + m_renderView.frameView().headerHeight()));
1848     }
1849     if (m_clipLayer)
1850         m_clipLayer->setSize(m_renderView.frameView().unscaledVisibleContentSize());
1851
1852 #if ENABLE(RUBBER_BANDING)
1853     if (m_contentShadowLayer) {
1854         m_contentShadowLayer->setPosition(m_rootContentLayer->position());
1855         m_contentShadowLayer->setSize(m_rootContentLayer->size());
1856     }
1857
1858     updateLayerForTopOverhangArea(m_layerForTopOverhangArea != nullptr);
1859     updateLayerForBottomOverhangArea(m_layerForBottomOverhangArea != nullptr);
1860     updateLayerForHeader(m_layerForHeader != nullptr);
1861     updateLayerForFooter(m_layerForFooter != nullptr);
1862 #endif
1863 }
1864
1865 bool RenderLayerCompositor::has3DContent() const
1866 {
1867     return layerHas3DContent(rootRenderLayer());
1868 }
1869
1870 bool RenderLayerCompositor::allowsIndependentlyCompositedFrames(const FrameView* view)
1871 {
1872 #if PLATFORM(MAC) && !PLATFORM(IOS)
1873     // frames are only independently composited in Mac pre-WebKit2.
1874     return view->platformWidget();
1875 #else
1876     UNUSED_PARAM(view);
1877 #endif
1878     return false;
1879 }
1880
1881 bool RenderLayerCompositor::shouldPropagateCompositingToEnclosingFrame() const
1882 {
1883     // Parent document content needs to be able to render on top of a composited frame, so correct behavior
1884     // is to have the parent document become composited too. However, this can cause problems on platforms that
1885     // use native views for frames (like Mac), so disable that behavior on those platforms for now.
1886     HTMLFrameOwnerElement* ownerElement = m_renderView.document().ownerElement();
1887     RenderElement* renderer = ownerElement ? ownerElement->renderer() : 0;
1888
1889     // If we are the top-level frame, don't propagate.
1890     if (!ownerElement)
1891         return false;
1892
1893     if (!allowsIndependentlyCompositedFrames(&m_renderView.frameView()))
1894         return true;
1895
1896     if (!renderer || !renderer->isWidget())
1897         return false;
1898
1899     // On Mac, only propagate compositing if the frame is overlapped in the parent
1900     // document, or the parent is already compositing, or the main frame is scaled.
1901     Page* page = this->page();
1902     if (page && page->pageScaleFactor() != 1)
1903         return true;
1904     
1905     RenderWidget* frameRenderer = toRenderWidget(renderer);
1906     if (frameRenderer->widget()) {
1907         ASSERT(frameRenderer->widget()->isFrameView());
1908         FrameView* view = toFrameView(frameRenderer->widget());
1909         if (view->isOverlappedIncludingAncestors() || view->hasCompositingAncestor())
1910             return true;
1911     }
1912
1913     return false;
1914 }
1915
1916 bool RenderLayerCompositor::needsToBeComposited(const RenderLayer& layer, RenderLayer::ViewportConstrainedNotCompositedReason* viewportConstrainedNotCompositedReason) const
1917 {
1918     if (!canBeComposited(layer))
1919         return false;
1920
1921     return requiresCompositingLayer(layer, viewportConstrainedNotCompositedReason) || layer.mustCompositeForIndirectReasons() || (inCompositingMode() && layer.isRootLayer());
1922 }
1923
1924 // Note: this specifies whether the RL needs a compositing layer for intrinsic reasons.
1925 // Use needsToBeComposited() to determine if a RL actually needs a compositing layer.
1926 // static
1927 bool RenderLayerCompositor::requiresCompositingLayer(const RenderLayer& layer, RenderLayer::ViewportConstrainedNotCompositedReason* viewportConstrainedNotCompositedReason) const
1928 {
1929     auto renderer = &layer.renderer();
1930
1931     // The compositing state of a reflection should match that of its reflected layer.
1932     if (layer.isReflection())
1933         renderer = toRenderLayerModelObject(renderer->parent()); // The RenderReplica's parent is the object being reflected.
1934
1935     // The root layer always has a compositing layer, but it may not have backing.
1936     return requiresCompositingForTransform(*renderer)
1937         || requiresCompositingForVideo(*renderer)
1938         || requiresCompositingForCanvas(*renderer)
1939         || requiresCompositingForPlugin(*renderer)
1940         || requiresCompositingForFrame(*renderer)
1941         || (canRender3DTransforms() && renderer->style().backfaceVisibility() == BackfaceVisibilityHidden)
1942         || clipsCompositingDescendants(*renderer->layer())
1943         || requiresCompositingForAnimation(*renderer)
1944         || requiresCompositingForFilters(*renderer)
1945         || requiresCompositingForPosition(*renderer, *renderer->layer(), viewportConstrainedNotCompositedReason)
1946 #if PLATFORM(IOS)
1947         || requiresCompositingForScrolling(*renderer)
1948 #endif
1949         || requiresCompositingForOverflowScrolling(*renderer->layer())
1950         || requiresCompositingForBlending(*renderer);
1951 }
1952
1953 bool RenderLayerCompositor::canBeComposited(const RenderLayer& layer) const
1954 {
1955     if (m_hasAcceleratedCompositing && layer.isSelfPaintingLayer()) {
1956         if (!layer.isInsideFlowThread())
1957             return true;
1958
1959         // CSS Regions flow threads do not need to be composited as we use composited RenderRegions
1960         // to render the background of the RenderFlowThread.
1961         if (layer.isRenderFlowThread())
1962             return false;
1963
1964         // A faster way of saying layer.enclosingFlowThreadLayer()->isFlowThreadCollectingGraphicsLayersUnderRegions()
1965         return layer.isInsideOutOfFlowThread();
1966     }
1967     return false;
1968 }
1969
1970 bool RenderLayerCompositor::requiresOwnBackingStore(const RenderLayer& layer, const RenderLayer* compositingAncestorLayer, const IntRect& layerCompositedBoundsInAncestor, const IntRect& ancestorCompositedBounds) const
1971 {
1972     auto& renderer = layer.renderer();
1973
1974     if (compositingAncestorLayer
1975         && !(compositingAncestorLayer->backing()->graphicsLayer()->drawsContent()
1976             || compositingAncestorLayer->backing()->paintsIntoWindow()
1977             || compositingAncestorLayer->backing()->paintsIntoCompositedAncestor()))
1978         return true;
1979
1980     if (layer.isRootLayer()
1981         || layer.transform() // note: excludes perspective and transformStyle3D.
1982         || requiresCompositingForVideo(renderer)
1983         || requiresCompositingForCanvas(renderer)
1984         || requiresCompositingForPlugin(renderer)
1985         || requiresCompositingForFrame(renderer)
1986         || (canRender3DTransforms() && renderer.style().backfaceVisibility() == BackfaceVisibilityHidden)
1987         || requiresCompositingForAnimation(renderer)
1988         || requiresCompositingForFilters(renderer)
1989         || requiresCompositingForBlending(renderer)
1990         || requiresCompositingForPosition(renderer, layer)
1991         || requiresCompositingForOverflowScrolling(layer)
1992         || renderer.isTransparent()
1993         || renderer.hasMask()
1994         || renderer.hasReflection()
1995         || renderer.hasFilter()
1996 #if PLATFORM(IOS)
1997         || requiresCompositingForScrolling(renderer)
1998 #endif
1999         )
2000         return true;
2001         
2002     
2003     if (layer.mustCompositeForIndirectReasons()) {
2004         RenderLayer::IndirectCompositingReason reason = layer.indirectCompositingReason();
2005         return reason == RenderLayer::IndirectCompositingForOverlap
2006             || reason == RenderLayer::IndirectCompositingForStacking
2007             || reason == RenderLayer::IndirectCompositingForBackgroundLayer
2008             || reason == RenderLayer::IndirectCompositingForGraphicalEffect
2009             || reason == RenderLayer::IndirectCompositingForPreserve3D; // preserve-3d has to create backing store to ensure that 3d-transformed elements intersect.
2010     }
2011
2012     if (!ancestorCompositedBounds.contains(layerCompositedBoundsInAncestor))
2013         return true;
2014
2015     return false;
2016 }
2017
2018 CompositingReasons RenderLayerCompositor::reasonsForCompositing(const RenderLayer& layer) const
2019 {
2020     CompositingReasons reasons = CompositingReasonNone;
2021
2022     if (!layer.isComposited())
2023         return reasons;
2024
2025     auto renderer = &layer.renderer();
2026     if (layer.isReflection())
2027         renderer = toRenderLayerModelObject(renderer->parent());
2028
2029     if (requiresCompositingForTransform(*renderer))
2030         reasons |= CompositingReason3DTransform;
2031
2032     if (requiresCompositingForVideo(*renderer))
2033         reasons |= CompositingReasonVideo;
2034     else if (requiresCompositingForCanvas(*renderer))
2035         reasons |= CompositingReasonCanvas;
2036     else if (requiresCompositingForPlugin(*renderer))
2037         reasons |= CompositingReasonPlugin;
2038     else if (requiresCompositingForFrame(*renderer))
2039         reasons |= CompositingReasonIFrame;
2040     
2041     if ((canRender3DTransforms() && renderer->style().backfaceVisibility() == BackfaceVisibilityHidden))
2042         reasons |= CompositingReasonBackfaceVisibilityHidden;
2043
2044     if (clipsCompositingDescendants(*renderer->layer()))
2045         reasons |= CompositingReasonClipsCompositingDescendants;
2046
2047     if (requiresCompositingForAnimation(*renderer))
2048         reasons |= CompositingReasonAnimation;
2049
2050     if (requiresCompositingForFilters(*renderer))
2051         reasons |= CompositingReasonFilters;
2052
2053     if (requiresCompositingForBlending(*renderer))
2054         reasons |= CompositingReasonBlending;
2055
2056     if (requiresCompositingForPosition(*renderer, *renderer->layer()))
2057         reasons |= renderer->style().position() == FixedPosition ? CompositingReasonPositionFixed : CompositingReasonPositionSticky;
2058
2059 #if PLATFORM(IOS)
2060     if (requiresCompositingForScrolling(*renderer))
2061         reasons |= CompositingReasonOverflowScrollingTouch;
2062 #endif
2063
2064     if (requiresCompositingForOverflowScrolling(*renderer->layer()))
2065         reasons |= CompositingReasonOverflowScrollingTouch;
2066
2067     if (renderer->layer()->indirectCompositingReason() == RenderLayer::IndirectCompositingForStacking)
2068         reasons |= CompositingReasonStacking;
2069     else if (renderer->layer()->indirectCompositingReason() == RenderLayer::IndirectCompositingForOverlap)
2070         reasons |= CompositingReasonOverlap;
2071     else if (renderer->layer()->indirectCompositingReason() == RenderLayer::IndirectCompositingForBackgroundLayer)
2072         reasons |= CompositingReasonNegativeZIndexChildren;
2073     else if (renderer->layer()->indirectCompositingReason() == RenderLayer::IndirectCompositingForGraphicalEffect) {
2074         if (renderer->layer()->transform())
2075             reasons |= CompositingReasonTransformWithCompositedDescendants;
2076
2077         if (renderer->isTransparent())
2078             reasons |= CompositingReasonOpacityWithCompositedDescendants;
2079
2080         if (renderer->hasMask())
2081             reasons |= CompositingReasonMaskWithCompositedDescendants;
2082
2083         if (renderer->hasReflection())
2084             reasons |= CompositingReasonReflectionWithCompositedDescendants;
2085
2086         if (renderer->hasFilter())
2087             reasons |= CompositingReasonFilterWithCompositedDescendants;
2088             
2089         if (renderer->hasBlendMode())
2090             reasons |= CompositingReasonBlendingWithCompositedDescendants;
2091     } else if (renderer->layer()->indirectCompositingReason() == RenderLayer::IndirectCompositingForPerspective)
2092         reasons |= CompositingReasonPerspective;
2093     else if (renderer->layer()->indirectCompositingReason() == RenderLayer::IndirectCompositingForPreserve3D)
2094         reasons |= CompositingReasonPreserve3D;
2095
2096     if (inCompositingMode() && renderer->layer()->isRootLayer())
2097         reasons |= CompositingReasonRoot;
2098
2099     return reasons;
2100 }
2101
2102 #if !LOG_DISABLED
2103 const char* RenderLayerCompositor::logReasonsForCompositing(const RenderLayer& layer)
2104 {
2105     CompositingReasons reasons = reasonsForCompositing(layer);
2106
2107     if (reasons & CompositingReason3DTransform)
2108         return "3D transform";
2109
2110     if (reasons & CompositingReasonVideo)
2111         return "video";
2112     else if (reasons & CompositingReasonCanvas)
2113         return "canvas";
2114     else if (reasons & CompositingReasonPlugin)
2115         return "plugin";
2116     else if (reasons & CompositingReasonIFrame)
2117         return "iframe";
2118     
2119     if (reasons & CompositingReasonBackfaceVisibilityHidden)
2120         return "backface-visibility: hidden";
2121
2122     if (reasons & CompositingReasonClipsCompositingDescendants)
2123         return "clips compositing descendants";
2124
2125     if (reasons & CompositingReasonAnimation)
2126         return "animation";
2127
2128     if (reasons & CompositingReasonFilters)
2129         return "filters";
2130
2131     if (reasons & CompositingReasonBlending)
2132         return "blending";
2133
2134     if (reasons & CompositingReasonPositionFixed)
2135         return "position: fixed";
2136
2137     if (reasons & CompositingReasonPositionSticky)
2138         return "position: sticky";
2139
2140     if (reasons & CompositingReasonOverflowScrollingTouch)
2141         return "-webkit-overflow-scrolling: touch";
2142
2143     if (reasons & CompositingReasonStacking)
2144         return "stacking";
2145
2146     if (reasons & CompositingReasonOverlap)
2147         return "overlap";
2148
2149     if (reasons & CompositingReasonNegativeZIndexChildren)
2150         return "negative z-index children";
2151
2152     if (reasons & CompositingReasonTransformWithCompositedDescendants)
2153         return "transform with composited descendants";
2154
2155     if (reasons & CompositingReasonOpacityWithCompositedDescendants)
2156         return "opacity with composited descendants";
2157
2158     if (reasons & CompositingReasonMaskWithCompositedDescendants)
2159         return "mask with composited descendants";
2160
2161     if (reasons & CompositingReasonReflectionWithCompositedDescendants)
2162         return "reflection with composited descendants";
2163
2164     if (reasons & CompositingReasonFilterWithCompositedDescendants)
2165         return "filter with composited descendants";
2166             
2167     if (reasons & CompositingReasonBlendingWithCompositedDescendants)
2168         return "blending with composited descendants";
2169
2170     if (reasons & CompositingReasonPerspective)
2171         return "perspective";
2172
2173     if (reasons & CompositingReasonPreserve3D)
2174         return "preserve-3d";
2175
2176     if (reasons & CompositingReasonRoot)
2177         return "root";
2178
2179     return "";
2180 }
2181 #endif
2182
2183 // Return true if the given layer has some ancestor in the RenderLayer hierarchy that clips,
2184 // up to the enclosing compositing ancestor. This is required because compositing layers are parented
2185 // according to the z-order hierarchy, yet clipping goes down the renderer hierarchy.
2186 // Thus, a RenderLayer can be clipped by a RenderLayer that is an ancestor in the renderer hierarchy,
2187 // but a sibling in the z-order hierarchy.
2188 bool RenderLayerCompositor::clippedByAncestor(RenderLayer& layer) const
2189 {
2190     if (!layer.isComposited() || !layer.parent())
2191         return false;
2192
2193     RenderLayer* compositingAncestor = layer.ancestorCompositingLayer();
2194     if (!compositingAncestor)
2195         return false;
2196
2197     // If the compositingAncestor clips, that will be taken care of by clipsCompositingDescendants(),
2198     // so we only care about clipping between its first child that is our ancestor (the computeClipRoot),
2199     // and layer.
2200     RenderLayer* computeClipRoot = nullptr;
2201     RenderLayer* parent = &layer;
2202     while (parent) {
2203         RenderLayer* next = parent->parent();
2204         if (next == compositingAncestor) {
2205             computeClipRoot = parent;
2206             break;
2207         }
2208         parent = next;
2209     }
2210     
2211     if (!computeClipRoot || computeClipRoot == &layer)
2212         return false;
2213
2214     return layer.backgroundClipRect(RenderLayer::ClipRectsContext(computeClipRoot, 0, TemporaryClipRects)).rect() != LayoutRect::infiniteRect(); // FIXME: Incorrect for CSS regions.
2215 }
2216
2217 // Return true if the given layer is a stacking context and has compositing child
2218 // layers that it needs to clip. In this case we insert a clipping GraphicsLayer
2219 // into the hierarchy between this layer and its children in the z-order hierarchy.
2220 bool RenderLayerCompositor::clipsCompositingDescendants(const RenderLayer& layer) const
2221 {
2222     return layer.hasCompositingDescendant() && layer.renderer().hasClipOrOverflowClip();
2223 }
2224
2225 bool RenderLayerCompositor::requiresCompositingForScrollableFrame() const
2226 {
2227     // Need this done first to determine overflow.
2228     ASSERT(!m_renderView.needsLayout());
2229     HTMLFrameOwnerElement* ownerElement = m_renderView.document().ownerElement();
2230     if (!ownerElement)
2231         return false;
2232
2233     if (!(m_compositingTriggers & ChromeClient::ScrollableInnerFrameTrigger))
2234         return false;
2235
2236     return m_renderView.frameView().isScrollable();
2237 }
2238
2239 bool RenderLayerCompositor::requiresCompositingForTransform(RenderLayerModelObject& renderer) const
2240 {
2241     if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
2242         return false;
2243
2244     // Note that we ask the renderer if it has a transform, because the style may have transforms,
2245     // but the renderer may be an inline that doesn't suppport them.
2246     return renderer.hasTransform() && renderer.style().transform().has3DOperation();
2247 }
2248
2249 bool RenderLayerCompositor::requiresCompositingForVideo(RenderLayerModelObject& renderer) const
2250 {
2251     if (!(m_compositingTriggers & ChromeClient::VideoTrigger))
2252         return false;
2253 #if ENABLE(VIDEO)
2254     if (renderer.isVideo()) {
2255         RenderVideo& video = toRenderVideo(renderer);
2256         return (video.requiresImmediateCompositing() || video.shouldDisplayVideo()) && canAccelerateVideoRendering(video);
2257     }
2258 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
2259     if (renderer.isWidget()) {
2260         if (!m_hasAcceleratedCompositing)
2261             return false;
2262
2263         Element* element = renderer.element();
2264         if (!element || (!isHTMLVideoElement(element) && !isHTMLAudioElement(element)))
2265             return false;
2266
2267         HTMLMediaElement* mediaElement = toHTMLMediaElement(element);
2268         return mediaElement->player() ? mediaElement->player()->supportsAcceleratedRendering() : false;
2269     }
2270 #endif // ENABLE(PLUGIN_PROXY_FOR_VIDEO)
2271 #else
2272     UNUSED_PARAM(renderer);
2273 #endif
2274     return false;
2275 }
2276
2277 bool RenderLayerCompositor::requiresCompositingForCanvas(RenderLayerModelObject& renderer) const
2278 {
2279     if (!(m_compositingTriggers & ChromeClient::CanvasTrigger))
2280         return false;
2281
2282     if (renderer.isCanvas()) {
2283 #if USE(COMPOSITING_FOR_SMALL_CANVASES)
2284         bool isCanvasLargeEnoughToForceCompositing = true;
2285 #else
2286         HTMLCanvasElement* canvas = toHTMLCanvasElement(renderer.element());
2287         bool isCanvasLargeEnoughToForceCompositing = canvas->size().area() >= canvasAreaThresholdRequiringCompositing;
2288 #endif
2289         CanvasCompositingStrategy compositingStrategy = canvasCompositingStrategy(renderer);
2290         return compositingStrategy == CanvasAsLayerContents || (compositingStrategy == CanvasPaintedToLayer && isCanvasLargeEnoughToForceCompositing);
2291     }
2292
2293     return false;
2294 }
2295
2296 bool RenderLayerCompositor::requiresCompositingForPlugin(RenderLayerModelObject& renderer) const
2297 {
2298     if (!(m_compositingTriggers & ChromeClient::PluginTrigger))
2299         return false;
2300
2301     bool composite = renderer.isEmbeddedObject() && toRenderEmbeddedObject(&renderer)->allowsAcceleratedCompositing();
2302     if (!composite)
2303         return false;
2304
2305     m_reevaluateCompositingAfterLayout = true;
2306     
2307     RenderWidget& pluginRenderer = *toRenderWidget(&renderer);
2308     // If we can't reliably know the size of the plugin yet, don't change compositing state.
2309     if (pluginRenderer.needsLayout())
2310         return pluginRenderer.hasLayer() && pluginRenderer.layer()->isComposited();
2311
2312     // Don't go into compositing mode if height or width are zero, or size is 1x1.
2313     IntRect contentBox = pixelSnappedIntRect(pluginRenderer.contentBoxRect());
2314     return contentBox.height() * contentBox.width() > 1;
2315 }
2316
2317 bool RenderLayerCompositor::requiresCompositingForFrame(RenderLayerModelObject& renderer) const
2318 {
2319     if (!renderer.isWidget())
2320         return false;
2321
2322     RenderWidget& frameRenderer = *toRenderWidget(&renderer);
2323
2324     if (!frameRenderer.requiresAcceleratedCompositing())
2325         return false;
2326
2327     m_reevaluateCompositingAfterLayout = true;
2328
2329     RenderLayerCompositor* innerCompositor = frameContentsCompositor(&frameRenderer);
2330     if (!innerCompositor || !innerCompositor->shouldPropagateCompositingToEnclosingFrame())
2331         return false;
2332
2333     // If we can't reliably know the size of the iframe yet, don't change compositing state.
2334     if (!frameRenderer.parent() || frameRenderer.needsLayout())
2335         return frameRenderer.hasLayer() && frameRenderer.layer()->isComposited();
2336     
2337     // Don't go into compositing mode if height or width are zero.
2338     return !pixelSnappedIntRect(frameRenderer.contentBoxRect()).isEmpty();
2339 }
2340
2341 bool RenderLayerCompositor::requiresCompositingForAnimation(RenderLayerModelObject& renderer) const
2342 {
2343     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
2344         return false;
2345
2346     AnimationController& animController = renderer.animation();
2347     return (animController.isRunningAnimationOnRenderer(&renderer, CSSPropertyOpacity)
2348             && (inCompositingMode() || (m_compositingTriggers & ChromeClient::AnimatedOpacityTrigger)))
2349 #if ENABLE(CSS_FILTERS)
2350 #if PLATFORM(IOS) || !PLATFORM(MAC) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
2351             // <rdar://problem/10907251> - WebKit2 doesn't support CA animations of CI filters on Lion and below
2352             || animController.isRunningAnimationOnRenderer(&renderer, CSSPropertyWebkitFilter)
2353 #endif // PLATFORM(IOS) || !PLATFORM(MAC) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
2354 #endif // CSS_FILTERS
2355             || animController.isRunningAnimationOnRenderer(&renderer, CSSPropertyWebkitTransform);
2356 }
2357
2358 bool RenderLayerCompositor::requiresCompositingForIndirectReason(RenderLayerModelObject& renderer, bool hasCompositedDescendants, bool hasBlendedDescendants, bool has3DTransformedDescendants, RenderLayer::IndirectCompositingReason& reason) const
2359 {
2360     RenderLayer& layer = *toRenderBoxModelObject(renderer).layer();
2361
2362     // When a layer has composited descendants, some effects, like 2d transforms, filters, masks etc must be implemented
2363     // via compositing so that they also apply to those composited descendants.
2364     if (hasCompositedDescendants && (hasBlendedDescendants || layer.transform() || renderer.createsGroup() || renderer.hasReflection() || renderer.isRenderNamedFlowFragmentContainer())) {
2365         reason = RenderLayer::IndirectCompositingForGraphicalEffect;
2366         return true;
2367     }
2368
2369     // A layer with preserve-3d or perspective only needs to be composited if there are descendant layers that
2370     // will be affected by the preserve-3d or perspective.
2371     if (has3DTransformedDescendants) {
2372         if (renderer.style().transformStyle3D() == TransformStyle3DPreserve3D) {
2373             reason = RenderLayer::IndirectCompositingForPreserve3D;
2374             return true;
2375         }
2376     
2377         if (renderer.style().hasPerspective()) {
2378             reason = RenderLayer::IndirectCompositingForPerspective;
2379             return true;
2380         }
2381     }
2382
2383     reason = RenderLayer::NoIndirectCompositingReason;
2384     return false;
2385 }
2386
2387 #if PLATFORM(IOS)
2388 bool RenderLayerCompositor::requiresCompositingForScrolling(RenderLayerModelObject& renderer) const
2389 {
2390     return renderer.hasLayer() && toRenderBoxModelObject(renderer).layer()->hasAcceleratedTouchScrolling();
2391 }
2392 #endif
2393
2394 bool RenderLayerCompositor::requiresCompositingForFilters(RenderLayerModelObject& renderer) const
2395 {
2396 #if ENABLE(CSS_FILTERS)
2397     if (!(m_compositingTriggers & ChromeClient::FilterTrigger))
2398         return false;
2399
2400     return renderer.hasFilter();
2401 #else
2402     UNUSED_PARAM(renderer);
2403     return false;
2404 #endif
2405 }
2406
2407 bool RenderLayerCompositor::requiresCompositingForBlending(RenderLayerModelObject& renderer) const
2408 {
2409 #if ENABLE(CSS_COMPOSITING)
2410     return renderer.hasBlendMode();
2411 #else
2412     UNUSED_PARAM(renderer);
2413     return false;
2414 #endif
2415 }
2416
2417 #if PLATFORM(IOS)
2418 static bool isStickyInAcceleratedScrollingLayerOrViewport(const RenderLayer& layer, const RenderLayer** enclosingAcceleratedOverflowLayer = 0)
2419 {
2420     ASSERT(layer.renderer().isStickyPositioned());
2421
2422     RenderLayer* enclosingOverflowLayer = layer.enclosingOverflowClipLayer(ExcludeSelf);
2423     if (enclosingOverflowLayer && enclosingOverflowLayer->hasAcceleratedTouchScrolling()) {
2424         if (enclosingAcceleratedOverflowLayer)
2425             *enclosingAcceleratedOverflowLayer = enclosingOverflowLayer;
2426         return true;
2427     }
2428
2429     return !enclosingOverflowLayer;
2430 }
2431 #endif
2432
2433 static bool isViewportConstrainedFixedOrStickyLayer(const RenderLayer& layer)
2434 {
2435 #if PLATFORM(IOS)
2436     if (layer.renderer().isStickyPositioned())
2437         return isStickyInAcceleratedScrollingLayerOrViewport(layer);
2438 #else
2439     if (layer.renderer().isStickyPositioned())
2440         return !layer.enclosingOverflowClipLayer(ExcludeSelf);
2441 #endif
2442
2443     if (layer.renderer().style().position() != FixedPosition)
2444         return false;
2445
2446     for (RenderLayer* stackingContainer = layer.stackingContainer(); stackingContainer; stackingContainer = stackingContainer->stackingContainer()) {
2447         if (stackingContainer->isComposited() && stackingContainer->renderer().style().position() == FixedPosition)
2448             return false;
2449     }
2450
2451     return true;
2452 }
2453
2454 bool RenderLayerCompositor::requiresCompositingForPosition(RenderLayerModelObject& renderer, const RenderLayer& layer, RenderLayer::ViewportConstrainedNotCompositedReason* viewportConstrainedNotCompositedReason) const
2455 {
2456 #if PLATFORM(IOS)
2457     if (renderer.isStickyPositioned())
2458         return true;
2459
2460     // position:fixed elements that create their own stacking context (e.g. have an explicit z-index,
2461     // opacity, transform) can get their own composited layer. A stacking context is required otherwise
2462     // z-index and clipping will be broken.
2463     if (!(renderer.isOutOfFlowPositioned() && renderer.style().position() == FixedPosition))
2464         return false;
2465
2466     if (!m_renderView.hasCustomFixedPosition(renderer, RenderView::CheckContainingBlock)) {
2467         m_reevaluateCompositingAfterLayout = true;
2468         return false;
2469     }
2470 #else
2471     // position:fixed elements that create their own stacking context (e.g. have an explicit z-index,
2472     // opacity, transform) can get their own composited layer. A stacking context is required otherwise
2473     // z-index and clipping will be broken.
2474     if (!renderer.isPositioned())
2475         return false;
2476     
2477     EPosition position = renderer.style().position();
2478     bool isFixed = renderer.isOutOfFlowPositioned() && position == FixedPosition;
2479     if (isFixed && !layer.isStackingContainer())
2480         return false;
2481     
2482     bool isSticky = renderer.isInFlowPositioned() && position == StickyPosition;
2483     if (!isFixed && !isSticky)
2484         return false;
2485
2486     // FIXME: acceleratedCompositingForFixedPositionEnabled should probably be renamed acceleratedCompositingForViewportConstrainedPositionEnabled().
2487     const Settings& settings = m_renderView.frameView().frame().settings();
2488     if (!settings.acceleratedCompositingForFixedPositionEnabled())
2489         return false;
2490
2491     if (isSticky)
2492         return hasCoordinatedScrolling() && isViewportConstrainedFixedOrStickyLayer(layer);
2493 #endif
2494
2495     auto container = renderer.container();
2496     // If the renderer is not hooked up yet then we have to wait until it is.
2497     if (!container) {
2498         m_reevaluateCompositingAfterLayout = true;
2499         return false;
2500     }
2501
2502     // Don't promote fixed position elements that are descendants of a non-view container, e.g. transformed elements.
2503     // They will stay fixed wrt the container rather than the enclosing frame.
2504     if (container != &m_renderView) {
2505         if (viewportConstrainedNotCompositedReason)
2506             *viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForNonViewContainer;
2507         return false;
2508     }
2509     
2510     // Subsequent tests depend on layout. If we can't tell now, just keep things the way they are until layout is done.
2511     if (!m_inPostLayoutUpdate) {
2512         m_reevaluateCompositingAfterLayout = true;
2513         return layer.isComposited();
2514     }
2515
2516     bool paintsContent = layer.isVisuallyNonEmpty() || layer.hasVisibleDescendant();
2517     if (!paintsContent) {
2518         if (viewportConstrainedNotCompositedReason)
2519             *viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForNoVisibleContent;
2520         return false;
2521     }
2522
2523     // Fixed position elements that are invisible in the current view don't get their own layer.
2524 #if PLATFORM(IOS)
2525     LayoutRect viewBounds = m_renderView.frameView().customFixedPositionLayoutRect();
2526 #else
2527     LayoutRect viewBounds = m_renderView.frameView().viewportConstrainedVisibleContentRect();
2528 #endif
2529     LayoutRect layerBounds = layer.calculateLayerBounds(&layer, 0, RenderLayer::UseLocalClipRectIfPossible | RenderLayer::IncludeLayerFilterOutsets | RenderLayer::UseFragmentBoxes
2530         | RenderLayer::ExcludeHiddenDescendants | RenderLayer::DontConstrainForMask | RenderLayer::IncludeCompositedDescendants);
2531     // Map to m_renderView to ignore page scale.
2532     FloatRect absoluteBounds = layer.renderer().localToContainerQuad(FloatRect(layerBounds), &m_renderView).boundingBox();
2533     if (!viewBounds.intersects(enclosingIntRect(absoluteBounds))) {
2534         if (viewportConstrainedNotCompositedReason)
2535             *viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForBoundsOutOfView;
2536         return false;
2537     }
2538     
2539     return true;
2540 }
2541
2542 bool RenderLayerCompositor::requiresCompositingForOverflowScrolling(const RenderLayer& layer) const
2543 {
2544     return layer.needsCompositedScrolling();
2545 }
2546
2547 bool RenderLayerCompositor::isRunningAcceleratedTransformAnimation(RenderLayerModelObject& renderer) const
2548 {
2549     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
2550         return false;
2551
2552     return renderer.animation().isRunningAnimationOnRenderer(&renderer, CSSPropertyWebkitTransform);
2553 }
2554
2555 // If an element has negative z-index children, those children render in front of the 
2556 // layer background, so we need an extra 'contents' layer for the foreground of the layer
2557 // object.
2558 bool RenderLayerCompositor::needsContentsCompositingLayer(const RenderLayer& layer) const
2559 {
2560     return layer.hasNegativeZOrderList();
2561 }
2562
2563 bool RenderLayerCompositor::requiresScrollLayer(RootLayerAttachment attachment) const
2564 {
2565     // This applies when the application UI handles scrolling, in which case RenderLayerCompositor doesn't need to manage it.
2566     if (m_renderView.frameView().delegatesScrolling())
2567         return false;
2568
2569     // We need to handle our own scrolling if we're:
2570     return !m_renderView.frameView().platformWidget() // viewless (i.e. non-Mac, or Mac in WebKit2)
2571         || attachment == RootLayerAttachedViaEnclosingFrame; // a composited frame on Mac
2572 }
2573
2574 static void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
2575 {
2576     if (!scrollbar)
2577         return;
2578
2579     context.save();
2580     const IntRect& scrollbarRect = scrollbar->frameRect();
2581     context.translate(-scrollbarRect.x(), -scrollbarRect.y());
2582     IntRect transformedClip = clip;
2583     transformedClip.moveBy(scrollbarRect.location());
2584     scrollbar->paint(&context, transformedClip);
2585     context.restore();
2586 }
2587
2588 void RenderLayerCompositor::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, GraphicsLayerPaintingPhase, const IntRect& clip)
2589 {
2590     if (graphicsLayer == layerForHorizontalScrollbar())
2591         paintScrollbar(m_renderView.frameView().horizontalScrollbar(), context, clip);
2592     else if (graphicsLayer == layerForVerticalScrollbar())
2593         paintScrollbar(m_renderView.frameView().verticalScrollbar(), context, clip);
2594     else if (graphicsLayer == layerForScrollCorner()) {
2595         const IntRect& scrollCorner = m_renderView.frameView().scrollCornerRect();
2596         context.save();
2597         context.translate(-scrollCorner.x(), -scrollCorner.y());
2598         IntRect transformedClip = clip;
2599         transformedClip.moveBy(scrollCorner.location());
2600         m_renderView.frameView().paintScrollCorner(&context, transformedClip);
2601         context.restore();
2602     }
2603 }
2604
2605 bool RenderLayerCompositor::supportsFixedRootBackgroundCompositing() const
2606 {
2607     RenderLayerBacking* renderViewBacking = m_renderView.layer()->backing();
2608     return renderViewBacking && renderViewBacking->usingTiledBacking();
2609 }
2610
2611 bool RenderLayerCompositor::needsFixedRootBackgroundLayer(const RenderLayer& layer) const
2612 {
2613     if (&layer != m_renderView.layer())
2614         return false;
2615
2616     return supportsFixedRootBackgroundCompositing() && m_renderView.rootBackgroundIsEntirelyFixed();
2617 }
2618
2619 GraphicsLayer* RenderLayerCompositor::fixedRootBackgroundLayer() const
2620 {
2621     // Get the fixed root background from the RenderView layer's backing.
2622     RenderLayer* viewLayer = m_renderView.layer();
2623     if (!viewLayer)
2624         return nullptr;
2625
2626     if (viewLayer->isComposited() && viewLayer->backing()->backgroundLayerPaintsFixedRootBackground())
2627         return viewLayer->backing()->backgroundLayer();
2628
2629     return nullptr;
2630 }
2631
2632 static void resetTrackedRepaintRectsRecursive(GraphicsLayer& graphicsLayer)
2633 {
2634     graphicsLayer.resetTrackedRepaints();
2635
2636     for (size_t i = 0, size = graphicsLayer.children().size(); i < size; ++i)
2637         resetTrackedRepaintRectsRecursive(*graphicsLayer.children()[i]);
2638
2639     if (GraphicsLayer* replicaLayer = graphicsLayer.replicaLayer())
2640         resetTrackedRepaintRectsRecursive(*replicaLayer);
2641
2642     if (GraphicsLayer* maskLayer = graphicsLayer.maskLayer())
2643         resetTrackedRepaintRectsRecursive(*maskLayer);
2644 }
2645
2646 void RenderLayerCompositor::resetTrackedRepaintRects()
2647 {
2648     if (GraphicsLayer* rootLayer = rootGraphicsLayer())
2649         resetTrackedRepaintRectsRecursive(*rootLayer);
2650 }
2651
2652 void RenderLayerCompositor::setTracksRepaints(bool tracksRepaints)
2653 {
2654     m_isTrackingRepaints = tracksRepaints;
2655 }
2656
2657 bool RenderLayerCompositor::isTrackingRepaints() const
2658 {
2659     return m_isTrackingRepaints;
2660 }
2661
2662 float RenderLayerCompositor::deviceScaleFactor() const
2663 {
2664     Page* page = this->page();
2665     return page ? page->deviceScaleFactor() : 1;
2666 }
2667
2668 float RenderLayerCompositor::pageScaleFactor() const
2669 {
2670     Page* page = this->page();
2671     return page ? page->pageScaleFactor() : 1;
2672 }
2673
2674 float RenderLayerCompositor::contentsScaleMultiplierForNewTiles(const GraphicsLayer*) const
2675 {
2676 #if PLATFORM(IOS)
2677     TileCache* tileCache = nullptr;
2678     if (Page* page = this->page()) {
2679         if (FrameView* frameView = page->mainFrame().view())
2680             tileCache = frameView->tileCache();
2681     }
2682
2683     if (!tileCache)
2684         return 1;
2685
2686     return tileCache->tilingMode() == TileCache::Zooming ? 0.125 : 1;
2687 #else
2688     return 1;
2689 #endif
2690 }
2691
2692 void RenderLayerCompositor::didCommitChangesForLayer(const GraphicsLayer*) const
2693 {
2694     // Nothing to do here yet.
2695 }
2696
2697 bool RenderLayerCompositor::keepLayersPixelAligned() const
2698 {
2699     // When scaling, attempt to align compositing layers to pixel boundaries.
2700     return true;
2701 }
2702
2703 bool RenderLayerCompositor::mainFrameBackingIsTiled() const
2704 {
2705     RenderLayer* layer = m_renderView.layer();
2706     if (!layer)
2707         return false;
2708
2709     RenderLayerBacking* backing = layer->backing();
2710     if (!backing)
2711         return false;
2712
2713     return backing->usingTiledBacking();
2714 }
2715
2716 bool RenderLayerCompositor::mainFrameBackingIsTiledWithMargin() const
2717 {
2718     RenderLayer* layer = m_renderView.layer();
2719     if (!layer)
2720         return false;
2721
2722     RenderLayerBacking* backing = layer->backing();
2723     if (!backing)
2724         return false;
2725
2726     return backing->tiledBackingHasMargin();
2727 }
2728
2729 bool RenderLayerCompositor::shouldCompositeOverflowControls() const
2730 {
2731     FrameView& frameView = m_renderView.frameView();
2732
2733     if (frameView.platformWidget())
2734         return false;
2735
2736     if (mainFrameBackingIsTiled())
2737         return true;
2738
2739     if (!frameView.hasOverlayScrollbars())
2740         return false;
2741
2742     return true;
2743 }
2744
2745 bool RenderLayerCompositor::requiresHorizontalScrollbarLayer() const
2746 {
2747     return shouldCompositeOverflowControls() && m_renderView.frameView().horizontalScrollbar();
2748 }
2749
2750 bool RenderLayerCompositor::requiresVerticalScrollbarLayer() const
2751 {
2752     return shouldCompositeOverflowControls() && m_renderView.frameView().verticalScrollbar();
2753 }
2754
2755 bool RenderLayerCompositor::requiresScrollCornerLayer() const
2756 {
2757     return shouldCompositeOverflowControls() && m_renderView.frameView().isScrollCornerVisible();
2758 }
2759
2760 #if ENABLE(RUBBER_BANDING)
2761 bool RenderLayerCompositor::requiresOverhangAreasLayer() const
2762 {
2763     // We don't want a layer if this is a subframe.
2764     if (m_renderView.document().ownerElement())
2765         return false;
2766
2767     // We do want a layer if we're using tiled drawing and can scroll.
2768     if (mainFrameBackingIsTiled() && m_renderView.frameView().hasOpaqueBackground() && !m_renderView.frameView().prohibitsScrolling())
2769         return true;
2770
2771     return false;
2772 }
2773
2774 bool RenderLayerCompositor::requiresContentShadowLayer() const
2775 {
2776     // We don't want a layer if this is a subframe.
2777     if (m_renderView.document().ownerElement())
2778         return false;
2779
2780 #if PLATFORM(MAC)
2781     if (viewHasTransparentBackground())
2782         return false;
2783
2784     // On Mac, we want a content shadow layer if we're using tiled drawing and can scroll.
2785     if (mainFrameBackingIsTiled() && !m_renderView.frameView().prohibitsScrolling())
2786         return true;
2787 #endif
2788
2789     return false;
2790 }
2791
2792 GraphicsLayer* RenderLayerCompositor::updateLayerForTopOverhangArea(bool wantsLayer)
2793 {
2794     if (m_renderView.document().ownerElement())
2795         return 0;
2796
2797     if (!wantsLayer) {
2798         if (m_layerForTopOverhangArea) {
2799             m_layerForTopOverhangArea->removeFromParent();
2800             m_layerForTopOverhangArea = nullptr;
2801         }
2802         return 0;
2803     }
2804
2805     if (!m_layerForTopOverhangArea) {
2806         m_layerForTopOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), this);
2807 #ifndef NDEBUG
2808         m_layerForTopOverhangArea->setName("top overhang area");
2809 #endif
2810         m_scrollLayer->addChildBelow(m_layerForTopOverhangArea.get(), m_rootContentLayer.get());
2811     }
2812
2813     return m_layerForTopOverhangArea.get();
2814 }
2815
2816 GraphicsLayer* RenderLayerCompositor::updateLayerForBottomOverhangArea(bool wantsLayer)
2817 {
2818     if (m_renderView.document().ownerElement())
2819         return 0;
2820
2821     if (!wantsLayer) {
2822         if (m_layerForBottomOverhangArea) {
2823             m_layerForBottomOverhangArea->removeFromParent();
2824             m_layerForBottomOverhangArea = nullptr;
2825         }
2826         return 0;
2827     }
2828
2829     if (!m_layerForBottomOverhangArea) {
2830         m_layerForBottomOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), this);
2831 #ifndef NDEBUG
2832         m_layerForBottomOverhangArea->setName("bottom overhang area");
2833 #endif
2834         m_scrollLayer->addChildBelow(m_layerForBottomOverhangArea.get(), m_rootContentLayer.get());
2835     }
2836
2837     m_layerForBottomOverhangArea->setPosition(FloatPoint(0, m_rootContentLayer->size().height() + m_renderView.frameView().headerHeight() + m_renderView.frameView().footerHeight()));
2838     return m_layerForBottomOverhangArea.get();
2839 }
2840
2841 GraphicsLayer* RenderLayerCompositor::updateLayerForHeader(bool wantsLayer)
2842 {
2843     if (m_renderView.document().ownerElement())
2844         return 0;
2845
2846     if (!wantsLayer) {
2847         if (m_layerForHeader) {
2848             m_layerForHeader->removeFromParent();
2849             m_layerForHeader = nullptr;
2850
2851             // The ScrollingTree knows about the header layer, and the position of the root layer is affected
2852             // by the header layer, so if we remove the header, we need to tell the scrolling tree.
2853             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2854                 scrollingCoordinator->frameViewRootLayerDidChange(&m_renderView.frameView());
2855         }
2856         return 0;
2857     }
2858
2859     if (!m_layerForHeader) {
2860         m_layerForHeader = GraphicsLayer::create(graphicsLayerFactory(), this);
2861 #ifndef NDEBUG
2862         m_layerForHeader->setName("header");
2863 #endif
2864         m_scrollLayer->addChildBelow(m_layerForHeader.get(), m_rootContentLayer.get());
2865         m_renderView.frameView().addPaintPendingMilestones(DidFirstFlushForHeaderLayer);
2866     }
2867
2868     m_layerForHeader->setPosition(FloatPoint());
2869     m_layerForHeader->setAnchorPoint(FloatPoint3D());
2870     m_layerForHeader->setSize(FloatSize(m_renderView.frameView().visibleWidth(), m_renderView.frameView().headerHeight()));
2871
2872     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2873         scrollingCoordinator->frameViewRootLayerDidChange(&m_renderView.frameView());
2874
2875     if (Page* page = this->page())
2876         page->chrome().client().didAddHeaderLayer(m_layerForHeader.get());
2877
2878     return m_layerForHeader.get();
2879 }
2880
2881 GraphicsLayer* RenderLayerCompositor::updateLayerForFooter(bool wantsLayer)
2882 {
2883     if (m_renderView.document().ownerElement())
2884         return 0;
2885
2886     if (!wantsLayer) {
2887         if (m_layerForFooter) {
2888             m_layerForFooter->removeFromParent();
2889             m_layerForFooter = nullptr;
2890
2891             // The ScrollingTree knows about the footer layer, and the total scrollable size is affected
2892             // by the footer layer, so if we remove the footer, we need to tell the scrolling tree.
2893             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2894                 scrollingCoordinator->frameViewRootLayerDidChange(&m_renderView.frameView());
2895         }
2896         return 0;
2897     }
2898
2899     if (!m_layerForFooter) {
2900         m_layerForFooter = GraphicsLayer::create(graphicsLayerFactory(), this);
2901 #ifndef NDEBUG
2902         m_layerForFooter->setName("footer");
2903 #endif
2904         m_scrollLayer->addChildBelow(m_layerForFooter.get(), m_rootContentLayer.get());
2905     }
2906
2907     m_layerForFooter->setPosition(FloatPoint(0, m_rootContentLayer->size().height() + m_renderView.frameView().headerHeight()));
2908     m_layerForFooter->setAnchorPoint(FloatPoint3D());
2909     m_layerForFooter->setSize(FloatSize(m_renderView.frameView().visibleWidth(), m_renderView.frameView().footerHeight()));
2910
2911     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2912         scrollingCoordinator->frameViewRootLayerDidChange(&m_renderView.frameView());
2913
2914     if (Page* page = this->page())
2915         page->chrome().client().didAddFooterLayer(m_layerForFooter.get());
2916
2917     return m_layerForFooter.get();
2918 }
2919
2920 #endif
2921
2922 bool RenderLayerCompositor::viewHasTransparentBackground(Color* backgroundColor) const
2923 {
2924     if (m_renderView.frameView().isTransparent()) {
2925         if (backgroundColor)
2926             *backgroundColor = Color(); // Return an invalid color.
2927         return true;
2928     }
2929
2930     Color documentBackgroundColor = m_renderView.frameView().documentBackgroundColor();
2931     if (!documentBackgroundColor.isValid())
2932         documentBackgroundColor = Color::white;
2933
2934     if (backgroundColor)
2935         *backgroundColor = documentBackgroundColor;
2936         
2937     return documentBackgroundColor.hasAlpha();
2938 }
2939
2940 void RenderLayerCompositor::updateOverflowControlsLayers()
2941 {
2942 #if ENABLE(RUBBER_BANDING)
2943     if (requiresOverhangAreasLayer()) {
2944         if (!m_layerForOverhangAreas) {
2945             m_layerForOverhangAreas = GraphicsLayer::create(graphicsLayerFactory(), this);
2946 #ifndef NDEBUG
2947             m_layerForOverhangAreas->setName("overhang areas");
2948 #endif
2949             m_layerForOverhangAreas->setDrawsContent(false);
2950             m_layerForOverhangAreas->setSize(m_renderView.frameView().frameRect().size());
2951             m_layerForOverhangAreas->setCustomAppearance(GraphicsLayer::ScrollingOverhang);
2952
2953             // We want the overhang areas layer to be positioned below the frame contents,
2954             // so insert it below the clip layer.
2955             m_overflowControlsHostLayer->addChildBelow(m_layerForOverhangAreas.get(), m_clipLayer.get());
2956         }
2957     } else if (m_layerForOverhangAreas) {
2958         m_layerForOverhangAreas->removeFromParent();
2959         m_layerForOverhangAreas = nullptr;
2960     }
2961
2962     if (requiresContentShadowLayer()) {
2963         if (!m_contentShadowLayer) {
2964             m_contentShadowLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
2965 #ifndef NDEBUG
2966             m_contentShadowLayer->setName("content shadow");
2967 #endif
2968             m_contentShadowLayer->setSize(m_rootContentLayer->size());
2969             m_contentShadowLayer->setPosition(m_rootContentLayer->position());
2970             m_contentShadowLayer->setCustomAppearance(GraphicsLayer::ScrollingShadow);
2971
2972             m_scrollLayer->addChildBelow(m_contentShadowLayer.get(), m_rootContentLayer.get());
2973         }
2974     } else if (m_contentShadowLayer) {
2975         m_contentShadowLayer->removeFromParent();
2976         m_contentShadowLayer = nullptr;
2977     }
2978 #endif
2979
2980     if (requiresHorizontalScrollbarLayer()) {
2981         if (!m_layerForHorizontalScrollbar) {
2982             m_layerForHorizontalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), this);
2983             m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
2984 #ifndef NDEBUG
2985             m_layerForHorizontalScrollbar->setName("horizontal scrollbar container");
2986
2987 #endif
2988 #if PLATFORM(MAC) && USE(CA)
2989             m_layerForHorizontalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
2990 #endif
2991             m_overflowControlsHostLayer->addChild(m_layerForHorizontalScrollbar.get());
2992
2993             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2994                 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_renderView.frameView(), HorizontalScrollbar);
2995         }
2996     } else if (m_layerForHorizontalScrollbar) {
2997         m_layerForHorizontalScrollbar->removeFromParent();
2998         m_layerForHorizontalScrollbar = nullptr;
2999
3000         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3001             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_renderView.frameView(), HorizontalScrollbar);
3002     }
3003
3004     if (requiresVerticalScrollbarLayer()) {
3005         if (!m_layerForVerticalScrollbar) {
3006             m_layerForVerticalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), this);
3007             m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
3008 #ifndef NDEBUG
3009             m_layerForVerticalScrollbar->setName("vertical scrollbar container");
3010 #endif
3011 #if PLATFORM(MAC) && USE(CA)
3012             m_layerForVerticalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
3013 #endif
3014             m_overflowControlsHostLayer->addChild(m_layerForVerticalScrollbar.get());
3015
3016             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3017                 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_renderView.frameView(), VerticalScrollbar);
3018         }
3019     } else if (m_layerForVerticalScrollbar) {
3020         m_layerForVerticalScrollbar->removeFromParent();
3021         m_layerForVerticalScrollbar = nullptr;
3022
3023         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3024             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_renderView.frameView(), VerticalScrollbar);
3025     }
3026
3027     if (requiresScrollCornerLayer()) {
3028         if (!m_layerForScrollCorner) {
3029             m_layerForScrollCorner = GraphicsLayer::create(graphicsLayerFactory(), this);
3030             m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
3031 #ifndef NDEBUG
3032             m_layerForScrollCorner->setName("scroll corner");
3033 #endif
3034 #if PLATFORM(MAC) && USE(CA)
3035             m_layerForScrollCorner->setAcceleratesDrawing(acceleratedDrawingEnabled());
3036 #endif
3037             m_overflowControlsHostLayer->addChild(m_layerForScrollCorner.get());
3038         }
3039     } else if (m_layerForScrollCorner) {
3040         m_layerForScrollCorner->removeFromParent();
3041         m_layerForScrollCorner = nullptr;
3042     }
3043
3044     m_renderView.frameView().positionScrollbarLayers();
3045 }
3046
3047 void RenderLayerCompositor::ensureRootLayer()
3048 {
3049     RootLayerAttachment expectedAttachment = shouldPropagateCompositingToEnclosingFrame() ? RootLayerAttachedViaEnclosingFrame : RootLayerAttachedViaChromeClient;
3050     if (expectedAttachment == m_rootLayerAttachment)
3051          return;
3052
3053     if (!m_rootContentLayer) {
3054         m_rootContentLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
3055 #ifndef NDEBUG
3056         m_rootContentLayer->setName("content root");
3057 #endif
3058         IntRect overflowRect = m_renderView.pixelSnappedLayoutOverflowRect();
3059         m_rootContentLayer->setSize(FloatSize(overflowRect.maxX(), overflowRect.maxY()));
3060         m_rootContentLayer->setPosition(FloatPoint());
3061
3062 #if PLATFORM(IOS)
3063         // Page scale is applied above this on iOS, so we'll just say that our root layer applies it.
3064         Frame& frame = m_renderView.frameView().frame();
3065         if (frame.isMainFrame())
3066             m_rootContentLayer->setAppliesPageScale();
3067 #endif
3068
3069         // Need to clip to prevent transformed content showing outside this frame
3070         m_rootContentLayer->setMasksToBounds(true);
3071     }
3072
3073     if (requiresScrollLayer(expectedAttachment)) {
3074         if (!m_overflowControlsHostLayer) {
3075             ASSERT(!m_scrollLayer);
3076             ASSERT(!m_clipLayer);
3077
3078             // Create a layer to host the clipping layer and the overflow controls layers.
3079             m_overflowControlsHostLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
3080 #ifndef NDEBUG
3081             m_overflowControlsHostLayer->setName("overflow controls host");
3082 #endif
3083
3084             // Create a clipping layer if this is an iframe
3085             m_clipLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
3086 #ifndef NDEBUG
3087             m_clipLayer->setName("frame clipping");
3088 #endif
3089             m_clipLayer->setMasksToBounds(true);
3090             
3091             m_scrollLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
3092 #ifndef NDEBUG
3093             m_scrollLayer->setName("frame scrolling");
3094 #endif
3095             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3096                 scrollingCoordinator->setLayerIsContainerForFixedPositionLayers(m_scrollLayer.get(), true);
3097
3098             // Hook them up
3099             m_overflowControlsHostLayer->addChild(m_clipLayer.get());
3100             m_clipLayer->addChild(m_scrollLayer.get());
3101             m_scrollLayer->addChild(m_rootContentLayer.get());
3102
3103             frameViewDidChangeSize();
3104             frameViewDidScroll();
3105         }
3106     } else {
3107         if (m_overflowControlsHostLayer) {
3108             m_overflowControlsHostLayer = nullptr;
3109             m_clipLayer = nullptr;
3110             m_scrollLayer = nullptr;
3111         }
3112     }
3113
3114     // Check to see if we have to change the attachment
3115     if (m_rootLayerAttachment != RootLayerUnattached)
3116         detachRootLayer();
3117
3118     attachRootLayer(expectedAttachment);
3119 }
3120
3121 void RenderLayerCompositor::destroyRootLayer()
3122 {
3123     if (!m_rootContentLayer)
3124         return;
3125
3126     detachRootLayer();
3127
3128 #if ENABLE(RUBBER_BANDING)
3129     if (m_layerForOverhangAreas) {
3130         m_layerForOverhangAreas->removeFromParent();
3131         m_layerForOverhangAreas = nullptr;
3132     }
3133 #endif
3134
3135     if (m_layerForHorizontalScrollbar) {
3136         m_layerForHorizontalScrollbar->removeFromParent();
3137         m_layerForHorizontalScrollbar = nullptr;
3138         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3139             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_renderView.frameView(), HorizontalScrollbar);
3140         if (Scrollbar* horizontalScrollbar = m_renderView.frameView().verticalScrollbar())
3141             m_renderView.frameView().invalidateScrollbar(horizontalScrollbar, IntRect(IntPoint(0, 0), horizontalScrollbar->frameRect().size()));
3142     }
3143
3144     if (m_layerForVerticalScrollbar) {
3145         m_layerForVerticalScrollbar->removeFromParent();
3146         m_layerForVerticalScrollbar = nullptr;
3147         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3148             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_renderView.frameView(), VerticalScrollbar);
3149         if (Scrollbar* verticalScrollbar = m_renderView.frameView().verticalScrollbar())
3150             m_renderView.frameView().invalidateScrollbar(verticalScrollbar, IntRect(IntPoint(0, 0), verticalScrollbar->frameRect().size()));
3151     }
3152
3153     if (m_layerForScrollCorner) {
3154         m_layerForScrollCorner = nullptr;
3155         m_renderView.frameView().invalidateScrollCorner(m_renderView.frameView().scrollCornerRect());
3156     }
3157
3158     if (m_overflowControlsHostLayer) {
3159         m_overflowControlsHostLayer = nullptr;
3160         m_clipLayer = nullptr;
3161         m_scrollLayer = nullptr;
3162     }
3163     ASSERT(!m_scrollLayer);
3164     m_rootContentLayer = nullptr;
3165
3166     m_layerUpdater = nullptr;
3167 }
3168
3169 void RenderLayerCompositor::attachRootLayer(RootLayerAttachment attachment)
3170 {
3171     if (!m_rootContentLayer)
3172         return;
3173
3174     switch (attachment) {
3175         case RootLayerUnattached:
3176             ASSERT_NOT_REACHED();
3177             break;
3178         case RootLayerAttachedViaChromeClient: {
3179             Frame& frame = m_renderView.frameView().frame();
3180             Page* page = frame.page();
3181             if (!page)
3182                 return;
3183
3184             page->chrome().client().attachRootGraphicsLayer(&frame, rootGraphicsLayer());
3185             break;
3186         }
3187         case RootLayerAttachedViaEnclosingFrame: {
3188             // The layer will get hooked up via RenderLayerBacking::updateGraphicsLayerConfiguration()
3189             // for the frame's renderer in the parent document.
3190             m_renderView.document().ownerElement()->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
3191             break;
3192         }
3193     }
3194
3195     m_rootLayerAttachment = attachment;
3196     rootLayerAttachmentChanged();
3197     
3198     if (m_shouldFlushOnReattach) {
3199         scheduleLayerFlushNow();
3200         m_shouldFlushOnReattach = false;
3201     }
3202 }
3203
3204 void RenderLayerCompositor::detachRootLayer()
3205 {
3206     if (!m_rootContentLayer || m_rootLayerAttachment == RootLayerUnattached)
3207         return;
3208
3209     switch (m_rootLayerAttachment) {
3210     case RootLayerAttachedViaEnclosingFrame: {
3211         // The layer will get unhooked up via RenderLayerBacking::updateGraphicsLayerConfiguration()
3212         // for the frame's renderer in the parent document.
3213         if (m_overflowControlsHostLayer)
3214             m_overflowControlsHostLayer->removeFromParent();
3215         else
3216             m_rootContentLayer->removeFromParent();
3217
3218         if (HTMLFrameOwnerElement* ownerElement = m_renderView.document().ownerElement())
3219             ownerElement->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
3220         break;
3221     }
3222     case RootLayerAttachedViaChromeClient: {
3223         Frame& frame = m_renderView.frameView().frame();
3224         Page* page = frame.page();
3225         if (!page)
3226             return;
3227
3228         page->chrome().client().attachRootGraphicsLayer(&frame, 0);
3229     }
3230     break;
3231     case RootLayerUnattached:
3232         break;
3233     }
3234
3235     m_rootLayerAttachment = RootLayerUnattached;
3236     rootLayerAttachmentChanged();
3237 }
3238
3239 void RenderLayerCompositor::updateRootLayerAttachment()
3240 {
3241     ensureRootLayer();
3242 }
3243
3244 void RenderLayerCompositor::rootLayerAttachmentChanged()
3245 {
3246     // The attachment can affect whether the RenderView layer's paintsIntoWindow() behavior,
3247     // so call updateGraphicsLayerGeometry() to udpate that.
3248     RenderLayer* layer = m_renderView.layer();
3249     if (RenderLayerBacking* backing = layer ? layer->backing() : 0)
3250         backing->updateDrawsContent();
3251 }
3252
3253 // IFrames are special, because we hook compositing layers together across iframe boundaries
3254 // when both parent and iframe content are composited. So when this frame becomes composited, we have
3255 // to use a synthetic style change to get the iframes into RenderLayers in order to allow them to composite.
3256 void RenderLayerCompositor::notifyIFramesOfCompositingChange()
3257 {
3258     Frame& frame = m_renderView.frameView().frame();
3259
3260     for (Frame* child = frame.tree().firstChild(); child; child = child->tree().traverseNext(&frame)) {
3261         if (child->document() && child->document()->ownerElement())
3262             child->document()->ownerElement()->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
3263     }
3264     
3265     // Compositing also affects the answer to RenderIFrame::requiresAcceleratedCompositing(), so 
3266     // we need to schedule a style recalc in our parent document.
3267     if (HTMLFrameOwnerElement* ownerElement = m_renderView.document().ownerElement())
3268         ownerElement->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
3269 }
3270
3271 bool RenderLayerCompositor::layerHas3DContent(const RenderLayer& layer) const
3272 {
3273     const RenderStyle& style = layer.renderer().style();
3274
3275     if (style.transformStyle3D() == TransformStyle3DPreserve3D || style.hasPerspective() || style.transform().has3DOperation())
3276         return true;
3277
3278     const_cast<RenderLayer&>(layer).updateLayerListsIfNeeded();
3279
3280 #if !ASSERT_DISABLED
3281     LayerListMutationDetector mutationChecker(const_cast<RenderLayer*>(&layer));
3282 #endif
3283
3284     if (layer.isStackingContainer()) {
3285         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
3286             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i) {
3287                 if (layerHas3DContent(*negZOrderList->at(i)))
3288                     return true;
3289             }
3290         }
3291
3292         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {
3293             for (size_t i = 0, size = posZOrderList->size(); i < size; ++i) {
3294                 if (layerHas3DContent(*posZOrderList->at(i)))
3295                     return true;
3296             }
3297         }
3298     }
3299
3300     if (Vector<RenderLayer*>* normalFlowList = layer.normalFlowList()) {
3301         for (size_t i = 0, size = normalFlowList->size(); i < size; ++i) {
3302             if (layerHas3DContent(*normalFlowList->at(i)))
3303                 return true;
3304         }
3305     }
3306
3307     return false;
3308 }
3309
3310 void RenderLayerCompositor::deviceOrPageScaleFactorChanged()
3311 {
3312     // Start at the RenderView's layer, since that's where the scale is applied.
3313     RenderLayer* viewLayer = m_renderView.layer();
3314     if (!viewLayer->isComposited())
3315         return;
3316
3317     if (GraphicsLayer* rootLayer = viewLayer->backing()->childForSuperlayers())
3318         rootLayer->noteDeviceOrPageScaleFactorChangedIncludingDescendants();
3319 }
3320
3321 void RenderLayerCompositor::updateViewportConstraintStatus(RenderLayer& layer)
3322 {
3323     if (isViewportConstrainedFixedOrStickyLayer(layer))
3324         addViewportConstrainedLayer(layer);
3325     else
3326         removeViewportConstrainedLayer(layer);
3327 }
3328
3329 void RenderLayerCompositor::addViewportConstrainedLayer(RenderLayer& layer)
3330 {
3331     m_viewportConstrainedLayers.add(&layer);
3332     registerOrUpdateViewportConstrainedLayer(layer);
3333 }
3334
3335 void RenderLayerCompositor::removeViewportConstrainedLayer(RenderLayer& layer)
3336 {
3337     if (!m_viewportConstrainedLayers.contains(&layer))
3338         return;
3339
3340     unregisterViewportConstrainedLayer(layer);
3341     m_viewportConstrainedLayers.remove(&layer);
3342     m_viewportConstrainedLayersNeedingUpdate.remove(&layer);
3343 }
3344
3345 FixedPositionViewportConstraints RenderLayerCompositor::computeFixedViewportConstraints(RenderLayer& layer) const
3346 {
3347     ASSERT(layer.isComposited());
3348
3349 #if PLATFORM(IOS)
3350     LayoutRect viewportRect = m_renderView.frameView().customFixedPositionLayoutRect();
3351 #else
3352     LayoutRect viewportRect = m_renderView.frameView().viewportConstrainedVisibleContentRect();
3353 #endif
3354
3355     FixedPositionViewportConstraints constraints;
3356
3357     GraphicsLayer* graphicsLayer = layer.backing()->graphicsLayer();
3358
3359     constraints.setLayerPositionAtLastLayout(graphicsLayer->position());
3360     constraints.setViewportRectAtLastLayout(viewportRect);
3361
3362     const RenderStyle& style = layer.renderer().style();
3363     if (!style.left().isAuto())
3364         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeLeft);
3365
3366     if (!style.right().isAuto())
3367         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeRight);
3368
3369     if (!style.top().isAuto())
3370         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeTop);
3371
3372     if (!style.bottom().isAuto())
3373         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeBottom);
3374
3375     // If left and right are auto, use left.
3376     if (style.left().isAuto() && style.right().isAuto())
3377         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeLeft);
3378
3379     // If top and bottom are auto, use top.
3380     if (style.top().isAuto() && style.bottom().isAuto())
3381         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeTop);
3382         
3383     return constraints;
3384 }
3385
3386 StickyPositionViewportConstraints RenderLayerCompositor::computeStickyViewportConstraints(RenderLayer& layer) const
3387 {
3388     ASSERT(layer.isComposited());
3389 #if !PLATFORM(IOS)
3390     // We should never get here for stickies constrained by an enclosing clipping layer.
3391     // FIXME: Why does this assertion fail on iOS?
3392     ASSERT(!layer.enclosingOverflowClipLayer(ExcludeSelf));
3393 #endif
3394
3395 #if PLATFORM(IOS)
3396     LayoutRect viewportRect = m_renderView.frameView().customFixedPositionLayoutRect();
3397 #else
3398     LayoutRect viewportRect = m_renderView.frameView().viewportConstrainedVisibleContentRect();
3399 #endif
3400
3401     RenderBoxModelObject& renderer = toRenderBoxModelObject(layer.renderer());
3402
3403     StickyPositionViewportConstraints constraints;
3404     renderer.computeStickyPositionConstraints(constraints, viewportRect);
3405
3406     GraphicsLayer* graphicsLayer = layer.backing()->graphicsLayer();
3407
3408     constraints.setLayerPositionAtLastLayout(graphicsLayer->position());
3409     constraints.setStickyOffsetAtLastLayout(renderer.stickyPositionOffset());
3410
3411     return constraints;
3412 }
3413
3414 #if !PLATFORM(IOS)
3415 static RenderLayerBacking* nearestScrollingCoordinatorAncestor(RenderLayer& layer)
3416 {
3417     RenderLayer* ancestor = layer.parent();
3418     while (ancestor) {
3419         if (RenderLayerBacking* backing = ancestor->backing()) {
3420             if (backing->scrollLayerID() && !ancestor->scrollsOverflow())
3421                 return backing;
3422         }
3423         ancestor = ancestor->parent();
3424     }
3425
3426     return nullptr;
3427 }
3428 #endif
3429
3430 void RenderLayerCompositor::registerOrUpdateViewportConstrainedLayer(RenderLayer& layer)
3431 {
3432 #if PLATFORM(IOS)
3433     UNUSED_PARAM(layer);
3434     // On iOS, we batch-update viewport-constrained layers in updateCustomLayersAfterFlush().
3435 #else
3436     // FIXME: We should support sticky position here! And we should eventuall support fixed/sticky elements
3437     // that are inside non-main frames once we get non-main frames scrolling with the ScrollingCoordinator.
3438     if (m_renderView.document().ownerElement())
3439         return;
3440
3441     ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator();
3442     if (!scrollingCoordinator)
3443         return;
3444
3445     // FIXME: rename to supportsViewportConstrainedPositionLayers()?
3446     if (!scrollingCoordinator->supportsFixedPositionLayers() || !layer.parent())
3447         return;
3448
3449     ASSERT(m_viewportConstrainedLayers.contains(&layer));
3450     ASSERT(layer.isComposited());
3451
3452     RenderLayerBacking* backing = layer.backing();
3453     if (!backing)
3454         return;
3455
3456     ScrollingNodeID nodeID = backing->scrollLayerID();
3457     RenderLayerBacking* parent = nearestScrollingCoordinatorAncestor(layer);
3458     if (!parent)
3459         return;
3460
3461     // Always call this even if the backing is already attached because the parent may have changed.
3462     backing->attachToScrollingCoordinatorWithParent(parent);
3463     nodeID = backing->scrollLayerID();
3464
3465     if (layer.renderer().isStickyPositioned())
3466         scrollingCoordinator->updateViewportConstrainedNode(nodeID, computeStickyViewportConstraints(layer), backing->graphicsLayer());
3467     else
3468         scrollingCoordinator->updateViewportConstrainedNode(nodeID, computeFixedViewportConstraints(layer), backing->graphicsLayer());
3469 #endif
3470 }
3471
3472 void RenderLayerCompositor::unregisterViewportConstrainedLayer(RenderLayer& layer)
3473 {
3474     ASSERT(m_viewportConstrainedLayers.contains(&layer));
3475 #if PLATFORM(IOS)
3476     UNUSED_PARAM(layer);
3477     // On iOS, we batch-update viewport-constrained layers in updateCustomLayersAfterFlush().
3478 #else
3479     if (RenderLayerBacking* backing = layer.backing())
3480         backing->detachFromScrollingCoordinator();
3481 #endif
3482 }
3483
3484 #if PLATFORM(IOS)
3485 typedef HashMap<PlatformLayer*, OwnPtr<ViewportConstraints>> LayerMap;
3486 typedef HashMap<PlatformLayer*, PlatformLayer*> StickyContainerMap;
3487
3488 void RenderLayerCompositor::registerAllViewportConstrainedLayers()
3489 {
3490     // Only the main frame should register fixed/sticky layers.
3491     if (m_renderView.document().ownerElement())
3492         return;
3493
3494     LayerMap layerMap;
3495     StickyContainerMap stickyContainerMap;
3496
3497     for (auto it = m_viewportConstrainedLayers.begin(), end = m_viewportConstrainedLayers.end(); it != end; ++it) {
3498         RenderLayer& layer = **it;
3499         ASSERT(layer.isComposited());
3500
3501         std::unique_ptr<ViewportConstraints> constraints;
3502         if (layer.renderer().isStickyPositioned()) {
3503             constraints = std::make_unique<ViewportConstraints>(new StickyPositionViewportConstraints(computeStickyViewportConstraints(layer)));
3504             const RenderLayer* enclosingTouchScrollableLayer = nullptr;
3505             if (isStickyInAcceleratedScrollingLayerOrViewport(layer, &enclosingTouchScrollableLayer) && enclosingTouchScrollableLayer) {
3506                 ASSERT(enclosingTouchScrollableLayer->isComposited());
3507                 stickyContainerMap.add(layer.backing()->graphicsLayer()->platformLayer(), enclosingTouchScrollableLayer->backing()->scrollingLayer()->platformLayer());
3508             }
3509         } else
3510             constraints = std::make_unique<ViewportConstraints>(new FixedPositionViewportConstraints(computeFixedViewportConstraints(layer)));
3511
3512         layerMap.add(layer.backing()->graphicsLayer()->platformLayer(), constraints.release());
3513     }
3514     
3515     if (ChromeClient* client = this->chromeClient())
3516         client->updateViewportConstrainedLayers(layerMap, stickyContainerMap);
3517 }
3518
3519 void RenderLayerCompositor::unregisterAllViewportConstrainedLayers()
3520 {
3521     // Only the main frame should register fixed/sticky layers.
3522     if (m_renderView.document().ownerElement())
3523         return;
3524
3525     if (ChromeClient* client = this->chromeClient()) {
3526         LayerMap layerMap;
3527         StickyContainerMap stickyContainerMap;
3528         client->updateViewportConstrainedLayers(layerMap, stickyContainerMap);
3529     }
3530 }
3531
3532 void RenderLayerCompositor::registerAllScrollingLayers()
3533 {
3534     ChromeClient* client = this->chromeClient();
3535     if (!client)
3536         return;
3537
3538     for (auto it = m_scrollingLayers.begin(), end = m_scrollingLayers.end(); it != end; ++it)
3539         updateScrollingLayerWithClient(**it, client);
3540 }
3541
3542 void RenderLayerCompositor::unregisterAllScrollingLayers()
3543 {
3544     ChromeClient* client = this->chromeClient();
3545     if (!client)
3546         return;
3547
3548     for (auto it = m_scrollingLayers.begin(), end = m_scrollingLayers.end(); it != end; ++it) {
3549         RenderLayer& layer = **it;
3550         RenderLayerBacking* backing = layer.backing();
3551         ASSERT(backing);
3552         client->removeScrollingLayer(layer.renderer().element(), backing->scrollingLayer()->platformLayer(), backing->scrollingContentsLayer()->platformLayer());
3553     }
3554 }
3555
3556 // Called when the size of the contentsLayer changes, and when the contentsLayer is replaced by another layer.
3557 void RenderLayerCompositor::scrollingLayerAddedOrUpdated(RenderLayer* layer)
3558 {
3559     ASSERT(!m_renderView.document().inPageCache());
3560     m_scrollingLayers.add(layer);
3561 }
3562
3563 void RenderLayerCompositor::scrollingLayerRemoved(RenderLayer* layer, PlatformLayer* scrollingLayer, PlatformLayer* contentsLayer)
3564 {
3565     m_scrollingLayersNeedingUpdate.remove(layer);
3566     m_scrollingLayers.remove(layer);
3567
3568     if (m_renderView.document().inPageCache())
3569         return;
3570
3571     if (ChromeClient* client = this->chromeClient())
3572         client->removeScrollingLayer(layer->renderer().element(), scrollingLayer, contentsLayer);
3573 }
3574 #endif
3575
3576 void RenderLayerCompositor::windowScreenDidChange(PlatformDisplayID displayID)
3577 {
3578     if (m_layerUpdater)
3579         m_layerUpdater->screenDidChange(displayID);
3580 }
3581
3582 ScrollingCoordinator* RenderLayerCompositor::scrollingCoordinator() const
3583 {
3584     if (Page* page = this->page())
3585         return page->scrollingCoordinator();
3586
3587     return 0;
3588 }
3589
3590 GraphicsLayerFactory* RenderLayerCompositor::graphicsLayerFactory() const
3591 {
3592     if (Page* page = this->page())
3593         return page->chrome().client().graphicsLayerFactory();
3594
3595     return 0;
3596 }
3597
3598 Page* RenderLayerCompositor::page() const
3599 {
3600     return m_renderView.frameView().frame().page();
3601 }
3602
3603 void RenderLayerCompositor::setLayerFlushThrottlingEnabled(bool enabled)
3604 {
3605     m_layerFlushThrottlingEnabled = enabled;
3606     if (m_layerFlushThrottlingEnabled)
3607         return;
3608     m_layerFlushTimer.stop();
3609     if (!m_hasPendingLayerFlush)
3610         return;
3611     scheduleLayerFlushNow();
3612 }
3613
3614 void RenderLayerCompositor::disableLayerFlushThrottlingTemporarilyForInteraction()
3615 {
3616     if (m_layerFlushThrottlingTemporarilyDisabledForInteraction)
3617         return;
3618     m_layerFlushThrottlingTemporarilyDisabledForInteraction = true;
3619 }
3620
3621 bool RenderLayerCompositor::isThrottlingLayerFlushes() const
3622 {
3623     if (!m_layerFlushThrottlingEnabled)
3624         return false;
3625     if (!m_layerFlushTimer.isActive())
3626         return false;
3627     if (m_layerFlushThrottlingTemporarilyDisabledForInteraction)
3628         return false;
3629     return true;
3630 }
3631
3632 void RenderLayerCompositor::startLayerFlushTimerIfNeeded()
3633 {
3634     m_layerFlushThrottlingTemporarilyDisabledForInteraction = false;
3635     m_layerFlushTimer.stop();
3636     if (!m_layerFlushThrottlingEnabled)
3637         return;
3638     m_layerFlushTimer.startOneShot(throttledLayerFlushDelay);
3639 }
3640
3641 #if PLATFORM(IOS)
3642 void RenderLayerCompositor::startInitialLayerFlushTimerIfNeeded()
3643 {
3644     if (!m_layerFlushThrottlingEnabled)
3645         return;
3646     if (m_layerFlushTimer.isActive())
3647         return;
3648     m_layerFlushTimer.startOneShot(throttledLayerFlushInitialDelay);
3649 }
3650 #endif
3651
3652 void RenderLayerCompositor::layerFlushTimerFired(Timer<RenderLayerCompositor>&)
3653 {
3654     if (!m_hasPendingLayerFlush)
3655         return;
3656     scheduleLayerFlushNow();
3657 }
3658
3659 void RenderLayerCompositor::paintRelatedMilestonesTimerFired(Timer<RenderLayerCompositor>&)
3660 {
3661     Frame& frame = m_renderView.frameView().frame();
3662     Page* page = frame.page();
3663     if (!page)
3664         return;
3665
3666     // If the layer tree is frozen, we'll paint when it's unfrozen and schedule the timer again.
3667     if (page->chrome().client().layerTreeStateIsFrozen())
3668         return;
3669
3670     m_renderView.frameView().firePaintRelatedMilestones();
3671 }
3672
3673 } // namespace WebCore
3674
3675 #endif // USE(ACCELERATED_COMPOSITING)