Make compositing updates incremental
[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().rootLayerConfigurationChanged();
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 && !canUseOverlayScrollbars())) {
776         ASSERT(layer() && layer()->hasVerticalScrollbar());
777         return verticalScrollbarWidth();
778     }
779
780     if (!isHorizontalWritingMode() && (style().overflowX() == Overflow::Scroll && !canUseOverlayScrollbars())) {
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::canUseOverlayScrollbars() const
938 {
939     return !style().hasPseudoStyle(PseudoId::Scrollbar) && ScrollbarTheme::theme().usesOverlayScrollbars();
940 }
941
942 bool RenderBox::hasVerticalScrollbarWithAutoBehavior() const
943 {
944     return hasOverflowClip() && (style().overflowY() == Overflow::Auto || (style().overflowY() == Overflow::Scroll && canUseOverlayScrollbars()));
945 }
946
947 bool RenderBox::hasHorizontalScrollbarWithAutoBehavior() const
948 {
949     return hasOverflowClip() && (style().overflowX() == Overflow::Auto || (style().overflowX() == Overflow::Scroll && canUseOverlayScrollbars()));
950 }
951
952 bool RenderBox::needsPreferredWidthsRecalculation() const
953 {
954     return style().paddingStart().isPercentOrCalculated() || style().paddingEnd().isPercentOrCalculated();
955 }
956
957 ScrollPosition RenderBox::scrollPosition() const
958 {
959     if (!hasOverflowClip())
960         return { 0, 0 };
961
962     ASSERT(hasLayer());
963     return layer()->scrollPosition();
964 }
965
966 LayoutSize RenderBox::cachedSizeForOverflowClip() const
967 {
968     ASSERT(hasOverflowClip());
969     ASSERT(hasLayer());
970     return layer()->size();
971 }
972
973 bool RenderBox::applyCachedClipAndScrollPosition(LayoutRect& rect, const RenderLayerModelObject* container, VisibleRectContext context) const
974 {
975     flipForWritingMode(rect);
976
977     if (context.m_options.contains(VisibleRectContextOption::ApplyCompositedContainerScrolls) || this != container || !usesCompositedScrolling())
978         rect.moveBy(-scrollPosition()); // For overflow:auto/scroll/hidden.
979
980     // Do not clip scroll layer contents to reduce the number of repaints while scrolling.
981     if (!context.m_options.contains(VisibleRectContextOption::ApplyCompositedClips) && usesCompositedScrolling()) {
982         flipForWritingMode(rect);
983         return true;
984     }
985
986     // height() is inaccurate if we're in the middle of a layout of this RenderBox, so use the
987     // layer's size instead. Even if the layer's size is wrong, the layer itself will repaint
988     // anyway if its size does change.
989     LayoutRect clipRect(LayoutPoint(), cachedSizeForOverflowClip());
990     bool intersects;
991     if (context.m_options.contains(VisibleRectContextOption::UseEdgeInclusiveIntersection))
992         intersects = rect.edgeInclusiveIntersect(clipRect);
993     else {
994         rect.intersect(clipRect);
995         intersects = !rect.isEmpty();
996     }
997     flipForWritingMode(rect);
998     return intersects;
999 }
1000
1001 void RenderBox::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
1002 {
1003     minLogicalWidth = minPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
1004     maxLogicalWidth = maxPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
1005 }
1006
1007 LayoutUnit RenderBox::minPreferredLogicalWidth() 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_minPreferredLogicalWidth;
1017 }
1018
1019 LayoutUnit RenderBox::maxPreferredLogicalWidth() const
1020 {
1021     if (preferredLogicalWidthsDirty()) {
1022 #ifndef NDEBUG
1023         SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox*>(this));
1024 #endif
1025         const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
1026     }
1027         
1028     return m_maxPreferredLogicalWidth;
1029 }
1030
1031 bool RenderBox::hasOverrideContentLogicalHeight() const
1032 {
1033     return gOverrideContentLogicalHeightMap && gOverrideContentLogicalHeightMap->contains(this);
1034 }
1035
1036 bool RenderBox::hasOverrideContentLogicalWidth() const
1037 {
1038     return gOverrideContentLogicalWidthMap && gOverrideContentLogicalWidthMap->contains(this);
1039 }
1040
1041 void RenderBox::setOverrideContentLogicalHeight(LayoutUnit height)
1042 {
1043     if (!gOverrideContentLogicalHeightMap)
1044         gOverrideContentLogicalHeightMap = new OverrideSizeMap();
1045     gOverrideContentLogicalHeightMap->set(this, height);
1046 }
1047
1048 void RenderBox::setOverrideContentLogicalWidth(LayoutUnit width)
1049 {
1050     if (!gOverrideContentLogicalWidthMap)
1051         gOverrideContentLogicalWidthMap = new OverrideSizeMap();
1052     gOverrideContentLogicalWidthMap->set(this, width);
1053 }
1054
1055 void RenderBox::clearOverrideContentLogicalHeight()
1056 {
1057     if (gOverrideContentLogicalHeightMap)
1058         gOverrideContentLogicalHeightMap->remove(this);
1059 }
1060
1061 void RenderBox::clearOverrideContentLogicalWidth()
1062 {
1063     if (gOverrideContentLogicalWidthMap)
1064         gOverrideContentLogicalWidthMap->remove(this);
1065 }
1066
1067 void RenderBox::clearOverrideContentSize()
1068 {
1069     clearOverrideContentLogicalHeight();
1070     clearOverrideContentLogicalWidth();
1071 }
1072
1073 LayoutUnit RenderBox::overrideContentLogicalWidth() const
1074 {
1075     ASSERT(hasOverrideContentLogicalWidth());
1076     return gOverrideContentLogicalWidthMap->get(this);
1077 }
1078
1079 LayoutUnit RenderBox::overrideContentLogicalHeight() const
1080 {
1081     ASSERT(hasOverrideContentLogicalHeight());
1082     return gOverrideContentLogicalHeightMap->get(this);
1083 }
1084
1085 std::optional<LayoutUnit> RenderBox::overrideContainingBlockContentLogicalWidth() const
1086 {
1087     ASSERT(hasOverrideContainingBlockContentLogicalWidth());
1088     return gOverrideContainingBlockContentLogicalWidthMap->get(this);
1089 }
1090
1091 std::optional<LayoutUnit> RenderBox::overrideContainingBlockContentLogicalHeight() const
1092 {
1093     ASSERT(hasOverrideContainingBlockContentLogicalHeight());
1094     return gOverrideContainingBlockContentLogicalHeightMap->get(this);
1095 }
1096
1097 bool RenderBox::hasOverrideContainingBlockContentLogicalWidth() const
1098 {
1099     return gOverrideContainingBlockContentLogicalWidthMap && gOverrideContainingBlockContentLogicalWidthMap->contains(this);
1100 }
1101
1102 bool RenderBox::hasOverrideContainingBlockContentLogicalHeight() const
1103 {
1104     return gOverrideContainingBlockContentLogicalHeightMap && gOverrideContainingBlockContentLogicalHeightMap->contains(this);
1105 }
1106
1107 void RenderBox::setOverrideContainingBlockContentLogicalWidth(std::optional<LayoutUnit> logicalWidth)
1108 {
1109     if (!gOverrideContainingBlockContentLogicalWidthMap)
1110         gOverrideContainingBlockContentLogicalWidthMap = new OverrideOptionalSizeMap;
1111     gOverrideContainingBlockContentLogicalWidthMap->set(this, logicalWidth);
1112 }
1113
1114 void RenderBox::setOverrideContainingBlockContentLogicalHeight(std::optional<LayoutUnit> logicalHeight)
1115 {
1116     if (!gOverrideContainingBlockContentLogicalHeightMap)
1117         gOverrideContainingBlockContentLogicalHeightMap = new OverrideOptionalSizeMap;
1118     gOverrideContainingBlockContentLogicalHeightMap->set(this, logicalHeight);
1119 }
1120
1121 void RenderBox::clearOverrideContainingBlockContentSize()
1122 {
1123     if (gOverrideContainingBlockContentLogicalWidthMap)
1124         gOverrideContainingBlockContentLogicalWidthMap->remove(this);
1125     clearOverrideContainingBlockContentLogicalHeight();
1126 }
1127
1128 void RenderBox::clearOverrideContainingBlockContentLogicalHeight()
1129 {
1130     if (gOverrideContainingBlockContentLogicalHeightMap)
1131         gOverrideContainingBlockContentLogicalHeightMap->remove(this);
1132 }
1133
1134 LayoutUnit RenderBox::adjustBorderBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1135 {
1136     LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
1137     if (style().boxSizing() == BoxSizing::ContentBox)
1138         return width + bordersPlusPadding;
1139     return std::max(width, bordersPlusPadding);
1140 }
1141
1142 LayoutUnit RenderBox::adjustBorderBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1143 {
1144     LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
1145     if (style().boxSizing() == BoxSizing::ContentBox)
1146         return height + bordersPlusPadding;
1147     return std::max(height, bordersPlusPadding);
1148 }
1149
1150 LayoutUnit RenderBox::adjustContentBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1151 {
1152     if (style().boxSizing() == BoxSizing::BorderBox)
1153         width -= borderAndPaddingLogicalWidth();
1154     return std::max<LayoutUnit>(0, width);
1155 }
1156
1157 LayoutUnit RenderBox::adjustContentBoxLogicalHeightForBoxSizing(std::optional<LayoutUnit> height) const
1158 {
1159     if (!height)
1160         return 0;
1161     LayoutUnit result = height.value();
1162     if (style().boxSizing() == BoxSizing::BorderBox)
1163         result -= borderAndPaddingLogicalHeight();
1164     return std::max(LayoutUnit(), result);
1165 }
1166
1167 // Hit Testing
1168 bool RenderBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
1169 {
1170     LayoutPoint adjustedLocation = accumulatedOffset + location();
1171
1172     // Check kids first.
1173     for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
1174         if (!child->hasLayer() && child->nodeAtPoint(request, result, locationInContainer, adjustedLocation, action)) {
1175             updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1176             return true;
1177         }
1178     }
1179
1180     // Check our bounds next. For this purpose always assume that we can only be hit in the
1181     // foreground phase (which is true for replaced elements like images).
1182     LayoutRect boundsRect = borderBoxRectInFragment(nullptr);
1183     boundsRect.moveBy(adjustedLocation);
1184     if (visibleToHitTesting() && action == HitTestForeground && locationInContainer.intersects(boundsRect)) {
1185         updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1186         if (result.addNodeToListBasedTestResult(element(), request, locationInContainer, boundsRect) == HitTestProgress::Stop)
1187             return true;
1188     }
1189
1190     return false;
1191 }
1192
1193 // --------------------- painting stuff -------------------------------
1194
1195 void RenderBox::paintRootBoxFillLayers(const PaintInfo& paintInfo)
1196 {
1197     ASSERT(isDocumentElementRenderer());
1198     if (paintInfo.skipRootBackground())
1199         return;
1200
1201     auto* rootBackgroundRenderer = view().rendererForRootBackground();
1202     if (!rootBackgroundRenderer)
1203         return;
1204
1205     auto& style = rootBackgroundRenderer->style();
1206
1207     auto color = style.visitedDependentColor(CSSPropertyBackgroundColor);
1208
1209     CompositeOperator compositeOp = CompositeSourceOver;
1210     if (document().settings().punchOutWhiteBackgroundsInDarkMode() && Color::isWhiteColor(color) && useDarkAppearance())
1211         compositeOp = CompositeDestinationOut;
1212
1213     paintFillLayers(paintInfo, style.colorByApplyingColorFilter(color), style.backgroundLayers(), view().backgroundRect(), BackgroundBleedNone, compositeOp, rootBackgroundRenderer);
1214 }
1215
1216 BackgroundBleedAvoidance RenderBox::determineBackgroundBleedAvoidance(GraphicsContext& context) const
1217 {
1218     if (context.paintingDisabled())
1219         return BackgroundBleedNone;
1220
1221     const RenderStyle& style = this->style();
1222
1223     if (!style.hasBackground() || !style.hasBorder() || !style.hasBorderRadius() || borderImageIsLoadedAndCanBeRendered())
1224         return BackgroundBleedNone;
1225
1226     AffineTransform ctm = context.getCTM();
1227     FloatSize contextScaling(static_cast<float>(ctm.xScale()), static_cast<float>(ctm.yScale()));
1228
1229     // Because RoundedRect uses IntRect internally the inset applied by the 
1230     // BackgroundBleedShrinkBackground strategy cannot be less than one integer
1231     // layout coordinate, even with subpixel layout enabled. To take that into
1232     // account, we clamp the contextScaling to 1.0 for the following test so
1233     // that borderObscuresBackgroundEdge can only return true if the border
1234     // widths are greater than 2 in both layout coordinates and screen
1235     // coordinates.
1236     // This precaution will become obsolete if RoundedRect is ever promoted to
1237     // a sub-pixel representation.
1238     if (contextScaling.width() > 1) 
1239         contextScaling.setWidth(1);
1240     if (contextScaling.height() > 1) 
1241         contextScaling.setHeight(1);
1242
1243     if (borderObscuresBackgroundEdge(contextScaling))
1244         return BackgroundBleedShrinkBackground;
1245     if (!style.hasAppearance() && borderObscuresBackground() && backgroundHasOpaqueTopLayer())
1246         return BackgroundBleedBackgroundOverBorder;
1247
1248     return BackgroundBleedUseTransparencyLayer;
1249 }
1250
1251 void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1252 {
1253     if (!paintInfo.shouldPaintWithinRoot(*this))
1254         return;
1255
1256     LayoutRect paintRect = borderBoxRectInFragment(nullptr);
1257     paintRect.moveBy(paintOffset);
1258     adjustBorderBoxRectForPainting(paintRect);
1259
1260 #if PLATFORM(IOS_FAMILY)
1261     // Workaround for <rdar://problem/6209763>. Force the painting bounds of checkboxes and radio controls to be square.
1262     if (style().appearance() == CheckboxPart || style().appearance() == RadioPart) {
1263         int width = std::min(paintRect.width(), paintRect.height());
1264         int height = width;
1265         paintRect = IntRect(paintRect.x(), paintRect.y() + (this->height() - height) / 2, width, height); // Vertically center the checkbox, like on desktop
1266     }
1267 #endif
1268     BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context());
1269
1270     // FIXME: Should eventually give the theme control over whether the box shadow should paint, since controls could have
1271     // custom shadows of their own.
1272     if (!boxShadowShouldBeAppliedToBackground(paintRect.location(), bleedAvoidance))
1273         paintBoxShadow(paintInfo, paintRect, style(), Normal);
1274
1275     GraphicsContextStateSaver stateSaver(paintInfo.context(), false);
1276     if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
1277         // To avoid the background color bleeding out behind the border, we'll render background and border
1278         // into a transparency layer, and then clip that in one go (which requires setting up the clip before
1279         // beginning the layer).
1280         stateSaver.save();
1281         paintInfo.context().clipRoundedRect(style().getRoundedBorderFor(paintRect).pixelSnappedRoundedRectForPainting(document().deviceScaleFactor()));
1282         paintInfo.context().beginTransparencyLayer(1);
1283     }
1284
1285     // If we have a native theme appearance, paint that before painting our background.
1286     // The theme will tell us whether or not we should also paint the CSS background.
1287     bool borderOrBackgroundPaintingIsNeeded = true;
1288     if (style().hasAppearance()) {
1289         ControlStates* controlStates = controlStatesForRenderer(*this);
1290         borderOrBackgroundPaintingIsNeeded = theme().paint(*this, *controlStates, paintInfo, paintRect);
1291         if (controlStates->needsRepaint())
1292             view().scheduleLazyRepaint(*this);
1293     }
1294
1295     if (borderOrBackgroundPaintingIsNeeded) {
1296         if (bleedAvoidance == BackgroundBleedBackgroundOverBorder)
1297             paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1298
1299         paintBackground(paintInfo, paintRect, bleedAvoidance);
1300
1301         if (style().hasAppearance())
1302             theme().paintDecorations(*this, paintInfo, paintRect);
1303     }
1304     paintBoxShadow(paintInfo, paintRect, style(), Inset);
1305
1306     // The theme will tell us whether or not we should also paint the CSS border.
1307     if (bleedAvoidance != BackgroundBleedBackgroundOverBorder && (!style().hasAppearance() || (borderOrBackgroundPaintingIsNeeded && theme().paintBorderOnly(*this, paintInfo, paintRect))) && style().hasVisibleBorderDecoration())
1308         paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1309
1310     if (bleedAvoidance == BackgroundBleedUseTransparencyLayer)
1311         paintInfo.context().endTransparencyLayer();
1312 }
1313
1314 bool RenderBox::paintsOwnBackground() const
1315 {
1316     if (isBody()) {
1317         // The <body> only paints its background if the root element has defined a background independent of the body,
1318         // or if the <body>'s parent is not the document element's renderer (e.g. inside SVG foreignObject).
1319         auto documentElementRenderer = document().documentElement()->renderer();
1320         return !documentElementRenderer
1321             || documentElementRenderer->hasBackground()
1322             || (documentElementRenderer != parent());
1323     }
1324     
1325     return true;
1326 }
1327
1328 void RenderBox::paintBackground(const PaintInfo& paintInfo, const LayoutRect& paintRect, BackgroundBleedAvoidance bleedAvoidance)
1329 {
1330     if (isDocumentElementRenderer()) {
1331         paintRootBoxFillLayers(paintInfo);
1332         return;
1333     }
1334
1335     if (!paintsOwnBackground())
1336         return;
1337
1338     if (backgroundIsKnownToBeObscured(paintRect.location()) && !boxShadowShouldBeAppliedToBackground(paintRect.location(), bleedAvoidance))
1339         return;
1340
1341     Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1342
1343     CompositeOperator compositeOp = CompositeSourceOver;
1344     if (document().settings().punchOutWhiteBackgroundsInDarkMode() && Color::isWhiteColor(backgroundColor) && useDarkAppearance())
1345         compositeOp = CompositeDestinationOut;
1346
1347     paintFillLayers(paintInfo, style().colorByApplyingColorFilter(backgroundColor), style().backgroundLayers(), paintRect, bleedAvoidance, compositeOp);
1348 }
1349
1350 bool RenderBox::getBackgroundPaintedExtent(const LayoutPoint& paintOffset, LayoutRect& paintedExtent) const
1351 {
1352     ASSERT(hasBackground());
1353     LayoutRect backgroundRect = snappedIntRect(borderBoxRect());
1354
1355     Color backgroundColor = style().visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor);
1356     if (backgroundColor.isVisible()) {
1357         paintedExtent = backgroundRect;
1358         return true;
1359     }
1360
1361     auto& layers = style().backgroundLayers();
1362     if (!layers.image() || layers.next()) {
1363         paintedExtent =  backgroundRect;
1364         return true;
1365     }
1366
1367     auto geometry = calculateBackgroundImageGeometry(nullptr, layers, paintOffset, backgroundRect);
1368     paintedExtent = geometry.destRect();
1369     return !geometry.hasNonLocalGeometry();
1370 }
1371
1372 bool RenderBox::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
1373 {
1374     if (!paintsOwnBackground())
1375         return false;
1376
1377     Color backgroundColor = style().visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor);
1378     if (!backgroundColor.isOpaque())
1379         return false;
1380
1381     // If the element has appearance, it might be painted by theme.
1382     // We cannot be sure if theme paints the background opaque.
1383     // In this case it is safe to not assume opaqueness.
1384     // FIXME: May be ask theme if it paints opaque.
1385     if (style().hasAppearance())
1386         return false;
1387     // FIXME: Check the opaqueness of background images.
1388
1389     if (hasClip() || hasClipPath())
1390         return false;
1391
1392     // FIXME: Use rounded rect if border radius is present.
1393     if (style().hasBorderRadius())
1394         return false;
1395     
1396     // FIXME: The background color clip is defined by the last layer.
1397     if (style().backgroundLayers().next())
1398         return false;
1399     LayoutRect backgroundRect;
1400     switch (style().backgroundClip()) {
1401     case FillBox::Border:
1402         backgroundRect = borderBoxRect();
1403         break;
1404     case FillBox::Padding:
1405         backgroundRect = paddingBoxRect();
1406         break;
1407     case FillBox::Content:
1408         backgroundRect = contentBoxRect();
1409         break;
1410     default:
1411         break;
1412     }
1413     return backgroundRect.contains(localRect);
1414 }
1415
1416 static bool isCandidateForOpaquenessTest(const RenderBox& childBox)
1417 {
1418     const RenderStyle& childStyle = childBox.style();
1419     if (childStyle.position() != PositionType::Static && childBox.containingBlock() != childBox.parent())
1420         return false;
1421     if (childStyle.visibility() != Visibility::Visible)
1422         return false;
1423     if (childStyle.shapeOutside())
1424         return false;
1425     if (!childBox.width() || !childBox.height())
1426         return false;
1427     if (RenderLayer* childLayer = childBox.layer()) {
1428         if (childLayer->isComposited())
1429             return false;
1430         // FIXME: Deal with z-index.
1431         if (!childStyle.hasAutoZIndex())
1432             return false;
1433         if (childLayer->hasTransform() || childLayer->isTransparent() || childLayer->hasFilter())
1434             return false;
1435         if (!childBox.scrollPosition().isZero())
1436             return false;
1437     }
1438     return true;
1439 }
1440
1441 bool RenderBox::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const
1442 {
1443     if (!maxDepthToTest)
1444         return false;
1445
1446     for (auto& childBox : childrenOfType<RenderBox>(*this)) {
1447         if (!isCandidateForOpaquenessTest(childBox))
1448             continue;
1449         LayoutPoint childLocation = childBox.location();
1450         if (childBox.isRelativelyPositioned())
1451             childLocation.move(childBox.relativePositionOffset());
1452         LayoutRect childLocalRect = localRect;
1453         childLocalRect.moveBy(-childLocation);
1454         if (childLocalRect.y() < 0 || childLocalRect.x() < 0) {
1455             // If there is unobscured area above/left of a static positioned box then the rect is probably not covered.
1456             if (childBox.style().position() == PositionType::Static)
1457                 return false;
1458             continue;
1459         }
1460         if (childLocalRect.maxY() > childBox.height() || childLocalRect.maxX() > childBox.width())
1461             continue;
1462         if (childBox.backgroundIsKnownToBeOpaqueInRect(childLocalRect))
1463             return true;
1464         if (childBox.foregroundIsKnownToBeOpaqueInRect(childLocalRect, maxDepthToTest - 1))
1465             return true;
1466     }
1467     return false;
1468 }
1469
1470 bool RenderBox::computeBackgroundIsKnownToBeObscured(const LayoutPoint& paintOffset)
1471 {
1472     // Test to see if the children trivially obscure the background.
1473     // FIXME: This test can be much more comprehensive.
1474     if (!hasBackground())
1475         return false;
1476     // Table and root background painting is special.
1477     if (isTable() || isDocumentElementRenderer())
1478         return false;
1479
1480     LayoutRect backgroundRect;
1481     if (!getBackgroundPaintedExtent(paintOffset, backgroundRect))
1482         return false;
1483
1484     if (hasLayer() && layer()->scrollingMayRevealBackground())
1485         return false;
1486
1487     return foregroundIsKnownToBeOpaqueInRect(backgroundRect, backgroundObscurationTestMaxDepth);
1488 }
1489
1490 bool RenderBox::backgroundHasOpaqueTopLayer() const
1491 {
1492     auto& fillLayer = style().backgroundLayers();
1493     if (fillLayer.clip() != FillBox::Border)
1494         return false;
1495
1496     // Clipped with local scrolling
1497     if (hasOverflowClip() && fillLayer.attachment() == FillAttachment::LocalBackground)
1498         return false;
1499
1500     if (fillLayer.hasOpaqueImage(*this) && fillLayer.hasRepeatXY() && fillLayer.image()->canRender(this, style().effectiveZoom()))
1501         return true;
1502
1503     // If there is only one layer and no image, check whether the background color is opaque.
1504     if (!fillLayer.next() && !fillLayer.hasImage()) {
1505         Color bgColor = style().visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor);
1506         if (bgColor.isOpaque())
1507             return true;
1508     }
1509
1510     return false;
1511 }
1512
1513 void RenderBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1514 {
1515     if (!paintInfo.shouldPaintWithinRoot(*this) || style().visibility() != Visibility::Visible || paintInfo.phase != PaintPhase::Mask || paintInfo.context().paintingDisabled())
1516         return;
1517
1518     LayoutRect paintRect = LayoutRect(paintOffset, size());
1519     adjustBorderBoxRectForPainting(paintRect);
1520     paintMaskImages(paintInfo, paintRect);
1521 }
1522
1523 void RenderBox::paintClippingMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1524 {
1525     if (!paintInfo.shouldPaintWithinRoot(*this) || style().visibility() != Visibility::Visible || paintInfo.phase != PaintPhase::ClippingMask || paintInfo.context().paintingDisabled())
1526         return;
1527
1528     LayoutRect paintRect = LayoutRect(paintOffset, size());
1529     paintInfo.context().fillRect(snappedIntRect(paintRect), Color::black);
1530 }
1531
1532 void RenderBox::paintMaskImages(const PaintInfo& paintInfo, const LayoutRect& paintRect)
1533 {
1534     // Figure out if we need to push a transparency layer to render our mask.
1535     bool pushTransparencyLayer = false;
1536     bool compositedMask = hasLayer() && layer()->hasCompositedMask();
1537     bool flattenCompositingLayers = paintInfo.paintBehavior.contains(PaintBehavior::FlattenCompositingLayers);
1538     CompositeOperator compositeOp = CompositeSourceOver;
1539
1540     bool allMaskImagesLoaded = true;
1541     
1542     if (!compositedMask || flattenCompositingLayers) {
1543         pushTransparencyLayer = true;
1544
1545         // Don't render a masked element until all the mask images have loaded, to prevent a flash of unmasked content.
1546         if (auto* maskBoxImage = style().maskBoxImage().image())
1547             allMaskImagesLoaded &= maskBoxImage->isLoaded();
1548
1549         allMaskImagesLoaded &= style().maskLayers().imagesAreLoaded();
1550
1551         paintInfo.context().setCompositeOperation(CompositeDestinationIn);
1552         paintInfo.context().beginTransparencyLayer(1);
1553         compositeOp = CompositeSourceOver;
1554     }
1555
1556     if (allMaskImagesLoaded) {
1557         paintFillLayers(paintInfo, Color(), style().maskLayers(), paintRect, BackgroundBleedNone, compositeOp);
1558         paintNinePieceImage(paintInfo.context(), paintRect, style(), style().maskBoxImage(), compositeOp);
1559     }
1560     
1561     if (pushTransparencyLayer)
1562         paintInfo.context().endTransparencyLayer();
1563 }
1564
1565 LayoutRect RenderBox::maskClipRect(const LayoutPoint& paintOffset)
1566 {
1567     const NinePieceImage& maskBoxImage = style().maskBoxImage();
1568     if (maskBoxImage.image()) {
1569         LayoutRect borderImageRect = borderBoxRect();
1570         
1571         // Apply outsets to the border box.
1572         borderImageRect.expand(style().maskBoxImageOutsets());
1573         return borderImageRect;
1574     }
1575     
1576     LayoutRect result;
1577     LayoutRect borderBox = borderBoxRect();
1578     for (auto* maskLayer = &style().maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
1579         if (maskLayer->image()) {
1580             // Masks should never have fixed attachment, so it's OK for paintContainer to be null.
1581             result.unite(calculateBackgroundImageGeometry(nullptr, *maskLayer, paintOffset, borderBox).destRect());
1582         }
1583     }
1584     return result;
1585 }
1586
1587 void RenderBox::paintFillLayers(const PaintInfo& paintInfo, const Color& color, const FillLayer& fillLayer, const LayoutRect& rect,
1588     BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject)
1589 {
1590     Vector<const FillLayer*, 8> layers;
1591     bool shouldDrawBackgroundInSeparateBuffer = false;
1592
1593     for (auto* layer = &fillLayer; layer; layer = layer->next()) {
1594         layers.append(layer);
1595
1596         if (layer->blendMode() != BlendMode::Normal)
1597             shouldDrawBackgroundInSeparateBuffer = true;
1598
1599         // Stop traversal when an opaque layer is encountered.
1600         // FIXME: It would be possible for the following occlusion culling test to be more aggressive
1601         // on layers with no repeat by testing whether the image covers the layout rect.
1602         // Testing that here would imply duplicating a lot of calculations that are currently done in
1603         // RenderBoxModelObject::paintFillLayerExtended. A more efficient solution might be to move
1604         // the layer recursion into paintFillLayerExtended, or to compute the layer geometry here
1605         // and pass it down.
1606
1607         // The clipOccludesNextLayers condition must be evaluated first to avoid short-circuiting.
1608         if (layer->clipOccludesNextLayers(layer == &fillLayer) && layer->hasOpaqueImage(*this) && layer->image()->canRender(this, style().effectiveZoom()) && layer->hasRepeatXY() && layer->blendMode() == BlendMode::Normal)
1609             break;
1610     }
1611
1612     auto& context = paintInfo.context();
1613     auto baseBgColorUsage = BaseBackgroundColorUse;
1614
1615     if (shouldDrawBackgroundInSeparateBuffer) {
1616         paintFillLayer(paintInfo, color, *layers.last(), rect, bleedAvoidance, op, backgroundObject, BaseBackgroundColorOnly);
1617         baseBgColorUsage = BaseBackgroundColorSkip;
1618         context.beginTransparencyLayer(1);
1619     }
1620
1621     auto topLayer = layers.rend();
1622     for (auto it = layers.rbegin(); it != topLayer; ++it)
1623         paintFillLayer(paintInfo, color, **it, rect, bleedAvoidance, op, backgroundObject, baseBgColorUsage);
1624
1625     if (shouldDrawBackgroundInSeparateBuffer)
1626         context.endTransparencyLayer();
1627 }
1628
1629 void RenderBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer& fillLayer, const LayoutRect& rect,
1630     BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject, BaseBackgroundColorUsage baseBgColorUsage)
1631 {
1632     paintFillLayerExtended(paintInfo, c, fillLayer, rect, bleedAvoidance, nullptr, LayoutSize(), op, backgroundObject, baseBgColorUsage);
1633 }
1634
1635 static bool layersUseImage(WrappedImagePtr image, const FillLayer& layers)
1636 {
1637     for (auto* layer = &layers; layer; layer = layer->next()) {
1638         if (layer->image() && image == layer->image()->data())
1639             return true;
1640     }
1641     return false;
1642 }
1643
1644 void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
1645 {
1646     if (!parent())
1647         return;
1648
1649     if ((style().borderImage().image() && style().borderImage().image()->data() == image) ||
1650         (style().maskBoxImage().image() && style().maskBoxImage().image()->data() == image)) {
1651         repaint();
1652         return;
1653     }
1654
1655     ShapeValue* shapeOutsideValue = style().shapeOutside();
1656     if (!view().frameView().layoutContext().isInRenderTreeLayout() && isFloating() && shapeOutsideValue && shapeOutsideValue->image() && shapeOutsideValue->image()->data() == image) {
1657         ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
1658         markShapeOutsideDependentsForLayout();
1659     }
1660
1661     bool didFullRepaint = repaintLayerRectsForImage(image, style().backgroundLayers(), true);
1662     if (!didFullRepaint)
1663         repaintLayerRectsForImage(image, style().maskLayers(), false);
1664
1665     if (!isComposited())
1666         return;
1667
1668     if (layer()->hasCompositedMask() && layersUseImage(image, style().maskLayers()))
1669         layer()->contentChanged(MaskImageChanged);
1670     if (layersUseImage(image, style().backgroundLayers()))
1671         layer()->contentChanged(BackgroundImageChanged);
1672 }
1673
1674 bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer& layers, bool drawingBackground)
1675 {
1676     LayoutRect rendererRect;
1677     RenderBox* layerRenderer = nullptr;
1678
1679     for (auto* layer = &layers; layer; layer = layer->next()) {
1680         if (layer->image() && image == layer->image()->data() && layer->image()->canRender(this, style().effectiveZoom())) {
1681             // Now that we know this image is being used, compute the renderer and the rect if we haven't already.
1682             bool drawingRootBackground = drawingBackground && (isDocumentElementRenderer() || (isBody() && !document().documentElement()->renderer()->hasBackground()));
1683             if (!layerRenderer) {
1684                 if (drawingRootBackground) {
1685                     layerRenderer = &view();
1686
1687                     LayoutUnit rw = downcast<RenderView>(*layerRenderer).frameView().contentsWidth();
1688                     LayoutUnit rh = downcast<RenderView>(*layerRenderer).frameView().contentsHeight();
1689
1690                     rendererRect = LayoutRect(-layerRenderer->marginLeft(),
1691                         -layerRenderer->marginTop(),
1692                         std::max(layerRenderer->width() + layerRenderer->horizontalMarginExtent() + layerRenderer->borderLeft() + layerRenderer->borderRight(), rw),
1693                         std::max(layerRenderer->height() + layerRenderer->verticalMarginExtent() + layerRenderer->borderTop() + layerRenderer->borderBottom(), rh));
1694                 } else {
1695                     layerRenderer = this;
1696                     rendererRect = borderBoxRect();
1697                 }
1698             }
1699             // FIXME: Figure out how to pass absolute position to calculateBackgroundImageGeometry (for pixel snapping)
1700             BackgroundImageGeometry geometry = layerRenderer->calculateBackgroundImageGeometry(nullptr, *layer, LayoutPoint(), rendererRect);
1701             if (geometry.hasNonLocalGeometry()) {
1702                 // Rather than incur the costs of computing the paintContainer for renderers with fixed backgrounds
1703                 // in order to get the right destRect, just repaint the entire renderer.
1704                 layerRenderer->repaint();
1705                 return true;
1706             }
1707             
1708             LayoutRect rectToRepaint = geometry.destRect();
1709             bool shouldClipToLayer = true;
1710
1711             // If this is the root background layer, we may need to extend the repaintRect if the FrameView has an
1712             // extendedBackground. We should only extend the rect if it is already extending the full width or height
1713             // of the rendererRect.
1714             if (drawingRootBackground && view().frameView().hasExtendedBackgroundRectForPainting()) {
1715                 shouldClipToLayer = false;
1716                 IntRect extendedBackgroundRect = view().frameView().extendedBackgroundRectForPainting();
1717                 if (rectToRepaint.width() == rendererRect.width()) {
1718                     rectToRepaint.move(extendedBackgroundRect.x(), 0);
1719                     rectToRepaint.setWidth(extendedBackgroundRect.width());
1720                 }
1721                 if (rectToRepaint.height() == rendererRect.height()) {
1722                     rectToRepaint.move(0, extendedBackgroundRect.y());
1723                     rectToRepaint.setHeight(extendedBackgroundRect.height());
1724                 }
1725             }
1726
1727             layerRenderer->repaintRectangle(rectToRepaint, shouldClipToLayer);
1728             if (geometry.destRect() == rendererRect)
1729                 return true;
1730         }
1731     }
1732     return false;
1733 }
1734
1735 bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset)
1736 {
1737     if (paintInfo.phase == PaintPhase::BlockBackground || paintInfo.phase == PaintPhase::SelfOutline || paintInfo.phase == PaintPhase::Mask)
1738         return false;
1739
1740     bool isControlClip = hasControlClip();
1741     bool isOverflowClip = hasOverflowClip() && !layer()->isSelfPaintingLayer();
1742     
1743     if (!isControlClip && !isOverflowClip)
1744         return false;
1745     
1746     if (paintInfo.phase == PaintPhase::Outline)
1747         paintInfo.phase = PaintPhase::ChildOutlines;
1748     else if (paintInfo.phase == PaintPhase::ChildBlockBackground) {
1749         paintInfo.phase = PaintPhase::BlockBackground;
1750         paintObject(paintInfo, accumulatedOffset);
1751         paintInfo.phase = PaintPhase::ChildBlockBackgrounds;
1752     }
1753     float deviceScaleFactor = document().deviceScaleFactor();
1754     FloatRect clipRect = snapRectToDevicePixels((isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset, nullptr, IgnoreOverlayScrollbarSize, paintInfo.phase)), deviceScaleFactor);
1755     paintInfo.context().save();
1756     if (style().hasBorderRadius())
1757         paintInfo.context().clipRoundedRect(style().getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size())).pixelSnappedRoundedRectForPainting(deviceScaleFactor));
1758     paintInfo.context().clip(clipRect);
1759     return true;
1760 }
1761
1762 void RenderBox::popContentsClip(PaintInfo& paintInfo, PaintPhase originalPhase, const LayoutPoint& accumulatedOffset)
1763 {
1764     ASSERT(hasControlClip() || (hasOverflowClip() && !layer()->isSelfPaintingLayer()));
1765
1766     paintInfo.context().restore();
1767     if (originalPhase == PaintPhase::Outline) {
1768         paintInfo.phase = PaintPhase::SelfOutline;
1769         paintObject(paintInfo, accumulatedOffset);
1770         paintInfo.phase = originalPhase;
1771     } else if (originalPhase == PaintPhase::ChildBlockBackground)
1772         paintInfo.phase = originalPhase;
1773 }
1774
1775 LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, RenderFragmentContainer* fragment, OverlayScrollbarSizeRelevancy relevancy, PaintPhase)
1776 {
1777     // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
1778     // here.
1779     LayoutRect clipRect = borderBoxRectInFragment(fragment);
1780     clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
1781     clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
1782
1783     // Subtract out scrollbars if we have them.
1784     if (layer()) {
1785         if (shouldPlaceBlockDirectionScrollbarOnLeft())
1786             clipRect.move(layer()->verticalScrollbarWidth(relevancy), 0);
1787         clipRect.contract(layer()->verticalScrollbarWidth(relevancy), layer()->horizontalScrollbarHeight(relevancy));
1788     }
1789
1790     return clipRect;
1791 }
1792
1793 LayoutRect RenderBox::clipRect(const LayoutPoint& location, RenderFragmentContainer* fragment)
1794 {
1795     LayoutRect borderBoxRect = borderBoxRectInFragment(fragment);
1796     LayoutRect clipRect = LayoutRect(borderBoxRect.location() + location, borderBoxRect.size());
1797
1798     if (!style().clipLeft().isAuto()) {
1799         LayoutUnit c = valueForLength(style().clipLeft(), borderBoxRect.width());
1800         clipRect.move(c, 0);
1801         clipRect.contract(c, 0);
1802     }
1803
1804     // We don't use the fragment-specific border box's width and height since clip offsets are (stupidly) specified
1805     // from the left and top edges. Therefore it's better to avoid constraining to smaller widths and heights.
1806
1807     if (!style().clipRight().isAuto())
1808         clipRect.contract(width() - valueForLength(style().clipRight(), width()), 0);
1809
1810     if (!style().clipTop().isAuto()) {
1811         LayoutUnit c = valueForLength(style().clipTop(), borderBoxRect.height());
1812         clipRect.move(0, c);
1813         clipRect.contract(0, c);
1814     }
1815
1816     if (!style().clipBottom().isAuto())
1817         clipRect.contract(0, height() - valueForLength(style().clipBottom(), height()));
1818
1819     return clipRect;
1820 }
1821
1822 LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock& cb, RenderFragmentContainer* fragment) const
1823 {    
1824     RenderFragmentContainer* containingBlockFragment = nullptr;
1825     LayoutUnit logicalTopPosition = logicalTop();
1826     if (fragment) {
1827         LayoutUnit offsetFromLogicalTopOfFragment = fragment ? fragment->logicalTopForFragmentedFlowContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1828         logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfFragment);
1829         containingBlockFragment = cb.clampToStartAndEndFragments(fragment);
1830     }
1831
1832     LayoutUnit logicalHeight = cb.logicalHeightForChild(*this);
1833     LayoutUnit result = cb.availableLogicalWidthForLineInFragment(logicalTopPosition, DoNotIndentText, containingBlockFragment, logicalHeight) - childMarginStart - childMarginEnd;
1834
1835     // We need to see if margins on either the start side or the end side can contain the floats in question. If they can,
1836     // then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line
1837     // offset at all, but can instead push all the way to the content edge of the containing block. In the case where the float
1838     // 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
1839     // "consumed" by the float. Negative margins aren't consumed by the float, and so we ignore them.
1840     if (childMarginStart > 0) {
1841         LayoutUnit startContentSide = cb.startOffsetForContent(containingBlockFragment);
1842         LayoutUnit startContentSideWithMargin = startContentSide + childMarginStart;
1843         LayoutUnit startOffset = cb.startOffsetForLineInFragment(logicalTopPosition, DoNotIndentText, containingBlockFragment, logicalHeight);
1844         if (startOffset > startContentSideWithMargin)
1845             result += childMarginStart;
1846         else
1847             result += startOffset - startContentSide;
1848     }
1849     
1850     if (childMarginEnd > 0) {
1851         LayoutUnit endContentSide = cb.endOffsetForContent(containingBlockFragment);
1852         LayoutUnit endContentSideWithMargin = endContentSide + childMarginEnd;
1853         LayoutUnit endOffset = cb.endOffsetForLineInFragment(logicalTopPosition, DoNotIndentText, containingBlockFragment, logicalHeight);
1854         if (endOffset > endContentSideWithMargin)
1855             result += childMarginEnd;
1856         else
1857             result += endOffset - endContentSide;
1858     }
1859
1860     return result;
1861 }
1862
1863 LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const
1864 {
1865     if (hasOverrideContainingBlockContentLogicalWidth()) {
1866         if (auto overrideLogicalWidth = overrideContainingBlockContentLogicalWidth())
1867             return overrideLogicalWidth.value();
1868     }
1869
1870     if (RenderBlock* cb = containingBlock())
1871         return cb->availableLogicalWidth();
1872     return LayoutUnit();
1873 }
1874
1875 LayoutUnit RenderBox::containingBlockLogicalHeightForContent(AvailableLogicalHeightType heightType) const
1876 {
1877     if (hasOverrideContainingBlockContentLogicalHeight()) {
1878         if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight())
1879             return overrideLogicalHeight.value();
1880     }
1881
1882     if (RenderBlock* cb = containingBlock())
1883         return cb->availableLogicalHeight(heightType);
1884     return LayoutUnit();
1885 }
1886
1887 LayoutUnit RenderBox::containingBlockLogicalWidthForContentInFragment(RenderFragmentContainer* fragment) const
1888 {
1889     if (!fragment)
1890         return containingBlockLogicalWidthForContent();
1891
1892     RenderBlock* cb = containingBlock();
1893     RenderFragmentContainer* containingBlockFragment = cb->clampToStartAndEndFragments(fragment);
1894     // FIXME: It's unclear if a fragment's content should use the containing block's override logical width.
1895     // If it should, the following line should call containingBlockLogicalWidthForContent.
1896     LayoutUnit result = cb->availableLogicalWidth();
1897     RenderBoxFragmentInfo* boxInfo = cb->renderBoxFragmentInfo(containingBlockFragment);
1898     if (!boxInfo)
1899         return result;
1900     return std::max<LayoutUnit>(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
1901 }
1902
1903 LayoutUnit RenderBox::containingBlockAvailableLineWidthInFragment(RenderFragmentContainer* fragment) const
1904 {
1905     RenderBlock* cb = containingBlock();
1906     RenderFragmentContainer* containingBlockFragment = nullptr;
1907     LayoutUnit logicalTopPosition = logicalTop();
1908     if (fragment) {
1909         LayoutUnit offsetFromLogicalTopOfFragment = fragment ? fragment->logicalTopForFragmentedFlowContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1910         logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfFragment);
1911         containingBlockFragment = cb->clampToStartAndEndFragments(fragment);
1912     }
1913     return cb->availableLogicalWidthForLineInFragment(logicalTopPosition, DoNotIndentText, containingBlockFragment, availableLogicalHeight(IncludeMarginBorderPadding));
1914 }
1915
1916 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
1917 {
1918     if (hasOverrideContainingBlockContentLogicalHeight()) {
1919         if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight())
1920             return overrideLogicalHeight.value();
1921     }
1922
1923     RenderBlock* cb = containingBlock();
1924     if (cb->hasOverrideContentLogicalHeight())
1925         return cb->overrideContentLogicalHeight();
1926
1927     const RenderStyle& containingBlockStyle = cb->style();
1928     Length logicalHeightLength = containingBlockStyle.logicalHeight();
1929
1930     // FIXME: For now just support fixed heights.  Eventually should support percentage heights as well.
1931     if (!logicalHeightLength.isFixed()) {
1932         LayoutUnit fillFallbackExtent = containingBlockStyle.isHorizontalWritingMode() ? view().frameView().visibleHeight() : view().frameView().visibleWidth();
1933         LayoutUnit fillAvailableExtent = containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding);
1934         view().addPercentHeightDescendant(const_cast<RenderBox&>(*this));
1935         // 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.
1936         return std::min(fillAvailableExtent, fillFallbackExtent);
1937     }
1938
1939     // Use the content box logical height as specified by the style.
1940     return cb->adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(logicalHeightLength.value()));
1941 }
1942
1943 void RenderBox::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
1944 {
1945     if (repaintContainer == this)
1946         return;
1947
1948     if (view().frameView().layoutContext().isPaintOffsetCacheEnabled() && !repaintContainer) {
1949         auto* layoutState = view().frameView().layoutContext().layoutState();
1950         LayoutSize offset = layoutState->paintOffset() + locationOffset();
1951         if (style().hasInFlowPosition() && layer())
1952             offset += layer()->offsetForInFlowPosition();
1953         transformState.move(offset);
1954         return;
1955     }
1956
1957     bool containerSkipped;
1958     RenderElement* container = this->container(repaintContainer, containerSkipped);
1959     if (!container)
1960         return;
1961
1962     bool isFixedPos = isFixedPositioned();
1963     // If this box has a transform, it acts as a fixed position container for fixed descendants,
1964     // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1965     if (hasTransform() && !isFixedPos)
1966         mode &= ~IsFixed;
1967     else if (isFixedPos)
1968         mode |= IsFixed;
1969
1970     if (wasFixed)
1971         *wasFixed = mode & IsFixed;
1972     
1973     LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint(transformState.mappedPoint()));
1974     
1975     bool preserve3D = mode & UseTransforms && (container->style().preserves3D() || style().preserves3D());
1976     if (mode & UseTransforms && shouldUseTransformFromContainer(container)) {
1977         TransformationMatrix t;
1978         getTransformFromContainer(container, containerOffset, t);
1979         transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1980     } else
1981         transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1982
1983     if (containerSkipped) {
1984         // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe
1985         // to just subtract the delta between the repaintContainer and o.
1986         LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(*container);
1987         transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1988         return;
1989     }
1990
1991     mode &= ~ApplyContainerFlip;
1992
1993     container->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed);
1994 }
1995
1996 const RenderObject* RenderBox::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
1997 {
1998     ASSERT(ancestorToStopAt != this);
1999
2000     bool ancestorSkipped;
2001     RenderElement* container = this->container(ancestorToStopAt, ancestorSkipped);
2002     if (!container)
2003         return nullptr;
2004
2005     bool isFixedPos = isFixedPositioned();
2006     LayoutSize adjustmentForSkippedAncestor;
2007     if (ancestorSkipped) {
2008         // There can't be a transform between repaintContainer and container, because transforms create containers, so it should be safe
2009         // to just subtract the delta between the ancestor and container.
2010         adjustmentForSkippedAncestor = -ancestorToStopAt->offsetFromAncestorContainer(*container);
2011     }
2012
2013     bool offsetDependsOnPoint = false;
2014     LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint(), &offsetDependsOnPoint);
2015
2016     bool preserve3D = container->style().preserves3D() || style().preserves3D();
2017     if (shouldUseTransformFromContainer(container) && (geometryMap.mapCoordinatesFlags() & UseTransforms)) {
2018         TransformationMatrix t;
2019         getTransformFromContainer(container, containerOffset, t);
2020         t.translateRight(adjustmentForSkippedAncestor.width(), adjustmentForSkippedAncestor.height());
2021         
2022         geometryMap.push(this, t, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform());
2023     } else {
2024         containerOffset += adjustmentForSkippedAncestor;
2025         geometryMap.push(this, containerOffset, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform());
2026     }
2027     
2028     return ancestorSkipped ? ancestorToStopAt : container;
2029 }
2030
2031 void RenderBox::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
2032 {
2033     bool isFixedPos = isFixedPositioned();
2034     if (hasTransform() && !isFixedPos) {
2035         // If this box has a transform, it acts as a fixed position container for fixed descendants,
2036         // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
2037         mode &= ~IsFixed;
2038     } else if (isFixedPos)
2039         mode |= IsFixed;
2040
2041     RenderBoxModelObject::mapAbsoluteToLocalPoint(mode, transformState);
2042 }
2043
2044 LayoutSize RenderBox::offsetFromContainer(RenderElement& container, const LayoutPoint&, bool* offsetDependsOnPoint) const
2045 {
2046     // A fragment "has" boxes inside it without being their container. 
2047     ASSERT(&container == this->container() || is<RenderFragmentContainer>(container));
2048
2049     LayoutSize offset;    
2050     if (isInFlowPositioned())
2051         offset += offsetForInFlowPosition();
2052
2053     if (!isInline() || isReplaced())
2054         offset += topLeftLocationOffset();
2055
2056     if (is<RenderBox>(container))
2057         offset -= toLayoutSize(downcast<RenderBox>(container).scrollPosition());
2058
2059     if (isAbsolutelyPositioned() && container.isInFlowPositioned() && is<RenderInline>(container))
2060         offset += downcast<RenderInline>(container).offsetForInFlowPositionedInline(this);
2061
2062     if (offsetDependsOnPoint)
2063         *offsetDependsOnPoint |= is<RenderFragmentedFlow>(container);
2064
2065     return offset;
2066 }
2067
2068 std::unique_ptr<InlineElementBox> RenderBox::createInlineBox()
2069 {
2070     return std::make_unique<InlineElementBox>(*this);
2071 }
2072
2073 void RenderBox::dirtyLineBoxes(bool fullLayout)
2074 {
2075     if (!m_inlineBoxWrapper)
2076         return;
2077     
2078     if (fullLayout) {
2079         delete m_inlineBoxWrapper;
2080         m_inlineBoxWrapper = nullptr;
2081     } else
2082         m_inlineBoxWrapper->dirtyLineBoxes();
2083 }
2084
2085 void RenderBox::positionLineBox(InlineElementBox& box)
2086 {
2087     if (isOutOfFlowPositioned()) {
2088         // Cache the x position only if we were an DisplayType::Inline type originally.
2089         bool wasInline = style().isOriginalDisplayInlineType();
2090         if (wasInline) {
2091             // The value is cached in the xPos of the box.  We only need this value if
2092             // our object was inline originally, since otherwise it would have ended up underneath
2093             // the inlines.
2094             RootInlineBox& rootBox = box.root();
2095             rootBox.blockFlow().setStaticInlinePositionForChild(*this, rootBox.lineTopWithLeading(), LayoutUnit::fromFloatRound(box.logicalLeft()));
2096             if (style().hasStaticInlinePosition(box.isHorizontal()))
2097                 setChildNeedsLayout(MarkOnlyThis); // Just mark the positioned object as needing layout, so it will update its position properly.
2098         } else {
2099             // Our object was a block originally, so we make our normal flow position be
2100             // just below the line box (as though all the inlines that came before us got
2101             // wrapped in an anonymous block, which is what would have happened had we been
2102             // in flow).  This value was cached in the y() of the box.
2103             layer()->setStaticBlockPosition(box.logicalTop());
2104             if (style().hasStaticBlockPosition(box.isHorizontal()))
2105                 setChildNeedsLayout(MarkOnlyThis); // Just mark the positioned object as needing layout, so it will update its position properly.
2106         }
2107         return;
2108     }
2109
2110     if (isReplaced()) {
2111         setLocation(LayoutPoint(box.topLeft()));
2112         setInlineBoxWrapper(&box);
2113     }
2114 }
2115
2116 void RenderBox::deleteLineBoxWrapper()
2117 {
2118     if (!m_inlineBoxWrapper)
2119         return;
2120     
2121     if (!renderTreeBeingDestroyed())
2122         m_inlineBoxWrapper->removeFromParent();
2123     delete m_inlineBoxWrapper;
2124     m_inlineBoxWrapper = nullptr;
2125 }
2126
2127 LayoutRect RenderBox::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
2128 {
2129     if (style().visibility() != Visibility::Visible && !enclosingLayer()->hasVisibleContent())
2130         return LayoutRect();
2131     LayoutRect r = visualOverflowRect();
2132     // FIXME: layoutDelta needs to be applied in parts before/after transforms and
2133     // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
2134     r.move(view().frameView().layoutContext().layoutDelta());
2135     return computeRectForRepaint(r, repaintContainer);
2136 }
2137
2138 LayoutRect RenderBox::computeVisibleRectUsingPaintOffset(const LayoutRect& rect) const
2139 {
2140     LayoutRect adjustedRect = rect;
2141     auto* layoutState = view().frameView().layoutContext().layoutState();
2142
2143     if (layer() && layer()->transform())
2144         adjustedRect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(adjustedRect), document().deviceScaleFactor()));
2145
2146     // We can't trust the bits on RenderObject, because this might be called while re-resolving style.
2147     if (style().hasInFlowPosition() && layer())
2148         adjustedRect.move(layer()->offsetForInFlowPosition());
2149
2150     adjustedRect.moveBy(location());
2151     adjustedRect.move(layoutState->paintOffset());
2152     if (layoutState->isClipped())
2153         adjustedRect.intersect(layoutState->clipRect());
2154     return adjustedRect;
2155 }
2156
2157 std::optional<LayoutRect> RenderBox::computeVisibleRectInContainer(const LayoutRect& rect, const RenderLayerModelObject* container, VisibleRectContext context) const
2158 {
2159     // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
2160     // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
2161     // offset corner for the enclosing container).  This allows for a fully RL or BT document to repaint
2162     // properly even during layout, since the rect remains flipped all the way until the end.
2163     //
2164     // RenderView::computeVisibleRectInContainer then converts the rect to physical coordinates. We also convert to
2165     // physical when we hit a repaint container boundary. Therefore the final rect returned is always in the
2166     // physical coordinate space of the container.
2167     const RenderStyle& styleToUse = style();
2168     // Paint offset cache is only valid for root-relative, non-fixed position repainting
2169     if (view().frameView().layoutContext().isPaintOffsetCacheEnabled() && !container && styleToUse.position() != PositionType::Fixed && !context.m_options.contains(VisibleRectContextOption::UseEdgeInclusiveIntersection))
2170         return computeVisibleRectUsingPaintOffset(rect);
2171
2172     LayoutRect adjustedRect = rect;
2173     if (hasReflection())
2174         adjustedRect.unite(reflectedRect(adjustedRect));
2175
2176     if (container == this) {
2177         if (container->style().isFlippedBlocksWritingMode())
2178             flipForWritingMode(adjustedRect);
2179         return adjustedRect;
2180     }
2181
2182     bool containerIsSkipped;
2183     auto* localContainer = this->container(container, containerIsSkipped);
2184     if (!localContainer)
2185         return adjustedRect;
2186     
2187     // This code isn't necessary for in-flow RenderFragmentedFlows.
2188     // Don't add the location of the fragment in the flow thread for absolute positioned
2189     // elements because their absolute position already pushes them down through
2190     // the fragments so adding this here and then adding the topLeft again would cause
2191     // us to add the height twice.
2192     // The same logic applies for elements flowed directly into the flow thread. Their topLeft member
2193     // will already contain the portion rect of the fragment.
2194     auto position = styleToUse.position();
2195     if (localContainer->isOutOfFlowRenderFragmentedFlow() && position != PositionType::Absolute && containingBlock() != enclosingFragmentedFlow()) {
2196         RenderFragmentContainer* firstFragment = nullptr;
2197         RenderFragmentContainer* lastFragment = nullptr;
2198         if (downcast<RenderFragmentedFlow>(*localContainer).getFragmentRangeForBox(this, firstFragment, lastFragment))
2199             adjustedRect.moveBy(firstFragment->fragmentedFlowPortionRect().location());
2200     }
2201
2202     if (isWritingModeRoot()) {
2203         if (!isOutOfFlowPositioned() || !context.m_dirtyRectIsFlipped) {
2204             flipForWritingMode(adjustedRect);
2205             context.m_dirtyRectIsFlipped = true;
2206         }
2207     }
2208
2209     LayoutSize locationOffset = this->locationOffset();
2210     // FIXME: This is needed as long as RenderWidget snaps to integral size/position.
2211     if (isRenderReplaced() && isWidget()) {
2212         LayoutSize flooredLocationOffset = toIntSize(flooredIntPoint(locationOffset));
2213         adjustedRect.expand(locationOffset - flooredLocationOffset);
2214         locationOffset = flooredLocationOffset;
2215     }
2216
2217     if (is<RenderMultiColumnFlow>(this)) {
2218         // We won't normally run this code. Only when the container is null (i.e., we're trying
2219         // to get the rect in view coordinates) will we come in here, since normally container
2220         // will be set and we'll stop at the flow thread. This case is mainly hit by the check for whether
2221         // or not images should animate.
2222         // FIXME: Just as with offsetFromContainer, we aren't really handling objects that span
2223         // multiple columns properly.
2224         LayoutPoint physicalPoint(flipForWritingMode(adjustedRect.location()));
2225         if (auto* fragment = downcast<RenderMultiColumnFlow>(*this).physicalTranslationFromFlowToFragment((physicalPoint))) {
2226             adjustedRect.setLocation(fragment->flipForWritingMode(physicalPoint));
2227             return fragment->computeVisibleRectInContainer(adjustedRect, container, context);
2228         }
2229     }
2230
2231     LayoutPoint topLeft = adjustedRect.location();
2232     topLeft.move(locationOffset);
2233
2234     // We are now in our parent container's coordinate space. Apply our transform to obtain a bounding box
2235     // in the parent's coordinate space that encloses us.
2236     if (hasLayer() && layer()->transform()) {
2237         context.m_hasPositionFixedDescendant = position == PositionType::Fixed;
2238         adjustedRect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(adjustedRect), document().deviceScaleFactor()));
2239         topLeft = adjustedRect.location();
2240         topLeft.move(locationOffset);
2241     } else if (position == PositionType::Fixed)
2242         context.m_hasPositionFixedDescendant = true;
2243
2244     if (position == PositionType::Absolute && localContainer->isInFlowPositioned() && is<RenderInline>(*localContainer))
2245         topLeft += downcast<RenderInline>(*localContainer).offsetForInFlowPositionedInline(this);
2246     else if (styleToUse.hasInFlowPosition() && layer()) {
2247         // Apply the relative position offset when invalidating a rectangle.  The layer
2248         // is translated, but the render box isn't, so we need to do this to get the
2249         // right dirty rect.  Since this is called from RenderObject::setStyle, the relative position
2250         // flag on the RenderObject has been cleared, so use the one on the style().
2251         topLeft += layer()->offsetForInFlowPosition();
2252     }
2253
2254     // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
2255     // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
2256     adjustedRect.setLocation(topLeft);
2257     if (localContainer->hasOverflowClip()) {
2258         RenderBox& containerBox = downcast<RenderBox>(*localContainer);
2259         bool isEmpty = !containerBox.applyCachedClipAndScrollPosition(adjustedRect, container, context);
2260         if (isEmpty) {
2261             if (context.m_options.contains(VisibleRectContextOption::UseEdgeInclusiveIntersection))
2262                 return std::nullopt;
2263             return adjustedRect;
2264         }
2265     }
2266
2267     if (containerIsSkipped) {
2268         // If the container is below localContainer, then we need to map the rect into container's coordinates.
2269         LayoutSize containerOffset = container->offsetFromAncestorContainer(*localContainer);
2270         adjustedRect.move(-containerOffset);
2271         return adjustedRect;
2272     }
2273     return localContainer->computeVisibleRectInContainer(adjustedRect, container, context);
2274 }
2275
2276 void RenderBox::repaintDuringLayoutIfMoved(const LayoutRect& oldRect)
2277 {
2278     if (oldRect.location() != m_frameRect.location()) {
2279         LayoutRect newRect = m_frameRect;
2280         // The child moved.  Invalidate the object's old and new positions.  We have to do this
2281         // since the object may not have gotten a layout.
2282         m_frameRect = oldRect;
2283         repaint();
2284         repaintOverhangingFloats(true);
2285         m_frameRect = newRect;
2286         repaint();
2287         repaintOverhangingFloats(true);
2288     }
2289 }
2290
2291 void RenderBox::repaintOverhangingFloats(bool)
2292 {
2293 }
2294
2295 void RenderBox::updateLogicalWidth()
2296 {
2297     LogicalExtentComputedValues computedValues;
2298     computeLogicalWidthInFragment(computedValues);
2299
2300     setLogicalWidth(computedValues.m_extent);
2301     setLogicalLeft(computedValues.m_position);
2302     setMarginStart(computedValues.m_margins.m_start);
2303     setMarginEnd(computedValues.m_margins.m_end);
2304 }
2305
2306 void RenderBox::computeLogicalWidthInFragment(LogicalExtentComputedValues& computedValues, RenderFragmentContainer* fragment) const
2307 {
2308     computedValues.m_extent = logicalWidth();
2309     computedValues.m_position = logicalLeft();
2310     computedValues.m_margins.m_start = marginStart();
2311     computedValues.m_margins.m_end = marginEnd();
2312
2313     if (isOutOfFlowPositioned()) {
2314         // FIXME: This calculation is not patched for block-flow yet.
2315         // https://bugs.webkit.org/show_bug.cgi?id=46500
2316         computePositionedLogicalWidth(computedValues, fragment);
2317         return;
2318     }
2319
2320     // If layout is limited to a subtree, the subtree root's logical width does not change.
2321     if (element() && !view().frameView().layoutContext().isLayoutPending() && view().frameView().layoutContext().subtreeLayoutRoot() == this)
2322         return;
2323
2324     // The parent box is flexing us, so it has increased or decreased our
2325     // width.  Use the width from the style context.
2326     // FIXME: Account for block-flow in flexible boxes.
2327     // https://bugs.webkit.org/show_bug.cgi?id=46418
2328     if (hasOverrideContentLogicalWidth() && (isRubyRun() || style().borderFit() == BorderFit::Lines || (parent()->isFlexibleBoxIncludingDeprecated()))) {
2329         computedValues.m_extent = overrideContentLogicalWidth() + borderAndPaddingLogicalWidth();
2330         return;
2331     }
2332
2333     // FIXME: Account for block-flow in flexible boxes.
2334     // https://bugs.webkit.org/show_bug.cgi?id=46418
2335     bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == BoxOrient::Vertical);
2336     bool stretching = (parent()->style().boxAlign() == BoxAlignment::Stretch);
2337     // FIXME: Stretching is the only reason why we don't want the box to be treated as a replaced element, so we could perhaps
2338     // refactor all this logic, not only for flex and grid since alignment is intended to be applied to any block.
2339     bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
2340     treatAsReplaced = treatAsReplaced && (!isGridItem() || !hasStretchedLogicalWidth());
2341
2342     const RenderStyle& styleToUse = style();
2343     Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse.logicalWidth();
2344
2345     RenderBlock& cb = *containingBlock();
2346     LayoutUnit containerLogicalWidth = std::max<LayoutUnit>(0, containingBlockLogicalWidthForContentInFragment(fragment));
2347     bool hasPerpendicularContainingBlock = cb.isHorizontalWritingMode() != isHorizontalWritingMode();
2348
2349     if (isInline() && !isInlineBlockOrInlineTable()) {
2350         // just calculate margins
2351         computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2352         computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2353         if (treatAsReplaced)
2354             computedValues.m_extent = std::max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
2355         return;
2356     }
2357
2358     LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
2359     if (hasPerpendicularContainingBlock)
2360         containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
2361
2362     // Width calculations
2363     if (treatAsReplaced) {
2364         computedValues.m_extent = logicalWidthLength.value() + borderAndPaddingLogicalWidth();
2365     } else {
2366         LayoutUnit preferredWidth = computeLogicalWidthInFragmentUsing(MainOrPreferredSize, styleToUse.logicalWidth(), containerWidthInInlineDirection, cb, fragment);
2367         computedValues.m_extent = constrainLogicalWidthInFragmentByMinMax(preferredWidth, containerWidthInInlineDirection, cb, fragment);
2368     }
2369
2370     // Margin calculations.
2371     if (hasPerpendicularContainingBlock || isFloating() || isInline()) {
2372         computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2373         computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2374     } else {
2375         LayoutUnit containerLogicalWidthForAutoMargins = containerLogicalWidth;
2376         if (avoidsFloats() && cb.containsFloats())
2377             containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInFragment(fragment);
2378         bool hasInvertedDirection = cb.style().isLeftToRightDirection() != style().isLeftToRightDirection();
2379         computeInlineDirectionMargins(cb, containerLogicalWidthForAutoMargins, computedValues.m_extent,
2380             hasInvertedDirection ? computedValues.m_margins.m_end : computedValues.m_margins.m_start,
2381             hasInvertedDirection ? computedValues.m_margins.m_start : computedValues.m_margins.m_end);
2382     }
2383     
2384     if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (computedValues.m_extent + computedValues.m_margins.m_start + computedValues.m_margins.m_end)
2385         && !isFloating() && !isInline() && !cb.isFlexibleBoxIncludingDeprecated()
2386 #if ENABLE(MATHML)
2387         // RenderMathMLBlocks take the size of their content so we must not adjust the margin to fill the container size.
2388         && !cb.isRenderMathMLBlock()
2389 #endif
2390         && !cb.isRenderGrid()
2391         ) {
2392         LayoutUnit newMarginTotal = containerLogicalWidth - computedValues.m_extent;
2393         bool hasInvertedDirection = cb.style().isLeftToRightDirection() != style().isLeftToRightDirection();
2394         if (hasInvertedDirection)
2395             computedValues.m_margins.m_start = newMarginTotal - computedValues.m_margins.m_end;
2396         else
2397             computedValues.m_margins.m_end = newMarginTotal - computedValues.m_margins.m_start;
2398     }
2399 }
2400
2401 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth) const
2402 {
2403     LayoutUnit marginStart = 0;
2404     LayoutUnit marginEnd = 0;
2405     return fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2406 }
2407
2408 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2409 {
2410     marginStart = minimumValueForLength(style().marginStart(), availableLogicalWidth);
2411     marginEnd = minimumValueForLength(style().marginEnd(), availableLogicalWidth);
2412     return availableLogicalWidth - marginStart - marginEnd;
2413 }
2414
2415 LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(Length logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const
2416 {
2417     if (logicalWidthLength.type() == FillAvailable)
2418         return std::max(borderAndPadding, fillAvailableMeasure(availableLogicalWidth));
2419
2420     LayoutUnit minLogicalWidth = 0;
2421     LayoutUnit maxLogicalWidth = 0;
2422     computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
2423
2424     if (logicalWidthLength.type() == MinContent)
2425         return minLogicalWidth + borderAndPadding;
2426
2427     if (logicalWidthLength.type() == MaxContent)
2428         return maxLogicalWidth + borderAndPadding;
2429
2430     if (logicalWidthLength.type() == FitContent) {
2431         minLogicalWidth += borderAndPadding;
2432         maxLogicalWidth += borderAndPadding;
2433         return std::max(minLogicalWidth, std::min(maxLogicalWidth, fillAvailableMeasure(availableLogicalWidth)));
2434     }
2435
2436     ASSERT_NOT_REACHED();
2437     return 0;
2438 }
2439
2440 LayoutUnit RenderBox::computeLogicalWidthInFragmentUsing(SizeType widthType, Length logicalWidth, LayoutUnit availableLogicalWidth,
2441     const RenderBlock& cb, RenderFragmentContainer* fragment) const
2442 {
2443     ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto());
2444     if (widthType == MinSize && logicalWidth.isAuto())
2445         return adjustBorderBoxLogicalWidthForBoxSizing(0);
2446
2447     if (!logicalWidth.isIntrinsicOrAuto()) {
2448         // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
2449         return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth));
2450     }
2451
2452     if (logicalWidth.isIntrinsic())
2453         return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth());
2454
2455     LayoutUnit marginStart = 0;
2456     LayoutUnit marginEnd = 0;
2457     LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2458
2459     if (shrinkToAvoidFloats() && cb.containsFloats())
2460         logicalWidthResult = std::min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, fragment));
2461
2462     if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(widthType))
2463         return std::max(minPreferredLogicalWidth(), std::min(maxPreferredLogicalWidth(), logicalWidthResult));
2464     return logicalWidthResult;
2465 }
2466
2467 bool RenderBox::columnFlexItemHasStretchAlignment() const
2468 {
2469     // auto margins mean we don't stretch. Note that this function will only be
2470     // used for widths, so we don't have to check marginBefore/marginAfter.
2471     const auto& parentStyle = parent()->style();
2472     ASSERT(parentStyle.isColumnFlexDirection());
2473     if (style().marginStart().isAuto() || style().marginEnd().isAuto())
2474         return false;
2475     return style().resolvedAlignSelf(&parentStyle, containingBlock()->selfAlignmentNormalBehavior()).position() == ItemPosition::Stretch;
2476 }
2477
2478 bool RenderBox::isStretchingColumnFlexItem() const
2479 {
2480     if (parent()->isDeprecatedFlexibleBox() && parent()->style().boxOrient() == BoxOrient::Vertical && parent()->style().boxAlign() == BoxAlignment::Stretch)
2481         return true;
2482
2483     // We don't stretch multiline flexboxes because they need to apply line spacing (align-content) first.
2484     if (parent()->isFlexibleBox() && parent()->style().flexWrap() == FlexWrap::NoWrap && parent()->style().isColumnFlexDirection() && columnFlexItemHasStretchAlignment())
2485         return true;
2486     return false;
2487 }
2488
2489 // FIXME: Can/Should we move this inside specific layout classes (flex. grid)? Can we refactor columnFlexItemHasStretchAlignment logic?
2490 bool RenderBox::hasStretchedLogicalWidth() const
2491 {
2492     auto& style = this->style();
2493     if (!style.logicalWidth().isAuto() || style.marginStart().isAuto() || style.marginEnd().isAuto())
2494         return false;
2495     RenderBlock* containingBlock = this->containingBlock();
2496     if (!containingBlock) {
2497         // We are evaluating align-self/justify-self, which default to 'normal' for the root element.
2498         // The 'normal' value behaves like 'start' except for Flexbox Items, which obviously should have a container.
2499         return false;
2500     }
2501     if (containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2502         return style.resolvedAlignSelf(&containingBlock->style(), containingBlock->selfAlignmentNormalBehavior(this)).position() == ItemPosition::Stretch;
2503     return style.resolvedJustifySelf(&containingBlock->style(), containingBlock->selfAlignmentNormalBehavior(this)).position() == ItemPosition::Stretch;
2504 }
2505
2506 bool RenderBox::sizesLogicalWidthToFitContent(SizeType widthType) const
2507 {
2508     // Marquees in WinIE are like a mixture of blocks and inline-blocks.  They size as though they're blocks,
2509     // but they allow text to sit on the same line as the marquee.
2510     if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee()))
2511         return true;
2512
2513     if (isGridItem())
2514         return !hasStretchedLogicalWidth();
2515
2516     // This code may look a bit strange.  Basically width:intrinsic should clamp the size when testing both
2517     // min-width and width.  max-width is only clamped if it is also intrinsic.
2518     Length logicalWidth = (widthType == MaxSize) ? style().logicalMaxWidth() : style().logicalWidth();
2519     if (logicalWidth.type() == Intrinsic)
2520         return true;
2521
2522     // Children of a horizontal marquee do not fill the container by default.
2523     // FIXME: Need to deal with MarqueeDirection::Auto value properly. It could be vertical.
2524     // FIXME: Think about block-flow here.  Need to find out how marquee direction relates to
2525     // block-flow (as well as how marquee overflow should relate to block flow).
2526     // https://bugs.webkit.org/show_bug.cgi?id=46472
2527     if (parent()->isHTMLMarquee()) {
2528         MarqueeDirection dir = parent()->style().marqueeDirection();
2529         if (dir == MarqueeDirection::Auto || dir == MarqueeDirection::Forward || dir == MarqueeDirection::Backward || dir == MarqueeDirection::Left || dir == MarqueeDirection::Right)
2530             return true;
2531     }
2532
2533 #if ENABLE(MATHML)
2534     // RenderMathMLBlocks take the size of their content, not of their container.
2535     if (parent()->isRenderMathMLBlock())
2536         return true;
2537 #endif
2538
2539     // Flexible box items should shrink wrap, so we lay them out at their intrinsic widths.
2540     // In the case of columns that have a stretch alignment, we layout at the stretched size
2541     // to avoid an extra layout when applying alignment.
2542     if (parent()->isFlexibleBox()) {
2543         // For multiline columns, we need to apply align-content first, so we can't stretch now.
2544         if (!parent()->style().isColumnFlexDirection() || parent()->style().flexWrap() != FlexWrap::NoWrap)
2545             return true;
2546         if (!columnFlexItemHasStretchAlignment())
2547             return true;
2548     }
2549
2550     // Flexible horizontal boxes lay out children at their intrinsic widths.  Also vertical boxes
2551     // that don't stretch their kids lay out their children at their intrinsic widths.
2552     // FIXME: Think about block-flow here.
2553     // https://bugs.webkit.org/show_bug.cgi?id=46473
2554     if (parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == BoxOrient::Horizontal || parent()->style().boxAlign() != BoxAlignment::Stretch))
2555         return true;
2556
2557     // Button, input, select, textarea, and legend treat width value of 'auto' as 'intrinsic' unless it's in a
2558     // stretching column flexbox.
2559     // FIXME: Think about block-flow here.
2560     // https://bugs.webkit.org/show_bug.cgi?id=46473
2561     if (logicalWidth.type() == Auto && !isStretchingColumnFlexItem() && element() && (is<HTMLInputElement>(*element()) || is<HTMLSelectElement>(*element()) || is<HTMLButtonElement>(*element()) || is<HTMLTextAreaElement>(*element()) || is<HTMLLegendElement>(*element())))
2562         return true;
2563
2564     if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
2565         return true;
2566
2567     return false;
2568 }
2569
2570 void RenderBox::computeInlineDirectionMargins(const RenderBlock& containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2571 {
2572     
2573     const RenderStyle& containingBlockStyle = containingBlock.style();
2574     Length marginStartLength = style().marginStartUsing(&containingBlockStyle);
2575     Length marginEndLength = style().marginEndUsing(&containingBlockStyle);
2576
2577     if (isFloating() || isInline()) {
2578         // Inline blocks/tables and floats don't have their margins increased.
2579         marginStart = minimumValueForLength(marginStartLength, containerWidth);
2580         marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2581         return;
2582     }
2583
2584     if (containingBlock.isFlexibleBox()) {
2585         // We need to let flexbox handle the margin adjustment - otherwise, flexbox
2586         // will think we're wider than we actually are and calculate line sizes
2587         // wrong. See also http://dev.w3.org/csswg/css-flexbox/#auto-margins
2588         if (marginStartLength.isAuto())
2589             marginStartLength = Length(0, Fixed);
2590         if (marginEndLength.isAuto())
2591             marginEndLength = Length(0, Fixed);
2592     }
2593
2594     // Case One: The object is being centered in the containing block's available logical width.
2595     if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
2596         || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock.style().textAlign() == TextAlignMode::WebKitCenter)) {
2597         // Other browsers center the margin box for align=center elements so we match them here.
2598         LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth);
2599         LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth);
2600         LayoutUnit centeredMarginBoxStart = std::max<LayoutUnit>(0, (containerWidth - childWidth - marginStartWidth - marginEndWidth) / 2);
2601         marginStart = centeredMarginBoxStart + marginStartWidth;
2602         marginEnd = containerWidth - childWidth - marginStart + marginEndWidth;
2603         return;
2604     } 
2605     
2606     // Case Two: The object is being pushed to the start of the containing block's available logical width.
2607     if (marginEndLength.isAuto() && childWidth < containerWidth) {
2608         marginStart = valueForLength(marginStartLength, containerWidth);
2609         marginEnd = containerWidth - childWidth - marginStart;
2610         return;
2611     } 
2612     
2613     // Case Three: The object is being pushed to the end of the containing block's available logical width.
2614     bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == TextAlignMode::WebKitLeft)
2615         || (containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == TextAlignMode::WebKitRight));
2616     if ((marginStartLength.isAuto() || pushToEndFromTextAlign) && childWidth < containerWidth) {
2617         marginEnd = valueForLength(marginEndLength, containerWidth);
2618         marginStart = containerWidth - childWidth - marginEnd;
2619         return;
2620     } 
2621     
2622     // Case Four: Either no auto margins, or our width is >= the container width (css2.1, 10.3.3).  In that case
2623     // auto margins will just turn into 0.
2624     marginStart = minimumValueForLength(marginStartLength, containerWidth);
2625     marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2626 }
2627
2628 RenderBoxFragmentInfo* RenderBox::renderBoxFragmentInfo(RenderFragmentContainer* fragment, RenderBoxFragmentInfoFlags cacheFlag) const
2629 {
2630     // Make sure nobody is trying to call this with a null fragment.
2631     if (!fragment)
2632         return nullptr;
2633
2634     // If we have computed our width in this fragment already, it will be cached, and we can
2635     // just return it.
2636     RenderBoxFragmentInfo* boxInfo = fragment->renderBoxFragmentInfo(this);
2637     if (boxInfo && cacheFlag == CacheRenderBoxFragmentInfo)
2638         return boxInfo;
2639
2640     return nullptr;
2641 }
2642
2643 static bool shouldFlipBeforeAfterMargins(const RenderStyle& containingBlockStyle, const RenderStyle* childStyle)
2644 {
2645     ASSERT(containingBlockStyle.isHorizontalWritingMode() != childStyle->isHorizontalWritingMode());
2646     WritingMode childWritingMode = childStyle->writingMode();
2647     bool shouldFlip = false;
2648     switch (containingBlockStyle.writingMode()) {
2649     case TopToBottomWritingMode:
2650         shouldFlip = (childWritingMode == RightToLeftWritingMode);
2651         break;
2652     case BottomToTopWritingMode:
2653         shouldFlip = (childWritingMode == RightToLeftWritingMode);
2654         break;
2655     case RightToLeftWritingMode:
2656         shouldFlip = (childWritingMode == BottomToTopWritingMode);
2657         break;
2658     case LeftToRightWritingMode:
2659         shouldFlip = (childWritingMode == BottomToTopWritingMode);
2660         break;
2661     }
2662
2663     if (!containingBlockStyle.isLeftToRightDirection())
2664         shouldFlip = !shouldFlip;
2665
2666     return shouldFlip;
2667 }
2668
2669 void RenderBox::cacheIntrinsicContentLogicalHeightForFlexItem(LayoutUnit height) const
2670 {
2671     if (isFloatingOrOutOfFlowPositioned() || !parent() || !parent()->isFlexibleBox())
2672         return;
2673     downcast<RenderFlexibleBox>(parent())->setCachedChildIntrinsicContentLogicalHeight(*this, height);
2674 }
2675
2676 void RenderBox::updateLogicalHeight()
2677 {
2678     cacheIntrinsicContentLogicalHeightForFlexItem(contentLogicalHeight());
2679     auto computedValues = computeLogicalHeight(logicalHeight(), logicalTop());
2680     setLogicalHeight(computedValues.m_extent);
2681     setLogicalTop(computedValues.m_position);
2682     setMarginBefore(computedValues.m_margins.m_before);
2683     setMarginAfter(computedValues.m_margins.m_after);
2684 }
2685
2686 RenderBox::LogicalExtentComputedValues RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop) const
2687 {
2688     LogicalExtentComputedValues computedValues;
2689     computedValues.m_extent = logicalHeight;
2690     computedValues.m_position = logicalTop;
2691
2692     // Cell height is managed by the table and inline non-replaced elements do not support a height property.
2693     if (isTableCell() || (isInline() && !isReplaced()))
2694         return computedValues;
2695
2696     Length h;
2697     if (isOutOfFlowPositioned())
2698         computePositionedLogicalHeight(computedValues);
2699     else {
2700         RenderBlock& cb = *containingBlock();
2701         bool hasPerpendicularContainingBlock = cb.isHorizontalWritingMode() != isHorizontalWritingMode();
2702     
2703         if (!hasPerpendicularContainingBlock) {
2704             bool shouldFlipBeforeAfter = cb.style().writingMode() != style().writingMode();
2705             computeBlockDirectionMargins(cb,
2706                 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2707                 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2708         }
2709
2710         // For tables, calculate margins only.
2711         if (isTable()) {
2712             if (hasPerpendicularContainingBlock) {
2713                 bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb.style(), &style());
2714                 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), computedValues.m_extent,
2715                     shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2716                     shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2717             }
2718             return computedValues;
2719         }
2720
2721         // FIXME: Account for block-flow in flexible boxes.
2722         // https://bugs.webkit.org/show_bug.cgi?id=46418
2723         bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style().boxOrient() == BoxOrient::Horizontal;
2724         bool stretching = parent()->style().boxAlign() == BoxAlignment::Stretch;
2725         bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
2726         bool checkMinMaxHeight = false;
2727
2728         // The parent box is flexing us, so it has increased or decreased our height.  We have to
2729         // grab our cached flexible height.
2730         // FIXME: Account for block-flow in flexible boxes.
2731         // https://bugs.webkit.org/show_bug.cgi?id=46418
2732         if (hasOverrideContentLogicalHeight() && (parent()->isFlexibleBoxIncludingDeprecated() || parent()->isRenderGrid())) {
2733             h = Length(overrideContentLogicalHeight(), Fixed);
2734         } else if (treatAsReplaced)
2735             h = Length(computeReplacedLogicalHeight(), Fixed);
2736         else {
2737             h = style().logicalHeight();
2738             checkMinMaxHeight = true;
2739         }
2740
2741         // Block children of horizontal flexible boxes fill the height of the box.
2742         // FIXME: Account for block-flow in flexible boxes.
2743         // https://bugs.webkit.org/show_bug.cgi?id=46418
2744         if (h.isAuto() && is<RenderDeprecatedFlexibleBox>(*parent()) && parent()->style().boxOrient() == BoxOrient::Horizontal
2745                 && downcast<RenderDeprecatedFlexibleBox>(*parent()).isStretchingChildren()) {
2746             h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2747             checkMinMaxHeight = false;
2748         }
2749
2750         LayoutUnit heightResult;
2751         if (checkMinMaxHeight) {
2752             LayoutUnit intrinsicHeight = computedValues.m_extent - borderAndPaddingLogicalHeight();
2753             heightResult = computeLogicalHeightUsing(MainOrPreferredSize, style().logicalHeight(), intrinsicHeight).value_or(computedValues.m_extent);
2754             heightResult = constrainLogicalHeightByMinMax(heightResult, intrinsicHeight);
2755         } else {
2756             // The only times we don't check min/max height are when a fixed length has
2757             // been given as an override.  Just use that.  The value has already been adjusted
2758             // for box-sizing.
2759             ASSERT(h.isFixed());
2760             heightResult = h.value() + borderAndPaddingLogicalHeight();
2761         }
2762
2763         computedValues.m_extent = heightResult;
2764
2765         if (hasPerpendicularContainingBlock) {
2766             bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb.style(), &style());
2767             computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult,
2768                     shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2769                     shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2770         }
2771     }
2772
2773     // WinIE quirk: The <html> block always fills the entire canvas in quirks mode.  The <body> always fills the
2774     // <html> block in quirks mode.  Only apply this quirk if the block is normal flow and no height
2775     // is specified. When we're printing, we also need this quirk if the body or root has a percentage 
2776     // height since we don't set a height in RenderView when we're printing. So without this quirk, the 
2777     // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2778     bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercentOrCalculated()
2779         && (isDocumentElementRenderer() || (isBody() && document().documentElement()->renderer()->style().logicalHeight().isPercentOrCalculated())) && !isInline();
2780     if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2781         LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2782         LayoutUnit visibleHeight = view().pageOrViewLogicalHeight();
2783         if (isDocumentElementRenderer())
2784             computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - margins);
2785         else {
2786             LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2787             computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - marginsBordersPadding);
2788         }
2789     }
2790     return computedValues;
2791 }
2792
2793 LayoutUnit RenderBox::computeLogicalHeightWithoutLayout() const
2794 {
2795     // FIXME:: We should probably return something other than just
2796     // border + padding, but for now we have no good way to do anything else
2797     // without layout, so we just use that.
2798     LogicalExtentComputedValues computedValues = computeLogicalHeight(borderAndPaddingLogicalHeight(), LayoutUnit());
2799     return computedValues.m_extent;
2800 }
2801
2802 std::optional<LayoutUnit> RenderBox::computeLogicalHeightUsing(SizeType heightType, const Length& height, std::optional<LayoutUnit> intrinsicContentHeight) const
2803 {
2804     if (std::optional<LayoutUnit> logicalHeight = computeContentAndScrollbarLogicalHeightUsing(heightType, height, intrinsicContentHeight))
2805         return adjustBorderBoxLogicalHeightForBoxSizing(logicalHeight.value());
2806     return std::nullopt;
2807 }
2808
2809 std::optional<LayoutUnit> RenderBox::computeContentLogicalHeight(SizeType heightType, const Length& height, std::optional<LayoutUnit> intrinsicContentHeight) const
2810 {
2811     if (std::optional<LayoutUnit> heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(heightType, height, intrinsicContentHeight))
2812         return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2813     return std::nullopt;
2814 }
2815
2816 std::optional<LayoutUnit> RenderBox::computeIntrinsicLogicalContentHeightUsing(Length logicalHeightLength, std::optional<LayoutUnit> intrinsicContentHeight, LayoutUnit borderAndPadding) const
2817 {
2818     // FIXME: The CSS sizing spec is considering changing what min-content/max-content should resolve to.
2819     // If that happens, this code will have to change.
2820     if (logicalHeightLength.isMinContent() || logicalHeightLength.isMaxContent() || logicalHeightLength.isFitContent()) {
2821         if (!intrinsicContentHeight)
2822             return intrinsicContentHeight;
2823         if (style().boxSizing() == BoxSizing::BorderBox)
2824             return intrinsicContentHeight.value() + borderAndPaddingLogicalHeight();
2825         return intrinsicContentHeight;
2826     }
2827     if (logicalHeightLength.isFillAvailable())
2828         return containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding) - borderAndPadding;
2829     ASSERT_NOT_REACHED();
2830     return LayoutUnit(0);
2831 }
2832
2833 std::optional<LayoutUnit> RenderBox::computeContentAndScrollbarLogicalHeightUsing(SizeType heightType, const Length& height, std::optional<LayoutUnit> intrinsicContentHeight) const
2834 {
2835     if (height.isAuto())
2836         return heightType == MinSize ? std::optional<LayoutUnit>(0) : std::nullopt;
2837     // FIXME: The CSS sizing spec is considering changing what min-content/max-content should resolve to.
2838     // If that happens, this code will have to change.
2839     if (height.isIntrinsic())
2840         return computeIntrinsicLogicalContentHeightUsing(height, intrinsicContentHeight, borderAndPaddingLogicalHeight());
2841     if (height.isFixed())
2842         return LayoutUnit(height.value());
2843     if (height.isPercentOrCalculated())
2844         return computePercentageLogicalHeight(height);
2845     return std::nullopt;
2846 }
2847
2848 bool RenderBox::skipContainingBlockForPercentHeightCalculation(const RenderBox& containingBlock, bool isPerpendicularWritingMode) const
2849 {
2850     // Flow threads for multicol or paged overflow should be skipped. They are invisible to the DOM,
2851     // and percent heights of children should be resolved against the multicol or paged container.
2852     if (containingBlock.isInFlowRenderFragmentedFlow() && !isPerpendicularWritingMode)
2853         return true;
2854
2855     // Render view is not considered auto height.
2856     if (is<RenderView>(containingBlock))
2857         return false;
2858
2859     // If the writing mode of the containing block is orthogonal to ours, it means
2860     // that we shouldn't skip anything, since we're going to resolve the
2861     // percentage height against a containing block *width*.
2862     if (isPerpendicularWritingMode)
2863         return false;
2864     
2865     // Anonymous blocks should not impede percentage resolution on a child.
2866     // Examples of such anonymous blocks are blocks wrapped around inlines that
2867     // have block siblings (from the CSS spec) and multicol flow threads (an
2868     // implementation detail). Another implementation detail, ruby runs, create
2869     // anonymous inline-blocks, so skip those too. All other types of anonymous
2870     // objects, such as table-cells and flexboxes, will be treated as if they were
2871     // non-anonymous.
2872     if (containingBlock.isAnonymous())
2873         return containingBlock.style().display() == DisplayType::Block || containingBlock.style().display() == DisplayType::InlineBlock;
2874     
2875     // For quirks mode, we skip most auto-height containing blocks when computing
2876     // percentages.
2877     return document().inQuirksMode() && !containingBlock.isTableCell() && !containingBlock.isOutOfFlowPositioned() && !containingBlock.isRenderGrid() && containingBlock.style().logicalHeight().isAuto();
2878 }
2879
2880 bool RenderBox::shouldTreatChildAsReplacedInTableCells() const
2881 {
2882     if (isReplaced())
2883         return true;
2884     return element() && (element()->isFormControlElement() || is<HTMLImageElement>(element()));
2885 }
2886
2887 static bool tableCellShouldHaveZeroInitialSize(const RenderBlock& block, const RenderBox& child, bool scrollsOverflowY)
2888 {
2889     // Normally we would let the cell size intrinsically, but scrolling overflow has to be
2890     // treated differently, since WinIE lets scrolled overflow fragments shrink as needed.
2891     // While we can't get all cases right, we can at least detect when the cell has a specified
2892     // height or when the table has a specified height. In these cases we want to initially have
2893     // no size and allow the flexing of the table or the cell to its specified height to cause us
2894     // to grow to fill the space. This could end up being wrong in some cases, but it is
2895     // preferable to the alternative (sizing intrinsically and making the row end up too big).
2896     const RenderTableCell& cell = downcast<RenderTableCell>(block);
2897     return scrollsOverflowY && !child.shouldTreatChildAsReplacedInTableCells() && (!cell.style().logicalHeight().isAuto() || !cell.table()->style().logicalHeight().isAuto());
2898 }
2899
2900 std::optional<LayoutUnit> RenderBox::computePercentageLogicalHeight(const Length& height) const
2901 {
2902     std::optional<LayoutUnit> availableHeight;
2903
2904     bool skippedAutoHeightContainingBlock = false;
2905     RenderBlock* cb = containingBlock();
2906     const RenderBox* containingBlockChild = this;
2907     LayoutUnit rootMarginBorderPaddingHeight = 0;
2908     bool isHorizontal = isHorizontalWritingMode();
2909     while (cb && !is<RenderView>(*cb) && skipContainingBlockForPercentHeightCalculation(*cb, isHorizontal != cb->isHorizontalWritingMode())) {
2910         if (cb->isBody() || cb->isDocumentElementRenderer())
2911             rootMarginBorderPaddingHeight += cb->marginBefore() + cb->marginAfter() + cb->borderAndPaddingLogicalHeight();
2912         skippedAutoHeightContainingBlock = true;
2913         containingBlockChild = cb;
2914         cb = cb->containingBlock();
2915     }
2916     cb->addPercentHeightDescendant(const_cast<RenderBox&>(*this));
2917
2918     if (isHorizontal != cb->isHorizontalWritingMode())
2919         availableHeight = containingBlockChild->containingBlockLogicalWidthForContent();
2920     else if (hasOverrideContainingBlockContentLogicalHeight())
2921         availableHeight = overrideContainingBlockContentLogicalHeight();
2922     else if (is<RenderTableCell>(*cb)) {
2923         if (!skippedAutoHeightContainingBlock) {
2924             // Table cells violate what the CSS spec says to do with heights. Basically we
2925             // don't care if the cell specified a height or not. We just always make ourselves
2926             // be a percentage of the cell's current content height.
2927             if (!cb->hasOverrideContentLogicalHeight())
2928                 return tableCellShouldHaveZeroInitialSize(*cb, *this, scrollsOverflowY()) ? std::optional<LayoutUnit>(0) : std::nullopt;
2929
2930             availableHeight = cb->overrideContentLogicalHeight();
2931         }
2932     } else
2933         availableHeight = cb->availableLogicalHeightForPercentageComputation();
2934     
2935     if (!availableHeight)
2936         return availableHeight;
2937
2938     LayoutUnit result = valueForLength(height, availableHeight.value() - rootMarginBorderPaddingHeight + (isTable() && isOutOfFlowPositioned() ? cb->paddingBefore() + cb->paddingAfter() : LayoutUnit()));
2939     
2940     // |overrideContentLogicalHeight| is the maximum height made available by the
2941     // cell to its percent height children when we decide they can determine the
2942     // height of the cell. If the percent height child is box-sizing:content-box
2943     // then we must subtract the border and padding from the cell's
2944     // |availableHeight| (given by |overrideContentLogicalHeight|) to arrive
2945     // at the child's computed height.
2946     bool subtractBorderAndPadding = isTable() || (is<RenderTableCell>(*cb) && !skippedAutoHeightContainingBlock && cb->hasOverrideContentLogicalHeight());
2947     if (subtractBorderAndPadding) {
2948         result -= borderAndPaddingLogicalHeight();
2949         return std::max(LayoutUnit(), result);
2950     }
2951     return result;
2952 }
2953
2954 LayoutUnit RenderBox::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
2955 {
2956     return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(MainOrPreferredSize, style().logicalWidth()), shouldComputePreferred);
2957 }
2958
2959 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, ShouldComputePreferred shouldComputePreferred) const
2960 {
2961     auto& logicalMinWidth = style().logicalMinWidth();
2962     auto& logicalMaxWidth = style().logicalMaxWidth();
2963     bool useLogicalWidthForMinWidth = (shouldComputePreferred == ComputePreferred && logicalMinWidth.isPercentOrCalculated()) || logicalMinWidth.isUndefined();
2964     bool useLogicalWidthForMaxWidth = (shouldComputePreferred == ComputePreferred && logicalMaxWidth.isPercentOrCalculated()) || logicalMaxWidth.isUndefined();
2965     auto minLogicalWidth =  useLogicalWidthForMinWidth ? logicalWidth : computeReplacedLogicalWidthUsing(MinSize, logicalMinWidth);
2966     auto maxLogicalWidth =  useLogicalWidthForMaxWidth ? logicalWidth : computeReplacedLogicalWidthUsing(MaxSize, logicalMaxWidth);
2967     return std::max(minLogicalWidth, std::min(logicalWidth, maxLogicalWidth));
2968 }
2969
2970 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(SizeType widthType, Length logicalWidth) const
2971 {
2972     ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto());
2973     if (widthType == MinSize && logicalWidth.isAuto())
2974         return adjustContentBoxLogicalWidthForBoxSizing(0);
2975
2976     switch (logicalWidth.type()) {
2977         case Fixed:
2978             return adjustContentBoxLogicalWidthForBoxSizing(logicalWidth.value());
2979         case MinContent:
2980         case MaxContent: {
2981             // MinContent/MaxContent don't need the availableLogicalWidth argument.
2982             LayoutUnit availableLogicalWidth = 0;
2983             return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2984         }
2985         case FitContent:
2986         case FillAvailable:
2987         case Percent: 
2988         case Calculated: {
2989             // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
2990             // containing block's block-flow.
2991             // https://bugs.webkit.org/show_bug.cgi?id=46496
2992             const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(downcast<RenderBoxModelObject>(*container())) : containingBlockLogicalWidthForContent();
2993             Length containerLogicalWidth = containingBlock()->style().logicalWidth();
2994             // FIXME: Handle cases when containing block width is calculated or viewport percent.
2995             // https://bugs.webkit.org/show_bug.cgi?id=91071
2996             if (logicalWidth.isIntrinsic())
2997                 return computeIntrinsicLogicalWidthUsing(logicalWidth, cw, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2998             if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercentOrCalculated())))
2999                 return adjustContentBoxLogicalWidthForBoxSizing(minimumValueForLength(logicalWidth, cw));
3000             return LayoutUnit();
3001         }
3002         case Intrinsic:
3003         case MinIntrinsic:
3004         case Auto:
3005         case Relative:
3006         case Undefined:
3007             return intrinsicLogicalWidth();
3008     }
3009
3010     ASSERT_NOT_REACHED();
3011     return 0;
3012 }
3013
3014 LayoutUnit RenderBox::computeReplacedLogicalHeight(std::optional<LayoutUnit>) const
3015 {
3016     return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(MainOrPreferredSize, style().logicalHeight()));
3017 }
3018
3019 static bool allowMinMaxPercentagesInAutoHeightBlocksQuirk()
3020 {
3021 #if PLATFORM(MAC)
3022     return MacApplication::isIBooks();
3023 #elif PLATFORM(IOS_FAMILY)
3024     return IOSApplication::isIBooks();
3025 #endif
3026     return false;
3027 }
3028
3029 bool RenderBox::replacedMinMaxLogicalHeightComputesAsNone(SizeType sizeType) const
3030 {
3031     ASSERT(sizeType == MinSize || sizeType == MaxSize);
3032     
3033     auto logicalHeight = sizeType == MinSize ? style().logicalMinHeight() : style().logicalMaxHeight();
3034     auto initialLogicalHeight = sizeType == MinSize ? RenderStyle::initialMinSize() : RenderStyle::initialMaxSize();
3035     
3036     if (logicalHeight == initialLogicalHeight)
3037         return true;
3038     
3039     // Make sure % min-height and % max-height resolve to none if the containing block has auto height.
3040     // Note that the "height" case for replaced elements was handled by hasReplacedLogicalHeight, which is why
3041     // min and max-height are the only ones handled here.
3042     // FIXME: For now we put in a quirk for iBooks until we can move them to viewport units.
3043     if (auto* cb = containingBlockForAutoHeightDetection(logicalHeight))
3044         return allowMinMaxPercentagesInAutoHeightBlocksQuirk() ? false : cb->hasAutoHeightOrContainingBlockWithAutoHeight();
3045
3046     return false;
3047 }
3048
3049 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
3050 {
3051     LayoutUnit minLogicalHeight;
3052     if (!replacedMinMaxLogicalHeightComputesAsNone(MinSize))
3053         minLogicalHeight = computeReplacedLogicalHeightUsing(MinSize, style().logicalMinHeight());
3054     LayoutUnit maxLogicalHeight = logicalHeight;
3055     if (!replacedMinMaxLogicalHeightComputesAsNone(MaxSize))
3056         maxLogicalHeight = computeReplacedLogicalHeightUsing(MaxSize, style().logicalMaxHeight());
3057     return std::max(minLogicalHeight, std::min(logicalHeight, maxLogicalHeight));
3058 }
3059
3060 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(SizeType heightType, Length logicalHeight) const
3061 {
3062     ASSERT(heightType == MinSize || heightType == MainOrPreferredSize || !logicalHeight.isAuto());
3063     if (heightType == MinSize && logicalHeight.isAuto())
3064         return adjustContentBoxLogicalHeightForBoxSizing(std::optional<LayoutUnit>(0));
3065
3066     switch (logicalHeight.type()) {
3067         case Fixed:
3068             return adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(logicalHeight.value()));
3069         case Percent:
3070         case Calculated:
3071         {
3072             auto* container = isOutOfFlowPositioned() ? this->container() : containingBlock();
3073             while (container && container->isAnonymous()) {
3074                 // Stop at rendering context root.
3075                 if (is<RenderView>(*container))
3076                     break;
3077                 container = container->containingBlock();
3078             }
3079             std::optional<LayoutUnit> stretchedHeight;
3080             if (is<RenderBlock>(container)) {
3081                 auto* block = downcast<RenderBlock>(container);
3082                 block->addPercentHeightDescendant(*const_cast<RenderBox*>(this));
3083                 if (block->isFlexItem())
3084                     stretchedHeight = downcast<RenderFlexibleBox>(block->parent())->childLogicalHeightForPercentageResolution(*block);
3085                 else if (block->isGridItem() && block->hasOverrideContentLogicalHeight())
3086                     stretchedHeight = block->overrideContentLogicalHeight();
3087             }
3088
3089             // FIXME: This calculation is not patched for block-flow yet.
3090             // https://bugs.webkit.org/show_bug.cgi?id=46500
3091             if (container->isOutOfFlowPositioned()
3092                 && container->style().height().isAuto()
3093                 && !(container->style().top().isAuto() || container->style().bottom().isAuto())) {
3094                 ASSERT_WITH_SECURITY_IMPLICATION(container->isRenderBlock());
3095                 auto& block = downcast<RenderBlock>(*container);
3096                 auto computedValues = block.computeLogicalHeight(block.logicalHeight(), 0);
3097                 LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3098                 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, newContentHeight));
3099             }
3100             
3101             // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
3102             // containing block's block-flow.
3103             // https://bugs.webkit.org/show_bug.cgi?id=46496
3104             LayoutUnit availableHeight;
3105             if (isOutOfFlowPositioned())
3106                 availableHeight = containingBlockLogicalHeightForPositioned(downcast<RenderBoxModelObject>(*container));
3107             else if (stretchedHeight)
3108                 availableHeight = stretchedHeight.value();
3109             else {
3110                 availableHeight = containingBlockLogicalHeightForContent(IncludeMarginBorderPadding);
3111                 // It is necessary to use the border-box to match WinIE's broken
3112                 // box model.  This is essential for sizing inside
3113                 // table cells using percentage heights.
3114                 // FIXME: This needs to be made block-flow-aware.  If the cell and image are perpendicular block-flows, this isn't right.
3115                 // https://bugs.webkit.org/show_bug.cgi?id=46997
3116                 while (container && !is<RenderView>(*container)
3117                     && (container->style().logicalHeight().isAuto() || container->style().logicalHeight().isPercentOrCalculated())) {
3118                     if (container->isTableCell()) {
3119                         // Don't let table cells squeeze percent-height replaced elements
3120                         // <http://bugs.webkit.org/show_bug.cgi?id=15359>
3121                         availableHeight = std::max(availableHeight, intrinsicLogicalHeight());
3122                         return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight());
3123                     }
3124                     downcast<RenderBlock>(*container).addPercentHeightDescendant(const_cast<RenderBox&>(*this));
3125                     container = container->containingBlock();
3126                 }
3127             }
3128             return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight));
3129         }
3130         case MinContent:
3131         case MaxContent:
3132         case FitContent:
3133         case FillAvailable:
3134             return adjustContentBoxLogicalHeightForBoxSizing(computeIntrinsicLogicalContentHeightUsing(logicalHeight, intrinsicLogicalHeight(), borderAndPaddingLogicalHeight()));
3135         default:
3136             return intrinsicLogicalHeight();
3137     }
3138 }
3139
3140 LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const
3141 {
3142     return constrainLogicalHeightByMinMax(availableLogicalHeightUsing(style().logicalHeight(), heightType), std::nullopt);
3143 }
3144
3145 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const
3146 {
3147     // We need to stop here, since we don't want to increase the height of the table
3148     // artificially.  We're going to rely on this cell getting expanded to some new
3149     // height, and then when we lay out again we'll use the calculation below.
3150     if (isTableCell() && (h.isAuto() || h.isPercentOrCalculated())) {
3151         if (hasOverrideContentLogicalHeight())
3152             return overrideContentLogicalHeight();
3153         return logicalHeight() - borderAndPaddingLogicalHeight();
3154     }
3155
3156     if (isFlexItem()) {
3157         auto& flexBox = downcast<RenderFlexibleBox>(*parent());
3158         auto stretchedHeight = flexBox.childLogicalHeightForPercentageResolution(*this);
3159         if (stretchedHeight)
3160             return stretchedHeight.value();
3161     }
3162
3163     if (h.isPercentOrCalculated() && isOutOfFlowPositioned() && !isRenderFragmentedFlow()) {
3164         // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3165         LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(*containingBlock());
3166         return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight));
3167     }
3168
3169     if (std::optional<LayoutUnit> heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(MainOrPreferredSize, h, std::nullopt))
3170         return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
3171
3172     // FIXME: Check logicalTop/logicalBottom here to correctly handle vertical writing-mode.
3173     // https://bugs.webkit.org/show_bug.cgi?id=46500
3174     if (is<RenderBlock>(*this) && isOutOfFlowPositioned() && style().height().isAuto() && !(style().top().isAuto() || style().bottom().isAuto())) {
3175         RenderBlock& block = const_cast<RenderBlock&>(downcast<RenderBlock>(*this));
3176         auto computedValues = block.computeLogicalHeight(block.logicalHeight(), 0);
3177         return computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3178     }
3179
3180     // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3181     LayoutUnit availableHeight = containingBlockLogicalHeightForContent(heightType);
3182     if (heightType == ExcludeMarginBorderPadding) {
3183         // FIXME: Margin collapsing hasn't happened yet, so this incorrectly removes collapsed margins.
3184         availableHeight -= marginBefore() + marginAfter() + borderAndPaddingLogicalHeight();
3185     }
3186     return availableHeight;
3187 }
3188
3189 void RenderBox::computeBlockDirectionMargins(const RenderBlock& containingBlock, LayoutUnit& marginBefore, LayoutUnit& marginAfter) const
3190 {
3191     if (isTableCell()) {
3192         // FIXME: Not right if we allow cells to have different directionality than the table.  If we do allow this, though,
3193         // we may just do it with an extra anonymous block inside the cell.
3194         marginBefore = 0;
3195         marginAfter = 0;
3196         return;
3197     }
3198
3199     // Margins are calculated with respect to the logical width of
3200     // the containing block (8.3)
3201     LayoutUnit cw = containingBlockLogicalWidthForContent();
3202     const RenderStyle& containingBlockStyle = containingBlock.style();
3203     marginBefore = minimumValueForLength(style().marginBeforeUsing(&containingBlockStyle), cw);
3204     marginAfter = minimumValueForLength(style().marginAfterUsing(&containingBlockStyle), cw);
3205 }
3206
3207 void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock& containingBlock)
3208 {
3209     LayoutUnit marginBefore;
3210     LayoutUnit marginAfter;
3211     computeBlockDirectionMargins(containingBlock, marginBefore, marginAfter);
3212     containingBlock.setMarginBeforeForChild(*this, marginBefore);
3213     containingBlock.setMarginAfterForChild(*this, marginAfter);
3214 }
3215
3216 LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject& containingBlock, RenderFragmentContainer* fragment, bool checkForPerpendicularWritingMode) const
3217 {
3218     if (checkForPerpendicularWritingMode && containingBlock.isHorizontalWritingMode() != isHorizontalWritingMode())
3219         return containingBlockLogicalHeightForPositioned(containingBlock, false);
3220
3221     if (hasOverrideContainingBlockContentLogicalWidth()) {
3222         if (auto overrideLogicalWidth = overrideContainingBlockContentLogicalWidth())
3223             return overrideLogicalWidth.value();
3224     }
3225
3226     if (is<RenderBox>(containingBlock)) {
3227         bool isFixedPosition = isFixedPositioned();
3228
3229         RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
3230         if (!fragmentedFlow) {
3231             if (isFixedPosition && is<RenderView>(containingBlock))
3232                 return downcast<RenderView>(containingBlock).clientLogicalWidthForFixedPosition();
3233
3234             return downcast<RenderBox>(containingBlock).clientLogicalWidth();
3235         }
3236
3237         if (!is<RenderBlock>(containingBlock))
3238             return downcast<RenderBox>(containingBlock).clientLogicalWidth();
3239
3240         const RenderBlock& cb = downcast<RenderBlock>(containingBlock);
3241         RenderBoxFragmentInfo* boxInfo = nullptr;
3242         if (!fragment) {
3243             if (is<RenderFragmentedFlow>(containingBlock) && !checkForPerpendicularWritingMode)
3244                 return downcast<RenderFragmentedFlow>(containingBlock).contentLogicalWidthOfFirstFragment();
3245             if (isWritingModeRoot()) {
3246                 LayoutUnit cbPageOffset = cb.offsetFromLogicalTopOfFirstPage();
3247                 RenderFragmentContainer* cbFragment = cb.fragmentAtBlockOffset(cbPageOffset);
3248                 if (cbFragment)
3249                     boxInfo = cb.renderBoxFragmentInfo(cbFragment);
3250             }
3251         } else if (fragmentedFlow->isHorizontalWritingMode() == containingBlock.isHorizontalWritingMode()) {
3252             RenderFragmentContainer* containingBlockFragment = cb.clampToStartAndEndFragments(fragment);
3253             boxInfo = cb.renderBoxFragmentInfo(containingBlockFragment);
3254         }
3255         return (boxInfo) ? std::max<LayoutUnit>(0, cb.clientLogicalWidth() - (cb.logicalWidth() - boxInfo->logicalWidth())) : cb.clientLogicalWidth();
3256     }
3257
3258     ASSERT(containingBlock.isInFlowPositioned());
3259
3260     const auto& flow = downcast<RenderInline>(containingBlock);
3261     InlineFlowBox* first = flow.firstLineBox();
3262     InlineFlowBox* last = flow.lastLineBox();
3263
3264     // If the containing block is empty, return a width of 0.
3265     if (!first || !last)
3266         return 0;
3267
3268     LayoutUnit fromLeft;
3269     LayoutUnit fromRight;
3270     if (containingBlock.style().isLeftToRightDirection()) {
3271         fromLeft = first->logicalLeft() + first->borderLogicalLeft();
3272         fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
3273     } else {
3274         fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
3275         fromLeft = last->logicalLeft() + last->borderLogicalLeft();
3276     }
3277
3278     return std::max<LayoutUnit>(0, fromRight - fromLeft);
3279 }
3280
3281 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject& containingBlock, bool checkForPerpendicularWritingMode) const
3282 {
3283     if (checkForPerpendicularWritingMode && containingBlock.isHorizontalWritingMode() != isHorizontalWritingMode())
3284         return containingBlockLogicalWidthForPositioned(containingBlock, nullptr, false);
3285
3286     if (hasOverrideContainingBlockContentLogicalHeight()) {
3287         if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight())
3288             return overrideLogicalHeight.value();
3289     }
3290
3291     if (containingBlock.isBox()) {
3292         bool isFixedPosition = isFixedPositioned();
3293
3294         if (isFixedPosition && is<RenderView>(containingBlock))
3295             return downcast<RenderView>(containingBlock).clientLogicalHeightForFixedPosition();
3296
3297         const RenderBlock& cb = is<RenderBlock>(containingBlock) ? downcast<RenderBlock>(containingBlock) : *containingBlock.containingBlock();
3298         LayoutUnit result = cb.clientLogicalHeight();
3299         RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
3300         if (fragmentedFlow && is<RenderFragmentedFlow>(containingBlock) && fragmentedFlow->isHorizontalWritingMode() == containingBlock.isHorizontalWritingMode())
3301             return downcast<RenderFragmentedFlow>(containingBlock).contentLogicalHeightOfFirstFragment();
3302         return result;
3303     }
3304         
3305     ASSERT(containingBlock.isInFlowPositioned());
3306
3307     const auto& flow = downcast<RenderInline>(containingBlock);
3308     InlineFlowBox* first = flow.firstLineBox();
3309     InlineFlowBox* last = flow.lastLineBox();
3310
3311     // If the containing block is empty, return a height of 0.
3312     if (!first || !last)
3313         return 0;
3314
3315     LayoutUnit heightResult;
3316     LayoutRect boundingBox = flow.linesBoundingBox();
3317     if (containingBlock.isHorizontalWritingMode())
3318         heightResult = boundingBox.height();
3319     else
3320         heightResult = boundingBox.width();
3321     heightResult -= (containingBlock.borderBefore() + containingBlock.borderAfter());
3322     return heightResult;
3323 }
3324
3325 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject& containerBlock, LayoutUnit containerLogicalWidth, RenderFragmentContainer* fragment)
3326 {
3327     if (!logicalLeft.isAuto() || !logicalRight.isAuto())
3328         return;
3329
3330     RenderObject* parent = child->parent();
3331     TextDirection parentDirection = parent->style().direction();
3332
3333     // This method is using enclosingBox() which is wrong for absolutely
3334     // positioned grid items, as they rely on the grid area. So for grid items if
3335     // both "left" and "right" properties are "auto", we can consider that one of
3336     // them (depending on the direction) is simply "0".
3337     if (parent->isRenderGrid() && parent == child->containingBlock()) {
3338         if (parentDirection == TextDirection::LTR)
3339             logicalLeft.setValue(Fixed, 0);
3340         else
3341             logicalRight.setValue(Fixed, 0);
3342         return;
3343     }
3344
3345     // FIXME: The static distance computation has not been patched for mixed writing modes yet.
3346     if (parentDirection == TextDirection::LTR) {
3347         LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock.borderLogicalLeft();
3348         for (auto* current = parent; current && current != &containerBlock; current = current->container()) {
3349             if (!is<RenderBox>(*current))
3350                 continue;
3351             const auto& renderBox = downcast<RenderBox>(*current);
3352             staticPosition += renderBox.logicalLeft();
3353             if (renderBox.isInFlowPositioned())
3354                 staticPosition += renderBox.isHorizontalWritingMode() ? renderBox.offsetForInFlowPosition().width() : renderBox.offsetForInFlowPosition().height();
3355             if (fragment && is<RenderBlock>(*current)) {
3356                 const RenderBlock& currentBlock = downcast<RenderBlock>(*current);
3357                 fragment = currentBlock.clampToStartAndEndFragments(fragment);
3358                 RenderBoxFragmentInfo* boxInfo = currentBlock.renderBoxFragmentInfo(fragment);
3359                 if (boxInfo)
3360                     staticPosition += boxInfo->logicalLeft();
3361             }
3362         }
3363         logicalLeft.setValue(Fixed, staticPosition);
3364     } else {
3365         LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock.borderLogicalLeft();
3366         auto& enclosingBox = parent->enclosingBox();
3367         if (&enclosingBox != &containerBlock && containerBlock.isDescendantOf(&enclosingBox)) {
3368             logicalRight.setValue(Fixed, staticPosition);
3369             return;
3370         }
3371
3372         staticPosition -= enclosingBox.logicalWidth();
3373         for (const RenderElement* current = &enclosingBox; current; current = current->container()) {
3374             if (!is<RenderBox>(*current))
3375                 continue;
3376
3377             if (current != &containerBlock) {
3378                 auto& renderBox = downcast<RenderBox>(*current);
3379                 staticPosition -= renderBox.logicalLeft();
3380                 if (renderBox.isInFlowPositioned())
3381                     staticPosition -= renderBox.isHorizontalWritingMode() ? renderBox.offsetForInFlowPosition().width() : renderBox.offsetForInFlowPosition().height();
3382             }
3383             if (fragment && is<RenderBlock>(*current)) {
3384                 auto& currentBlock = downcast<RenderBlock>(*current);
3385                 fragment = currentBlock.clampToStartAndEndFragments(fragment);
3386                 RenderBoxFragmentInfo* boxInfo = currentBlock.renderBoxFragmentInfo(fragment);
3387                 if (boxInfo) {
3388                     if (current != &containerBlock)
3389                         staticPosition -= currentBlock.logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth());
3390                     if (current == &enclosingBox)
3391                         staticPosition += enclosingBox.logicalWidth() - boxInfo->logicalWidth();
3392                 }
3393             }
3394             if (current == &containerBlock)
3395                 break;
3396         }
3397         logicalRight.setValue(Fixed, staticPosition);
3398     }
3399 }
3400
3401 void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues, RenderFragmentContainer* fragment) const
3402 {
3403     if (isReplaced()) {
3404         // FIXME: Positioned replaced elements inside a flow thread are not working properly
3405         // with variable width fragments (see https://bugs.webkit.org/show_bug.cgi?id=69896 ).
3406         computePositionedLogicalWidthReplaced(computedValues);
3407         return;
3408     }
3409
3410     // QUESTIONS
3411     // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
3412     // the type 'static' in determining whether to calculate the static distance?
3413     // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
3414
3415     // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
3416     // than or less than the computed width().  Be careful of box-sizing and
3417     // percentage issues.
3418
3419     // The following is based off of the W3C Working Draft from April 11, 2006 of
3420     // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
3421     // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
3422     // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
3423     // correspond to text from the spec)
3424
3425
3426     // We don't use containingBlock(), since we may be positioned by an enclosing
3427     // relative positioned inline.
3428     const RenderBoxModelObject& containerBlock = downcast<RenderBoxModelObject>(*container());
3429     
3430     const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, fragment);
3431
3432     // Use the container block's direction except when calculating the static distance
3433     // This conforms with the reference results for abspos-replaced-width-margin-000.htm
3434     // of the CSS 2.1 test suite
3435     TextDirection containerDirection = containerBlock.style().direction();
3436
3437     bool isHorizontal = isHorizontalWritingMode();
3438     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
3439     const Length marginLogicalLeft = isHorizontal ? style().marginLeft() : style().marginTop();
3440     const Length marginLogicalRight = isHorizontal ? style().marginRight() : style().marginBottom();
3441
3442     Length logicalLeftLength = style().logicalLeft();
3443     Length logicalRightLength = style().logicalRight();
3444
3445     /*---------------------------------------------------------------------------*\
3446      * For the purposes of this section and the next, the term "static position"
3447      * (of an element) refers, roughly, to the position an element would have had
3448      * in the normal flow. More precisely:
3449      *
3450      * * The static position for 'left' is the distance from the left edge of the
3451      *   containing block to the left margin edge of a hypothetical box that would
3452      *   have been the first box of the element if its 'position' property had
3453      *   been 'static' and 'float' had been 'none'. The value is negative if the
3454      *   hypothetical box is to the left of the containing block.
3455      * * The static position for 'right' is the distance from the right edge of the
3456      *   containing block to the right margin edge of the same hypothetical box as
3457      *   above. The value is positive if the hypothetical box is to the left of the
3458      *   containing block's edge.
3459      *
3460      * But rather than actually calculating the dimensions of that hypothetical box,
3461      * user agents are free to make a guess at its probable position.
3462      *
3463      * For the purposes of calculating the static position, the containing block of
3464      * fixed positioned elements is the initial containing block instead of the
3465      * viewport, and all scrollable boxes should be assumed to be scrolled to their
3466      * origin.
3467     \*---------------------------------------------------------------------------*/
3468
3469     // see FIXME 1
3470     // Calculate the static distance if needed.
3471     computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth, fragment);
3472     
3473     // Calculate constraint equation values for 'width' case.
3474     computePositionedLogicalWidthUsing(MainOrPreferredSize, style().logicalWidth(), containerBlock, containerDirection,
3475                                        containerLogicalWidth, bordersPlusPadding,
3476                                        logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3477                                        computedValues);
3478
3479     // Calculate constraint equation values for 'max-width' case.
3480     if (!style().logicalMaxWidth().isUndefined()) {
3481         LogicalExtentComputedValues maxValues;
3482
3483         computePositionedLogicalWidthUsing(MaxSize, style().logicalMaxWidth(), containerBlock, containerDirection,
3484                                            containerLogicalWidth, bordersPlusPadding,
3485                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3486                                            maxValues);
3487
3488         if (computedValues.m_extent > maxValues.m_extent) {
3489             computedValues.m_extent = maxValues.m_extent;
3490             computedValues.m_position = maxValues.m_position;
3491             computedValues.m_margins.m_start = maxValues.m_margins.m_start;
3492             computedValues.m_margins.m_end = maxValues.m_margins.m_end;
3493         }
3494     }
3495
3496     // Calculate constraint equation values for 'min-width' case.
3497     if (!style().logicalMinWidth().isZero() || style().logicalMinWidth().isIntrinsic()) {
3498         LogicalExtentComputedValues minValues;
3499
3500         computePositionedLogicalWidthUsing(MinSize, style().logicalMinWidth(), containerBlock, containerDirection,
3501                                            containerLogicalWidth, bordersPlusPadding,
3502                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3503                                            minValues);
3504
3505         if (computedValues.m_extent < minValues.m_extent) {
3506             computedValues.m_extent = minValues.m_extent;
3507             computedValues.m_position = minValues.m_position;
3508             computedValues.m_margins.m_start = minValues.m_margins.m_start;
3509             computedValues.m_margins.m_end = minValues.m_margins.m_end;
3510         }
3511     }
3512
3513     computedValues.m_extent += bordersPlusPadding;
3514     if (is<RenderBox>(containerBlock)) {
3515         auto& containingBox = downcast<RenderBox>(containerBlock);
3516         if (containingBox.shouldPlaceBlockDirectionScrollbarOnLeft())
3517             computedValues.m_position += containingBox.verticalScrollbarWidth();
3518     }
3519     
3520     // Adjust logicalLeft if we need to for the flipped version of our writing mode in fragments.
3521     // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock.
3522     RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
3523     if (fragmentedFlow && !fragment && isWritingModeRoot() && isHorizontalWritingMode() == containerBlock.isHorizontalWritingMode() && is<RenderBlock>(containerBlock)) {
3524         ASSERT(containerBlock.canHaveBoxInfoInFragment());
3525         LayoutUnit logicalLeftPos = computedValues.m_position;
3526         const RenderBlock& renderBlock = downcast<RenderBlock>(containerBlock);
3527         LayoutUnit cbPageOffset = renderBlock.offsetFromLogicalTopOfFirstPage();
3528         RenderFragmentContainer* cbFragment = renderBlock.fragmentAtBlockOffset(cbPageOffset);
3529         if (cbFragment) {
3530             RenderBoxFragmentInfo* boxInfo = renderBlock.renderBoxFragmentInfo(cbFragment);
3531             if (boxInfo) {
3532                 logicalLeftPos += boxInfo->logicalLeft();
3533                 computedValues.m_position = logicalLeftPos;
3534             }
3535         }
3536     }
3537 }
3538
3539 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject& containerBlock, LayoutUnit containerLogicalWidth)
3540 {
3541     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3542     // along this axis, then we need to flip the coordinate.  This can only happen if the containing block is both a flipped mode and perpendicular to us.
3543     if (containerBlock.isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock.style().isFlippedBlocksWritingMode()) {
3544         logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
3545         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock.borderRight() : containerBlock.borderBottom());
3546     } else
3547         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock.borderLeft() : containerBlock.borderTop());
3548 }
3549
3550 void RenderBox::computePositionedLogicalWidthUsing(SizeType widthType, Length logicalWidth, const RenderBoxModelObject& containerBlock, TextDirection containerDirection,
3551                                                    LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
3552                                                    Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight,
3553                                                    LogicalExtentComputedValues& computedValues) const
3554 {
3555     ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto());
3556     if (widthType == MinSize && logicalWidth.isAuto())
3557         logicalWidth = Length(0, Fixed);
3558     else if (logicalWidth.isIntrinsic())
3559         logicalWidth = Length(computeIntrinsicLogicalWidthUsing(logicalWidth, containerLogicalWidth, bordersPlusPadding) - bordersPlusPadding, Fixed);
3560
3561     // 'left' and 'right' cannot both be 'auto' because one would of been
3562     // converted to the static position already
3563     ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
3564
3565     LayoutUnit logicalLeftValue = 0;
3566
3567     const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, nullptr, false);
3568
3569     bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
3570     bool logicalLeftIsAuto = logicalLeft.isAuto();
3571     bool logicalRightIsAuto = logicalRight.isAuto();
3572     LayoutUnit& marginLogicalLeftValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
3573     LayoutUnit& marginLogicalRightValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
3574
3575     if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3576         /*-----------------------------------------------------------------------*\
3577          * If none of the three is 'auto': If both 'margin-left' and 'margin-
3578          * right' are 'auto', solve the equation under the extra constraint that
3579          * the two margins get equal values, unless this would make them negative,
3580          * in which case when direction of the containing block is 'ltr' ('rtl'),
3581          * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
3582          * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
3583          * solve the equation for that value. If the values are over-constrained,
3584          * ignore the value for 'left' (in case the 'direction' property of the
3585          * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
3586          * and solve for that value.
3587         \*-----------------------------------------------------------------------*/
3588         // NOTE:  It is not necessary to solve for 'right' in the over constrained
3589         // case because the value is not used for any further calculations.
3590
3591         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3592         computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3593
3594         const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth) + bordersPlusPadding);
3595
3596         // Margins are now the only unknown
3597         if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
3598             // Both margins auto, solve for equality
3599             if (availableSpace >= 0) {
3600                 marginLogicalLeftValue = availableSpace / 2; // split the difference
3601                 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
3602             } else {
3603                 // Use the containing block's direction rather than the parent block's
3604                 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3605                 if (containerDirection == TextDirection::LTR) {
3606                     marginLogicalLeftValue = 0;
3607                     marginLogicalRightValue = availableSpace; // will be negative
3608                 } else {
3609                     marginLogicalLeftValue = availableSpace; // will be negative
3610                     marginLogicalRightValue = 0;
3611                 }
3612             }
3613         } else if (marginLogicalLeft.isAuto()) {
3614             // Solve for left margin
3615             marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3616             marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
3617         } else if (marginLogicalRight.isAuto()) {
3618             // Solve for right margin
3619             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3620             marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
3621         } else {
3622             // Over-constrained, solve for left if direction is RTL
3623             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3624             marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3625
3626             // Use the containing block's direction rather than the parent block's
3627             // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3628             if (containerDirection == TextDirection::RTL)
3629                 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
3630         }
3631     } else {
3632         /*--------------------------------------------------------------------*\
3633          * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
3634          * to 0, and pick the one of the following six rules that applies.
3635          *
3636          * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
3637          *    width is shrink-to-fit. Then solve for 'left'
3638          *
3639          *              OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3640          * ------------------------------------------------------------------
3641          * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
3642          *    the 'direction' property of the containing block is 'ltr' set
3643          *    'left' to the static position, otherwise set 'right' to the
3644          *    static position. Then solve for 'left' (if 'direction is 'rtl')
3645          *    or 'right' (if 'direction' is 'ltr').
3646          * ------------------------------------------------------------------
3647          *
3648          * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
3649          *    width is shrink-to-fit . Then solve for 'right'
3650          * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
3651          *    for 'left'
3652          * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
3653          *    for 'width'
3654          * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
3655          *    for 'right'
3656          *
3657          * Calculation of the shrink-to-fit width is similar to calculating the
3658          * width of a table cell using the automatic table layout algorithm.
3659          * Roughly: calculate the preferred width by formatting the content
3660          * without breaking lines other than where explicit line breaks occur,
3661          * and also calculate the preferred minimum width, e.g., by trying all
3662          * possible line breaks. CSS 2.1 does not define the exact algorithm.
3663          * Thirdly, calculate the available width: this is found by solving
3664          * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
3665          * to 0.
3666          *
3667          * Then the shrink-to-fit width is:
3668          * min(max(preferred minimum width, available width), preferred width).
3669         \*--------------------------------------------------------------------*/
3670         // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
3671         // because the value is not used for any further calculations.
3672
3673         // Calculate margins, 'auto' margins are ignored.
3674         marginLogicalLeftValue = minimumValueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3675         marginLogicalRightValue = minimumValueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3676
3677         const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
3678
3679         // FIXME: Is there a faster way to find the correct case?
3680         // Use rule/case that applies.
3681         if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3682             // RULE 1: (use shrink-to-fit for width, and solve of left)
3683             LayoutUnit logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3684
3685             // FIXME: would it be better to have shrink-to-fit in one step?
3686             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3687             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3688             LayoutUnit availableWidth = availableSpace - logicalRightValue;
3689             computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3690             logicalLeftValue = availableSpace - (computedValues.m_extent + logicalRightValue);
3691         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
3692             // RULE 3: (use shrink-to-fit for width, and no need solve of right)
3693             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3694
3695             // FIXME: would it be better to have shrink-to-fit in one step?
3696             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3697             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3698             LayoutUnit availableWidth = availableSpace - logicalLeftValue;
3699             computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3700         } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3701             // RULE 4: (solve for left)
3702             computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3703             logicalLeftValue = availableSpace - (computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth));
3704         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3705             // RULE 5: (solve for width)
3706             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3707             computedValues.m_extent = availableSpace - (logicalLeftValue + valueForLength(logicalRight, containerLogicalWidth));
3708         } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
3709             // RULE 6: (no need solve for right)
3710             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3711             computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3712         }
3713     }
3714
3715     // Use computed values to calculate the horizontal position.
3716
3717     // FIXME: This hack is needed to calculate the  logical left position for a 'rtl' relatively
3718     // positioned, inline because right now, it is using the logical left position
3719     // of the first line box when really it should use the last line box.  When
3720     // this is fixed elsewhere, this block should be removed.
3721     if (is<RenderInline>(containerBlock) && !containerBlock.style().isLeftToRightDirection()) {
3722         const auto& flow = downcast<RenderInline>(containerBlock);
3723         InlineFlowBox* firstLine = flow.firstLineBox();
3724         InlineFlowBox* lastLine = flow.lastLineBox();
3725         if (firstLine && lastLine && firstLine != lastLine) {
3726             computedValues.m_position = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
3727             return;
3728         }
3729     }
3730
3731     computedValues.m_position = logicalLeftValue + marginLogicalLeftValue;
3732     computeLogicalLeftPositionedOffset(computedValues.m_position, this, computedValues.m_extent, containerBlock, containerLogicalWidth);
3733 }
3734
3735 static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject& containerBlock)
3736 {
3737     if (!logicalTop.isAuto() || !logicalBottom.isAuto())
3738         return;
3739     
3740     // FIXME: The static distance computation has not been patched for mixed writing modes.
3741     LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock.borderBefore();
3742     for (RenderElement* container = child->parent(); container && container != &containerBlock; container = container->container()) {
3743         if (!is<RenderBox>(*container))
3744             continue;
3745         const auto& renderBox = downcast<RenderBox>(*container);
3746         if (!is<RenderTableRow>(renderBox))
3747             staticLogicalTop += renderBox.logicalTop();
3748         if (renderBox.isInFlowPositioned())
3749             staticLogicalTop += renderBox.isHorizontalWritingMode() ? renderBox.offsetForInFlowPosition().height() : renderBox.offsetForInFlowPosition().width();
3750     }
3751     logicalTop.setValue(Fixed, staticLogicalTop);
3752 }
3753
3754 void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& computedValues) const
3755 {
3756     if (isReplaced()) {
3757         computePositionedLogicalHeightReplaced(computedValues);
3758         return;
3759     }
3760
3761     // The following is based off of the W3C Working Draft from April 11, 2006 of
3762     // CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
3763     // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
3764     // (block-style-comments in this function and in computePositionedLogicalHeightUsing()
3765     // correspond to text from the spec)
3766
3767
3768     // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
3769     const RenderBoxModelObject& containerBlock = downcast<RenderBoxModelObject>(*container());
3770
3771     const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
3772
3773     const RenderStyle& styleToUse = style();
3774     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
3775     const Length marginBefore = styleToUse.marginBefore();
3776     const Length marginAfter = styleToUse.marginAfter();
3777     Length logicalTopLength = styleToUse.logicalTop();
3778     Length logicalBottomLength = styleToUse.logicalBottom();
3779
3780     /*---------------------------------------------------------------------------*\
3781      * For the purposes of this section and the next, the term "static position"
3782      * (of an element) refers, roughly, to the position an element would have had
3783      * in the normal flow. More precisely, the static position for 'top' is the
3784      * distance from the top edge of the containing block to the top margin edge
3785      * of a hypothetical box that would have been the first box of the element if
3786      * its 'position' property had been 'static' and 'float' had been 'none'. The
3787      * value is negative if the hypothetical box is above the containing block.
3788      *
3789      * But rather than actually calculating the dimensions of that hypothetical
3790      * box, user agents are free to make a guess at its probable position.
3791      *
3792      * For the purposes of calculating the static position, the containing block
3793      * of fixed positioned elements is the initial containing block instead of
3794      * the viewport.
3795     \*---------------------------------------------------------------------------*/