2d72c437ebcef606a6a663a9ae75ebcb7ab20422
[WebKit-https.git] / Source / WebCore / rendering / RenderLayer.cpp
1 /*
2  * Copyright (C) 2006-2017 Apple Inc. All rights reserved.
3  * Copyright (C) 2019 Adobe. All rights reserved.
4  *
5  * Portions are Copyright (C) 1998 Netscape Communications Corporation.
6  *
7  * Other contributors:
8  *   Robert O'Callahan <roc+@cs.cmu.edu>
9  *   David Baron <dbaron@fas.harvard.edu>
10  *   Christian Biesinger <cbiesinger@web.de>
11  *   Randall Jesup <rjesup@wgate.com>
12  *   Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
13  *   Josh Soref <timeless@mac.com>
14  *   Boris Zbarsky <bzbarsky@mit.edu>
15  *
16  * This library is free software; you can redistribute it and/or
17  * modify it under the terms of the GNU Lesser General Public
18  * License as published by the Free Software Foundation; either
19  * version 2.1 of the License, or (at your option) any later version.
20  *
21  * This library is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
24  * Lesser General Public License for more details.
25  *
26  * You should have received a copy of the GNU Lesser General Public
27  * License along with this library; if not, write to the Free Software
28  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
29  *
30  * Alternatively, the contents of this file may be used under the terms
31  * of either the Mozilla Public License Version 1.1, found at
32  * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
33  * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
34  * (the "GPL"), in which case the provisions of the MPL or the GPL are
35  * applicable instead of those above.  If you wish to allow use of your
36  * version of this file only under the terms of one of those two
37  * licenses (the MPL or the GPL) and not to allow others to use your
38  * version of this file under the LGPL, indicate your decision by
39  * deletingthe provisions above and replace them with the notice and
40  * other provisions required by the MPL or the GPL, as the case may be.
41  * If you do not delete the provisions above, a recipient may use your
42  * version of this file under any of the LGPL, the MPL or the GPL.
43  */
44
45 #include "config.h"
46 #include "RenderLayer.h"
47
48 #include "BoxShape.h"
49 #include "CSSAnimationController.h"
50 #include "CSSFilter.h"
51 #include "CSSPropertyNames.h"
52 #include "Chrome.h"
53 #include "DebugPageOverlays.h"
54 #include "DeprecatedGlobalSettings.h"
55 #include "Document.h"
56 #include "DocumentMarkerController.h"
57 #include "DocumentTimeline.h"
58 #include "Editor.h"
59 #include "Element.h"
60 #include "EventHandler.h"
61 #include "FEColorMatrix.h"
62 #include "FEMerge.h"
63 #include "FloatConversion.h"
64 #include "FloatPoint3D.h"
65 #include "FloatRect.h"
66 #include "FloatRoundedRect.h"
67 #include "FocusController.h"
68 #include "Frame.h"
69 #include "FrameLoader.h"
70 #include "FrameLoaderClient.h"
71 #include "FrameSelection.h"
72 #include "FrameTree.h"
73 #include "FrameView.h"
74 #include "Gradient.h"
75 #include "GraphicsContext.h"
76 #include "HTMLFormControlElement.h"
77 #include "HTMLFrameElement.h"
78 #include "HTMLFrameOwnerElement.h"
79 #include "HTMLIFrameElement.h"
80 #include "HTMLNames.h"
81 #include "HTMLParserIdioms.h"
82 #include "HitTestRequest.h"
83 #include "HitTestResult.h"
84 #include "HitTestingTransformState.h"
85 #include "Logging.h"
86 #include "OverflowEvent.h"
87 #include "OverlapTestRequestClient.h"
88 #include "Page.h"
89 #include "PlatformMouseEvent.h"
90 #include "RenderFlexibleBox.h"
91 #include "RenderFragmentContainer.h"
92 #include "RenderFragmentedFlow.h"
93 #include "RenderGeometryMap.h"
94 #include "RenderImage.h"
95 #include "RenderInline.h"
96 #include "RenderIterator.h"
97 #include "RenderLayerBacking.h"
98 #include "RenderLayerCompositor.h"
99 #include "RenderLayerFilters.h"
100 #include "RenderMarquee.h"
101 #include "RenderMultiColumnFlow.h"
102 #include "RenderReplica.h"
103 #include "RenderSVGResourceClipper.h"
104 #include "RenderSVGRoot.h"
105 #include "RenderScrollbar.h"
106 #include "RenderScrollbarPart.h"
107 #include "RenderTableCell.h"
108 #include "RenderTableRow.h"
109 #include "RenderText.h"
110 #include "RenderTheme.h"
111 #include "RenderTreeAsText.h"
112 #include "RenderView.h"
113 #include "RuntimeEnabledFeatures.h"
114 #include "SVGNames.h"
115 #include "ScaleTransformOperation.h"
116 #include "ScriptDisallowedScope.h"
117 #include "ScrollAnimator.h"
118 #include "Scrollbar.h"
119 #include "ScrollbarTheme.h"
120 #include "ScrollingCoordinator.h"
121 #include "Settings.h"
122 #include "ShadowRoot.h"
123 #include "SourceGraphic.h"
124 #include "StyleProperties.h"
125 #include "StyleResolver.h"
126 #include "TransformationMatrix.h"
127 #include "TranslateTransformOperation.h"
128 #include "WheelEventTestMonitor.h"
129 #include <stdio.h>
130 #include <wtf/MonotonicTime.h>
131 #include <wtf/StdLibExtras.h>
132 #include <wtf/text/CString.h>
133 #include <wtf/text/TextStream.h>
134
135 #if ENABLE(CSS_SCROLL_SNAP)
136 #include "AxisScrollSnapOffsets.h"
137 #endif
138
139 #define MIN_INTERSECT_FOR_REVEAL 32
140
141 namespace WebCore {
142
143 using namespace HTMLNames;
144
145 class ClipRects : public RefCounted<ClipRects> {
146     WTF_MAKE_FAST_ALLOCATED;
147 public:
148     static Ref<ClipRects> create()
149     {
150         return adoptRef(*new ClipRects);
151     }
152
153     static Ref<ClipRects> create(const ClipRects& other)
154     {
155         return adoptRef(*new ClipRects(other));
156     }
157
158     void reset()
159     {
160         m_overflowClipRect.reset();
161         m_fixedClipRect.reset();
162         m_posClipRect.reset();
163         m_fixed = false;
164     }
165
166     const ClipRect& overflowClipRect() const { return m_overflowClipRect; }
167     void setOverflowClipRect(const ClipRect& clipRect) { m_overflowClipRect = clipRect; }
168
169     const ClipRect& fixedClipRect() const { return m_fixedClipRect; }
170     void setFixedClipRect(const ClipRect& clipRect) { m_fixedClipRect = clipRect; }
171
172     const ClipRect& posClipRect() const { return m_posClipRect; }
173     void setPosClipRect(const ClipRect& clipRect) { m_posClipRect = clipRect; }
174
175     bool fixed() const { return m_fixed; }
176     void setFixed(bool fixed) { m_fixed = fixed; }
177
178     bool operator==(const ClipRects& other) const
179     {
180         return m_overflowClipRect == other.overflowClipRect()
181             && m_fixedClipRect == other.fixedClipRect()
182             && m_posClipRect == other.posClipRect()
183             && m_fixed == other.fixed();
184     }
185
186     ClipRects& operator=(const ClipRects& other)
187     {
188         m_overflowClipRect = other.overflowClipRect();
189         m_fixedClipRect = other.fixedClipRect();
190         m_posClipRect = other.posClipRect();
191         m_fixed = other.fixed();
192         return *this;
193     }
194
195 private:
196     ClipRects() = default;
197
198     ClipRects(const LayoutRect& clipRect)
199         : m_overflowClipRect(clipRect)
200         , m_fixedClipRect(clipRect)
201         , m_posClipRect(clipRect)
202     {
203     }
204
205     ClipRects(const ClipRects& other)
206         : RefCounted()
207         , m_fixed(other.fixed())
208         , m_overflowClipRect(other.overflowClipRect())
209         , m_fixedClipRect(other.fixedClipRect())
210         , m_posClipRect(other.posClipRect())
211     {
212     }
213
214     bool m_fixed { false };
215     ClipRect m_overflowClipRect;
216     ClipRect m_fixedClipRect;
217     ClipRect m_posClipRect;
218 };
219
220 class ClipRectsCache {
221     WTF_MAKE_FAST_ALLOCATED;
222 public:
223     ClipRectsCache()
224     {
225 #if ASSERT_ENABLED
226         for (int i = 0; i < NumCachedClipRectsTypes; ++i) {
227             m_clipRectsRoot[i] = 0;
228             m_scrollbarRelevancy[i] = IgnoreOverlayScrollbarSize;
229         }
230 #endif
231     }
232
233     ClipRects* getClipRects(ClipRectsType clipRectsType, ShouldRespectOverflowClip respectOverflow) const
234     {
235         return m_clipRects[getIndex(clipRectsType, respectOverflow)].get();
236     }
237
238     void setClipRects(ClipRectsType clipRectsType, ShouldRespectOverflowClip respectOverflow, RefPtr<ClipRects>&& clipRects)
239     {
240         m_clipRects[getIndex(clipRectsType, respectOverflow)] = WTFMove(clipRects);
241     }
242
243 #if ASSERT_ENABLED
244     const RenderLayer* m_clipRectsRoot[NumCachedClipRectsTypes];
245     OverlayScrollbarSizeRelevancy m_scrollbarRelevancy[NumCachedClipRectsTypes];
246 #endif
247
248 private:
249     unsigned getIndex(ClipRectsType clipRectsType, ShouldRespectOverflowClip respectOverflow) const
250     {
251         unsigned index = static_cast<unsigned>(clipRectsType);
252         if (respectOverflow == RespectOverflowClip)
253             index += static_cast<unsigned>(NumCachedClipRectsTypes);
254         ASSERT_WITH_SECURITY_IMPLICATION(index < NumCachedClipRectsTypes * 2);
255         return index;
256     }
257
258     RefPtr<ClipRects> m_clipRects[NumCachedClipRectsTypes * 2];
259 };
260
261 void makeMatrixRenderable(TransformationMatrix& matrix, bool has3DRendering)
262 {
263 #if !ENABLE(3D_TRANSFORMS)
264     UNUSED_PARAM(has3DRendering);
265     matrix.makeAffine();
266 #else
267     if (!has3DRendering)
268         matrix.makeAffine();
269 #endif
270 }
271
272 #if !LOG_DISABLED
273 static TextStream& operator<<(TextStream& ts, const ClipRects& clipRects)
274 {
275     TextStream::GroupScope scope(ts);
276     ts << indent << "ClipRects\n";
277     ts << indent << "  overflow  : " << clipRects.overflowClipRect() << "\n";
278     ts << indent << "  fixed     : " << clipRects.fixedClipRect() << "\n";
279     ts << indent << "  positioned: " << clipRects.posClipRect() << "\n";
280
281     return ts;
282 }
283
284 #endif
285
286 static ScrollingScope nextScrollingScope()
287 {
288     static ScrollingScope currentScope = 0;
289     return ++currentScope;
290 }
291
292 DEFINE_ALLOCATOR_WITH_HEAP_IDENTIFIER(RenderLayer);
293
294 RenderLayer::RenderLayer(RenderLayerModelObject& rendererLayerModelObject)
295     : m_isRenderViewLayer(rendererLayerModelObject.isRenderView())
296     , m_forcedStackingContext(rendererLayerModelObject.isMedia())
297     , m_isNormalFlowOnly(false)
298     , m_isCSSStackingContext(false)
299     , m_isOpportunisticStackingContext(false)
300     , m_zOrderListsDirty(false)
301     , m_normalFlowListDirty(true)
302     , m_hadNegativeZOrderList(false)
303     , m_inResizeMode(false)
304     , m_scrollDimensionsDirty(true)
305     , m_hasSelfPaintingLayerDescendant(false)
306     , m_hasSelfPaintingLayerDescendantDirty(false)
307     , m_usedTransparency(false)
308     , m_paintingInsideReflection(false)
309     , m_inOverflowRelayout(false)
310     , m_repaintStatus(NeedsNormalRepaint)
311     , m_visibleContentStatusDirty(true)
312     , m_hasVisibleContent(false)
313     , m_visibleDescendantStatusDirty(false)
314     , m_hasVisibleDescendant(false)
315     , m_registeredScrollableArea(false)
316     , m_isFixedIntersectingViewport(false)
317     , m_behavesAsFixed(false)
318     , m_3DTransformedDescendantStatusDirty(true)
319     , m_has3DTransformedDescendant(false)
320     , m_hasCompositingDescendant(false)
321     , m_hasCompositedScrollingAncestor(false)
322     , m_hasCompositedScrollableOverflow(false)
323     , m_hasTransformedAncestor(false)
324     , m_has3DTransformedAncestor(false)
325     , m_indirectCompositingReason(static_cast<unsigned>(IndirectCompositingReason::None))
326     , m_viewportConstrainedNotCompositedReason(NoNotCompositedReason)
327 #if PLATFORM(IOS_FAMILY)
328 #if ENABLE(IOS_TOUCH_EVENTS)
329     , m_registeredAsTouchEventListenerForScrolling(false)
330 #endif
331     , m_adjustForIOSCaretWhenScrolling(false)
332 #endif
333     , m_requiresScrollPositionReconciliation(false)
334     , m_containsDirtyOverlayScrollbars(false)
335     , m_updatingMarqueePosition(false)
336 #if ASSERT_ENABLED
337     , m_layerListMutationAllowed(true)
338 #endif
339 #if ENABLE(CSS_COMPOSITING)
340     , m_blendMode(static_cast<unsigned>(BlendMode::Normal))
341     , m_hasNotIsolatedCompositedBlendingDescendants(false)
342     , m_hasNotIsolatedBlendingDescendants(false)
343     , m_hasNotIsolatedBlendingDescendantsStatusDirty(false)
344 #endif
345     , m_renderer(rendererLayerModelObject)
346 {
347     setIsNormalFlowOnly(shouldBeNormalFlowOnly());
348     setIsCSSStackingContext(shouldBeCSSStackingContext());
349
350     m_isSelfPaintingLayer = shouldBeSelfPaintingLayer();
351
352     if (isRenderViewLayer())
353         m_boxScrollingScope = m_contentsScrollingScope = nextScrollingScope();
354
355     if (!renderer().firstChild()) {
356         m_visibleContentStatusDirty = false;
357         m_hasVisibleContent = renderer().style().visibility() == Visibility::Visible;
358     }
359
360     if (Element* element = renderer().element()) {
361         // We save and restore only the scrollOffset as the other scroll values are recalculated.
362         m_scrollPosition = element->savedLayerScrollPosition();
363         if (!m_scrollPosition.isZero())
364             scrollAnimator().setCurrentPosition(m_scrollPosition);
365         element->setSavedLayerScrollPosition(IntPoint());
366     }
367 }
368
369 RenderLayer::~RenderLayer()
370 {
371     if (inResizeMode())
372         renderer().frame().eventHandler().resizeLayerDestroyed();
373
374     ASSERT(m_registeredScrollableArea == renderer().view().frameView().containsScrollableArea(this));
375
376     if (m_registeredScrollableArea)
377         renderer().view().frameView().removeScrollableArea(this);
378
379 #if ENABLE(IOS_TOUCH_EVENTS)
380     unregisterAsTouchEventListenerForScrolling();
381 #endif
382     if (Element* element = renderer().element())
383         element->setSavedLayerScrollPosition(m_scrollPosition);
384
385     destroyScrollbar(HorizontalScrollbar);
386     destroyScrollbar(VerticalScrollbar);
387
388     if (auto* scrollingCoordinator = renderer().page().scrollingCoordinator())
389         scrollingCoordinator->willDestroyScrollableArea(*this);
390
391     if (m_reflection)
392         removeReflection();
393
394     clearScrollCorner();
395     clearResizer();
396
397     clearLayerFilters();
398
399     if (paintsIntoProvidedBacking()) {
400         auto* backingProviderLayer = this->backingProviderLayer();
401         if (backingProviderLayer->backing())
402             backingProviderLayer->backing()->removeBackingSharingLayer(*this);
403     }
404
405     // Child layers will be deleted by their corresponding render objects, so
406     // we don't need to delete them ourselves.
407
408     clearBacking(true);
409
410     // Layer and all its children should be removed from the tree before destruction.
411     RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(renderer().renderTreeBeingDestroyed() || !parent());
412     RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(renderer().renderTreeBeingDestroyed() || !firstChild());
413 }
414
415 void RenderLayer::addChild(RenderLayer& child, RenderLayer* beforeChild)
416 {
417     RenderLayer* prevSibling = beforeChild ? beforeChild->previousSibling() : lastChild();
418     if (prevSibling) {
419         child.setPreviousSibling(prevSibling);
420         prevSibling->setNextSibling(&child);
421         ASSERT(prevSibling != &child);
422     } else
423         setFirstChild(&child);
424
425     if (beforeChild) {
426         beforeChild->setPreviousSibling(&child);
427         child.setNextSibling(beforeChild);
428         ASSERT(beforeChild != &child);
429     } else
430         setLastChild(&child);
431
432     child.setParent(this);
433
434     dirtyPaintOrderListsOnChildChange(child);
435
436     child.updateDescendantDependentFlags();
437     if (child.m_hasVisibleContent || child.m_hasVisibleDescendant)
438         setAncestorChainHasVisibleDescendant();
439
440     if (child.isSelfPaintingLayer() || child.hasSelfPaintingLayerDescendant())
441         setAncestorChainHasSelfPaintingLayerDescendant();
442
443     if (compositor().hasContentCompositingLayers())
444         setDescendantsNeedCompositingRequirementsTraversal();
445
446     if (child.hasDescendantNeedingCompositingRequirementsTraversal() || child.needsCompositingRequirementsTraversal())
447         child.setAncestorsHaveCompositingDirtyFlag(Compositing::HasDescendantNeedingRequirementsTraversal);
448
449     if (child.hasDescendantNeedingUpdateBackingOrHierarchyTraversal() || child.needsUpdateBackingOrHierarchyTraversal())
450         child.setAncestorsHaveCompositingDirtyFlag(Compositing::HasDescendantNeedingBackingOrHierarchyTraversal);
451
452 #if ENABLE(CSS_COMPOSITING)
453     if (child.hasBlendMode() || (child.hasNotIsolatedBlendingDescendants() && !child.isolatesBlending()))
454         updateAncestorChainHasBlendingDescendants(); // Why not just dirty?
455 #endif
456
457     compositor().layerWasAdded(*this, child);
458 }
459
460 void RenderLayer::removeChild(RenderLayer& oldChild)
461 {
462     if (!renderer().renderTreeBeingDestroyed())
463         compositor().layerWillBeRemoved(*this, oldChild);
464
465     // remove the child
466     if (oldChild.previousSibling())
467         oldChild.previousSibling()->setNextSibling(oldChild.nextSibling());
468     if (oldChild.nextSibling())
469         oldChild.nextSibling()->setPreviousSibling(oldChild.previousSibling());
470
471     if (m_first == &oldChild)
472         m_first = oldChild.nextSibling();
473     if (m_last == &oldChild)
474         m_last = oldChild.previousSibling();
475
476     dirtyPaintOrderListsOnChildChange(oldChild);
477
478     oldChild.setPreviousSibling(nullptr);
479     oldChild.setNextSibling(nullptr);
480     oldChild.setParent(nullptr);
481     
482     oldChild.updateDescendantDependentFlags();
483     if (oldChild.m_hasVisibleContent || oldChild.m_hasVisibleDescendant)
484         dirtyAncestorChainVisibleDescendantStatus();
485
486     if (oldChild.isSelfPaintingLayer() || oldChild.hasSelfPaintingLayerDescendant())
487         dirtyAncestorChainHasSelfPaintingLayerDescendantStatus();
488
489     if (compositor().hasContentCompositingLayers())
490         setDescendantsNeedCompositingRequirementsTraversal();
491
492 #if ENABLE(CSS_COMPOSITING)
493     if (oldChild.hasBlendMode() || (oldChild.hasNotIsolatedBlendingDescendants() && !oldChild.isolatesBlending()))
494         dirtyAncestorChainHasBlendingDescendants();
495 #endif
496 }
497
498 void RenderLayer::dirtyPaintOrderListsOnChildChange(RenderLayer& child)
499 {
500     if (child.isNormalFlowOnly())
501         dirtyNormalFlowList();
502
503     if (!child.isNormalFlowOnly() || child.firstChild()) {
504         // Dirty the z-order list in which we are contained. The stackingContext() can be null in the
505         // case where we're building up generated content layers. This is ok, since the lists will start
506         // off dirty in that case anyway.
507         child.dirtyStackingContextZOrderLists();
508     }
509 }
510
511 void RenderLayer::insertOnlyThisLayer(LayerChangeTiming timing)
512 {
513     if (!m_parent && renderer().parent()) {
514         // We need to connect ourselves when our renderer() has a parent.
515         // Find our enclosingLayer and add ourselves.
516         RenderLayer* parentLayer = renderer().parent()->enclosingLayer();
517         ASSERT(parentLayer);
518         RenderLayer* beforeChild = parentLayer->reflectionLayer() != this ? renderer().parent()->findNextLayer(parentLayer, &renderer()) : nullptr;
519         parentLayer->addChild(*this, beforeChild);
520     }
521
522     // Remove all descendant layers from the hierarchy and add them to the new position.
523     for (auto& child : childrenOfType<RenderElement>(renderer()))
524         child.moveLayers(m_parent, this);
525
526     if (parent()) {
527         if (timing == LayerChangeTiming::StyleChange)
528             renderer().view().layerChildrenChangedDuringStyleChange(*parent());
529     }
530     
531     // Clear out all the clip rects.
532     clearClipRectsIncludingDescendants();
533 }
534
535 void RenderLayer::removeOnlyThisLayer(LayerChangeTiming timing)
536 {
537     if (!m_parent)
538         return;
539
540     if (timing == LayerChangeTiming::StyleChange)
541         renderer().view().layerChildrenChangedDuringStyleChange(*parent());
542
543     // Mark that we are about to lose our layer. This makes render tree
544     // walks ignore this layer while we're removing it.
545     renderer().setHasLayer(false);
546
547     compositor().layerWillBeRemoved(*m_parent, *this);
548
549     // Dirty the clip rects.
550     clearClipRectsIncludingDescendants();
551
552     RenderLayer* nextSib = nextSibling();
553
554     // Remove the child reflection layer before moving other child layers.
555     // The reflection layer should not be moved to the parent.
556     if (reflection())
557         removeChild(*reflectionLayer());
558
559     // Now walk our kids and reattach them to our parent.
560     RenderLayer* current = m_first;
561     while (current) {
562         RenderLayer* next = current->nextSibling();
563         removeChild(*current);
564         m_parent->addChild(*current, nextSib);
565         current->setRepaintStatus(NeedsFullRepaint);
566         current = next;
567     }
568
569     // Remove us from the parent.
570     m_parent->removeChild(*this);
571     renderer().destroyLayer();
572 }
573
574 static bool canCreateStackingContext(const RenderLayer& layer)
575 {
576     auto& renderer = layer.renderer();
577     return renderer.hasTransformRelatedProperty()
578         || renderer.hasClipPath()
579         || renderer.hasFilter()
580         || renderer.hasMask()
581         || renderer.hasBackdropFilter()
582 #if ENABLE(CSS_COMPOSITING)
583         || renderer.hasBlendMode()
584 #endif
585         || renderer.isTransparent()
586         || renderer.isPositioned() // Note that this only creates stacking context in conjunction with explicit z-index.
587         || renderer.hasReflection()
588         || renderer.style().hasIsolation()
589         || !renderer.style().hasAutoUsedZIndex()
590         || (renderer.style().willChange() && renderer.style().willChange()->canCreateStackingContext());
591 }
592
593 bool RenderLayer::shouldBeNormalFlowOnly() const
594 {
595     if (canCreateStackingContext(*this))
596         return false;
597
598     return renderer().hasOverflowClip()
599         || renderer().isCanvas()
600         || renderer().isVideo()
601         || renderer().isEmbeddedObject()
602         || renderer().isRenderIFrame()
603         || (renderer().isRenderImage() && downcast<RenderImage>(renderer()).isEditableImage())
604         || (renderer().style().specifiesColumns() && !isRenderViewLayer())
605         || renderer().isInFlowRenderFragmentedFlow();
606 }
607
608 bool RenderLayer::shouldBeCSSStackingContext() const
609 {
610     return !renderer().style().hasAutoUsedZIndex() || isRenderViewLayer();
611 }
612
613 bool RenderLayer::setIsNormalFlowOnly(bool isNormalFlowOnly)
614 {
615     if (isNormalFlowOnly == m_isNormalFlowOnly)
616         return false;
617     
618     m_isNormalFlowOnly = isNormalFlowOnly;
619
620     if (auto* p = parent())
621         p->dirtyNormalFlowList();
622     dirtyStackingContextZOrderLists();
623     return true;
624 }
625
626 void RenderLayer::isStackingContextChanged()
627 {
628     dirtyStackingContextZOrderLists();
629     if (isStackingContext())
630         dirtyZOrderLists();
631     else
632         clearZOrderLists();
633 }
634
635 bool RenderLayer::setIsOpportunisticStackingContext(bool isStacking)
636 {
637     bool wasStacking = isStackingContext();
638     m_isOpportunisticStackingContext = isStacking;
639     if (wasStacking == isStackingContext())
640         return false;
641
642     isStackingContextChanged();
643     return true;
644 }
645
646 bool RenderLayer::setIsCSSStackingContext(bool isCSSStackingContext)
647 {
648     bool wasStacking = isStackingContext();
649     m_isCSSStackingContext = isCSSStackingContext;
650     if (wasStacking == isStackingContext())
651         return false;
652
653     isStackingContextChanged();
654     return true;
655 }
656
657 void RenderLayer::setParent(RenderLayer* parent)
658 {
659     if (parent == m_parent)
660         return;
661
662     if (m_parent && !renderer().renderTreeBeingDestroyed())
663         compositor().layerWillBeRemoved(*m_parent, *this);
664
665     m_parent = parent;
666
667     if (m_parent && !renderer().renderTreeBeingDestroyed())
668         compositor().layerWasAdded(*m_parent, *this);
669 }
670
671 RenderLayer* RenderLayer::stackingContext() const
672 {
673     auto* layer = parent();
674     while (layer && !layer->isStackingContext())
675         layer = layer->parent();
676
677     ASSERT(!layer || layer->isStackingContext());
678     return layer;
679 }
680
681 void RenderLayer::dirtyZOrderLists()
682 {
683     ASSERT(layerListMutationAllowed());
684     ASSERT(isStackingContext());
685
686     if (m_posZOrderList)
687         m_posZOrderList->clear();
688     if (m_negZOrderList)
689         m_negZOrderList->clear();
690     m_zOrderListsDirty = true;
691
692     // FIXME: Ideally, we'd only dirty if the lists changed.
693     if (hasCompositingDescendant())
694         setNeedsCompositingPaintOrderChildrenUpdate();
695 }
696
697 void RenderLayer::dirtyStackingContextZOrderLists()
698 {
699     if (auto* sc = stackingContext())
700         sc->dirtyZOrderLists();
701 }
702
703 void RenderLayer::dirtyNormalFlowList()
704 {
705     ASSERT(layerListMutationAllowed());
706
707     if (m_normalFlowList)
708         m_normalFlowList->clear();
709     m_normalFlowListDirty = true;
710
711     if (hasCompositingDescendant())
712         setNeedsCompositingPaintOrderChildrenUpdate();
713 }
714
715 void RenderLayer::updateNormalFlowList()
716 {
717     if (!m_normalFlowListDirty)
718         return;
719
720     ASSERT(layerListMutationAllowed());
721
722     for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
723         // Ignore non-overflow layers and reflections.
724         if (child->isNormalFlowOnly() && !isReflectionLayer(*child)) {
725             if (!m_normalFlowList)
726                 m_normalFlowList = makeUnique<Vector<RenderLayer*>>();
727             m_normalFlowList->append(child);
728         }
729     }
730     
731     m_normalFlowListDirty = false;
732 }
733
734 void RenderLayer::rebuildZOrderLists()
735 {
736     ASSERT(layerListMutationAllowed());
737     ASSERT(isDirtyStackingContext());
738     
739     OptionSet<Compositing> childDirtyFlags;
740     rebuildZOrderLists(m_posZOrderList, m_negZOrderList, childDirtyFlags);
741     m_zOrderListsDirty = false;
742     
743     bool hasNegativeZOrderList = m_negZOrderList && m_negZOrderList->size();
744     // Having negative z-order lists affect whether a compositing layer needs a foreground layer.
745     // Ideally we'd only trigger this when having z-order children changes, but we blow away the old z-order
746     // lists on dirtying so we don't know the old state.
747     if (hasNegativeZOrderList != m_hadNegativeZOrderList) {
748         m_hadNegativeZOrderList = hasNegativeZOrderList;
749         if (isComposited())
750             setNeedsCompositingConfigurationUpdate();
751     }
752
753     // Building lists may have added layers with dirty flags, so make sure we propagate dirty bits up the tree.
754     if (m_compositingDirtyBits.containsAll({ Compositing::DescendantsNeedRequirementsTraversal, Compositing::DescendantsNeedBackingAndHierarchyTraversal }))
755         return;
756
757     if (childDirtyFlags.containsAny(computeCompositingRequirementsFlags()))
758         setDescendantsNeedCompositingRequirementsTraversal();
759
760     if (childDirtyFlags.containsAny(updateBackingOrHierarchyFlags()))
761         setDescendantsNeedUpdateBackingAndHierarchyTraversal();
762 }
763
764 void RenderLayer::rebuildZOrderLists(std::unique_ptr<Vector<RenderLayer*>>& posZOrderList, std::unique_ptr<Vector<RenderLayer*>>& negZOrderList, OptionSet<Compositing>& accumulatedDirtyFlags)
765 {
766     bool includeHiddenLayers = compositor().usesCompositing();
767     for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
768         if (!isReflectionLayer(*child))
769             child->collectLayers(includeHiddenLayers, posZOrderList, negZOrderList, accumulatedDirtyFlags);
770     }
771
772     auto compareZIndex = [] (const RenderLayer* first, const RenderLayer* second) -> bool {
773         return first->zIndex() < second->zIndex();
774     };
775
776     // Sort the two lists.
777     if (posZOrderList)
778         std::stable_sort(posZOrderList->begin(), posZOrderList->end(), compareZIndex);
779
780     if (negZOrderList)
781         std::stable_sort(negZOrderList->begin(), negZOrderList->end(), compareZIndex);
782 }
783
784 void RenderLayer::collectLayers(bool includeHiddenLayers, std::unique_ptr<Vector<RenderLayer*>>& positiveZOrderList, std::unique_ptr<Vector<RenderLayer*>>& negativeZOrderList, OptionSet<Compositing>& accumulatedDirtyFlags)
785 {
786     updateDescendantDependentFlags();
787
788     bool isStacking = isStackingContext();
789     // Overflow layers are just painted by their enclosing layers, so they don't get put in zorder lists.
790     bool includeHiddenLayer = includeHiddenLayers || (m_hasVisibleContent || (m_hasVisibleDescendant && isStacking));
791     if (includeHiddenLayer && !isNormalFlowOnly()) {
792         auto& layerList = (zIndex() >= 0) ? positiveZOrderList : negativeZOrderList;
793         if (!layerList)
794             layerList = makeUnique<Vector<RenderLayer*>>();
795         layerList->append(this);
796         accumulatedDirtyFlags.add(m_compositingDirtyBits);
797     }
798
799     // Recur into our children to collect more layers, but only if we don't establish
800     // a stacking context/container.
801     if ((includeHiddenLayers || m_hasVisibleDescendant) && !isStacking) {
802         for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
803             // Ignore reflections.
804             if (!isReflectionLayer(*child))
805                 child->collectLayers(includeHiddenLayers, positiveZOrderList, negativeZOrderList, accumulatedDirtyFlags);
806         }
807     }
808 }
809
810 void RenderLayer::setAncestorsHaveCompositingDirtyFlag(Compositing flag)
811 {
812     for (auto* layer = paintOrderParent(); layer; layer = layer->paintOrderParent()) {
813         if (layer->m_compositingDirtyBits.contains(flag))
814             break;
815         layer->m_compositingDirtyBits.add(flag);
816     }
817 }
818
819 void RenderLayer::updateLayerListsIfNeeded()
820 {
821     updateZOrderLists();
822     updateNormalFlowList();
823
824     if (RenderLayer* reflectionLayer = this->reflectionLayer()) {
825         reflectionLayer->updateZOrderLists();
826         reflectionLayer->updateNormalFlowList();
827     }
828 }
829
830 String RenderLayer::name() const
831 {
832     StringBuilder name;
833
834     if (Element* element = renderer().element()) {
835         name.append(" <");
836         name.append(element->tagName().convertToLowercaseWithoutLocale());
837         name.append('>');
838
839         if (element->hasID()) {
840             name.appendLiteral(" id=\'");
841             name.append(element->getIdAttribute());
842             name.append('\'');
843         }
844
845         if (element->hasClass()) {
846             name.appendLiteral(" class=\'");
847             size_t classNamesToDump = element->classNames().size();
848             const size_t maxNumClassNames = 7;
849             bool addEllipsis = false;
850             if (classNamesToDump > maxNumClassNames) {
851                 classNamesToDump = maxNumClassNames;
852                 addEllipsis = true;
853             }
854             
855             for (size_t i = 0; i < classNamesToDump; ++i) {
856                 if (i > 0)
857                     name.append(' ');
858                 name.append(element->classNames()[i]);
859             }
860             if (addEllipsis)
861                 name.append("...");
862             name.append('\'');
863         }
864     } else
865         name.append(renderer().renderName());
866
867     if (isReflection())
868         name.appendLiteral(" (reflection)");
869
870     return name.toString();
871 }
872
873 RenderLayerCompositor& RenderLayer::compositor() const
874 {
875     return renderer().view().compositor();
876 }
877
878 void RenderLayer::contentChanged(ContentChangeType changeType)
879 {
880     if (changeType == CanvasChanged || changeType == VideoChanged || changeType == FullScreenChanged || (isComposited() && changeType == ImageChanged)) {
881         setNeedsPostLayoutCompositingUpdate();
882         setNeedsCompositingConfigurationUpdate();
883     }
884
885     if (auto* backing = this->backing())
886         backing->contentChanged(changeType);
887 }
888
889 bool RenderLayer::canRender3DTransforms() const
890 {
891     return compositor().canRender3DTransforms();
892 }
893
894 bool RenderLayer::paintsWithFilters() const
895 {
896     if (!renderer().hasFilter())
897         return false;
898         
899     if (!isComposited())
900         return true;
901
902     return !m_backing->canCompositeFilters();
903 }
904
905 bool RenderLayer::requiresFullLayerImageForFilters() const 
906 {
907     if (!paintsWithFilters())
908         return false;
909
910     return m_filters && m_filters->hasFilterThatMovesPixels();
911 }
912
913 OptionSet<RenderLayer::UpdateLayerPositionsFlag> RenderLayer::flagsForUpdateLayerPositions(RenderLayer& startingLayer)
914 {
915     OptionSet<UpdateLayerPositionsFlag> flags = { CheckForRepaint };
916
917     if (auto* parent = startingLayer.parent()) {
918         if (parent->hasTransformedAncestor() || parent->transform())
919             flags.add(SeenTransformedLayer);
920
921         if (parent->has3DTransformedAncestor() || (parent->transform() && !parent->transform()->isAffine()))
922             flags.add(Seen3DTransformedLayer);
923
924         if (parent->behavesAsFixed() || (parent->renderer().isFixedPositioned() && !parent->hasTransformedAncestor()))
925             flags.add(SeenFixedLayer);
926
927         if (parent->hasCompositedScrollingAncestor() || parent->hasCompositedScrollableOverflow())
928             flags.add(SeenCompositedScrollingLayer);
929     }
930
931     return flags;
932 }
933
934 void RenderLayer::updateLayerPositionsAfterStyleChange()
935 {
936     updateLayerPositions(nullptr, flagsForUpdateLayerPositions(*this));
937 }
938
939 void RenderLayer::updateLayerPositionsAfterLayout(bool isRelayoutingSubtree, bool didFullRepaint)
940 {
941     auto updateLayerPositionFlags = [&](bool isRelayoutingSubtree, bool didFullRepaint) {
942         auto flags = flagsForUpdateLayerPositions(*this);
943         if (didFullRepaint) {
944             flags.remove(RenderLayer::CheckForRepaint);
945             flags.add(RenderLayer::NeedsFullRepaintInBacking);
946         }
947         if (isRelayoutingSubtree && enclosingPaginationLayer(RenderLayer::IncludeCompositedPaginatedLayers))
948             flags.add(RenderLayer::UpdatePagination);
949         return flags;
950     };
951
952     LOG(Compositing, "RenderLayer %p updateLayerPositionsAfterLayout", this);
953     RenderGeometryMap geometryMap(UseTransforms);
954     if (!isRenderViewLayer())
955         geometryMap.pushMappingsToAncestor(parent(), nullptr);
956
957     updateLayerPositions(&geometryMap, updateLayerPositionFlags(isRelayoutingSubtree, didFullRepaint));
958 }
959
960 void RenderLayer::updateLayerPositions(RenderGeometryMap* geometryMap, OptionSet<UpdateLayerPositionsFlag> flags)
961 {
962     updateLayerPosition(&flags);
963     applyPostLayoutScrollPositionIfNeeded();
964
965     if (geometryMap)
966         geometryMap->pushMappingsToAncestor(this, parent());
967
968     // Clear our cached clip rect information.
969     clearClipRects();
970
971     if (hasOverflowControls()) {
972         LayoutSize offsetFromRoot;
973         if (geometryMap)
974             offsetFromRoot = LayoutSize(toFloatSize(geometryMap->absolutePoint(FloatPoint())));
975         else {
976             // FIXME: It looks suspicious to call convertToLayerCoords here
977             // as canUseOffsetFromAncestor may be true for an ancestor layer.
978             offsetFromRoot = offsetFromAncestor(root());
979         }
980         positionOverflowControls(roundedIntSize(offsetFromRoot));
981     }
982
983     updateDescendantDependentFlags();
984
985     if (flags & UpdatePagination)
986         updatePagination();
987     else
988         m_enclosingPaginationLayer = nullptr;
989     
990     if (m_hasVisibleContent) {
991         // FIXME: Paint offset cache does not work with RenderLayers as there is not a 1-to-1
992         // mapping between them and the RenderObjects. It would be neat to enable
993         // LayoutState outside the layout() phase and use it here.
994         ASSERT(!renderer().view().frameView().layoutContext().isPaintOffsetCacheEnabled());
995
996         RenderLayerModelObject* repaintContainer = renderer().containerForRepaint();
997         
998         auto hadRepaintLayoutRects = renderer().hasRepaintLayoutRects();
999         RepaintLayoutRects oldRects = hadRepaintLayoutRects ? renderer().repaintLayoutRects() : RepaintLayoutRects();
1000         computeRepaintRects(repaintContainer, geometryMap);
1001         
1002         auto hasRepaintLayoutRects = renderer().hasRepaintLayoutRects();
1003         RepaintLayoutRects newRects = hasRepaintLayoutRects ? renderer().repaintLayoutRects() : RepaintLayoutRects();
1004         // FIXME: Should ASSERT that value calculated for m_outlineBox using the cached offset is the same
1005         // as the value not using the cached offset, but we can't due to https://bugs.webkit.org/show_bug.cgi?id=37048
1006         if ((flags & CheckForRepaint) && hasRepaintLayoutRects) {
1007             if (!renderer().view().printing()) {
1008                 if (m_repaintStatus & NeedsFullRepaint) {
1009                     if (hadRepaintLayoutRects)
1010                         renderer().repaintUsingContainer(repaintContainer, oldRects.m_repaintRect);
1011                     if (!hadRepaintLayoutRects || newRects.m_repaintRect != oldRects.m_repaintRect)
1012                         renderer().repaintUsingContainer(repaintContainer, newRects.m_repaintRect);
1013                 } else if (shouldRepaintAfterLayout()) {
1014                     // FIXME: We will convert this to just take the old and new RepaintLayoutRects once
1015                     // we change other callers to use RepaintLayoutRects.
1016                     renderer().repaintAfterLayoutIfNeeded(repaintContainer, oldRects.m_repaintRect, oldRects.m_outlineBox, &newRects.m_repaintRect, &newRects.m_outlineBox);
1017                 }
1018             }
1019         }
1020     } else
1021         clearRepaintRects();
1022
1023     m_repaintStatus = NeedsNormalRepaint;
1024     m_hasTransformedAncestor = flags.contains(SeenTransformedLayer);
1025     m_has3DTransformedAncestor = flags.contains(Seen3DTransformedLayer);
1026     m_behavesAsFixed = flags.contains(SeenFixedLayer);
1027     setHasCompositedScrollingAncestor(flags.contains(SeenCompositedScrollingLayer));
1028
1029     // Update the reflection's position and size.
1030     if (m_reflection)
1031         m_reflection->layout();
1032
1033     if (renderer().isInFlowRenderFragmentedFlow()) {
1034         updatePagination();
1035         flags.add(UpdatePagination);
1036     }
1037
1038     if (transform()) {
1039         flags.add(SeenTransformedLayer);
1040         if (!transform()->isAffine())
1041             flags.add(Seen3DTransformedLayer);
1042     }
1043
1044     // Fixed inside transform behaves like absolute (per spec).
1045     if (renderer().isFixedPositioned() && !m_hasTransformedAncestor) {
1046         m_behavesAsFixed = true;
1047         flags.add(SeenFixedLayer);
1048     }
1049
1050     if (hasCompositedScrollableOverflow())
1051         flags.add(SeenCompositedScrollingLayer);
1052
1053     for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
1054         child->updateLayerPositions(geometryMap, flags);
1055
1056     // With all our children positioned, now update our marquee if we need to.
1057     if (m_marquee) {
1058         // FIXME: would like to use SetForScope<> but it doesn't work with bitfields.
1059         bool oldUpdatingMarqueePosition = m_updatingMarqueePosition;
1060         m_updatingMarqueePosition = true;
1061         m_marquee->updateMarqueePosition();
1062         m_updatingMarqueePosition = oldUpdatingMarqueePosition;
1063     }
1064
1065     if (renderer().isFixedPositioned() && renderer().settings().acceleratedCompositingForFixedPositionEnabled()) {
1066         bool intersectsViewport = compositor().fixedLayerIntersectsViewport(*this);
1067         if (intersectsViewport != m_isFixedIntersectingViewport) {
1068             m_isFixedIntersectingViewport = intersectsViewport;
1069             setNeedsPostLayoutCompositingUpdate();
1070         }
1071     }
1072
1073     if (isComposited())
1074         backing()->updateAfterLayout(flags.contains(ContainingClippingLayerChangedSize), flags.contains(NeedsFullRepaintInBacking));
1075
1076     if (geometryMap)
1077         geometryMap->popMappingsToAncestor(parent());
1078
1079     renderer().document().markers().invalidateRectsForAllMarkers();
1080 }
1081
1082 LayoutRect RenderLayer::repaintRectIncludingNonCompositingDescendants() const
1083 {
1084     LayoutRect repaintRect = renderer().repaintLayoutRects().m_repaintRect;
1085     for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
1086         // Don't include repaint rects for composited child layers; they will paint themselves and have a different origin.
1087         if (child->isComposited())
1088             continue;
1089
1090         repaintRect.uniteIfNonZero(child->repaintRectIncludingNonCompositingDescendants());
1091     }
1092     return repaintRect;
1093 }
1094
1095 void RenderLayer::setAncestorChainHasSelfPaintingLayerDescendant()
1096 {
1097     for (RenderLayer* layer = this; layer; layer = layer->parent()) {
1098         if (!layer->m_hasSelfPaintingLayerDescendantDirty && layer->hasSelfPaintingLayerDescendant())
1099             break;
1100
1101         layer->m_hasSelfPaintingLayerDescendantDirty = false;
1102         layer->m_hasSelfPaintingLayerDescendant = true;
1103     }
1104 }
1105
1106 void RenderLayer::dirtyAncestorChainHasSelfPaintingLayerDescendantStatus()
1107 {
1108     for (RenderLayer* layer = this; layer; layer = layer->parent()) {
1109         layer->m_hasSelfPaintingLayerDescendantDirty = true;
1110         // If we have reached a self-painting layer, we know our parent should have a self-painting descendant
1111         // in this case, there is no need to dirty our ancestors further.
1112         if (layer->isSelfPaintingLayer()) {
1113             ASSERT(!parent() || parent()->m_hasSelfPaintingLayerDescendantDirty || parent()->hasSelfPaintingLayerDescendant());
1114             break;
1115         }
1116     }
1117 }
1118
1119 void RenderLayer::computeRepaintRects(const RenderLayerModelObject* repaintContainer, const RenderGeometryMap* geometryMap)
1120 {
1121     ASSERT(!m_visibleContentStatusDirty);
1122     renderer().computeRepaintLayoutRects(repaintContainer, geometryMap);
1123 }
1124
1125 void RenderLayer::computeRepaintRectsIncludingDescendants()
1126 {
1127     // FIXME: computeRepaintRects() has to walk up the parent chain for every layer to compute the rects.
1128     // We should make this more efficient.
1129     // FIXME: it's wrong to call this when layout is not up-to-date, which we do.
1130     computeRepaintRects(renderer().containerForRepaint());
1131
1132     for (RenderLayer* layer = firstChild(); layer; layer = layer->nextSibling())
1133         layer->computeRepaintRectsIncludingDescendants();
1134 }
1135
1136 void RenderLayer::clearRepaintRects()
1137 {
1138     ASSERT(!m_visibleContentStatusDirty);
1139
1140     renderer().clearRepaintLayoutRects();
1141 }
1142
1143 void RenderLayer::updateLayerPositionsAfterDocumentScroll()
1144 {
1145     ASSERT(this == renderer().view().layer());
1146
1147     LOG(Scrolling, "RenderLayer::updateLayerPositionsAfterDocumentScroll");
1148
1149     RenderGeometryMap geometryMap(UseTransforms);
1150     updateLayerPositionsAfterScroll(&geometryMap);
1151 }
1152
1153 void RenderLayer::updateLayerPositionsAfterOverflowScroll()
1154 {
1155     RenderGeometryMap geometryMap(UseTransforms);
1156     if (this != renderer().view().layer())
1157         geometryMap.pushMappingsToAncestor(parent(), nullptr);
1158
1159     // FIXME: why is it OK to not check the ancestors of this layer in order to
1160     // initialize the HasSeenViewportConstrainedAncestor and HasSeenAncestorWithOverflowClip flags?
1161     updateLayerPositionsAfterScroll(&geometryMap, IsOverflowScroll);
1162 }
1163
1164 void RenderLayer::updateLayerPositionsAfterScroll(RenderGeometryMap* geometryMap, OptionSet<UpdateLayerPositionsAfterScrollFlag> flags)
1165 {
1166     // FIXME: This shouldn't be needed, but there are some corner cases where
1167     // these flags are still dirty. Update so that the check below is valid.
1168     updateDescendantDependentFlags();
1169
1170     // If we have no visible content and no visible descendants, there is no point recomputing
1171     // our rectangles as they will be empty. If our visibility changes, we are expected to
1172     // recompute all our positions anyway.
1173     if (!m_hasVisibleDescendant && !m_hasVisibleContent)
1174         return;
1175
1176     bool positionChanged = updateLayerPosition();
1177     if (positionChanged)
1178         flags.add(HasChangedAncestor);
1179
1180     if (flags.containsAny({ HasChangedAncestor, HasSeenViewportConstrainedAncestor, IsOverflowScroll }))
1181         clearClipRects();
1182
1183     if (renderer().style().hasViewportConstrainedPosition())
1184         flags.add(HasSeenViewportConstrainedAncestor);
1185
1186     if (renderer().hasOverflowClip())
1187         flags.add(HasSeenAncestorWithOverflowClip);
1188     
1189     bool shouldComputeRepaintRects = (flags.contains(HasSeenViewportConstrainedAncestor) || flags.containsAll({ IsOverflowScroll, HasSeenAncestorWithOverflowClip })) && isSelfPaintingLayer();
1190     bool isVisuallyEmpty = !isVisuallyNonEmpty();
1191     bool shouldPushAndPopMappings = geometryMap && ((shouldComputeRepaintRects && !isVisuallyEmpty) || firstChild());
1192     if (shouldPushAndPopMappings)
1193         geometryMap->pushMappingsToAncestor(this, parent());
1194
1195     if (shouldComputeRepaintRects) {
1196         // When scrolling, we don't compute repaint rects for visually non-empty layers.
1197         if (isVisuallyEmpty)
1198             clearRepaintRects();
1199         else // FIXME: We could track the repaint container as we walk down the tree.
1200             computeRepaintRects(renderer().containerForRepaint(), geometryMap);
1201     } else if (!renderer().view().frameView().platformWidget()) {
1202         // When ScrollView's m_paintsEntireContents flag flips due to layer backing changes, the repaint area transitions from
1203         // visual to layout overflow. When this happens the cached repaint rects become invalid and they need to be recomputed (see webkit.org/b/188121).
1204         // Check that our cached rects are correct.
1205         ASSERT(!renderer().hasRepaintLayoutRects() || renderer().repaintLayoutRects().m_repaintRect == renderer().clippedOverflowRectForRepaint(renderer().containerForRepaint()));
1206         ASSERT(!renderer().hasRepaintLayoutRects() || renderer().repaintLayoutRects().m_outlineBox == renderer().outlineBoundsForRepaint(renderer().containerForRepaint()));
1207     }
1208     
1209     for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
1210         child->updateLayerPositionsAfterScroll(geometryMap, flags);
1211
1212     // We don't update our reflection as scrolling is a translation which does not change the size()
1213     // of an object, thus RenderReplica will still repaint itself properly as the layer position was
1214     // updated above.
1215
1216     if (m_marquee) {
1217         bool oldUpdatingMarqueePosition = m_updatingMarqueePosition;
1218         m_updatingMarqueePosition = true;
1219         m_marquee->updateMarqueePosition();
1220         m_updatingMarqueePosition = oldUpdatingMarqueePosition;
1221     }
1222
1223     if (shouldPushAndPopMappings)
1224         geometryMap->popMappingsToAncestor(parent());
1225
1226     renderer().document().markers().invalidateRectsForAllMarkers();
1227 }
1228
1229 #if ENABLE(CSS_COMPOSITING)
1230
1231 void RenderLayer::updateBlendMode()
1232 {
1233     bool hadBlendMode = static_cast<BlendMode>(m_blendMode) != BlendMode::Normal;
1234     if (parent() && hadBlendMode != hasBlendMode()) {
1235         if (hasBlendMode())
1236             parent()->updateAncestorChainHasBlendingDescendants();
1237         else
1238             parent()->dirtyAncestorChainHasBlendingDescendants();
1239     }
1240
1241     BlendMode newBlendMode = renderer().style().blendMode();
1242     if (newBlendMode != static_cast<BlendMode>(m_blendMode))
1243         m_blendMode = static_cast<unsigned>(newBlendMode);
1244 }
1245
1246 void RenderLayer::willRemoveChildWithBlendMode()
1247 {
1248     parent()->dirtyAncestorChainHasBlendingDescendants();
1249 }
1250
1251 void RenderLayer::updateAncestorChainHasBlendingDescendants()
1252 {
1253     for (auto* layer = this; layer; layer = layer->parent()) {
1254         if (!layer->hasNotIsolatedBlendingDescendantsStatusDirty() && layer->hasNotIsolatedBlendingDescendants())
1255             break;
1256         layer->m_hasNotIsolatedBlendingDescendants = true;
1257         layer->m_hasNotIsolatedBlendingDescendantsStatusDirty = false;
1258
1259         layer->updateSelfPaintingLayer();
1260
1261         if (layer->isCSSStackingContext())
1262             break;
1263     }
1264 }
1265
1266 void RenderLayer::dirtyAncestorChainHasBlendingDescendants()
1267 {
1268     for (auto* layer = this; layer; layer = layer->parent()) {
1269         if (layer->hasNotIsolatedBlendingDescendantsStatusDirty())
1270             break;
1271         
1272         layer->m_hasNotIsolatedBlendingDescendantsStatusDirty = true;
1273
1274         if (layer->isCSSStackingContext())
1275             break;
1276     }
1277 }
1278 #endif
1279
1280 static inline LayoutRect computeReferenceRectFromBox(const RenderBox& box, const CSSBoxType& boxType, const LayoutSize& offsetFromRoot)
1281 {
1282     LayoutRect referenceBox;
1283     switch (boxType) {
1284     case CSSBoxType::ContentBox:
1285     case CSSBoxType::FillBox:
1286         referenceBox = box.contentBoxRect();
1287         referenceBox.move(offsetFromRoot);
1288         break;
1289     case CSSBoxType::PaddingBox:
1290         referenceBox = box.paddingBoxRect();
1291         referenceBox.move(offsetFromRoot);
1292         break;
1293     case CSSBoxType::MarginBox:
1294         referenceBox = box.marginBoxRect();
1295         referenceBox.move(offsetFromRoot);
1296         break;
1297     // stroke-box, view-box compute to border-box for HTML elements.
1298     case CSSBoxType::StrokeBox:
1299     case CSSBoxType::ViewBox:
1300     case CSSBoxType::BorderBox:
1301     case CSSBoxType::BoxMissing:
1302         referenceBox = box.borderBoxRect();
1303         referenceBox.move(offsetFromRoot);
1304         break;
1305     }
1306
1307     return referenceBox;
1308 }
1309
1310 static inline LayoutRect computeReferenceBox(const RenderObject& renderer, const CSSBoxType& boxType, const LayoutSize& offsetFromRoot, const LayoutRect& rootRelativeBounds)
1311 {
1312     // FIXME: Support different reference boxes for inline content.
1313     // https://bugs.webkit.org/show_bug.cgi?id=129047
1314     if (!renderer.isBox())
1315         return rootRelativeBounds;
1316     
1317     return computeReferenceRectFromBox(downcast<RenderBox>(renderer), boxType, offsetFromRoot);
1318 }
1319
1320 static inline CSSBoxType transformBoxToCSSBoxType(TransformBox transformBox)
1321 {
1322     switch (transformBox) {
1323     case TransformBox::StrokeBox:
1324         return CSSBoxType::StrokeBox;
1325     case TransformBox::ContentBox:
1326         return CSSBoxType::ContentBox;
1327     case TransformBox::BorderBox:
1328         return CSSBoxType::BorderBox;
1329     case TransformBox::FillBox:
1330         return CSSBoxType::FillBox;
1331     case TransformBox::ViewBox:
1332         return CSSBoxType::ViewBox;
1333     default:
1334         ASSERT_NOT_REACHED();
1335         return CSSBoxType::BorderBox;
1336     }
1337 }
1338
1339 void RenderLayer::updateTransform()
1340 {
1341     bool hasTransform = renderer().hasTransform();
1342     bool had3DTransform = has3DTransform();
1343
1344     bool hadTransform = !!m_transform;
1345     if (hasTransform != hadTransform) {
1346         if (hasTransform)
1347             m_transform = makeUnique<TransformationMatrix>();
1348         else
1349             m_transform = nullptr;
1350         
1351         // Layers with transforms act as clip rects roots, so clear the cached clip rects here.
1352         clearClipRectsIncludingDescendants();
1353     }
1354     
1355     if (hasTransform) {
1356         RenderBox* box = renderBox();
1357         ASSERT(box);
1358         m_transform->makeIdentity();
1359         LayoutSize offsetFromRoot;
1360         auto computedReferenceBox = computeReferenceRectFromBox(*box, transformBoxToCSSBoxType(box->style().transformBox()), offsetFromRoot);
1361         box->style().applyTransform(*m_transform, snapRectToDevicePixels(computedReferenceBox, box->document().deviceScaleFactor()), RenderStyle::IncludeTransformOrigin);
1362         makeMatrixRenderable(*m_transform, canRender3DTransforms());
1363     }
1364
1365     if (had3DTransform != has3DTransform()) {
1366         dirty3DTransformedDescendantStatus();
1367         // Having a 3D transform affects whether enclosing perspective and preserve-3d layers composite, so trigger an update.
1368         setNeedsPostLayoutCompositingUpdateOnAncestors();
1369     }
1370 }
1371
1372 TransformationMatrix RenderLayer::currentTransform(RenderStyle::ApplyTransformOrigin applyOrigin) const
1373 {
1374     if (!m_transform)
1375         return TransformationMatrix();
1376     
1377     RenderBox* box = renderBox();
1378
1379     if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled()) {
1380         if (auto* timeline = renderer().documentTimeline()) {
1381             if (timeline->isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyTransform)) {
1382                 TransformationMatrix currTransform;
1383                 LayoutSize offsetFromRoot;
1384                 std::unique_ptr<RenderStyle> style = timeline->animatedStyleForRenderer(renderer());
1385                 auto computedReferenceBox = computeReferenceBox(renderer(), transformBoxToCSSBoxType(style->transformBox()), offsetFromRoot, box->borderBoxRect());
1386                 FloatRect pixelSnappedBorderRect = snapRectToDevicePixels(computedReferenceBox, box->document().deviceScaleFactor());
1387                 style->applyTransform(currTransform, pixelSnappedBorderRect, applyOrigin);
1388                 makeMatrixRenderable(currTransform, canRender3DTransforms());
1389                 return currTransform;
1390             }
1391         }
1392     } else {
1393         if (renderer().animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyTransform)) {
1394             TransformationMatrix currTransform;
1395             std::unique_ptr<RenderStyle> style = renderer().animation().animatedStyleForRenderer(renderer());
1396             LayoutSize offsetFromRoot;
1397             auto computedReferenceBox = computeReferenceBox(renderer(), transformBoxToCSSBoxType(style->transformBox()), offsetFromRoot, box->borderBoxRect());
1398             FloatRect pixelSnappedBorderRect = snapRectToDevicePixels(computedReferenceBox, box->document().deviceScaleFactor());
1399             style->applyTransform(currTransform, pixelSnappedBorderRect, applyOrigin);
1400             makeMatrixRenderable(currTransform, canRender3DTransforms());
1401             return currTransform;
1402         }
1403     }
1404
1405
1406     // m_transform includes transform-origin, so we need to recompute the transform here.
1407     if (applyOrigin == RenderStyle::ExcludeTransformOrigin) {
1408         TransformationMatrix currTransform;
1409         LayoutSize offsetFromRoot;
1410         std::unique_ptr<RenderStyle> style = renderer().animation().animatedStyleForRenderer(renderer());
1411         auto computedReferenceBox = computeReferenceBox(renderer(), transformBoxToCSSBoxType(style->transformBox()), offsetFromRoot, box->borderBoxRect());
1412         FloatRect pixelSnappedBorderRect = snapRectToDevicePixels(computedReferenceBox, box->document().deviceScaleFactor());
1413         box->style().applyTransform(currTransform, pixelSnappedBorderRect, RenderStyle::ExcludeTransformOrigin);
1414         makeMatrixRenderable(currTransform, canRender3DTransforms());
1415         return currTransform;
1416     }
1417
1418     return *m_transform;
1419 }
1420
1421 TransformationMatrix RenderLayer::renderableTransform(OptionSet<PaintBehavior> paintBehavior) const
1422 {
1423     if (!m_transform)
1424         return TransformationMatrix();
1425     
1426     if (paintBehavior & PaintBehavior::FlattenCompositingLayers) {
1427         TransformationMatrix matrix = *m_transform;
1428         makeMatrixRenderable(matrix, false /* flatten 3d */);
1429         return matrix;
1430     }
1431
1432     return *m_transform;
1433 }
1434
1435 RenderLayer* RenderLayer::enclosingOverflowClipLayer(IncludeSelfOrNot includeSelf) const
1436 {
1437     const RenderLayer* layer = (includeSelf == IncludeSelf) ? this : parent();
1438     while (layer) {
1439         if (layer->renderer().hasOverflowClip())
1440             return const_cast<RenderLayer*>(layer);
1441
1442         layer = layer->parent();
1443     }
1444     return nullptr;
1445 }
1446
1447 // FIXME: This is terrible. Bring back a cached bit for this someday. This crawl is going to slow down all
1448 // painting of content inside paginated layers.
1449 bool RenderLayer::hasCompositedLayerInEnclosingPaginationChain() const
1450 {
1451     // No enclosing layer means no compositing in the chain.
1452     if (!m_enclosingPaginationLayer)
1453         return false;
1454     
1455     // If the enclosing layer is composited, we don't have to check anything in between us and that
1456     // layer.
1457     if (m_enclosingPaginationLayer->isComposited())
1458         return true;
1459
1460     // If we are the enclosing pagination layer, then we can't be composited or we'd have passed the
1461     // previous check.
1462     if (m_enclosingPaginationLayer == this)
1463         return false;
1464
1465     // The enclosing paginated layer is our ancestor and is not composited, so we have to check
1466     // intermediate layers between us and the enclosing pagination layer. Start with our own layer.
1467     if (isComposited())
1468         return true;
1469     
1470     // For normal flow layers, we can recur up the layer tree.
1471     if (isNormalFlowOnly())
1472         return parent()->hasCompositedLayerInEnclosingPaginationChain();
1473     
1474     // Otherwise we have to go up the containing block chain. Find the first enclosing
1475     // containing block layer ancestor, and check that.
1476     for (const auto* containingBlock = renderer().containingBlock(); containingBlock && !is<RenderView>(*containingBlock); containingBlock = containingBlock->containingBlock()) {
1477         if (containingBlock->hasLayer())
1478             return containingBlock->layer()->hasCompositedLayerInEnclosingPaginationChain();
1479     }
1480     return false;
1481 }
1482
1483 void RenderLayer::updatePagination()
1484 {
1485     m_enclosingPaginationLayer = nullptr;
1486     
1487     if (!parent())
1488         return;
1489     
1490     // Each layer that is inside a multicolumn flow thread has to be checked individually and
1491     // genuinely know if it is going to have to split itself up when painting only its contents (and not any other descendant
1492     // layers). We track an enclosingPaginationLayer instead of using a simple bit, since we want to be able to get back
1493     // to that layer easily.
1494     if (renderer().isInFlowRenderFragmentedFlow()) {
1495         m_enclosingPaginationLayer = makeWeakPtr(*this);
1496         return;
1497     }
1498
1499     if (isNormalFlowOnly()) {
1500         // Content inside a transform is not considered to be paginated, since we simply
1501         // paint the transform multiple times in each column, so we don't have to use
1502         // fragments for the transformed content.
1503         if (parent()->hasTransform())
1504             m_enclosingPaginationLayer = nullptr;
1505         else
1506             m_enclosingPaginationLayer = makeWeakPtr(parent()->enclosingPaginationLayer(IncludeCompositedPaginatedLayers));
1507         return;
1508     }
1509
1510     // For the new columns code, we want to walk up our containing block chain looking for an enclosing layer. Once
1511     // we find one, then we just check its pagination status.
1512     for (const auto* containingBlock = renderer().containingBlock(); containingBlock && !is<RenderView>(*containingBlock); containingBlock = containingBlock->containingBlock()) {
1513         if (containingBlock->hasLayer()) {
1514             // Content inside a transform is not considered to be paginated, since we simply
1515             // paint the transform multiple times in each column, so we don't have to use
1516             // fragments for the transformed content.
1517             if (containingBlock->layer()->hasTransform())
1518                 m_enclosingPaginationLayer = nullptr;
1519             else
1520                 m_enclosingPaginationLayer = makeWeakPtr(containingBlock->layer()->enclosingPaginationLayer(IncludeCompositedPaginatedLayers));
1521             return;
1522         }
1523     }
1524 }
1525
1526 void RenderLayer::setHasVisibleContent()
1527
1528     if (m_hasVisibleContent && !m_visibleContentStatusDirty) {
1529         ASSERT(!parent() || parent()->hasVisibleDescendant());
1530         return;
1531     }
1532
1533     m_visibleContentStatusDirty = false; 
1534     m_hasVisibleContent = true;
1535     computeRepaintRects(renderer().containerForRepaint());
1536     if (!isNormalFlowOnly()) {
1537         // We don't collect invisible layers in z-order lists if we are not in compositing mode.
1538         // As we became visible, we need to dirty our stacking containers ancestors to be properly
1539         // collected. FIXME: When compositing, we could skip this dirtying phase.
1540         for (RenderLayer* sc = stackingContext(); sc; sc = sc->stackingContext()) {
1541             sc->dirtyZOrderLists();
1542             if (sc->hasVisibleContent())
1543                 break;
1544         }
1545     }
1546
1547     if (parent())
1548         parent()->setAncestorChainHasVisibleDescendant();
1549 }
1550
1551 void RenderLayer::dirtyVisibleContentStatus() 
1552
1553     m_visibleContentStatusDirty = true; 
1554     if (parent())
1555         parent()->dirtyAncestorChainVisibleDescendantStatus();
1556 }
1557
1558 void RenderLayer::dirtyAncestorChainVisibleDescendantStatus()
1559 {
1560     for (RenderLayer* layer = this; layer; layer = layer->parent()) {
1561         if (layer->m_visibleDescendantStatusDirty)
1562             break;
1563
1564         layer->m_visibleDescendantStatusDirty = true;
1565     }
1566 }
1567
1568 void RenderLayer::setAncestorChainHasVisibleDescendant()
1569 {
1570     for (RenderLayer* layer = this; layer; layer = layer->parent()) {
1571         if (!layer->m_visibleDescendantStatusDirty && layer->hasVisibleDescendant())
1572             break;
1573
1574         layer->m_hasVisibleDescendant = true;
1575         layer->m_visibleDescendantStatusDirty = false;
1576     }
1577 }
1578
1579 void RenderLayer::updateDescendantDependentFlags()
1580 {
1581     if (m_visibleDescendantStatusDirty || m_hasSelfPaintingLayerDescendantDirty || hasNotIsolatedBlendingDescendantsStatusDirty()) {
1582         bool hasVisibleDescendant = false;
1583         bool hasSelfPaintingLayerDescendant = false;
1584 #if ENABLE(CSS_COMPOSITING)
1585         bool hasNotIsolatedBlendingDescendants = false;
1586 #endif
1587
1588         for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
1589             child->updateDescendantDependentFlags();
1590
1591             hasVisibleDescendant |= child->m_hasVisibleContent || child->m_hasVisibleDescendant;
1592             hasSelfPaintingLayerDescendant |= child->isSelfPaintingLayer() || child->hasSelfPaintingLayerDescendant();
1593 #if ENABLE(CSS_COMPOSITING)
1594             hasNotIsolatedBlendingDescendants |= child->hasBlendMode() || (child->hasNotIsolatedBlendingDescendants() && !child->isolatesBlending());
1595 #endif
1596
1597             bool allFlagsSet = hasVisibleDescendant && hasSelfPaintingLayerDescendant;
1598 #if ENABLE(CSS_COMPOSITING)
1599             allFlagsSet &= hasNotIsolatedBlendingDescendants;
1600 #endif
1601             if (allFlagsSet)
1602                 break;
1603         }
1604
1605         m_hasVisibleDescendant = hasVisibleDescendant;
1606         m_visibleDescendantStatusDirty = false;
1607         m_hasSelfPaintingLayerDescendant = hasSelfPaintingLayerDescendant;
1608         m_hasSelfPaintingLayerDescendantDirty = false;
1609
1610 #if ENABLE(CSS_COMPOSITING)
1611         m_hasNotIsolatedBlendingDescendants = hasNotIsolatedBlendingDescendants;
1612         if (m_hasNotIsolatedBlendingDescendantsStatusDirty) {
1613             m_hasNotIsolatedBlendingDescendantsStatusDirty = false;
1614             updateSelfPaintingLayer();
1615         }
1616 #endif
1617     }
1618
1619     if (m_visibleContentStatusDirty) {
1620         if (renderer().style().visibility() == Visibility::Visible)
1621             m_hasVisibleContent = true;
1622         else {
1623             // layer may be hidden but still have some visible content, check for this
1624             m_hasVisibleContent = false;
1625             RenderObject* r = renderer().firstChild();
1626             while (r) {
1627                 if (r->style().visibility() == Visibility::Visible && !r->hasLayer()) {
1628                     m_hasVisibleContent = true;
1629                     break;
1630                 }
1631                 RenderObject* child = nullptr;
1632                 if (!r->hasLayer() && (child = r->firstChildSlow()))
1633                     r = child;
1634                 else if (r->nextSibling())
1635                     r = r->nextSibling();
1636                 else {
1637                     do {
1638                         r = r->parent();
1639                         if (r == &renderer())
1640                             r = nullptr;
1641                     } while (r && !r->nextSibling());
1642                     if (r)
1643                         r = r->nextSibling();
1644                 }
1645             }
1646         }    
1647         m_visibleContentStatusDirty = false; 
1648     }
1649 }
1650
1651 void RenderLayer::dirty3DTransformedDescendantStatus()
1652 {
1653     RenderLayer* curr = stackingContext();
1654     if (curr)
1655         curr->m_3DTransformedDescendantStatusDirty = true;
1656         
1657     // This propagates up through preserve-3d hierarchies to the enclosing flattening layer.
1658     // Note that preserves3D() creates stacking context, so we can just run up the stacking containers.
1659     while (curr && curr->preserves3D()) {
1660         curr->m_3DTransformedDescendantStatusDirty = true;
1661         curr = curr->stackingContext();
1662     }
1663 }
1664
1665 // Return true if this layer or any preserve-3d descendants have 3d.
1666 bool RenderLayer::update3DTransformedDescendantStatus()
1667 {
1668     if (m_3DTransformedDescendantStatusDirty) {
1669         m_has3DTransformedDescendant = false;
1670
1671         updateZOrderLists();
1672
1673         // Transformed or preserve-3d descendants can only be in the z-order lists, not
1674         // in the normal flow list, so we only need to check those.
1675         for (auto* layer : positiveZOrderLayers())
1676             m_has3DTransformedDescendant |= layer->update3DTransformedDescendantStatus();
1677
1678         // Now check our negative z-index children.
1679         for (auto* layer : negativeZOrderLayers())
1680             m_has3DTransformedDescendant |= layer->update3DTransformedDescendantStatus();
1681         
1682         m_3DTransformedDescendantStatusDirty = false;
1683     }
1684     
1685     // If we live in a 3d hierarchy, then the layer at the root of that hierarchy needs
1686     // the m_has3DTransformedDescendant set.
1687     if (preserves3D())
1688         return has3DTransform() || m_has3DTransformedDescendant;
1689
1690     return has3DTransform();
1691 }
1692
1693 bool RenderLayer::updateLayerPosition(OptionSet<UpdateLayerPositionsFlag>* flags)
1694 {
1695     LayoutPoint localPoint;
1696     LayoutSize inlineBoundingBoxOffset; // We don't put this into the RenderLayer x/y for inlines, so we need to subtract it out when done.
1697     if (renderer().isInline() && is<RenderInline>(renderer())) {
1698         auto& inlineFlow = downcast<RenderInline>(renderer());
1699         IntRect lineBox = inlineFlow.linesBoundingBox();
1700         setSize(lineBox.size());
1701         inlineBoundingBoxOffset = toLayoutSize(lineBox.location());
1702         localPoint += inlineBoundingBoxOffset;
1703     } else if (RenderBox* box = renderBox()) {
1704         // FIXME: Is snapping the size really needed here for the RenderBox case?
1705         auto newSize = snappedIntRect(box->frameRect()).size();
1706         if (newSize != size()) {
1707             if (is<RenderWidget>(*box) && downcast<RenderWidget>(*box).requiresAcceleratedCompositing()) {
1708                 // Trigger RenderLayerCompositor::requiresCompositingForFrame() which depends on the contentBoxRect size.
1709                 setNeedsPostLayoutCompositingUpdate();
1710             }
1711
1712             if (flags && renderer().hasOverflowClip())
1713                 flags->add(ContainingClippingLayerChangedSize);
1714
1715             setSize(newSize);
1716         }
1717         
1718         box->applyTopLeftLocationOffset(localPoint);
1719     }
1720
1721     if (!renderer().isOutOfFlowPositioned()) {
1722         auto* ancestor = renderer().parent();
1723         // We must adjust our position by walking up the render tree looking for the
1724         // nearest enclosing object with a layer.
1725         while (ancestor && !ancestor->hasLayer()) {
1726             if (is<RenderBox>(*ancestor) && !is<RenderTableRow>(*ancestor)) {
1727                 // Rows and cells share the same coordinate space (that of the section).
1728                 // Omit them when computing our xpos/ypos.
1729                 localPoint += downcast<RenderBox>(*ancestor).topLeftLocationOffset();
1730             }
1731             ancestor = ancestor->parent();
1732         }
1733         if (is<RenderTableRow>(ancestor)) {
1734             // Put ourselves into the row coordinate space.
1735             localPoint -= downcast<RenderTableRow>(*ancestor).topLeftLocationOffset();
1736         }
1737     }
1738     
1739     // Subtract our parent's scroll offset.
1740     RenderLayer* positionedParent;
1741     if (renderer().isOutOfFlowPositioned() && (positionedParent = enclosingAncestorForPosition(renderer().style().position()))) {
1742         // For positioned layers, we subtract out the enclosing positioned layer's scroll offset.
1743         if (positionedParent->renderer().hasOverflowClip())
1744             localPoint -= toLayoutSize(positionedParent->scrollPosition());
1745         
1746         if (positionedParent->renderer().isInFlowPositioned() && is<RenderInline>(positionedParent->renderer())) {
1747             LayoutSize offset = downcast<RenderInline>(positionedParent->renderer()).offsetForInFlowPositionedInline(&downcast<RenderBox>(renderer()));
1748             localPoint += offset;
1749         }
1750
1751         ASSERT(positionedParent->contentsScrollingScope());
1752         m_boxScrollingScope = positionedParent->contentsScrollingScope();
1753     } else if (auto* parentLayer = parent()) {
1754         if (parentLayer->renderer().hasOverflowClip())
1755             localPoint -= toLayoutSize(parent()->scrollPosition());
1756
1757         ASSERT(parentLayer->contentsScrollingScope());
1758         m_boxScrollingScope = parentLayer->contentsScrollingScope();
1759     }
1760
1761     if (hasCompositedScrollableOverflow()) {
1762         if (!m_contentsScrollingScope || m_contentsScrollingScope == m_boxScrollingScope)
1763             m_contentsScrollingScope = nextScrollingScope();
1764     } else if (!m_contentsScrollingScope || m_contentsScrollingScope != m_boxScrollingScope)
1765         m_contentsScrollingScope = m_boxScrollingScope;
1766
1767     bool positionOrOffsetChanged = false;
1768     if (renderer().isInFlowPositioned()) {
1769         LayoutSize newOffset = downcast<RenderBoxModelObject>(renderer()).offsetForInFlowPosition();
1770         positionOrOffsetChanged = newOffset != m_offsetForInFlowPosition;
1771         m_offsetForInFlowPosition = newOffset;
1772         localPoint.move(m_offsetForInFlowPosition);
1773     } else {
1774         m_offsetForInFlowPosition = LayoutSize();
1775     }
1776
1777     // FIXME: We'd really like to just get rid of the concept of a layer rectangle and rely on the renderers.
1778     localPoint -= inlineBoundingBoxOffset;
1779     
1780     positionOrOffsetChanged |= location() != localPoint;
1781     setLocation(localPoint);
1782     
1783     if (positionOrOffsetChanged && compositor().hasContentCompositingLayers()) {
1784         if (isComposited())
1785             setNeedsCompositingGeometryUpdate();
1786         // This layer's position can affect the location of a composited descendant (which may be a sibling in z-order),
1787         // so trigger a descendant walk from the paint-order parent.
1788         if (auto* paintParent = paintOrderParent())
1789             paintParent->setDescendantsNeedUpdateBackingAndHierarchyTraversal();
1790     }
1791
1792     return positionOrOffsetChanged;
1793 }
1794
1795 TransformationMatrix RenderLayer::perspectiveTransform() const
1796 {
1797     RenderBox* box = renderBox();
1798     if (!box)
1799         return TransformationMatrix();
1800     
1801     if (!box->hasTransformRelatedProperty())
1802         return TransformationMatrix();
1803
1804     const RenderStyle& style = box->style();
1805     if (!style.hasPerspective())
1806         return TransformationMatrix();
1807
1808     // Maybe fetch the perspective from the backing?
1809     const FloatRect borderBox = snapRectToDevicePixels(box->borderBoxRect(), box->document().deviceScaleFactor());
1810     float perspectiveOriginX = floatValueForLength(style.perspectiveOriginX(), borderBox.width());
1811     float perspectiveOriginY = floatValueForLength(style.perspectiveOriginY(), borderBox.height());
1812
1813     // A perspective origin of 0,0 makes the vanishing point in the center of the element.
1814     // We want it to be in the top-left, so subtract half the height and width.
1815     perspectiveOriginX -= borderBox.width() / 2.0f;
1816     perspectiveOriginY -= borderBox.height() / 2.0f;
1817     
1818     TransformationMatrix t;
1819     t.translate(perspectiveOriginX, perspectiveOriginY);
1820     t.applyPerspective(style.perspective());
1821     t.translate(-perspectiveOriginX, -perspectiveOriginY);
1822     
1823     return t;
1824 }
1825
1826 FloatPoint RenderLayer::perspectiveOrigin() const
1827 {
1828     if (!renderer().hasTransformRelatedProperty())
1829         return FloatPoint();
1830
1831     const LayoutRect borderBox = downcast<RenderBox>(renderer()).borderBoxRect();
1832     const RenderStyle& style = renderer().style();
1833
1834     return FloatPoint(floatValueForLength(style.perspectiveOriginX(), borderBox.width()),
1835                       floatValueForLength(style.perspectiveOriginY(), borderBox.height()));
1836 }
1837
1838 static inline bool isContainerForPositioned(RenderLayer& layer, PositionType position)
1839 {
1840     switch (position) {
1841     case PositionType::Fixed:
1842         return layer.renderer().canContainFixedPositionObjects();
1843
1844     case PositionType::Absolute:
1845         return layer.renderer().canContainAbsolutelyPositionedObjects();
1846     
1847     default:
1848         ASSERT_NOT_REACHED();
1849         return false;
1850     }
1851 }
1852
1853 bool RenderLayer::ancestorLayerIsInContainingBlockChain(const RenderLayer& ancestor, const RenderLayer* checkLimit) const
1854 {
1855     if (&ancestor == this)
1856         return true;
1857
1858     for (const auto* currentBlock = renderer().containingBlock(); currentBlock && !is<RenderView>(*currentBlock); currentBlock = currentBlock->containingBlock()) {
1859         auto* currLayer = currentBlock->layer();
1860         if (currLayer == &ancestor)
1861             return true;
1862         
1863         if (currLayer && currLayer == checkLimit)
1864             return false;
1865     }
1866     
1867     return false;
1868 }
1869
1870 RenderLayer* RenderLayer::enclosingAncestorForPosition(PositionType position) const
1871 {
1872     RenderLayer* curr = parent();
1873     while (curr && !isContainerForPositioned(*curr, position))
1874         curr = curr->parent();
1875
1876     return curr;
1877 }
1878
1879 static RenderLayer* enclosingFrameRenderLayer(const RenderLayer& layer)
1880 {
1881     auto* ownerElement = layer.renderer().document().ownerElement();
1882     if (!ownerElement)
1883         return nullptr;
1884
1885     auto* ownerRenderer = ownerElement->renderer();
1886     if (!ownerRenderer)
1887         return nullptr;
1888
1889     return ownerRenderer->enclosingLayer();
1890 }
1891
1892 static RenderLayer* parentLayerCrossFrame(const RenderLayer& layer)
1893 {
1894     if (auto* parent = layer.parent())
1895         return parent;
1896
1897     return enclosingFrameRenderLayer(layer);
1898 }
1899
1900 RenderLayer* RenderLayer::enclosingScrollableLayer() const
1901 {
1902     for (RenderLayer* nextLayer = parentLayerCrossFrame(*this); nextLayer; nextLayer = parentLayerCrossFrame(*nextLayer)) {
1903         if (is<RenderBox>(nextLayer->renderer()) && downcast<RenderBox>(nextLayer->renderer()).canBeScrolledAndHasScrollableArea())
1904             return nextLayer;
1905     }
1906
1907     return nullptr;
1908 }
1909
1910 IntRect RenderLayer::scrollableAreaBoundingBox(bool* isInsideFixed) const
1911 {
1912     return renderer().absoluteBoundingBoxRect(/* useTransforms */ true, isInsideFixed);
1913 }
1914
1915 bool RenderLayer::isRubberBandInProgress() const
1916 {
1917 #if ENABLE(RUBBER_BANDING)
1918     if (!scrollsOverflow())
1919         return false;
1920
1921     if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
1922         return scrollAnimator->isRubberBandInProgress();
1923 #endif
1924
1925     return false;
1926 }
1927
1928 bool RenderLayer::forceUpdateScrollbarsOnMainThreadForPerformanceTesting() const
1929 {
1930     return renderer().settings().forceUpdateScrollbarsOnMainThreadForPerformanceTesting();
1931 }
1932
1933 RenderLayer* RenderLayer::enclosingTransformedAncestor() const
1934 {
1935     RenderLayer* curr = parent();
1936     while (curr && !curr->isRenderViewLayer() && !curr->transform())
1937         curr = curr->parent();
1938
1939     return curr;
1940 }
1941
1942 inline bool RenderLayer::shouldRepaintAfterLayout() const
1943 {
1944     if (m_repaintStatus == NeedsNormalRepaint)
1945         return true;
1946
1947     // Composited layers that were moved during a positioned movement only
1948     // layout, don't need to be repainted. They just need to be recomposited.
1949     ASSERT(m_repaintStatus == NeedsFullRepaintForPositionedMovementLayout);
1950     return !isComposited() || backing()->paintsIntoCompositedAncestor();
1951 }
1952
1953 void RenderLayer::setBackingProviderLayer(RenderLayer* backingProvider)
1954 {
1955     if (backingProvider == m_backingProviderLayer)
1956         return;
1957
1958     if (!renderer().renderTreeBeingDestroyed())
1959         clearClipRectsIncludingDescendants();
1960
1961     m_backingProviderLayer = makeWeakPtr(backingProvider);
1962 }
1963
1964 void RenderLayer::disconnectFromBackingProviderLayer()
1965 {
1966     if (!m_backingProviderLayer)
1967         return;
1968     
1969     ASSERT(m_backingProviderLayer->isComposited());
1970     if (m_backingProviderLayer->isComposited())
1971         m_backingProviderLayer->backing()->removeBackingSharingLayer(*this);
1972 }
1973
1974 bool compositedWithOwnBackingStore(const RenderLayer& layer)
1975 {
1976     return layer.isComposited() && !layer.backing()->paintsIntoCompositedAncestor();
1977 }
1978
1979 RenderLayer* RenderLayer::enclosingCompositingLayer(IncludeSelfOrNot includeSelf) const
1980 {
1981     if (includeSelf == IncludeSelf && isComposited())
1982         return const_cast<RenderLayer*>(this);
1983
1984     for (const RenderLayer* curr = paintOrderParent(); curr; curr = curr->paintOrderParent()) {
1985         if (curr->isComposited())
1986             return const_cast<RenderLayer*>(curr);
1987     }
1988          
1989     return nullptr;
1990 }
1991
1992 RenderLayer* RenderLayer::enclosingCompositingLayerForRepaint(IncludeSelfOrNot includeSelf) const
1993 {
1994     auto repaintTargetForLayer = [](const RenderLayer& layer) -> RenderLayer* {
1995         if (compositedWithOwnBackingStore(layer))
1996             return const_cast<RenderLayer*>(&layer);
1997         
1998         if (layer.paintsIntoProvidedBacking())
1999             return layer.backingProviderLayer();
2000         
2001         return nullptr;
2002     };
2003
2004     RenderLayer* repaintTarget = nullptr;
2005     if (includeSelf == IncludeSelf && (repaintTarget = repaintTargetForLayer(*this)))
2006         return repaintTarget;
2007
2008     for (const RenderLayer* curr = paintOrderParent(); curr; curr = curr->paintOrderParent()) {
2009         if ((repaintTarget = repaintTargetForLayer(*curr)))
2010             return repaintTarget;
2011     }
2012          
2013     return nullptr;
2014 }
2015
2016 RenderLayer* RenderLayer::enclosingFilterLayer(IncludeSelfOrNot includeSelf) const
2017 {
2018     const RenderLayer* curr = (includeSelf == IncludeSelf) ? this : parent();
2019     for (; curr; curr = curr->parent()) {
2020         if (curr->requiresFullLayerImageForFilters())
2021             return const_cast<RenderLayer*>(curr);
2022     }
2023     
2024     return nullptr;
2025 }
2026
2027 RenderLayer* RenderLayer::enclosingFilterRepaintLayer() const
2028 {
2029     for (const RenderLayer* curr = this; curr; curr = curr->parent()) {
2030         if ((curr != this && curr->requiresFullLayerImageForFilters()) || compositedWithOwnBackingStore(*curr) || curr->isRenderViewLayer())
2031             return const_cast<RenderLayer*>(curr);
2032     }
2033     return nullptr;
2034 }
2035
2036 // FIXME: This neeeds a better name.
2037 void RenderLayer::setFilterBackendNeedsRepaintingInRect(const LayoutRect& rect)
2038 {
2039     ASSERT(requiresFullLayerImageForFilters());
2040     ASSERT(m_filters);
2041
2042     if (rect.isEmpty())
2043         return;
2044     
2045     LayoutRect rectForRepaint = rect;
2046     rectForRepaint += filterOutsets();
2047
2048     m_filters->expandDirtySourceRect(rectForRepaint);
2049     
2050     RenderLayer* parentLayer = enclosingFilterRepaintLayer();
2051     ASSERT(parentLayer);
2052     FloatQuad repaintQuad(rectForRepaint);
2053     LayoutRect parentLayerRect = renderer().localToContainerQuad(repaintQuad, &parentLayer->renderer()).enclosingBoundingBox();
2054
2055     if (parentLayer->isComposited()) {
2056         if (!parentLayer->backing()->paintsIntoWindow()) {
2057             parentLayer->setBackingNeedsRepaintInRect(parentLayerRect);
2058             return;
2059         }
2060         // If the painting goes to window, redirect the painting to the parent RenderView.
2061         parentLayer = renderer().view().layer();
2062         parentLayerRect = renderer().localToContainerQuad(repaintQuad, &parentLayer->renderer()).enclosingBoundingBox();
2063     }
2064
2065     if (parentLayer->paintsWithFilters()) {
2066         parentLayer->setFilterBackendNeedsRepaintingInRect(parentLayerRect);
2067         return;        
2068     }
2069     
2070     if (parentLayer->isRenderViewLayer()) {
2071         downcast<RenderView>(parentLayer->renderer()).repaintViewRectangle(parentLayerRect);
2072         return;
2073     }
2074     
2075     ASSERT_NOT_REACHED();
2076 }
2077
2078 bool RenderLayer::hasAncestorWithFilterOutsets() const
2079 {
2080     for (const RenderLayer* curr = this; curr; curr = curr->parent()) {
2081         if (curr->hasFilterOutsets())
2082             return true;
2083     }
2084     return false;
2085 }
2086
2087 RenderLayer* RenderLayer::clippingRootForPainting() const
2088 {
2089     if (isComposited())
2090         return const_cast<RenderLayer*>(this);
2091
2092     if (paintsIntoProvidedBacking())
2093         return backingProviderLayer();
2094
2095     const RenderLayer* current = this;
2096     while (current) {
2097         if (current->isRenderViewLayer())
2098             return const_cast<RenderLayer*>(current);
2099
2100         current = current->paintOrderParent();
2101         ASSERT(current);
2102         if (current->transform() || compositedWithOwnBackingStore(*current))
2103             return const_cast<RenderLayer*>(current);
2104
2105         if (current->paintsIntoProvidedBacking())
2106             return current->backingProviderLayer();
2107     }
2108
2109     ASSERT_NOT_REACHED();
2110     return nullptr;
2111 }
2112
2113 LayoutPoint RenderLayer::absoluteToContents(const LayoutPoint& absolutePoint) const
2114 {
2115     // We don't use convertToLayerCoords because it doesn't know about transforms
2116     return LayoutPoint(renderer().absoluteToLocal(absolutePoint, UseTransforms));
2117 }
2118
2119 bool RenderLayer::cannotBlitToWindow() const
2120 {
2121     if (isTransparent() || hasReflection() || hasTransform())
2122         return true;
2123     if (!parent())
2124         return false;
2125     return parent()->cannotBlitToWindow();
2126 }
2127
2128 RenderLayer* RenderLayer::transparentPaintingAncestor()
2129 {
2130     if (isComposited())
2131         return nullptr;
2132
2133     for (RenderLayer* curr = parent(); curr; curr = curr->parent()) {
2134         if (curr->isComposited())
2135             return nullptr;
2136         if (curr->isTransparent())
2137             return curr;
2138     }
2139     return nullptr;
2140 }
2141
2142 enum TransparencyClipBoxBehavior {
2143     PaintingTransparencyClipBox,
2144     HitTestingTransparencyClipBox
2145 };
2146
2147 enum TransparencyClipBoxMode {
2148     DescendantsOfTransparencyClipBox,
2149     RootOfTransparencyClipBox
2150 };
2151
2152 static LayoutRect transparencyClipBox(const RenderLayer&, const RenderLayer* rootLayer, TransparencyClipBoxBehavior, TransparencyClipBoxMode, OptionSet<PaintBehavior> = { });
2153
2154 static void expandClipRectForDescendantsAndReflection(LayoutRect& clipRect, const RenderLayer& layer, const RenderLayer* rootLayer,
2155     TransparencyClipBoxBehavior transparencyBehavior, OptionSet<PaintBehavior> paintBehavior)
2156 {
2157     // If we have a mask, then the clip is limited to the border box area (and there is
2158     // no need to examine child layers).
2159     if (!layer.renderer().hasMask()) {
2160         // Note: we don't have to walk z-order lists since transparent elements always establish
2161         // a stacking container. This means we can just walk the layer tree directly.
2162         for (RenderLayer* curr = layer.firstChild(); curr; curr = curr->nextSibling()) {
2163             if (!layer.isReflectionLayer(*curr))
2164                 clipRect.unite(transparencyClipBox(*curr, rootLayer, transparencyBehavior, DescendantsOfTransparencyClipBox, paintBehavior));
2165         }
2166     }
2167
2168     // If we have a reflection, then we need to account for that when we push the clip.  Reflect our entire
2169     // current transparencyClipBox to catch all child layers.
2170     // FIXME: Accelerated compositing will eventually want to do something smart here to avoid incorporating this
2171     // size into the parent layer.
2172     if (layer.renderer().hasReflection()) {
2173         LayoutSize delta = layer.offsetFromAncestor(rootLayer);
2174         clipRect.move(-delta);
2175         clipRect.unite(layer.renderBox()->reflectedRect(clipRect));
2176         clipRect.move(delta);
2177     }
2178 }
2179
2180 static LayoutRect transparencyClipBox(const RenderLayer& layer, const RenderLayer* rootLayer, TransparencyClipBoxBehavior transparencyBehavior,
2181     TransparencyClipBoxMode transparencyMode, OptionSet<PaintBehavior> paintBehavior)
2182 {
2183     // FIXME: Although this function completely ignores CSS-imposed clipping, we did already intersect with the
2184     // paintDirtyRect, and that should cut down on the amount we have to paint.  Still it
2185     // would be better to respect clips.
2186     
2187     if (rootLayer != &layer && ((transparencyBehavior == PaintingTransparencyClipBox && layer.paintsWithTransform(paintBehavior))
2188         || (transparencyBehavior == HitTestingTransparencyClipBox && layer.hasTransform()))) {
2189         // The best we can do here is to use enclosed bounding boxes to establish a "fuzzy" enough clip to encompass
2190         // the transformed layer and all of its children.
2191         RenderLayer::PaginationInclusionMode mode = transparencyBehavior == HitTestingTransparencyClipBox ? RenderLayer::IncludeCompositedPaginatedLayers : RenderLayer::ExcludeCompositedPaginatedLayers;
2192         const RenderLayer* paginationLayer = transparencyMode == DescendantsOfTransparencyClipBox ? layer.enclosingPaginationLayer(mode) : nullptr;
2193         const RenderLayer* rootLayerForTransform = paginationLayer ? paginationLayer : rootLayer;
2194         LayoutSize delta = layer.offsetFromAncestor(rootLayerForTransform);
2195
2196         TransformationMatrix transform;
2197         transform.translate(delta.width(), delta.height());
2198         transform.multiply(*layer.transform());
2199
2200         // We don't use fragment boxes when collecting a transformed layer's bounding box, since it always
2201         // paints unfragmented.
2202         LayoutRect clipRect = layer.boundingBox(&layer);
2203         expandClipRectForDescendantsAndReflection(clipRect, layer, &layer, transparencyBehavior, paintBehavior);
2204         clipRect += layer.filterOutsets();
2205         LayoutRect result = transform.mapRect(clipRect);
2206         if (!paginationLayer)
2207             return result;
2208         
2209         // We have to break up the transformed extent across our columns.
2210         // Split our box up into the actual fragment boxes that render in the columns/pages and unite those together to
2211         // get our true bounding box.
2212         auto& enclosingFragmentedFlow = downcast<RenderFragmentedFlow>(paginationLayer->renderer());
2213         result = enclosingFragmentedFlow.fragmentsBoundingBox(result);
2214         result.move(paginationLayer->offsetFromAncestor(rootLayer));
2215         return result;
2216     }
2217     
2218     LayoutRect clipRect = layer.boundingBox(rootLayer, layer.offsetFromAncestor(rootLayer), transparencyBehavior == HitTestingTransparencyClipBox ? RenderLayer::UseFragmentBoxesIncludingCompositing : RenderLayer::UseFragmentBoxesExcludingCompositing);
2219     expandClipRectForDescendantsAndReflection(clipRect, layer, rootLayer, transparencyBehavior, paintBehavior);
2220     clipRect += layer.filterOutsets();
2221
2222     return clipRect;
2223 }
2224
2225 static LayoutRect paintingExtent(const RenderLayer& currentLayer, const RenderLayer* rootLayer, const LayoutRect& paintDirtyRect, OptionSet<PaintBehavior> paintBehavior)
2226 {
2227     return intersection(transparencyClipBox(currentLayer, rootLayer, PaintingTransparencyClipBox, RootOfTransparencyClipBox, paintBehavior), paintDirtyRect);
2228 }
2229
2230 void RenderLayer::beginTransparencyLayers(GraphicsContext& context, const LayerPaintingInfo& paintingInfo, const LayoutRect& dirtyRect)
2231 {
2232     if (context.paintingDisabled() || (paintsWithTransparency(paintingInfo.paintBehavior) && m_usedTransparency))
2233         return;
2234
2235     RenderLayer* ancestor = transparentPaintingAncestor();
2236     if (ancestor)
2237         ancestor->beginTransparencyLayers(context, paintingInfo, dirtyRect);
2238     
2239     if (paintsWithTransparency(paintingInfo.paintBehavior)) {
2240         ASSERT(isCSSStackingContext());
2241         m_usedTransparency = true;
2242         context.save();
2243         LayoutRect adjustedClipRect = paintingExtent(*this, paintingInfo.rootLayer, dirtyRect, paintingInfo.paintBehavior);
2244         adjustedClipRect.move(paintingInfo.subpixelOffset);
2245         FloatRect pixelSnappedClipRect = snapRectToDevicePixels(adjustedClipRect, renderer().document().deviceScaleFactor());
2246         context.clip(pixelSnappedClipRect);
2247
2248 #if ENABLE(CSS_COMPOSITING)
2249         bool usesCompositeOperation = hasBlendMode() && !(renderer().isSVGRoot() && parent() && parent()->isRenderViewLayer());
2250         if (usesCompositeOperation)
2251             context.setCompositeOperation(context.compositeOperation(), blendMode());
2252 #endif
2253
2254         context.beginTransparencyLayer(renderer().opacity());
2255
2256 #if ENABLE(CSS_COMPOSITING)
2257         if (usesCompositeOperation)
2258             context.setCompositeOperation(context.compositeOperation(), BlendMode::Normal);
2259 #endif
2260
2261 #ifdef REVEAL_TRANSPARENCY_LAYERS
2262         context.setFillColor(Color(0.0f, 0.0f, 0.5f, 0.2f));
2263         context.fillRect(pixelSnappedClipRect);
2264 #endif
2265     }
2266 }
2267
2268 #if PLATFORM(IOS_FAMILY)
2269 void RenderLayer::willBeDestroyed()
2270 {
2271     if (RenderLayerBacking* layerBacking = backing())
2272         layerBacking->layerWillBeDestroyed();
2273 }
2274 #endif
2275
2276 bool RenderLayer::isDescendantOf(const RenderLayer& layer) const
2277 {
2278     for (auto* ancestor = this; ancestor; ancestor = ancestor->parent()) {
2279         if (&layer == ancestor)
2280             return true;
2281     }
2282     return false;
2283 }
2284
2285 static RenderLayer* findCommonAncestor(const RenderLayer& firstLayer, const RenderLayer& secondLayer)
2286 {
2287     if (&firstLayer == &secondLayer)
2288         return const_cast<RenderLayer*>(&firstLayer);
2289
2290     HashSet<const RenderLayer*> ancestorChain;
2291     for (auto* currLayer = &firstLayer; currLayer; currLayer = currLayer->parent())
2292         ancestorChain.add(currLayer);
2293
2294     for (auto* currLayer = &secondLayer; currLayer; currLayer = currLayer->parent()) {
2295         if (ancestorChain.contains(currLayer))
2296             return const_cast<RenderLayer*>(currLayer);
2297     }
2298     return nullptr;
2299 }
2300
2301 RenderLayer* RenderLayer::commonAncestorWithLayer(const RenderLayer& layer) const
2302 {
2303     return findCommonAncestor(*this, layer);
2304 }
2305
2306 void RenderLayer::convertToPixelSnappedLayerCoords(const RenderLayer* ancestorLayer, IntPoint& roundedLocation, ColumnOffsetAdjustment adjustForColumns) const
2307 {
2308     LayoutPoint location = convertToLayerCoords(ancestorLayer, roundedLocation, adjustForColumns);
2309     roundedLocation = roundedIntPoint(location);
2310 }
2311
2312 // Returns the layer reached on the walk up towards the ancestor.
2313 static inline const RenderLayer* accumulateOffsetTowardsAncestor(const RenderLayer* layer, const RenderLayer* ancestorLayer, LayoutPoint& location, RenderLayer::ColumnOffsetAdjustment adjustForColumns)
2314 {
2315     ASSERT(ancestorLayer != layer);
2316
2317     const RenderLayerModelObject& renderer = layer->renderer();
2318     auto position = renderer.style().position();
2319
2320     // FIXME: Special casing RenderFragmentedFlow so much for fixed positioning here is not great.
2321     RenderFragmentedFlow* fixedFragmentedFlowContainer = position == PositionType::Fixed ? renderer.enclosingFragmentedFlow() : nullptr;
2322     if (fixedFragmentedFlowContainer && !fixedFragmentedFlowContainer->isOutOfFlowPositioned())
2323         fixedFragmentedFlowContainer = nullptr;
2324
2325     // FIXME: Positioning of out-of-flow(fixed, absolute) elements collected in a RenderFragmentedFlow
2326     // may need to be revisited in a future patch.
2327     // If the fixed renderer is inside a RenderFragmentedFlow, we should not compute location using localToAbsolute,
2328     // since localToAbsolute maps the coordinates from named flow to regions coordinates and regions can be
2329     // positioned in a completely different place in the viewport (RenderView).
2330     if (position == PositionType::Fixed && !fixedFragmentedFlowContainer && (!ancestorLayer || ancestorLayer == renderer.view().layer())) {
2331         // If the fixed layer's container is the root, just add in the offset of the view. We can obtain this by calling
2332         // localToAbsolute() on the RenderView.
2333         FloatPoint absPos = renderer.localToAbsolute(FloatPoint(), IsFixed);
2334         location += LayoutSize(absPos.x(), absPos.y());
2335         return ancestorLayer;
2336     }
2337
2338     // For the fixed positioned elements inside a render flow thread, we should also skip the code path below
2339     // Otherwise, for the case of ancestorLayer == rootLayer and fixed positioned element child of a transformed
2340     // element in render flow thread, we will hit the fixed positioned container before hitting the ancestor layer.
2341     if (position == PositionType::Fixed && !fixedFragmentedFlowContainer) {
2342         // For a fixed layers, we need to walk up to the root to see if there's a fixed position container
2343         // (e.g. a transformed layer). It's an error to call offsetFromAncestor() across a layer with a transform,
2344         // so we should always find the ancestor at or before we find the fixed position container.
2345         RenderLayer* fixedPositionContainerLayer = nullptr;
2346         bool foundAncestor = false;
2347         for (RenderLayer* currLayer = layer->parent(); currLayer; currLayer = currLayer->parent()) {
2348             if (currLayer == ancestorLayer)
2349                 foundAncestor = true;
2350
2351             if (isContainerForPositioned(*currLayer, PositionType::Fixed)) {
2352                 fixedPositionContainerLayer = currLayer;
2353                 ASSERT_UNUSED(foundAncestor, foundAncestor);
2354                 break;
2355             }
2356         }
2357         
2358         ASSERT(fixedPositionContainerLayer); // We should have hit the RenderView's layer at least.
2359
2360         if (fixedPositionContainerLayer != ancestorLayer) {
2361             LayoutSize fixedContainerCoords = layer->offsetFromAncestor(fixedPositionContainerLayer);
2362             LayoutSize ancestorCoords = ancestorLayer->offsetFromAncestor(fixedPositionContainerLayer);
2363             location += (fixedContainerCoords - ancestorCoords);
2364             return ancestorLayer;
2365         }
2366     }
2367
2368     if (position == PositionType::Fixed && fixedFragmentedFlowContainer) {
2369         ASSERT(ancestorLayer);
2370         if (ancestorLayer->isOutOfFlowRenderFragmentedFlow()) {
2371             location += toLayoutSize(layer->location());
2372             return ancestorLayer;
2373         }
2374
2375         if (ancestorLayer == renderer.view().layer()) {
2376             // Add location in flow thread coordinates.
2377             location += toLayoutSize(layer->location());
2378
2379             // Add flow thread offset in view coordinates since the view may be scrolled.
2380             FloatPoint absPos = renderer.view().localToAbsolute(FloatPoint(), IsFixed);
2381             location += LayoutSize(absPos.x(), absPos.y());
2382             return ancestorLayer;
2383         }
2384     }
2385
2386     RenderLayer* parentLayer;
2387     if (position == PositionType::Absolute || position == PositionType::Fixed) {
2388         // Do what enclosingAncestorForPosition() does, but check for ancestorLayer along the way.
2389         parentLayer = layer->parent();
2390         bool foundAncestorFirst = false;
2391         while (parentLayer) {
2392             // RenderFragmentedFlow is a positioned container, child of RenderView, positioned at (0,0).
2393             // This implies that, for out-of-flow positioned elements inside a RenderFragmentedFlow,
2394             // we are bailing out before reaching root layer.
2395             if (isContainerForPositioned(*parentLayer, position))
2396                 break;
2397
2398             if (parentLayer == ancestorLayer) {
2399                 foundAncestorFirst = true;
2400                 break;
2401             }
2402
2403             parentLayer = parentLayer->parent();
2404         }
2405
2406         // We should not reach RenderView layer past the RenderFragmentedFlow layer for any
2407         // children of the RenderFragmentedFlow.
2408         if (renderer.enclosingFragmentedFlow() && !layer->isOutOfFlowRenderFragmentedFlow())
2409             ASSERT(parentLayer != renderer.view().layer());
2410
2411         if (foundAncestorFirst) {
2412             // Found ancestorLayer before the abs. positioned container, so compute offset of both relative
2413             // to enclosingAncestorForPosition and subtract.
2414             RenderLayer* positionedAncestor = parentLayer->enclosingAncestorForPosition(position);
2415             LayoutSize thisCoords = layer->offsetFromAncestor(positionedAncestor);
2416             LayoutSize ancestorCoords = ancestorLayer->offsetFromAncestor(positionedAncestor);
2417             location += (thisCoords - ancestorCoords);
2418             return ancestorLayer;
2419         }
2420     } else
2421         parentLayer = layer->parent();
2422     
2423     if (!parentLayer)
2424         return nullptr;
2425
2426     location += toLayoutSize(layer->location());
2427
2428     if (adjustForColumns == RenderLayer::AdjustForColumns) {
2429         if (RenderLayer* parentLayer = layer->parent()) {
2430             if (is<RenderMultiColumnFlow>(parentLayer->renderer())) {
2431                 RenderFragmentContainer* fragment = downcast<RenderMultiColumnFlow>(parentLayer->renderer()).physicalTranslationFromFlowToFragment(location);
2432                 if (fragment)
2433                     location.moveBy(fragment->topLeftLocation() + -parentLayer->renderBox()->topLeftLocation());
2434             }
2435         }
2436     }
2437
2438     return parentLayer;
2439 }
2440
2441 LayoutPoint RenderLayer::convertToLayerCoords(const RenderLayer* ancestorLayer, const LayoutPoint& location, ColumnOffsetAdjustment adjustForColumns) const
2442 {
2443     if (ancestorLayer == this)
2444         return location;
2445
2446     const RenderLayer* currLayer = this;
2447     LayoutPoint locationInLayerCoords = location;
2448     while (currLayer && currLayer != ancestorLayer)
2449         currLayer = accumulateOffsetTowardsAncestor(currLayer, ancestorLayer, locationInLayerCoords, adjustForColumns);
2450     return locationInLayerCoords;
2451 }
2452
2453 LayoutSize RenderLayer::offsetFromAncestor(const RenderLayer* ancestorLayer, ColumnOffsetAdjustment adjustForColumns) const
2454 {
2455     return toLayoutSize(convertToLayerCoords(ancestorLayer, LayoutPoint(), adjustForColumns));
2456 }
2457
2458 bool RenderLayer::canUseCompositedScrolling() const
2459 {
2460     bool isVisible = renderer().style().visibility() == Visibility::Visible;
2461     if (renderer().settings().asyncOverflowScrollingEnabled())
2462         return isVisible && scrollsOverflow();
2463
2464 #if PLATFORM(IOS_FAMILY) && ENABLE(OVERFLOW_SCROLLING_TOUCH)
2465     return isVisible && scrollsOverflow() && (renderer().style().useTouchOverflowScrolling() || renderer().settings().alwaysUseAcceleratedOverflowScroll());
2466 #else
2467     return false;
2468 #endif
2469 }
2470
2471 #if ENABLE(IOS_TOUCH_EVENTS)
2472 bool RenderLayer::handleTouchEvent(const PlatformTouchEvent& touchEvent)
2473 {
2474     // If we have accelerated scrolling, let the scrolling be handled outside of WebKit.
2475     if (hasCompositedScrollableOverflow())
2476         return false;
2477
2478     return ScrollableArea::handleTouchEvent(touchEvent);
2479 }
2480
2481 void RenderLayer::registerAsTouchEventListenerForScrolling()
2482 {
2483     if (!renderer().element() || m_registeredAsTouchEventListenerForScrolling)
2484         return;
2485     
2486     renderer().document().addTouchEventHandler(*renderer().element());
2487     m_registeredAsTouchEventListenerForScrolling = true;
2488 }
2489
2490 void RenderLayer::unregisterAsTouchEventListenerForScrolling()
2491 {
2492     if (!renderer().element() || !m_registeredAsTouchEventListenerForScrolling)
2493         return;
2494
2495     renderer().document().removeTouchEventHandler(*renderer().element());
2496     m_registeredAsTouchEventListenerForScrolling = false;
2497 }
2498 #endif // ENABLE(IOS_TOUCH_EVENTS)
2499
2500 // FIXME: this is only valid after we've made layers.
2501 bool RenderLayer::usesCompositedScrolling() const
2502 {
2503     return isComposited() && backing()->hasScrollingLayer();
2504 }
2505
2506 // FIXME: this is only valid after we've made layers.
2507 bool RenderLayer::usesAsyncScrolling() const
2508 {
2509     return compositor().useCoordinatedScrollingForLayer(*this);
2510 }
2511
2512 static inline int adjustedScrollDelta(int beginningDelta)
2513 {
2514     // This implemention matches Firefox's.
2515     // http://mxr.mozilla.org/firefox/source/toolkit/content/widgets/browser.xml#856.
2516     const int speedReducer = 12;
2517
2518     int adjustedDelta = beginningDelta / speedReducer;
2519     if (adjustedDelta > 1)
2520         adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(adjustedDelta))) - 1;
2521     else if (adjustedDelta < -1)
2522         adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(-adjustedDelta))) + 1;
2523
2524     return adjustedDelta;
2525 }
2526
2527 static inline IntSize adjustedScrollDelta(const IntSize& delta)
2528 {
2529     return IntSize(adjustedScrollDelta(delta.width()), adjustedScrollDelta(delta.height()));
2530 }
2531
2532 void RenderLayer::panScrollFromPoint(const IntPoint& sourcePoint)
2533 {
2534     IntPoint lastKnownMousePosition = renderer().frame().eventHandler().lastKnownMousePosition();
2535     
2536     // We need to check if the last known mouse position is out of the window. When the mouse is out of the window, the position is incoherent
2537     static IntPoint previousMousePosition;
2538     if (lastKnownMousePosition.x() < 0 || lastKnownMousePosition.y() < 0)
2539         lastKnownMousePosition = previousMousePosition;
2540     else
2541         previousMousePosition = lastKnownMousePosition;
2542
2543     IntSize delta = lastKnownMousePosition - sourcePoint;
2544
2545     if (abs(delta.width()) <= ScrollView::noPanScrollRadius) // at the center we let the space for the icon
2546         delta.setWidth(0);
2547     if (abs(delta.height()) <= ScrollView::noPanScrollRadius)
2548         delta.setHeight(0);
2549
2550     scrollByRecursively(adjustedScrollDelta(delta));
2551 }
2552
2553 // FIXME: unify with the scrollRectToVisible() code below.
2554 void RenderLayer::scrollByRecursively(const IntSize& delta, ScrollableArea** scrolledArea)
2555 {
2556     if (delta.isZero())
2557         return;
2558
2559     bool restrictedByLineClamp = false;
2560     if (renderer().parent())
2561         restrictedByLineClamp = !renderer().parent()->style().lineClamp().isNone();
2562
2563     if (renderer().hasOverflowClip() && !restrictedByLineClamp) {
2564         ScrollOffset newScrollOffset = scrollOffset() + delta;
2565         scrollToOffset(newScrollOffset);
2566         if (scrolledArea)
2567             *scrolledArea = this;
2568
2569         // If this layer can't do the scroll we ask the next layer up that can scroll to try
2570         IntSize remainingScrollOffset = newScrollOffset - scrollOffset();
2571         if (!remainingScrollOffset.isZero() && renderer().parent()) {
2572             if (RenderLayer* scrollableLayer = enclosingScrollableLayer())
2573                 scrollableLayer->scrollByRecursively(remainingScrollOffset, scrolledArea);
2574
2575             renderer().frame().eventHandler().updateAutoscrollRenderer();
2576         }
2577     } else {
2578         // If we are here, we were called on a renderer that can be programmatically scrolled, but doesn't
2579         // have an overflow clip. Which means that it is a document node that can be scrolled.
2580         renderer().view().frameView().scrollBy(delta);
2581         if (scrolledArea)
2582             *scrolledArea = &renderer().view().frameView();
2583
2584         // FIXME: If we didn't scroll the whole way, do we want to try looking at the frames ownerElement? 
2585         // https://bugs.webkit.org/show_bug.cgi?id=28237
2586     }
2587 }
2588
2589 void RenderLayer::setPostLayoutScrollPosition(Optional<ScrollPosition> position)
2590 {
2591     m_postLayoutScrollPosition = position;
2592 }
2593
2594 void RenderLayer::applyPostLayoutScrollPositionIfNeeded()
2595 {
2596     if (!m_postLayoutScrollPosition)
2597         return;
2598
2599     scrollToOffset(scrollOffsetFromPosition(m_postLayoutScrollPosition.value()));
2600     m_postLayoutScrollPosition = WTF::nullopt;
2601 }
2602
2603 void RenderLayer::scrollToXPosition(int x, ScrollType scrollType, ScrollClamping clamping, bool animated)
2604 {
2605     ScrollPosition position(x, m_scrollPosition.y());
2606     scrollToPosition(position, scrollType, clamping, animated);
2607 }
2608
2609 void RenderLayer::scrollToYPosition(int y, ScrollType scrollType, ScrollClamping clamping, bool animated)
2610 {
2611     ScrollPosition position(m_scrollPosition.x(), y);
2612     scrollToPosition(position, scrollType, clamping, animated);
2613 }
2614
2615 void RenderLayer::scrollToPosition(const ScrollPosition& position, ScrollType scrollType, ScrollClamping clamping, bool animated)
2616 {
2617     if (animated)
2618         scrollToOffsetWithAnimation(scrollOffsetFromPosition(position), scrollType, clamping);
2619     else
2620         scrollToOffset(scrollOffsetFromPosition(position), scrollType, clamping);
2621 }
2622
2623 ScrollOffset RenderLayer::clampScrollOffset(const ScrollOffset& scrollOffset) const
2624 {
2625     return scrollOffset.constrainedBetween(IntPoint(), maximumScrollOffset());
2626 }
2627
2628 bool RenderLayer::requestScrollPositionUpdate(const ScrollPosition& position, ScrollType scrollType, ScrollClamping clamping)
2629 {
2630 #if ENABLE(ASYNC_SCROLLING)
2631     if (ScrollingCoordinator* scrollingCoordinator = page().scrollingCoordinator())
2632         return scrollingCoordinator->requestScrollPositionUpdate(*this, position, scrollType, clamping);
2633 #endif
2634     return false;
2635 }
2636
2637 void RenderLayer::scrollToOffset(const ScrollOffset& scrollOffset, ScrollType scrollType, ScrollClamping clamping)
2638 {
2639     if (currentScrollBehaviorStatus() == ScrollBehaviorStatus::InNonNativeAnimation)
2640         scrollAnimator().cancelAnimations();
2641
2642     ScrollOffset clampedScrollOffset = clamping == ScrollClamping::Clamped ? clampScrollOffset(scrollOffset) : scrollOffset;
2643     if (clampedScrollOffset == this->scrollOffset())
2644         return;
2645
2646     auto previousScrollType = currentScrollType();
2647     setCurrentScrollType(scrollType);
2648
2649     if (!requestScrollPositionUpdate(scrollPositionFromOffset(clampedScrollOffset), scrollType, clamping))
2650         scrollToOffsetWithoutAnimation(clampedScrollOffset, clamping);
2651     setScrollBehaviorStatus(ScrollBehaviorStatus::NotInAnimation);
2652
2653     setCurrentScrollType(previousScrollType);
2654 }
2655
2656 void RenderLayer::scrollToOffsetWithAnimation(const ScrollOffset& offset, ScrollType scrollType, ScrollClamping clamping)
2657 {
2658     auto previousScrollType = currentScrollType();
2659     setCurrentScrollType(scrollType);
2660
2661     ScrollOffset newScrollOffset = clamping == ScrollClamping::Clamped ? clampScrollOffset(offset) : offset;
2662     if (currentScrollBehaviorStatus() == ScrollBehaviorStatus::InNonNativeAnimation)
2663         scrollAnimator().cancelAnimations();
2664     if (newScrollOffset != this->scrollOffset())
2665         ScrollableArea::scrollToOffsetWithAnimation(newScrollOffset);
2666
2667     setCurrentScrollType(previousScrollType);
2668 }
2669
2670 void RenderLayer::scrollTo(const ScrollPosition& position)
2671 {
2672     RenderBox* box = renderBox();
2673     if (!box)
2674         return;
2675
2676     LOG_WITH_STREAM(Scrolling, stream << "RenderLayer::scrollTo " << position << " from " << m_scrollPosition << " (is user scroll " << (currentScrollType() == ScrollType::User) << ")");
2677
2678     ScrollPosition newPosition = position;
2679     if (!box->isHTMLMarquee()) {
2680         // Ensure that the dimensions will be computed if they need to be (for overflow:hidden blocks).
2681         if (m_scrollDimensionsDirty)
2682             computeScrollDimensions();
2683 #if PLATFORM(IOS_FAMILY)
2684         if (adjustForIOSCaretWhenScrolling()) {
2685             // FIXME: It's not clear what this code is trying to do. Behavior seems reasonable with it removed.
2686             int maxOffset = scrollWidth() - roundToInt(box->clientWidth());
2687             ScrollOffset newOffset = scrollOffsetFromPosition(newPosition);
2688             int scrollXOffset = newOffset.x();
2689             if (scrollXOffset > maxOffset - caretWidth) {
2690                 scrollXOffset += caretWidth;
2691                 if (scrollXOffset <= caretWidth)
2692                     scrollXOffset = 0;
2693             } else if (scrollXOffset < m_scrollPosition.x() - caretWidth)
2694                 scrollXOffset -= caretWidth;
2695
2696             newOffset.setX(scrollXOffset);
2697             newPosition = scrollPositionFromOffset(newOffset);
2698         }
2699 #endif
2700     }
2701     
2702     if (m_scrollPosition == newPosition && currentScrollBehaviorStatus() == ScrollBehaviorStatus::NotInAnimation) {
2703         // FIXME: Nothing guarantees we get a scrollTo() with an unchanged position at the end of a user gesture.
2704         // The ScrollingCoordinator probably needs to message the main thread when a gesture ends.
2705         if (requiresScrollPositionReconciliation()) {
2706             setNeedsCompositingGeometryUpdate();
2707             updateCompositingLayersAfterScroll();
2708         }
2709         return;
2710     }
2711
2712     m_scrollPosition = newPosition;
2713
2714     RenderView& view = renderer().view();
2715
2716     // Update the positions of our child layers (if needed as only fixed layers should be impacted by a scroll).
2717     // We don't update compositing layers, because we need to do a deep update from the compositing ancestor.
2718     if (!view.frameView().layoutContext().isInRenderTreeLayout()) {
2719         // If we're in the middle of layout, we'll just update layers once layout has finished.
2720         updateLayerPositionsAfterOverflowScroll();
2721
2722         view.frameView().scheduleUpdateWidgetPositions();
2723
2724         if (!m_updatingMarqueePosition) {
2725             // Avoid updating compositing layers if, higher on the stack, we're already updating layer
2726             // positions. Updating layer positions requires a full walk of up-to-date RenderLayers, and
2727             // in this case we're still updating their positions; we'll update compositing layers later
2728             // when that completes.
2729             if (usesCompositedScrolling()) {
2730                 setNeedsCompositingGeometryUpdate();
2731
2732                 // Scroll position can affect the location of a composited descendant (which may be a sibling in z-order),
2733                 // so trigger a descendant walk from the paint-order parent.
2734                 if (auto* paintParent = paintOrderParent())
2735                     paintParent->setDescendantsNeedUpdateBackingAndHierarchyTraversal();
2736             }
2737
2738             updateCompositingLayersAfterScroll();
2739         }
2740
2741         // Update regions, scrolling may change the clip of a particular region.
2742         renderer().document().invalidateRenderingDependentRegions();
2743         DebugPageOverlays::didLayout(renderer().frame());
2744     }
2745
2746     Frame& frame = renderer().frame();
2747     RenderLayerModelObject* repaintContainer = renderer().containerForRepaint();
2748     // The caret rect needs to be invalidated after scrolling
2749     frame.selection().setCaretRectNeedsUpdate();
2750     
2751     LayoutRect rectForRepaint = renderer().hasRepaintLayoutRects() ? renderer().repaintLayoutRects().m_repaintRect : renderer().clippedOverflowRectForRepaint(repaintContainer);
2752
2753     FloatQuad quadForFakeMouseMoveEvent = FloatQuad(rectForRepaint);
2754     if (repaintContainer)
2755         quadForFakeMouseMoveEvent = repaintContainer->localToAbsoluteQuad(quadForFakeMouseMoveEvent);
2756     frame.eventHandler().dispatchFakeMouseMoveEventSoonInQuad(quadForFakeMouseMoveEvent);
2757
2758     bool requiresRepaint = true;
2759     if (usesCompositedScrolling()) {
2760         setNeedsCompositingGeometryUpdate();
2761         setDescendantsNeedUpdateBackingAndHierarchyTraversal();
2762         requiresRepaint = false;
2763     }
2764
2765     // Just schedule a full repaint of our object.
2766     if (requiresRepaint)
2767         renderer().repaintUsingContainer(repaintContainer, rectForRepaint);
2768
2769     // Schedule the scroll and scroll-related DOM events.
2770     if (Element* element = renderer().element())
2771         element->document().addPendingScrollEventTarget(*element);
2772
2773     if (scrollsOverflow())
2774         view.frameView().didChangeScrollOffset();
2775
2776     view.frameView().viewportContentsChanged();
2777     frame.editor().renderLayerDidScroll(*this);
2778 }
2779
2780 static inline bool frameElementAndViewPermitScroll(HTMLFrameElementBase* frameElementBase, FrameView& frameView)
2781 {
2782     // If scrollbars aren't explicitly forbidden, permit scrolling.
2783     if (frameElementBase && frameElementBase->scrollingMode() != ScrollbarAlwaysOff)
2784         return true;
2785
2786     // If scrollbars are forbidden, user initiated scrolls should obviously be ignored.
2787     if (frameView.wasScrolledByUser())
2788         return false;
2789
2790     // Forbid autoscrolls when scrollbars are off, but permits other programmatic scrolls,
2791     // like navigation to an anchor.
2792     return !frameView.frame().eventHandler().autoscrollInProgress();
2793 }
2794
2795 bool RenderLayer::allowsCurrentScroll() const
2796 {
2797     if (!renderer().hasOverflowClip())
2798         return false;
2799
2800     // Don't scroll to reveal an overflow layer that is restricted by the -webkit-line-clamp property.
2801     // FIXME: Is this still needed? It used to be relevant for Safari RSS.
2802     if (renderer().parent() && !renderer().parent()->style().lineClamp().isNone())
2803         return false;
2804
2805     RenderBox* box = renderBox();
2806     ASSERT(box); // Only boxes can have overflowClip set.
2807
2808     if (renderer().frame().eventHandler().autoscrollInProgress()) {
2809         // The "programmatically" here is misleading; this asks whether the box has scrollable overflow,
2810         // or is a special case like a form control.
2811         return box->canBeProgramaticallyScrolled();
2812     }
2813
2814     // Programmatic scrolls can scroll overflow:hidden.
2815     return box->hasHorizontalOverflow() || box->hasVerticalOverflow();
2816 }
2817
2818 void RenderLayer::scrollRectToVisible(const LayoutRect& absoluteRect, bool insideFixed, const ScrollRectToVisibleOptions& options)
2819 {
2820     LOG_WITH_STREAM(Scrolling, stream << "Layer " << this << " scrollRectToVisible " << absoluteRect);
2821
2822     RenderLayer* parentLayer = nullptr;
2823     LayoutRect newRect = absoluteRect;
2824
2825     // We may end up propagating a scroll event. It is important that we suspend events until 
2826     // the end of the function since they could delete the layer or the layer's renderer().
2827     FrameView& frameView = renderer().view().frameView();
2828
2829     if (renderer().parent())
2830         parentLayer = renderer().parent()->enclosingLayer();
2831
2832     if (allowsCurrentScroll()) {
2833         // Don't scroll to reveal an overflow layer that is restricted by the -webkit-line-clamp property.
2834         // This will prevent us from revealing text hidden by the slider in Safari RSS.
2835         RenderBox* box = renderBox();
2836         ASSERT(box);
2837         LayoutRect localExposeRect(box->absoluteToLocalQuad(FloatQuad(FloatRect(absoluteRect))).boundingBox());
2838         if (shouldPlaceBlockDirectionScrollbarOnLeft()) {
2839             // For direction: rtl; writing-mode: horizontal-tb box, the scroll bar is on the left side. The visible rect
2840             // starts from the right side of scroll bar. So the x of localExposeRect should start from the same position too.
2841             localExposeRect.moveBy(LayoutPoint(-verticalScrollbarWidth(), 0));
2842         }
2843         LayoutRect layerBounds(0_lu, 0_lu, box->clientWidth(), box->clientHeight());
2844         LayoutRect revealRect = getRectToExpose(layerBounds, localExposeRect, insideFixed, options.alignX, options.alignY);
2845
2846         ScrollOffset clampedScrollOffset = clampScrollOffset(scrollOffset() + toIntSize(roundedIntRect(revealRect).location()));
2847         if (clampedScrollOffset != scrollOffset() || currentScrollBehaviorStatus() != ScrollBehaviorStatus::NotInAnimation) {
2848             ScrollOffset oldScrollOffset = scrollOffset();
2849             bool animated = useSmoothScrolling(options.behavior, box->element());
2850             scrollToPosition(scrollPositionFromOffset(clampedScrollOffset), ScrollType::Programmatic, ScrollClamping::Clamped, animated);
2851             IntSize scrollOffsetDifference = clampedScrollOffset - oldScrollOffset;
2852             localExposeRect.move(-scrollOffsetDifference);
2853             newRect = LayoutRect(box->localToAbsoluteQuad(FloatQuad(FloatRect(localExposeRect)), UseTransforms).boundingBox());
2854         }
2855     } else if (!parentLayer && renderer().isRenderView()) {
2856         HTMLFrameOwnerElement* ownerElement = renderer().document().ownerElement();
2857
2858         if (ownerElement && ownerElement->renderer()) {
2859             HTMLFrameElementBase* frameElementBase = nullptr;
2860
2861             if (is<HTMLFrameElementBase>(*ownerElement))
2862                 frameElementBase = downcast<HTMLFrameElementBase>(ownerElement);
2863
2864             if (frameElementAndViewPermitScroll(frameElementBase, frameView)) {
2865                 // If this assertion fires we need to protect the ownerElement from being destroyed.
2866                 ScriptDisallowedScope::InMainThread scriptDisallowedScope;
2867
2868                 LayoutRect viewRect = frameView.visibleContentRect(LegacyIOSDocumentVisibleRect);
2869                 LayoutRect exposeRect = getRectToExpose(viewRect, absoluteRect, insideFixed, options.alignX, options.alignY);
2870
2871                 IntPoint scrollPosition(roundedIntPoint(exposeRect.location()));
2872                 // Adjust offsets if they're outside of the allowable range.
2873                 scrollPosition = scrollPosition.constrainedBetween(IntPoint(), IntPoint(frameView.contentsSize()));
2874                 // FIXME: Should we use contentDocument()->scrollingElement()?
2875                 // See https://bugs.webkit.org/show_bug.cgi?id=205059
2876                 bool animated = ownerElement->contentDocument() && useSmoothScrolling(options.behavior, ownerElement->contentDocument()->documentElement());
2877                 frameView.setScrollPosition(scrollPosition, ScrollClamping::Clamped, animated);
2878
2879                 if (options.shouldAllowCrossOriginScrolling == ShouldAllowCrossOriginScrolling::Yes || frameView.safeToPropagateScrollToParent()) {
2880                     parentLayer = ownerElement->renderer()->enclosingLayer();
2881                     // Convert the rect into the coordinate space of the parent frame's document.
2882                     newRect = frameView.contentsToContainingViewContents(enclosingIntRect(newRect));
2883                     insideFixed = false; // FIXME: ideally need to determine if this <iframe> is inside position:fixed.
2884                 } else
2885                     parentLayer = nullptr;
2886             }
2887         } else {
2888             if (options.revealMode == SelectionRevealMode::RevealUpToMainFrame && frameView.frame().isMainFrame())
2889                 return;
2890
2891             auto minScrollPosition = frameView.minimumScrollPosition();
2892             auto maxScrollPosition = frameView.maximumScrollPosition();
2893
2894 #if !PLATFORM(IOS_FAMILY)
2895             LayoutRect viewRect = frameView.visibleContentRect();
2896 #else
2897             // FIXME: ContentInsets should be taken care of in UI process side. webkit.org/b/199682
2898             // To do that, getRectToExpose needs to return the additional scrolling to do beyond content rect.
2899             LayoutRect viewRect = frameView.viewRectExpandedByContentInsets();
2900
2901             // FIXME: webkit.org/b/199683 FrameView::visibleContentRect is wrong when content insets are present
2902             maxScrollPosition = frameView.scrollPositionFromOffset(ScrollPosition(frameView.totalContentsSize() - flooredIntSize(viewRect.size())));
2903
2904             auto contentInsets = page().contentInsets();
2905             minScrollPosition.move(-contentInsets.left(), -contentInsets.top());
2906             maxScrollPosition.move(contentInsets.right(), contentInsets.bottom());
2907 #endif
2908             // Move the target rect into "scrollView contents" coordinates.
2909             LayoutRect targetRect = absoluteRect;
2910             targetRect.move(0, frameView.headerHeight());
2911
2912             LayoutRect revealRect = getRectToExpose(viewRect, targetRect, insideFixed, options.alignX, options.alignY);
2913             // Avoid scrolling to the rounded value of revealRect.location() if we don't actually need to scroll
2914             if (revealRect != viewRect) {
2915                 ScrollOffset clampedScrollPosition = roundedIntPoint(revealRect.location()).constrainedBetween(minScrollPosition, maxScrollPosition);
2916                 // FIXME: Should we use document()->scrollingElement()?
2917                 // See https://bugs.webkit.org/show_bug.cgi?id=205059
2918                 bool animated = useSmoothScrolling(options.behavior, renderer().document().documentElement());
2919                 frameView.setScrollPosition(clampedScrollPosition, ScrollClamping::Clamped, animated);
2920             }
2921
2922             // This is the outermost view of a web page, so after scrolling this view we
2923             // scroll its container by calling Page::scrollRectIntoView.
2924             // This only has an effect on the Mac platform in applications
2925             // that put web views into scrolling containers, such as Mac OS X Mail.
2926             // The canAutoscroll function in EventHandler also knows about this.
2927             page().chrome().scrollRectIntoView(snappedIntRect(absoluteRect));
2928         }
2929     }
2930     
2931     if (parentLayer)
2932         parentLayer->scrollRectToVisible(newRect, insideFixed, options);
2933 }
2934
2935 void RenderLayer::updateCompositingLayersAfterScroll()
2936 {
2937     if (compositor().hasContentCompositingLayers()) {
2938         // Our stacking container is guaranteed to contain all of our descendants that may need
2939         // repositioning, so update compositing layers from there.
2940         if (RenderLayer* compositingAncestor = stackingContext()->enclosingCompositingLayer()) {
2941             if (usesCompositedScrolling())
2942                 compositor().updateCompositingLayers(CompositingUpdateType::OnCompositedScroll, compositingAncestor);
2943             else {
2944                 // FIXME: would be nice to only dirty layers whose positions were affected by scrolling.
2945                 compositingAncestor->setDescendantsNeedUpdateBackingAndHierarchyTraversal();
2946                 compositor().updateCompositingLayers(CompositingUpdateType::OnScroll, compositingAncestor);
2947             }
2948         }
2949     }
2950 }
2951
2952 LayoutRect RenderLayer::getRectToExpose(const LayoutRect& visibleRect, const LayoutRect& exposeRect, bool insideFixed, const ScrollAlignment& alignX, const ScrollAlignment& alignY) const
2953 {
2954     FrameView& frameView = renderer().view().frameView();
2955     if (renderer().isRenderView() && insideFixed) {
2956         // If the element is inside position:fixed and we're not scaled, no amount of scrolling is going to move things around.
2957         if (frameView.frameScaleFactor() == 1)
2958             return visibleRect;
2959
2960         if (renderer().settings().visualViewportEnabled()) {
2961             // exposeRect is in absolute coords, affected by page scale. Unscale it.
2962             LayoutRect unscaledExposeRect = exposeRect;
2963             unscaledExposeRect.scale(1 / frameView.frameScaleFactor());
2964             unscaledExposeRect.move(0, -frameView.headerHeight());
2965
2966             // These are both in unscaled coordinates.
2967             LayoutRect layoutViewport = frameView.layoutViewportRect();
2968             LayoutRect visualViewport = frameView.visualViewportRect();
2969
2970             // The rect to expose may be partially offscreen, which we can't do anything about with position:fixed.
2971             unscaledExposeRect.intersect(layoutViewport);
2972             // Make sure it's not larger than the visual viewport; if so, we'll just move to the top left.
2973             unscaledExposeRect.setSize(unscaledExposeRect.size().shrunkTo(visualViewport.size()));
2974
2975             // Compute how much we have to move the visualViewport to reveal the part of the layoutViewport that contains exposeRect.
2976             LayoutRect requiredVisualViewport = getRectToExpose(visualViewport, unscaledExposeRect, false, alignX, alignY);
2977             // Scale it back up.
2978             requiredVisualViewport.scale(frameView.frameScaleFactor());
2979             requiredVisualViewport.move(0, frameView.headerHeight());
2980             return requiredVisualViewport;
2981         }
2982     }
2983
2984     // Determine the appropriate X behavior.
2985     ScrollAlignment::Behavior scrollX;
2986     LayoutRect exposeRectX(exposeRect.x(), visibleRect.y(), exposeRect.width(), visibleRect.height());
2987     LayoutUnit intersectWidth = intersection(visibleRect, exposeRectX).width();
2988     if (intersectWidth == exposeRect.width() || intersectWidth >= MIN_INTERSECT_FOR_REVEAL)
2989         // If the rectangle is fully visible, use the specified visible behavior.
2990         // If the rectangle is partially visible, but over a certain threshold,
2991         // then treat it as fully visible to avoid unnecessary horizontal scrolling
2992         scrollX = ScrollAlignment::getVisibleBehavior(alignX);
2993     else if (intersectWidth == visibleRect.width()) {
2994         // If the rect is bigger than the visible area, don't bother trying to center. Other alignments will work.
2995         scrollX = ScrollAlignment::getVisibleBehavior(alignX);
2996         if (scrollX == ScrollAlignment::Behavior::AlignCenter)
2997             scrollX = ScrollAlignment::Behavior::NoScroll;
2998     } else if (intersectWidth > 0)
2999         // If the rectangle is partially visible, but not above the minimum threshold, use the specified partial behavior
3000         scrollX = ScrollAlignment::getPartialBehavior(alignX);
3001     else
3002         scrollX = ScrollAlignment::getHiddenBehavior(alignX);
3003     // If we're trying to align to the closest edge, and the exposeRect is further right
3004     // than the visibleRect, and not bigger than the visible area, then align with the right.
3005     if (scrollX == ScrollAlignment::Behavior::AlignToClosestEdge && exposeRect.maxX() > visibleRect.maxX() && exposeRect.width() < visibleRect.width())
3006         scrollX = ScrollAlignment::Behavior::AlignRight;
3007
3008     // Given the X behavior, compute the X coordinate.
3009     LayoutUnit x;
3010     if (scrollX == ScrollAlignment::Behavior::NoScroll)
3011         x = visibleRect.x();
3012     else if (scrollX == ScrollAlignment::Behavior::AlignRight)
3013         x = exposeRect.maxX() - visibleRect.width();
3014     else if (scrollX == ScrollAlignment::Behavior::AlignCenter)
3015         x = exposeRect.x() + (exposeRect.width() - visibleRect.width()) / 2;
3016     else
3017         x = exposeRect.x();
3018
3019     // Determine the appropriate Y behavior.
3020     ScrollAlignment::Behavior scrollY;
3021     LayoutRect exposeRectY(visibleRect.x(), exposeRect.y(), visibleRect.width(), exposeRect.height());
3022     LayoutUnit intersectHeight = intersection(visibleRect, exposeRectY).height();
3023     if (intersectHeight == exposeRect.height())
3024         // If the rectangle is fully visible, use the specified visible behavior.
3025         scrollY = ScrollAlignment::getVisibleBehavior(alignY);
3026     else if (intersectHeight == visibleRect.height()) {
3027         // If the rect is bigger than the visible area, don't bother trying to center. Other alignments will work.
3028         scrollY = ScrollAlignment::getVisibleBehavior(alignY);
3029         if (scrollY == ScrollAlignment::Behavior::AlignCenter)
3030             scrollY = ScrollAlignment::Behavior::NoScroll;
3031     } else if (intersectHeight > 0)
3032         // If the rectangle is partially visible, use the specified partial behavior
3033         scrollY = ScrollAlignment::getPartialBehavior(alignY);
3034     else
3035         scrollY = ScrollAlignment::getHiddenBehavior(alignY);
3036     // If we're trying to align to the closest edge, and the exposeRect is further down
3037     // than the visibleRect, and not bigger than the visible area, then align with the bottom.
3038     if (scrollY == ScrollAlignment::Behavior::AlignToClosestEdge && exposeRect.maxY() > visibleRect.maxY() && exposeRect.height() < visibleRect.height())
3039         scrollY = ScrollAlignment::Behavior::AlignBottom;
3040
3041     // Given the Y behavior, compute the Y coordinate.
3042     LayoutUnit y;
3043     if (scrollY == ScrollAlignment::Behavior::NoScroll)
3044         y = visibleRect.y();
3045     else if (scrollY == ScrollAlignment::Behavior::AlignBottom)
3046         y = exposeRect.maxY() - visibleRect.height();
3047     else if (scrollY == ScrollAlignment::Behavior::AlignCenter)
3048         y = exposeRect.y() + (exposeRect.height() - visibleRect.height()) / 2;
3049     else
3050         y = exposeRect.y();
3051
3052     return LayoutRect(LayoutPoint(x, y), visibleRect.size());
3053 }
3054
3055 void RenderLayer::autoscroll(const IntPoint& positionInWindow)
3056 {
3057     IntPoint currentDocumentPosition = renderer().view().frameView().windowToContents(positionInWindow);
3058     scrollRectToVisible(LayoutRect(currentDocumentPosition, LayoutSize(1, 1)), false, { SelectionRevealMode::Reveal, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded, ShouldAllowCrossOriginScrolling::Yes });
3059 }
3060
3061 bool RenderLayer::canResize() const
3062 {
3063     // We need a special case for <iframe> because they never have
3064     // hasOverflowClip(). However, they do "implicitly" clip their contents, so
3065     // we want to allow resizing them also.
3066     return (renderer().hasOverflowClip() || renderer().isRenderIFrame()) && renderer().style().resize() != Resize::None;
3067 }
3068
3069 void RenderLayer::resize(const PlatformMouseEvent& evt, const LayoutSize& oldOffset)
3070 {
3071     // FIXME: This should be possible on generated content but is not right now.
3072     if (!inResizeMode() || !canResize() || !renderer().element())
3073         return;
3074
3075     // FIXME: The only case where renderer->element()->renderer() != renderer is with continuations. Do they matter here?
3076     // If they do it would still be better to deal with them explicitly.
3077     Element* element = renderer().element();
3078     auto* renderer = downcast<RenderBox>(element->renderer());
3079
3080     Document& document = element->document();
3081     if (!document.frame()->eventHandler().mousePressed())
3082         return;
3083
3084     float zoomFactor = renderer->style().effectiveZoom();
3085
3086     LayoutSize newOffset = offsetFromResizeCorner(document.view()->windowToContents(evt.position()));
3087     newOffset.setWidth(newOffset.width() / zoomFactor);
3088     newOffset.setHeight(newOffset.height() / zoomFactor);
3089     
3090     LayoutSize currentSize = LayoutSize(renderer->width() / zoomFactor, renderer->height() / zoomFactor);
3091     LayoutSize minimumSize = element->minimumSizeForResizing().shrunkTo(currentSize);
3092     element->setMinimumSizeForResizing(minimumSize);
3093     
3094     LayoutSize adjustedOldOffset = LayoutSize(oldOffset.width() / zoomFactor, oldOffset.height() / zoomFactor);
3095     if (shouldPlaceBlockDirectionScrollbarOnLeft()) {
3096         newOffset.setWidth(-newOffset.width());
3097         adjustedOldOffset.setWidth(-adjustedOldOffset.width());
3098     }
3099     
3100     LayoutSize difference = (currentSize + newOffset - adjustedOldOffset).expandedTo(minimumSize) - currentSize;
3101
3102     StyledElement* styledElement = downcast<StyledElement>(element);
3103     bool isBoxSizingBorder = renderer->style().boxSizing() == BoxSizing::BorderBox;
3104
3105     Resize resize = renderer->style().resize();
3106     if (resize != Resize::Vertical && difference.width()) {
3107         if (is<HTMLFormControlElement>(*element)) {
3108             // Make implicit margins from the theme explicit (see <http://bugs.webkit.org/show_bug.cgi?id=9547>).
3109             styledElement->setInlineStyleProperty(CSSPropertyMarginLeft, renderer->marginLeft() / zoomFactor, CSSUnitType::CSS_PX);
3110             styledElement->setInlineStyleProperty(CSSPropertyMarginRight, renderer->marginRight() / zoomFactor, CSSUnitType::CSS_PX);
3111         }
3112         LayoutUnit baseWidth = renderer->width() - (isBoxSizingBorder ? 0_lu : renderer->horizontalBorderAndPaddingExtent());
3113         baseWidth = baseWidth / zoomFactor;
3114         styledElement->setInlineStyleProperty(CSSPropertyWidth, roundToInt(baseWidth + difference.width()), CSSUnitType::CSS_PX);
3115     }
3116
3117     if (resize != Resize::Horizontal && difference.height()) {
3118         if (is<HTMLFormControlElement>(*element)) {
3119             // Make implicit margins from the theme explicit (see <http://bugs.webkit.org/show_bug.cgi?id=9547>).
3120             styledElement->setInlineStyleProperty(CSSPropertyMarginTop, renderer->marginTop() / zoomFactor, CSSUnitType::CSS_PX);
3121             styledElement->setInlineStyleProperty(CSSPropertyMarginBottom, renderer->marginBottom() / zoomFactor, CSSUnitType::CSS_PX);
3122         }
3123         LayoutUnit baseHeight = renderer->height() - (isBoxSizingBorder ? 0_lu : renderer->verticalBorderAndPaddingExtent());
3124         baseHeight = baseHeight / zoomFactor;
3125         styledElement->setInlineStyleProperty(CSSPropertyHeight, roundToInt(baseHeight + difference.height()), CSSUnitType::CSS_PX);
3126     }
3127
3128     document.updateLayout();
3129
3130     // FIXME (Radar 4118564): We should also autoscroll the window as necessary to keep the point under the cursor in view.
3131 }
3132
3133 void RenderLayer::setScrollOffset(const ScrollOffset& offset)
3134 {
3135     scrollTo(scrollPositionFromOffset(offset));
3136 }
3137
3138 ScrollingNodeID RenderLayer::scrollingNodeID() const
3139 {
3140     if (!isComposited())
3141         return 0;
3142
3143     return backing()->scrollingNodeIDForRole(ScrollCoordinationRole::Scrolling);
3144 }
3145
3146 IntRect RenderLayer::visibleContentRectInternal(VisibleContentRectIncludesScrollbars scrollbarInclusion, VisibleContentRectBehavior) const
3147 {
3148     IntSize scrollbarSpace;
3149     if (showsOverflowControls() && scrollbarInclusion == IncludeScrollbars)
3150         scrollbarSpace = scrollbarIntrusion();
3151     
3152     auto visibleSize = this->visibleSize();
3153     return { scrollPosition(), { std::max(0, visibleSize.width() - scrollbarSpace.width()), std::max(0, visibleSize.height() - scrollbarSpace.height()) } };
3154 }
3155
3156 IntSize RenderLayer::overhangAmount() const
3157 {
3158 #if ENABLE(RUBBER_BANDING)
3159     if (!renderer().settings().rubberBandingForSubScrollableRegionsEnabled())
3160         return IntSize();
3161
3162     IntSize stretch;
3163
3164     // FIXME: use maximumScrollOffset(), or just move this to ScrollableArea.
3165     ScrollOffset scrollOffset = scrollOffsetFromPosition(scrollPosition());
3166     auto reachableSize = reachableTotalContentsSize();
3167     if (scrollOffset.y() < 0)
3168         stretch.setHeight(scrollOffset.y());
3169     else if (reachableSize.height() && scrollOffset.y() > reachableSize.height() - visibleHeight())
3170         stretch.setHeight(scrollOffset.y() - (reachableSize.height() - visibleHeight()));
3171
3172     if (scrollOffset.x() < 0)
3173         stretch.setWidth(scrollOffset.x());
3174     else if (reachableSize.width() && scrollOffset.x() > reachableSize.width() - visibleWidth())
3175         stretch.setWidth(scrollOffset.x() - (reachableSize.width() - visibleWidth()));
3176
3177     return stretch;
3178 #else
3179     return IntSize();
3180 #endif
3181 }
3182
3183 bool RenderLayer::isActive() const
3184 {
3185     return page().focusController().isActive();
3186 }
3187
3188 static int cornerStart(const RenderLayer& layer, int minX, int maxX, int thickness)
3189 {
3190     if (layer.shouldPlaceBlockDirectionScrollbarOnLeft())
3191         return minX + layer.renderer().style().borderLeftWidth();
3192     return maxX - thickness - layer.renderer().style().borderRightWidth();
3193 }
3194
3195 static LayoutRect cornerRect(const RenderLayer& layer, const LayoutRect& bounds)
3196 {
3197     int horizontalThickness;
3198     int verticalThickness;
3199     if (!layer.verticalScrollbar() && !layer.horizontalScrollbar()) {
3200         // FIXME: This isn't right.  We need to know the thickness of custom scrollbars
3201         // even when they don't exist in order to set the resizer square size properly.
3202         horizontalThickness = ScrollbarTheme::theme().scrollbarThickness();
3203         verticalThickness = horizontalThickness;
3204     } else if (layer.verticalScrollbar() && !layer.horizontalScrollbar()) {
3205         horizontalThickness = layer.verticalScrollbar()->width();
3206         verticalThickness = horizontalThickness;
3207     } else if (layer.horizontalScrollbar() && !layer.verticalScrollbar()) {
3208         verticalThickness = layer.horizontalScrollbar()->height();
3209         horizontalThickness = verticalThickness;
3210     } else {
3211         horizontalThickness = layer.verticalScrollbar()->width();
3212         verticalThickness = layer.horizontalScrollbar()->height();
3213     }
3214     return LayoutRect(cornerStart(layer, bounds.x(), bounds.maxX(), horizontalThickness),
3215         bounds.maxY() - verticalThickness - layer.renderer().style().borderBottomWidth(),
3216         horizontalThickness, verticalThickness);
3217 }
3218
3219 IntRect RenderLayer::scrollCornerRect() const
3220 {
3221     // We have a scrollbar corner when a non overlay scrollbar is visible and not filling the entire length of the box.
3222     // This happens when:
3223     // (a) A resizer is present and at least one non overlay scrollbar is present
3224     // (b) Both non overlay scrollbars are present.
3225     // Overlay scrollbars always fill the entire length of the box so we never have scroll corner in that case.
3226     bool hasHorizontalBar = m_hBar && !m_hBar->isOverlayScrollbar();
3227     bool hasVerticalBar = m_vBar && !m_vBar->isOverlayScrollbar();
3228     bool hasResizer = renderer().style().resize() != Resize::None;
3229     if ((hasHorizontalBar && hasVerticalBar) || (hasResizer && (hasHorizontalBar || hasVerticalBar)))
3230         return snappedIntRect(cornerRect(*this, renderBox()->borderBoxRect()));
3231     return IntRect();
3232 }
3233
3234 static LayoutRect resizerCornerRect(const RenderLayer& layer, const LayoutRect& bounds)
3235 {
3236     ASSERT(layer.renderer().isBox());
3237     if (layer.renderer().style().resize() == Resize::None)
3238         return LayoutRect();
3239     return cornerRect(layer, bounds);
3240 }
3241
3242 LayoutRect RenderLayer::scrollCornerAndResizerRect() const
3243 {
3244     RenderBox* box = renderBox();
3245     if (!box)
3246         return LayoutRect();
3247     LayoutRect scrollCornerAndResizer = scrollCornerRect();
3248     if (scrollCornerAndResizer.isEmpty())
3249         scrollCornerAndResizer = resizerCornerRect(*this, box->borderBoxRect());
3250     return scrollCornerAndResizer;
3251 }
3252
3253 bool RenderLayer::isScrollCornerVisible() const
3254 {
3255     ASSERT(renderer().isBox());
3256     return !scrollCornerRect().isEmpty();
3257 }
3258
3259 IntRect RenderLayer::convertFromScrollbarToContainingView(const Scrollbar& scrollbar, const IntRect& scrollbarRect) const
3260 {
3261     IntRect rect = scrollbarRect;
3262     rect.move(scrollbarOffset(scrollbar));
3263
3264     return renderer().view().frameView().convertFromRendererToContainingView(&renderer(), rect);
3265 }
3266
3267 IntRect RenderLayer::convertFromContainingViewToScrollbar(const Scrollbar& scrollbar, const IntRect& parentRect) const
3268 {
3269     IntRect rect = renderer().view().frameView().convertFromContainingViewToRenderer(&renderer(), parentRect);
3270     rect.move(-scrollbarOffset(scrollbar));
3271     return rect;
3272 }
3273
3274 IntPoint RenderLayer::convertFromScrollbarToContainingView(const Scrollbar& scrollbar, const IntPoint& scrollbarPoint) const
3275 {
3276     IntPoint point = scrollbarPoint;
3277     point.move(scrollbarOffset(scrollbar));
3278     return renderer().view().frameView().convertFromRendererToContainingView(&renderer(), point);
3279 }
3280
3281 IntPoint RenderLayer::convertFromContainingViewToScrollbar(const Scrollbar& scrollbar, const IntPoint& parentPoint) const
3282 {
3283     IntPoint point = renderer().view().frameView().convertFromContainingViewToRenderer(&renderer(), parentPoint);
3284     point.move(-scrollbarOffset(scrollbar));
3285     return point;
3286 }
3287
3288 IntSize RenderLayer::visibleSize() const
3289 {
3290     RenderBox* box = renderBox();
3291     if (!box)
3292         return IntSize();
3293
3294     return IntSize(roundToInt(box->clientWidth()), roundToInt(box->clientHeight()));
3295 }
3296
3297 IntSize RenderLayer::contentsSize() const
3298 {
3299     return IntSize(scrollWidth(), scrollHeight());
3300 }
3301
3302 IntSize RenderLayer::reachableTotalContentsSize() const
3303 {
3304     IntSize contentsSize = this->contentsSize();
3305
3306     if (!hasScrollableHorizontalOverflow())
3307         contentsSize.setWidth(std::min(contentsSize.width(), visibleSize().width()));
3308
3309     if (!hasScrollableVerticalOverflow())
3310         contentsSize.setHeight(std::min(contentsSize.height(), visibleSize().height()));
3311
3312     return contentsSize;
3313 }
3314
3315 void RenderLayer::availableContentSizeChanged(AvailableSizeChangeReason reason)
3316 {
3317     ScrollableArea::availableContentSizeChanged(reason);
3318
3319     if (reason == AvailableSizeChangeReason::ScrollbarsChanged) {
3320         if (is<RenderBlock>(renderer()))
3321             downcast<RenderBlock>(renderer()).setShouldForceRelayoutChildren(true);
3322         renderer().setNeedsLayout();
3323     }
3324 }
3325
3326 bool RenderLayer::shouldSuspendScrollAnimations() const
3327 {
3328     return renderer().view().frameView().shouldSuspendScrollAnimations();
3329 }
3330
3331 #if PLATFORM(IOS_FAMILY)
3332 void RenderLayer::didStartScroll()
3333 {
3334     page().chrome().client().didStartOverflowScroll();
3335 }
3336
3337 void RenderLayer::didEndScroll()
3338 {
3339     page().chrome().client().didEndOverflowScroll();
3340 }
3341     
3342 void RenderLayer::didUpdateScroll()
3343 {
3344     // Send this notification when we scroll, since this is how we keep selection updated.
3345     page().chrome().client().didLayout(ChromeClient::Scroll);
3346 }
3347 #endif
3348
3349 IntPoint RenderLayer::lastKnownMousePosition() const
3350 {
3351     return renderer().frame().eventHandler().lastKnownMousePosition();
3352 }
3353
3354 bool RenderLayer::isHandlingWheelEvent() const
3355 {
3356     return renderer().frame().eventHandler().isHandlingWheelEvent();
3357 }
3358
3359 IntRect RenderLayer::rectForHorizontalScrollbar(const IntRect& borderBoxRect) const
3360 {
3361     if (!m_hBar)
3362         return IntRect();
3363
3364     const RenderBox* box = renderBox();
3365     const IntRect& scrollCorner = scrollCornerRect();
3366
3367     return IntRect(horizontalScrollbarStart(borderBoxRect.x()),
3368         borderBoxRect.maxY() - box->borderBottom() - m_hBar->height(),
3369         borderBoxRect.width() - (box->borderLeft() + box->borderRight()) - scrollCorner.width(),
3370         m_hBar->height());
3371 }
3372
3373 IntRect RenderLayer::rectForVerticalScrollbar(const IntRect& borderBoxRect) const
3374 {
3375     if (!m_vBar)
3376         return IntRect();
3377
3378     const RenderBox* box = renderBox();
3379     const IntRect& scrollCorner = scrollCornerRect();
3380
3381     return IntRect(verticalScrollbarStart(borderBoxRect.x(), borderBoxRect.maxX()),
3382         borderBoxRect.y() + box->borderTop(),
3383         m_vBar->width(),
3384         borderBoxRect.height() - (box->borderTop() + box->borderBottom()) - scrollCorner.height());
3385 }
3386
3387 LayoutUnit RenderLayer::verticalScrollbarStart(int minX, int maxX) const
3388 {
3389     const RenderBox* box = renderBox();
3390     if (shouldPlaceBlockDirectionScrollbarOnLeft())
3391         return minX + box->borderLeft();
3392     return maxX - box->borderRight() - m_vBar->width();
3393 }
3394
3395 LayoutUnit RenderLayer::horizontalScrollbarStart(int minX) const
3396 {
3397     const RenderBox* box = renderBox();
3398     int x = minX + box->borderLeft();
3399     if (shouldPlaceBlockDirectionScrollbarOnLeft())
3400         x += m_vBar ? m_vBar->width() : roundToInt(resizerCornerRect(*this, box->borderBoxRect()).width());
3401     return x;
3402 }
3403
3404 IntSize RenderLayer::scrollbarOffset(const Scrollbar& scrollbar) const
3405 {
3406     RenderBox* box = renderBox();
3407
3408     if (&scrollbar == m_vBar.get())
3409         return IntSize(verticalScrollbarStart(0, box->width()), box->borderTop());
3410
3411     if (&scrollbar == m_hBar.get())
3412         return IntSize(horizontalScrollbarStart(0), box->height() - box->borderBottom() - scrollbar.height());
3413     
3414     ASSERT_NOT_REACHED();
3415     return IntSize();
3416 }
3417
3418 void RenderLayer::invalidateScrollbarRect(Scrollbar& scrollbar, const IntRect& rect)
3419 {
3420     if (!showsOverflowControls())
3421         return;
3422
3423     if (&scrollbar == m_vBar.get()) {
3424         if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
3425             layer->setNeedsDisplayInRect(rect);
3426             return;
3427         }
3428     } else {
3429         if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
3430             layer->setNeedsDisplayInRect(rect);
3431             return;
3432         }
3433     }
3434
3435     IntRect scrollRect = rect;
3436     RenderBox* box = renderBox();
3437     ASSERT(box);
3438     // If we are not yet inserted into the tree, there is no need to repaint.
3439     if (!box->parent())
3440         return;
3441
3442     if (&scrollbar == m_vBar.get())
3443         scrollRect.move(verticalScrollbarStart(0, box->width()), box->borderTop());
3444     else
3445         scrollRect.move(horizontalScrollbarStart(0), box->height() - box->borderBottom() - scrollbar.height());
3446     LayoutRect repaintRect = scrollRect;
3447     renderBox()->flipForWritingMode(repaintRect);
3448     renderer().repaintRectangle(repaintRect);
3449 }
3450
3451 void RenderLayer::invalidateScrollCornerRect(const IntRect& rect)
3452 {
3453     if (!showsOverflowControls())
3454         return;
3455
3456     if (GraphicsLayer* layer = layerForScrollCorner()) {
3457         layer->setNeedsDisplayInRect(rect);
3458         return;
3459     }
3460
3461     if (m_scrollCorner)
3462         m_scrollCorner->repaintRectangle(rect);
3463     if (m_resizer)
3464         m_resizer->repaintRectangle(rect);
3465 }
3466
3467 static bool scrollbarHiddenByStyle(Scrollbar* scrollbar)
3468 {
3469     return scrollbar && scrollbar->isHiddenByStyle();
3470 }
3471
3472 bool RenderLayer::horizontalScrollbarHiddenByStyle() const
3473 {
3474     return scrollbarHiddenByStyle(horizontalScrollbar());
3475 }
3476
3477 bool RenderLayer::verticalScrollbarHiddenByStyle() const
3478 {
3479     return scrollbarHiddenByStyle(verticalScrollbar());
3480 }
3481
3482 static inline RenderElement* rendererForScrollbar(RenderLayerModelObject& renderer)
3483 {
3484     if (Element* element = renderer.element()) {
3485         if (ShadowRoot* shadowRoot = element->containingShadowRoot()) {
3486             if (shadowRoot->mode() == ShadowRootMode::UserAgent)
3487                 return shadowRoot->host()->renderer();
3488         }
3489     }
3490
3491     return &renderer;
3492 }
3493
3494 Ref<Scrollbar> RenderLayer::createScrollbar(ScrollbarOrientation orientation)
3495 {
3496     RefPtr<Scrollbar> widget;
3497     ASSERT(rendererForScrollbar(renderer()));
3498     auto& actualRenderer = *rendererForScrollbar(renderer());
3499     bool hasCustomScrollbarStyle = is<RenderBox>(actualRenderer) && downcast<RenderBox>(actualRenderer).style().hasPseudoStyle(PseudoId::Scrollbar);
3500     if (hasCustomScrollbarStyle)
3501         widget = RenderScrollbar::createCustomScrollbar(*this, orientation, downcast<RenderBox>(actualRenderer).element());
3502     else {
3503         widget = Scrollbar::createNativeScrollbar(*this, orientation, RegularScrollbar);
3504         didAddScrollbar(widget.get(), orientation);
3505         if (page().isMonitoringWheelEvents())
3506             scrollAnimator().setWheelEventTestMonitor(page().wheelEventTestMonitor());
3507     }
3508     renderer().view().frameView().addChild(*widget);
3509     return widget.releaseNonNull();
3510 }
3511
3512 void RenderLayer::destroyScrollbar(ScrollbarOrientation orientation)
3513 {
3514     RefPtr<Scrollbar>& scrollbar = orientation == HorizontalScrollbar ? m_hBar : m_vBar;
3515     if (!scrollbar)
3516         return;
3517
3518     if (!scrollbar->isCustomScrollbar())
3519         willRemoveScrollbar(scrollbar.get(), orientation);
3520
3521     scrollbar->removeFromParent();
3522     scrollbar = nullptr;
3523 }
3524
3525 bool RenderLayer::scrollsOverflow() const
3526 {
3527     if (!is<RenderBox>(renderer()))
3528         return false;
3529
3530     return downcast<RenderBox>(renderer()).scrollsOverflow();
3531 }
3532
3533 void RenderLayer::setHasHorizontalScrollbar(bool hasScrollbar)
3534 {
3535     if (hasScrollbar == hasHorizontalScrollbar())
3536         return;
3537
3538     if (hasScrollbar) {
3539         m_hBar = createScrollbar(HorizontalScrollbar);
3540 #if ENABLE(RUBBER_BANDING)
3541         ScrollElasticity elasticity = scrollsOverflow() && renderer().settings().rubberBandingForSubScrollableRegionsEnabled() ? ScrollElasticityAutomatic : ScrollElasticityNone;
3542         ScrollableArea::setHorizontalScrollElasticity(elasticity);
3543 #endif
3544     } else {
3545         destroyScrollbar(HorizontalScrollbar);
3546 #if ENABLE(RUBBER_BANDING)
3547         ScrollableArea::setHorizontalScrollElasticity(ScrollElasticityNone);
3548 #endif
3549     }
3550
3551     // Destroying or creating one bar can cause our scrollbar corner to come and go.  We need to update the opposite scrollbar's style.
3552     if (m_hBar)
3553         m_hBar->styleChanged();
3554     if (m_vBar)
3555         m_vBar->styleChanged();
3556 }
3557
3558 void RenderLayer::setHasVerticalScrollbar(bool hasScrollbar)
3559 {
3560     if (hasScrollbar == hasVerticalScrollbar())
3561         return;
3562
3563     if (hasScrollbar) {
3564         m_vBar = createScrollbar(VerticalScrollbar);
3565 #if ENABLE(RUBBER_BANDING)
3566         ScrollElasticity elasticity = scrollsOverflow() && renderer().settings().rubberBandingForSubScrollableRegionsEnabled() ? ScrollElasticityAutomatic : ScrollElasticityNone;
3567         ScrollableArea::setVerticalScrollElasticity(elasticity);
3568 #endif
3569     } else {
3570         destroyScrollbar(VerticalScrollbar);
3571 #if ENABLE(RUBBER_BANDING)
3572         ScrollableArea::setVerticalScrollElasticity(ScrollElasticityNone);
3573 #endif
3574     }
3575
3576      // Destroying or creating one bar can cause our scrollbar corner to come and go.  We need to update the opposite scrollbar's style.
3577     if (m_hBar)
3578         m_hBar->styleChanged();
3579     if (m_vBar)
3580         m_vBar->styleChanged();
3581 }
3582
3583 ScrollableArea* RenderLayer::enclosingScrollableArea() const
3584 {
3585     if (RenderLayer* scrollableLayer = enclosingScrollableLayer())
3586         return scrollableLayer;
3587
3588     // FIXME: We should return the frame view here (or possibly an ancestor frame view,
3589     // if the frame view isn't scrollable.
3590     return nullptr;
3591 }
3592
3593 bool RenderLayer::isScrollableOrRubberbandable()
3594 {
3595     return renderer().isScrollableOrRubberbandableBox();
3596 }
3597
3598 bool RenderLayer::hasScrollableOrRubberbandableAncestor()
3599 {
3600     for (RenderLayer* nextLayer = parentLayerCrossFrame(*this); nextLayer; nextLayer = parentLayerCrossFrame(*nextLayer)) {
3601         if (nextLayer->isScrollableOrRubberbandable())
3602             return true;
3603     }
3604
3605     return false;
3606 }
3607
3608 bool RenderLayer::useDarkAppearance() const
3609 {
3610     return renderer().useDarkAppearance();
3611 }
3612
3613 #if ENABLE(CSS_SCROLL_SNAP)
3614 void RenderLayer::updateSnapOffsets()
3615 {
3616     // FIXME: Extend support beyond HTMLElements.
3617     if (!is<HTMLElement>(enclosingElement()) || !enclosingElement()->renderBox())
3618         return;
3619
3620     RenderBox* box = enclosingElement()->renderBox();
3621     updateSnapOffsetsForScrollableArea(*this, *downcast<HTMLElement>(enclosingElement()), *box, box->style());
3622 }
3623
3624 bool RenderLayer::isScrollSnapInProgress() const
3625 {
3626     if (!scrollsOverflow())
3627         return false;
3628     
3629     if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
3630         return scrollAnimator->isScrollSnapInProgress();
3631     
3632     return false;
3633 }
3634 #endif
3635
3636 bool RenderLayer::usesMockScrollAnimator() const
3637 {
3638     return DeprecatedGlobalSettings::usesMockScrollAnimator();
3639 }
3640
3641 void RenderLayer::logMockScrollAnimatorMessage(const String& message) const
3642 {
3643     renderer().document().addConsoleMessage(MessageSource::Other, MessageLevel::Debug, "RenderLayer: " + message);
3644 }
3645
3646 int RenderLayer::verticalScrollbarWidth(OverlayScrollbarSizeRelevancy relevancy) const
3647 {
3648     if (!m_vBar
3649         || !showsOverflowControls()
3650         || (m_vBar->isOverlayScrollbar() && (relevancy == IgnoreOverlayScrollbarSize || !m_vBar->shouldParticipateInHitTesting())))
3651         return 0;
3652
3653     return m_vBar->width();
3654 }
3655
3656 int RenderLayer::horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy relevancy) const
3657 {
3658     if (!m_hBar
3659         || !showsOverflowControls()
3660         || (m_hBar->isOverlayScrollbar() && (relevancy == IgnoreOverlayScrollbarSize || !m_hBar->shouldParticipateInHitTesting())))
3661         return 0;
3662
3663     return m_hBar->height();
3664 }
3665
3666 IntSize RenderLayer::offsetFromResizeCorner(const IntPoint& absolutePoint) const
3667 {
3668     // Currently the resize corner is either the bottom right corner or the bottom left corner.
3669     // FIXME: This assumes the location is 0, 0. Is this guaranteed to always be the case?
3670     IntSize elementSize = size();
3671     if (shouldPlaceBlockDirectionScrollbarOnLeft())
3672         elementSize.setWidth(0);
3673     IntPoint resizerPoint = IntPoint(elementSize);
3674     IntPoint localPoint = roundedIntPoint(absoluteToContents(absolutePoint));
3675     return localPoint - resizerPoint;
3676 }
3677
3678 bool RenderLayer::hasOverflowControls() const
3679 {
3680     return m_hBar || m_vBar || m_scrollCorner || renderer().style().resize() != Resize::None;
3681 }
3682
3683 void RenderLayer::positionOverflowControls(const IntSize& offsetFromRoot)
3684 {
3685     if (!m_hBar && !m_vBar && !canResize())
3686         return;
3687     
3688     RenderBox* box = renderBox();
3689     if (!box)
3690         return;
3691
3692     const IntRect borderBox = snappedIntRect(box->borderBoxRect());
3693     const IntRect& scrollCorner = scrollCornerRect();
3694     IntRect absBounds(borderBox.location() + offsetFromRoot, borderBox.size());
3695     if (m_vBar) {
3696         IntRect vBarRect = rectForVerticalScrollbar(borderBox);
3697         vBarRect.move(offsetFromRoot);
3698         m_vBar->setFrameRect(vBarRect);
3699     }
3700     
3701     if (m_hBar) {
3702         IntRect hBarRect = rectForHorizontalScrollbar(borderBox);
3703         hBarRect.move(offsetFromRoot);
3704         m_hBar->setFrameRect(hBarRect);
3705     }
3706     
3707     if (m_scrollCorner)
3708         m_scrollCorner->setFrameRect(scrollCorner);
3709     if (m_resizer)
3710         m_resizer->setFrameRect(resizerCornerRect(*this, borderBox));
3711
3712     if (isComposited())
3713         backing()->positionOverflowControlsLayers();
3714 }
3715
3716 int RenderLayer::scrollWidth() const
3717 {
3718     ASSERT(renderBox());
3719     if (m_scrollDimensionsDirty)
3720         const_cast<RenderLayer*>(this)->computeScrollDimensions();
3721     // FIXME: This should use snappedIntSize() instead with absolute coordinates.
3722     return m_scrollSize.width();
3723 }
3724
3725 int RenderLayer::scrollHeight() const
3726 {
3727     ASSERT(renderBox());
3728     if (m_scrollDimensionsDirty)
3729         const_cast<RenderLayer*>(this)->computeScrollDimensions();
3730     // FIXME: This should use snappedIntSize() instead with absolute coordinates.
3731     return m_scrollSize.height();
3732 }
3733
3734 LayoutUnit RenderLayer::overflowTop() const
3735 {
3736     RenderBox* box = renderBox();
3737     LayoutRect overflowRect(box->layoutOverflowRect());
3738     box->flipForWritingMode(overflowRect);
3739     return overflowRect.y();
3740 }
3741
3742 LayoutUnit RenderLayer::overflowBottom() const
3743 {
3744     RenderBox* box = renderBox();
3745     LayoutRect overflowRect(box->layoutOverflowRect());
3746     box->flipForWritingMode(overflowRect);
3747     return overflowRect.maxY();
3748 }
3749
3750 LayoutUnit RenderLayer::overflowLeft() const
3751 {
3752     RenderBox* box = renderBox();
3753     LayoutRect overflowRect(box->layoutOverflowRect());
3754     box->flipForWritingMode(overflowRect);
3755     return overflowRect.x();
3756 }
3757
3758 LayoutUnit RenderLayer::overflowRight() const
3759 {
3760     RenderBox* box = renderBox();
3761     LayoutRect overflowRect(box->layoutOverflowRect());
3762     box->flipForWritingMode(overflowRect);
3763     return overflowRect.maxX();
3764 }
3765
3766 void RenderLayer::computeScrollDimensions()
3767 {
3768     RenderBox* box = renderBox();
3769     ASSERT(box);
3770
3771     m_scrollDimensionsDirty = false;
3772
3773     m_scrollSize.setWidth(roundToInt(overflowRight() - overflowLeft()));
3774     m_scrollSize.setHeight(roundToInt(overflowBottom() - overflowTop()));
3775
3776     int scrollableLeftOverflow = roundToInt(overflowLeft() - box->borderLeft());
3777     if (shouldPlaceBlockDirectionScrollbarOnLeft())
3778         scrollableLeftOverflow -= verticalScrollbarWidth();
3779     int scrollableTopOverflow = roundToInt(overflowTop() - box->borderTop());
3780     setScrollOrigin(IntPoint(-scrollableLeftOverflow, -scrollableTopOverflow));
3781     
3782     m_hasCompositedScrollableOverflow = canUseCompositedScrolling() && (hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
3783 }
3784
3785 bool RenderLayer::hasScrollableHorizontalOverflow() const
3786 {
3787     return hasHorizontalOverflow() && renderBox()->scrollsOverflowX();
3788 }
3789
3790 bool RenderLayer::hasScrollableVerticalOverflow() const
3791 {
3792     return hasVerticalOverflow() && renderBox()->scrollsOverflowY();
3793 }
3794
3795 bool RenderLayer::hasHorizontalOverflow() const
3796 {
3797     ASSERT(!m_scrollDimensionsDirty);
3798
3799     return scrollWidth() > roundToInt(renderBox()->clientWidth());
3800 }
3801
3802 bool RenderLayer::hasVerticalOverflow() const
3803 {
3804     ASSERT(!m_scrollDimensionsDirty);
3805
3806     return scrollHeight() > roundToInt(renderBox()->clientHeight());
3807 }
3808
3809 static bool styleRequiresScrollbar(const RenderStyle& style, ScrollbarOrientation axis)
3810 {
3811     Overflow overflow = axis == ScrollbarOrientation::HorizontalScrollbar ? style.overflowX() : style.overflowY();
3812     bool overflowScrollActsLikeAuto = overflow == Overflow::Scroll && !style.hasPseudoStyle(PseudoId::Scrollbar) && ScrollbarTheme::theme().usesOverlayScrollbars();
3813     return overflow == Overflow::Scroll && !overflowScrollActsLikeAuto;
3814 }
3815
3816 static bool styleDefinesAutomaticScrollbar(const RenderStyle& style, ScrollbarOrientation axis)
3817 {
3818     Overflow overflow = axis == ScrollbarOrientation::HorizontalScrollbar ? style.overflowX() : style.overflowY();
3819     bool overflowScrollActsLikeAuto = overflow == Overflow::Scroll && !style.hasPseudoStyle(PseudoId::Scrollbar) && ScrollbarTheme::theme().usesOverlayScrollbars();
3820     return overflow == Overflow::Auto || overflowScrollActsLikeAuto;
3821 }
3822
3823 void RenderLayer::updateScrollbarsAfterLayout()
3824 {
3825     RenderBox* box = renderBox();
3826     ASSERT(box);
3827
3828     // List box parts handle the scrollbars by themselves so we have nothing to do.
3829     if (box->style().appearance() == ListboxPart)
3830         return;
3831
3832     bool hasHorizontalOverflow = this->hasHorizontalOverflow();
3833     bool hasVerticalOverflow = this->hasVerticalOverflow();
3834
3835     // If overflow requires a scrollbar, then we just need to enable or disable.
3836     if (m_hBar && styleRequiresScrollbar(renderer().style(), HorizontalScrollbar))
3837         m_hBar->setEnabled(hasHorizontalOverflow);
3838     if (m_vBar && styleRequiresScrollbar(renderer().style(), VerticalScrollbar))
3839         m_vBar->setEnabled(hasVerticalOverflow);
3840
3841     // Scrollbars with auto behavior may need to lay out again if scrollbars got added or removed.
3842     bool autoHorizontalScrollBarChanged = box->hasHorizontalScrollbarWithAutoBehavior() && (hasHorizontalScrollbar() != hasHorizontalOverflow);
3843     bool autoVerticalScrollBarChanged = box->hasVerticalScrollbarWithAutoBehavior() && (hasVerticalScrollbar() != hasVerticalOverflow);
3844
3845     if (autoHorizontalScrollBarChanged || autoVerticalScrollBarChanged) {
3846         if (box->hasHorizontalScrollbarWithAutoBehavior())
3847             setHasHorizontalScrollbar(hasHorizontalOverflow);
3848         if (box->hasVerticalScrollbarWithAutoBehavior())
3849             setHasVerticalScrollbar(hasVerticalOverflow);
3850
3851         updateSelfPaintingLayer();
3852
3853         renderer().repaint();
3854
3855         if (renderer().style().overflowX() == Overflow::Auto || renderer().style().overflowY() == Overflow::Auto) {
3856             if (!m_inOverflowRelayout) {
3857                 m_inOverflowRelayout = true;
3858                 renderer().setNeedsLayout(MarkOnlyThis);
3859                 if (is<RenderBlock>(renderer())) {
3860                     RenderBlock& block = downcast<RenderBlock>(renderer());
3861                     block.scrollbarsChanged(autoHorizontalScrollBarChanged, autoVerticalScrollBarChanged);
3862                     block.layoutBlock(true);
3863                 } else
3864                     renderer().layout();
3865                 m_inOverflowRelayout = false;
3866             }
3867         }
3868         
3869         RenderObject* parent = renderer().parent();
3870         if (parent && parent->isFlexibleBox() && renderer().isBox())
3871             downcast<RenderFlexibleBox>(parent)->clearCachedMainSizeForChild(*renderBox());
3872     }
3873
3874     // Set up the range (and page step/line step).
3875     if (m_hBar) {
3876         int clientWidth = roundToInt(box->clientWidth());
3877         int pageStep = Scrollbar::pageStep(clientWidth);
3878         m_hBar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep);
3879         m_hBar->setProportion(clientWidth, m_scrollSize.width());
3880     }
3881     if (m_vBar) {
3882         int clientHeight = roundToInt(box->clientHeight());
3883         int pageStep = Scrollbar::pageStep(clientHeight);
3884         m_vBar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep);
3885         m_vBar->setProportion(clientHeight, m_scrollSize.height());
3886     }
3887
3888     updateScrollableAreaSet(hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
3889 }
3890
3891 // This is called from layout code (before updateLayerPositions).
3892 void RenderLayer::updateScrollInfoAfterLayout()
3893 {
3894     RenderBox* box = renderBox();
3895     if (!box)
3896         return;
3897
3898     m_scrollDimensionsDirty = true;
3899     ScrollOffset originalScrollOffset = scrollOffset();
3900
3901     computeScrollDimensions();
3902
3903 #if ENABLE(CSS_SCROLL_SNAP)
3904     // FIXME: Ensure that offsets are also updated in case of programmatic style changes.
3905     // https://bugs.webkit.org/show_bug.cgi?id=135964
3906     updateSnapOffsets();
3907 #endif
3908
3909     if (!box->isHTMLMarquee() && !isRubberBandInProgress()) {
3910         // Layout may cause us to be at an invalid scroll position. In this case we need
3911         // to pull our scroll offsets back to the max (or push them up to the min).
3912         ScrollOffset clampedScrollOffset = clampScrollOffset(scrollOffset());
3913 #if PLATFORM(IOS_FAMILY)
3914         // FIXME: This looks wrong. The caret adjust mode should only be enabled on editing related entry points.
3915         // This code was added to fix an issue where the text insertion point would always be drawn on the right edge
3916         // of a text field whose content overflowed its bounds. See <rdar://problem/15579797> for more details.
3917         setAdjustForIOSCaretWhenScrolling(true);
3918 #endif
3919         if (clampedScrollOffset != scrollOffset())
3920             scrollToOffset(clampedScrollOffset);
3921
3922 #if PLATFORM(IOS_FAMILY)
3923         setAdjustForIOSCaretWhenScrolling(false);
3924 #endif
3925     }
3926
3927     updateScrollbarsAfterLayout();
3928
3929     if (originalScrollOffset != scrollOffset())
3930         scrollToOffsetWithoutAnimation(IntPoint(scrollOffset()));
3931
3932     if (isComposited()) {
3933         setNeedsCompositingGeometryUpdate();
3934         setNeedsCompositingConfigurationUpdate();
3935     }
3936
3937     if (canUseCompositedScrolling())
3938         setNeedsPostLayoutCompositingUpdate();
3939
3940     updateScrollSnapState();
3941 }
3942
3943 bool RenderLayer::overflowControlsIntersectRect(const IntRect& localRect) const
3944 {
3945     const IntRect borderBox = snappedIntRect(renderBox()->borderBoxRect());
3946
3947     if (rectForHorizontalScrollbar(borderBox).intersects(localRect))
3948         return true;
3949
3950     if (rectForVerticalScrollbar(borderBox).intersects(localRect))
3951         return true;
3952
3953     if (scrollCornerRect().intersects(localRect))
3954         return true;
3955     
3956     if (resizerCornerRect(*this, borderBox).intersects(localRect))
3957         return true;
3958
3959     return false;
3960 }
3961
3962 bool RenderLayer::showsOverflowControls() const
3963 {
3964 #if PLATFORM(IOS_FAMILY)
3965     // On iOS, the scrollbars are made in the UI process.
3966     return !canUseCompositedScrolling();
3967 #endif
3968
3969     return true;
3970 }
3971
3972 void RenderLayer::paintOverflowControls(GraphicsContext& context, const IntPoint& paintOffset, const IntRect& damageRect, bool paintingOverlayControls)
3973 {
3974     // Don't do anything if we have no overflow.
3975     if (!renderer().hasOverflowClip())
3976         return;
3977
3978     if (!showsOverflowControls())
3979         return;
3980
3981     // Overlay scrollbars paint in a second pass through the layer tree so that they will paint
3982     // on top of everything else. If this is the normal painting pass, paintingOverlayControls
3983     // will be false, and we should just tell the root layer that there are overlay scrollbars
3984     // that need to be painted. That will cause the second pass through the layer tree to run,
3985     // and we'll paint the scrollbars then. In the meantime, cache tx and ty so that the 
3986     // second pass doesn't need to re-enter the RenderTree to get it right.
3987     if (hasOverlayScrollbars() && !paintingOverlayControls) {
3988         m_cachedOverlayScrollbarOffset = paintOffset;
3989
3990         // It's not necessary to do the second pass if the scrollbars paint into layers.
3991         if ((m_hBar && layerForHorizontalScrollbar()) || (m_vBar && layerForVerticalScrollbar()))
3992             return;
3993         IntRect localDamgeRect = damageRect;
3994         localDamgeRect.moveBy(-paintOffset);
3995         if (!overflowControlsIntersectRect(localDamgeRect))
3996             return;
3997
3998         RenderLayer* paintingRoot