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