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