Some fixed position elements disappear in WK2 on iOS
[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     // position:fixed elements that create their own stacking context (e.g. have an explicit z-index,
2499     // opacity, transform) can get their own composited layer. A stacking context is required otherwise
2500     // z-index and clipping will be broken.
2501     if (!renderer.isPositioned())
2502         return false;
2503     
2504     EPosition position = renderer.style().position();
2505     bool isFixed = renderer.isOutOfFlowPositioned() && position == FixedPosition;
2506     if (isFixed && !layer.isStackingContainer())
2507         return false;
2508     
2509     bool isSticky = renderer.isInFlowPositioned() && position == StickyPosition;
2510     if (!isFixed && !isSticky)
2511         return false;
2512
2513     // FIXME: acceleratedCompositingForFixedPositionEnabled should probably be renamed acceleratedCompositingForViewportConstrainedPositionEnabled().
2514     const Settings& settings = m_renderView.frameView().frame().settings();
2515     if (!settings.acceleratedCompositingForFixedPositionEnabled())
2516         return false;
2517
2518     if (isSticky)
2519         return hasCoordinatedScrolling() && isViewportConstrainedFixedOrStickyLayer(layer);
2520
2521     auto container = renderer.container();
2522     // If the renderer is not hooked up yet then we have to wait until it is.
2523     if (!container) {
2524         m_reevaluateCompositingAfterLayout = true;
2525         return false;
2526     }
2527
2528     // Don't promote fixed position elements that are descendants of a non-view container, e.g. transformed elements.
2529     // They will stay fixed wrt the container rather than the enclosing frame.
2530     if (container != &m_renderView && !renderer.fixedPositionedWithNamedFlowContainingBlock()) {
2531         if (viewportConstrainedNotCompositedReason)
2532             *viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForNonViewContainer;
2533         return false;
2534     }
2535     
2536     // Subsequent tests depend on layout. If we can't tell now, just keep things the way they are until layout is done.
2537     if (!m_inPostLayoutUpdate) {
2538         m_reevaluateCompositingAfterLayout = true;
2539         return layer.isComposited();
2540     }
2541
2542     bool paintsContent = layer.isVisuallyNonEmpty() || layer.hasVisibleDescendant();
2543     if (!paintsContent) {
2544         if (viewportConstrainedNotCompositedReason)
2545             *viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForNoVisibleContent;
2546         return false;
2547     }
2548
2549     // Fixed position elements that are invisible in the current view don't get their own layer.
2550     LayoutRect viewBounds = m_renderView.frameView().viewportConstrainedExtentRect();
2551     LayoutRect layerBounds = layer.calculateLayerBounds(&layer, 0, RenderLayer::UseLocalClipRectIfPossible | RenderLayer::IncludeLayerFilterOutsets | RenderLayer::UseFragmentBoxes
2552         | RenderLayer::ExcludeHiddenDescendants | RenderLayer::DontConstrainForMask | RenderLayer::IncludeCompositedDescendants);
2553     // Map to m_renderView to ignore page scale.
2554     FloatRect absoluteBounds = layer.renderer().localToContainerQuad(FloatRect(layerBounds), &m_renderView).boundingBox();
2555     if (!viewBounds.intersects(enclosingIntRect(absoluteBounds))) {
2556         if (viewportConstrainedNotCompositedReason)
2557             *viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForBoundsOutOfView;
2558         return false;
2559     }
2560     
2561     return true;
2562 }
2563
2564 bool RenderLayerCompositor::requiresCompositingForOverflowScrolling(const RenderLayer& layer) const
2565 {
2566     return layer.needsCompositedScrolling();
2567 }
2568
2569 bool RenderLayerCompositor::isRunningAcceleratedTransformAnimation(RenderLayerModelObject& renderer) const
2570 {
2571     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
2572         return false;
2573
2574     return renderer.animation().isRunningAnimationOnRenderer(&renderer, CSSPropertyWebkitTransform);
2575 }
2576
2577 // If an element has negative z-index children, those children render in front of the 
2578 // layer background, so we need an extra 'contents' layer for the foreground of the layer
2579 // object.
2580 bool RenderLayerCompositor::needsContentsCompositingLayer(const RenderLayer& layer) const
2581 {
2582     return layer.hasNegativeZOrderList();
2583 }
2584
2585 bool RenderLayerCompositor::requiresScrollLayer(RootLayerAttachment attachment) const
2586 {
2587     // This applies when the application UI handles scrolling, in which case RenderLayerCompositor doesn't need to manage it.
2588     if (m_renderView.frameView().delegatesScrolling())
2589         return false;
2590
2591     // We need to handle our own scrolling if we're:
2592     return !m_renderView.frameView().platformWidget() // viewless (i.e. non-Mac, or Mac in WebKit2)
2593         || attachment == RootLayerAttachedViaEnclosingFrame; // a composited frame on Mac
2594 }
2595
2596 static void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
2597 {
2598     if (!scrollbar)
2599         return;
2600
2601     context.save();
2602     const IntRect& scrollbarRect = scrollbar->frameRect();
2603     context.translate(-scrollbarRect.x(), -scrollbarRect.y());
2604     IntRect transformedClip = clip;
2605     transformedClip.moveBy(scrollbarRect.location());
2606     scrollbar->paint(&context, transformedClip);
2607     context.restore();
2608 }
2609
2610 void RenderLayerCompositor::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, GraphicsLayerPaintingPhase, const IntRect& clip)
2611 {
2612     if (graphicsLayer == layerForHorizontalScrollbar())
2613         paintScrollbar(m_renderView.frameView().horizontalScrollbar(), context, clip);
2614     else if (graphicsLayer == layerForVerticalScrollbar())
2615         paintScrollbar(m_renderView.frameView().verticalScrollbar(), context, clip);
2616     else if (graphicsLayer == layerForScrollCorner()) {
2617         const IntRect& scrollCorner = m_renderView.frameView().scrollCornerRect();
2618         context.save();
2619         context.translate(-scrollCorner.x(), -scrollCorner.y());
2620         IntRect transformedClip = clip;
2621         transformedClip.moveBy(scrollCorner.location());
2622         m_renderView.frameView().paintScrollCorner(&context, transformedClip);
2623         context.restore();
2624     }
2625 }
2626
2627 bool RenderLayerCompositor::supportsFixedRootBackgroundCompositing() const
2628 {
2629     RenderLayerBacking* renderViewBacking = m_renderView.layer()->backing();
2630     return renderViewBacking && renderViewBacking->usingTiledBacking();
2631 }
2632
2633 bool RenderLayerCompositor::needsFixedRootBackgroundLayer(const RenderLayer& layer) const
2634 {
2635     if (&layer != m_renderView.layer())
2636         return false;
2637
2638     return supportsFixedRootBackgroundCompositing() && m_renderView.rootBackgroundIsEntirelyFixed();
2639 }
2640
2641 GraphicsLayer* RenderLayerCompositor::fixedRootBackgroundLayer() const
2642 {
2643     // Get the fixed root background from the RenderView layer's backing.
2644     RenderLayer* viewLayer = m_renderView.layer();
2645     if (!viewLayer)
2646         return nullptr;
2647
2648     if (viewLayer->isComposited() && viewLayer->backing()->backgroundLayerPaintsFixedRootBackground())
2649         return viewLayer->backing()->backgroundLayer();
2650
2651     return nullptr;
2652 }
2653
2654 static void resetTrackedRepaintRectsRecursive(GraphicsLayer& graphicsLayer)
2655 {
2656     graphicsLayer.resetTrackedRepaints();
2657
2658     for (size_t i = 0, size = graphicsLayer.children().size(); i < size; ++i)
2659         resetTrackedRepaintRectsRecursive(*graphicsLayer.children()[i]);
2660
2661     if (GraphicsLayer* replicaLayer = graphicsLayer.replicaLayer())
2662         resetTrackedRepaintRectsRecursive(*replicaLayer);
2663
2664     if (GraphicsLayer* maskLayer = graphicsLayer.maskLayer())
2665         resetTrackedRepaintRectsRecursive(*maskLayer);
2666 }
2667
2668 void RenderLayerCompositor::resetTrackedRepaintRects()
2669 {
2670     if (GraphicsLayer* rootLayer = rootGraphicsLayer())
2671         resetTrackedRepaintRectsRecursive(*rootLayer);
2672 }
2673
2674 void RenderLayerCompositor::setTracksRepaints(bool tracksRepaints)
2675 {
2676     m_isTrackingRepaints = tracksRepaints;
2677 }
2678
2679 bool RenderLayerCompositor::isTrackingRepaints() const
2680 {
2681     return m_isTrackingRepaints;
2682 }
2683
2684 float RenderLayerCompositor::deviceScaleFactor() const
2685 {
2686     Page* page = this->page();
2687     return page ? page->deviceScaleFactor() : 1;
2688 }
2689
2690 float RenderLayerCompositor::pageScaleFactor() const
2691 {
2692     Page* page = this->page();
2693     return page ? page->pageScaleFactor() : 1;
2694 }
2695
2696 float RenderLayerCompositor::contentsScaleMultiplierForNewTiles(const GraphicsLayer*) const
2697 {
2698 #if PLATFORM(IOS)
2699     TileCache* tileCache = nullptr;
2700     if (Page* page = this->page()) {
2701         if (FrameView* frameView = page->mainFrame().view())
2702             tileCache = frameView->tileCache();
2703     }
2704
2705     if (!tileCache)
2706         return 1;
2707
2708     return tileCache->tilingMode() == TileCache::Zooming ? 0.125 : 1;
2709 #else
2710     return 1;
2711 #endif
2712 }
2713
2714 void RenderLayerCompositor::didCommitChangesForLayer(const GraphicsLayer*) const
2715 {
2716     // Nothing to do here yet.
2717 }
2718
2719 bool RenderLayerCompositor::keepLayersPixelAligned() const
2720 {
2721     // When scaling, attempt to align compositing layers to pixel boundaries.
2722     return true;
2723 }
2724
2725 bool RenderLayerCompositor::mainFrameBackingIsTiled() const
2726 {
2727     RenderLayer* layer = m_renderView.layer();
2728     if (!layer)
2729         return false;
2730
2731     RenderLayerBacking* backing = layer->backing();
2732     if (!backing)
2733         return false;
2734
2735     return backing->usingTiledBacking();
2736 }
2737
2738 bool RenderLayerCompositor::mainFrameBackingIsTiledWithMargin() const
2739 {
2740     RenderLayer* layer = m_renderView.layer();
2741     if (!layer)
2742         return false;
2743
2744     RenderLayerBacking* backing = layer->backing();
2745     if (!backing)
2746         return false;
2747
2748     return backing->tiledBackingHasMargin();
2749 }
2750
2751 bool RenderLayerCompositor::shouldCompositeOverflowControls() const
2752 {
2753     FrameView& frameView = m_renderView.frameView();
2754
2755     if (frameView.platformWidget())
2756         return false;
2757
2758     if (frameView.delegatesScrolling())
2759         return false;
2760
2761     if (mainFrameBackingIsTiled())
2762         return true;
2763
2764     if (!frameView.hasOverlayScrollbars())
2765         return false;
2766
2767     return true;
2768 }
2769
2770 bool RenderLayerCompositor::requiresHorizontalScrollbarLayer() const
2771 {
2772     return shouldCompositeOverflowControls() && m_renderView.frameView().horizontalScrollbar();
2773 }
2774
2775 bool RenderLayerCompositor::requiresVerticalScrollbarLayer() const
2776 {
2777     return shouldCompositeOverflowControls() && m_renderView.frameView().verticalScrollbar();
2778 }
2779
2780 bool RenderLayerCompositor::requiresScrollCornerLayer() const
2781 {
2782     return shouldCompositeOverflowControls() && m_renderView.frameView().isScrollCornerVisible();
2783 }
2784
2785 #if ENABLE(RUBBER_BANDING)
2786 bool RenderLayerCompositor::requiresOverhangAreasLayer() const
2787 {
2788     // We don't want a layer if this is a subframe.
2789     if (m_renderView.document().ownerElement())
2790         return false;
2791
2792     // We do want a layer if we're using tiled drawing and can scroll.
2793     if (mainFrameBackingIsTiled() && m_renderView.frameView().hasOpaqueBackground() && !m_renderView.frameView().prohibitsScrolling())
2794         return true;
2795
2796     return false;
2797 }
2798
2799 bool RenderLayerCompositor::requiresContentShadowLayer() const
2800 {
2801     // We don't want a layer if this is a subframe.
2802     if (m_renderView.document().ownerElement())
2803         return false;
2804
2805 #if PLATFORM(MAC)
2806     if (viewHasTransparentBackground())
2807         return false;
2808
2809     // On Mac, we want a content shadow layer if we're using tiled drawing and can scroll.
2810     if (mainFrameBackingIsTiled() && !m_renderView.frameView().prohibitsScrolling())
2811         return true;
2812 #endif
2813
2814     return false;
2815 }
2816
2817 GraphicsLayer* RenderLayerCompositor::updateLayerForTopOverhangArea(bool wantsLayer)
2818 {
2819     if (m_renderView.document().ownerElement())
2820         return 0;
2821
2822     if (!wantsLayer) {
2823         if (m_layerForTopOverhangArea) {
2824             m_layerForTopOverhangArea->removeFromParent();
2825             m_layerForTopOverhangArea = nullptr;
2826         }
2827         return 0;
2828     }
2829
2830     if (!m_layerForTopOverhangArea) {
2831         m_layerForTopOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), this);
2832 #ifndef NDEBUG
2833         m_layerForTopOverhangArea->setName("top overhang area");
2834 #endif
2835         m_scrollLayer->addChildBelow(m_layerForTopOverhangArea.get(), m_rootContentLayer.get());
2836     }
2837
2838     return m_layerForTopOverhangArea.get();
2839 }
2840
2841 GraphicsLayer* RenderLayerCompositor::updateLayerForBottomOverhangArea(bool wantsLayer)
2842 {
2843     if (m_renderView.document().ownerElement())
2844         return 0;
2845
2846     if (!wantsLayer) {
2847         if (m_layerForBottomOverhangArea) {
2848             m_layerForBottomOverhangArea->removeFromParent();
2849             m_layerForBottomOverhangArea = nullptr;
2850         }
2851         return 0;
2852     }
2853
2854     if (!m_layerForBottomOverhangArea) {
2855         m_layerForBottomOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), this);
2856 #ifndef NDEBUG
2857         m_layerForBottomOverhangArea->setName("bottom overhang area");
2858 #endif
2859         m_scrollLayer->addChildBelow(m_layerForBottomOverhangArea.get(), m_rootContentLayer.get());
2860     }
2861
2862     m_layerForBottomOverhangArea->setPosition(FloatPoint(0, m_rootContentLayer->size().height() + m_renderView.frameView().headerHeight() + m_renderView.frameView().footerHeight()));
2863     return m_layerForBottomOverhangArea.get();
2864 }
2865
2866 GraphicsLayer* RenderLayerCompositor::updateLayerForHeader(bool wantsLayer)
2867 {
2868     if (m_renderView.document().ownerElement())
2869         return 0;
2870
2871     if (!wantsLayer) {
2872         if (m_layerForHeader) {
2873             m_layerForHeader->removeFromParent();
2874             m_layerForHeader = nullptr;
2875
2876             // The ScrollingTree knows about the header layer, and the position of the root layer is affected
2877             // by the header layer, so if we remove the header, we need to tell the scrolling tree.
2878             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2879                 scrollingCoordinator->frameViewRootLayerDidChange(&m_renderView.frameView());
2880         }
2881         return 0;
2882     }
2883
2884     if (!m_layerForHeader) {
2885         m_layerForHeader = GraphicsLayer::create(graphicsLayerFactory(), this);
2886 #ifndef NDEBUG
2887         m_layerForHeader->setName("header");
2888 #endif
2889         m_scrollLayer->addChildBelow(m_layerForHeader.get(), m_rootContentLayer.get());
2890         m_renderView.frameView().addPaintPendingMilestones(DidFirstFlushForHeaderLayer);
2891     }
2892
2893     m_layerForHeader->setPosition(FloatPoint());
2894     m_layerForHeader->setAnchorPoint(FloatPoint3D());
2895     m_layerForHeader->setSize(FloatSize(m_renderView.frameView().visibleWidth(), m_renderView.frameView().headerHeight()));
2896
2897     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2898         scrollingCoordinator->frameViewRootLayerDidChange(&m_renderView.frameView());
2899
2900     if (Page* page = this->page())
2901         page->chrome().client().didAddHeaderLayer(m_layerForHeader.get());
2902
2903     return m_layerForHeader.get();
2904 }
2905
2906 GraphicsLayer* RenderLayerCompositor::updateLayerForFooter(bool wantsLayer)
2907 {
2908     if (m_renderView.document().ownerElement())
2909         return 0;
2910
2911     if (!wantsLayer) {
2912         if (m_layerForFooter) {
2913             m_layerForFooter->removeFromParent();
2914             m_layerForFooter = nullptr;
2915
2916             // The ScrollingTree knows about the footer layer, and the total scrollable size is affected
2917             // by the footer layer, so if we remove the footer, we need to tell the scrolling tree.
2918             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2919                 scrollingCoordinator->frameViewRootLayerDidChange(&m_renderView.frameView());
2920         }
2921         return 0;
2922     }
2923
2924     if (!m_layerForFooter) {
2925         m_layerForFooter = GraphicsLayer::create(graphicsLayerFactory(), this);
2926 #ifndef NDEBUG
2927         m_layerForFooter->setName("footer");
2928 #endif
2929         m_scrollLayer->addChildBelow(m_layerForFooter.get(), m_rootContentLayer.get());
2930     }
2931
2932     m_layerForFooter->setPosition(FloatPoint(0, m_rootContentLayer->size().height() + m_renderView.frameView().headerHeight()));
2933     m_layerForFooter->setAnchorPoint(FloatPoint3D());
2934     m_layerForFooter->setSize(FloatSize(m_renderView.frameView().visibleWidth(), m_renderView.frameView().footerHeight()));
2935
2936     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
2937         scrollingCoordinator->frameViewRootLayerDidChange(&m_renderView.frameView());
2938
2939     if (Page* page = this->page())
2940         page->chrome().client().didAddFooterLayer(m_layerForFooter.get());
2941
2942     return m_layerForFooter.get();
2943 }
2944
2945 #endif
2946
2947 bool RenderLayerCompositor::viewHasTransparentBackground(Color* backgroundColor) const
2948 {
2949     if (m_renderView.frameView().isTransparent()) {
2950         if (backgroundColor)
2951             *backgroundColor = Color(); // Return an invalid color.
2952         return true;
2953     }
2954
2955     Color documentBackgroundColor = m_renderView.frameView().documentBackgroundColor();
2956     if (!documentBackgroundColor.isValid())
2957         documentBackgroundColor = Color::white;
2958
2959     if (backgroundColor)
2960         *backgroundColor = documentBackgroundColor;
2961         
2962     return documentBackgroundColor.hasAlpha();
2963 }
2964
2965 void RenderLayerCompositor::updateOverflowControlsLayers()
2966 {
2967 #if ENABLE(RUBBER_BANDING)
2968     if (requiresOverhangAreasLayer()) {
2969         if (!m_layerForOverhangAreas) {
2970             m_layerForOverhangAreas = GraphicsLayer::create(graphicsLayerFactory(), this);
2971 #ifndef NDEBUG
2972             m_layerForOverhangAreas->setName("overhang areas");
2973 #endif
2974             m_layerForOverhangAreas->setDrawsContent(false);
2975             m_layerForOverhangAreas->setSize(m_renderView.frameView().frameRect().size());
2976             m_layerForOverhangAreas->setCustomAppearance(GraphicsLayer::ScrollingOverhang);
2977
2978             // We want the overhang areas layer to be positioned below the frame contents,
2979             // so insert it below the clip layer.
2980             m_overflowControlsHostLayer->addChildBelow(m_layerForOverhangAreas.get(), m_clipLayer.get());
2981         }
2982     } else if (m_layerForOverhangAreas) {
2983         m_layerForOverhangAreas->removeFromParent();
2984         m_layerForOverhangAreas = nullptr;
2985     }
2986
2987     if (requiresContentShadowLayer()) {
2988         if (!m_contentShadowLayer) {
2989             m_contentShadowLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
2990 #ifndef NDEBUG
2991             m_contentShadowLayer->setName("content shadow");
2992 #endif
2993             m_contentShadowLayer->setSize(m_rootContentLayer->size());
2994             m_contentShadowLayer->setPosition(m_rootContentLayer->position());
2995             m_contentShadowLayer->setCustomAppearance(GraphicsLayer::ScrollingShadow);
2996
2997             m_scrollLayer->addChildBelow(m_contentShadowLayer.get(), m_rootContentLayer.get());
2998         }
2999     } else if (m_contentShadowLayer) {
3000         m_contentShadowLayer->removeFromParent();
3001         m_contentShadowLayer = nullptr;
3002     }
3003 #endif
3004
3005     if (requiresHorizontalScrollbarLayer()) {
3006         if (!m_layerForHorizontalScrollbar) {
3007             m_layerForHorizontalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), this);
3008             m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
3009 #ifndef NDEBUG
3010             m_layerForHorizontalScrollbar->setName("horizontal scrollbar container");
3011
3012 #endif
3013 #if PLATFORM(MAC) && USE(CA)
3014             m_layerForHorizontalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
3015 #endif
3016             m_overflowControlsHostLayer->addChild(m_layerForHorizontalScrollbar.get());
3017
3018             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3019                 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_renderView.frameView(), HorizontalScrollbar);
3020         }
3021     } else if (m_layerForHorizontalScrollbar) {
3022         m_layerForHorizontalScrollbar->removeFromParent();
3023         m_layerForHorizontalScrollbar = nullptr;
3024
3025         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3026             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_renderView.frameView(), HorizontalScrollbar);
3027     }
3028
3029     if (requiresVerticalScrollbarLayer()) {
3030         if (!m_layerForVerticalScrollbar) {
3031             m_layerForVerticalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), this);
3032             m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
3033 #ifndef NDEBUG
3034             m_layerForVerticalScrollbar->setName("vertical scrollbar container");
3035 #endif
3036 #if PLATFORM(MAC) && USE(CA)
3037             m_layerForVerticalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
3038 #endif
3039             m_overflowControlsHostLayer->addChild(m_layerForVerticalScrollbar.get());
3040
3041             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3042                 scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_renderView.frameView(), VerticalScrollbar);
3043         }
3044     } else if (m_layerForVerticalScrollbar) {
3045         m_layerForVerticalScrollbar->removeFromParent();
3046         m_layerForVerticalScrollbar = nullptr;
3047
3048         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3049             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_renderView.frameView(), VerticalScrollbar);
3050     }
3051
3052     if (requiresScrollCornerLayer()) {
3053         if (!m_layerForScrollCorner) {
3054             m_layerForScrollCorner = GraphicsLayer::create(graphicsLayerFactory(), this);
3055             m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
3056 #ifndef NDEBUG
3057             m_layerForScrollCorner->setName("scroll corner");
3058 #endif
3059 #if PLATFORM(MAC) && USE(CA)
3060             m_layerForScrollCorner->setAcceleratesDrawing(acceleratedDrawingEnabled());
3061 #endif
3062             m_overflowControlsHostLayer->addChild(m_layerForScrollCorner.get());
3063         }
3064     } else if (m_layerForScrollCorner) {
3065         m_layerForScrollCorner->removeFromParent();
3066         m_layerForScrollCorner = nullptr;
3067     }
3068
3069     m_renderView.frameView().positionScrollbarLayers();
3070 }
3071
3072 void RenderLayerCompositor::ensureRootLayer()
3073 {
3074     RootLayerAttachment expectedAttachment = shouldPropagateCompositingToEnclosingFrame() ? RootLayerAttachedViaEnclosingFrame : RootLayerAttachedViaChromeClient;
3075     if (expectedAttachment == m_rootLayerAttachment)
3076          return;
3077
3078     if (!m_rootContentLayer) {
3079         m_rootContentLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
3080 #ifndef NDEBUG
3081         m_rootContentLayer->setName("content root");
3082 #endif
3083         IntRect overflowRect = m_renderView.pixelSnappedLayoutOverflowRect();
3084         m_rootContentLayer->setSize(FloatSize(overflowRect.maxX(), overflowRect.maxY()));
3085         m_rootContentLayer->setPosition(FloatPoint());
3086
3087 #if PLATFORM(IOS)
3088         // Page scale is applied above this on iOS, so we'll just say that our root layer applies it.
3089         Frame& frame = m_renderView.frameView().frame();
3090         if (frame.isMainFrame())
3091             m_rootContentLayer->setAppliesPageScale();
3092 #endif
3093
3094         // Need to clip to prevent transformed content showing outside this frame
3095         m_rootContentLayer->setMasksToBounds(true);
3096     }
3097
3098     if (requiresScrollLayer(expectedAttachment)) {
3099         if (!m_overflowControlsHostLayer) {
3100             ASSERT(!m_scrollLayer);
3101             ASSERT(!m_clipLayer);
3102
3103             // Create a layer to host the clipping layer and the overflow controls layers.
3104             m_overflowControlsHostLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
3105 #ifndef NDEBUG
3106             m_overflowControlsHostLayer->setName("overflow controls host");
3107 #endif
3108
3109             // Create a clipping layer if this is an iframe
3110             m_clipLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
3111 #ifndef NDEBUG
3112             m_clipLayer->setName("frame clipping");
3113 #endif
3114             m_clipLayer->setMasksToBounds(true);
3115             
3116             m_scrollLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
3117 #ifndef NDEBUG
3118             m_scrollLayer->setName("frame scrolling");
3119 #endif
3120             if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3121                 scrollingCoordinator->setLayerIsContainerForFixedPositionLayers(m_scrollLayer.get(), true);
3122
3123             // Hook them up
3124             m_overflowControlsHostLayer->addChild(m_clipLayer.get());
3125             m_clipLayer->addChild(m_scrollLayer.get());
3126             m_scrollLayer->addChild(m_rootContentLayer.get());
3127
3128             m_clipLayer->setSize(m_renderView.frameView().unscaledVisibleContentSize());
3129
3130             updateOverflowControlsLayers();
3131
3132             if (hasCoordinatedScrolling())
3133                 scheduleLayerFlush(true);
3134             else
3135                 updateScrollLayerPosition();
3136         }
3137     } else {
3138         if (m_overflowControlsHostLayer) {
3139             m_overflowControlsHostLayer = nullptr;
3140             m_clipLayer = nullptr;
3141             m_scrollLayer = nullptr;
3142         }
3143     }
3144
3145     // Check to see if we have to change the attachment
3146     if (m_rootLayerAttachment != RootLayerUnattached)
3147         detachRootLayer();
3148
3149     attachRootLayer(expectedAttachment);
3150 }
3151
3152 void RenderLayerCompositor::destroyRootLayer()
3153 {
3154     if (!m_rootContentLayer)
3155         return;
3156
3157     detachRootLayer();
3158
3159 #if ENABLE(RUBBER_BANDING)
3160     if (m_layerForOverhangAreas) {
3161         m_layerForOverhangAreas->removeFromParent();
3162         m_layerForOverhangAreas = nullptr;
3163     }
3164 #endif
3165
3166     if (m_layerForHorizontalScrollbar) {
3167         m_layerForHorizontalScrollbar->removeFromParent();
3168         m_layerForHorizontalScrollbar = nullptr;
3169         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3170             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_renderView.frameView(), HorizontalScrollbar);
3171         if (Scrollbar* horizontalScrollbar = m_renderView.frameView().verticalScrollbar())
3172             m_renderView.frameView().invalidateScrollbar(horizontalScrollbar, IntRect(IntPoint(0, 0), horizontalScrollbar->frameRect().size()));
3173     }
3174
3175     if (m_layerForVerticalScrollbar) {
3176         m_layerForVerticalScrollbar->removeFromParent();
3177         m_layerForVerticalScrollbar = nullptr;
3178         if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
3179             scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(&m_renderView.frameView(), VerticalScrollbar);
3180         if (Scrollbar* verticalScrollbar = m_renderView.frameView().verticalScrollbar())
3181             m_renderView.frameView().invalidateScrollbar(verticalScrollbar, IntRect(IntPoint(0, 0), verticalScrollbar->frameRect().size()));
3182     }
3183
3184     if (m_layerForScrollCorner) {
3185         m_layerForScrollCorner = nullptr;
3186         m_renderView.frameView().invalidateScrollCorner(m_renderView.frameView().scrollCornerRect());
3187     }
3188
3189     if (m_overflowControlsHostLayer) {
3190         m_overflowControlsHostLayer = nullptr;
3191         m_clipLayer = nullptr;
3192         m_scrollLayer = nullptr;
3193     }
3194     ASSERT(!m_scrollLayer);
3195     m_rootContentLayer = nullptr;
3196
3197     m_layerUpdater = nullptr;
3198 }
3199
3200 void RenderLayerCompositor::attachRootLayer(RootLayerAttachment attachment)
3201 {
3202     if (!m_rootContentLayer)
3203         return;
3204
3205     switch (attachment) {
3206         case RootLayerUnattached:
3207             ASSERT_NOT_REACHED();
3208             break;
3209         case RootLayerAttachedViaChromeClient: {
3210             Frame& frame = m_renderView.frameView().frame();
3211             Page* page = frame.page();
3212             if (!page)
3213                 return;
3214
3215             page->chrome().client().attachRootGraphicsLayer(&frame, rootGraphicsLayer());
3216             break;
3217         }
3218         case RootLayerAttachedViaEnclosingFrame: {
3219             // The layer will get hooked up via RenderLayerBacking::updateGraphicsLayerConfiguration()
3220             // for the frame's renderer in the parent document.
3221             m_renderView.document().ownerElement()->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
3222             break;
3223         }
3224     }
3225
3226     m_rootLayerAttachment = attachment;
3227     rootLayerAttachmentChanged();
3228     
3229     if (m_shouldFlushOnReattach) {
3230         scheduleLayerFlushNow();
3231         m_shouldFlushOnReattach = false;
3232     }
3233 }
3234
3235 void RenderLayerCompositor::detachRootLayer()
3236 {
3237     if (!m_rootContentLayer || m_rootLayerAttachment == RootLayerUnattached)
3238         return;
3239
3240     switch (m_rootLayerAttachment) {
3241     case RootLayerAttachedViaEnclosingFrame: {
3242         // The layer will get unhooked up via RenderLayerBacking::updateGraphicsLayerConfiguration()
3243         // for the frame's renderer in the parent document.
3244         if (m_overflowControlsHostLayer)
3245             m_overflowControlsHostLayer->removeFromParent();
3246         else
3247             m_rootContentLayer->removeFromParent();
3248
3249         if (HTMLFrameOwnerElement* ownerElement = m_renderView.document().ownerElement())
3250             ownerElement->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
3251         break;
3252     }
3253     case RootLayerAttachedViaChromeClient: {
3254         Frame& frame = m_renderView.frameView().frame();
3255         Page* page = frame.page();
3256         if (!page)
3257             return;
3258
3259         page->chrome().client().attachRootGraphicsLayer(&frame, 0);
3260     }
3261     break;
3262     case RootLayerUnattached:
3263         break;
3264     }
3265
3266     m_rootLayerAttachment = RootLayerUnattached;
3267     rootLayerAttachmentChanged();
3268 }
3269
3270 void RenderLayerCompositor::updateRootLayerAttachment()
3271 {
3272     ensureRootLayer();
3273 }
3274
3275 void RenderLayerCompositor::rootLayerAttachmentChanged()
3276 {
3277     // The attachment can affect whether the RenderView layer's paintsIntoWindow() behavior,
3278     // so call updateGraphicsLayerGeometry() to udpate that.
3279     RenderLayer* layer = m_renderView.layer();
3280     if (RenderLayerBacking* backing = layer ? layer->backing() : 0)
3281         backing->updateDrawsContent();
3282 }
3283
3284 // IFrames are special, because we hook compositing layers together across iframe boundaries
3285 // when both parent and iframe content are composited. So when this frame becomes composited, we have
3286 // to use a synthetic style change to get the iframes into RenderLayers in order to allow them to composite.
3287 void RenderLayerCompositor::notifyIFramesOfCompositingChange()
3288 {
3289     Frame& frame = m_renderView.frameView().frame();
3290
3291     for (Frame* child = frame.tree().firstChild(); child; child = child->tree().traverseNext(&frame)) {
3292         if (child->document() && child->document()->ownerElement())
3293             child->document()->ownerElement()->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
3294     }
3295     
3296     // Compositing also affects the answer to RenderIFrame::requiresAcceleratedCompositing(), so 
3297     // we need to schedule a style recalc in our parent document.
3298     if (HTMLFrameOwnerElement* ownerElement = m_renderView.document().ownerElement())
3299         ownerElement->scheduleSetNeedsStyleRecalc(SyntheticStyleChange);
3300 }
3301
3302 bool RenderLayerCompositor::layerHas3DContent(const RenderLayer& layer) const
3303 {
3304     const RenderStyle& style = layer.renderer().style();
3305
3306     if (style.transformStyle3D() == TransformStyle3DPreserve3D || style.hasPerspective() || style.transform().has3DOperation())
3307         return true;
3308
3309     const_cast<RenderLayer&>(layer).updateLayerListsIfNeeded();
3310
3311 #if !ASSERT_DISABLED
3312     LayerListMutationDetector mutationChecker(const_cast<RenderLayer*>(&layer));
3313 #endif
3314
3315     if (layer.isStackingContainer()) {
3316         if (Vector<RenderLayer*>* negZOrderList = layer.negZOrderList()) {
3317             for (size_t i = 0, size = negZOrderList->size(); i < size; ++i) {
3318                 if (layerHas3DContent(*negZOrderList->at(i)))
3319                     return true;
3320             }
3321         }
3322
3323         if (Vector<RenderLayer*>* posZOrderList = layer.posZOrderList()) {