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