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