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