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