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