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