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