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