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