Use "= default" to denote default constructor or destructor
[WebKit-https.git] / Source / WebCore / rendering / RenderBox.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
5  *           (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
6  * Copyright (C) 2005-2010, 2015 Apple Inc. All rights reserved.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public License
19  * along with this library; see the file COPYING.LIB.  If not, write to
20  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  *
23  */
24
25 #include "config.h"
26 #include "RenderBox.h"
27
28 #include "CSSFontSelector.h"
29 #include "ControlStates.h"
30 #include "Document.h"
31 #include "Editing.h"
32 #include "EventHandler.h"
33 #include "FloatQuad.h"
34 #include "FloatRoundedRect.h"
35 #include "Frame.h"
36 #include "FrameView.h"
37 #include "GraphicsContext.h"
38 #include "HTMLBodyElement.h"
39 #include "HTMLButtonElement.h"
40 #include "HTMLFrameOwnerElement.h"
41 #include "HTMLHtmlElement.h"
42 #include "HTMLImageElement.h"
43 #include "HTMLInputElement.h"
44 #include "HTMLLegendElement.h"
45 #include "HTMLNames.h"
46 #include "HTMLSelectElement.h"
47 #include "HTMLTextAreaElement.h"
48 #include "HitTestResult.h"
49 #include "InlineElementBox.h"
50 #include "MainFrame.h"
51 #include "Page.h"
52 #include "PaintInfo.h"
53 #include "RenderBoxFragmentInfo.h"
54 #include "RenderChildIterator.h"
55 #include "RenderDeprecatedFlexibleBox.h"
56 #include "RenderFlexibleBox.h"
57 #include "RenderFragmentContainer.h"
58 #include "RenderGeometryMap.h"
59 #include "RenderInline.h"
60 #include "RenderIterator.h"
61 #include "RenderLayer.h"
62 #include "RenderLayerCompositor.h"
63 #include "RenderMultiColumnFlow.h"
64 #include "RenderTableCell.h"
65 #include "RenderTheme.h"
66 #include "RenderView.h"
67 #include "RuntimeApplicationChecks.h"
68 #include "ScrollAnimator.h"
69 #include "ScrollbarTheme.h"
70 #include "StyleScrollSnapPoints.h"
71 #include "TransformState.h"
72 #include <algorithm>
73 #include <math.h>
74 #include <wtf/StackStats.h>
75
76 #include "RenderGrid.h"
77
78 #if PLATFORM(IOS)
79 #include "Settings.h"
80 #endif
81
82 namespace WebCore {
83
84 struct SameSizeAsRenderBox : public RenderBoxModelObject {
85     virtual ~SameSizeAsRenderBox() = default;
86     LayoutRect frameRect;
87     LayoutBoxExtent marginBox;
88     LayoutUnit preferredLogicalWidths[2];
89     void* pointers[2];
90 };
91
92 COMPILE_ASSERT(sizeof(RenderBox) == sizeof(SameSizeAsRenderBox), RenderBox_should_stay_small);
93
94 using namespace HTMLNames;
95
96 // Used by flexible boxes when flexing this element and by table cells.
97 typedef WTF::HashMap<const RenderBox*, LayoutUnit> OverrideSizeMap;
98 static OverrideSizeMap* gOverrideHeightMap = nullptr;
99 static OverrideSizeMap* gOverrideWidthMap = nullptr;
100
101 // Used by grid elements to properly size their grid items.
102 typedef WTF::HashMap<const RenderBox*, std::optional<LayoutUnit>> OverrideOptionalSizeMap;
103 static OverrideOptionalSizeMap* gOverrideContainingBlockLogicalHeightMap = nullptr;
104 static OverrideOptionalSizeMap* gOverrideContainingBlockLogicalWidthMap = nullptr;
105
106 // Size of border belt for autoscroll. When mouse pointer in border belt,
107 // autoscroll is started.
108 static const int autoscrollBeltSize = 20;
109 static const unsigned backgroundObscurationTestMaxDepth = 4;
110
111 using ControlStatesRendererMap = HashMap<const RenderObject*, std::unique_ptr<ControlStates>>;
112 static ControlStatesRendererMap& controlStatesRendererMap()
113 {
114     static NeverDestroyed<ControlStatesRendererMap> map;
115     return map;
116 }
117
118 static ControlStates* controlStatesForRenderer(const RenderBox& renderer)
119 {
120     return controlStatesRendererMap().ensure(&renderer, [] {
121         return std::make_unique<ControlStates>();
122     }).iterator->value.get();
123 }
124
125 static void removeControlStatesForRenderer(const RenderBox& renderer)
126 {
127     controlStatesRendererMap().remove(&renderer);
128 }
129
130 bool RenderBox::s_hadOverflowClip = false;
131
132 RenderBox::RenderBox(Element& element, RenderStyle&& style, BaseTypeFlags baseTypeFlags)
133     : RenderBoxModelObject(element, WTFMove(style), baseTypeFlags)
134 {
135     setIsBox();
136 }
137
138 RenderBox::RenderBox(Document& document, RenderStyle&& style, BaseTypeFlags baseTypeFlags)
139     : RenderBoxModelObject(document, WTFMove(style), baseTypeFlags)
140 {
141     setIsBox();
142 }
143
144 RenderBox::~RenderBox()
145 {
146     // Do not add any code here. Add it to willBeDestroyed() instead.
147 }
148
149 void RenderBox::willBeDestroyed()
150 {
151     if (frame().eventHandler().autoscrollRenderer() == this)
152         frame().eventHandler().stopAutoscrollTimer(true);
153
154     clearOverrideSize();
155     clearContainingBlockOverrideSize();
156
157     RenderBlock::removePercentHeightDescendantIfNeeded(*this);
158
159     ShapeOutsideInfo::removeInfo(*this);
160
161     view().unscheduleLazyRepaint(*this);
162     removeControlStatesForRenderer(*this);
163
164 #if ENABLE(CSS_SCROLL_SNAP)
165     if (hasInitializedStyle() && style().scrollSnapArea().hasSnapPosition())
166         view().unregisterBoxWithScrollSnapPositions(*this);
167 #endif
168
169     RenderBoxModelObject::willBeDestroyed();
170 }
171
172 RenderFragmentContainer* RenderBox::clampToStartAndEndFragments(RenderFragmentContainer* fragment) const
173 {
174     RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
175
176     ASSERT(isRenderView() || (fragment && fragmentedFlow));
177     if (isRenderView())
178         return fragment;
179
180     // We need to clamp to the block, since we want any lines or blocks that overflow out of the
181     // logical top or logical bottom of the block to size as though the border box in the first and
182     // last fragments extended infinitely. Otherwise the lines are going to size according to the fragments
183     // they overflow into, which makes no sense when this block doesn't exist in |fragment| at all.
184     RenderFragmentContainer* startFragment = nullptr;
185     RenderFragmentContainer* endFragment = nullptr;
186     if (!fragmentedFlow->getFragmentRangeForBox(this, startFragment, endFragment))
187         return fragment;
188
189     if (fragment->logicalTopForFragmentedFlowContent() < startFragment->logicalTopForFragmentedFlowContent())
190         return startFragment;
191     if (fragment->logicalTopForFragmentedFlowContent() > endFragment->logicalTopForFragmentedFlowContent())
192         return endFragment;
193
194     return fragment;
195 }
196
197 bool RenderBox::hasFragmentRangeInFragmentedFlow() const
198 {
199     RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
200     if (!fragmentedFlow || !fragmentedFlow->hasValidFragmentInfo())
201         return false;
202
203     return fragmentedFlow->hasCachedFragmentRangeForBox(*this);
204 }
205
206 LayoutRect RenderBox::clientBoxRectInFragment(RenderFragmentContainer* fragment) const
207 {
208     if (!fragment)
209         return clientBoxRect();
210
211     LayoutRect clientBox = borderBoxRectInFragment(fragment);
212     clientBox.setLocation(clientBox.location() + LayoutSize(borderLeft(), borderTop()));
213     clientBox.setSize(clientBox.size() - LayoutSize(borderLeft() + borderRight() + verticalScrollbarWidth(), borderTop() + borderBottom() + horizontalScrollbarHeight()));
214
215     return clientBox;
216 }
217
218 LayoutRect RenderBox::borderBoxRectInFragment(RenderFragmentContainer*, RenderBoxFragmentInfoFlags) const
219 {
220     return borderBoxRect();
221 }
222
223 static RenderBlockFlow* outermostBlockContainingFloatingObject(RenderBox& box)
224 {
225     ASSERT(box.isFloating());
226     RenderBlockFlow* parentBlock = nullptr;
227     for (auto& ancestor : ancestorsOfType<RenderBlockFlow>(box)) {
228         if (ancestor.isRenderView())
229             break;
230         if (!parentBlock || ancestor.containsFloat(box))
231             parentBlock = &ancestor;
232     }
233     return parentBlock;
234 }
235
236 void RenderBox::removeFloatingOrPositionedChildFromBlockLists()
237 {
238     ASSERT(isFloatingOrOutOfFlowPositioned());
239
240     if (renderTreeBeingDestroyed())
241         return;
242
243     if (isFloating()) {
244         if (RenderBlockFlow* parentBlock = outermostBlockContainingFloatingObject(*this)) {
245             parentBlock->markSiblingsWithFloatsForLayout(this);
246             parentBlock->markAllDescendantsWithFloatsForLayout(this, false);
247         }
248     }
249
250     if (isOutOfFlowPositioned())
251         RenderBlock::removePositionedObject(*this);
252 }
253
254 void RenderBox::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
255 {
256     s_hadOverflowClip = hasOverflowClip();
257
258     const RenderStyle* oldStyle = hasInitializedStyle() ? &style() : nullptr;
259     if (oldStyle) {
260         // The background of the root element or the body element could propagate up to
261         // the canvas. Issue full repaint, when our style changes substantially.
262         if (diff >= StyleDifferenceRepaint && (isDocumentElementRenderer() || isBody())) {
263             view().repaintRootContents();
264             if (oldStyle->hasEntirelyFixedBackground() != newStyle.hasEntirelyFixedBackground())
265                 view().compositor().rootFixedBackgroundsChanged();
266         }
267         
268         // When a layout hint happens and an object's position style changes, we have to do a layout
269         // to dirty the render tree using the old position value now.
270         if (diff == StyleDifferenceLayout && parent() && oldStyle->position() != newStyle.position()) {
271             markContainingBlocksForLayout();
272             if (oldStyle->position() == StaticPosition)
273                 repaint();
274             else if (newStyle.hasOutOfFlowPosition())
275                 parent()->setChildNeedsLayout();
276             if (isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition())
277                 removeFloatingOrPositionedChildFromBlockLists();
278         }
279     } else if (isBody())
280         view().repaintRootContents();
281
282 #if ENABLE(CSS_SCROLL_SNAP)
283     bool boxContributesSnapPositions = newStyle.scrollSnapArea().hasSnapPosition();
284     if (boxContributesSnapPositions || (oldStyle && oldStyle->scrollSnapArea().hasSnapPosition())) {
285         if (boxContributesSnapPositions)
286             view().registerBoxWithScrollSnapPositions(*this);
287         else
288             view().unregisterBoxWithScrollSnapPositions(*this);
289     }
290 #endif
291
292     RenderBoxModelObject::styleWillChange(diff, newStyle);
293 }
294
295 void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
296 {
297     // Horizontal writing mode definition is updated in RenderBoxModelObject::updateFromStyle,
298     // (as part of the RenderBoxModelObject::styleDidChange call below). So, we can safely cache the horizontal
299     // writing mode value before style change here.
300     bool oldHorizontalWritingMode = isHorizontalWritingMode();
301
302     RenderBoxModelObject::styleDidChange(diff, oldStyle);
303
304     const RenderStyle& newStyle = style();
305     if (needsLayout() && oldStyle) {
306         RenderBlock::removePercentHeightDescendantIfNeeded(*this);
307
308         // Normally we can do optimized positioning layout for absolute/fixed positioned objects. There is one special case, however, which is
309         // when the positioned object's margin-before is changed. In this case the parent has to get a layout in order to run margin collapsing
310         // to determine the new static position.
311         if (isOutOfFlowPositioned() && newStyle.hasStaticBlockPosition(isHorizontalWritingMode()) && oldStyle->marginBefore() != newStyle.marginBefore()
312             && parent() && !parent()->normalChildNeedsLayout())
313             parent()->setChildNeedsLayout();
314     }
315
316     if (RenderBlock::hasPercentHeightContainerMap() && firstChild()
317         && oldHorizontalWritingMode != isHorizontalWritingMode())
318         RenderBlock::clearPercentHeightDescendantsFrom(*this);
319
320     // If our zoom factor changes and we have a defined scrollLeft/Top, we need to adjust that value into the
321     // new zoomed coordinate space.
322     if (hasOverflowClip() && layer() && oldStyle && oldStyle->effectiveZoom() != newStyle.effectiveZoom()) {
323         ScrollPosition scrollPosition = layer()->scrollPosition();
324         float zoomScaleFactor = newStyle.effectiveZoom() / oldStyle->effectiveZoom();
325         scrollPosition.scale(zoomScaleFactor);
326         layer()->setPostLayoutScrollPosition(scrollPosition);
327     }
328
329     // Our opaqueness might have changed without triggering layout.
330     if (diff >= StyleDifferenceRepaint && diff <= StyleDifferenceRepaintLayer) {
331         auto parentToInvalidate = parent();
332         for (unsigned i = 0; i < backgroundObscurationTestMaxDepth && parentToInvalidate; ++i) {
333             parentToInvalidate->invalidateBackgroundObscurationStatus();
334             parentToInvalidate = parentToInvalidate->parent();
335         }
336     }
337
338     bool isBodyRenderer = isBody();
339     bool isDocElementRenderer = isDocumentElementRenderer();
340
341     if (isDocElementRenderer || isBodyRenderer) {
342         // Propagate the new writing mode and direction up to the RenderView.
343         auto* documentElementRenderer = document().documentElement()->renderer();
344         auto& viewStyle = view().mutableStyle();
345         bool rootStyleChanged = false;
346         bool viewDirectionOrWritingModeChanged = false;
347         auto* rootRenderer = isBodyRenderer ? documentElementRenderer : nullptr;
348         if (viewStyle.direction() != newStyle.direction() && (isDocElementRenderer || !documentElementRenderer->style().hasExplicitlySetDirection())) {
349             viewStyle.setDirection(newStyle.direction());
350             viewDirectionOrWritingModeChanged = true;
351             if (isBodyRenderer) {
352                 rootRenderer->mutableStyle().setDirection(newStyle.direction());
353                 rootStyleChanged = true;
354             }
355             setNeedsLayoutAndPrefWidthsRecalc();
356
357             view().frameView().topContentDirectionDidChange();
358         }
359
360         if (viewStyle.writingMode() != newStyle.writingMode() && (isDocElementRenderer || !documentElementRenderer->style().hasExplicitlySetWritingMode())) {
361             viewStyle.setWritingMode(newStyle.writingMode());
362             viewDirectionOrWritingModeChanged = true;
363             view().setHorizontalWritingMode(newStyle.isHorizontalWritingMode());
364             view().markAllDescendantsWithFloatsForLayout();
365             if (isBodyRenderer) {
366                 rootStyleChanged = true;
367                 rootRenderer->mutableStyle().setWritingMode(newStyle.writingMode());
368                 rootRenderer->setHorizontalWritingMode(newStyle.isHorizontalWritingMode());
369             }
370             setNeedsLayoutAndPrefWidthsRecalc();
371         }
372
373         view().frameView().recalculateScrollbarOverlayStyle();
374         
375         const Pagination& pagination = view().frameView().pagination();
376         if (viewDirectionOrWritingModeChanged && pagination.mode != Pagination::Unpaginated) {
377             viewStyle.setColumnStylesFromPaginationMode(pagination.mode);
378             if (view().multiColumnFlow())
379                 view().updateColumnProgressionFromStyle(viewStyle);
380         }
381         
382         if (viewDirectionOrWritingModeChanged && view().multiColumnFlow())
383             view().updateStylesForColumnChildren();
384         
385         if (rootStyleChanged && is<RenderBlockFlow>(rootRenderer) && downcast<RenderBlockFlow>(*rootRenderer).multiColumnFlow())
386             downcast<RenderBlockFlow>(*rootRenderer).updateStylesForColumnChildren();
387         
388         if (isBodyRenderer && pagination.mode != Pagination::Unpaginated && page().paginationLineGridEnabled()) {
389             // Propagate the body font back up to the RenderView and use it as
390             // the basis of the grid.
391             if (newStyle.fontDescription() != view().style().fontDescription()) {
392                 view().mutableStyle().setFontDescription(newStyle.fontDescription());
393                 view().mutableStyle().fontCascade().update(&document().fontSelector());
394             }
395         }
396
397         if (diff != StyleDifferenceEqual)
398             view().compositor().rootOrBodyStyleChanged(*this, oldStyle);
399     }
400
401     if ((oldStyle && oldStyle->shapeOutside()) || style().shapeOutside())
402         updateShapeOutsideInfoAfterStyleChange(style(), oldStyle);
403     updateGridPositionAfterStyleChange(style(), oldStyle);
404 }
405
406 void RenderBox::updateGridPositionAfterStyleChange(const RenderStyle& style, const RenderStyle* oldStyle)
407 {
408     if (!oldStyle || !is<RenderGrid>(parent()))
409         return;
410
411     if (oldStyle->gridItemColumnStart() == style.gridItemColumnStart()
412         && oldStyle->gridItemColumnEnd() == style.gridItemColumnEnd()
413         && oldStyle->gridItemRowStart() == style.gridItemRowStart()
414         && oldStyle->gridItemRowEnd() == style.gridItemRowEnd()
415         && oldStyle->order() == style.order()
416         && oldStyle->hasOutOfFlowPosition() == style.hasOutOfFlowPosition())
417         return;
418
419     // Positioned items don't participate on the layout of the grid,
420     // so we don't need to mark the grid as dirty if they change positions.
421     if (oldStyle->hasOutOfFlowPosition() && style.hasOutOfFlowPosition())
422         return;
423
424     // It should be possible to not dirty the grid in some cases (like moving an
425     // explicitly placed grid item).
426     // For now, it's more simple to just always recompute the grid.
427     downcast<RenderGrid>(*parent()).dirtyGrid();
428 }
429
430 void RenderBox::updateShapeOutsideInfoAfterStyleChange(const RenderStyle& style, const RenderStyle* oldStyle)
431 {
432     const ShapeValue* shapeOutside = style.shapeOutside();
433     const ShapeValue* oldShapeOutside = oldStyle ? oldStyle->shapeOutside() : nullptr;
434
435     Length shapeMargin = style.shapeMargin();
436     Length oldShapeMargin = oldStyle ? oldStyle->shapeMargin() : RenderStyle::initialShapeMargin();
437
438     float shapeImageThreshold = style.shapeImageThreshold();
439     float oldShapeImageThreshold = oldStyle ? oldStyle->shapeImageThreshold() : RenderStyle::initialShapeImageThreshold();
440
441     // FIXME: A future optimization would do a deep comparison for equality. (bug 100811)
442     if (shapeOutside == oldShapeOutside && shapeMargin == oldShapeMargin && shapeImageThreshold == oldShapeImageThreshold)
443         return;
444
445     if (!shapeOutside)
446         ShapeOutsideInfo::removeInfo(*this);
447     else
448         ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
449
450     if (shapeOutside || shapeOutside != oldShapeOutside)
451         markShapeOutsideDependentsForLayout();
452 }
453
454 void RenderBox::updateFromStyle()
455 {
456     RenderBoxModelObject::updateFromStyle();
457
458     const RenderStyle& styleToUse = style();
459     bool isDocElementRenderer = isDocumentElementRenderer();
460     bool isViewObject = isRenderView();
461
462     // The root and the RenderView always paint their backgrounds/borders.
463     if (isDocElementRenderer || isViewObject)
464         setHasVisibleBoxDecorations(true);
465
466     setFloating(!isOutOfFlowPositioned() && styleToUse.isFloating());
467
468     // We also handle <body> and <html>, whose overflow applies to the viewport.
469     if (styleToUse.overflowX() != OVISIBLE && !isDocElementRenderer && isRenderBlock()) {
470         bool boxHasOverflowClip = true;
471         if (isBody()) {
472             // Overflow on the body can propagate to the viewport under the following conditions.
473             // (1) The root element is <html>.
474             // (2) We are the primary <body> (can be checked by looking at document.body).
475             // (3) The root element has visible overflow.
476             if (is<HTMLHtmlElement>(*document().documentElement())
477                 && document().body() == element()
478                 && document().documentElement()->renderer()->style().overflowX() == OVISIBLE) {
479                 boxHasOverflowClip = false;
480             }
481         }
482         // Check for overflow clip.
483         // It's sufficient to just check one direction, since it's illegal to have visible on only one overflow value.
484         if (boxHasOverflowClip) {
485             if (!s_hadOverflowClip && hasRenderOverflow()) {
486                 // Erase the overflow.
487                 // Overflow changes have to result in immediate repaints of the entire layout overflow area because
488                 // repaints issued by removal of descendants get clipped using the updated style when they shouldn't.
489                 repaintRectangle(visualOverflowRect());
490                 repaintRectangle(layoutOverflowRect());
491             }
492             setHasOverflowClip();
493         }
494     }
495     setHasTransformRelatedProperty(styleToUse.hasTransformRelatedProperty());
496     setHasReflection(styleToUse.boxReflect());
497 }
498
499 void RenderBox::layout()
500 {
501     StackStats::LayoutCheckPoint layoutCheckPoint;
502     ASSERT(needsLayout());
503
504     RenderObject* child = firstChild();
505     if (!child) {
506         clearNeedsLayout();
507         return;
508     }
509
510     LayoutStateMaintainer statePusher(view(), *this, locationOffset(), style().isFlippedBlocksWritingMode());
511     while (child) {
512         if (child->needsLayout())
513             downcast<RenderElement>(*child).layout();
514         ASSERT(!child->needsLayout());
515         child = child->nextSibling();
516     }
517     statePusher.pop();
518     invalidateBackgroundObscurationStatus();
519     clearNeedsLayout();
520 }
521
522 // More IE extensions.  clientWidth and clientHeight represent the interior of an object
523 // excluding border and scrollbar.
524 LayoutUnit RenderBox::clientWidth() const
525 {
526     return width() - borderLeft() - borderRight() - verticalScrollbarWidth();
527 }
528
529 LayoutUnit RenderBox::clientHeight() const
530 {
531     return height() - borderTop() - borderBottom() - horizontalScrollbarHeight();
532 }
533
534 int RenderBox::scrollWidth() const
535 {
536     if (hasOverflowClip() && layer())
537         return layer()->scrollWidth();
538     // For objects with visible overflow, this matches IE.
539     // FIXME: Need to work right with writing modes.
540     if (style().isLeftToRightDirection()) {
541         // FIXME: This should use snappedIntSize() instead with absolute coordinates.
542         return roundToInt(std::max(clientWidth(), layoutOverflowRect().maxX() - borderLeft()));
543     }
544     return roundToInt(clientWidth() - std::min<LayoutUnit>(0, layoutOverflowRect().x() - borderLeft()));
545 }
546
547 int RenderBox::scrollHeight() const
548 {
549     if (hasOverflowClip() && layer())
550         return layer()->scrollHeight();
551     // For objects with visible overflow, this matches IE.
552     // FIXME: Need to work right with writing modes.
553     // FIXME: This should use snappedIntSize() instead with absolute coordinates.
554     return roundToInt(std::max(clientHeight(), layoutOverflowRect().maxY() - borderTop()));
555 }
556
557 int RenderBox::scrollLeft() const
558 {
559     return hasOverflowClip() && layer() ? layer()->scrollPosition().x() : 0;
560 }
561
562 int RenderBox::scrollTop() const
563 {
564     return hasOverflowClip() && layer() ? layer()->scrollPosition().y() : 0;
565 }
566
567 static void setupWheelEventTestTrigger(RenderLayer& layer)
568 {
569     Page& page = layer.renderer().page();
570     if (!page.expectsWheelEventTriggers())
571         return;
572     layer.scrollAnimator().setWheelEventTestTrigger(page.testTrigger());
573 }
574
575 void RenderBox::setScrollLeft(int newLeft)
576 {
577     if (!hasOverflowClip() || !layer())
578         return;
579     setupWheelEventTestTrigger(*layer());
580     layer()->scrollToXPosition(newLeft, RenderLayer::ScrollOffsetClamped);
581 }
582
583 void RenderBox::setScrollTop(int newTop)
584 {
585     if (!hasOverflowClip() || !layer())
586         return;
587     setupWheelEventTestTrigger(*layer());
588     layer()->scrollToYPosition(newTop, RenderLayer::ScrollOffsetClamped);
589 }
590
591 void RenderBox::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
592 {
593     rects.append(snappedIntRect(accumulatedOffset, size()));
594 }
595
596 void RenderBox::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
597 {
598     FloatRect localRect(0, 0, width(), height());
599
600     RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
601     if (fragmentedFlow && fragmentedFlow->absoluteQuadsForBox(quads, wasFixed, this, localRect.y(), localRect.maxY()))
602         return;
603
604     quads.append(localToAbsoluteQuad(localRect, UseTransforms, wasFixed));
605 }
606
607 void RenderBox::updateLayerTransform()
608 {
609     // Transform-origin depends on box size, so we need to update the layer transform after layout.
610     if (hasLayer())
611         layer()->updateTransform();
612 }
613
614 LayoutUnit RenderBox::constrainLogicalWidthInFragmentByMinMax(LayoutUnit logicalWidth, LayoutUnit availableWidth, RenderBlock& cb, RenderFragmentContainer* fragment) const
615 {
616     const RenderStyle& styleToUse = style();
617     if (!styleToUse.logicalMaxWidth().isUndefined())
618         logicalWidth = std::min(logicalWidth, computeLogicalWidthInFragmentUsing(MaxSize, styleToUse.logicalMaxWidth(), availableWidth, cb, fragment));
619     return std::max(logicalWidth, computeLogicalWidthInFragmentUsing(MinSize, styleToUse.logicalMinWidth(), availableWidth, cb, fragment));
620 }
621
622 LayoutUnit RenderBox::constrainLogicalHeightByMinMax(LayoutUnit logicalHeight, std::optional<LayoutUnit> intrinsicContentHeight) const
623 {
624     const RenderStyle& styleToUse = style();
625     if (!styleToUse.logicalMaxHeight().isUndefined()) {
626         if (std::optional<LayoutUnit> maxH = computeLogicalHeightUsing(MaxSize, styleToUse.logicalMaxHeight(), intrinsicContentHeight))
627             logicalHeight = std::min(logicalHeight, maxH.value());
628     }
629     if (std::optional<LayoutUnit> computedLogicalHeight = computeLogicalHeightUsing(MinSize, styleToUse.logicalMinHeight(), intrinsicContentHeight))
630         return std::max(logicalHeight, computedLogicalHeight.value());
631     return logicalHeight;
632 }
633
634 LayoutUnit RenderBox::constrainContentBoxLogicalHeightByMinMax(LayoutUnit logicalHeight, std::optional<LayoutUnit> intrinsicContentHeight) const
635 {
636     const RenderStyle& styleToUse = style();
637     if (!styleToUse.logicalMaxHeight().isUndefined()) {
638         if (std::optional<LayoutUnit> maxH = computeContentLogicalHeight(MaxSize, styleToUse.logicalMaxHeight(), intrinsicContentHeight))
639             logicalHeight = std::min(logicalHeight, maxH.value());
640     }
641     if (std::optional<LayoutUnit> computedContentLogicalHeight = computeContentLogicalHeight(MinSize, styleToUse.logicalMinHeight(), intrinsicContentHeight))
642         return std::max(logicalHeight, computedContentLogicalHeight.value());
643     return logicalHeight;
644 }
645
646 RoundedRect::Radii RenderBox::borderRadii() const
647 {
648     auto& style = this->style();
649     LayoutRect bounds = frameRect();
650
651     unsigned borderLeft = style.borderLeftWidth();
652     unsigned borderTop = style.borderTopWidth();
653     bounds.moveBy(LayoutPoint(borderLeft, borderTop));
654     bounds.contract(borderLeft + style.borderRightWidth(), borderTop + style.borderBottomWidth());
655     return style.getRoundedBorderFor(bounds).radii();
656 }
657
658 LayoutRect RenderBox::contentBoxRect() const
659 {
660     LayoutUnit x = borderLeft() + paddingLeft();
661     if (shouldPlaceBlockDirectionScrollbarOnLeft())
662         x += verticalScrollbarWidth();
663     LayoutUnit y = borderTop() + paddingTop();
664     return LayoutRect(x, y, contentWidth(), contentHeight());
665 }
666
667 IntRect RenderBox::absoluteContentBox() const
668 {
669     // This is wrong with transforms and flipped writing modes.
670     IntRect rect = snappedIntRect(contentBoxRect());
671     FloatPoint absPos = localToAbsolute();
672     rect.move(absPos.x(), absPos.y());
673     return rect;
674 }
675
676 FloatQuad RenderBox::absoluteContentQuad() const
677 {
678     LayoutRect rect = contentBoxRect();
679     return localToAbsoluteQuad(FloatRect(rect));
680 }
681
682 LayoutRect RenderBox::outlineBoundsForRepaint(const RenderLayerModelObject* repaintContainer, const RenderGeometryMap* geometryMap) const
683 {
684     LayoutRect box = borderBoundingBox();
685     adjustRectForOutlineAndShadow(box);
686
687     if (repaintContainer != this) {
688         FloatQuad containerRelativeQuad;
689         if (geometryMap)
690             containerRelativeQuad = geometryMap->mapToContainer(box, repaintContainer);
691         else
692             containerRelativeQuad = localToContainerQuad(FloatRect(box), repaintContainer);
693
694         box = LayoutRect(containerRelativeQuad.boundingBox());
695     }
696     
697     // FIXME: layoutDelta needs to be applied in parts before/after transforms and
698     // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
699     box.move(view().layoutDelta());
700
701     return LayoutRect(snapRectToDevicePixels(box, document().deviceScaleFactor()));
702 }
703
704 void RenderBox::addFocusRingRects(Vector<LayoutRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject*)
705 {
706     if (!size().isEmpty())
707         rects.append(LayoutRect(additionalOffset, size()));
708 }
709
710 int RenderBox::reflectionOffset() const
711 {
712     if (!style().boxReflect())
713         return 0;
714     if (style().boxReflect()->direction() == ReflectionLeft || style().boxReflect()->direction() == ReflectionRight)
715         return valueForLength(style().boxReflect()->offset(), borderBoxRect().width());
716     return valueForLength(style().boxReflect()->offset(), borderBoxRect().height());
717 }
718
719 LayoutRect RenderBox::reflectedRect(const LayoutRect& r) const
720 {
721     if (!style().boxReflect())
722         return LayoutRect();
723
724     LayoutRect box = borderBoxRect();
725     LayoutRect result = r;
726     switch (style().boxReflect()->direction()) {
727         case ReflectionBelow:
728             result.setY(box.maxY() + reflectionOffset() + (box.maxY() - r.maxY()));
729             break;
730         case ReflectionAbove:
731             result.setY(box.y() - reflectionOffset() - box.height() + (box.maxY() - r.maxY()));
732             break;
733         case ReflectionLeft:
734             result.setX(box.x() - reflectionOffset() - box.width() + (box.maxX() - r.maxX()));
735             break;
736         case ReflectionRight:
737             result.setX(box.maxX() + reflectionOffset() + (box.maxX() - r.maxX()));
738             break;
739     }
740     return result;
741 }
742
743 bool RenderBox::fixedElementLaysOutRelativeToFrame(const FrameView& frameView) const
744 {
745     return style().position() == FixedPosition && container()->isRenderView() && frameView.fixedElementsLayoutRelativeToFrame();
746 }
747
748 bool RenderBox::includeVerticalScrollbarSize() const
749 {
750     return hasOverflowClip() && layer() && !layer()->hasOverlayScrollbars()
751         && (style().overflowY() == OSCROLL || style().overflowY() == OAUTO);
752 }
753
754 bool RenderBox::includeHorizontalScrollbarSize() const
755 {
756     return hasOverflowClip() && layer() && !layer()->hasOverlayScrollbars()
757         && (style().overflowX() == OSCROLL || style().overflowX() == OAUTO);
758 }
759
760 int RenderBox::verticalScrollbarWidth() const
761 {
762     return includeVerticalScrollbarSize() ? layer()->verticalScrollbarWidth() : 0;
763 }
764
765 int RenderBox::horizontalScrollbarHeight() const
766 {
767     return includeHorizontalScrollbarSize() ? layer()->horizontalScrollbarHeight() : 0;
768 }
769
770 int RenderBox::intrinsicScrollbarLogicalWidth() const
771 {
772     if (!hasOverflowClip())
773         return 0;
774
775     if (isHorizontalWritingMode() && (style().overflowY() == OSCROLL && !hasVerticalScrollbarWithAutoBehavior())) {
776         ASSERT(layer() && layer()->hasVerticalScrollbar());
777         return verticalScrollbarWidth();
778     }
779
780     if (!isHorizontalWritingMode() && (style().overflowX() == OSCROLL && !hasHorizontalScrollbarWithAutoBehavior())) {
781         ASSERT(layer() && layer()->hasHorizontalScrollbar());
782         return horizontalScrollbarHeight();
783     }
784
785     return 0;
786 }
787
788 bool RenderBox::scrollLayer(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement)
789 {
790     RenderLayer* boxLayer = layer();
791     if (boxLayer && boxLayer->scroll(direction, granularity, multiplier)) {
792         if (stopElement)
793             *stopElement = element();
794
795         return true;
796     }
797
798     return false;
799 }
800
801 bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement, RenderBox* startBox, const IntPoint& wheelEventAbsolutePoint)
802 {
803     if (scrollLayer(direction, granularity, multiplier, stopElement))
804         return true;
805
806     if (stopElement && *stopElement && *stopElement == element())
807         return true;
808
809     RenderBlock* nextScrollBlock = containingBlock();
810
811     if (nextScrollBlock && !nextScrollBlock->isRenderView())
812         return nextScrollBlock->scroll(direction, granularity, multiplier, stopElement, startBox, wheelEventAbsolutePoint);
813
814     return false;
815 }
816
817 bool RenderBox::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement)
818 {
819     bool scrolled = false;
820     
821     RenderLayer* l = layer();
822     if (l) {
823 #if PLATFORM(COCOA)
824         // On Mac only we reset the inline direction position when doing a document scroll (e.g., hitting Home/End).
825         if (granularity == ScrollByDocument)
826             scrolled = l->scroll(logicalToPhysical(ScrollInlineDirectionBackward, isHorizontalWritingMode(), style().isFlippedBlocksWritingMode()), ScrollByDocument, multiplier);
827 #endif
828         if (l->scroll(logicalToPhysical(direction, isHorizontalWritingMode(), style().isFlippedBlocksWritingMode()), granularity, multiplier))
829             scrolled = true;
830         
831         if (scrolled) {
832             if (stopElement)
833                 *stopElement = element();
834             return true;
835         }
836     }
837
838     if (stopElement && *stopElement && *stopElement == element())
839         return true;
840
841     RenderBlock* b = containingBlock();
842     if (b && !b->isRenderView())
843         return b->logicalScroll(direction, granularity, multiplier, stopElement);
844     return false;
845 }
846
847 bool RenderBox::canBeScrolledAndHasScrollableArea() const
848 {
849     return canBeProgramaticallyScrolled() && (hasHorizontalOverflow() || hasVerticalOverflow());
850 }
851
852 bool RenderBox::isScrollableOrRubberbandableBox() const
853 {
854     return canBeScrolledAndHasScrollableArea();
855 }
856
857 // FIXME: This is badly named. overflow:hidden can be programmatically scrolled, yet this returns false in that case.
858 bool RenderBox::canBeProgramaticallyScrolled() const
859 {
860     if (isRenderView())
861         return true;
862
863     if (!hasOverflowClip())
864         return false;
865
866     if (hasScrollableOverflowX() || hasScrollableOverflowY())
867         return true;
868
869     return element() && element()->hasEditableStyle();
870 }
871
872 bool RenderBox::usesCompositedScrolling() const
873 {
874     return hasOverflowClip() && hasLayer() && layer()->usesCompositedScrolling();
875 }
876
877 void RenderBox::autoscroll(const IntPoint& position)
878 {
879     if (layer())
880         layer()->autoscroll(position);
881 }
882
883 // There are two kinds of renderer that can autoscroll.
884 bool RenderBox::canAutoscroll() const
885 {
886     if (isRenderView())
887         return view().frameView().isScrollable();
888
889     // Check for a box that can be scrolled in its own right.
890     if (canBeScrolledAndHasScrollableArea())
891         return true;
892
893     return false;
894 }
895
896 // If specified point is in border belt, returned offset denotes direction of
897 // scrolling.
898 IntSize RenderBox::calculateAutoscrollDirection(const IntPoint& windowPoint) const
899 {
900     IntRect box(absoluteBoundingBoxRect());
901     box.moveBy(view().frameView().scrollPosition());
902     IntRect windowBox = view().frameView().contentsToWindow(box);
903
904     IntPoint windowAutoscrollPoint = windowPoint;
905
906     if (windowAutoscrollPoint.x() < windowBox.x() + autoscrollBeltSize)
907         windowAutoscrollPoint.move(-autoscrollBeltSize, 0);
908     else if (windowAutoscrollPoint.x() > windowBox.maxX() - autoscrollBeltSize)
909         windowAutoscrollPoint.move(autoscrollBeltSize, 0);
910
911     if (windowAutoscrollPoint.y() < windowBox.y() + autoscrollBeltSize)
912         windowAutoscrollPoint.move(0, -autoscrollBeltSize);
913     else if (windowAutoscrollPoint.y() > windowBox.maxY() - autoscrollBeltSize)
914         windowAutoscrollPoint.move(0, autoscrollBeltSize);
915
916     return windowAutoscrollPoint - windowPoint;
917 }
918
919 RenderBox* RenderBox::findAutoscrollable(RenderObject* renderer)
920 {
921     while (renderer && !(is<RenderBox>(*renderer) && downcast<RenderBox>(*renderer).canAutoscroll())) {
922         if (is<RenderView>(*renderer) && renderer->document().ownerElement())
923             renderer = renderer->document().ownerElement()->renderer();
924         else
925             renderer = renderer->parent();
926     }
927
928     return is<RenderBox>(renderer) ? downcast<RenderBox>(renderer) : nullptr;
929 }
930
931 void RenderBox::panScroll(const IntPoint& source)
932 {
933     if (layer())
934         layer()->panScrollFromPoint(source);
935 }
936
937 bool RenderBox::hasVerticalScrollbarWithAutoBehavior() const
938 {
939     bool overflowScrollActsLikeAuto = style().overflowY() == OSCROLL && !style().hasPseudoStyle(SCROLLBAR) && ScrollbarTheme::theme().usesOverlayScrollbars();
940     return hasOverflowClip() && (style().overflowY() == OAUTO || style().overflowY() == OOVERLAY || overflowScrollActsLikeAuto);
941 }
942
943 bool RenderBox::hasHorizontalScrollbarWithAutoBehavior() const
944 {
945     bool overflowScrollActsLikeAuto = style().overflowX() == OSCROLL && !style().hasPseudoStyle(SCROLLBAR) && ScrollbarTheme::theme().usesOverlayScrollbars();
946     return hasOverflowClip() && (style().overflowX() == OAUTO || style().overflowX() == OOVERLAY || overflowScrollActsLikeAuto);
947 }
948
949 bool RenderBox::needsPreferredWidthsRecalculation() const
950 {
951     return style().paddingStart().isPercentOrCalculated() || style().paddingEnd().isPercentOrCalculated();
952 }
953
954 ScrollPosition RenderBox::scrollPosition() const
955 {
956     if (!hasOverflowClip())
957         return { 0, 0 };
958
959     ASSERT(hasLayer());
960     return layer()->scrollPosition();
961 }
962
963 LayoutSize RenderBox::cachedSizeForOverflowClip() const
964 {
965     ASSERT(hasOverflowClip());
966     ASSERT(hasLayer());
967     return layer()->size();
968 }
969
970 void RenderBox::applyCachedClipAndScrollPositionForRepaint(LayoutRect& paintRect) const
971 {
972     flipForWritingMode(paintRect);
973     paintRect.moveBy(-scrollPosition()); // For overflow:auto/scroll/hidden.
974
975     // Do not clip scroll layer contents to reduce the number of repaints while scrolling.
976     if (usesCompositedScrolling()) {
977         flipForWritingMode(paintRect);
978         return;
979     }
980
981     // height() is inaccurate if we're in the middle of a layout of this RenderBox, so use the
982     // layer's size instead. Even if the layer's size is wrong, the layer itself will repaint
983     // anyway if its size does change.
984     LayoutRect clipRect(LayoutPoint(), cachedSizeForOverflowClip());
985     paintRect = intersection(paintRect, clipRect);
986     flipForWritingMode(paintRect);
987 }
988
989 void RenderBox::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
990 {
991     minLogicalWidth = minPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
992     maxLogicalWidth = maxPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
993 }
994
995 LayoutUnit RenderBox::minPreferredLogicalWidth() const
996 {
997     if (preferredLogicalWidthsDirty()) {
998 #ifndef NDEBUG
999         SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox*>(this));
1000 #endif
1001         const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
1002     }
1003         
1004     return m_minPreferredLogicalWidth;
1005 }
1006
1007 LayoutUnit RenderBox::maxPreferredLogicalWidth() const
1008 {
1009     if (preferredLogicalWidthsDirty()) {
1010 #ifndef NDEBUG
1011         SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox*>(this));
1012 #endif
1013         const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
1014     }
1015         
1016     return m_maxPreferredLogicalWidth;
1017 }
1018
1019 bool RenderBox::hasOverrideLogicalContentHeight() const
1020 {
1021     return gOverrideHeightMap && gOverrideHeightMap->contains(this);
1022 }
1023
1024 bool RenderBox::hasOverrideLogicalContentWidth() const
1025 {
1026     return gOverrideWidthMap && gOverrideWidthMap->contains(this);
1027 }
1028
1029 void RenderBox::setOverrideLogicalContentHeight(LayoutUnit height)
1030 {
1031     if (!gOverrideHeightMap)
1032         gOverrideHeightMap = new OverrideSizeMap();
1033     gOverrideHeightMap->set(this, height);
1034 }
1035
1036 void RenderBox::setOverrideLogicalContentWidth(LayoutUnit width)
1037 {
1038     if (!gOverrideWidthMap)
1039         gOverrideWidthMap = new OverrideSizeMap();
1040     gOverrideWidthMap->set(this, width);
1041 }
1042
1043 void RenderBox::clearOverrideLogicalContentHeight()
1044 {
1045     if (gOverrideHeightMap)
1046         gOverrideHeightMap->remove(this);
1047 }
1048
1049 void RenderBox::clearOverrideLogicalContentWidth()
1050 {
1051     if (gOverrideWidthMap)
1052         gOverrideWidthMap->remove(this);
1053 }
1054
1055 void RenderBox::clearOverrideSize()
1056 {
1057     clearOverrideLogicalContentHeight();
1058     clearOverrideLogicalContentWidth();
1059 }
1060
1061 LayoutUnit RenderBox::overrideLogicalContentWidth() const
1062 {
1063     ASSERT(hasOverrideLogicalContentWidth());
1064     return gOverrideWidthMap->get(this);
1065 }
1066
1067 LayoutUnit RenderBox::overrideLogicalContentHeight() const
1068 {
1069     ASSERT(hasOverrideLogicalContentHeight());
1070     return gOverrideHeightMap->get(this);
1071 }
1072
1073 std::optional<LayoutUnit> RenderBox::overrideContainingBlockContentLogicalWidth() const
1074 {
1075     ASSERT(hasOverrideContainingBlockLogicalWidth());
1076     return gOverrideContainingBlockLogicalWidthMap->get(this);
1077 }
1078
1079 std::optional<LayoutUnit> RenderBox::overrideContainingBlockContentLogicalHeight() const
1080 {
1081     ASSERT(hasOverrideContainingBlockLogicalHeight());
1082     return gOverrideContainingBlockLogicalHeightMap->get(this);
1083 }
1084
1085 bool RenderBox::hasOverrideContainingBlockLogicalWidth() const
1086 {
1087     return gOverrideContainingBlockLogicalWidthMap && gOverrideContainingBlockLogicalWidthMap->contains(this);
1088 }
1089
1090 bool RenderBox::hasOverrideContainingBlockLogicalHeight() const
1091 {
1092     return gOverrideContainingBlockLogicalHeightMap && gOverrideContainingBlockLogicalHeightMap->contains(this);
1093 }
1094
1095 void RenderBox::setOverrideContainingBlockContentLogicalWidth(std::optional<LayoutUnit> logicalWidth)
1096 {
1097     if (!gOverrideContainingBlockLogicalWidthMap)
1098         gOverrideContainingBlockLogicalWidthMap = new OverrideOptionalSizeMap;
1099     gOverrideContainingBlockLogicalWidthMap->set(this, logicalWidth);
1100 }
1101
1102 void RenderBox::setOverrideContainingBlockContentLogicalHeight(std::optional<LayoutUnit> logicalHeight)
1103 {
1104     if (!gOverrideContainingBlockLogicalHeightMap)
1105         gOverrideContainingBlockLogicalHeightMap = new OverrideOptionalSizeMap;
1106     gOverrideContainingBlockLogicalHeightMap->set(this, logicalHeight);
1107 }
1108
1109 void RenderBox::clearContainingBlockOverrideSize()
1110 {
1111     if (gOverrideContainingBlockLogicalWidthMap)
1112         gOverrideContainingBlockLogicalWidthMap->remove(this);
1113     clearOverrideContainingBlockContentLogicalHeight();
1114 }
1115
1116 void RenderBox::clearOverrideContainingBlockContentLogicalHeight()
1117 {
1118     if (gOverrideContainingBlockLogicalHeightMap)
1119         gOverrideContainingBlockLogicalHeightMap->remove(this);
1120 }
1121
1122 LayoutUnit RenderBox::adjustBorderBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1123 {
1124     LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
1125     if (style().boxSizing() == CONTENT_BOX)
1126         return width + bordersPlusPadding;
1127     return std::max(width, bordersPlusPadding);
1128 }
1129
1130 LayoutUnit RenderBox::adjustBorderBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1131 {
1132     LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
1133     if (style().boxSizing() == CONTENT_BOX)
1134         return height + bordersPlusPadding;
1135     return std::max(height, bordersPlusPadding);
1136 }
1137
1138 LayoutUnit RenderBox::adjustContentBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1139 {
1140     if (style().boxSizing() == BORDER_BOX)
1141         width -= borderAndPaddingLogicalWidth();
1142     return std::max<LayoutUnit>(0, width);
1143 }
1144
1145 LayoutUnit RenderBox::adjustContentBoxLogicalHeightForBoxSizing(std::optional<LayoutUnit> height) const
1146 {
1147     if (!height)
1148         return 0;
1149     LayoutUnit result = height.value();
1150     if (style().boxSizing() == BORDER_BOX)
1151         result -= borderAndPaddingLogicalHeight();
1152     return std::max(LayoutUnit(), result);
1153 }
1154
1155 // Hit Testing
1156 bool RenderBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
1157 {
1158     LayoutPoint adjustedLocation = accumulatedOffset + location();
1159
1160     // Check kids first.
1161     for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
1162         if (!child->hasLayer() && child->nodeAtPoint(request, result, locationInContainer, adjustedLocation, action)) {
1163             updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1164             return true;
1165         }
1166     }
1167
1168     // Check our bounds next. For this purpose always assume that we can only be hit in the
1169     // foreground phase (which is true for replaced elements like images).
1170     LayoutRect boundsRect = borderBoxRectInFragment(nullptr);
1171     boundsRect.moveBy(adjustedLocation);
1172     if (visibleToHitTesting() && action == HitTestForeground && locationInContainer.intersects(boundsRect)) {
1173         updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1174         if (result.addNodeToListBasedTestResult(element(), request, locationInContainer, boundsRect) == HitTestProgress::Stop)
1175             return true;
1176     }
1177
1178     return false;
1179 }
1180
1181 // --------------------- painting stuff -------------------------------
1182
1183 void RenderBox::paintRootBoxFillLayers(const PaintInfo& paintInfo)
1184 {
1185     ASSERT(isDocumentElementRenderer());
1186     if (paintInfo.skipRootBackground())
1187         return;
1188
1189     auto* rootBackgroundRenderer = view().rendererForRootBackground();
1190     if (!rootBackgroundRenderer)
1191         return;
1192
1193     auto& style = rootBackgroundRenderer->style();
1194     auto color = style.visitedDependentColor(CSSPropertyBackgroundColor);
1195     paintFillLayers(paintInfo, color, style.backgroundLayers(), view().backgroundRect(), BackgroundBleedNone, CompositeSourceOver, rootBackgroundRenderer);
1196 }
1197
1198 BackgroundBleedAvoidance RenderBox::determineBackgroundBleedAvoidance(GraphicsContext& context) const
1199 {
1200     if (context.paintingDisabled())
1201         return BackgroundBleedNone;
1202
1203     const RenderStyle& style = this->style();
1204
1205     if (!style.hasBackground() || !style.hasBorder() || !style.hasBorderRadius() || borderImageIsLoadedAndCanBeRendered())
1206         return BackgroundBleedNone;
1207
1208     AffineTransform ctm = context.getCTM();
1209     FloatSize contextScaling(static_cast<float>(ctm.xScale()), static_cast<float>(ctm.yScale()));
1210
1211     // Because RoundedRect uses IntRect internally the inset applied by the 
1212     // BackgroundBleedShrinkBackground strategy cannot be less than one integer
1213     // layout coordinate, even with subpixel layout enabled. To take that into
1214     // account, we clamp the contextScaling to 1.0 for the following test so
1215     // that borderObscuresBackgroundEdge can only return true if the border
1216     // widths are greater than 2 in both layout coordinates and screen
1217     // coordinates.
1218     // This precaution will become obsolete if RoundedRect is ever promoted to
1219     // a sub-pixel representation.
1220     if (contextScaling.width() > 1) 
1221         contextScaling.setWidth(1);
1222     if (contextScaling.height() > 1) 
1223         contextScaling.setHeight(1);
1224
1225     if (borderObscuresBackgroundEdge(contextScaling))
1226         return BackgroundBleedShrinkBackground;
1227     if (!style.hasAppearance() && borderObscuresBackground() && backgroundHasOpaqueTopLayer())
1228         return BackgroundBleedBackgroundOverBorder;
1229
1230     return BackgroundBleedUseTransparencyLayer;
1231 }
1232
1233 void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1234 {
1235     if (!paintInfo.shouldPaintWithinRoot(*this))
1236         return;
1237
1238     LayoutRect paintRect = borderBoxRectInFragment(nullptr);
1239     paintRect.moveBy(paintOffset);
1240     adjustBorderBoxRectForPainting(paintRect);
1241
1242 #if PLATFORM(IOS)
1243     // Workaround for <rdar://problem/6209763>. Force the painting bounds of checkboxes and radio controls to be square.
1244     if (style().appearance() == CheckboxPart || style().appearance() == RadioPart) {
1245         int width = std::min(paintRect.width(), paintRect.height());
1246         int height = width;
1247         paintRect = IntRect(paintRect.x(), paintRect.y() + (this->height() - height) / 2, width, height); // Vertically center the checkbox, like on desktop
1248     }
1249 #endif
1250     BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context());
1251
1252     // FIXME: Should eventually give the theme control over whether the box shadow should paint, since controls could have
1253     // custom shadows of their own.
1254     if (!boxShadowShouldBeAppliedToBackground(paintRect.location(), bleedAvoidance))
1255         paintBoxShadow(paintInfo, paintRect, style(), Normal);
1256
1257     GraphicsContextStateSaver stateSaver(paintInfo.context(), false);
1258     if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
1259         // To avoid the background color bleeding out behind the border, we'll render background and border
1260         // into a transparency layer, and then clip that in one go (which requires setting up the clip before
1261         // beginning the layer).
1262         stateSaver.save();
1263         paintInfo.context().clipRoundedRect(style().getRoundedBorderFor(paintRect).pixelSnappedRoundedRectForPainting(document().deviceScaleFactor()));
1264         paintInfo.context().beginTransparencyLayer(1);
1265     }
1266
1267     // If we have a native theme appearance, paint that before painting our background.
1268     // The theme will tell us whether or not we should also paint the CSS background.
1269     bool borderOrBackgroundPaintingIsNeeded = true;
1270     if (style().hasAppearance()) {
1271         ControlStates* controlStates = controlStatesForRenderer(*this);
1272         borderOrBackgroundPaintingIsNeeded = theme().paint(*this, *controlStates, paintInfo, paintRect);
1273         if (controlStates->needsRepaint())
1274             view().scheduleLazyRepaint(*this);
1275     }
1276
1277     if (borderOrBackgroundPaintingIsNeeded) {
1278         if (bleedAvoidance == BackgroundBleedBackgroundOverBorder)
1279             paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1280
1281         paintBackground(paintInfo, paintRect, bleedAvoidance);
1282
1283         if (style().hasAppearance())
1284             theme().paintDecorations(*this, paintInfo, paintRect);
1285     }
1286     paintBoxShadow(paintInfo, paintRect, style(), Inset);
1287
1288     // The theme will tell us whether or not we should also paint the CSS border.
1289     if (bleedAvoidance != BackgroundBleedBackgroundOverBorder && (!style().hasAppearance() || (borderOrBackgroundPaintingIsNeeded && theme().paintBorderOnly(*this, paintInfo, paintRect))) && style().hasVisibleBorderDecoration())
1290         paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1291
1292     if (bleedAvoidance == BackgroundBleedUseTransparencyLayer)
1293         paintInfo.context().endTransparencyLayer();
1294 }
1295
1296 bool RenderBox::paintsOwnBackground() const
1297 {
1298     if (isBody()) {
1299         // The <body> only paints its background if the root element has defined a background independent of the body,
1300         // or if the <body>'s parent is not the document element's renderer (e.g. inside SVG foreignObject).
1301         auto documentElementRenderer = document().documentElement()->renderer();
1302         return !documentElementRenderer
1303             || documentElementRenderer->hasBackground()
1304             || (documentElementRenderer != parent());
1305     }
1306     
1307     return true;
1308 }
1309
1310 void RenderBox::paintBackground(const PaintInfo& paintInfo, const LayoutRect& paintRect, BackgroundBleedAvoidance bleedAvoidance)
1311 {
1312     if (isDocumentElementRenderer()) {
1313         paintRootBoxFillLayers(paintInfo);
1314         return;
1315     }
1316
1317     if (!paintsOwnBackground())
1318         return;
1319
1320     if (backgroundIsKnownToBeObscured(paintRect.location()) && !boxShadowShouldBeAppliedToBackground(paintRect.location(), bleedAvoidance))
1321         return;
1322
1323     paintFillLayers(paintInfo, style().visitedDependentColor(CSSPropertyBackgroundColor), style().backgroundLayers(), paintRect, bleedAvoidance);
1324 }
1325
1326 bool RenderBox::getBackgroundPaintedExtent(const LayoutPoint& paintOffset, LayoutRect& paintedExtent) const
1327 {
1328     ASSERT(hasBackground());
1329     LayoutRect backgroundRect = snappedIntRect(borderBoxRect());
1330
1331     Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1332     if (backgroundColor.isVisible()) {
1333         paintedExtent = backgroundRect;
1334         return true;
1335     }
1336
1337     auto& layers = style().backgroundLayers();
1338     if (!layers.image() || layers.next()) {
1339         paintedExtent =  backgroundRect;
1340         return true;
1341     }
1342
1343     auto geometry = calculateBackgroundImageGeometry(nullptr, layers, paintOffset, backgroundRect);
1344     paintedExtent = geometry.destRect();
1345     return !geometry.hasNonLocalGeometry();
1346 }
1347
1348 bool RenderBox::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
1349 {
1350     if (!paintsOwnBackground())
1351         return false;
1352
1353     Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1354     if (!backgroundColor.isOpaque())
1355         return false;
1356
1357     // If the element has appearance, it might be painted by theme.
1358     // We cannot be sure if theme paints the background opaque.
1359     // In this case it is safe to not assume opaqueness.
1360     // FIXME: May be ask theme if it paints opaque.
1361     if (style().hasAppearance())
1362         return false;
1363     // FIXME: Check the opaqueness of background images.
1364
1365     if (hasClip() || hasClipPath())
1366         return false;
1367
1368     // FIXME: Use rounded rect if border radius is present.
1369     if (style().hasBorderRadius())
1370         return false;
1371     
1372     // FIXME: The background color clip is defined by the last layer.
1373     if (style().backgroundLayers().next())
1374         return false;
1375     LayoutRect backgroundRect;
1376     switch (style().backgroundClip()) {
1377     case BorderFillBox:
1378         backgroundRect = borderBoxRect();
1379         break;
1380     case PaddingFillBox:
1381         backgroundRect = paddingBoxRect();
1382         break;
1383     case ContentFillBox:
1384         backgroundRect = contentBoxRect();
1385         break;
1386     default:
1387         break;
1388     }
1389     return backgroundRect.contains(localRect);
1390 }
1391
1392 static bool isCandidateForOpaquenessTest(const RenderBox& childBox)
1393 {
1394     const RenderStyle& childStyle = childBox.style();
1395     if (childStyle.position() != StaticPosition && childBox.containingBlock() != childBox.parent())
1396         return false;
1397     if (childStyle.visibility() != VISIBLE)
1398         return false;
1399     if (childStyle.shapeOutside())
1400         return false;
1401     if (!childBox.width() || !childBox.height())
1402         return false;
1403     if (RenderLayer* childLayer = childBox.layer()) {
1404         if (childLayer->isComposited())
1405             return false;
1406         // FIXME: Deal with z-index.
1407         if (!childStyle.hasAutoZIndex())
1408             return false;
1409         if (childLayer->hasTransform() || childLayer->isTransparent() || childLayer->hasFilter())
1410             return false;
1411         if (!childBox.scrollPosition().isZero())
1412             return false;
1413     }
1414     return true;
1415 }
1416
1417 bool RenderBox::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const
1418 {
1419     if (!maxDepthToTest)
1420         return false;
1421     for (auto& childBox : childrenOfType<RenderBox>(*this)) {
1422         if (!isCandidateForOpaquenessTest(childBox))
1423             continue;
1424         LayoutPoint childLocation = childBox.location();
1425         if (childBox.isRelPositioned())
1426             childLocation.move(childBox.relativePositionOffset());
1427         LayoutRect childLocalRect = localRect;
1428         childLocalRect.moveBy(-childLocation);
1429         if (childLocalRect.y() < 0 || childLocalRect.x() < 0) {
1430             // If there is unobscured area above/left of a static positioned box then the rect is probably not covered.
1431             if (childBox.style().position() == StaticPosition)
1432                 return false;
1433             continue;
1434         }
1435         if (childLocalRect.maxY() > childBox.height() || childLocalRect.maxX() > childBox.width())
1436             continue;
1437         if (childBox.backgroundIsKnownToBeOpaqueInRect(childLocalRect))
1438             return true;
1439         if (childBox.foregroundIsKnownToBeOpaqueInRect(childLocalRect, maxDepthToTest - 1))
1440             return true;
1441     }
1442     return false;
1443 }
1444
1445 bool RenderBox::computeBackgroundIsKnownToBeObscured(const LayoutPoint& paintOffset)
1446 {
1447     // Test to see if the children trivially obscure the background.
1448     // FIXME: This test can be much more comprehensive.
1449     if (!hasBackground())
1450         return false;
1451     // Table and root background painting is special.
1452     if (isTable() || isDocumentElementRenderer())
1453         return false;
1454
1455     LayoutRect backgroundRect;
1456     if (!getBackgroundPaintedExtent(paintOffset, backgroundRect))
1457         return false;
1458     return foregroundIsKnownToBeOpaqueInRect(backgroundRect, backgroundObscurationTestMaxDepth);
1459 }
1460
1461 bool RenderBox::backgroundHasOpaqueTopLayer() const
1462 {
1463     auto& fillLayer = style().backgroundLayers();
1464     if (fillLayer.clip() != BorderFillBox)
1465         return false;
1466
1467     // Clipped with local scrolling
1468     if (hasOverflowClip() && fillLayer.attachment() == LocalBackgroundAttachment)
1469         return false;
1470
1471     if (fillLayer.hasOpaqueImage(*this) && fillLayer.hasRepeatXY() && fillLayer.image()->canRender(this, style().effectiveZoom()))
1472         return true;
1473
1474     // If there is only one layer and no image, check whether the background color is opaque.
1475     if (!fillLayer.next() && !fillLayer.hasImage()) {
1476         Color bgColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1477         if (bgColor.isOpaque())
1478             return true;
1479     }
1480
1481     return false;
1482 }
1483
1484 void RenderBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1485 {
1486     if (!paintInfo.shouldPaintWithinRoot(*this) || style().visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask || paintInfo.context().paintingDisabled())
1487         return;
1488
1489     LayoutRect paintRect = LayoutRect(paintOffset, size());
1490     adjustBorderBoxRectForPainting(paintRect);
1491     paintMaskImages(paintInfo, paintRect);
1492 }
1493
1494 void RenderBox::paintClippingMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1495 {
1496     if (!paintInfo.shouldPaintWithinRoot(*this) || style().visibility() != VISIBLE || paintInfo.phase != PaintPhaseClippingMask || paintInfo.context().paintingDisabled())
1497         return;
1498
1499     LayoutRect paintRect = LayoutRect(paintOffset, size());
1500     paintInfo.context().fillRect(snappedIntRect(paintRect), Color::black);
1501 }
1502
1503 void RenderBox::paintMaskImages(const PaintInfo& paintInfo, const LayoutRect& paintRect)
1504 {
1505     // Figure out if we need to push a transparency layer to render our mask.
1506     bool pushTransparencyLayer = false;
1507     bool compositedMask = hasLayer() && layer()->hasCompositedMask();
1508     bool flattenCompositingLayers = paintInfo.paintBehavior & PaintBehaviorFlattenCompositingLayers;
1509     CompositeOperator compositeOp = CompositeSourceOver;
1510
1511     bool allMaskImagesLoaded = true;
1512     
1513     if (!compositedMask || flattenCompositingLayers) {
1514         pushTransparencyLayer = true;
1515
1516         // Don't render a masked element until all the mask images have loaded, to prevent a flash of unmasked content.
1517         if (auto* maskBoxImage = style().maskBoxImage().image())
1518             allMaskImagesLoaded &= maskBoxImage->isLoaded();
1519
1520         allMaskImagesLoaded &= style().maskLayers().imagesAreLoaded();
1521
1522         paintInfo.context().setCompositeOperation(CompositeDestinationIn);
1523         paintInfo.context().beginTransparencyLayer(1);
1524         compositeOp = CompositeSourceOver;
1525     }
1526
1527     if (allMaskImagesLoaded) {
1528         paintFillLayers(paintInfo, Color(), style().maskLayers(), paintRect, BackgroundBleedNone, compositeOp);
1529         paintNinePieceImage(paintInfo.context(), paintRect, style(), style().maskBoxImage(), compositeOp);
1530     }
1531     
1532     if (pushTransparencyLayer)
1533         paintInfo.context().endTransparencyLayer();
1534 }
1535
1536 LayoutRect RenderBox::maskClipRect(const LayoutPoint& paintOffset)
1537 {
1538     const NinePieceImage& maskBoxImage = style().maskBoxImage();
1539     if (maskBoxImage.image()) {
1540         LayoutRect borderImageRect = borderBoxRect();
1541         
1542         // Apply outsets to the border box.
1543         borderImageRect.expand(style().maskBoxImageOutsets());
1544         return borderImageRect;
1545     }
1546     
1547     LayoutRect result;
1548     LayoutRect borderBox = borderBoxRect();
1549     for (auto* maskLayer = &style().maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
1550         if (maskLayer->image()) {
1551             // Masks should never have fixed attachment, so it's OK for paintContainer to be null.
1552             result.unite(calculateBackgroundImageGeometry(nullptr, *maskLayer, paintOffset, borderBox).destRect());
1553         }
1554     }
1555     return result;
1556 }
1557
1558 void RenderBox::paintFillLayers(const PaintInfo& paintInfo, const Color& color, const FillLayer& fillLayer, const LayoutRect& rect,
1559     BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject)
1560 {
1561     Vector<const FillLayer*, 8> layers;
1562     bool shouldDrawBackgroundInSeparateBuffer = false;
1563
1564     for (auto* layer = &fillLayer; layer; layer = layer->next()) {
1565         layers.append(layer);
1566
1567         if (layer->blendMode() != BlendModeNormal)
1568             shouldDrawBackgroundInSeparateBuffer = true;
1569
1570         // Stop traversal when an opaque layer is encountered.
1571         // FIXME: It would be possible for the following occlusion culling test to be more aggressive
1572         // on layers with no repeat by testing whether the image covers the layout rect.
1573         // Testing that here would imply duplicating a lot of calculations that are currently done in
1574         // RenderBoxModelObject::paintFillLayerExtended. A more efficient solution might be to move
1575         // the layer recursion into paintFillLayerExtended, or to compute the layer geometry here
1576         // and pass it down.
1577
1578         // The clipOccludesNextLayers condition must be evaluated first to avoid short-circuiting.
1579         if (layer->clipOccludesNextLayers(layer == &fillLayer) && layer->hasOpaqueImage(*this) && layer->image()->canRender(this, style().effectiveZoom()) && layer->hasRepeatXY() && layer->blendMode() == BlendModeNormal)
1580             break;
1581     }
1582
1583     auto& context = paintInfo.context();
1584     auto baseBgColorUsage = BaseBackgroundColorUse;
1585
1586     if (shouldDrawBackgroundInSeparateBuffer) {
1587         paintFillLayer(paintInfo, color, *layers.last(), rect, bleedAvoidance, op, backgroundObject, BaseBackgroundColorOnly);
1588         baseBgColorUsage = BaseBackgroundColorSkip;
1589         context.beginTransparencyLayer(1);
1590     }
1591
1592     auto topLayer = layers.rend();
1593     for (auto it = layers.rbegin(); it != topLayer; ++it)
1594         paintFillLayer(paintInfo, color, **it, rect, bleedAvoidance, op, backgroundObject, baseBgColorUsage);
1595
1596     if (shouldDrawBackgroundInSeparateBuffer)
1597         context.endTransparencyLayer();
1598 }
1599
1600 void RenderBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer& fillLayer, const LayoutRect& rect,
1601     BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject, BaseBackgroundColorUsage baseBgColorUsage)
1602 {
1603     paintFillLayerExtended(paintInfo, c, fillLayer, rect, bleedAvoidance, nullptr, LayoutSize(), op, backgroundObject, baseBgColorUsage);
1604 }
1605
1606 static bool layersUseImage(WrappedImagePtr image, const FillLayer& layers)
1607 {
1608     for (auto* layer = &layers; layer; layer = layer->next()) {
1609         if (layer->image() && image == layer->image()->data())
1610             return true;
1611     }
1612     return false;
1613 }
1614
1615 void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
1616 {
1617     if (!parent())
1618         return;
1619
1620     if ((style().borderImage().image() && style().borderImage().image()->data() == image) ||
1621         (style().maskBoxImage().image() && style().maskBoxImage().image()->data() == image)) {
1622         repaint();
1623         return;
1624     }
1625
1626     ShapeValue* shapeOutsideValue = style().shapeOutside();
1627     if (!view().frameView().isInRenderTreeLayout() && isFloating() && shapeOutsideValue && shapeOutsideValue->image() && shapeOutsideValue->image()->data() == image) {
1628         ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
1629         markShapeOutsideDependentsForLayout();
1630     }
1631
1632     bool didFullRepaint = repaintLayerRectsForImage(image, style().backgroundLayers(), true);
1633     if (!didFullRepaint)
1634         repaintLayerRectsForImage(image, style().maskLayers(), false);
1635
1636     if (!isComposited())
1637         return;
1638
1639     if (layer()->hasCompositedMask() && layersUseImage(image, style().maskLayers()))
1640         layer()->contentChanged(MaskImageChanged);
1641     if (layersUseImage(image, style().backgroundLayers()))
1642         layer()->contentChanged(BackgroundImageChanged);
1643 }
1644
1645 bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer& layers, bool drawingBackground)
1646 {
1647     LayoutRect rendererRect;
1648     RenderBox* layerRenderer = nullptr;
1649
1650     for (auto* layer = &layers; layer; layer = layer->next()) {
1651         if (layer->image() && image == layer->image()->data() && layer->image()->canRender(this, style().effectiveZoom())) {
1652             // Now that we know this image is being used, compute the renderer and the rect if we haven't already.
1653             bool drawingRootBackground = drawingBackground && (isDocumentElementRenderer() || (isBody() && !document().documentElement()->renderer()->hasBackground()));
1654             if (!layerRenderer) {
1655                 if (drawingRootBackground) {
1656                     layerRenderer = &view();
1657
1658                     LayoutUnit rw = downcast<RenderView>(*layerRenderer).frameView().contentsWidth();
1659                     LayoutUnit rh = downcast<RenderView>(*layerRenderer).frameView().contentsHeight();
1660
1661                     rendererRect = LayoutRect(-layerRenderer->marginLeft(),
1662                         -layerRenderer->marginTop(),
1663                         std::max(layerRenderer->width() + layerRenderer->horizontalMarginExtent() + layerRenderer->borderLeft() + layerRenderer->borderRight(), rw),
1664                         std::max(layerRenderer->height() + layerRenderer->verticalMarginExtent() + layerRenderer->borderTop() + layerRenderer->borderBottom(), rh));
1665                 } else {
1666                     layerRenderer = this;
1667                     rendererRect = borderBoxRect();
1668                 }
1669             }
1670             // FIXME: Figure out how to pass absolute position to calculateBackgroundImageGeometry (for pixel snapping)
1671             BackgroundImageGeometry geometry = layerRenderer->calculateBackgroundImageGeometry(nullptr, *layer, LayoutPoint(), rendererRect);
1672             if (geometry.hasNonLocalGeometry()) {
1673                 // Rather than incur the costs of computing the paintContainer for renderers with fixed backgrounds
1674                 // in order to get the right destRect, just repaint the entire renderer.
1675                 layerRenderer->repaint();
1676                 return true;
1677             }
1678             
1679             LayoutRect rectToRepaint = geometry.destRect();
1680             bool shouldClipToLayer = true;
1681
1682             // If this is the root background layer, we may need to extend the repaintRect if the FrameView has an
1683             // extendedBackground. We should only extend the rect if it is already extending the full width or height
1684             // of the rendererRect.
1685             if (drawingRootBackground && view().frameView().hasExtendedBackgroundRectForPainting()) {
1686                 shouldClipToLayer = false;
1687                 IntRect extendedBackgroundRect = view().frameView().extendedBackgroundRectForPainting();
1688                 if (rectToRepaint.width() == rendererRect.width()) {
1689                     rectToRepaint.move(extendedBackgroundRect.x(), 0);
1690                     rectToRepaint.setWidth(extendedBackgroundRect.width());
1691                 }
1692                 if (rectToRepaint.height() == rendererRect.height()) {
1693                     rectToRepaint.move(0, extendedBackgroundRect.y());
1694                     rectToRepaint.setHeight(extendedBackgroundRect.height());
1695                 }
1696             }
1697
1698             layerRenderer->repaintRectangle(rectToRepaint, shouldClipToLayer);
1699             if (geometry.destRect() == rendererRect)
1700                 return true;
1701         }
1702     }
1703     return false;
1704 }
1705
1706 bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset)
1707 {
1708     if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask)
1709         return false;
1710         
1711     bool isControlClip = hasControlClip();
1712     bool isOverflowClip = hasOverflowClip() && !layer()->isSelfPaintingLayer();
1713     
1714     if (!isControlClip && !isOverflowClip)
1715         return false;
1716     
1717     if (paintInfo.phase == PaintPhaseOutline)
1718         paintInfo.phase = PaintPhaseChildOutlines;
1719     else if (paintInfo.phase == PaintPhaseChildBlockBackground) {
1720         paintInfo.phase = PaintPhaseBlockBackground;
1721         paintObject(paintInfo, accumulatedOffset);
1722         paintInfo.phase = PaintPhaseChildBlockBackgrounds;
1723     }
1724     float deviceScaleFactor = document().deviceScaleFactor();
1725     FloatRect clipRect = snapRectToDevicePixels((isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset, nullptr, IgnoreOverlayScrollbarSize, paintInfo.phase)), deviceScaleFactor);
1726     paintInfo.context().save();
1727     if (style().hasBorderRadius())
1728         paintInfo.context().clipRoundedRect(style().getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size())).pixelSnappedRoundedRectForPainting(deviceScaleFactor));
1729     paintInfo.context().clip(clipRect);
1730     return true;
1731 }
1732
1733 void RenderBox::popContentsClip(PaintInfo& paintInfo, PaintPhase originalPhase, const LayoutPoint& accumulatedOffset)
1734 {
1735     ASSERT(hasControlClip() || (hasOverflowClip() && !layer()->isSelfPaintingLayer()));
1736
1737     paintInfo.context().restore();
1738     if (originalPhase == PaintPhaseOutline) {
1739         paintInfo.phase = PaintPhaseSelfOutline;
1740         paintObject(paintInfo, accumulatedOffset);
1741         paintInfo.phase = originalPhase;
1742     } else if (originalPhase == PaintPhaseChildBlockBackground)
1743         paintInfo.phase = originalPhase;
1744 }
1745
1746 LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, RenderFragmentContainer* fragment, OverlayScrollbarSizeRelevancy relevancy, PaintPhase)
1747 {
1748     // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
1749     // here.
1750     LayoutRect clipRect = borderBoxRectInFragment(fragment);
1751     clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
1752     clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
1753
1754     // Subtract out scrollbars if we have them.
1755     if (layer()) {
1756         if (shouldPlaceBlockDirectionScrollbarOnLeft())
1757             clipRect.move(layer()->verticalScrollbarWidth(relevancy), 0);
1758         clipRect.contract(layer()->verticalScrollbarWidth(relevancy), layer()->horizontalScrollbarHeight(relevancy));
1759     }
1760
1761     return clipRect;
1762 }
1763
1764 LayoutRect RenderBox::clipRect(const LayoutPoint& location, RenderFragmentContainer* fragment)
1765 {
1766     LayoutRect borderBoxRect = borderBoxRectInFragment(fragment);
1767     LayoutRect clipRect = LayoutRect(borderBoxRect.location() + location, borderBoxRect.size());
1768
1769     if (!style().clipLeft().isAuto()) {
1770         LayoutUnit c = valueForLength(style().clipLeft(), borderBoxRect.width());
1771         clipRect.move(c, 0);
1772         clipRect.contract(c, 0);
1773     }
1774
1775     // We don't use the fragment-specific border box's width and height since clip offsets are (stupidly) specified
1776     // from the left and top edges. Therefore it's better to avoid constraining to smaller widths and heights.
1777
1778     if (!style().clipRight().isAuto())
1779         clipRect.contract(width() - valueForLength(style().clipRight(), width()), 0);
1780
1781     if (!style().clipTop().isAuto()) {
1782         LayoutUnit c = valueForLength(style().clipTop(), borderBoxRect.height());
1783         clipRect.move(0, c);
1784         clipRect.contract(0, c);
1785     }
1786
1787     if (!style().clipBottom().isAuto())
1788         clipRect.contract(0, height() - valueForLength(style().clipBottom(), height()));
1789
1790     return clipRect;
1791 }
1792
1793 LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock& cb, RenderFragmentContainer* fragment) const
1794 {    
1795     RenderFragmentContainer* containingBlockFragment = nullptr;
1796     LayoutUnit logicalTopPosition = logicalTop();
1797     if (fragment) {
1798         LayoutUnit offsetFromLogicalTopOfFragment = fragment ? fragment->logicalTopForFragmentedFlowContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1799         logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfFragment);
1800         containingBlockFragment = cb.clampToStartAndEndFragments(fragment);
1801     }
1802
1803     LayoutUnit logicalHeight = cb.logicalHeightForChild(*this);
1804     LayoutUnit result = cb.availableLogicalWidthForLineInFragment(logicalTopPosition, DoNotIndentText, containingBlockFragment, logicalHeight) - childMarginStart - childMarginEnd;
1805
1806     // We need to see if margins on either the start side or the end side can contain the floats in question. If they can,
1807     // then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line
1808     // offset at all, but can instead push all the way to the content edge of the containing block. In the case where the float
1809     // doesn't fit, we can use the line offset, but we need to grow it by the margin to reflect the fact that the margin was
1810     // "consumed" by the float. Negative margins aren't consumed by the float, and so we ignore them.
1811     if (childMarginStart > 0) {
1812         LayoutUnit startContentSide = cb.startOffsetForContent(containingBlockFragment);
1813         LayoutUnit startContentSideWithMargin = startContentSide + childMarginStart;
1814         LayoutUnit startOffset = cb.startOffsetForLineInFragment(logicalTopPosition, DoNotIndentText, containingBlockFragment, logicalHeight);
1815         if (startOffset > startContentSideWithMargin)
1816             result += childMarginStart;
1817         else
1818             result += startOffset - startContentSide;
1819     }
1820     
1821     if (childMarginEnd > 0) {
1822         LayoutUnit endContentSide = cb.endOffsetForContent(containingBlockFragment);
1823         LayoutUnit endContentSideWithMargin = endContentSide + childMarginEnd;
1824         LayoutUnit endOffset = cb.endOffsetForLineInFragment(logicalTopPosition, DoNotIndentText, containingBlockFragment, logicalHeight);
1825         if (endOffset > endContentSideWithMargin)
1826             result += childMarginEnd;
1827         else
1828             result += endOffset - endContentSide;
1829     }
1830
1831     return result;
1832 }
1833
1834 LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const
1835 {
1836     if (hasOverrideContainingBlockLogicalWidth()) {
1837         if (auto overrideLogicalWidth = overrideContainingBlockContentLogicalWidth())
1838             return overrideLogicalWidth.value();
1839     }
1840
1841     if (RenderBlock* cb = containingBlock())
1842         return cb->availableLogicalWidth();
1843     return LayoutUnit();
1844 }
1845
1846 LayoutUnit RenderBox::containingBlockLogicalHeightForContent(AvailableLogicalHeightType heightType) const
1847 {
1848     if (hasOverrideContainingBlockLogicalHeight()) {
1849         if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight())
1850             return overrideLogicalHeight.value();
1851     }
1852
1853     if (RenderBlock* cb = containingBlock())
1854         return cb->availableLogicalHeight(heightType);
1855     return LayoutUnit();
1856 }
1857
1858 LayoutUnit RenderBox::containingBlockLogicalWidthForContentInFragment(RenderFragmentContainer* fragment) const
1859 {
1860     if (!fragment)
1861         return containingBlockLogicalWidthForContent();
1862
1863     RenderBlock* cb = containingBlock();
1864     RenderFragmentContainer* containingBlockFragment = cb->clampToStartAndEndFragments(fragment);
1865     // FIXME: It's unclear if a fragment's content should use the containing block's override logical width.
1866     // If it should, the following line should call containingBlockLogicalWidthForContent.
1867     LayoutUnit result = cb->availableLogicalWidth();
1868     RenderBoxFragmentInfo* boxInfo = cb->renderBoxFragmentInfo(containingBlockFragment);
1869     if (!boxInfo)
1870         return result;
1871     return std::max<LayoutUnit>(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
1872 }
1873
1874 LayoutUnit RenderBox::containingBlockAvailableLineWidthInFragment(RenderFragmentContainer* fragment) const
1875 {
1876     RenderBlock* cb = containingBlock();
1877     RenderFragmentContainer* containingBlockFragment = nullptr;
1878     LayoutUnit logicalTopPosition = logicalTop();
1879     if (fragment) {
1880         LayoutUnit offsetFromLogicalTopOfFragment = fragment ? fragment->logicalTopForFragmentedFlowContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1881         logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfFragment);
1882         containingBlockFragment = cb->clampToStartAndEndFragments(fragment);
1883     }
1884     return cb->availableLogicalWidthForLineInFragment(logicalTopPosition, DoNotIndentText, containingBlockFragment, availableLogicalHeight(IncludeMarginBorderPadding));
1885 }
1886
1887 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
1888 {
1889     if (hasOverrideContainingBlockLogicalHeight()) {
1890         if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight())
1891             return overrideLogicalHeight.value();
1892     }
1893
1894     RenderBlock* cb = containingBlock();
1895     if (cb->hasOverrideLogicalContentHeight())
1896         return cb->overrideLogicalContentHeight();
1897
1898     const RenderStyle& containingBlockStyle = cb->style();
1899     Length logicalHeightLength = containingBlockStyle.logicalHeight();
1900
1901     // FIXME: For now just support fixed heights.  Eventually should support percentage heights as well.
1902     if (!logicalHeightLength.isFixed()) {
1903         LayoutUnit fillFallbackExtent = containingBlockStyle.isHorizontalWritingMode() ? view().frameView().visibleHeight() : view().frameView().visibleWidth();
1904         LayoutUnit fillAvailableExtent = containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding);
1905         view().addPercentHeightDescendant(const_cast<RenderBox&>(*this));
1906         // FIXME: https://bugs.webkit.org/show_bug.cgi?id=158286 We also need to perform the same percentHeightDescendant treatment to the element which dictates the return value for containingBlock()->availableLogicalHeight() above.
1907         return std::min(fillAvailableExtent, fillFallbackExtent);
1908     }
1909
1910     // Use the content box logical height as specified by the style.
1911     return cb->adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(logicalHeightLength.value()));
1912 }
1913
1914 void RenderBox::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
1915 {
1916     if (repaintContainer == this)
1917         return;
1918
1919     if (view().layoutStateEnabled() && !repaintContainer) {
1920         LayoutState* layoutState = view().layoutState();
1921         LayoutSize offset = layoutState->m_paintOffset + locationOffset();
1922         if (style().hasInFlowPosition() && layer())
1923             offset += layer()->offsetForInFlowPosition();
1924         transformState.move(offset);
1925         return;
1926     }
1927
1928     bool containerSkipped;
1929     RenderElement* container = this->container(repaintContainer, containerSkipped);
1930     if (!container)
1931         return;
1932
1933     bool isFixedPos = style().position() == FixedPosition;
1934     // If this box has a transform, it acts as a fixed position container for fixed descendants,
1935     // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1936     if (hasTransform() && !isFixedPos)
1937         mode &= ~IsFixed;
1938     else if (isFixedPos)
1939         mode |= IsFixed;
1940
1941     if (wasFixed)
1942         *wasFixed = mode & IsFixed;
1943     
1944     LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint(transformState.mappedPoint()));
1945     
1946     bool preserve3D = mode & UseTransforms && (container->style().preserves3D() || style().preserves3D());
1947     if (mode & UseTransforms && shouldUseTransformFromContainer(container)) {
1948         TransformationMatrix t;
1949         getTransformFromContainer(container, containerOffset, t);
1950         transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1951     } else
1952         transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1953
1954     if (containerSkipped) {
1955         // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe
1956         // to just subtract the delta between the repaintContainer and o.
1957         LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(*container);
1958         transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1959         return;
1960     }
1961
1962     mode &= ~ApplyContainerFlip;
1963
1964     container->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed);
1965 }
1966
1967 const RenderObject* RenderBox::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
1968 {
1969     ASSERT(ancestorToStopAt != this);
1970
1971     bool ancestorSkipped;
1972     RenderElement* container = this->container(ancestorToStopAt, ancestorSkipped);
1973     if (!container)
1974         return nullptr;
1975
1976     bool isFixedPos = style().position() == FixedPosition;
1977     LayoutSize adjustmentForSkippedAncestor;
1978     if (ancestorSkipped) {
1979         // There can't be a transform between repaintContainer and container, because transforms create containers, so it should be safe
1980         // to just subtract the delta between the ancestor and container.
1981         adjustmentForSkippedAncestor = -ancestorToStopAt->offsetFromAncestorContainer(*container);
1982     }
1983
1984     bool offsetDependsOnPoint = false;
1985     LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint(), &offsetDependsOnPoint);
1986
1987     bool preserve3D = container->style().preserves3D() || style().preserves3D();
1988     if (shouldUseTransformFromContainer(container) && (geometryMap.mapCoordinatesFlags() & UseTransforms)) {
1989         TransformationMatrix t;
1990         getTransformFromContainer(container, containerOffset, t);
1991         t.translateRight(adjustmentForSkippedAncestor.width(), adjustmentForSkippedAncestor.height());
1992         
1993         geometryMap.push(this, t, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform());
1994     } else {
1995         containerOffset += adjustmentForSkippedAncestor;
1996         geometryMap.push(this, containerOffset, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform());
1997     }
1998     
1999     return ancestorSkipped ? ancestorToStopAt : container;
2000 }
2001
2002 void RenderBox::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
2003 {
2004     bool isFixedPos = style().position() == FixedPosition;
2005     if (hasTransform() && !isFixedPos) {
2006         // If this box has a transform, it acts as a fixed position container for fixed descendants,
2007         // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
2008         mode &= ~IsFixed;
2009     } else if (isFixedPos)
2010         mode |= IsFixed;
2011
2012     RenderBoxModelObject::mapAbsoluteToLocalPoint(mode, transformState);
2013 }
2014
2015 LayoutSize RenderBox::offsetFromContainer(RenderElement& renderer, const LayoutPoint&, bool* offsetDependsOnPoint) const
2016 {
2017     // A fragment "has" boxes inside it without being their container. 
2018     ASSERT(&renderer == container() || is<RenderFragmentContainer>(renderer));
2019
2020     LayoutSize offset;    
2021     if (isInFlowPositioned())
2022         offset += offsetForInFlowPosition();
2023
2024     if (!isInline() || isReplaced())
2025         offset += topLeftLocationOffset();
2026
2027     if (is<RenderBox>(renderer))
2028         offset -= toLayoutSize(downcast<RenderBox>(renderer).scrollPosition());
2029
2030     if (style().position() == AbsolutePosition && renderer.isInFlowPositioned() && is<RenderInline>(renderer))
2031         offset += downcast<RenderInline>(renderer).offsetForInFlowPositionedInline(this);
2032
2033     if (offsetDependsOnPoint)
2034         *offsetDependsOnPoint |= is<RenderFragmentedFlow>(renderer);
2035
2036     return offset;
2037 }
2038
2039 std::unique_ptr<InlineElementBox> RenderBox::createInlineBox()
2040 {
2041     return std::make_unique<InlineElementBox>(*this);
2042 }
2043
2044 void RenderBox::dirtyLineBoxes(bool fullLayout)
2045 {
2046     if (!m_inlineBoxWrapper)
2047         return;
2048     
2049     if (fullLayout) {
2050         delete m_inlineBoxWrapper;
2051         m_inlineBoxWrapper = nullptr;
2052     } else
2053         m_inlineBoxWrapper->dirtyLineBoxes();
2054 }
2055
2056 void RenderBox::positionLineBox(InlineElementBox& box)
2057 {
2058     if (isOutOfFlowPositioned()) {
2059         // Cache the x position only if we were an INLINE type originally.
2060         bool wasInline = style().isOriginalDisplayInlineType();
2061         if (wasInline) {
2062             // The value is cached in the xPos of the box.  We only need this value if
2063             // our object was inline originally, since otherwise it would have ended up underneath
2064             // the inlines.
2065             RootInlineBox& rootBox = box.root();
2066             rootBox.blockFlow().setStaticInlinePositionForChild(*this, rootBox.lineTopWithLeading(), LayoutUnit::fromFloatRound(box.logicalLeft()));
2067             if (style().hasStaticInlinePosition(box.isHorizontal()))
2068                 setChildNeedsLayout(MarkOnlyThis); // Just mark the positioned object as needing layout, so it will update its position properly.
2069         } else {
2070             // Our object was a block originally, so we make our normal flow position be
2071             // just below the line box (as though all the inlines that came before us got
2072             // wrapped in an anonymous block, which is what would have happened had we been
2073             // in flow).  This value was cached in the y() of the box.
2074             layer()->setStaticBlockPosition(box.logicalTop());
2075             if (style().hasStaticBlockPosition(box.isHorizontal()))
2076                 setChildNeedsLayout(MarkOnlyThis); // Just mark the positioned object as needing layout, so it will update its position properly.
2077         }
2078         return;
2079     }
2080
2081     if (isReplaced()) {
2082         setLocation(LayoutPoint(box.topLeft()));
2083         setInlineBoxWrapper(&box);
2084     }
2085 }
2086
2087 void RenderBox::deleteLineBoxWrapper()
2088 {
2089     if (!m_inlineBoxWrapper)
2090         return;
2091     
2092     if (!renderTreeBeingDestroyed())
2093         m_inlineBoxWrapper->removeFromParent();
2094     delete m_inlineBoxWrapper;
2095     m_inlineBoxWrapper = nullptr;
2096 }
2097
2098 LayoutRect RenderBox::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
2099 {
2100     if (style().visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
2101         return LayoutRect();
2102     LayoutRect r = visualOverflowRect();
2103     // FIXME: layoutDelta needs to be applied in parts before/after transforms and
2104     // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
2105     r.move(view().layoutDelta());
2106     return computeRectForRepaint(r, repaintContainer);
2107 }
2108
2109 bool RenderBox::shouldApplyClipAndScrollPositionForRepaint(const RenderLayerModelObject* repaintContainer) const
2110 {
2111 #if PLATFORM(IOS)
2112     if (!repaintContainer || repaintContainer != this)
2113         return true;
2114
2115     return !hasLayer() || !layer()->usesCompositedScrolling();
2116 #else
2117     UNUSED_PARAM(repaintContainer);
2118     return true;
2119 #endif
2120 }
2121
2122 LayoutRect RenderBox::computeRectForRepaint(const LayoutRect& rect, const RenderLayerModelObject* repaintContainer, RepaintContext context) const
2123 {
2124     // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
2125     // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
2126     // offset corner for the enclosing container).  This allows for a fully RL or BT document to repaint
2127     // properly even during layout, since the rect remains flipped all the way until the end.
2128     //
2129     // RenderView::computeRectForRepaint then converts the rect to physical coordinates.  We also convert to
2130     // physical when we hit a repaintContainer boundary.  Therefore the final rect returned is always in the
2131     // physical coordinate space of the repaintContainer.
2132     LayoutRect adjustedRect = rect;
2133     const RenderStyle& styleToUse = style();
2134     // LayoutState is only valid for root-relative, non-fixed position repainting
2135     if (view().layoutStateEnabled() && !repaintContainer && styleToUse.position() != FixedPosition) {
2136         LayoutState* layoutState = view().layoutState();
2137
2138         if (layer() && layer()->transform())
2139             adjustedRect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(adjustedRect), document().deviceScaleFactor()));
2140
2141         // We can't trust the bits on RenderObject, because this might be called while re-resolving style.
2142         if (styleToUse.hasInFlowPosition() && layer())
2143             adjustedRect.move(layer()->offsetForInFlowPosition());
2144
2145         adjustedRect.moveBy(location());
2146         adjustedRect.move(layoutState->m_paintOffset);
2147         if (layoutState->m_clipped)
2148             adjustedRect.intersect(layoutState->m_clipRect);
2149         return adjustedRect;
2150     }
2151
2152     if (hasReflection())
2153         adjustedRect.unite(reflectedRect(adjustedRect));
2154
2155     if (repaintContainer == this) {
2156         if (repaintContainer->style().isFlippedBlocksWritingMode())
2157             flipForWritingMode(adjustedRect);
2158         return adjustedRect;
2159     }
2160
2161     bool repaintContainerIsSkipped;
2162     auto* container = this->container(repaintContainer, repaintContainerIsSkipped);
2163     if (!container)
2164         return adjustedRect;
2165     
2166     // This code isn't necessary for in-flow RenderFragmentedFlows.
2167     // Don't add the location of the fragment in the flow thread for absolute positioned
2168     // elements because their absolute position already pushes them down through
2169     // the fragments so adding this here and then adding the topLeft again would cause
2170     // us to add the height twice.
2171     // The same logic applies for elements flowed directly into the flow thread. Their topLeft member
2172     // will already contain the portion rect of the fragment.
2173     EPosition position = styleToUse.position();
2174     if (container->isOutOfFlowRenderFragmentedFlow() && position != AbsolutePosition && containingBlock() != enclosingFragmentedFlow()) {
2175         RenderFragmentContainer* firstFragment = nullptr;
2176         RenderFragmentContainer* lastFragment = nullptr;
2177         if (downcast<RenderFragmentedFlow>(*container).getFragmentRangeForBox(this, firstFragment, lastFragment))
2178             adjustedRect.moveBy(firstFragment->fragmentedFlowPortionRect().location());
2179     }
2180
2181     if (isWritingModeRoot()) {
2182         if (!isOutOfFlowPositioned() || !context.m_dirtyRectIsFlipped) {
2183             flipForWritingMode(adjustedRect);
2184             context.m_dirtyRectIsFlipped = true;
2185         }
2186     }
2187
2188     LayoutSize locationOffset = this->locationOffset();
2189     // FIXME: This is needed as long as RenderWidget snaps to integral size/position.
2190     if (isRenderReplaced() && isWidget()) {
2191         LayoutSize flooredLocationOffset = toIntSize(flooredIntPoint(locationOffset));
2192         adjustedRect.expand(locationOffset - flooredLocationOffset);
2193         locationOffset = flooredLocationOffset;
2194     }
2195
2196     if (is<RenderMultiColumnFlow>(this)) {
2197         // We won't normally run this code. Only when the repaintContainer is null (i.e., we're trying
2198         // to get the rect in view coordinates) will we come in here, since normally repaintContainer
2199         // will be set and we'll stop at the flow thread. This case is mainly hit by the check for whether
2200         // or not images should animate.
2201         // FIXME: Just as with offsetFromContainer, we aren't really handling objects that span
2202         // multiple columns properly.
2203         LayoutPoint physicalPoint(flipForWritingMode(adjustedRect.location()));
2204         if (auto* fragment = downcast<RenderMultiColumnFlow>(*this).physicalTranslationFromFlowToFragment((physicalPoint))) {
2205             adjustedRect.setLocation(fragment->flipForWritingMode(physicalPoint));
2206             return fragment->computeRectForRepaint(adjustedRect, repaintContainer, context);
2207         }
2208     }
2209
2210     LayoutPoint topLeft = adjustedRect.location();
2211     topLeft.move(locationOffset);
2212
2213     // We are now in our parent container's coordinate space. Apply our transform to obtain a bounding box
2214     // in the parent's coordinate space that encloses us.
2215     if (hasLayer() && layer()->transform()) {
2216         context.m_hasPositionFixedDescendant = position == FixedPosition;
2217         adjustedRect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(adjustedRect), document().deviceScaleFactor()));
2218         topLeft = adjustedRect.location();
2219         topLeft.move(locationOffset);
2220     } else if (position == FixedPosition)
2221         context.m_hasPositionFixedDescendant = true;
2222
2223     if (position == AbsolutePosition && container->isInFlowPositioned() && is<RenderInline>(*container))
2224         topLeft += downcast<RenderInline>(*container).offsetForInFlowPositionedInline(this);
2225     else if (styleToUse.hasInFlowPosition() && layer()) {
2226         // Apply the relative position offset when invalidating a rectangle.  The layer
2227         // is translated, but the render box isn't, so we need to do this to get the
2228         // right dirty rect.  Since this is called from RenderObject::setStyle, the relative position
2229         // flag on the RenderObject has been cleared, so use the one on the style().
2230         topLeft += layer()->offsetForInFlowPosition();
2231     }
2232
2233     // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
2234     // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
2235     adjustedRect.setLocation(topLeft);
2236     if (container->hasOverflowClip()) {
2237         RenderBox& containerBox = downcast<RenderBox>(*container);
2238         if (containerBox.shouldApplyClipAndScrollPositionForRepaint(repaintContainer)) {
2239             containerBox.applyCachedClipAndScrollPositionForRepaint(adjustedRect);
2240             if (adjustedRect.isEmpty())
2241                 return adjustedRect;
2242         }
2243     }
2244
2245     if (repaintContainerIsSkipped) {
2246         // If the repaintContainer is below container, then we need to map the rect into repaintContainer's coordinates.
2247         LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(*container);
2248         adjustedRect.move(-containerOffset);
2249         return adjustedRect;
2250     }
2251     return container->computeRectForRepaint(adjustedRect, repaintContainer, context);
2252 }
2253
2254 void RenderBox::repaintDuringLayoutIfMoved(const LayoutRect& oldRect)
2255 {
2256     if (oldRect.location() != m_frameRect.location()) {
2257         LayoutRect newRect = m_frameRect;
2258         // The child moved.  Invalidate the object's old and new positions.  We have to do this
2259         // since the object may not have gotten a layout.
2260         m_frameRect = oldRect;
2261         repaint();
2262         repaintOverhangingFloats(true);
2263         m_frameRect = newRect;
2264         repaint();
2265         repaintOverhangingFloats(true);
2266     }
2267 }
2268
2269 void RenderBox::repaintOverhangingFloats(bool)
2270 {
2271 }
2272
2273 void RenderBox::updateLogicalWidth()
2274 {
2275     LogicalExtentComputedValues computedValues;
2276     computeLogicalWidthInFragment(computedValues);
2277
2278     setLogicalWidth(computedValues.m_extent);
2279     setLogicalLeft(computedValues.m_position);
2280     setMarginStart(computedValues.m_margins.m_start);
2281     setMarginEnd(computedValues.m_margins.m_end);
2282 }
2283
2284 void RenderBox::computeLogicalWidthInFragment(LogicalExtentComputedValues& computedValues, RenderFragmentContainer* fragment) const
2285 {
2286     computedValues.m_extent = logicalWidth();
2287     computedValues.m_position = logicalLeft();
2288     computedValues.m_margins.m_start = marginStart();
2289     computedValues.m_margins.m_end = marginEnd();
2290
2291     if (isOutOfFlowPositioned()) {
2292         // FIXME: This calculation is not patched for block-flow yet.
2293         // https://bugs.webkit.org/show_bug.cgi?id=46500
2294         computePositionedLogicalWidth(computedValues, fragment);
2295         return;
2296     }
2297
2298     // If layout is limited to a subtree, the subtree root's logical width does not change.
2299     if (element() && !view().frameView().layoutPending() && view().frameView().subtreeLayoutRoot() == this)
2300         return;
2301
2302     // The parent box is flexing us, so it has increased or decreased our
2303     // width.  Use the width from the style context.
2304     // FIXME: Account for block-flow in flexible boxes.
2305     // https://bugs.webkit.org/show_bug.cgi?id=46418
2306     if (hasOverrideLogicalContentWidth() && (isRubyRun() || style().borderFit() == BorderFitLines || (parent()->isFlexibleBoxIncludingDeprecated()))) {
2307         computedValues.m_extent = overrideLogicalContentWidth() + borderAndPaddingLogicalWidth();
2308         return;
2309     }
2310
2311     // FIXME: Account for block-flow in flexible boxes.
2312     // https://bugs.webkit.org/show_bug.cgi?id=46418
2313     bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == VERTICAL);
2314     bool stretching = (parent()->style().boxAlign() == BSTRETCH);
2315     // FIXME: Stretching is the only reason why we don't want the box to be treated as a replaced element, so we could perhaps
2316     // refactor all this logic, not only for flex and grid since alignment is intended to be applied to any block.
2317     bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
2318     treatAsReplaced = treatAsReplaced && (!isGridItem() || !hasStretchedLogicalWidth());
2319
2320     const RenderStyle& styleToUse = style();
2321     Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse.logicalWidth();
2322
2323     RenderBlock& cb = *containingBlock();
2324     LayoutUnit containerLogicalWidth = std::max<LayoutUnit>(0, containingBlockLogicalWidthForContentInFragment(fragment));
2325     bool hasPerpendicularContainingBlock = cb.isHorizontalWritingMode() != isHorizontalWritingMode();
2326
2327     if (isInline() && !isInlineBlockOrInlineTable()) {
2328         // just calculate margins
2329         computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2330         computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2331         if (treatAsReplaced)
2332             computedValues.m_extent = std::max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
2333         return;
2334     }
2335
2336     LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
2337     if (hasPerpendicularContainingBlock)
2338         containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
2339
2340     // Width calculations
2341     if (treatAsReplaced) {
2342         computedValues.m_extent = logicalWidthLength.value() + borderAndPaddingLogicalWidth();
2343     } else {
2344         LayoutUnit preferredWidth = computeLogicalWidthInFragmentUsing(MainOrPreferredSize, styleToUse.logicalWidth(), containerWidthInInlineDirection, cb, fragment);
2345         computedValues.m_extent = constrainLogicalWidthInFragmentByMinMax(preferredWidth, containerWidthInInlineDirection, cb, fragment);
2346     }
2347
2348     // Margin calculations.
2349     if (hasPerpendicularContainingBlock || isFloating() || isInline()) {
2350         computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2351         computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2352     } else {
2353         LayoutUnit containerLogicalWidthForAutoMargins = containerLogicalWidth;
2354         if (avoidsFloats() && cb.containsFloats())
2355             containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInFragment(fragment);
2356         bool hasInvertedDirection = cb.style().isLeftToRightDirection() != style().isLeftToRightDirection();
2357         computeInlineDirectionMargins(cb, containerLogicalWidthForAutoMargins, computedValues.m_extent,
2358             hasInvertedDirection ? computedValues.m_margins.m_end : computedValues.m_margins.m_start,
2359             hasInvertedDirection ? computedValues.m_margins.m_start : computedValues.m_margins.m_end);
2360     }
2361     
2362     if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (computedValues.m_extent + computedValues.m_margins.m_start + computedValues.m_margins.m_end)
2363         && !isFloating() && !isInline() && !cb.isFlexibleBoxIncludingDeprecated()
2364 #if ENABLE(MATHML)
2365         // RenderMathMLBlocks take the size of their content so we must not adjust the margin to fill the container size.
2366         && !cb.isRenderMathMLBlock()
2367 #endif
2368         && !cb.isRenderGrid()
2369         ) {
2370         LayoutUnit newMarginTotal = containerLogicalWidth - computedValues.m_extent;
2371         bool hasInvertedDirection = cb.style().isLeftToRightDirection() != style().isLeftToRightDirection();
2372         if (hasInvertedDirection)
2373             computedValues.m_margins.m_start = newMarginTotal - computedValues.m_margins.m_end;
2374         else
2375             computedValues.m_margins.m_end = newMarginTotal - computedValues.m_margins.m_start;
2376     }
2377 }
2378
2379 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth) const
2380 {
2381     LayoutUnit marginStart = 0;
2382     LayoutUnit marginEnd = 0;
2383     return fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2384 }
2385
2386 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2387 {
2388     marginStart = minimumValueForLength(style().marginStart(), availableLogicalWidth);
2389     marginEnd = minimumValueForLength(style().marginEnd(), availableLogicalWidth);
2390     return availableLogicalWidth - marginStart - marginEnd;
2391 }
2392
2393 LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(Length logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const
2394 {
2395     if (logicalWidthLength.type() == FillAvailable)
2396         return std::max(borderAndPadding, fillAvailableMeasure(availableLogicalWidth));
2397
2398     LayoutUnit minLogicalWidth = 0;
2399     LayoutUnit maxLogicalWidth = 0;
2400     computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
2401
2402     if (logicalWidthLength.type() == MinContent)
2403         return minLogicalWidth + borderAndPadding;
2404
2405     if (logicalWidthLength.type() == MaxContent)
2406         return maxLogicalWidth + borderAndPadding;
2407
2408     if (logicalWidthLength.type() == FitContent) {
2409         minLogicalWidth += borderAndPadding;
2410         maxLogicalWidth += borderAndPadding;
2411         return std::max(minLogicalWidth, std::min(maxLogicalWidth, fillAvailableMeasure(availableLogicalWidth)));
2412     }
2413
2414     ASSERT_NOT_REACHED();
2415     return 0;
2416 }
2417
2418 LayoutUnit RenderBox::computeLogicalWidthInFragmentUsing(SizeType widthType, Length logicalWidth, LayoutUnit availableLogicalWidth,
2419     const RenderBlock& cb, RenderFragmentContainer* fragment) const
2420 {
2421     ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto());
2422     if (widthType == MinSize && logicalWidth.isAuto())
2423         return adjustBorderBoxLogicalWidthForBoxSizing(0);
2424
2425     if (!logicalWidth.isIntrinsicOrAuto()) {
2426         // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
2427         return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth));
2428     }
2429
2430     if (logicalWidth.isIntrinsic())
2431         return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth());
2432
2433     LayoutUnit marginStart = 0;
2434     LayoutUnit marginEnd = 0;
2435     LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2436
2437     if (shrinkToAvoidFloats() && cb.containsFloats())
2438         logicalWidthResult = std::min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, fragment));
2439
2440     if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(widthType))
2441         return std::max(minPreferredLogicalWidth(), std::min(maxPreferredLogicalWidth(), logicalWidthResult));
2442     return logicalWidthResult;
2443 }
2444
2445 bool RenderBox::columnFlexItemHasStretchAlignment() const
2446 {
2447     // auto margins mean we don't stretch. Note that this function will only be
2448     // used for widths, so we don't have to check marginBefore/marginAfter.
2449     const auto& parentStyle = parent()->style();
2450     ASSERT(parentStyle.isColumnFlexDirection());
2451     if (style().marginStart().isAuto() || style().marginEnd().isAuto())
2452         return false;
2453     return style().resolvedAlignSelf(&parentStyle, containingBlock()->selfAlignmentNormalBehavior()).position() == ItemPositionStretch;
2454 }
2455
2456 bool RenderBox::isStretchingColumnFlexItem() const
2457 {
2458     if (parent()->isDeprecatedFlexibleBox() && parent()->style().boxOrient() == VERTICAL && parent()->style().boxAlign() == BSTRETCH)
2459         return true;
2460
2461     // We don't stretch multiline flexboxes because they need to apply line spacing (align-content) first.
2462     if (parent()->isFlexibleBox() && parent()->style().flexWrap() == FlexNoWrap && parent()->style().isColumnFlexDirection() && columnFlexItemHasStretchAlignment())
2463         return true;
2464     return false;
2465 }
2466
2467 // FIXME: Can/Should we move this inside specific layout classes (flex. grid)? Can we refactor columnFlexItemHasStretchAlignment logic?
2468 bool RenderBox::hasStretchedLogicalWidth() const
2469 {
2470     auto& style = this->style();
2471     if (!style.logicalWidth().isAuto() || style.marginStart().isAuto() || style.marginEnd().isAuto())
2472         return false;
2473     RenderBlock* containingBlock = this->containingBlock();
2474     if (!containingBlock) {
2475         // We are evaluating align-self/justify-self, which default to 'normal' for the root element.
2476         // The 'normal' value behaves like 'start' except for Flexbox Items, which obviously should have a container.
2477         return false;
2478     }
2479     if (containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2480         return style.resolvedAlignSelf(&containingBlock->style(), containingBlock->selfAlignmentNormalBehavior(this)).position() == ItemPositionStretch;
2481     return style.resolvedJustifySelf(&containingBlock->style(), containingBlock->selfAlignmentNormalBehavior(this)).position() == ItemPositionStretch;
2482 }
2483
2484 bool RenderBox::sizesLogicalWidthToFitContent(SizeType widthType) const
2485 {
2486     // Marquees in WinIE are like a mixture of blocks and inline-blocks.  They size as though they're blocks,
2487     // but they allow text to sit on the same line as the marquee.
2488     if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee()))
2489         return true;
2490
2491     if (isGridItem())
2492         return !hasStretchedLogicalWidth();
2493
2494     // This code may look a bit strange.  Basically width:intrinsic should clamp the size when testing both
2495     // min-width and width.  max-width is only clamped if it is also intrinsic.
2496     Length logicalWidth = (widthType == MaxSize) ? style().logicalMaxWidth() : style().logicalWidth();
2497     if (logicalWidth.type() == Intrinsic)
2498         return true;
2499
2500     // Children of a horizontal marquee do not fill the container by default.
2501     // FIXME: Need to deal with MAUTO value properly.  It could be vertical.
2502     // FIXME: Think about block-flow here.  Need to find out how marquee direction relates to
2503     // block-flow (as well as how marquee overflow should relate to block flow).
2504     // https://bugs.webkit.org/show_bug.cgi?id=46472
2505     if (parent()->isHTMLMarquee()) {
2506         EMarqueeDirection dir = parent()->style().marqueeDirection();
2507         if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
2508             return true;
2509     }
2510
2511 #if ENABLE(MATHML)
2512     // RenderMathMLBlocks take the size of their content, not of their container.
2513     if (parent()->isRenderMathMLBlock())
2514         return true;
2515 #endif
2516
2517     // Flexible box items should shrink wrap, so we lay them out at their intrinsic widths.
2518     // In the case of columns that have a stretch alignment, we layout at the stretched size
2519     // to avoid an extra layout when applying alignment.
2520     if (parent()->isFlexibleBox()) {
2521         // For multiline columns, we need to apply align-content first, so we can't stretch now.
2522         if (!parent()->style().isColumnFlexDirection() || parent()->style().flexWrap() != FlexNoWrap)
2523             return true;
2524         if (!columnFlexItemHasStretchAlignment())
2525             return true;
2526     }
2527
2528     // Flexible horizontal boxes lay out children at their intrinsic widths.  Also vertical boxes
2529     // that don't stretch their kids lay out their children at their intrinsic widths.
2530     // FIXME: Think about block-flow here.
2531     // https://bugs.webkit.org/show_bug.cgi?id=46473
2532     if (parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == HORIZONTAL || parent()->style().boxAlign() != BSTRETCH))
2533         return true;
2534
2535     // Button, input, select, textarea, and legend treat width value of 'auto' as 'intrinsic' unless it's in a
2536     // stretching column flexbox.
2537     // FIXME: Think about block-flow here.
2538     // https://bugs.webkit.org/show_bug.cgi?id=46473
2539     if (logicalWidth.type() == Auto && !isStretchingColumnFlexItem() && element() && (is<HTMLInputElement>(*element()) || is<HTMLSelectElement>(*element()) || is<HTMLButtonElement>(*element()) || is<HTMLTextAreaElement>(*element()) || is<HTMLLegendElement>(*element())))
2540         return true;
2541
2542     if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
2543         return true;
2544
2545     return false;
2546 }
2547
2548 void RenderBox::computeInlineDirectionMargins(const RenderBlock& containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2549 {
2550     
2551     const RenderStyle& containingBlockStyle = containingBlock.style();
2552     Length marginStartLength = style().marginStartUsing(&containingBlockStyle);
2553     Length marginEndLength = style().marginEndUsing(&containingBlockStyle);
2554
2555     if (isFloating() || isInline()) {
2556         // Inline blocks/tables and floats don't have their margins increased.
2557         marginStart = minimumValueForLength(marginStartLength, containerWidth);
2558         marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2559         return;
2560     }
2561
2562     if (containingBlock.isFlexibleBox()) {
2563         // We need to let flexbox handle the margin adjustment - otherwise, flexbox
2564         // will think we're wider than we actually are and calculate line sizes
2565         // wrong. See also http://dev.w3.org/csswg/css-flexbox/#auto-margins
2566         if (marginStartLength.isAuto())
2567             marginStartLength = Length(0, Fixed);
2568         if (marginEndLength.isAuto())
2569             marginEndLength = Length(0, Fixed);
2570     }
2571
2572     // Case One: The object is being centered in the containing block's available logical width.
2573     if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
2574         || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock.style().textAlign() == WEBKIT_CENTER)) {
2575         // Other browsers center the margin box for align=center elements so we match them here.
2576         LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth);
2577         LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth);
2578         LayoutUnit centeredMarginBoxStart = std::max<LayoutUnit>(0, (containerWidth - childWidth - marginStartWidth - marginEndWidth) / 2);
2579         marginStart = centeredMarginBoxStart + marginStartWidth;
2580         marginEnd = containerWidth - childWidth - marginStart + marginEndWidth;
2581         return;
2582     } 
2583     
2584     // Case Two: The object is being pushed to the start of the containing block's available logical width.
2585     if (marginEndLength.isAuto() && childWidth < containerWidth) {
2586         marginStart = valueForLength(marginStartLength, containerWidth);
2587         marginEnd = containerWidth - childWidth - marginStart;
2588         return;
2589     } 
2590     
2591     // Case Three: The object is being pushed to the end of the containing block's available logical width.
2592     bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_LEFT)
2593         || (containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_RIGHT));
2594     if ((marginStartLength.isAuto() || pushToEndFromTextAlign) && childWidth < containerWidth) {
2595         marginEnd = valueForLength(marginEndLength, containerWidth);
2596         marginStart = containerWidth - childWidth - marginEnd;
2597         return;
2598     } 
2599     
2600     // Case Four: Either no auto margins, or our width is >= the container width (css2.1, 10.3.3).  In that case
2601     // auto margins will just turn into 0.
2602     marginStart = minimumValueForLength(marginStartLength, containerWidth);
2603     marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2604 }
2605
2606 RenderBoxFragmentInfo* RenderBox::renderBoxFragmentInfo(RenderFragmentContainer* fragment, RenderBoxFragmentInfoFlags cacheFlag) const
2607 {
2608     // Make sure nobody is trying to call this with a null fragment.
2609     if (!fragment)
2610         return nullptr;
2611
2612     // If we have computed our width in this fragment already, it will be cached, and we can
2613     // just return it.
2614     RenderBoxFragmentInfo* boxInfo = fragment->renderBoxFragmentInfo(this);
2615     if (boxInfo && cacheFlag == CacheRenderBoxFragmentInfo)
2616         return boxInfo;
2617
2618     return nullptr;
2619 }
2620
2621 static bool shouldFlipBeforeAfterMargins(const RenderStyle& containingBlockStyle, const RenderStyle* childStyle)
2622 {
2623     ASSERT(containingBlockStyle.isHorizontalWritingMode() != childStyle->isHorizontalWritingMode());
2624     WritingMode childWritingMode = childStyle->writingMode();
2625     bool shouldFlip = false;
2626     switch (containingBlockStyle.writingMode()) {
2627     case TopToBottomWritingMode:
2628         shouldFlip = (childWritingMode == RightToLeftWritingMode);
2629         break;
2630     case BottomToTopWritingMode:
2631         shouldFlip = (childWritingMode == RightToLeftWritingMode);
2632         break;
2633     case RightToLeftWritingMode:
2634         shouldFlip = (childWritingMode == BottomToTopWritingMode);
2635         break;
2636     case LeftToRightWritingMode:
2637         shouldFlip = (childWritingMode == BottomToTopWritingMode);
2638         break;
2639     }
2640
2641     if (!containingBlockStyle.isLeftToRightDirection())
2642         shouldFlip = !shouldFlip;
2643
2644     return shouldFlip;
2645 }
2646
2647 void RenderBox::cacheIntrinsicContentLogicalHeightForFlexItem(LayoutUnit height) const
2648 {
2649     if (isFloatingOrOutOfFlowPositioned() || !parent() || !parent()->isFlexibleBox())
2650         return;
2651     downcast<RenderFlexibleBox>(parent())->setCachedChildIntrinsicContentLogicalHeight(*this, height);
2652 }
2653
2654 void RenderBox::updateLogicalHeight()
2655 {
2656     cacheIntrinsicContentLogicalHeightForFlexItem(contentLogicalHeight());
2657     auto computedValues = computeLogicalHeight(logicalHeight(), logicalTop());
2658     setLogicalHeight(computedValues.m_extent);
2659     setLogicalTop(computedValues.m_position);
2660     setMarginBefore(computedValues.m_margins.m_before);
2661     setMarginAfter(computedValues.m_margins.m_after);
2662 }
2663
2664 RenderBox::LogicalExtentComputedValues RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop) const
2665 {
2666     LogicalExtentComputedValues computedValues;
2667     computedValues.m_extent = logicalHeight;
2668     computedValues.m_position = logicalTop;
2669
2670     // Cell height is managed by the table and inline non-replaced elements do not support a height property.
2671     if (isTableCell() || (isInline() && !isReplaced()))
2672         return computedValues;
2673
2674     Length h;
2675     if (isOutOfFlowPositioned())
2676         computePositionedLogicalHeight(computedValues);
2677     else {
2678         RenderBlock& cb = *containingBlock();
2679         bool hasPerpendicularContainingBlock = cb.isHorizontalWritingMode() != isHorizontalWritingMode();
2680     
2681         if (!hasPerpendicularContainingBlock) {
2682             bool shouldFlipBeforeAfter = cb.style().writingMode() != style().writingMode();
2683             computeBlockDirectionMargins(cb,
2684                 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2685                 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2686         }
2687
2688         // For tables, calculate margins only.
2689         if (isTable()) {
2690             if (hasPerpendicularContainingBlock) {
2691                 bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb.style(), &style());
2692                 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), computedValues.m_extent,
2693                     shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2694                     shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2695             }
2696             return computedValues;
2697         }
2698
2699         // FIXME: Account for block-flow in flexible boxes.
2700         // https://bugs.webkit.org/show_bug.cgi?id=46418
2701         bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style().boxOrient() == HORIZONTAL;
2702         bool stretching = parent()->style().boxAlign() == BSTRETCH;
2703         bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
2704         bool checkMinMaxHeight = false;
2705
2706         // The parent box is flexing us, so it has increased or decreased our height.  We have to
2707         // grab our cached flexible height.
2708         // FIXME: Account for block-flow in flexible boxes.
2709         // https://bugs.webkit.org/show_bug.cgi?id=46418
2710         if (hasOverrideLogicalContentHeight() && (parent()->isFlexibleBoxIncludingDeprecated() || parent()->isRenderGrid())) {
2711             h = Length(overrideLogicalContentHeight(), Fixed);
2712         } else if (treatAsReplaced)
2713             h = Length(computeReplacedLogicalHeight(), Fixed);
2714         else {
2715             h = style().logicalHeight();
2716             checkMinMaxHeight = true;
2717         }
2718
2719         // Block children of horizontal flexible boxes fill the height of the box.
2720         // FIXME: Account for block-flow in flexible boxes.
2721         // https://bugs.webkit.org/show_bug.cgi?id=46418
2722         if (h.isAuto() && is<RenderDeprecatedFlexibleBox>(*parent()) && parent()->style().boxOrient() == HORIZONTAL
2723                 && downcast<RenderDeprecatedFlexibleBox>(*parent()).isStretchingChildren()) {
2724             h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2725             checkMinMaxHeight = false;
2726         }
2727
2728         LayoutUnit heightResult;
2729         if (checkMinMaxHeight) {
2730             LayoutUnit intrinsicHeight = computedValues.m_extent - borderAndPaddingLogicalHeight();
2731             heightResult = computeLogicalHeightUsing(MainOrPreferredSize, style().logicalHeight(), intrinsicHeight).value_or(computedValues.m_extent);
2732             heightResult = constrainLogicalHeightByMinMax(heightResult, intrinsicHeight);
2733         } else {
2734             // The only times we don't check min/max height are when a fixed length has
2735             // been given as an override.  Just use that.  The value has already been adjusted
2736             // for box-sizing.
2737             ASSERT(h.isFixed());
2738             heightResult = h.value() + borderAndPaddingLogicalHeight();
2739         }
2740
2741         computedValues.m_extent = heightResult;
2742
2743         if (hasPerpendicularContainingBlock) {
2744             bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb.style(), &style());
2745             computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult,
2746                     shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2747                     shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2748         }
2749     }
2750
2751     // WinIE quirk: The <html> block always fills the entire canvas in quirks mode.  The <body> always fills the
2752     // <html> block in quirks mode.  Only apply this quirk if the block is normal flow and no height
2753     // is specified. When we're printing, we also need this quirk if the body or root has a percentage 
2754     // height since we don't set a height in RenderView when we're printing. So without this quirk, the 
2755     // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2756     bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercentOrCalculated()
2757         && (isDocumentElementRenderer() || (isBody() && document().documentElement()->renderer()->style().logicalHeight().isPercentOrCalculated())) && !isInline();
2758     if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2759         LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2760         LayoutUnit visibleHeight = view().pageOrViewLogicalHeight();
2761         if (isDocumentElementRenderer())
2762             computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - margins);
2763         else {
2764             LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2765             computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - marginsBordersPadding);
2766         }
2767     }
2768     return computedValues;
2769 }
2770
2771 LayoutUnit RenderBox::computeLogicalHeightWithoutLayout() const
2772 {
2773     // FIXME:: We should probably return something other than just
2774     // border + padding, but for now we have no good way to do anything else
2775     // without layout, so we just use that.
2776     LogicalExtentComputedValues computedValues = computeLogicalHeight(borderAndPaddingLogicalHeight(), LayoutUnit());
2777     return computedValues.m_extent;
2778 }
2779
2780 std::optional<LayoutUnit> RenderBox::computeLogicalHeightUsing(SizeType heightType, const Length& height, std::optional<LayoutUnit> intrinsicContentHeight) const
2781 {
2782     if (std::optional<LayoutUnit> logicalHeight = computeContentAndScrollbarLogicalHeightUsing(heightType, height, intrinsicContentHeight))
2783         return adjustBorderBoxLogicalHeightForBoxSizing(logicalHeight.value());
2784     return std::nullopt;
2785 }
2786
2787 std::optional<LayoutUnit> RenderBox::computeContentLogicalHeight(SizeType heightType, const Length& height, std::optional<LayoutUnit> intrinsicContentHeight) const
2788 {
2789     if (std::optional<LayoutUnit> heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(heightType, height, intrinsicContentHeight))
2790         return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2791     return std::nullopt;
2792 }
2793
2794 std::optional<LayoutUnit> RenderBox::computeIntrinsicLogicalContentHeightUsing(Length logicalHeightLength, std::optional<LayoutUnit> intrinsicContentHeight, LayoutUnit borderAndPadding) const
2795 {
2796     // FIXME: The CSS sizing spec is considering changing what min-content/max-content should resolve to.
2797     // If that happens, this code will have to change.
2798     if (logicalHeightLength.isMinContent() || logicalHeightLength.isMaxContent() || logicalHeightLength.isFitContent()) {
2799         if (!intrinsicContentHeight)
2800             return intrinsicContentHeight;
2801         if (style().boxSizing() == BORDER_BOX)
2802             return intrinsicContentHeight.value() + borderAndPaddingLogicalHeight();
2803         return intrinsicContentHeight;
2804     }
2805     if (logicalHeightLength.isFillAvailable())
2806         return containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding) - borderAndPadding;
2807     ASSERT_NOT_REACHED();
2808     return LayoutUnit(0);
2809 }
2810
2811 std::optional<LayoutUnit> RenderBox::computeContentAndScrollbarLogicalHeightUsing(SizeType heightType, const Length& height, std::optional<LayoutUnit> intrinsicContentHeight) const
2812 {
2813     if (height.isAuto())
2814         return heightType == MinSize ? std::optional<LayoutUnit>(0) : std::nullopt;
2815     // FIXME: The CSS sizing spec is considering changing what min-content/max-content should resolve to.
2816     // If that happens, this code will have to change.
2817     if (height.isIntrinsic())
2818         return computeIntrinsicLogicalContentHeightUsing(height, intrinsicContentHeight, borderAndPaddingLogicalHeight());
2819     if (height.isFixed())
2820         return LayoutUnit(height.value());
2821     if (height.isPercentOrCalculated())
2822         return computePercentageLogicalHeight(height);
2823     return std::nullopt;
2824 }
2825
2826 bool RenderBox::skipContainingBlockForPercentHeightCalculation(const RenderBox& containingBlock, bool isPerpendicularWritingMode) const
2827 {
2828     // Flow threads for multicol or paged overflow should be skipped. They are invisible to the DOM,
2829     // and percent heights of children should be resolved against the multicol or paged container.
2830     if (containingBlock.isInFlowRenderFragmentedFlow() && !isPerpendicularWritingMode)
2831         return true;
2832
2833     // Render view is not considered auto height.
2834     if (is<RenderView>(containingBlock))
2835         return false;
2836
2837     // If the writing mode of the containing block is orthogonal to ours, it means
2838     // that we shouldn't skip anything, since we're going to resolve the
2839     // percentage height against a containing block *width*.
2840     if (isPerpendicularWritingMode)
2841         return false;
2842     
2843     // Anonymous blocks should not impede percentage resolution on a child.
2844     // Examples of such anonymous blocks are blocks wrapped around inlines that
2845     // have block siblings (from the CSS spec) and multicol flow threads (an
2846     // implementation detail). Another implementation detail, ruby runs, create
2847     // anonymous inline-blocks, so skip those too. All other types of anonymous
2848     // objects, such as table-cells and flexboxes, will be treated as if they were
2849     // non-anonymous.
2850     if (containingBlock.isAnonymous())
2851         return containingBlock.style().display() == BLOCK || containingBlock.style().display() == INLINE_BLOCK;
2852     
2853     // For quirks mode, we skip most auto-height containing blocks when computing
2854     // percentages.
2855     return document().inQuirksMode() && !containingBlock.isTableCell() && !containingBlock.isOutOfFlowPositioned() && !containingBlock.isRenderGrid() && containingBlock.style().logicalHeight().isAuto();
2856 }
2857
2858 bool RenderBox::shouldTreatChildAsReplacedInTableCells() const
2859 {
2860     if (isReplaced())
2861         return true;
2862     return element() && (element()->isFormControlElement() || is<HTMLImageElement>(element()));
2863 }
2864
2865 static bool tableCellShouldHaveZeroInitialSize(const RenderBlock& block, const RenderBox& child, bool scrollsOverflowY)
2866 {
2867     // Normally we would let the cell size intrinsically, but scrolling overflow has to be
2868     // treated differently, since WinIE lets scrolled overflow fragments shrink as needed.
2869     // While we can't get all cases right, we can at least detect when the cell has a specified
2870     // height or when the table has a specified height. In these cases we want to initially have
2871     // no size and allow the flexing of the table or the cell to its specified height to cause us
2872     // to grow to fill the space. This could end up being wrong in some cases, but it is
2873     // preferable to the alternative (sizing intrinsically and making the row end up too big).
2874     const RenderTableCell& cell = downcast<RenderTableCell>(block);
2875     return scrollsOverflowY && !child.shouldTreatChildAsReplacedInTableCells() && (!cell.style().logicalHeight().isAuto() || !cell.table()->style().logicalHeight().isAuto());
2876 }
2877
2878 std::optional<LayoutUnit> RenderBox::computePercentageLogicalHeight(const Length& height) const
2879 {
2880     std::optional<LayoutUnit> availableHeight;
2881
2882     bool skippedAutoHeightContainingBlock = false;
2883     RenderBlock* cb = containingBlock();
2884     const RenderBox* containingBlockChild = this;
2885     LayoutUnit rootMarginBorderPaddingHeight = 0;
2886     bool isHorizontal = isHorizontalWritingMode();
2887     while (cb && !is<RenderView>(*cb) && skipContainingBlockForPercentHeightCalculation(*cb, isHorizontal != cb->isHorizontalWritingMode())) {
2888         if (cb->isBody() || cb->isDocumentElementRenderer())
2889             rootMarginBorderPaddingHeight += cb->marginBefore() + cb->marginAfter() + cb->borderAndPaddingLogicalHeight();
2890         skippedAutoHeightContainingBlock = true;
2891         containingBlockChild = cb;
2892         cb = cb->containingBlock();
2893     }
2894     cb->addPercentHeightDescendant(const_cast<RenderBox&>(*this));
2895
2896     if (isHorizontal != cb->isHorizontalWritingMode())
2897         availableHeight = containingBlockChild->containingBlockLogicalWidthForContent();
2898     else if (hasOverrideContainingBlockLogicalHeight())
2899         availableHeight = overrideContainingBlockContentLogicalHeight();
2900     else if (is<RenderTableCell>(*cb)) {
2901         if (!skippedAutoHeightContainingBlock) {
2902             // Table cells violate what the CSS spec says to do with heights. Basically we
2903             // don't care if the cell specified a height or not. We just always make ourselves
2904             // be a percentage of the cell's current content height.
2905             if (!cb->hasOverrideLogicalContentHeight())
2906                 return tableCellShouldHaveZeroInitialSize(*cb, *this, scrollsOverflowY()) ? std::optional<LayoutUnit>(0) : std::nullopt;
2907
2908             availableHeight = cb->overrideLogicalContentHeight();
2909         }
2910     } else
2911         availableHeight = cb->availableLogicalHeightForPercentageComputation();
2912     
2913     if (!availableHeight)
2914         return availableHeight;
2915
2916     LayoutUnit result = valueForLength(height, availableHeight.value() - rootMarginBorderPaddingHeight + (isTable() && isOutOfFlowPositioned() ? cb->paddingBefore() + cb->paddingAfter() : LayoutUnit()));
2917     
2918     // |overrideLogicalContentHeight| is the maximum height made available by the
2919     // cell to its percent height children when we decide they can determine the
2920     // height of the cell. If the percent height child is box-sizing:content-box
2921     // then we must subtract the border and padding from the cell's
2922     // |availableHeight| (given by |overrideLogicalContentHeight|) to arrive
2923     // at the child's computed height.
2924     bool subtractBorderAndPadding = isTable() || (is<RenderTableCell>(*cb) && !skippedAutoHeightContainingBlock && cb->hasOverrideLogicalContentHeight());
2925     if (subtractBorderAndPadding) {
2926         result -= borderAndPaddingLogicalHeight();
2927         return std::max(LayoutUnit(), result);
2928     }
2929     return result;
2930 }
2931
2932 LayoutUnit RenderBox::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
2933 {
2934     return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(MainOrPreferredSize, style().logicalWidth()), shouldComputePreferred);
2935 }
2936
2937 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, ShouldComputePreferred shouldComputePreferred) const
2938 {
2939     auto& logicalMinWidth = style().logicalMinWidth();
2940     auto& logicalMaxWidth = style().logicalMaxWidth();
2941     bool useLogicalWidthForMinWidth = (shouldComputePreferred == ComputePreferred && logicalMinWidth.isPercentOrCalculated()) || logicalMinWidth.isUndefined();
2942     bool useLogicalWidthForMaxWidth = (shouldComputePreferred == ComputePreferred && logicalMaxWidth.isPercentOrCalculated()) || logicalMaxWidth.isUndefined();
2943     auto minLogicalWidth =  useLogicalWidthForMinWidth ? logicalWidth : computeReplacedLogicalWidthUsing(MinSize, logicalMinWidth);
2944     auto maxLogicalWidth =  useLogicalWidthForMaxWidth ? logicalWidth : computeReplacedLogicalWidthUsing(MaxSize, logicalMaxWidth);
2945     return std::max(minLogicalWidth, std::min(logicalWidth, maxLogicalWidth));
2946 }
2947
2948 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(SizeType widthType, Length logicalWidth) const
2949 {
2950     ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto());
2951     if (widthType == MinSize && logicalWidth.isAuto())
2952         return adjustContentBoxLogicalWidthForBoxSizing(0);
2953
2954     switch (logicalWidth.type()) {
2955         case Fixed:
2956             return adjustContentBoxLogicalWidthForBoxSizing(logicalWidth.value());
2957         case MinContent:
2958         case MaxContent: {
2959             // MinContent/MaxContent don't need the availableLogicalWidth argument.
2960             LayoutUnit availableLogicalWidth = 0;
2961             return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2962         }
2963         case FitContent:
2964         case FillAvailable:
2965         case Percent: 
2966         case Calculated: {
2967             // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
2968             // containing block's block-flow.
2969             // https://bugs.webkit.org/show_bug.cgi?id=46496
2970             const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(downcast<RenderBoxModelObject>(*container())) : containingBlockLogicalWidthForContent();
2971             Length containerLogicalWidth = containingBlock()->style().logicalWidth();
2972             // FIXME: Handle cases when containing block width is calculated or viewport percent.
2973             // https://bugs.webkit.org/show_bug.cgi?id=91071
2974             if (logicalWidth.isIntrinsic())
2975                 return computeIntrinsicLogicalWidthUsing(logicalWidth, cw, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2976             if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercentOrCalculated())))
2977                 return adjustContentBoxLogicalWidthForBoxSizing(minimumValueForLength(logicalWidth, cw));
2978             return LayoutUnit();
2979         }
2980         case Intrinsic:
2981         case MinIntrinsic:
2982         case Auto:
2983         case Relative:
2984         case Undefined:
2985             return intrinsicLogicalWidth();
2986     }
2987
2988     ASSERT_NOT_REACHED();
2989     return 0;
2990 }
2991
2992 LayoutUnit RenderBox::computeReplacedLogicalHeight(std::optional<LayoutUnit>) const
2993 {
2994     return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(MainOrPreferredSize, style().logicalHeight()));
2995 }
2996
2997 static bool allowMinMaxPercentagesInAutoHeightBlocksQuirk()
2998 {
2999 #if PLATFORM(MAC)
3000     return MacApplication::isIBooks();
3001 #elif PLATFORM(IOS)
3002     return IOSApplication::isIBooks();
3003 #endif
3004     return false;
3005 }
3006
3007 bool RenderBox::replacedMinMaxLogicalHeightComputesAsNone(SizeType sizeType) const
3008 {
3009     ASSERT(sizeType == MinSize || sizeType == MaxSize);
3010     
3011     auto logicalHeight = sizeType == MinSize ? style().logicalMinHeight() : style().logicalMaxHeight();
3012     auto initialLogicalHeight = sizeType == MinSize ? RenderStyle::initialMinSize() : RenderStyle::initialMaxSize();
3013     
3014     if (logicalHeight == initialLogicalHeight)
3015         return true;
3016     
3017     // Make sure % min-height and % max-height resolve to none if the containing block has auto height.
3018     // Note that the "height" case for replaced elements was handled by hasReplacedLogicalHeight, which is why
3019     // min and max-height are the only ones handled here.
3020     // FIXME: For now we put in a quirk for iBooks until we can move them to viewport units.
3021     if (auto* cb = containingBlockForAutoHeightDetection(logicalHeight))
3022         return allowMinMaxPercentagesInAutoHeightBlocksQuirk() ? false : cb->hasAutoHeightOrContainingBlockWithAutoHeight();
3023
3024     return false;
3025 }
3026
3027 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
3028 {
3029     LayoutUnit minLogicalHeight;
3030     if (!replacedMinMaxLogicalHeightComputesAsNone(MinSize))
3031         minLogicalHeight = computeReplacedLogicalHeightUsing(MinSize, style().logicalMinHeight());
3032     LayoutUnit maxLogicalHeight = logicalHeight;
3033     if (!replacedMinMaxLogicalHeightComputesAsNone(MaxSize))
3034         maxLogicalHeight = computeReplacedLogicalHeightUsing(MaxSize, style().logicalMaxHeight());
3035     return std::max(minLogicalHeight, std::min(logicalHeight, maxLogicalHeight));
3036 }
3037
3038 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(SizeType heightType, Length logicalHeight) const
3039 {
3040     ASSERT(heightType == MinSize || heightType == MainOrPreferredSize || !logicalHeight.isAuto());
3041     if (heightType == MinSize && logicalHeight.isAuto())
3042         return adjustContentBoxLogicalHeightForBoxSizing(std::optional<LayoutUnit>(0));
3043
3044     switch (logicalHeight.type()) {
3045         case Fixed:
3046             return adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(logicalHeight.value()));
3047         case Percent:
3048         case Calculated:
3049         {
3050             auto* container = isOutOfFlowPositioned() ? this->container() : containingBlock();
3051             while (container && container->isAnonymous()) {
3052                 // Stop at rendering context root.
3053                 if (is<RenderView>(*container))
3054                     break;
3055                 container = container->containingBlock();
3056             }
3057             std::optional<LayoutUnit> stretchedHeight;
3058             if (is<RenderBlock>(container)) {
3059                 auto* block = downcast<RenderBlock>(container);
3060                 block->addPercentHeightDescendant(*const_cast<RenderBox*>(this));
3061                 if (block->isFlexItem())
3062                     stretchedHeight = downcast<RenderFlexibleBox>(block->parent())->childLogicalHeightForPercentageResolution(*block);
3063                 else if (block->isGridItem() && block->hasOverrideLogicalContentHeight())
3064                     stretchedHeight = block->overrideLogicalContentHeight();
3065             }
3066
3067             // FIXME: This calculation is not patched for block-flow yet.
3068             // https://bugs.webkit.org/show_bug.cgi?id=46500
3069             if (container->isOutOfFlowPositioned()
3070                 && container->style().height().isAuto()
3071                 && !(container->style().top().isAuto() || container->style().bottom().isAuto())) {
3072                 ASSERT_WITH_SECURITY_IMPLICATION(container->isRenderBlock());
3073                 auto& block = downcast<RenderBlock>(*container);
3074                 auto computedValues = block.computeLogicalHeight(block.logicalHeight(), 0);
3075                 LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3076                 LayoutUnit newHeight = block.adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3077                 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, newHeight));
3078             }
3079             
3080             // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
3081             // containing block's block-flow.
3082             // https://bugs.webkit.org/show_bug.cgi?id=46496
3083             LayoutUnit availableHeight;
3084             if (isOutOfFlowPositioned())
3085                 availableHeight = containingBlockLogicalHeightForPositioned(downcast<RenderBoxModelObject>(*container));
3086             else if (stretchedHeight)
3087                 availableHeight = stretchedHeight.value();
3088             else {
3089                 availableHeight = containingBlockLogicalHeightForContent(IncludeMarginBorderPadding);
3090                 // It is necessary to use the border-box to match WinIE's broken
3091                 // box model.  This is essential for sizing inside
3092                 // table cells using percentage heights.
3093                 // FIXME: This needs to be made block-flow-aware.  If the cell and image are perpendicular block-flows, this isn't right.
3094                 // https://bugs.webkit.org/show_bug.cgi?id=46997
3095                 while (container && !is<RenderView>(*container)
3096                     && (container->style().logicalHeight().isAuto() || container->style().logicalHeight().isPercentOrCalculated())) {
3097                     if (container->isTableCell()) {
3098                         // Don't let table cells squeeze percent-height replaced elements
3099                         // <http://bugs.webkit.org/show_bug.cgi?id=15359>
3100                         availableHeight = std::max(availableHeight, intrinsicLogicalHeight());
3101                         return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight());
3102                     }
3103                     downcast<RenderBlock>(*container).addPercentHeightDescendant(const_cast<RenderBox&>(*this));
3104                     container = container->containingBlock();
3105                 }
3106             }
3107             return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight));
3108         }
3109         case MinContent:
3110         case MaxContent:
3111         case FitContent:
3112         case FillAvailable:
3113             return adjustContentBoxLogicalHeightForBoxSizing(computeIntrinsicLogicalContentHeightUsing(logicalHeight, intrinsicLogicalHeight(), borderAndPaddingLogicalHeight()));
3114         default:
3115             return intrinsicLogicalHeight();
3116     }
3117 }
3118
3119 LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const
3120 {
3121     return constrainLogicalHeightByMinMax(availableLogicalHeightUsing(style().logicalHeight(), heightType), std::nullopt);
3122 }
3123
3124 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const
3125 {
3126     // We need to stop here, since we don't want to increase the height of the table
3127     // artificially.  We're going to rely on this cell getting expanded to some new
3128     // height, and then when we lay out again we'll use the calculation below.
3129     if (isTableCell() && (h.isAuto() || h.isPercentOrCalculated())) {
3130         if (hasOverrideLogicalContentHeight())
3131             return overrideLogicalContentHeight();
3132         return logicalHeight() - borderAndPaddingLogicalHeight();
3133     }
3134
3135     if (isFlexItem()) {
3136         auto& flexBox = downcast<RenderFlexibleBox>(*parent());
3137         auto stretchedHeight = flexBox.childLogicalHeightForPercentageResolution(*this);
3138         if (stretchedHeight)
3139             return stretchedHeight.value();
3140     }
3141
3142     if (h.isPercentOrCalculated() && isOutOfFlowPositioned() && !isRenderFragmentedFlow()) {
3143         // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3144         LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(*containingBlock());
3145         return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight));
3146     }
3147
3148     if (std::optional<LayoutUnit> heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(MainOrPreferredSize, h, std::nullopt))
3149         return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
3150
3151     // FIXME: Check logicalTop/logicalBottom here to correctly handle vertical writing-mode.
3152     // https://bugs.webkit.org/show_bug.cgi?id=46500
3153     if (is<RenderBlock>(*this) && isOutOfFlowPositioned() && style().height().isAuto() && !(style().top().isAuto() || style().bottom().isAuto())) {
3154         RenderBlock& block = const_cast<RenderBlock&>(downcast<RenderBlock>(*this));
3155         auto computedValues = block.computeLogicalHeight(block.logicalHeight(), 0);
3156         LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3157         return adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3158     }
3159
3160     // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3161     LayoutUnit availableHeight = containingBlockLogicalHeightForContent(heightType);
3162     if (heightType == ExcludeMarginBorderPadding) {
3163         // FIXME: Margin collapsing hasn't happened yet, so this incorrectly removes collapsed margins.
3164         availableHeight -= marginBefore() + marginAfter() + borderAndPaddingLogicalHeight();
3165     }
3166     return availableHeight;
3167 }
3168
3169 void RenderBox::computeBlockDirectionMargins(const RenderBlock& containingBlock, LayoutUnit& marginBefore, LayoutUnit& marginAfter) const
3170 {
3171     if (isTableCell()) {
3172         // FIXME: Not right if we allow cells to have different directionality than the table.  If we do allow this, though,
3173         // we may just do it with an extra anonymous block inside the cell.
3174         marginBefore = 0;
3175         marginAfter = 0;
3176         return;
3177     }
3178
3179     // Margins are calculated with respect to the logical width of
3180     // the containing block (8.3)
3181     LayoutUnit cw = containingBlockLogicalWidthForContent();
3182     const RenderStyle& containingBlockStyle = containingBlock.style();
3183     marginBefore = minimumValueForLength(style().marginBeforeUsing(&containingBlockStyle), cw);
3184     marginAfter = minimumValueForLength(style().marginAfterUsing(&containingBlockStyle), cw);
3185 }
3186
3187 void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock& containingBlock)
3188 {
3189     LayoutUnit marginBefore;
3190     LayoutUnit marginAfter;
3191     computeBlockDirectionMargins(containingBlock, marginBefore, marginAfter);
3192     containingBlock.setMarginBeforeForChild(*this, marginBefore);
3193     containingBlock.setMarginAfterForChild(*this, marginAfter);
3194 }
3195
3196 LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject& containingBlock, RenderFragmentContainer* fragment, bool checkForPerpendicularWritingMode) const
3197 {
3198     if (checkForPerpendicularWritingMode && containingBlock.isHorizontalWritingMode() != isHorizontalWritingMode())
3199         return containingBlockLogicalHeightForPositioned(containingBlock, false);
3200
3201     if (hasOverrideContainingBlockLogicalWidth()) {
3202         if (auto overrideLogicalWidth = overrideContainingBlockContentLogicalWidth())
3203             return overrideLogicalWidth.value();
3204     }
3205
3206     if (is<RenderBox>(containingBlock)) {
3207         bool isFixedPosition = style().position() == FixedPosition;
3208
3209         RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
3210         if (!fragmentedFlow) {
3211             if (isFixedPosition && is<RenderView>(containingBlock))
3212                 return downcast<RenderView>(containingBlock).clientLogicalWidthForFixedPosition();
3213
3214             return downcast<RenderBox>(containingBlock).clientLogicalWidth();
3215         }
3216
3217         if (!is<RenderBlock>(containingBlock))
3218             return downcast<RenderBox>(containingBlock).clientLogicalWidth();
3219
3220         const RenderBlock& cb = downcast<RenderBlock>(containingBlock);
3221         RenderBoxFragmentInfo* boxInfo = nullptr;
3222         if (!fragment) {
3223             if (is<RenderFragmentedFlow>(containingBlock) && !checkForPerpendicularWritingMode)
3224                 return downcast<RenderFragmentedFlow>(containingBlock).contentLogicalWidthOfFirstFragment();
3225             if (isWritingModeRoot()) {
3226                 LayoutUnit cbPageOffset = cb.offsetFromLogicalTopOfFirstPage();
3227                 RenderFragmentContainer* cbFragment = cb.fragmentAtBlockOffset(cbPageOffset);
3228                 if (cbFragment)
3229                     boxInfo = cb.renderBoxFragmentInfo(cbFragment);
3230             }
3231         } else if (fragmentedFlow->isHorizontalWritingMode() == containingBlock.isHorizontalWritingMode()) {
3232             RenderFragmentContainer* containingBlockFragment = cb.clampToStartAndEndFragments(fragment);
3233             boxInfo = cb.renderBoxFragmentInfo(containingBlockFragment);
3234         }
3235         return (boxInfo) ? std::max<LayoutUnit>(0, cb.clientLogicalWidth() - (cb.logicalWidth() - boxInfo->logicalWidth())) : cb.clientLogicalWidth();
3236     }
3237
3238     ASSERT(containingBlock.isInFlowPositioned());
3239
3240     const auto& flow = downcast<RenderInline>(containingBlock);
3241     InlineFlowBox* first = flow.firstLineBox();
3242     InlineFlowBox* last = flow.lastLineBox();
3243
3244     // If the containing block is empty, return a width of 0.
3245     if (!first || !last)
3246         return 0;
3247
3248     LayoutUnit fromLeft;
3249     LayoutUnit fromRight;
3250     if (containingBlock.style().isLeftToRightDirection()) {
3251         fromLeft = first->logicalLeft() + first->borderLogicalLeft();
3252         fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
3253     } else {
3254         fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
3255         fromLeft = last->logicalLeft() + last->borderLogicalLeft();
3256     }
3257
3258     return std::max<LayoutUnit>(0, fromRight - fromLeft);
3259 }
3260
3261 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject& containingBlock, bool checkForPerpendicularWritingMode) const
3262 {
3263     if (checkForPerpendicularWritingMode && containingBlock.isHorizontalWritingMode() != isHorizontalWritingMode())
3264         return containingBlockLogicalWidthForPositioned(containingBlock, nullptr, false);
3265
3266     if (hasOverrideContainingBlockLogicalHeight()) {
3267         if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight())
3268             return overrideLogicalHeight.value();
3269     }
3270
3271     if (containingBlock.isBox()) {
3272         bool isFixedPosition = style().position() == FixedPosition;
3273
3274         if (isFixedPosition && is<RenderView>(containingBlock))
3275             return downcast<RenderView>(containingBlock).clientLogicalHeightForFixedPosition();
3276
3277         const RenderBlock& cb = is<RenderBlock>(containingBlock) ? downcast<RenderBlock>(containingBlock) : *containingBlock.containingBlock();
3278         LayoutUnit result = cb.clientLogicalHeight();
3279         RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
3280         if (fragmentedFlow && is<RenderFragmentedFlow>(containingBlock) && fragmentedFlow->isHorizontalWritingMode() == containingBlock.isHorizontalWritingMode())
3281             return downcast<RenderFragmentedFlow>(containingBlock).contentLogicalHeightOfFirstFragment();
3282         return result;
3283     }
3284         
3285     ASSERT(containingBlock.isInFlowPositioned());
3286
3287     const auto& flow = downcast<RenderInline>(containingBlock);
3288     InlineFlowBox* first = flow.firstLineBox();
3289     InlineFlowBox* last = flow.lastLineBox();
3290
3291     // If the containing block is empty, return a height of 0.
3292     if (!first || !last)
3293         return 0;
3294
3295     LayoutUnit heightResult;
3296     LayoutRect boundingBox = flow.linesBoundingBox();
3297     if (containingBlock.isHorizontalWritingMode())
3298         heightResult = boundingBox.height();
3299     else
3300         heightResult = boundingBox.width();
3301     heightResult -= (containingBlock.borderBefore() + containingBlock.borderAfter());
3302     return heightResult;
3303 }
3304
3305 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject& containerBlock, LayoutUnit containerLogicalWidth, RenderFragmentContainer* fragment)
3306 {
3307     if (!logicalLeft.isAuto() || !logicalRight.isAuto())
3308         return;
3309
3310     RenderObject* parent = child->parent();
3311     TextDirection parentDirection = parent->style().direction();
3312
3313     // This method is using enclosingBox() which is wrong for absolutely
3314     // positioned grid items, as they rely on the grid area. So for grid items if
3315     // both "left" and "right" properties are "auto", we can consider that one of
3316     // them (depending on the direction) is simply "0".
3317     if (parent->isRenderGrid() && parent == child->containingBlock()) {
3318         if (parentDirection == LTR)
3319             logicalLeft.setValue(Fixed, 0);
3320         else
3321             logicalRight.setValue(Fixed, 0);
3322         return;
3323     }
3324
3325     // FIXME: The static distance computation has not been patched for mixed writing modes yet.
3326     if (parentDirection == LTR) {
3327         LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock.borderLogicalLeft();
3328         for (auto* current = parent; current && current != &containerBlock; current = current->container()) {
3329             if (!is<RenderBox>(*current))
3330                 continue;
3331             const auto& renderBox = downcast<RenderBox>(*current);
3332             staticPosition += renderBox.logicalLeft();
3333             if (renderBox.isInFlowPositioned())
3334                 staticPosition += renderBox.isHorizontalWritingMode() ? renderBox.offsetForInFlowPosition().width() : renderBox.offsetForInFlowPosition().height();
3335             if (fragment && is<RenderBlock>(*current)) {