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