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