Update flexbox to Blink's tip of tree
[WebKit-https.git] / Source / WebCore / rendering / RenderBox.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
5  *           (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
6  * Copyright (C) 2005-2010, 2015 Apple Inc. All rights reserved.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public License
19  * along with this library; see the file COPYING.LIB.  If not, write to
20  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  *
23  */
24
25 #include "config.h"
26 #include "RenderBox.h"
27
28 #include "CSSFontSelector.h"
29 #include "ControlStates.h"
30 #include "Document.h"
31 #include "EventHandler.h"
32 #include "FloatQuad.h"
33 #include "FloatRoundedRect.h"
34 #include "Frame.h"
35 #include "FrameView.h"
36 #include "GraphicsContext.h"
37 #include "HTMLBodyElement.h"
38 #include "HTMLButtonElement.h"
39 #include "HTMLFrameOwnerElement.h"
40 #include "HTMLHtmlElement.h"
41 #include "HTMLImageElement.h"
42 #include "HTMLInputElement.h"
43 #include "HTMLLegendElement.h"
44 #include "HTMLNames.h"
45 #include "HTMLSelectElement.h"
46 #include "HTMLTextAreaElement.h"
47 #include "HitTestResult.h"
48 #include "InlineElementBox.h"
49 #include "MainFrame.h"
50 #include "Page.h"
51 #include "PaintInfo.h"
52 #include "RenderBoxRegionInfo.h"
53 #include "RenderChildIterator.h"
54 #include "RenderDeprecatedFlexibleBox.h"
55 #include "RenderFlexibleBox.h"
56 #include "RenderGeometryMap.h"
57 #include "RenderInline.h"
58 #include "RenderIterator.h"
59 #include "RenderLayer.h"
60 #include "RenderLayerCompositor.h"
61 #include "RenderNamedFlowFragment.h"
62 #include "RenderNamedFlowThread.h"
63 #include "RenderTableCell.h"
64 #include "RenderTheme.h"
65 #include "RenderView.h"
66 #include "ScrollAnimator.h"
67 #include "ScrollbarTheme.h"
68 #include "StyleScrollSnapPoints.h"
69 #include "TransformState.h"
70 #include "htmlediting.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
1340 #if PLATFORM(IOS)
1341     // Workaround for <rdar://problem/6209763>. Force the painting bounds of checkboxes and radio controls to be square.
1342     if (style().appearance() == CheckboxPart || style().appearance() == RadioPart) {
1343         int width = std::min(paintRect.width(), paintRect.height());
1344         int height = width;
1345         paintRect = IntRect(paintRect.x(), paintRect.y() + (this->height() - height) / 2, width, height); // Vertically center the checkbox, like on desktop
1346     }
1347 #endif
1348     BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context());
1349
1350     // FIXME: Should eventually give the theme control over whether the box shadow should paint, since controls could have
1351     // custom shadows of their own.
1352     if (!boxShadowShouldBeAppliedToBackground(paintRect.location(), bleedAvoidance))
1353         paintBoxShadow(paintInfo, paintRect, style(), Normal);
1354
1355     GraphicsContextStateSaver stateSaver(paintInfo.context(), false);
1356     if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
1357         // To avoid the background color bleeding out behind the border, we'll render background and border
1358         // into a transparency layer, and then clip that in one go (which requires setting up the clip before
1359         // beginning the layer).
1360         stateSaver.save();
1361         paintInfo.context().clipRoundedRect(style().getRoundedBorderFor(paintRect).pixelSnappedRoundedRectForPainting(document().deviceScaleFactor()));
1362         paintInfo.context().beginTransparencyLayer(1);
1363     }
1364
1365     // If we have a native theme appearance, paint that before painting our background.
1366     // The theme will tell us whether or not we should also paint the CSS background.
1367     bool borderOrBackgroundPaintingIsNeeded = true;
1368     if (style().hasAppearance()) {
1369         ControlStates* controlStates = controlStatesForRenderer(*this);
1370         borderOrBackgroundPaintingIsNeeded = theme().paint(*this, *controlStates, paintInfo, paintRect);
1371         if (controlStates->needsRepaint())
1372             view().scheduleLazyRepaint(*this);
1373     }
1374
1375     if (borderOrBackgroundPaintingIsNeeded) {
1376         if (bleedAvoidance == BackgroundBleedBackgroundOverBorder)
1377             paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1378
1379         paintBackground(paintInfo, paintRect, bleedAvoidance);
1380
1381         if (style().hasAppearance())
1382             theme().paintDecorations(*this, paintInfo, paintRect);
1383     }
1384     paintBoxShadow(paintInfo, paintRect, style(), Inset);
1385
1386     // The theme will tell us whether or not we should also paint the CSS border.
1387     if (bleedAvoidance != BackgroundBleedBackgroundOverBorder && (!style().hasAppearance() || (borderOrBackgroundPaintingIsNeeded && theme().paintBorderOnly(*this, paintInfo, paintRect))) && style().hasVisibleBorderDecoration())
1388         paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1389
1390     if (bleedAvoidance == BackgroundBleedUseTransparencyLayer)
1391         paintInfo.context().endTransparencyLayer();
1392 }
1393
1394 bool RenderBox::paintsOwnBackground() const
1395 {
1396     if (isBody()) {
1397         // The <body> only paints its background if the root element has defined a background independent of the body,
1398         // or if the <body>'s parent is not the document element's renderer (e.g. inside SVG foreignObject).
1399         auto documentElementRenderer = document().documentElement()->renderer();
1400         return !documentElementRenderer
1401             || documentElementRenderer->hasBackground()
1402             || (documentElementRenderer != parent());
1403     }
1404     
1405     return true;
1406 }
1407
1408 void RenderBox::paintBackground(const PaintInfo& paintInfo, const LayoutRect& paintRect, BackgroundBleedAvoidance bleedAvoidance)
1409 {
1410     if (isDocumentElementRenderer()) {
1411         paintRootBoxFillLayers(paintInfo);
1412         return;
1413     }
1414
1415     if (!paintsOwnBackground())
1416         return;
1417
1418     if (backgroundIsKnownToBeObscured(paintRect.location()) && !boxShadowShouldBeAppliedToBackground(paintRect.location(), bleedAvoidance))
1419         return;
1420
1421     paintFillLayers(paintInfo, style().visitedDependentColor(CSSPropertyBackgroundColor), style().backgroundLayers(), paintRect, bleedAvoidance);
1422 }
1423
1424 bool RenderBox::getBackgroundPaintedExtent(const LayoutPoint& paintOffset, LayoutRect& paintedExtent) const
1425 {
1426     ASSERT(hasBackground());
1427     LayoutRect backgroundRect = snappedIntRect(borderBoxRect());
1428
1429     Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1430     if (backgroundColor.isVisible()) {
1431         paintedExtent = backgroundRect;
1432         return true;
1433     }
1434
1435     auto& layers = style().backgroundLayers();
1436     if (!layers.image() || layers.next()) {
1437         paintedExtent =  backgroundRect;
1438         return true;
1439     }
1440
1441     auto geometry = calculateBackgroundImageGeometry(nullptr, layers, paintOffset, backgroundRect);
1442     paintedExtent = geometry.destRect();
1443     return !geometry.hasNonLocalGeometry();
1444 }
1445
1446 bool RenderBox::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
1447 {
1448     if (!paintsOwnBackground())
1449         return false;
1450
1451     Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1452     if (!backgroundColor.isOpaque())
1453         return false;
1454
1455     // If the element has appearance, it might be painted by theme.
1456     // We cannot be sure if theme paints the background opaque.
1457     // In this case it is safe to not assume opaqueness.
1458     // FIXME: May be ask theme if it paints opaque.
1459     if (style().hasAppearance())
1460         return false;
1461     // FIXME: Check the opaqueness of background images.
1462
1463     if (hasClip() || hasClipPath())
1464         return false;
1465
1466     // FIXME: Use rounded rect if border radius is present.
1467     if (style().hasBorderRadius())
1468         return false;
1469     
1470     // FIXME: The background color clip is defined by the last layer.
1471     if (style().backgroundLayers().next())
1472         return false;
1473     LayoutRect backgroundRect;
1474     switch (style().backgroundClip()) {
1475     case BorderFillBox:
1476         backgroundRect = borderBoxRect();
1477         break;
1478     case PaddingFillBox:
1479         backgroundRect = paddingBoxRect();
1480         break;
1481     case ContentFillBox:
1482         backgroundRect = contentBoxRect();
1483         break;
1484     default:
1485         break;
1486     }
1487     return backgroundRect.contains(localRect);
1488 }
1489
1490 static bool isCandidateForOpaquenessTest(const RenderBox& childBox)
1491 {
1492     const RenderStyle& childStyle = childBox.style();
1493     if (childStyle.position() != StaticPosition && childBox.containingBlock() != childBox.parent())
1494         return false;
1495     if (childStyle.visibility() != VISIBLE)
1496         return false;
1497     if (childStyle.shapeOutside())
1498         return false;
1499     if (!childBox.width() || !childBox.height())
1500         return false;
1501     if (RenderLayer* childLayer = childBox.layer()) {
1502         if (childLayer->isComposited())
1503             return false;
1504         // FIXME: Deal with z-index.
1505         if (!childStyle.hasAutoZIndex())
1506             return false;
1507         if (childLayer->hasTransform() || childLayer->isTransparent() || childLayer->hasFilter())
1508             return false;
1509         if (!childBox.scrollPosition().isZero())
1510             return false;
1511     }
1512     return true;
1513 }
1514
1515 bool RenderBox::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const
1516 {
1517     if (!maxDepthToTest)
1518         return false;
1519     for (auto& childBox : childrenOfType<RenderBox>(*this)) {
1520         if (!isCandidateForOpaquenessTest(childBox))
1521             continue;
1522         LayoutPoint childLocation = childBox.location();
1523         if (childBox.isRelPositioned())
1524             childLocation.move(childBox.relativePositionOffset());
1525         LayoutRect childLocalRect = localRect;
1526         childLocalRect.moveBy(-childLocation);
1527         if (childLocalRect.y() < 0 || childLocalRect.x() < 0) {
1528             // If there is unobscured area above/left of a static positioned box then the rect is probably not covered.
1529             if (childBox.style().position() == StaticPosition)
1530                 return false;
1531             continue;
1532         }
1533         if (childLocalRect.maxY() > childBox.height() || childLocalRect.maxX() > childBox.width())
1534             continue;
1535         if (childBox.backgroundIsKnownToBeOpaqueInRect(childLocalRect))
1536             return true;
1537         if (childBox.foregroundIsKnownToBeOpaqueInRect(childLocalRect, maxDepthToTest - 1))
1538             return true;
1539     }
1540     return false;
1541 }
1542
1543 bool RenderBox::computeBackgroundIsKnownToBeObscured(const LayoutPoint& paintOffset)
1544 {
1545     // Test to see if the children trivially obscure the background.
1546     // FIXME: This test can be much more comprehensive.
1547     if (!hasBackground())
1548         return false;
1549     // Table and root background painting is special.
1550     if (isTable() || isDocumentElementRenderer())
1551         return false;
1552
1553     LayoutRect backgroundRect;
1554     if (!getBackgroundPaintedExtent(paintOffset, backgroundRect))
1555         return false;
1556     return foregroundIsKnownToBeOpaqueInRect(backgroundRect, backgroundObscurationTestMaxDepth);
1557 }
1558
1559 bool RenderBox::backgroundHasOpaqueTopLayer() const
1560 {
1561     auto& fillLayer = style().backgroundLayers();
1562     if (fillLayer.clip() != BorderFillBox)
1563         return false;
1564
1565     // Clipped with local scrolling
1566     if (hasOverflowClip() && fillLayer.attachment() == LocalBackgroundAttachment)
1567         return false;
1568
1569     if (fillLayer.hasOpaqueImage(*this) && fillLayer.hasRepeatXY() && fillLayer.image()->canRender(this, style().effectiveZoom()))
1570         return true;
1571
1572     // If there is only one layer and no image, check whether the background color is opaque.
1573     if (!fillLayer.next() && !fillLayer.hasImage()) {
1574         Color bgColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1575         if (bgColor.isOpaque())
1576             return true;
1577     }
1578
1579     return false;
1580 }
1581
1582 void RenderBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1583 {
1584     if (!paintInfo.shouldPaintWithinRoot(*this) || style().visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask || paintInfo.context().paintingDisabled())
1585         return;
1586
1587     LayoutRect paintRect = LayoutRect(paintOffset, size());
1588     paintMaskImages(paintInfo, paintRect);
1589 }
1590
1591 void RenderBox::paintClippingMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1592 {
1593     if (!paintInfo.shouldPaintWithinRoot(*this) || style().visibility() != VISIBLE || paintInfo.phase != PaintPhaseClippingMask || paintInfo.context().paintingDisabled())
1594         return;
1595
1596     LayoutRect paintRect = LayoutRect(paintOffset, size());
1597     paintInfo.context().fillRect(snappedIntRect(paintRect), Color::black);
1598 }
1599
1600 void RenderBox::paintMaskImages(const PaintInfo& paintInfo, const LayoutRect& paintRect)
1601 {
1602     // Figure out if we need to push a transparency layer to render our mask.
1603     bool pushTransparencyLayer = false;
1604     bool compositedMask = hasLayer() && layer()->hasCompositedMask();
1605     bool flattenCompositingLayers = view().frameView().paintBehavior() & PaintBehaviorFlattenCompositingLayers;
1606     CompositeOperator compositeOp = CompositeSourceOver;
1607
1608     bool allMaskImagesLoaded = true;
1609     
1610     if (!compositedMask || flattenCompositingLayers) {
1611         pushTransparencyLayer = true;
1612
1613         // Don't render a masked element until all the mask images have loaded, to prevent a flash of unmasked content.
1614         if (auto* maskBoxImage = style().maskBoxImage().image())
1615             allMaskImagesLoaded &= maskBoxImage->isLoaded();
1616
1617         allMaskImagesLoaded &= style().maskLayers().imagesAreLoaded();
1618
1619         paintInfo.context().setCompositeOperation(CompositeDestinationIn);
1620         paintInfo.context().beginTransparencyLayer(1);
1621         compositeOp = CompositeSourceOver;
1622     }
1623
1624     if (allMaskImagesLoaded) {
1625         paintFillLayers(paintInfo, Color(), style().maskLayers(), paintRect, BackgroundBleedNone, compositeOp);
1626         paintNinePieceImage(paintInfo.context(), paintRect, style(), style().maskBoxImage(), compositeOp);
1627     }
1628     
1629     if (pushTransparencyLayer)
1630         paintInfo.context().endTransparencyLayer();
1631 }
1632
1633 LayoutRect RenderBox::maskClipRect(const LayoutPoint& paintOffset)
1634 {
1635     const NinePieceImage& maskBoxImage = style().maskBoxImage();
1636     if (maskBoxImage.image()) {
1637         LayoutRect borderImageRect = borderBoxRect();
1638         
1639         // Apply outsets to the border box.
1640         borderImageRect.expand(style().maskBoxImageOutsets());
1641         return borderImageRect;
1642     }
1643     
1644     LayoutRect result;
1645     LayoutRect borderBox = borderBoxRect();
1646     for (auto* maskLayer = &style().maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
1647         if (maskLayer->image()) {
1648             // Masks should never have fixed attachment, so it's OK for paintContainer to be null.
1649             result.unite(calculateBackgroundImageGeometry(nullptr, *maskLayer, paintOffset, borderBox).destRect());
1650         }
1651     }
1652     return result;
1653 }
1654
1655 void RenderBox::paintFillLayers(const PaintInfo& paintInfo, const Color& color, const FillLayer& fillLayer, const LayoutRect& rect,
1656     BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject)
1657 {
1658     Vector<const FillLayer*, 8> layers;
1659     bool shouldDrawBackgroundInSeparateBuffer = false;
1660
1661     for (auto* layer = &fillLayer; layer; layer = layer->next()) {
1662         layers.append(layer);
1663
1664         if (layer->blendMode() != BlendModeNormal)
1665             shouldDrawBackgroundInSeparateBuffer = true;
1666
1667         // Stop traversal when an opaque layer is encountered.
1668         // FIXME: It would be possible for the following occlusion culling test to be more aggressive
1669         // on layers with no repeat by testing whether the image covers the layout rect.
1670         // Testing that here would imply duplicating a lot of calculations that are currently done in
1671         // RenderBoxModelObject::paintFillLayerExtended. A more efficient solution might be to move
1672         // the layer recursion into paintFillLayerExtended, or to compute the layer geometry here
1673         // and pass it down.
1674
1675         // The clipOccludesNextLayers condition must be evaluated first to avoid short-circuiting.
1676         if (layer->clipOccludesNextLayers(layer == &fillLayer) && layer->hasOpaqueImage(*this) && layer->image()->canRender(this, style().effectiveZoom()) && layer->hasRepeatXY() && layer->blendMode() == BlendModeNormal)
1677             break;
1678     }
1679
1680     auto& context = paintInfo.context();
1681     auto baseBgColorUsage = BaseBackgroundColorUse;
1682
1683     if (shouldDrawBackgroundInSeparateBuffer) {
1684         paintFillLayer(paintInfo, color, *layers.last(), rect, bleedAvoidance, op, backgroundObject, BaseBackgroundColorOnly);
1685         baseBgColorUsage = BaseBackgroundColorSkip;
1686         context.beginTransparencyLayer(1);
1687     }
1688
1689     auto topLayer = layers.rend();
1690     for (auto it = layers.rbegin(); it != topLayer; ++it)
1691         paintFillLayer(paintInfo, color, **it, rect, bleedAvoidance, op, backgroundObject, baseBgColorUsage);
1692
1693     if (shouldDrawBackgroundInSeparateBuffer)
1694         context.endTransparencyLayer();
1695 }
1696
1697 void RenderBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer& fillLayer, const LayoutRect& rect,
1698     BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject, BaseBackgroundColorUsage baseBgColorUsage)
1699 {
1700     paintFillLayerExtended(paintInfo, c, fillLayer, rect, bleedAvoidance, nullptr, LayoutSize(), op, backgroundObject, baseBgColorUsage);
1701 }
1702
1703 static bool layersUseImage(WrappedImagePtr image, const FillLayer& layers)
1704 {
1705     for (auto* layer = &layers; layer; layer = layer->next()) {
1706         if (layer->image() && image == layer->image()->data())
1707             return true;
1708     }
1709     return false;
1710 }
1711
1712 void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
1713 {
1714     if (!parent())
1715         return;
1716
1717     if ((style().borderImage().image() && style().borderImage().image()->data() == image) ||
1718         (style().maskBoxImage().image() && style().maskBoxImage().image()->data() == image)) {
1719         repaint();
1720         return;
1721     }
1722
1723     ShapeValue* shapeOutsideValue = style().shapeOutside();
1724     if (!view().frameView().isInRenderTreeLayout() && isFloating() && shapeOutsideValue && shapeOutsideValue->image() && shapeOutsideValue->image()->data() == image) {
1725         ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
1726         markShapeOutsideDependentsForLayout();
1727     }
1728
1729     bool didFullRepaint = repaintLayerRectsForImage(image, style().backgroundLayers(), true);
1730     if (!didFullRepaint)
1731         repaintLayerRectsForImage(image, style().maskLayers(), false);
1732
1733     if (!isComposited())
1734         return;
1735
1736     if (layer()->hasCompositedMask() && layersUseImage(image, style().maskLayers()))
1737         layer()->contentChanged(MaskImageChanged);
1738     if (layersUseImage(image, style().backgroundLayers()))
1739         layer()->contentChanged(BackgroundImageChanged);
1740 }
1741
1742 bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer& layers, bool drawingBackground)
1743 {
1744     LayoutRect rendererRect;
1745     RenderBox* layerRenderer = nullptr;
1746
1747     for (auto* layer = &layers; layer; layer = layer->next()) {
1748         if (layer->image() && image == layer->image()->data() && layer->image()->canRender(this, style().effectiveZoom())) {
1749             // Now that we know this image is being used, compute the renderer and the rect if we haven't already.
1750             bool drawingRootBackground = drawingBackground && (isDocumentElementRenderer() || (isBody() && !document().documentElement()->renderer()->hasBackground()));
1751             if (!layerRenderer) {
1752                 if (drawingRootBackground) {
1753                     layerRenderer = &view();
1754
1755                     LayoutUnit rw = downcast<RenderView>(*layerRenderer).frameView().contentsWidth();
1756                     LayoutUnit rh = downcast<RenderView>(*layerRenderer).frameView().contentsHeight();
1757
1758                     rendererRect = LayoutRect(-layerRenderer->marginLeft(),
1759                         -layerRenderer->marginTop(),
1760                         std::max(layerRenderer->width() + layerRenderer->horizontalMarginExtent() + layerRenderer->borderLeft() + layerRenderer->borderRight(), rw),
1761                         std::max(layerRenderer->height() + layerRenderer->verticalMarginExtent() + layerRenderer->borderTop() + layerRenderer->borderBottom(), rh));
1762                 } else {
1763                     layerRenderer = this;
1764                     rendererRect = borderBoxRect();
1765                 }
1766             }
1767             // FIXME: Figure out how to pass absolute position to calculateBackgroundImageGeometry (for pixel snapping)
1768             BackgroundImageGeometry geometry = layerRenderer->calculateBackgroundImageGeometry(nullptr, *layer, LayoutPoint(), rendererRect);
1769             if (geometry.hasNonLocalGeometry()) {
1770                 // Rather than incur the costs of computing the paintContainer for renderers with fixed backgrounds
1771                 // in order to get the right destRect, just repaint the entire renderer.
1772                 layerRenderer->repaint();
1773                 return true;
1774             }
1775             
1776             LayoutRect rectToRepaint = geometry.destRect();
1777             bool shouldClipToLayer = true;
1778
1779             // If this is the root background layer, we may need to extend the repaintRect if the FrameView has an
1780             // extendedBackground. We should only extend the rect if it is already extending the full width or height
1781             // of the rendererRect.
1782             if (drawingRootBackground && view().frameView().hasExtendedBackgroundRectForPainting()) {
1783                 shouldClipToLayer = false;
1784                 IntRect extendedBackgroundRect = view().frameView().extendedBackgroundRectForPainting();
1785                 if (rectToRepaint.width() == rendererRect.width()) {
1786                     rectToRepaint.move(extendedBackgroundRect.x(), 0);
1787                     rectToRepaint.setWidth(extendedBackgroundRect.width());
1788                 }
1789                 if (rectToRepaint.height() == rendererRect.height()) {
1790                     rectToRepaint.move(0, extendedBackgroundRect.y());
1791                     rectToRepaint.setHeight(extendedBackgroundRect.height());
1792                 }
1793             }
1794
1795             layerRenderer->repaintRectangle(rectToRepaint, shouldClipToLayer);
1796             if (geometry.destRect() == rendererRect)
1797                 return true;
1798         }
1799     }
1800     return false;
1801 }
1802
1803 bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset)
1804 {
1805     if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask)
1806         return false;
1807         
1808     bool isControlClip = hasControlClip();
1809     bool isOverflowClip = hasOverflowClip() && !layer()->isSelfPaintingLayer();
1810     
1811     if (!isControlClip && !isOverflowClip)
1812         return false;
1813     
1814     if (paintInfo.phase == PaintPhaseOutline)
1815         paintInfo.phase = PaintPhaseChildOutlines;
1816     else if (paintInfo.phase == PaintPhaseChildBlockBackground) {
1817         paintInfo.phase = PaintPhaseBlockBackground;
1818         paintObject(paintInfo, accumulatedOffset);
1819         paintInfo.phase = PaintPhaseChildBlockBackgrounds;
1820     }
1821     float deviceScaleFactor = document().deviceScaleFactor();
1822     FloatRect clipRect = snapRectToDevicePixels((isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset, currentRenderNamedFlowFragment(), IgnoreOverlayScrollbarSize, paintInfo.phase)), deviceScaleFactor);
1823     paintInfo.context().save();
1824     if (style().hasBorderRadius())
1825         paintInfo.context().clipRoundedRect(style().getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size())).pixelSnappedRoundedRectForPainting(deviceScaleFactor));
1826     paintInfo.context().clip(clipRect);
1827     return true;
1828 }
1829
1830 void RenderBox::popContentsClip(PaintInfo& paintInfo, PaintPhase originalPhase, const LayoutPoint& accumulatedOffset)
1831 {
1832     ASSERT(hasControlClip() || (hasOverflowClip() && !layer()->isSelfPaintingLayer()));
1833
1834     paintInfo.context().restore();
1835     if (originalPhase == PaintPhaseOutline) {
1836         paintInfo.phase = PaintPhaseSelfOutline;
1837         paintObject(paintInfo, accumulatedOffset);
1838         paintInfo.phase = originalPhase;
1839     } else if (originalPhase == PaintPhaseChildBlockBackground)
1840         paintInfo.phase = originalPhase;
1841 }
1842
1843 LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, RenderRegion* region, OverlayScrollbarSizeRelevancy relevancy, PaintPhase)
1844 {
1845     // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
1846     // here.
1847     LayoutRect clipRect = borderBoxRectInRegion(region);
1848     clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
1849     clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
1850
1851     // Subtract out scrollbars if we have them.
1852     if (layer()) {
1853         if (shouldPlaceBlockDirectionScrollbarOnLeft())
1854             clipRect.move(layer()->verticalScrollbarWidth(relevancy), 0);
1855         clipRect.contract(layer()->verticalScrollbarWidth(relevancy), layer()->horizontalScrollbarHeight(relevancy));
1856     }
1857
1858     return clipRect;
1859 }
1860
1861 LayoutRect RenderBox::clipRect(const LayoutPoint& location, RenderRegion* region)
1862 {
1863     LayoutRect borderBoxRect = borderBoxRectInRegion(region);
1864     LayoutRect clipRect = LayoutRect(borderBoxRect.location() + location, borderBoxRect.size());
1865
1866     if (!style().clipLeft().isAuto()) {
1867         LayoutUnit c = valueForLength(style().clipLeft(), borderBoxRect.width());
1868         clipRect.move(c, 0);
1869         clipRect.contract(c, 0);
1870     }
1871
1872     // We don't use the region-specific border box's width and height since clip offsets are (stupidly) specified
1873     // from the left and top edges. Therefore it's better to avoid constraining to smaller widths and heights.
1874
1875     if (!style().clipRight().isAuto())
1876         clipRect.contract(width() - valueForLength(style().clipRight(), width()), 0);
1877
1878     if (!style().clipTop().isAuto()) {
1879         LayoutUnit c = valueForLength(style().clipTop(), borderBoxRect.height());
1880         clipRect.move(0, c);
1881         clipRect.contract(0, c);
1882     }
1883
1884     if (!style().clipBottom().isAuto())
1885         clipRect.contract(0, height() - valueForLength(style().clipBottom(), height()));
1886
1887     return clipRect;
1888 }
1889
1890 LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock& cb, RenderRegion* region) const
1891 {    
1892     RenderRegion* containingBlockRegion = nullptr;
1893     LayoutUnit logicalTopPosition = logicalTop();
1894     if (region) {
1895         LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1896         logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
1897         containingBlockRegion = cb.clampToStartAndEndRegions(region);
1898     }
1899
1900     LayoutUnit logicalHeight = cb.logicalHeightForChild(*this);
1901     LayoutUnit result = cb.availableLogicalWidthForLineInRegion(logicalTopPosition, DoNotIndentText, containingBlockRegion, logicalHeight) - childMarginStart - childMarginEnd;
1902
1903     // We need to see if margins on either the start side or the end side can contain the floats in question. If they can,
1904     // then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line
1905     // offset at all, but can instead push all the way to the content edge of the containing block. In the case where the float
1906     // 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
1907     // "consumed" by the float. Negative margins aren't consumed by the float, and so we ignore them.
1908     if (childMarginStart > 0) {
1909         LayoutUnit startContentSide = cb.startOffsetForContent(containingBlockRegion);
1910         LayoutUnit startContentSideWithMargin = startContentSide + childMarginStart;
1911         LayoutUnit startOffset = cb.startOffsetForLineInRegion(logicalTopPosition, DoNotIndentText, containingBlockRegion, logicalHeight);
1912         if (startOffset > startContentSideWithMargin)
1913             result += childMarginStart;
1914         else
1915             result += startOffset - startContentSide;
1916     }
1917     
1918     if (childMarginEnd > 0) {
1919         LayoutUnit endContentSide = cb.endOffsetForContent(containingBlockRegion);
1920         LayoutUnit endContentSideWithMargin = endContentSide + childMarginEnd;
1921         LayoutUnit endOffset = cb.endOffsetForLineInRegion(logicalTopPosition, DoNotIndentText, containingBlockRegion, logicalHeight);
1922         if (endOffset > endContentSideWithMargin)
1923             result += childMarginEnd;
1924         else
1925             result += endOffset - endContentSide;
1926     }
1927
1928     return result;
1929 }
1930
1931 LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const
1932 {
1933     if (hasOverrideContainingBlockLogicalWidth()) {
1934         if (auto overrideLogicalWidth = overrideContainingBlockContentLogicalWidth())
1935             return overrideLogicalWidth.value();
1936     }
1937
1938     if (RenderBlock* cb = containingBlock())
1939         return cb->availableLogicalWidth();
1940     return LayoutUnit();
1941 }
1942
1943 LayoutUnit RenderBox::containingBlockLogicalHeightForContent(AvailableLogicalHeightType heightType) const
1944 {
1945     if (hasOverrideContainingBlockLogicalHeight()) {
1946         if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight())
1947             return overrideLogicalHeight.value();
1948     }
1949
1950     if (RenderBlock* cb = containingBlock())
1951         return cb->availableLogicalHeight(heightType);
1952     return LayoutUnit();
1953 }
1954
1955 LayoutUnit RenderBox::containingBlockLogicalWidthForContentInRegion(RenderRegion* region) const
1956 {
1957     if (!region)
1958         return containingBlockLogicalWidthForContent();
1959
1960     RenderBlock* cb = containingBlock();
1961     RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
1962     // FIXME: It's unclear if a region's content should use the containing block's override logical width.
1963     // If it should, the following line should call containingBlockLogicalWidthForContent.
1964     LayoutUnit result = cb->availableLogicalWidth();
1965     RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(containingBlockRegion);
1966     if (!boxInfo)
1967         return result;
1968     return std::max<LayoutUnit>(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
1969 }
1970
1971 LayoutUnit RenderBox::containingBlockAvailableLineWidthInRegion(RenderRegion* region) const
1972 {
1973     RenderBlock* cb = containingBlock();
1974     RenderRegion* containingBlockRegion = nullptr;
1975     LayoutUnit logicalTopPosition = logicalTop();
1976     if (region) {
1977         LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1978         logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
1979         containingBlockRegion = cb->clampToStartAndEndRegions(region);
1980     }
1981     return cb->availableLogicalWidthForLineInRegion(logicalTopPosition, DoNotIndentText, containingBlockRegion, availableLogicalHeight(IncludeMarginBorderPadding));
1982 }
1983
1984 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
1985 {
1986     if (hasOverrideContainingBlockLogicalHeight()) {
1987         if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight())
1988             return overrideLogicalHeight.value();
1989     }
1990
1991     RenderBlock* cb = containingBlock();
1992     if (cb->hasOverrideLogicalContentHeight())
1993         return cb->overrideLogicalContentHeight();
1994
1995     const RenderStyle& containingBlockStyle = cb->style();
1996     Length logicalHeightLength = containingBlockStyle.logicalHeight();
1997
1998     // FIXME: For now just support fixed heights.  Eventually should support percentage heights as well.
1999     if (!logicalHeightLength.isFixed()) {
2000         LayoutUnit fillFallbackExtent = containingBlockStyle.isHorizontalWritingMode() ? view().frameView().visibleHeight() : view().frameView().visibleWidth();
2001         LayoutUnit fillAvailableExtent = containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding);
2002         view().addPercentHeightDescendant(const_cast<RenderBox&>(*this));
2003         // 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.
2004         return std::min(fillAvailableExtent, fillFallbackExtent);
2005     }
2006
2007     // Use the content box logical height as specified by the style.
2008     return cb->adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(logicalHeightLength.value()));
2009 }
2010
2011 void RenderBox::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
2012 {
2013     if (repaintContainer == this)
2014         return;
2015
2016     if (view().layoutStateEnabled() && !repaintContainer) {
2017         LayoutState* layoutState = view().layoutState();
2018         LayoutSize offset = layoutState->m_paintOffset + locationOffset();
2019         if (style().hasInFlowPosition() && layer())
2020             offset += layer()->offsetForInFlowPosition();
2021         transformState.move(offset);
2022         return;
2023     }
2024
2025     bool containerSkipped;
2026     RenderElement* container = this->container(repaintContainer, containerSkipped);
2027     if (!container)
2028         return;
2029
2030     bool isFixedPos = style().position() == FixedPosition;
2031     // If this box has a transform, it acts as a fixed position container for fixed descendants,
2032     // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
2033     if (hasTransform() && !isFixedPos)
2034         mode &= ~IsFixed;
2035     else if (isFixedPos)
2036         mode |= IsFixed;
2037
2038     if (wasFixed)
2039         *wasFixed = mode & IsFixed;
2040     
2041     LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint(transformState.mappedPoint()));
2042     
2043     bool preserve3D = mode & UseTransforms && (container->style().preserves3D() || style().preserves3D());
2044     if (mode & UseTransforms && shouldUseTransformFromContainer(container)) {
2045         TransformationMatrix t;
2046         getTransformFromContainer(container, containerOffset, t);
2047         transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2048     } else
2049         transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2050
2051     if (containerSkipped) {
2052         // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe
2053         // to just subtract the delta between the repaintContainer and o.
2054         LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(*container);
2055         transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2056         return;
2057     }
2058
2059     mode &= ~ApplyContainerFlip;
2060
2061     // For fixed positioned elements inside out-of-flow named flows, we do not want to
2062     // map their position further to regions based on their coordinates inside the named flows.
2063     if (!container->isOutOfFlowRenderFlowThread() || !fixedPositionedWithNamedFlowContainingBlock())
2064         container->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed);
2065     else
2066         container->mapLocalToContainer(downcast<RenderLayerModelObject>(container), transformState, mode, wasFixed);
2067 }
2068
2069 const RenderObject* RenderBox::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
2070 {
2071     ASSERT(ancestorToStopAt != this);
2072
2073     bool ancestorSkipped;
2074     RenderElement* container = this->container(ancestorToStopAt, ancestorSkipped);
2075     if (!container)
2076         return nullptr;
2077
2078     bool isFixedPos = style().position() == FixedPosition;
2079     LayoutSize adjustmentForSkippedAncestor;
2080     if (ancestorSkipped) {
2081         // There can't be a transform between repaintContainer and container, because transforms create containers, so it should be safe
2082         // to just subtract the delta between the ancestor and container.
2083         adjustmentForSkippedAncestor = -ancestorToStopAt->offsetFromAncestorContainer(*container);
2084     }
2085
2086     bool offsetDependsOnPoint = false;
2087     LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint(), &offsetDependsOnPoint);
2088
2089     bool preserve3D = container->style().preserves3D() || style().preserves3D();
2090     if (shouldUseTransformFromContainer(container) && (geometryMap.mapCoordinatesFlags() & UseTransforms)) {
2091         TransformationMatrix t;
2092         getTransformFromContainer(container, containerOffset, t);
2093         t.translateRight(adjustmentForSkippedAncestor.width(), adjustmentForSkippedAncestor.height());
2094         
2095         geometryMap.push(this, t, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform());
2096     } else {
2097         containerOffset += adjustmentForSkippedAncestor;
2098         geometryMap.push(this, containerOffset, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform());
2099     }
2100     
2101     return ancestorSkipped ? ancestorToStopAt : container;
2102 }
2103
2104 void RenderBox::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
2105 {
2106     bool isFixedPos = style().position() == FixedPosition;
2107     if (hasTransform() && !isFixedPos) {
2108         // If this box has a transform, it acts as a fixed position container for fixed descendants,
2109         // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
2110         mode &= ~IsFixed;
2111     } else if (isFixedPos)
2112         mode |= IsFixed;
2113
2114     RenderBoxModelObject::mapAbsoluteToLocalPoint(mode, transformState);
2115 }
2116
2117 LayoutSize RenderBox::offsetFromContainer(RenderElement& renderer, const LayoutPoint&, bool* offsetDependsOnPoint) const
2118 {
2119     // A region "has" boxes inside it without being their container. 
2120     ASSERT(&renderer == container() || is<RenderRegion>(renderer));
2121
2122     LayoutSize offset;    
2123     if (isInFlowPositioned())
2124         offset += offsetForInFlowPosition();
2125
2126     if (!isInline() || isReplaced())
2127         offset += topLeftLocationOffset();
2128
2129     if (is<RenderBox>(renderer))
2130         offset -= toLayoutSize(downcast<RenderBox>(renderer).scrollPosition());
2131
2132     if (style().position() == AbsolutePosition && renderer.isInFlowPositioned() && is<RenderInline>(renderer))
2133         offset += downcast<RenderInline>(renderer).offsetForInFlowPositionedInline(this);
2134
2135     if (offsetDependsOnPoint)
2136         *offsetDependsOnPoint |= is<RenderFlowThread>(renderer);
2137
2138     return offset;
2139 }
2140
2141 std::unique_ptr<InlineElementBox> RenderBox::createInlineBox()
2142 {
2143     return std::make_unique<InlineElementBox>(*this);
2144 }
2145
2146 void RenderBox::dirtyLineBoxes(bool fullLayout)
2147 {
2148     if (!m_inlineBoxWrapper)
2149         return;
2150     
2151     if (fullLayout) {
2152         delete m_inlineBoxWrapper;
2153         m_inlineBoxWrapper = nullptr;
2154     } else
2155         m_inlineBoxWrapper->dirtyLineBoxes();
2156 }
2157
2158 void RenderBox::positionLineBox(InlineElementBox& box)
2159 {
2160     if (isOutOfFlowPositioned()) {
2161         // Cache the x position only if we were an INLINE type originally.
2162         bool wasInline = style().isOriginalDisplayInlineType();
2163         if (wasInline) {
2164             // The value is cached in the xPos of the box.  We only need this value if
2165             // our object was inline originally, since otherwise it would have ended up underneath
2166             // the inlines.
2167             RootInlineBox& rootBox = box.root();
2168             rootBox.blockFlow().setStaticInlinePositionForChild(*this, rootBox.lineTopWithLeading(), LayoutUnit::fromFloatRound(box.logicalLeft()));
2169             if (style().hasStaticInlinePosition(box.isHorizontal()))
2170                 setChildNeedsLayout(MarkOnlyThis); // Just mark the positioned object as needing layout, so it will update its position properly.
2171         } else {
2172             // Our object was a block originally, so we make our normal flow position be
2173             // just below the line box (as though all the inlines that came before us got
2174             // wrapped in an anonymous block, which is what would have happened had we been
2175             // in flow).  This value was cached in the y() of the box.
2176             layer()->setStaticBlockPosition(box.logicalTop());
2177             if (style().hasStaticBlockPosition(box.isHorizontal()))
2178                 setChildNeedsLayout(MarkOnlyThis); // Just mark the positioned object as needing layout, so it will update its position properly.
2179         }
2180         return;
2181     }
2182
2183     if (isReplaced()) {
2184         setLocation(LayoutPoint(box.topLeft()));
2185         setInlineBoxWrapper(&box);
2186     }
2187 }
2188
2189 void RenderBox::deleteLineBoxWrapper()
2190 {
2191     if (!m_inlineBoxWrapper)
2192         return;
2193     
2194     if (!documentBeingDestroyed())
2195         m_inlineBoxWrapper->removeFromParent();
2196     delete m_inlineBoxWrapper;
2197     m_inlineBoxWrapper = nullptr;
2198 }
2199
2200 LayoutRect RenderBox::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
2201 {
2202     if (style().visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
2203         return LayoutRect();
2204     LayoutRect r = visualOverflowRect();
2205     // FIXME: layoutDelta needs to be applied in parts before/after transforms and
2206     // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
2207     r.move(view().layoutDelta());
2208     return computeRectForRepaint(r, repaintContainer);
2209 }
2210
2211 bool RenderBox::shouldApplyClipAndScrollPositionForRepaint(const RenderLayerModelObject* repaintContainer) const
2212 {
2213 #if PLATFORM(IOS)
2214     if (!repaintContainer || repaintContainer != this)
2215         return true;
2216
2217     return !hasLayer() || !layer()->usesCompositedScrolling();
2218 #else
2219     UNUSED_PARAM(repaintContainer);
2220     return true;
2221 #endif
2222 }
2223
2224 LayoutRect RenderBox::computeRectForRepaint(const LayoutRect& rect, const RenderLayerModelObject* repaintContainer, RepaintContext context) const
2225 {
2226     // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
2227     // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
2228     // offset corner for the enclosing container).  This allows for a fully RL or BT document to repaint
2229     // properly even during layout, since the rect remains flipped all the way until the end.
2230     //
2231     // RenderView::computeRectForRepaint then converts the rect to physical coordinates.  We also convert to
2232     // physical when we hit a repaintContainer boundary.  Therefore the final rect returned is always in the
2233     // physical coordinate space of the repaintContainer.
2234     LayoutRect adjustedRect = rect;
2235     const RenderStyle& styleToUse = style();
2236     // LayoutState is only valid for root-relative, non-fixed position repainting
2237     if (view().layoutStateEnabled() && !repaintContainer && styleToUse.position() != FixedPosition) {
2238         LayoutState* layoutState = view().layoutState();
2239
2240         if (layer() && layer()->transform())
2241             adjustedRect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(adjustedRect), document().deviceScaleFactor()));
2242
2243         // We can't trust the bits on RenderObject, because this might be called while re-resolving style.
2244         if (styleToUse.hasInFlowPosition() && layer())
2245             adjustedRect.move(layer()->offsetForInFlowPosition());
2246
2247         adjustedRect.moveBy(location());
2248         adjustedRect.move(layoutState->m_paintOffset);
2249         if (layoutState->m_clipped)
2250             adjustedRect.intersect(layoutState->m_clipRect);
2251         return adjustedRect;
2252     }
2253
2254     if (hasReflection())
2255         adjustedRect.unite(reflectedRect(adjustedRect));
2256
2257     if (repaintContainer == this) {
2258         if (repaintContainer->style().isFlippedBlocksWritingMode())
2259             flipForWritingMode(adjustedRect);
2260         return adjustedRect;
2261     }
2262
2263     bool repaintContainerIsSkipped;
2264     auto* container = this->container(repaintContainer, repaintContainerIsSkipped);
2265     if (!container)
2266         return adjustedRect;
2267     
2268     // This code isn't necessary for in-flow RenderFlowThreads.
2269     // Don't add the location of the region in the flow thread for absolute positioned
2270     // elements because their absolute position already pushes them down through
2271     // the regions so adding this here and then adding the topLeft again would cause
2272     // us to add the height twice.
2273     // The same logic applies for elements flowed directly into the flow thread. Their topLeft member
2274     // will already contain the portion rect of the region.
2275     EPosition position = styleToUse.position();
2276     if (container->isOutOfFlowRenderFlowThread() && position != AbsolutePosition && containingBlock() != flowThreadContainingBlock()) {
2277         RenderRegion* firstRegion = nullptr;
2278         RenderRegion* lastRegion = nullptr;
2279         if (downcast<RenderFlowThread>(*container).getRegionRangeForBox(this, firstRegion, lastRegion))
2280             adjustedRect.moveBy(firstRegion->flowThreadPortionRect().location());
2281     }
2282
2283     if (isWritingModeRoot()) {
2284         if (!isOutOfFlowPositioned() || !context.m_dirtyRectIsFlipped) {
2285             flipForWritingMode(adjustedRect);
2286             context.m_dirtyRectIsFlipped = true;
2287         }
2288     }
2289
2290     LayoutSize locationOffset = this->locationOffset();
2291     // FIXME: This is needed as long as RenderWidget snaps to integral size/position.
2292     if (isRenderReplaced() && isWidget()) {
2293         LayoutSize flooredLocationOffset = toIntSize(flooredIntPoint(locationOffset));
2294         adjustedRect.expand(locationOffset - flooredLocationOffset);
2295         locationOffset = flooredLocationOffset;
2296     }
2297     LayoutPoint topLeft = adjustedRect.location();
2298     topLeft.move(locationOffset);
2299
2300     // We are now in our parent container's coordinate space. Apply our transform to obtain a bounding box
2301     // in the parent's coordinate space that encloses us.
2302     if (hasLayer() && layer()->transform()) {
2303         context.m_hasPositionFixedDescendant = position == FixedPosition;
2304         adjustedRect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(adjustedRect), document().deviceScaleFactor()));
2305         topLeft = adjustedRect.location();
2306         topLeft.move(locationOffset);
2307     } else if (position == FixedPosition)
2308         context.m_hasPositionFixedDescendant = true;
2309
2310     if (position == AbsolutePosition && container->isInFlowPositioned() && is<RenderInline>(*container))
2311         topLeft += downcast<RenderInline>(*container).offsetForInFlowPositionedInline(this);
2312     else if (styleToUse.hasInFlowPosition() && layer()) {
2313         // Apply the relative position offset when invalidating a rectangle.  The layer
2314         // is translated, but the render box isn't, so we need to do this to get the
2315         // right dirty rect.  Since this is called from RenderObject::setStyle, the relative position
2316         // flag on the RenderObject has been cleared, so use the one on the style().
2317         topLeft += layer()->offsetForInFlowPosition();
2318     }
2319
2320     // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
2321     // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
2322     adjustedRect.setLocation(topLeft);
2323     if (container->hasOverflowClip()) {
2324         RenderBox& containerBox = downcast<RenderBox>(*container);
2325         if (containerBox.shouldApplyClipAndScrollPositionForRepaint(repaintContainer)) {
2326             containerBox.applyCachedClipAndScrollPositionForRepaint(adjustedRect);
2327             if (adjustedRect.isEmpty())
2328                 return adjustedRect;
2329         }
2330     }
2331
2332     if (repaintContainerIsSkipped) {
2333         // If the repaintContainer is below container, then we need to map the rect into repaintContainer's coordinates.
2334         LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(*container);
2335         adjustedRect.move(-containerOffset);
2336         return adjustedRect;
2337     }
2338     return container->computeRectForRepaint(adjustedRect, repaintContainer, context);
2339 }
2340
2341 void RenderBox::repaintDuringLayoutIfMoved(const LayoutRect& oldRect)
2342 {
2343     if (oldRect.location() != m_frameRect.location()) {
2344         LayoutRect newRect = m_frameRect;
2345         // The child moved.  Invalidate the object's old and new positions.  We have to do this
2346         // since the object may not have gotten a layout.
2347         m_frameRect = oldRect;
2348         repaint();
2349         repaintOverhangingFloats(true);
2350         m_frameRect = newRect;
2351         repaint();
2352         repaintOverhangingFloats(true);
2353     }
2354 }
2355
2356 void RenderBox::repaintOverhangingFloats(bool)
2357 {
2358 }
2359
2360 void RenderBox::updateLogicalWidth()
2361 {
2362     LogicalExtentComputedValues computedValues;
2363     computeLogicalWidthInRegion(computedValues);
2364
2365     setLogicalWidth(computedValues.m_extent);
2366     setLogicalLeft(computedValues.m_position);
2367     setMarginStart(computedValues.m_margins.m_start);
2368     setMarginEnd(computedValues.m_margins.m_end);
2369 }
2370
2371 void RenderBox::computeLogicalWidthInRegion(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
2372 {
2373     computedValues.m_extent = logicalWidth();
2374     computedValues.m_position = logicalLeft();
2375     computedValues.m_margins.m_start = marginStart();
2376     computedValues.m_margins.m_end = marginEnd();
2377
2378     if (isOutOfFlowPositioned()) {
2379         // FIXME: This calculation is not patched for block-flow yet.
2380         // https://bugs.webkit.org/show_bug.cgi?id=46500
2381         computePositionedLogicalWidth(computedValues, region);
2382         return;
2383     }
2384
2385     // If layout is limited to a subtree, the subtree root's logical width does not change.
2386     if (element() && !view().frameView().layoutPending() && view().frameView().layoutRoot() == this)
2387         return;
2388
2389     // The parent box is flexing us, so it has increased or decreased our
2390     // width.  Use the width from the style context.
2391     // FIXME: Account for block-flow in flexible boxes.
2392     // https://bugs.webkit.org/show_bug.cgi?id=46418
2393     if (hasOverrideLogicalContentWidth() && (isRubyRun() || style().borderFit() == BorderFitLines || (parent()->isFlexibleBoxIncludingDeprecated()))) {
2394         computedValues.m_extent = overrideLogicalContentWidth() + borderAndPaddingLogicalWidth();
2395         return;
2396     }
2397
2398     // FIXME: Account for block-flow in flexible boxes.
2399     // https://bugs.webkit.org/show_bug.cgi?id=46418
2400     bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == VERTICAL);
2401     bool stretching = (parent()->style().boxAlign() == BSTRETCH);
2402     // FIXME: Stretching is the only reason why we don't want the box to be treated as a replaced element, so we could perhaps
2403     // refactor all this logic, not only for flex and grid since alignment is intended to be applied to any block.
2404     bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
2405     treatAsReplaced = treatAsReplaced && (!isGridItem() || !hasStretchedLogicalWidth());
2406
2407     const RenderStyle& styleToUse = style();
2408     Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse.logicalWidth();
2409
2410     RenderBlock& cb = *containingBlock();
2411     LayoutUnit containerLogicalWidth = std::max<LayoutUnit>(0, containingBlockLogicalWidthForContentInRegion(region));
2412     bool hasPerpendicularContainingBlock = cb.isHorizontalWritingMode() != isHorizontalWritingMode();
2413
2414     if (isInline() && !isInlineBlockOrInlineTable()) {
2415         // just calculate margins
2416         computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2417         computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2418         if (treatAsReplaced)
2419             computedValues.m_extent = std::max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
2420         return;
2421     }
2422
2423     LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
2424     if (hasPerpendicularContainingBlock)
2425         containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
2426
2427     // Width calculations
2428     if (treatAsReplaced) {
2429         computedValues.m_extent = logicalWidthLength.value() + borderAndPaddingLogicalWidth();
2430     } else if (parent()->isRenderGrid() && style().logicalWidth().isAuto() && style().logicalMinWidth().isAuto() && style().overflowX() == OVISIBLE && containerWidthInInlineDirection < minPreferredLogicalWidth()) {
2431         // TODO (lajava) Move this logic to the LayoutGrid class.
2432         // Implied minimum size of Grid items.
2433         computedValues.m_extent = constrainLogicalWidthInRegionByMinMax(minPreferredLogicalWidth(), containerWidthInInlineDirection, cb);
2434     } else {
2435         LayoutUnit preferredWidth = computeLogicalWidthInRegionUsing(MainOrPreferredSize, styleToUse.logicalWidth(), containerWidthInInlineDirection, cb, region);
2436         computedValues.m_extent = constrainLogicalWidthInRegionByMinMax(preferredWidth, containerWidthInInlineDirection, cb, region);
2437     }
2438
2439     // Margin calculations.
2440     if (hasPerpendicularContainingBlock || isFloating() || isInline()) {
2441         computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2442         computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2443     } else {
2444         LayoutUnit containerLogicalWidthForAutoMargins = containerLogicalWidth;
2445         if (avoidsFloats() && cb.containsFloats())
2446             containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInRegion(region);
2447         bool hasInvertedDirection = cb.style().isLeftToRightDirection() != style().isLeftToRightDirection();
2448         computeInlineDirectionMargins(cb, containerLogicalWidthForAutoMargins, computedValues.m_extent,
2449             hasInvertedDirection ? computedValues.m_margins.m_end : computedValues.m_margins.m_start,
2450             hasInvertedDirection ? computedValues.m_margins.m_start : computedValues.m_margins.m_end);
2451     }
2452     
2453     if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (computedValues.m_extent + computedValues.m_margins.m_start + computedValues.m_margins.m_end)
2454         && !isFloating() && !isInline() && !cb.isFlexibleBoxIncludingDeprecated()
2455 #if ENABLE(MATHML)
2456         // RenderMathMLBlocks take the size of their content so we must not adjust the margin to fill the container size.
2457         && !cb.isRenderMathMLBlock()
2458 #endif
2459         && !cb.isRenderGrid()
2460         ) {
2461         LayoutUnit newMargin = containerLogicalWidth - computedValues.m_extent - cb.marginStartForChild(*this);
2462         bool hasInvertedDirection = cb.style().isLeftToRightDirection() != style().isLeftToRightDirection();
2463         if (hasInvertedDirection)
2464             computedValues.m_margins.m_start = newMargin;
2465         else
2466             computedValues.m_margins.m_end = newMargin;
2467     }
2468 }
2469
2470 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth) const
2471 {
2472     LayoutUnit marginStart = 0;
2473     LayoutUnit marginEnd = 0;
2474     return fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2475 }
2476
2477 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2478 {
2479     marginStart = minimumValueForLength(style().marginStart(), availableLogicalWidth);
2480     marginEnd = minimumValueForLength(style().marginEnd(), availableLogicalWidth);
2481     return availableLogicalWidth - marginStart - marginEnd;
2482 }
2483
2484 LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(Length logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const
2485 {
2486     if (logicalWidthLength.type() == FillAvailable)
2487         return std::max(borderAndPadding, fillAvailableMeasure(availableLogicalWidth));
2488
2489     LayoutUnit minLogicalWidth = 0;
2490     LayoutUnit maxLogicalWidth = 0;
2491     computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
2492
2493     if (logicalWidthLength.type() == MinContent)
2494         return minLogicalWidth + borderAndPadding;
2495
2496     if (logicalWidthLength.type() == MaxContent)
2497         return maxLogicalWidth + borderAndPadding;
2498
2499     if (logicalWidthLength.type() == FitContent) {
2500         minLogicalWidth += borderAndPadding;
2501         maxLogicalWidth += borderAndPadding;
2502         return std::max(minLogicalWidth, std::min(maxLogicalWidth, fillAvailableMeasure(availableLogicalWidth)));
2503     }
2504
2505     ASSERT_NOT_REACHED();
2506     return 0;
2507 }
2508
2509 LayoutUnit RenderBox::computeLogicalWidthInRegionUsing(SizeType widthType, Length logicalWidth, LayoutUnit availableLogicalWidth,
2510     const RenderBlock& cb, RenderRegion* region) const
2511 {
2512     ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto());
2513     if (widthType == MinSize && logicalWidth.isAuto())
2514         return adjustBorderBoxLogicalWidthForBoxSizing(0);
2515
2516     if (!logicalWidth.isIntrinsicOrAuto()) {
2517         // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
2518         return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth));
2519     }
2520
2521     if (logicalWidth.isIntrinsic())
2522         return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth());
2523
2524     LayoutUnit marginStart = 0;
2525     LayoutUnit marginEnd = 0;
2526     LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2527
2528     if (shrinkToAvoidFloats() && cb.containsFloats())
2529         logicalWidthResult = std::min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, region));
2530
2531     if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(widthType))
2532         return std::max(minPreferredLogicalWidth(), std::min(maxPreferredLogicalWidth(), logicalWidthResult));
2533     return logicalWidthResult;
2534 }
2535
2536 bool RenderBox::columnFlexItemHasStretchAlignment() const
2537 {
2538     // auto margins mean we don't stretch. Note that this function will only be
2539     // used for widths, so we don't have to check marginBefore/marginAfter.
2540     const auto& parentStyle = parent()->style();
2541     ASSERT(parentStyle.isColumnFlexDirection());
2542     if (style().marginStart().isAuto() || style().marginEnd().isAuto())
2543         return false;
2544     return style().resolvedAlignSelf(isAnonymous() ? &parentStyle : nullptr, containingBlock()->selfAlignmentNormalBehavior()).position() == ItemPositionStretch;
2545 }
2546
2547 bool RenderBox::isStretchingColumnFlexItem() const
2548 {
2549     if (parent()->isDeprecatedFlexibleBox() && parent()->style().boxOrient() == VERTICAL && parent()->style().boxAlign() == BSTRETCH)
2550         return true;
2551
2552     // We don't stretch multiline flexboxes because they need to apply line spacing (align-content) first.
2553     if (parent()->isFlexibleBox() && parent()->style().flexWrap() == FlexNoWrap && parent()->style().isColumnFlexDirection() && columnFlexItemHasStretchAlignment())
2554         return true;
2555     return false;
2556 }
2557
2558 // FIXME: Can/Should we move this inside specific layout classes (flex. grid)? Can we refactor columnFlexItemHasStretchAlignment logic?
2559 bool RenderBox::hasStretchedLogicalWidth() const
2560 {
2561     auto& style = this->style();
2562     if (!style.logicalWidth().isAuto() || style.marginStart().isAuto() || style.marginEnd().isAuto())
2563         return false;
2564     RenderBlock* containingBlock = this->containingBlock();
2565     if (!containingBlock) {
2566         // We are evaluating align-self/justify-self, which default to 'normal' for the root element.
2567         // The 'normal' value behaves like 'start' except for Flexbox Items, which obviously should have a container.
2568         return false;
2569     }
2570     if (containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2571         return style.resolvedAlignSelf(&containingBlock->style(), ItemPositionStretch).position() == ItemPositionStretch;
2572     return style.resolvedJustifySelf(&containingBlock->style(), ItemPositionStretch).position() == ItemPositionStretch;
2573 }
2574
2575 bool RenderBox::sizesLogicalWidthToFitContent(SizeType widthType) const
2576 {
2577     // Anonymous inline blocks always fill the width of their containing block.
2578     if (isAnonymousInlineBlock())
2579         return false;
2580
2581     // Marquees in WinIE are like a mixture of blocks and inline-blocks.  They size as though they're blocks,
2582     // but they allow text to sit on the same line as the marquee.
2583     if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee()))
2584         return true;
2585
2586     if (isGridItem())
2587         return !hasStretchedLogicalWidth();
2588
2589     // This code may look a bit strange.  Basically width:intrinsic should clamp the size when testing both
2590     // min-width and width.  max-width is only clamped if it is also intrinsic.
2591     Length logicalWidth = (widthType == MaxSize) ? style().logicalMaxWidth() : style().logicalWidth();
2592     if (logicalWidth.type() == Intrinsic)
2593         return true;
2594
2595     // Children of a horizontal marquee do not fill the container by default.
2596     // FIXME: Need to deal with MAUTO value properly.  It could be vertical.
2597     // FIXME: Think about block-flow here.  Need to find out how marquee direction relates to
2598     // block-flow (as well as how marquee overflow should relate to block flow).
2599     // https://bugs.webkit.org/show_bug.cgi?id=46472
2600     if (parent()->isHTMLMarquee()) {
2601         EMarqueeDirection dir = parent()->style().marqueeDirection();
2602         if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
2603             return true;
2604     }
2605
2606 #if ENABLE(MATHML)
2607     // RenderMathMLBlocks take the size of their content, not of their container.
2608     if (parent()->isRenderMathMLBlock())
2609         return true;
2610 #endif
2611
2612     // Flexible box items should shrink wrap, so we lay them out at their intrinsic widths.
2613     // In the case of columns that have a stretch alignment, we layout at the stretched size
2614     // to avoid an extra layout when applying alignment.
2615     if (parent()->isFlexibleBox()) {
2616         // For multiline columns, we need to apply align-content first, so we can't stretch now.
2617         if (!parent()->style().isColumnFlexDirection() || parent()->style().flexWrap() != FlexNoWrap)
2618             return true;
2619         if (!columnFlexItemHasStretchAlignment())
2620             return true;
2621     }
2622
2623     // Flexible horizontal boxes lay out children at their intrinsic widths.  Also vertical boxes
2624     // that don't stretch their kids lay out their children at their intrinsic widths.
2625     // FIXME: Think about block-flow here.
2626     // https://bugs.webkit.org/show_bug.cgi?id=46473
2627     if (parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == HORIZONTAL || parent()->style().boxAlign() != BSTRETCH))
2628         return true;
2629
2630     // Button, input, select, textarea, and legend treat width value of 'auto' as 'intrinsic' unless it's in a
2631     // stretching column flexbox.
2632     // FIXME: Think about block-flow here.
2633     // https://bugs.webkit.org/show_bug.cgi?id=46473
2634     if (logicalWidth.type() == Auto && !isStretchingColumnFlexItem() && element() && (is<HTMLInputElement>(*element()) || is<HTMLSelectElement>(*element()) || is<HTMLButtonElement>(*element()) || is<HTMLTextAreaElement>(*element()) || is<HTMLLegendElement>(*element())))
2635         return true;
2636
2637     if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
2638         return true;
2639
2640     return false;
2641 }
2642
2643 void RenderBox::computeInlineDirectionMargins(const RenderBlock& containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2644 {
2645     
2646     const RenderStyle& containingBlockStyle = containingBlock.style();
2647     Length marginStartLength = style().marginStartUsing(&containingBlockStyle);
2648     Length marginEndLength = style().marginEndUsing(&containingBlockStyle);
2649
2650     if (isFloating() || isInline()) {
2651         // Inline blocks/tables and floats don't have their margins increased.
2652         marginStart = minimumValueForLength(marginStartLength, containerWidth);
2653         marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2654         return;
2655     }
2656
2657     if (containingBlock.isFlexibleBox()) {
2658         // We need to let flexbox handle the margin adjustment - otherwise, flexbox
2659         // will think we're wider than we actually are and calculate line sizes
2660         // wrong. See also http://dev.w3.org/csswg/css-flexbox/#auto-margins
2661         if (marginStartLength.isAuto())
2662             marginStartLength = Length(0, Fixed);
2663         if (marginEndLength.isAuto())
2664             marginEndLength = Length(0, Fixed);
2665     }
2666
2667     // Case One: The object is being centered in the containing block's available logical width.
2668     if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
2669         || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock.style().textAlign() == WEBKIT_CENTER)) {
2670         // Other browsers center the margin box for align=center elements so we match them here.
2671         LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth);
2672         LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth);
2673         LayoutUnit centeredMarginBoxStart = std::max<LayoutUnit>(0, (containerWidth - childWidth - marginStartWidth - marginEndWidth) / 2);
2674         marginStart = centeredMarginBoxStart + marginStartWidth;
2675         marginEnd = containerWidth - childWidth - marginStart + marginEndWidth;
2676         return;
2677     } 
2678     
2679     // Case Two: The object is being pushed to the start of the containing block's available logical width.
2680     if (marginEndLength.isAuto() && childWidth < containerWidth) {
2681         marginStart = valueForLength(marginStartLength, containerWidth);
2682         marginEnd = containerWidth - childWidth - marginStart;
2683         return;
2684     } 
2685     
2686     // Case Three: The object is being pushed to the end of the containing block's available logical width.
2687     bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_LEFT)
2688         || (containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_RIGHT));
2689     if ((marginStartLength.isAuto() || pushToEndFromTextAlign) && childWidth < containerWidth) {
2690         marginEnd = valueForLength(marginEndLength, containerWidth);
2691         marginStart = containerWidth - childWidth - marginEnd;
2692         return;
2693     } 
2694     
2695     // Case Four: Either no auto margins, or our width is >= the container width (css2.1, 10.3.3).  In that case
2696     // auto margins will just turn into 0.
2697     marginStart = minimumValueForLength(marginStartLength, containerWidth);
2698     marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2699 }
2700
2701 RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
2702 {
2703     // Make sure nobody is trying to call this with a null region.
2704     if (!region)
2705         return nullptr;
2706
2707     // If we have computed our width in this region already, it will be cached, and we can
2708     // just return it.
2709     RenderBoxRegionInfo* boxInfo = region->renderBoxRegionInfo(this);
2710     if (boxInfo && cacheFlag == CacheRenderBoxRegionInfo)
2711         return boxInfo;
2712
2713     // No cached value was found, so we have to compute our insets in this region.
2714     // FIXME: For now we limit this computation to normal RenderBlocks. Future patches will expand
2715     // support to cover all boxes.
2716     RenderFlowThread* flowThread = flowThreadContainingBlock();
2717     if (isRenderFlowThread() || !flowThread || !canHaveBoxInfoInRegion() || flowThread->style().writingMode() != style().writingMode())
2718         return nullptr;
2719
2720     LogicalExtentComputedValues computedValues;
2721     computeLogicalWidthInRegion(computedValues, region);
2722
2723     // Now determine the insets based off where this object is supposed to be positioned.
2724     RenderBlock& cb = *containingBlock();
2725     RenderRegion* clampedContainingBlockRegion = cb.clampToStartAndEndRegions(region);
2726     RenderBoxRegionInfo* containingBlockInfo = cb.renderBoxRegionInfo(clampedContainingBlockRegion);
2727     LayoutUnit containingBlockLogicalWidth = cb.logicalWidth();
2728     LayoutUnit containingBlockLogicalWidthInRegion = containingBlockInfo ? containingBlockInfo->logicalWidth() : containingBlockLogicalWidth;
2729     
2730     LayoutUnit marginStartInRegion = computedValues.m_margins.m_start;
2731     LayoutUnit startMarginDelta = marginStartInRegion - marginStart();
2732     LayoutUnit logicalWidthInRegion = computedValues.m_extent;
2733     LayoutUnit logicalLeftInRegion = computedValues.m_position;
2734     LayoutUnit widthDelta = logicalWidthInRegion - logicalWidth();
2735     LayoutUnit logicalLeftDelta = isOutOfFlowPositioned() ? logicalLeftInRegion - logicalLeft() : startMarginDelta;
2736     LayoutUnit logicalRightInRegion = containingBlockLogicalWidthInRegion - (logicalLeftInRegion + logicalWidthInRegion);
2737     LayoutUnit oldLogicalRight = containingBlockLogicalWidth - (logicalLeft() + logicalWidth());
2738     LayoutUnit logicalRightDelta = isOutOfFlowPositioned() ? logicalRightInRegion - oldLogicalRight : startMarginDelta;
2739
2740     LayoutUnit logicalLeftOffset = 0;
2741     
2742     if (!isOutOfFlowPositioned() && avoidsFloats() && cb.containsFloats()) {
2743         LayoutUnit startPositionDelta = cb.computeStartPositionDeltaForChildAvoidingFloats(*this, marginStartInRegion, region);
2744         if (cb.style().isLeftToRightDirection())
2745             logicalLeftDelta += startPositionDelta;
2746         else
2747             logicalRightDelta += startPositionDelta;
2748     }
2749
2750     if (cb.style().isLeftToRightDirection())
2751         logicalLeftOffset += logicalLeftDelta;
2752     else
2753         logicalLeftOffset -= (widthDelta + logicalRightDelta);
2754     
2755     LayoutUnit logicalRightOffset = logicalWidth() - (logicalLeftOffset + logicalWidthInRegion);
2756     bool isShifted = (containingBlockInfo && containingBlockInfo->isShifted())
2757             || (style().isLeftToRightDirection() && logicalLeftOffset)
2758             || (!style().isLeftToRightDirection() && logicalRightOffset);
2759
2760     // FIXME: Although it's unlikely, these boxes can go outside our bounds, and so we will need to incorporate them into overflow.
2761     if (cacheFlag == CacheRenderBoxRegionInfo)
2762         return region->setRenderBoxRegionInfo(this, logicalLeftOffset, logicalWidthInRegion, isShifted);
2763     return new RenderBoxRegionInfo(logicalLeftOffset, logicalWidthInRegion, isShifted);
2764 }
2765
2766 static bool shouldFlipBeforeAfterMargins(const RenderStyle& containingBlockStyle, const RenderStyle* childStyle)
2767 {
2768     ASSERT(containingBlockStyle.isHorizontalWritingMode() != childStyle->isHorizontalWritingMode());
2769     WritingMode childWritingMode = childStyle->writingMode();
2770     bool shouldFlip = false;
2771     switch (containingBlockStyle.writingMode()) {
2772     case TopToBottomWritingMode:
2773         shouldFlip = (childWritingMode == RightToLeftWritingMode);
2774         break;
2775     case BottomToTopWritingMode:
2776         shouldFlip = (childWritingMode == RightToLeftWritingMode);
2777         break;
2778     case RightToLeftWritingMode:
2779         shouldFlip = (childWritingMode == BottomToTopWritingMode);
2780         break;
2781     case LeftToRightWritingMode:
2782         shouldFlip = (childWritingMode == BottomToTopWritingMode);
2783         break;
2784     }
2785
2786     if (!containingBlockStyle.isLeftToRightDirection())
2787         shouldFlip = !shouldFlip;
2788
2789     return shouldFlip;
2790 }
2791
2792 void RenderBox::cacheIntrinsicContentLogicalHeightForFlexItem(LayoutUnit height) const
2793 {
2794     if (isFloatingOrOutOfFlowPositioned() || !parent() || !parent()->isFlexibleBox())
2795         return;
2796     downcast<RenderFlexibleBox>(parent())->setCachedChildIntrinsicContentLogicalHeight(*this, height);
2797 }
2798
2799 void RenderBox::updateLogicalHeight()
2800 {
2801     cacheIntrinsicContentLogicalHeightForFlexItem(contentLogicalHeight());
2802     auto computedValues = computeLogicalHeight(logicalHeight(), logicalTop());
2803     setLogicalHeight(computedValues.m_extent);
2804     setLogicalTop(computedValues.m_position);
2805     setMarginBefore(computedValues.m_margins.m_before);
2806     setMarginAfter(computedValues.m_margins.m_after);
2807 }
2808
2809 RenderBox::LogicalExtentComputedValues RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop) const
2810 {
2811     LogicalExtentComputedValues computedValues;
2812     computedValues.m_extent = logicalHeight;
2813     computedValues.m_position = logicalTop;
2814
2815     // Cell height is managed by the table and inline non-replaced elements do not support a height property.
2816     if (isTableCell() || (isInline() && !isReplaced()))
2817         return computedValues;
2818
2819     Length h;
2820     if (isOutOfFlowPositioned())
2821         computePositionedLogicalHeight(computedValues);
2822     else {
2823         RenderBlock& cb = *containingBlock();
2824         bool hasPerpendicularContainingBlock = cb.isHorizontalWritingMode() != isHorizontalWritingMode();
2825     
2826         if (!hasPerpendicularContainingBlock) {
2827             bool shouldFlipBeforeAfter = cb.style().writingMode() != style().writingMode();
2828             computeBlockDirectionMargins(cb,
2829                 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2830                 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2831         }
2832
2833         // For tables, calculate margins only.
2834         if (isTable()) {
2835             if (hasPerpendicularContainingBlock) {
2836                 bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb.style(), &style());
2837                 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), computedValues.m_extent,
2838                     shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2839                     shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2840             }
2841             return computedValues;
2842         }
2843
2844         // FIXME: Account for block-flow in flexible boxes.
2845         // https://bugs.webkit.org/show_bug.cgi?id=46418
2846         bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style().boxOrient() == HORIZONTAL;
2847         bool stretching = parent()->style().boxAlign() == BSTRETCH;
2848         bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
2849         bool checkMinMaxHeight = false;
2850
2851         // The parent box is flexing us, so it has increased or decreased our height.  We have to
2852         // grab our cached flexible height.
2853         // FIXME: Account for block-flow in flexible boxes.
2854         // https://bugs.webkit.org/show_bug.cgi?id=46418
2855         if (hasOverrideLogicalContentHeight() && (parent()->isFlexibleBoxIncludingDeprecated() || parent()->isRenderGrid())) {
2856             LayoutUnit contentHeight = overrideLogicalContentHeight();
2857             if (parent()->isRenderGrid() && style().logicalHeight().isAuto() && style().logicalMinHeight().isAuto() && style().overflowX() == OVISIBLE) {
2858                 LayoutUnit intrinsicContentHeight = computedValues.m_extent - borderAndPaddingLogicalHeight();
2859                 if (auto minContentHeight = computeContentLogicalHeight(MinSize, Length(MinContent), intrinsicContentHeight))
2860                     contentHeight = std::max(contentHeight, constrainContentBoxLogicalHeightByMinMax(minContentHeight.value(), intrinsicContentHeight));
2861             }
2862             h = Length(contentHeight, Fixed);
2863         } else if (treatAsReplaced)
2864             h = Length(computeReplacedLogicalHeight(), Fixed);
2865         else {
2866             h = style().logicalHeight();
2867             checkMinMaxHeight = true;
2868         }
2869
2870         // Block children of horizontal flexible boxes fill the height of the box.
2871         // FIXME: Account for block-flow in flexible boxes.
2872         // https://bugs.webkit.org/show_bug.cgi?id=46418
2873         if (h.isAuto() && is<RenderDeprecatedFlexibleBox>(*parent()) && parent()->style().boxOrient() == HORIZONTAL
2874                 && downcast<RenderDeprecatedFlexibleBox>(*parent()).isStretchingChildren()) {
2875             h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2876             checkMinMaxHeight = false;
2877         }
2878
2879         LayoutUnit heightResult;
2880         if (checkMinMaxHeight) {
2881             LayoutUnit intrinsicHeight = computedValues.m_extent - borderAndPaddingLogicalHeight();
2882             heightResult = computeLogicalHeightUsing(MainOrPreferredSize, style().logicalHeight(), intrinsicHeight).value_or(computedValues.m_extent);
2883             heightResult = constrainLogicalHeightByMinMax(heightResult, intrinsicHeight);
2884         } else {
2885             // The only times we don't check min/max height are when a fixed length has
2886             // been given as an override.  Just use that.  The value has already been adjusted
2887             // for box-sizing.
2888             ASSERT(h.isFixed());
2889             heightResult = h.value() + borderAndPaddingLogicalHeight();
2890         }
2891
2892         computedValues.m_extent = heightResult;
2893
2894         if (hasPerpendicularContainingBlock) {
2895             bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb.style(), &style());
2896             computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult,
2897                     shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2898                     shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2899         }
2900     }
2901
2902     // WinIE quirk: The <html> block always fills the entire canvas in quirks mode.  The <body> always fills the
2903     // <html> block in quirks mode.  Only apply this quirk if the block is normal flow and no height
2904     // is specified. When we're printing, we also need this quirk if the body or root has a percentage 
2905     // height since we don't set a height in RenderView when we're printing. So without this quirk, the 
2906     // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2907     bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercentOrCalculated()
2908         && (isDocumentElementRenderer() || (isBody() && document().documentElement()->renderer()->style().logicalHeight().isPercentOrCalculated())) && !isInline();
2909     if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2910         LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2911         LayoutUnit visibleHeight = view().pageOrViewLogicalHeight();
2912         if (isDocumentElementRenderer())
2913             computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - margins);
2914         else {
2915             LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2916             computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - marginsBordersPadding);
2917         }
2918     }
2919     return computedValues;
2920 }
2921
2922 LayoutUnit RenderBox::computeLogicalHeightWithoutLayout() const
2923 {
2924     // FIXME:: We should probably return something other than just
2925     // border + padding, but for now we have no good way to do anything else
2926     // without layout, so we just use that.
2927     LogicalExtentComputedValues computedValues = computeLogicalHeight(borderAndPaddingLogicalHeight(), LayoutUnit());
2928     return computedValues.m_extent;
2929 }
2930
2931 std::optional<LayoutUnit> RenderBox::computeLogicalHeightUsing(SizeType heightType, const Length& height, std::optional<LayoutUnit> intrinsicContentHeight) const
2932 {
2933     if (std::optional<LayoutUnit> logicalHeight = computeContentAndScrollbarLogicalHeightUsing(heightType, height, intrinsicContentHeight))
2934         return adjustBorderBoxLogicalHeightForBoxSizing(logicalHeight.value());
2935     return std::nullopt;
2936 }
2937
2938 std::optional<LayoutUnit> RenderBox::computeContentLogicalHeight(SizeType heightType, const Length& height, std::optional<LayoutUnit> intrinsicContentHeight) const
2939 {
2940     if (std::optional<LayoutUnit> heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(heightType, height, intrinsicContentHeight))
2941         return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2942     return std::nullopt;
2943 }
2944
2945 std::optional<LayoutUnit> RenderBox::computeIntrinsicLogicalContentHeightUsing(Length logicalHeightLength, std::optional<LayoutUnit> intrinsicContentHeight, LayoutUnit borderAndPadding) const
2946 {
2947     // FIXME: The CSS sizing spec is considering changing what min-content/max-content should resolve to.
2948     // If that happens, this code will have to change.
2949     if (logicalHeightLength.isMinContent() || logicalHeightLength.isMaxContent() || logicalHeightLength.isFitContent()) {
2950         if (!intrinsicContentHeight)
2951             return intrinsicContentHeight;
2952         if (style().boxSizing() == BORDER_BOX)
2953             return intrinsicContentHeight.value() + borderAndPaddingLogicalHeight();
2954         return intrinsicContentHeight;
2955     }
2956     if (logicalHeightLength.isFillAvailable())
2957         return containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding) - borderAndPadding;
2958     ASSERT_NOT_REACHED();
2959     return LayoutUnit(0);
2960 }
2961
2962 std::optional<LayoutUnit> RenderBox::computeContentAndScrollbarLogicalHeightUsing(SizeType heightType, const Length& height, std::optional<LayoutUnit> intrinsicContentHeight) const
2963 {
2964     if (height.isAuto())
2965         return heightType == MinSize ? std::optional<LayoutUnit>(0) : std::nullopt;
2966     // FIXME: The CSS sizing spec is considering changing what min-content/max-content should resolve to.
2967     // If that happens, this code will have to change.
2968     if (height.isIntrinsic())
2969         return computeIntrinsicLogicalContentHeightUsing(height, intrinsicContentHeight, borderAndPaddingLogicalHeight());
2970     if (height.isFixed())
2971         return LayoutUnit(height.value());
2972     if (height.isPercentOrCalculated())
2973         return computePercentageLogicalHeight(height);
2974     return std::nullopt;
2975 }
2976
2977 bool RenderBox::skipContainingBlockForPercentHeightCalculation(const RenderBox& containingBlock, bool isPerpendicularWritingMode) const
2978 {
2979     // Flow threads for multicol or paged overflow should be skipped. They are invisible to the DOM,
2980     // and percent heights of children should be resolved against the multicol or paged container.
2981     if (containingBlock.isInFlowRenderFlowThread() && !isPerpendicularWritingMode)
2982         return true;
2983
2984     // Render view is not considered auto height.
2985     if (is<RenderView>(containingBlock))
2986         return false;
2987
2988     // If the writing mode of the containing block is orthogonal to ours, it means
2989     // that we shouldn't skip anything, since we're going to resolve the
2990     // percentage height against a containing block *width*.
2991     if (isPerpendicularWritingMode)
2992         return false;
2993     
2994     // Anonymous blocks should not impede percentage resolution on a child.
2995     // Examples of such anonymous blocks are blocks wrapped around inlines that
2996     // have block siblings (from the CSS spec) and multicol flow threads (an
2997     // implementation detail). Another implementation detail, ruby runs, create
2998     // anonymous inline-blocks, so skip those too. All other types of anonymous
2999     // objects, such as table-cells and flexboxes, will be treated as if they were
3000     // non-anonymous.
3001     if (containingBlock.isAnonymous())
3002         return containingBlock.style().display() == BLOCK || containingBlock.style().display() == INLINE_BLOCK;
3003     
3004     // For quirks mode, we skip most auto-height containing blocks when computing
3005     // percentages.
3006     return document().inQuirksMode() && !containingBlock.isTableCell() && !containingBlock.isOutOfFlowPositioned() && !containingBlock.isRenderGrid() && containingBlock.style().logicalHeight().isAuto();
3007 }
3008
3009 bool RenderBox::shouldTreatChildAsReplacedInTableCells() const
3010 {
3011     if (isReplaced())
3012         return true;
3013     return element() && (element()->isFormControlElement() || is<HTMLImageElement>(element()));
3014 }
3015
3016 static bool tableCellShouldHaveZeroInitialSize(const RenderBlock& block, const RenderBox& child, bool scrollsOverflowY)
3017 {
3018     // Normally we would let the cell size intrinsically, but scrolling overflow has to be
3019     // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
3020     // While we can't get all cases right, we can at least detect when the cell has a specified
3021     // height or when the table has a specified height. In these cases we want to initially have
3022     // no size and allow the flexing of the table or the cell to its specified height to cause us
3023     // to grow to fill the space. This could end up being wrong in some cases, but it is
3024     // preferable to the alternative (sizing intrinsically and making the row end up too big).
3025     const RenderTableCell& cell = downcast<RenderTableCell>(block);
3026     return scrollsOverflowY && !child.shouldTreatChildAsReplacedInTableCells() && (!cell.style().logicalHeight().isAuto() || !cell.table()->style().logicalHeight().isAuto());
3027 }
3028
3029 std::optional<LayoutUnit> RenderBox::computePercentageLogicalHeight(const Length& height) const
3030 {
3031     std::optional<LayoutUnit> availableHeight;
3032
3033     bool skippedAutoHeightContainingBlock = false;
3034     RenderBlock* cb = containingBlock();
3035     const RenderBox* containingBlockChild = this;
3036     LayoutUnit rootMarginBorderPaddingHeight = 0;
3037     bool isHorizontal = isHorizontalWritingMode();
3038     while (cb && !is<RenderView>(*cb) && skipContainingBlockForPercentHeightCalculation(*cb, isHorizontal != cb->isHorizontalWritingMode())) {
3039         if (cb->isBody() || cb->isDocumentElementRenderer())
3040             rootMarginBorderPaddingHeight += cb->marginBefore() + cb->marginAfter() + cb->borderAndPaddingLogicalHeight();
3041         skippedAutoHeightContainingBlock = true;
3042         containingBlockChild = cb;
3043         cb = cb->containingBlock();
3044     }
3045     cb->addPercentHeightDescendant(const_cast<RenderBox&>(*this));
3046
3047     if (isHorizontal != cb->isHorizontalWritingMode())
3048         availableHeight = containingBlockChild->containingBlockLogicalWidthForContent();
3049     else if (hasOverrideContainingBlockLogicalHeight())
3050         availableHeight = overrideContainingBlockContentLogicalHeight();
3051     else if (is<RenderTableCell>(*cb)) {
3052         if (!skippedAutoHeightContainingBlock) {
3053             // Table cells violate what the CSS spec says to do with heights. Basically we
3054             // don't care if the cell specified a height or not. We just always make ourselves
3055             // be a percentage of the cell's current content height.
3056             if (!cb->hasOverrideLogicalContentHeight())
3057                 return tableCellShouldHaveZeroInitialSize(*cb, *this, scrollsOverflowY()) ? std::optional<LayoutUnit>(0) : std::nullopt;
3058
3059             availableHeight = cb->overrideLogicalContentHeight();
3060         }
3061     } else
3062         availableHeight = cb->availableLogicalHeightForPercentageComputation();
3063     
3064     if (!availableHeight)
3065         return availableHeight;
3066
3067     LayoutUnit result = valueForLength(height, availableHeight.value() - rootMarginBorderPaddingHeight + (isTable() && isOutOfFlowPositioned() ? cb->paddingBefore() + cb->paddingAfter() : LayoutUnit()));
3068     
3069     // |overrideLogicalContentHeight| is the maximum height made available by the
3070     // cell to its percent height children when we decide they can determine the
3071     // height of the cell. If the percent height child is box-sizing:content-box
3072     // then we must subtract the border and padding from the cell's
3073     // |availableHeight| (given by |overrideLogicalContentHeight|) to arrive
3074     // at the child's computed height.
3075     bool subtractBorderAndPadding = isTable() || (is<RenderTableCell>(*cb) && !skippedAutoHeightContainingBlock && cb->hasOverrideLogicalContentHeight());
3076     if (subtractBorderAndPadding) {
3077         result -= borderAndPaddingLogicalHeight();
3078         return std::max(LayoutUnit(), result);
3079     }
3080     return result;
3081 }
3082
3083 LayoutUnit RenderBox::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
3084 {
3085     return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(MainOrPreferredSize, style().logicalWidth()), shouldComputePreferred);
3086 }
3087
3088 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, ShouldComputePreferred shouldComputePreferred) const
3089 {
3090     auto& logicalMinWidth = style().logicalMinWidth();
3091     auto& logicalMaxWidth = style().logicalMaxWidth();
3092     bool useLogicalWidthForMinWidth = (shouldComputePreferred == ComputePreferred && logicalMinWidth.isPercentOrCalculated()) || logicalMinWidth.isUndefined();
3093     bool useLogicalWidthForMaxWidth = (shouldComputePreferred == ComputePreferred && logicalMaxWidth.isPercentOrCalculated()) || logicalMaxWidth.isUndefined();
3094     auto minLogicalWidth =  useLogicalWidthForMinWidth ? logicalWidth : computeReplacedLogicalWidthUsing(MinSize, logicalMinWidth);
3095     auto maxLogicalWidth =  useLogicalWidthForMaxWidth ? logicalWidth : computeReplacedLogicalWidthUsing(MaxSize, logicalMaxWidth);
3096     return std::max(minLogicalWidth, std::min(logicalWidth, maxLogicalWidth));
3097 }
3098
3099 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(SizeType widthType, Length logicalWidth) const
3100 {
3101     ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto());
3102     if (widthType == MinSize && logicalWidth.isAuto())
3103         return adjustContentBoxLogicalWidthForBoxSizing(0);
3104
3105     switch (logicalWidth.type()) {
3106         case Fixed:
3107             return adjustContentBoxLogicalWidthForBoxSizing(logicalWidth.value());
3108         case MinContent:
3109         case MaxContent: {
3110             // MinContent/MaxContent don't need the availableLogicalWidth argument.
3111             LayoutUnit availableLogicalWidth = 0;
3112             return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
3113         }
3114         case FitContent:
3115         case FillAvailable:
3116         case Percent: 
3117         case Calculated: {
3118             // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
3119             // containing block's block-flow.
3120             // https://bugs.webkit.org/show_bug.cgi?id=46496
3121             const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(downcast<RenderBoxModelObject>(*container())) : containingBlockLogicalWidthForContent();
3122             Length containerLogicalWidth = containingBlock()->style().logicalWidth();
3123             // FIXME: Handle cases when containing block width is calculated or viewport percent.
3124             // https://bugs.webkit.org/show_bug.cgi?id=91071
3125             if (logicalWidth.isIntrinsic())
3126                 return computeIntrinsicLogicalWidthUsing(logicalWidth, cw, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
3127             if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercentOrCalculated())))
3128                 return adjustContentBoxLogicalWidthForBoxSizing(minimumValueForLength(logicalWidth, cw));
3129         }
3130         FALLTHROUGH;
3131         case Intrinsic:
3132         case MinIntrinsic:
3133         case Auto:
3134         case Relative:
3135         case Undefined:
3136             return intrinsicLogicalWidth();
3137     }
3138
3139     ASSERT_NOT_REACHED();
3140     return 0;
3141 }
3142
3143 LayoutUnit RenderBox::computeReplacedLogicalHeight() const
3144 {
3145     return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(MainOrPreferredSize, style().logicalHeight()));
3146 }
3147
3148 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
3149 {
3150     LayoutUnit minLogicalHeight = computeReplacedLogicalHeightUsing(MinSize, style().logicalMinHeight());
3151     LayoutUnit maxLogicalHeight = style().logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(MaxSize, style().logicalMaxHeight());
3152     return std::max(minLogicalHeight, std::min(logicalHeight, maxLogicalHeight));
3153 }
3154
3155 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(SizeType heightType, Length logicalHeight) const
3156 {
3157     ASSERT(heightType == MinSize || heightType == MainOrPreferredSize || !logicalHeight.isAuto());
3158     if (heightType == MinSize && logicalHeight.isAuto())
3159         return adjustContentBoxLogicalHeightForBoxSizing(std::optional<LayoutUnit>(0));
3160
3161     switch (logicalHeight.type()) {
3162         case Fixed:
3163             return adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(logicalHeight.value()));
3164         case Percent:
3165         case Calculated:
3166         {
3167             auto* container = isOutOfFlowPositioned() ? this->container() : containingBlock();
3168             while (container && container->isAnonymous()) {
3169                 // Stop at rendering context root.
3170                 if (is<RenderView>(*container) || is<RenderNamedFlowThread>(*container))
3171                     break;
3172                 container = container->containingBlock();
3173             }
3174             std::optional<LayoutUnit> stretchedHeight;
3175             if (is<RenderBlock>(container)) {
3176                 auto* block = downcast<RenderBlock>(container);
3177                 block->addPercentHeightDescendant(*const_cast<RenderBox*>(this));
3178                 if (block->isFlexItem())
3179                     stretchedHeight = downcast<RenderFlexibleBox>(block->parent())->childLogicalHeightForPercentageResolution(*block);
3180                 else if (block->isGridItem() && block->hasOverrideLogicalContentHeight())
3181                     stretchedHeight = block->overrideLogicalContentHeight();
3182             }
3183
3184             // FIXME: This calculation is not patched for block-flow yet.
3185             // https://bugs.webkit.org/show_bug.cgi?id=46500
3186             if (container->isOutOfFlowPositioned()
3187                 && container->style().height().isAuto()
3188                 && !(container->style().top().isAuto() || container->style().bottom().isAuto())) {
3189                 ASSERT_WITH_SECURITY_IMPLICATION(container->isRenderBlock());
3190                 auto& block = downcast<RenderBlock>(*container);
3191                 auto computedValues = block.computeLogicalHeight(block.logicalHeight(), 0);
3192                 LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3193                 LayoutUnit newHeight = block.adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3194                 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, newHeight));
3195             }
3196             
3197             // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
3198             // containing block's block-flow.
3199             // https://bugs.webkit.org/show_bug.cgi?id=46496
3200             LayoutUnit availableHeight;
3201             if (isOutOfFlowPositioned())
3202                 availableHeight = containingBlockLogicalHeightForPositioned(downcast<RenderBoxModelObject>(*container));
3203             else if (stretchedHeight)
3204                 availableHeight = stretchedHeight.value();
3205             else {
3206                 availableHeight = containingBlockLogicalHeightForContent(IncludeMarginBorderPadding);
3207                 // It is necessary to use the border-box to match WinIE's broken
3208                 // box model.  This is essential for sizing inside
3209                 // table cells using percentage heights.
3210                 // FIXME: This needs to be made block-flow-aware.  If the cell and image are perpendicular block-flows, this isn't right.
3211                 // https://bugs.webkit.org/show_bug.cgi?id=46997
3212                 while (container && !is<RenderView>(*container)
3213                     && (container->style().logicalHeight().isAuto() || container->style().logicalHeight().isPercentOrCalculated())) {
3214                     if (container->isTableCell()) {
3215                         // Don't let table cells squeeze percent-height replaced elements
3216                         // <http://bugs.webkit.org/show_bug.cgi?id=15359>
3217                         availableHeight = std::max(availableHeight, intrinsicLogicalHeight());
3218                         return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight());
3219                     }
3220                     downcast<RenderBlock>(*container).addPercentHeightDescendant(const_cast<RenderBox&>(*this));
3221                     container = container->containingBlock();
3222                 }
3223             }
3224             return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight));
3225         }
3226         case MinContent:
3227         case MaxContent:
3228         case FitContent:
3229         case FillAvailable:
3230             return adjustContentBoxLogicalHeightForBoxSizing(computeIntrinsicLogicalContentHeightUsing(logicalHeight, intrinsicLogicalHeight(), borderAndPaddingLogicalHeight()));
3231         default:
3232             return intrinsicLogicalHeight();
3233     }
3234 }
3235
3236 LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const
3237 {
3238     return constrainLogicalHeightByMinMax(availableLogicalHeightUsing(style().logicalHeight(), heightType), std::nullopt);
3239 }
3240
3241 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const
3242 {
3243     // We need to stop here, since we don't want to increase the height of the table
3244     // artificially.  We're going to rely on this cell getting expanded to some new
3245     // height, and then when we lay out again we'll use the calculation below.
3246     if (isTableCell() && (h.isAuto() || h.isPercentOrCalculated())) {
3247         if (hasOverrideLogicalContentHeight())
3248             return overrideLogicalContentHeight();
3249         return logicalHeight() - borderAndPaddingLogicalHeight();
3250     }
3251
3252     if (isFlexItem()) {
3253         auto& flexBox = downcast<RenderFlexibleBox>(*parent());
3254         auto stretchedHeight = flexBox.childLogicalHeightForPercentageResolution(*this);
3255         if (stretchedHeight)
3256             return stretchedHeight.value();
3257     }
3258
3259     if (h.isPercentOrCalculated() && isOutOfFlowPositioned() && !isRenderFlowThread()) {
3260         // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3261         LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(*containingBlock());
3262         return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight));
3263     }
3264
3265     if (std::optional<LayoutUnit> heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(MainOrPreferredSize, h, std::nullopt))
3266         return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
3267
3268     // FIXME: Check logicalTop/logicalBottom here to correctly handle vertical writing-mode.
3269     // https://bugs.webkit.org/show_bug.cgi?id=46500
3270     if (is<RenderBlock>(*this) && isOutOfFlowPositioned() && style().height().isAuto() && !(style().top().isAuto() || style().bottom().isAuto())) {
3271         RenderBlock& block = const_cast<RenderBlock&>(downcast<RenderBlock>(*this));
3272         auto computedValues = block.computeLogicalHeight(block.logicalHeight(), 0);
3273         LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3274         return adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3275     }
3276
3277     // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3278     LayoutUnit availableHeight = containingBlockLogicalHeightForContent(heightType);
3279     if (heightType == ExcludeMarginBorderPadding) {
3280         // FIXME: Margin collapsing hasn't happened yet, so this incorrectly removes collapsed margins.
3281         availableHeight -= marginBefore() + marginAfter() + borderAndPaddingLogicalHeight();
3282     }
3283     return availableHeight;
3284 }
3285
3286 void RenderBox::computeBlockDirectionMargins(const RenderBlock& containingBlock, LayoutUnit& marginBefore, LayoutUnit& marginAfter) const
3287 {
3288     if (isTableCell()) {
3289         // FIXME: Not right if we allow cells to have different directionality than the table.  If we do allow this, though,
3290         // we may just do it with an extra anonymous block inside the cell.
3291         marginBefore = 0;
3292         marginAfter = 0;
3293         return;
3294     }
3295
3296     // Margins are calculated with respect to the logical width of
3297     // the containing block (8.3)
3298     LayoutUnit cw = containingBlockLogicalWidthForContent();
3299     const RenderStyle& containingBlockStyle = containingBlock.style();
3300     marginBefore = minimumValueForLength(style().marginBeforeUsing(&containingBlockStyle), cw);
3301     marginAfter = minimumValueForLength(style().marginAfterUsing(&containingBlockStyle), cw);
3302 }
3303
3304 void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock& containingBlock)
3305 {
3306     LayoutUnit marginBefore;
3307     LayoutUnit marginAfter;
3308     computeBlockDirectionMargins(containingBlock, marginBefore, marginAfter);
3309     containingBlock.setMarginBeforeForChild(*this, marginBefore);
3310     containingBlock.setMarginAfterForChild(*this, marginAfter);
3311 }
3312
3313 LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject& containingBlock, RenderRegion* region, bool checkForPerpendicularWritingMode) const
3314 {
3315     if (checkForPerpendicularWritingMode && containingBlock.isHorizontalWritingMode() != isHorizontalWritingMode())
3316         return containingBlockLogicalHeightForPositioned(containingBlock, false);
3317
3318     if (hasOverrideContainingBlockLogicalWidth()) {
3319         if (auto overrideLogicalWidth = overrideContainingBlockContentLogicalWidth())
3320             return overrideLogicalWidth.value();
3321     }
3322
3323     if (is<RenderBox>(containingBlock)) {
3324         bool isFixedPosition = style().position() == FixedPosition;
3325
3326         RenderFlowThread* flowThread = flowThreadContainingBlock();
3327         if (!flowThread) {
3328             if (isFixedPosition && is<RenderView>(containingBlock))
3329                 return downcast<RenderView>(containingBlock).clientLogicalWidthForFixedPosition();
3330
3331             return downcast<RenderBox>(containingBlock).clientLogicalWidth();
3332         }
3333
3334         if (isFixedPosition && is<RenderNamedFlowThread>(containingBlock))
3335             return containingBlock.view().clientLogicalWidth();
3336
3337         if (!is<RenderBlock>(containingBlock))
3338             return downcast<RenderBox>(containingBlock).clientLogicalWidth();
3339
3340         const RenderBlock& cb = downcast<RenderBlock>(containingBlock);
3341         RenderBoxRegionInfo* boxInfo = nullptr;
3342         if (!region) {
3343             if (is<RenderFlowThread>(containingBlock) && !checkForPerpendicularWritingMode)
3344                 return downcast<RenderFlowThread>(containingBlock).contentLogicalWidthOfFirstRegion();
3345             if (isWritingModeRoot()) {
3346                 LayoutUnit cbPageOffset = cb.offsetFromLogicalTopOfFirstPage();
3347                 RenderRegion* cbRegion = cb.regionAtBlockOffset(cbPageOffset);
3348                 if (cbRegion)
3349                     boxInfo = cb.renderBoxRegionInfo(cbRegion);
3350             }
3351         } else if (flowThread->isHorizontalWritingMode() == containingBlock.isHorizontalWritingMode()) {
3352             RenderRegion* containingBlockRegion = cb.clampToStartAndEndRegions(region);
3353             boxInfo = cb.renderBoxRegionInfo(containingBlockRegion);
3354         }
3355         return (boxInfo) ? std::max<LayoutUnit>(0, cb.clientLogicalWidth() - (cb.logicalWidth() - boxInfo->logicalWidth())) : cb.clientLogicalWidth();
3356     }
3357
3358     ASSERT(containingBlock.isInFlowPositioned());
3359
3360     const auto& flow = downcast<RenderInline>(containingBlock);
3361     InlineFlowBox* first = flow.firstLineBox();
3362     InlineFlowBox* last = flow.lastLineBox();
3363
3364     // If the containing block is empty, return a width of 0.
3365     if (!first || !last)
3366         return 0;
3367
3368     LayoutUnit fromLeft;
3369     LayoutUnit fromRight;
3370     if (containingBlock.style().isLeftToRightDirection()) {
3371         fromLeft = first->logicalLeft() + first->borderLogicalLeft();
3372         fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
3373     } else {
3374         fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
3375         fromLeft = last->logicalLeft() + last->borderLogicalLeft();
3376     }
3377
3378     return std::max<LayoutUnit>(0, fromRight - fromLeft);
3379 }
3380
3381 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject& containingBlock, bool checkForPerpendicularWritingMode) const
3382 {
3383     if (checkForPerpendicularWritingMode && containingBlock.isHorizontalWritingMode() != isHorizontalWritingMode())
3384         return containingBlockLogicalWidthForPositioned(containingBlock, nullptr, false);
3385
3386     if (hasOverrideContainingBlockLogicalHeight()) {
3387         if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight())
3388             return overrideLogicalHeight.value();
3389     }
3390
3391     if (containingBlock.isBox()) {
3392         bool isFixedPosition = style().position() == FixedPosition;
3393
3394         if (isFixedPosition && is<RenderView>(containingBlock))
3395             return downcast<RenderView>(containingBlock).clientLogicalHeightForFixedPosition();
3396
3397         const RenderBlock& cb = is<RenderBlock>(containingBlock) ? downcast<RenderBlock>(containingBlock) : *containingBlock.containingBlock();
3398         LayoutUnit result = cb.clientLogicalHeight();
3399         RenderFlowThread* flowThread = flowThreadContainingBlock();
3400         if (flowThread && is<RenderFlowThread>(containingBlock) && flowThread->isHorizontalWritingMode() == containingBlock.isHorizontalWritingMode()) {
3401             if (is<RenderNamedFlowThread>(containingBlock) && isFixedPosition)
3402                 return containingBlock.view().clientLogicalHeight();
3403             return downcast<RenderFlowThread>(containingBlock).contentLogicalHeightOfFirstRegion();
3404         }
3405         return result;
3406     }
3407         
3408     ASSERT(containingBlock.isInFlowPositioned());
3409
3410     const auto& flow = downcast<RenderInline>(containingBlock);
3411     InlineFlowBox* first = flow.firstLineBox();
3412     InlineFlowBox* last = flow.lastLineBox();
3413
3414     // If the containing block is empty, return a height of 0.
3415     if (!first || !last)
3416         return 0;
3417
3418     LayoutUnit heightResult;
3419     LayoutRect boundingBox = flow.linesBoundingBox();
3420     if (containingBlock.isHorizontalWritingMode())
3421         heightResult = boundingBox.height();
3422     else
3423         heightResult = boundingBox.width();
3424     heightResult -= (containingBlock.borderBefore() + containingBlock.borderAfter());
3425     return heightResult;
3426 }
3427
3428 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject& containerBlock, LayoutUnit containerLogicalWidth, RenderRegion* region)
3429 {
3430     if (!logicalLeft.isAuto() || !logicalRight.isAuto())
3431         return;
3432
3433     // FIXME: The static distance computation has not been patched for mixed writing modes yet.
3434     if (child->parent()->style().direction() == LTR) {
3435         LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock.borderLogicalLeft();
3436         for (auto* current = child->parent(); current && current != &containerBlock; current = current->container()) {
3437             if (!is<RenderBox>(*current))
3438                 continue;
3439             const auto& renderBox = downcast<RenderBox>(*current);
3440             staticPosition += renderBox.logicalLeft();
3441             if (renderBox.isInFlowPositioned())
3442                 staticPosition += renderBox.isHorizontalWritingMode() ? renderBox.offsetForInFlowPosition().width() : renderBox.offsetForInFlowPosition().height();
3443             if (region && is<RenderBlock>(*current)) {
3444                 const RenderBlock& currentBlock = downcast<RenderBlock>(*current);
3445                 region = currentBlock.clampToStartAndEndRegions(region);
3446                 RenderBoxRegionInfo* boxInfo = currentBlock.renderBoxRegionInfo(region);
3447                 if (boxInfo)
3448                     staticPosition += boxInfo->logicalLeft();
3449             }
3450         }
3451         logicalLeft.setValue(Fixed, staticPosition);
3452     } else {
3453         LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock.borderLogicalLeft();
3454         auto& enclosingBox = child->parent()->enclosingBox();
3455         if (&enclosingBox != &containerBlock && containerBlock.isDescendantOf(&enclosingBox)) {
3456             logicalRight.setValue(Fixed, staticPosition);
3457             return;
3458         }
3459
3460         staticPosition -= enclosingBox.logicalWidth();
3461         for (const RenderElement* current = &enclosingBox; current; current = current->container()) {
3462             if (!is<RenderBox>(*current))
3463                 continue;
3464
3465             if (current != &containerBlock) {
3466                 auto& renderBox = downcast<RenderBox>(*current);
3467                 staticPosition -= renderBox.logicalLeft();
3468                 if (renderBox.isInFlowPositioned())
3469                     staticPosition -= renderBox.isHorizontalWritingMode() ? renderBox.offsetForInFlowPosition().width() : renderBox.offsetForInFlowPosition().height();
3470             }
3471             if (region && is<RenderBlock>(*current)) {
3472                 auto& currentBlock = downcast<RenderBlock>(*current);
3473                 region = currentBlock.clampToStartAndEndRegions(region);
3474                 RenderBoxRegionInfo* boxInfo = currentBlock.renderBoxRegionInfo(region);
3475                 if (boxInfo) {
3476                     if (current != &containerBlock)
3477                         staticPosition -= currentBlock.logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth());
3478                     if (current == &enclosingBox)
3479                         staticPosition += enclosingBox.logicalWidth() - boxInfo->logicalWidth();
3480                 }
3481             }
3482             if (current == &containerBlock)
3483                 break;
3484         }
3485         logicalRight.setValue(Fixed, staticPosition);
3486     }
3487 }
3488
3489 void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
3490 {
3491     if (isReplaced()) {
3492         // FIXME: Positioned replaced elements inside a flow thread are not working properly
3493         // with variable width regions (see https://bugs.webkit.org/show_bug.cgi?id=69896 ).
3494         computePositionedLogicalWidthReplaced(computedValues);
3495         return;
3496     }
3497
3498     // QUESTIONS
3499     // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
3500     // the type 'static' in determining whether to calculate the static distance?
3501     // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
3502
3503     // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
3504     // than or less than the computed width().  Be careful of box-sizing and
3505     // percentage issues.
3506
3507     // The following is based off of the W3C Working Draft from April 11, 2006 of
3508     // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
3509     // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
3510     // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
3511     // correspond to text from the spec)
3512
3513
3514     // We don't use containingBlock(), since we may be positioned by an enclosing
3515     // relative positioned inline.
3516     const RenderBoxModelObject& containerBlock = downcast<RenderBoxModelObject>(*container());
3517     
3518     const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, region);
3519
3520     // Use the container block's direction except when calculating the static distance
3521     // This conforms with the reference results for abspos-replaced-width-margin-000.htm
3522     // of the CSS 2.1 test suite
3523     TextDirection containerDirection = containerBlock.style().direction();
3524
3525     bool isHorizontal = isHorizontalWritingMode();
3526     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
3527     const Length marginLogicalLeft = isHorizontal ? style().marginLeft() : style().marginTop();
3528     const Length marginLogicalRight = isHorizontal ? style().marginRight() : style().marginBottom();
3529
3530     Length logicalLeftLength = style().logicalLeft();
3531     Length logicalRightLength = style().logicalRight();
3532
3533     /*---------------------------------------------------------------------------*\
3534      * For the purposes of this section and the next, the term "static position"
3535      * (of an element) refers, roughly, to the position an element would have had
3536      * in the normal flow. More precisely:
3537      *
3538      * * The static position for 'left' is the distance from the left edge of the
3539      *   containing block to the left margin edge of a hypothetical box that would
3540      *   have been the first box of the element if its 'position' property had
3541      *   been 'static' and 'float' had been 'none'. The value is negative if the
3542      *   hypothetical box is to the left of the containing block.
3543      * * The static position for 'right' is the distance from the right edge of the
3544      *   containing block to the right margin edge of the same hypothetical box as
3545      *   above. The value is positive if the hypothetical box is to the left of the
3546      *   containing block's edge.
3547      *
3548      * But rather than actually calculating the dimensions of that hypothetical box,
3549      * user agents are free to make a guess at its probable position.
3550      *
3551      * For the purposes of calculating the static position, the containing block of
3552      * fixed positioned elements is the initial containing block instead of the
3553      * viewport, and all scrollable boxes should be assumed to be scrolled to their
3554      * origin.
3555     \*---------------------------------------------------------------------------*/
3556
3557     // see FIXME 1
3558     // Calculate the static distance if needed.
3559     computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth, region);
3560     
3561     // Calculate constraint equation values for 'width' case.
3562     computePositionedLogicalWidthUsing(MainOrPreferredSize, style().logicalWidth(), containerBlock, containerDirection,
3563                                        containerLogicalWidth, bordersPlusPadding,
3564                                        logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3565                                        computedValues);
3566
3567     // Calculate constraint equation values for 'max-width' case.
3568     if (!style().logicalMaxWidth().isUndefined()) {
3569         LogicalExtentComputedValues maxValues;
3570
3571         computePositionedLogicalWidthUsing(MaxSize, style().logicalMaxWidth(), containerBlock, containerDirection,
3572                                            containerLogicalWidth, bordersPlusPadding,
3573                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3574                                            maxValues);
3575
3576         if (computedValues.m_extent > maxValues.m_extent) {
3577             computedValues.m_extent = maxValues.m_extent;
3578             computedValues.m_position = maxValues.m_position;
3579             computedValues.m_margins.m_start = maxValues.m_margins.m_start;
3580             computedValues.m_margins.m_end = maxValues.m_margins.m_end;
3581         }
3582     }
3583
3584     // Calculate constraint equation values for 'min-width' case.
3585     if (!style().logicalMinWidth().isZero() || style().logicalMinWidth().isIntrinsic()) {
3586         LogicalExtentComputedValues minValues;
3587
3588         computePositionedLogicalWidthUsing(MinSize, style().logicalMinWidth(), containerBlock, containerDirection,
3589                                            containerLogicalWidth, bordersPlusPadding,
3590                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3591                                            minValues);
3592
3593         if (computedValues.m_extent < minValues.m_extent) {
3594             computedValues.m_extent = minValues.m_extent;
3595             computedValues.m_position = minValues.m_position;
3596             computedValues.m_margins.m_start = minValues.m_margins.m_start;
3597             computedValues.m_margins.m_end = minValues.m_margins.m_end;
3598         }
3599     }
3600
3601     if (!style().hasStaticInlinePosition(isHorizontal))
3602         computedValues.m_position += extraInlineOffset();
3603
3604     computedValues.m_extent += bordersPlusPadding;
3605     if (is<RenderBox>(containerBlock)) {
3606         auto& containingBox = downcast<RenderBox>(containerBlock);
3607         if (containingBox.shouldPlaceBlockDirectionScrollbarOnLeft())
3608             computedValues.m_position += containingBox.verticalScrollbarWidth();
3609     }
3610     
3611     // Adjust logicalLeft if we need to for the flipped version of our writing mode in regions.
3612     // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock.
3613     RenderFlowThread* flowThread = flowThreadContainingBlock();
3614     if (flowThread && !region && isWritingModeRoot() && isHorizontalWritingMode() == containerBlock.isHorizontalWritingMode() && is<RenderBlock>(containerBlock)) {
3615         ASSERT(containerBlock.canHaveBoxInfoInRegion());
3616         LayoutUnit logicalLeftPos = computedValues.m_position;
3617         const RenderBlock& renderBlock = downcast<RenderBlock>(containerBlock);
3618         LayoutUnit cbPageOffset = renderBlock.offsetFromLogicalTopOfFirstPage();
3619         RenderRegion* cbRegion = renderBlock.regionAtBlockOffset(cbPageOffset);
3620         if (cbRegion) {
3621             RenderBoxRegionInfo* boxInfo = renderBlock.renderBoxRegionInfo(cbRegion);
3622             if (boxInfo) {
3623                 logicalLeftPos += boxInfo->logicalLeft();
3624                 computedValues.m_position = logicalLeftPos;
3625             }
3626         }
3627     }
3628 }
3629
3630 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject& containerBlock, LayoutUnit containerLogicalWidth)
3631 {
3632     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3633     // 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.
3634     if (containerBlock.isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock.style().isFlippedBlocksWritingMode()) {
3635         logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
3636         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock.borderRight() : containerBlock.borderBottom());
3637     } else
3638         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock.borderLeft() : containerBlock.borderTop());
3639 }
3640
3641 void RenderBox::computePositionedLogicalWidthUsing(SizeType widthType, Length logicalWidth, const RenderBoxModelObject& containerBlock, TextDirection containerDirection,
3642                                                    LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
3643                                                    Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight,
3644                                                    LogicalExtentComputedValues& computedValues) const
3645 {
3646     ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto());
3647     if (widthType == MinSize && logicalWidth.isAuto())
3648         logicalWidth = Length(0, Fixed);
3649     else if (logicalWidth.isIntrinsic())
3650         logicalWidth = Length(computeIntrinsicLogicalWidthUsing(logicalWidth, containerLogicalWidth, bordersPlusPadding) - bordersPlusPadding, Fixed);
3651
3652     // 'left' and 'right' cannot both be 'auto' because one would of been
3653     // converted to the static position already
3654     ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
3655
3656     LayoutUnit logicalLeftValue = 0;
3657
3658     const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, nullptr, false);
3659
3660     bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
3661     bool logicalLeftIsAuto = logicalLeft.isAuto();
3662     bool logicalRightIsAuto = logicalRight.isAuto();
3663     LayoutUnit& marginLogicalLeftValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
3664     LayoutUnit& marginLogicalRightValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
3665
3666     if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3667         /*-----------------------------------------------------------------------*\
3668          * If none of the three is 'auto': If both 'margin-left' and 'margin-
3669          * right' are 'auto', solve the equation under the extra constraint that
3670          * the two margins get equal values, unless this would make them negative,
3671          * in which case when direction of the containing block is 'ltr' ('rtl'),
3672          * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
3673          * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
3674          * solve the equation for that value. If the values are over-constrained,
3675          * ignore the value for 'left' (in case the 'direction' property of the
3676          * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
3677          * and solve for that value.
3678         \*-----------------------------------------------------------------------*/
3679         // NOTE:  It is not necessary to solve for 'right' in the over constrained
3680         // case because the value is not used for any further calculations.
3681
3682         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3683         computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3684
3685         const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth) + bordersPlusPadding);
3686
3687         // Margins are now the only unknown
3688         if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
3689             // Both margins auto, solve for equality
3690             if (availableSpace >= 0) {
3691                 marginLogicalLeftValue = availableSpace / 2; // split the difference
3692                 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
3693             } else {
3694                 // Use the containing block's direction rather than the parent block's
3695                 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3696                 if (containerDirection == LTR) {
3697                     marginLogicalLeftValue = 0;
3698                     marginLogicalRightValue = availableSpace; // will be negative
3699                 } else {
3700                     marginLogicalLeftValue = availableSpace; // will be negative
3701                     marginLogicalRightValue = 0;
3702                 }
3703             }
3704         } else if (marginLogicalLeft.isAuto()) {
3705             // Solve for left margin
3706             marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3707             marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
3708         } else if (marginLogicalRight.isAuto()) {
3709             // Solve for right margin
3710             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3711             marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
3712         } else {
3713             // Over-constrained, solve for left if direction is RTL
3714             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3715             marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3716
3717             // Use the containing block's direction rather than the parent block's
3718             // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3719             if (containerDirection == RTL)
3720                 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
3721         }
3722     } else {
3723         /*--------------------------------------------------------------------*\
3724          * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
3725          * to 0, and pick the one of the following six rules that applies.
3726          *
3727          * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
3728          *    width is shrink-to-fit. Then solve for 'left'
3729          *
3730          *              OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3731          * ------------------------------------------------------------------
3732          * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
3733          *    the 'direction' property of the containing block is 'ltr' set
3734          *    'left' to the static position, otherwise set 'right' to the
3735          *    static position. Then solve for 'left' (if 'direction is 'rtl')
3736          *    or 'right' (if 'direction' is 'ltr').
3737          * ------------------------------------------------------------------
3738          *
3739          * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
3740          *    width is shrink-to-fit . Then solve for 'right'
3741          * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
3742          *    for 'left'
3743          * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
3744          *    for 'width'
3745          * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
3746          *    for 'right'
3747          *
3748          * Calculation of the shrink-to-fit width is similar to calculating the
3749          * width of a table cell using the automatic table layout algorithm.
3750          * Roughly: calculate the preferred width by formatting the content
3751          * without breaking lines other than where explicit line breaks occur,
3752          * and also calculate the preferred minimum width, e.g., by trying all
3753          * possible line breaks. CSS 2.1 does not define the exact algorithm.
3754          * Thirdly, calculate the available width: this is found by solving
3755          * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
3756          * to 0.
3757          *
3758          * Then the shrink-to-fit width is:
3759          * min(max(preferred minimum width, available width), preferred width).
3760         \*--------------------------------------------------------------------*/
3761         // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
3762         // because the value is not used for any further calculations.
3763
3764         // Calculate margins, 'auto' margins are ignored.
3765         marginLogicalLeftValue = minimumValueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3766         marginLogicalRightValue = minimumValueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3767
3768         const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
3769
3770         // FIXME: Is there a faster way to find the correct case?
3771         // Use rule/case that applies.
3772         if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3773             // RULE 1: (use shrink-to-fit for width, and solve of left)
3774             LayoutUnit logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3775
3776             // FIXME: would it be better to have shrink-to-fit in one step?
3777             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3778             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3779             LayoutUnit availableWidth = availableSpace - logicalRightValue;
3780             computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3781             logicalLeftValue = availableSpace - (computedValues.m_extent + logicalRightValue);
3782         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
3783             // RULE 3: (use shrink-to-fit for width, and no need solve of right)
3784             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3785
3786             // FIXME: would it be better to have shrink-to-fit in one step?
3787             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3788             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3789             LayoutUnit availableWidth = availableSpace - logicalLeftValue;
3790             computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3791         } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3792             // RULE 4: (solve for left)
3793             computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3794             logicalLeftValue = availableSpace - (computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth));
3795         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3796             // RULE 5: (solve for width)
3797             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3798             computedValues.m_extent = availableSpace - (logicalLeftValue + valueForLength(logicalRight, containerLogicalWidth));
3799         } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
3800             // RULE 6: (no need solve for right)
3801             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3802   &n