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