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