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