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