Use smart pointers for creating, adding and removing renderers
[WebKit-https.git] / Source / WebCore / rendering / RenderBox.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
5  *           (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
6  * Copyright (C) 2005-2010, 2015 Apple Inc. All rights reserved.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public License
19  * along with this library; see the file COPYING.LIB.  If not, write to
20  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  *
23  */
24
25 #include "config.h"
26 #include "RenderBox.h"
27
28 #include "CSSFontSelector.h"
29 #include "ControlStates.h"
30 #include "Document.h"
31 #include "Editing.h"
32 #include "EventHandler.h"
33 #include "FloatQuad.h"
34 #include "FloatRoundedRect.h"
35 #include "Frame.h"
36 #include "FrameView.h"
37 #include "GraphicsContext.h"
38 #include "HTMLBodyElement.h"
39 #include "HTMLButtonElement.h"
40 #include "HTMLFrameOwnerElement.h"
41 #include "HTMLHtmlElement.h"
42 #include "HTMLImageElement.h"
43 #include "HTMLInputElement.h"
44 #include "HTMLLegendElement.h"
45 #include "HTMLNames.h"
46 #include "HTMLSelectElement.h"
47 #include "HTMLTextAreaElement.h"
48 #include "HitTestResult.h"
49 #include "InlineElementBox.h"
50 #include "MainFrame.h"
51 #include "Page.h"
52 #include "PaintInfo.h"
53 #include "RenderBoxFragmentInfo.h"
54 #include "RenderChildIterator.h"
55 #include "RenderDeprecatedFlexibleBox.h"
56 #include "RenderFlexibleBox.h"
57 #include "RenderFragmentContainer.h"
58 #include "RenderGeometryMap.h"
59 #include "RenderInline.h"
60 #include "RenderIterator.h"
61 #include "RenderLayer.h"
62 #include "RenderLayerCompositor.h"
63 #include "RenderMultiColumnFlow.h"
64 #include "RenderTableCell.h"
65 #include "RenderTheme.h"
66 #include "RenderView.h"
67 #include "RuntimeApplicationChecks.h"
68 #include "ScrollAnimator.h"
69 #include "ScrollbarTheme.h"
70 #include "StyleScrollSnapPoints.h"
71 #include "TransformState.h"
72 #include <algorithm>
73 #include <math.h>
74 #include <wtf/StackStats.h>
75
76 #include "RenderGrid.h"
77
78 #if PLATFORM(IOS)
79 #include "Settings.h"
80 #endif
81
82 namespace WebCore {
83
84 struct SameSizeAsRenderBox : public RenderBoxModelObject {
85     virtual ~SameSizeAsRenderBox() { }
86     LayoutRect frameRect;
87     LayoutBoxExtent marginBox;
88     LayoutUnit preferredLogicalWidths[2];
89     void* pointers[2];
90 };
91
92 COMPILE_ASSERT(sizeof(RenderBox) == sizeof(SameSizeAsRenderBox), RenderBox_should_stay_small);
93
94 using namespace HTMLNames;
95
96 // Used by flexible boxes when flexing this element and by table cells.
97 typedef WTF::HashMap<const RenderBox*, LayoutUnit> OverrideSizeMap;
98 static OverrideSizeMap* gOverrideHeightMap = nullptr;
99 static OverrideSizeMap* gOverrideWidthMap = nullptr;
100
101 // Used by grid elements to properly size their grid items.
102 typedef WTF::HashMap<const RenderBox*, std::optional<LayoutUnit>> OverrideOptionalSizeMap;
103 static OverrideOptionalSizeMap* gOverrideContainingBlockLogicalHeightMap = nullptr;
104 static OverrideOptionalSizeMap* gOverrideContainingBlockLogicalWidthMap = nullptr;
105
106 // Size of border belt for autoscroll. When mouse pointer in border belt,
107 // autoscroll is started.
108 static const int autoscrollBeltSize = 20;
109 static const unsigned backgroundObscurationTestMaxDepth = 4;
110
111 using ControlStatesRendererMap = HashMap<const RenderObject*, std::unique_ptr<ControlStates>>;
112 static ControlStatesRendererMap& controlStatesRendererMap()
113 {
114     static NeverDestroyed<ControlStatesRendererMap> map;
115     return map;
116 }
117
118 static ControlStates* controlStatesForRenderer(const RenderBox& renderer)
119 {
120     return controlStatesRendererMap().ensure(&renderer, [] {
121         return std::make_unique<ControlStates>();
122     }).iterator->value.get();
123 }
124
125 static void removeControlStatesForRenderer(const RenderBox& renderer)
126 {
127     controlStatesRendererMap().remove(&renderer);
128 }
129
130 bool RenderBox::s_hadOverflowClip = false;
131
132 RenderBox::RenderBox(Element& element, RenderStyle&& style, BaseTypeFlags baseTypeFlags)
133     : RenderBoxModelObject(element, WTFMove(style), baseTypeFlags)
134 {
135     setIsBox();
136 }
137
138 RenderBox::RenderBox(Document& document, RenderStyle&& style, BaseTypeFlags baseTypeFlags)
139     : RenderBoxModelObject(document, WTFMove(style), baseTypeFlags)
140 {
141     setIsBox();
142 }
143
144 RenderBox::~RenderBox()
145 {
146     // Do not add any code here. Add it to willBeDestroyed() instead.
147 }
148
149 void RenderBox::willBeDestroyed()
150 {
151     if (frame().eventHandler().autoscrollRenderer() == this)
152         frame().eventHandler().stopAutoscrollTimer(true);
153
154     clearOverrideSize();
155     clearContainingBlockOverrideSize();
156
157     RenderBlock::removePercentHeightDescendantIfNeeded(*this);
158
159     ShapeOutsideInfo::removeInfo(*this);
160
161     view().unscheduleLazyRepaint(*this);
162     removeControlStatesForRenderer(*this);
163     
164     RenderBoxModelObject::willBeDestroyed();
165 }
166
167 RenderFragmentContainer* RenderBox::clampToStartAndEndFragments(RenderFragmentContainer* fragment) const
168 {
169     RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
170
171     ASSERT(isRenderView() || (fragment && fragmentedFlow));
172     if (isRenderView())
173         return fragment;
174
175     // We need to clamp to the block, since we want any lines or blocks that overflow out of the
176     // logical top or logical bottom of the block to size as though the border box in the first and
177     // last fragments extended infinitely. Otherwise the lines are going to size according to the fragments
178     // they overflow into, which makes no sense when this block doesn't exist in |fragment| at all.
179     RenderFragmentContainer* startFragment = nullptr;
180     RenderFragmentContainer* endFragment = nullptr;
181     if (!fragmentedFlow->getFragmentRangeForBox(this, startFragment, endFragment))
182         return fragment;
183
184     if (fragment->logicalTopForFragmentedFlowContent() < startFragment->logicalTopForFragmentedFlowContent())
185         return startFragment;
186     if (fragment->logicalTopForFragmentedFlowContent() > endFragment->logicalTopForFragmentedFlowContent())
187         return endFragment;
188
189     return fragment;
190 }
191
192 bool RenderBox::hasFragmentRangeInFragmentedFlow() const
193 {
194     RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
195     if (!fragmentedFlow || !fragmentedFlow->hasValidFragmentInfo())
196         return false;
197
198     return fragmentedFlow->hasCachedFragmentRangeForBox(*this);
199 }
200
201 LayoutRect RenderBox::clientBoxRectInFragment(RenderFragmentContainer* fragment) const
202 {
203     if (!fragment)
204         return clientBoxRect();
205
206     LayoutRect clientBox = borderBoxRectInFragment(fragment);
207     clientBox.setLocation(clientBox.location() + LayoutSize(borderLeft(), borderTop()));
208     clientBox.setSize(clientBox.size() - LayoutSize(borderLeft() + borderRight() + verticalScrollbarWidth(), borderTop() + borderBottom() + horizontalScrollbarHeight()));
209
210     return clientBox;
211 }
212
213 LayoutRect RenderBox::borderBoxRectInFragment(RenderFragmentContainer*, RenderBoxFragmentInfoFlags) const
214 {
215     return borderBoxRect();
216 }
217
218 static RenderBlockFlow* outermostBlockContainingFloatingObject(RenderBox& box)
219 {
220     ASSERT(box.isFloating());
221     RenderBlockFlow* parentBlock = nullptr;
222     for (auto& ancestor : ancestorsOfType<RenderBlockFlow>(box)) {
223         if (ancestor.isRenderView())
224             break;
225         if (!parentBlock || ancestor.containsFloat(box))
226             parentBlock = &ancestor;
227     }
228     return parentBlock;
229 }
230
231 void RenderBox::removeFloatingOrPositionedChildFromBlockLists()
232 {
233     ASSERT(isFloatingOrOutOfFlowPositioned());
234
235     if (renderTreeBeingDestroyed())
236         return;
237
238     if (isFloating()) {
239         if (RenderBlockFlow* parentBlock = outermostBlockContainingFloatingObject(*this)) {
240             parentBlock->markSiblingsWithFloatsForLayout(this);
241             parentBlock->markAllDescendantsWithFloatsForLayout(this, false);
242         }
243     }
244
245     if (isOutOfFlowPositioned())
246         RenderBlock::removePositionedObject(*this);
247 }
248
249 void RenderBox::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
250 {
251     s_hadOverflowClip = hasOverflowClip();
252
253     const RenderStyle* oldStyle = hasInitializedStyle() ? &style() : nullptr;
254     if (oldStyle) {
255         // The background of the root element or the body element could propagate up to
256         // the canvas. Issue full repaint, when our style changes substantially.
257         if (diff >= StyleDifferenceRepaint && (isDocumentElementRenderer() || isBody())) {
258             view().repaintRootContents();
259             if (oldStyle->hasEntirelyFixedBackground() != newStyle.hasEntirelyFixedBackground())
260                 view().compositor().rootFixedBackgroundsChanged();
261         }
262         
263         // When a layout hint happens and an object's position style changes, we have to do a layout
264         // to dirty the render tree using the old position value now.
265         if (diff == StyleDifferenceLayout && parent() && oldStyle->position() != newStyle.position()) {
266             markContainingBlocksForLayout();
267             if (oldStyle->position() == StaticPosition)
268                 repaint();
269             else if (newStyle.hasOutOfFlowPosition())
270                 parent()->setChildNeedsLayout();
271             if (isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition())
272                 removeFloatingOrPositionedChildFromBlockLists();
273         }
274     } else if (isBody())
275         view().repaintRootContents();
276
277 #if ENABLE(CSS_SCROLL_SNAP)
278     bool boxContributesSnapPositions = newStyle.scrollSnapArea().hasSnapPosition();
279     if (boxContributesSnapPositions || (oldStyle && oldStyle->scrollSnapArea().hasSnapPosition())) {
280         if (boxContributesSnapPositions)
281             view().registerBoxWithScrollSnapPositions(*this);
282         else
283             view().unregisterBoxWithScrollSnapPositions(*this);
284     }
285 #endif
286
287     RenderBoxModelObject::styleWillChange(diff, newStyle);
288 }
289
290 void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
291 {
292     // Horizontal writing mode definition is updated in RenderBoxModelObject::updateFromStyle,
293     // (as part of the RenderBoxModelObject::styleDidChange call below). So, we can safely cache the horizontal
294     // writing mode value before style change here.
295     bool oldHorizontalWritingMode = isHorizontalWritingMode();
296
297     RenderBoxModelObject::styleDidChange(diff, oldStyle);
298
299     const RenderStyle& newStyle = style();
300     if (needsLayout() && oldStyle) {
301         RenderBlock::removePercentHeightDescendantIfNeeded(*this);
302
303         // Normally we can do optimized positioning layout for absolute/fixed positioned objects. There is one special case, however, which is
304         // when the positioned object's margin-before is changed. In this case the parent has to get a layout in order to run margin collapsing
305         // to determine the new static position.
306         if (isOutOfFlowPositioned() && newStyle.hasStaticBlockPosition(isHorizontalWritingMode()) && oldStyle->marginBefore() != newStyle.marginBefore()
307             && parent() && !parent()->normalChildNeedsLayout())
308             parent()->setChildNeedsLayout();
309     }
310
311     if (RenderBlock::hasPercentHeightContainerMap() && firstChild()
312         && oldHorizontalWritingMode != isHorizontalWritingMode())
313         RenderBlock::clearPercentHeightDescendantsFrom(*this);
314
315     // If our zoom factor changes and we have a defined scrollLeft/Top, we need to adjust that value into the
316     // new zoomed coordinate space.
317     if (hasOverflowClip() && layer() && oldStyle && oldStyle->effectiveZoom() != newStyle.effectiveZoom()) {
318         if (int left = layer()->scrollOffset().x()) {
319             left = (left / oldStyle->effectiveZoom()) * newStyle.effectiveZoom();
320             layer()->scrollToXOffset(left);
321         }
322         if (int top = layer()->scrollOffset().y()) {
323             top = (top / oldStyle->effectiveZoom()) * newStyle.effectiveZoom();
324             layer()->scrollToYOffset(top);
325         }
326     }
327
328     // Our opaqueness might have changed without triggering layout.
329     if (diff >= StyleDifferenceRepaint && diff <= StyleDifferenceRepaintLayer) {
330         auto parentToInvalidate = parent();
331         for (unsigned i = 0; i < backgroundObscurationTestMaxDepth && parentToInvalidate; ++i) {
332             parentToInvalidate->invalidateBackgroundObscurationStatus();
333             parentToInvalidate = parentToInvalidate->parent();
334         }
335     }
336
337     bool isBodyRenderer = isBody();
338     bool isDocElementRenderer = isDocumentElementRenderer();
339
340     if (isDocElementRenderer || isBodyRenderer) {
341         // Propagate the new writing mode and direction up to the RenderView.
342         auto* documentElementRenderer = document().documentElement()->renderer();
343         auto& viewStyle = view().mutableStyle();
344         bool rootStyleChanged = false;
345         bool viewDirectionOrWritingModeChanged = false;
346         auto* rootRenderer = isBodyRenderer ? documentElementRenderer : nullptr;
347         if (viewStyle.direction() != newStyle.direction() && (isDocElementRenderer || !documentElementRenderer->style().hasExplicitlySetDirection())) {
348             viewStyle.setDirection(newStyle.direction());
349             viewDirectionOrWritingModeChanged = true;
350             if (isBodyRenderer) {
351                 rootRenderer->mutableStyle().setDirection(newStyle.direction());
352                 rootStyleChanged = true;
353             }
354             setNeedsLayoutAndPrefWidthsRecalc();
355
356             view().frameView().topContentDirectionDidChange();
357         }
358
359         if (viewStyle.writingMode() != newStyle.writingMode() && (isDocElementRenderer || !documentElementRenderer->style().hasExplicitlySetWritingMode())) {
360             viewStyle.setWritingMode(newStyle.writingMode());
361             viewDirectionOrWritingModeChanged = true;
362             view().setHorizontalWritingMode(newStyle.isHorizontalWritingMode());
363             view().markAllDescendantsWithFloatsForLayout();
364             if (isBodyRenderer) {
365                 rootStyleChanged = true;
366                 rootRenderer->mutableStyle().setWritingMode(newStyle.writingMode());
367                 rootRenderer->setHorizontalWritingMode(newStyle.isHorizontalWritingMode());
368             }
369             setNeedsLayoutAndPrefWidthsRecalc();
370         }
371
372         view().frameView().recalculateScrollbarOverlayStyle();
373         
374         const Pagination& pagination = view().frameView().pagination();
375         if (viewDirectionOrWritingModeChanged && pagination.mode != Pagination::Unpaginated) {
376             viewStyle.setColumnStylesFromPaginationMode(pagination.mode);
377             if (view().multiColumnFlow())
378                 view().updateColumnProgressionFromStyle(viewStyle);
379         }
380         
381         if (viewDirectionOrWritingModeChanged && view().multiColumnFlow())
382             view().updateStylesForColumnChildren();
383         
384         if (rootStyleChanged && is<RenderBlockFlow>(rootRenderer) && downcast<RenderBlockFlow>(*rootRenderer).multiColumnFlow())
385             downcast<RenderBlockFlow>(*rootRenderer).updateStylesForColumnChildren();
386         
387         if (isBodyRenderer && pagination.mode != Pagination::Unpaginated && page().paginationLineGridEnabled()) {
388             // Propagate the body font back up to the RenderView and use it as
389             // the basis of the grid.
390             if (newStyle.fontDescription() != view().style().fontDescription()) {
391                 view().mutableStyle().setFontDescription(newStyle.fontDescription());
392                 view().mutableStyle().fontCascade().update(&document().fontSelector());
393             }
394         }
395
396         if (diff != StyleDifferenceEqual)
397             view().compositor().rootOrBodyStyleChanged(*this, oldStyle);
398     }
399
400     if ((oldStyle && oldStyle->shapeOutside()) || style().shapeOutside())
401         updateShapeOutsideInfoAfterStyleChange(style(), oldStyle);
402     updateGridPositionAfterStyleChange(style(), oldStyle);
403 }
404
405 void RenderBox::willBeRemovedFromTree()
406 {
407 #if ENABLE(CSS_SCROLL_SNAP)
408     if (hasInitializedStyle() && style().scrollSnapArea().hasSnapPosition())
409         view().unregisterBoxWithScrollSnapPositions(*this);
410 #endif
411     
412     RenderBoxModelObject::willBeRemovedFromTree();
413 }
414     
415
416 void RenderBox::updateGridPositionAfterStyleChange(const RenderStyle& style, const RenderStyle* oldStyle)
417 {
418     if (!oldStyle || !is<RenderGrid>(parent()))
419         return;
420
421     if (oldStyle->gridItemColumnStart() == style.gridItemColumnStart()
422         && oldStyle->gridItemColumnEnd() == style.gridItemColumnEnd()
423         && oldStyle->gridItemRowStart() == style.gridItemRowStart()
424         && oldStyle->gridItemRowEnd() == style.gridItemRowEnd()
425         && oldStyle->order() == style.order()
426         && oldStyle->hasOutOfFlowPosition() == style.hasOutOfFlowPosition())
427         return;
428
429     // Positioned items don't participate on the layout of the grid,
430     // so we don't need to mark the grid as dirty if they change positions.
431     if (oldStyle->hasOutOfFlowPosition() && style.hasOutOfFlowPosition())
432         return;
433
434     // It should be possible to not dirty the grid in some cases (like moving an
435     // explicitly placed grid item).
436     // For now, it's more simple to just always recompute the grid.
437     downcast<RenderGrid>(*parent()).dirtyGrid();
438 }
439
440 void RenderBox::updateShapeOutsideInfoAfterStyleChange(const RenderStyle& style, const RenderStyle* oldStyle)
441 {
442     const ShapeValue* shapeOutside = style.shapeOutside();
443     const ShapeValue* oldShapeOutside = oldStyle ? oldStyle->shapeOutside() : nullptr;
444
445     Length shapeMargin = style.shapeMargin();
446     Length oldShapeMargin = oldStyle ? oldStyle->shapeMargin() : RenderStyle::initialShapeMargin();
447
448     float shapeImageThreshold = style.shapeImageThreshold();
449     float oldShapeImageThreshold = oldStyle ? oldStyle->shapeImageThreshold() : RenderStyle::initialShapeImageThreshold();
450
451     // FIXME: A future optimization would do a deep comparison for equality. (bug 100811)
452     if (shapeOutside == oldShapeOutside && shapeMargin == oldShapeMargin && shapeImageThreshold == oldShapeImageThreshold)
453         return;
454
455     if (!shapeOutside)
456         ShapeOutsideInfo::removeInfo(*this);
457     else
458         ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
459
460     if (shapeOutside || shapeOutside != oldShapeOutside)
461         markShapeOutsideDependentsForLayout();
462 }
463
464 void RenderBox::updateFromStyle()
465 {
466     RenderBoxModelObject::updateFromStyle();
467
468     const RenderStyle& styleToUse = style();
469     bool isDocElementRenderer = isDocumentElementRenderer();
470     bool isViewObject = isRenderView();
471
472     // The root and the RenderView always paint their backgrounds/borders.
473     if (isDocElementRenderer || isViewObject)
474         setHasVisibleBoxDecorations(true);
475
476     setFloating(!isOutOfFlowPositioned() && styleToUse.isFloating());
477
478     // We also handle <body> and <html>, whose overflow applies to the viewport.
479     if (styleToUse.overflowX() != OVISIBLE && !isDocElementRenderer && isRenderBlock()) {
480         bool boxHasOverflowClip = true;
481         if (isBody()) {
482             // Overflow on the body can propagate to the viewport under the following conditions.
483             // (1) The root element is <html>.
484             // (2) We are the primary <body> (can be checked by looking at document.body).
485             // (3) The root element has visible overflow.
486             if (is<HTMLHtmlElement>(*document().documentElement())
487                 && document().body() == element()
488                 && document().documentElement()->renderer()->style().overflowX() == OVISIBLE) {
489                 boxHasOverflowClip = false;
490             }
491         }
492         // Check for overflow clip.
493         // It's sufficient to just check one direction, since it's illegal to have visible on only one overflow value.
494         if (boxHasOverflowClip) {
495             if (!s_hadOverflowClip && hasRenderOverflow()) {
496                 // Erase the overflow.
497                 // Overflow changes have to result in immediate repaints of the entire layout overflow area because
498                 // repaints issued by removal of descendants get clipped using the updated style when they shouldn't.
499                 repaintRectangle(visualOverflowRect());
500                 repaintRectangle(layoutOverflowRect());
501             }
502             setHasOverflowClip();
503         }
504     }
505     setHasTransformRelatedProperty(styleToUse.hasTransformRelatedProperty());
506     setHasReflection(styleToUse.boxReflect());
507 }
508
509 void RenderBox::layout()
510 {
511     StackStats::LayoutCheckPoint layoutCheckPoint;
512     ASSERT(needsLayout());
513
514     RenderObject* child = firstChild();
515     if (!child) {
516         clearNeedsLayout();
517         return;
518     }
519
520     LayoutStateMaintainer statePusher(view(), *this, locationOffset(), style().isFlippedBlocksWritingMode());
521     while (child) {
522         if (child->needsLayout())
523             downcast<RenderElement>(*child).layout();
524         ASSERT(!child->needsLayout());
525         child = child->nextSibling();
526     }
527     statePusher.pop();
528     invalidateBackgroundObscurationStatus();
529     clearNeedsLayout();
530 }
531
532 // More IE extensions.  clientWidth and clientHeight represent the interior of an object
533 // excluding border and scrollbar.
534 LayoutUnit RenderBox::clientWidth() const
535 {
536     return width() - borderLeft() - borderRight() - verticalScrollbarWidth();
537 }
538
539 LayoutUnit RenderBox::clientHeight() const
540 {
541     return height() - borderTop() - borderBottom() - horizontalScrollbarHeight();
542 }
543
544 int RenderBox::scrollWidth() const
545 {
546     if (hasOverflowClip() && layer())
547         return layer()->scrollWidth();
548     // For objects with visible overflow, this matches IE.
549     // FIXME: Need to work right with writing modes.
550     if (style().isLeftToRightDirection()) {
551         // FIXME: This should use snappedIntSize() instead with absolute coordinates.
552         return roundToInt(std::max(clientWidth(), layoutOverflowRect().maxX() - borderLeft()));
553     }
554     return roundToInt(clientWidth() - std::min<LayoutUnit>(0, layoutOverflowRect().x() - borderLeft()));
555 }
556
557 int RenderBox::scrollHeight() const
558 {
559     if (hasOverflowClip() && layer())
560         return layer()->scrollHeight();
561     // For objects with visible overflow, this matches IE.
562     // FIXME: Need to work right with writing modes.
563     // FIXME: This should use snappedIntSize() instead with absolute coordinates.
564     return roundToInt(std::max(clientHeight(), layoutOverflowRect().maxY() - borderTop()));
565 }
566
567 int RenderBox::scrollLeft() const
568 {
569     return hasOverflowClip() && layer() ? layer()->scrollPosition().x() : 0;
570 }
571
572 int RenderBox::scrollTop() const
573 {
574     return hasOverflowClip() && layer() ? layer()->scrollPosition().y() : 0;
575 }
576
577 static void setupWheelEventTestTrigger(RenderLayer& layer)
578 {
579     Page& page = layer.renderer().page();
580     if (!page.expectsWheelEventTriggers())
581         return;
582     layer.scrollAnimator().setWheelEventTestTrigger(page.testTrigger());
583 }
584
585 void RenderBox::setScrollLeft(int newLeft)
586 {
587     if (!hasOverflowClip() || !layer())
588         return;
589     setupWheelEventTestTrigger(*layer());
590     layer()->scrollToXPosition(newLeft, RenderLayer::ScrollOffsetClamped);
591 }
592
593 void RenderBox::setScrollTop(int newTop)
594 {
595     if (!hasOverflowClip() || !layer())
596         return;
597     setupWheelEventTestTrigger(*layer());
598     layer()->scrollToYPosition(newTop, RenderLayer::ScrollOffsetClamped);
599 }
600
601 void RenderBox::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
602 {
603     rects.append(snappedIntRect(accumulatedOffset, size()));
604 }
605
606 void RenderBox::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
607 {
608     FloatRect localRect(0, 0, width(), height());
609
610     RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
611     if (fragmentedFlow && fragmentedFlow->absoluteQuadsForBox(quads, wasFixed, this, localRect.y(), localRect.maxY()))
612         return;
613
614     quads.append(localToAbsoluteQuad(localRect, UseTransforms, wasFixed));
615 }
616
617 void RenderBox::updateLayerTransform()
618 {
619     // Transform-origin depends on box size, so we need to update the layer transform after layout.
620     if (hasLayer())
621         layer()->updateTransform();
622 }
623
624 LayoutUnit RenderBox::constrainLogicalWidthInFragmentByMinMax(LayoutUnit logicalWidth, LayoutUnit availableWidth, RenderBlock& cb, RenderFragmentContainer* fragment) const
625 {
626     const RenderStyle& styleToUse = style();
627     if (!styleToUse.logicalMaxWidth().isUndefined())
628         logicalWidth = std::min(logicalWidth, computeLogicalWidthInFragmentUsing(MaxSize, styleToUse.logicalMaxWidth(), availableWidth, cb, fragment));
629     return std::max(logicalWidth, computeLogicalWidthInFragmentUsing(MinSize, styleToUse.logicalMinWidth(), availableWidth, cb, fragment));
630 }
631
632 LayoutUnit RenderBox::constrainLogicalHeightByMinMax(LayoutUnit logicalHeight, std::optional<LayoutUnit> intrinsicContentHeight) const
633 {
634     const RenderStyle& styleToUse = style();
635     if (!styleToUse.logicalMaxHeight().isUndefined()) {
636         if (std::optional<LayoutUnit> maxH = computeLogicalHeightUsing(MaxSize, styleToUse.logicalMaxHeight(), intrinsicContentHeight))
637             logicalHeight = std::min(logicalHeight, maxH.value());
638     }
639     if (std::optional<LayoutUnit> computedLogicalHeight = computeLogicalHeightUsing(MinSize, styleToUse.logicalMinHeight(), intrinsicContentHeight))
640         return std::max(logicalHeight, computedLogicalHeight.value());
641     return logicalHeight;
642 }
643
644 LayoutUnit RenderBox::constrainContentBoxLogicalHeightByMinMax(LayoutUnit logicalHeight, std::optional<LayoutUnit> intrinsicContentHeight) const
645 {
646     const RenderStyle& styleToUse = style();
647     if (!styleToUse.logicalMaxHeight().isUndefined()) {
648         if (std::optional<LayoutUnit> maxH = computeContentLogicalHeight(MaxSize, styleToUse.logicalMaxHeight(), intrinsicContentHeight))
649             logicalHeight = std::min(logicalHeight, maxH.value());
650     }
651     if (std::optional<LayoutUnit> computedContentLogicalHeight = computeContentLogicalHeight(MinSize, styleToUse.logicalMinHeight(), intrinsicContentHeight))
652         return std::max(logicalHeight, computedContentLogicalHeight.value());
653     return logicalHeight;
654 }
655
656 RoundedRect::Radii RenderBox::borderRadii() const
657 {
658     auto& style = this->style();
659     LayoutRect bounds = frameRect();
660
661     unsigned borderLeft = style.borderLeftWidth();
662     unsigned borderTop = style.borderTopWidth();
663     bounds.moveBy(LayoutPoint(borderLeft, borderTop));
664     bounds.contract(borderLeft + style.borderRightWidth(), borderTop + style.borderBottomWidth());
665     return style.getRoundedBorderFor(bounds).radii();
666 }
667
668 LayoutRect RenderBox::contentBoxRect() const
669 {
670     LayoutUnit x = borderLeft() + paddingLeft();
671     if (shouldPlaceBlockDirectionScrollbarOnLeft())
672         x += verticalScrollbarWidth();
673     LayoutUnit y = borderTop() + paddingTop();
674     return LayoutRect(x, y, contentWidth(), contentHeight());
675 }
676
677 IntRect RenderBox::absoluteContentBox() const
678 {
679     // This is wrong with transforms and flipped writing modes.
680     IntRect rect = snappedIntRect(contentBoxRect());
681     FloatPoint absPos = localToAbsolute();
682     rect.move(absPos.x(), absPos.y());
683     return rect;
684 }
685
686 FloatQuad RenderBox::absoluteContentQuad() const
687 {
688     LayoutRect rect = contentBoxRect();
689     return localToAbsoluteQuad(FloatRect(rect));
690 }
691
692 LayoutRect RenderBox::outlineBoundsForRepaint(const RenderLayerModelObject* repaintContainer, const RenderGeometryMap* geometryMap) const
693 {
694     LayoutRect box = borderBoundingBox();
695     adjustRectForOutlineAndShadow(box);
696
697     if (repaintContainer != this) {
698         FloatQuad containerRelativeQuad;
699         if (geometryMap)
700             containerRelativeQuad = geometryMap->mapToContainer(box, repaintContainer);
701         else
702             containerRelativeQuad = localToContainerQuad(FloatRect(box), repaintContainer);
703
704         box = LayoutRect(containerRelativeQuad.boundingBox());
705     }
706     
707     // FIXME: layoutDelta needs to be applied in parts before/after transforms and
708     // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
709     box.move(view().layoutDelta());
710
711     return LayoutRect(snapRectToDevicePixels(box, document().deviceScaleFactor()));
712 }
713
714 void RenderBox::addFocusRingRects(Vector<LayoutRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject*)
715 {
716     if (!size().isEmpty())
717         rects.append(LayoutRect(additionalOffset, size()));
718 }
719
720 int RenderBox::reflectionOffset() const
721 {
722     if (!style().boxReflect())
723         return 0;
724     if (style().boxReflect()->direction() == ReflectionLeft || style().boxReflect()->direction() == ReflectionRight)
725         return valueForLength(style().boxReflect()->offset(), borderBoxRect().width());
726     return valueForLength(style().boxReflect()->offset(), borderBoxRect().height());
727 }
728
729 LayoutRect RenderBox::reflectedRect(const LayoutRect& r) const
730 {
731     if (!style().boxReflect())
732         return LayoutRect();
733
734     LayoutRect box = borderBoxRect();
735     LayoutRect result = r;
736     switch (style().boxReflect()->direction()) {
737         case ReflectionBelow:
738             result.setY(box.maxY() + reflectionOffset() + (box.maxY() - r.maxY()));
739             break;
740         case ReflectionAbove:
741             result.setY(box.y() - reflectionOffset() - box.height() + (box.maxY() - r.maxY()));
742             break;
743         case ReflectionLeft:
744             result.setX(box.x() - reflectionOffset() - box.width() + (box.maxX() - r.maxX()));
745             break;
746         case ReflectionRight:
747             result.setX(box.maxX() + reflectionOffset() + (box.maxX() - r.maxX()));
748             break;
749     }
750     return result;
751 }
752
753 bool RenderBox::fixedElementLaysOutRelativeToFrame(const FrameView& frameView) const
754 {
755     return style().position() == FixedPosition && container()->isRenderView() && frameView.fixedElementsLayoutRelativeToFrame();
756 }
757
758 bool RenderBox::includeVerticalScrollbarSize() const
759 {
760     return hasOverflowClip() && layer() && !layer()->hasOverlayScrollbars()
761         && (style().overflowY() == OSCROLL || style().overflowY() == OAUTO);
762 }
763
764 bool RenderBox::includeHorizontalScrollbarSize() const
765 {
766     return hasOverflowClip() && layer() && !layer()->hasOverlayScrollbars()
767         && (style().overflowX() == OSCROLL || style().overflowX() == OAUTO);
768 }
769
770 int RenderBox::verticalScrollbarWidth() const
771 {
772     return includeVerticalScrollbarSize() ? layer()->verticalScrollbarWidth() : 0;
773 }
774
775 int RenderBox::horizontalScrollbarHeight() const
776 {
777     return includeHorizontalScrollbarSize() ? layer()->horizontalScrollbarHeight() : 0;
778 }
779
780 int RenderBox::intrinsicScrollbarLogicalWidth() const
781 {
782     if (!hasOverflowClip())
783         return 0;
784
785     if (isHorizontalWritingMode() && (style().overflowY() == OSCROLL && !hasVerticalScrollbarWithAutoBehavior())) {
786         ASSERT(layer() && layer()->hasVerticalScrollbar());
787         return verticalScrollbarWidth();
788     }
789
790     if (!isHorizontalWritingMode() && (style().overflowX() == OSCROLL && !hasHorizontalScrollbarWithAutoBehavior())) {
791         ASSERT(layer() && layer()->hasHorizontalScrollbar());
792         return horizontalScrollbarHeight();
793     }
794
795     return 0;
796 }
797
798 bool RenderBox::scrollLayer(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement)
799 {
800     RenderLayer* boxLayer = layer();
801     if (boxLayer && boxLayer->scroll(direction, granularity, multiplier)) {
802         if (stopElement)
803             *stopElement = element();
804
805         return true;
806     }
807
808     return false;
809 }
810
811 bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement, RenderBox* startBox, const IntPoint& wheelEventAbsolutePoint)
812 {
813     if (scrollLayer(direction, granularity, multiplier, stopElement))
814         return true;
815
816     if (stopElement && *stopElement && *stopElement == element())
817         return true;
818
819     RenderBlock* nextScrollBlock = containingBlock();
820
821     if (nextScrollBlock && !nextScrollBlock->isRenderView())
822         return nextScrollBlock->scroll(direction, granularity, multiplier, stopElement, startBox, wheelEventAbsolutePoint);
823
824     return false;
825 }
826
827 bool RenderBox::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement)
828 {
829     bool scrolled = false;
830     
831     RenderLayer* l = layer();
832     if (l) {
833 #if PLATFORM(COCOA)
834         // On Mac only we reset the inline direction position when doing a document scroll (e.g., hitting Home/End).
835         if (granularity == ScrollByDocument)
836             scrolled = l->scroll(logicalToPhysical(ScrollInlineDirectionBackward, isHorizontalWritingMode(), style().isFlippedBlocksWritingMode()), ScrollByDocument, multiplier);
837 #endif
838         if (l->scroll(logicalToPhysical(direction, isHorizontalWritingMode(), style().isFlippedBlocksWritingMode()), granularity, multiplier))
839             scrolled = true;
840         
841         if (scrolled) {
842             if (stopElement)
843                 *stopElement = element();
844             return true;
845         }
846     }
847
848     if (stopElement && *stopElement && *stopElement == element())
849         return true;
850
851     RenderBlock* b = containingBlock();
852     if (b && !b->isRenderView())
853         return b->logicalScroll(direction, granularity, multiplier, stopElement);
854     return false;
855 }
856
857 bool RenderBox::canBeScrolledAndHasScrollableArea() const
858 {
859     return canBeProgramaticallyScrolled() && (hasHorizontalOverflow() || hasVerticalOverflow());
860 }
861
862 bool RenderBox::isScrollableOrRubberbandableBox() const
863 {
864     return canBeScrolledAndHasScrollableArea();
865 }
866
867 // FIXME: This is badly named. overflow:hidden can be programmatically scrolled, yet this returns false in that case.
868 bool RenderBox::canBeProgramaticallyScrolled() const
869 {
870     if (isRenderView())
871         return true;
872
873     if (!hasOverflowClip())
874         return false;
875
876     if (hasScrollableOverflowX() || hasScrollableOverflowY())
877         return true;
878
879     return element() && element()->hasEditableStyle();
880 }
881
882 bool RenderBox::usesCompositedScrolling() const
883 {
884     return hasOverflowClip() && hasLayer() && layer()->usesCompositedScrolling();
885 }
886
887 void RenderBox::autoscroll(const IntPoint& position)
888 {
889     if (layer())
890         layer()->autoscroll(position);
891 }
892
893 // There are two kinds of renderer that can autoscroll.
894 bool RenderBox::canAutoscroll() const
895 {
896     if (isRenderView())
897         return view().frameView().isScrollable();
898
899     // Check for a box that can be scrolled in its own right.
900     if (canBeScrolledAndHasScrollableArea())
901         return true;
902
903     return false;
904 }
905
906 // If specified point is in border belt, returned offset denotes direction of
907 // scrolling.
908 IntSize RenderBox::calculateAutoscrollDirection(const IntPoint& windowPoint) const
909 {
910     IntRect box(absoluteBoundingBoxRect());
911     box.moveBy(view().frameView().scrollPosition());
912     IntRect windowBox = view().frameView().contentsToWindow(box);
913
914     IntPoint windowAutoscrollPoint = windowPoint;
915
916     if (windowAutoscrollPoint.x() < windowBox.x() + autoscrollBeltSize)
917         windowAutoscrollPoint.move(-autoscrollBeltSize, 0);
918     else if (windowAutoscrollPoint.x() > windowBox.maxX() - autoscrollBeltSize)
919         windowAutoscrollPoint.move(autoscrollBeltSize, 0);
920
921     if (windowAutoscrollPoint.y() < windowBox.y() + autoscrollBeltSize)
922         windowAutoscrollPoint.move(0, -autoscrollBeltSize);
923     else if (windowAutoscrollPoint.y() > windowBox.maxY() - autoscrollBeltSize)
924         windowAutoscrollPoint.move(0, autoscrollBeltSize);
925
926     return windowAutoscrollPoint - windowPoint;
927 }
928
929 RenderBox* RenderBox::findAutoscrollable(RenderObject* renderer)
930 {
931     while (renderer && !(is<RenderBox>(*renderer) && downcast<RenderBox>(*renderer).canAutoscroll())) {
932         if (is<RenderView>(*renderer) && renderer->document().ownerElement())
933             renderer = renderer->document().ownerElement()->renderer();
934         else
935             renderer = renderer->parent();
936     }
937
938     return is<RenderBox>(renderer) ? downcast<RenderBox>(renderer) : nullptr;
939 }
940
941 void RenderBox::panScroll(const IntPoint& source)
942 {
943     if (layer())
944         layer()->panScrollFromPoint(source);
945 }
946
947 bool RenderBox::hasVerticalScrollbarWithAutoBehavior() const
948 {
949     bool overflowScrollActsLikeAuto = style().overflowY() == OSCROLL && !style().hasPseudoStyle(SCROLLBAR) && ScrollbarTheme::theme().usesOverlayScrollbars();
950     return hasOverflowClip() && (style().overflowY() == OAUTO || style().overflowY() == OOVERLAY || overflowScrollActsLikeAuto);
951 }
952
953 bool RenderBox::hasHorizontalScrollbarWithAutoBehavior() const
954 {
955     bool overflowScrollActsLikeAuto = style().overflowX() == OSCROLL && !style().hasPseudoStyle(SCROLLBAR) && ScrollbarTheme::theme().usesOverlayScrollbars();
956     return hasOverflowClip() && (style().overflowX() == OAUTO || style().overflowX() == OOVERLAY || overflowScrollActsLikeAuto);
957 }
958
959 bool RenderBox::needsPreferredWidthsRecalculation() const
960 {
961     return style().paddingStart().isPercentOrCalculated() || style().paddingEnd().isPercentOrCalculated();
962 }
963
964 ScrollPosition RenderBox::scrollPosition() const
965 {
966     if (!hasOverflowClip())
967         return { 0, 0 };
968
969     ASSERT(hasLayer());
970     return layer()->scrollPosition();
971 }
972
973 LayoutSize RenderBox::cachedSizeForOverflowClip() const
974 {
975     ASSERT(hasOverflowClip());
976     ASSERT(hasLayer());
977     return layer()->size();
978 }
979
980 void RenderBox::applyCachedClipAndScrollPositionForRepaint(LayoutRect& paintRect) const
981 {
982     flipForWritingMode(paintRect);
983     paintRect.moveBy(-scrollPosition()); // For overflow:auto/scroll/hidden.
984
985     // Do not clip scroll layer contents to reduce the number of repaints while scrolling.
986     if (usesCompositedScrolling()) {
987         flipForWritingMode(paintRect);
988         return;
989     }
990
991     // height() is inaccurate if we're in the middle of a layout of this RenderBox, so use the
992     // layer's size instead. Even if the layer's size is wrong, the layer itself will repaint
993     // anyway if its size does change.
994     LayoutRect clipRect(LayoutPoint(), cachedSizeForOverflowClip());
995     paintRect = intersection(paintRect, clipRect);
996     flipForWritingMode(paintRect);
997 }
998
999 void RenderBox::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
1000 {
1001     minLogicalWidth = minPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
1002     maxLogicalWidth = maxPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
1003 }
1004
1005 LayoutUnit RenderBox::minPreferredLogicalWidth() const
1006 {
1007     if (preferredLogicalWidthsDirty()) {
1008 #ifndef NDEBUG
1009         SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox*>(this));
1010 #endif
1011         const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
1012     }
1013         
1014     return m_minPreferredLogicalWidth;
1015 }
1016
1017 LayoutUnit RenderBox::maxPreferredLogicalWidth() const
1018 {
1019     if (preferredLogicalWidthsDirty()) {
1020 #ifndef NDEBUG
1021         SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox*>(this));
1022 #endif
1023         const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
1024     }
1025         
1026     return m_maxPreferredLogicalWidth;
1027 }
1028
1029 bool RenderBox::hasOverrideLogicalContentHeight() const
1030 {
1031     return gOverrideHeightMap && gOverrideHeightMap->contains(this);
1032 }
1033
1034 bool RenderBox::hasOverrideLogicalContentWidth() const
1035 {
1036     return gOverrideWidthMap && gOverrideWidthMap->contains(this);
1037 }
1038
1039 void RenderBox::setOverrideLogicalContentHeight(LayoutUnit height)
1040 {
1041     if (!gOverrideHeightMap)
1042         gOverrideHeightMap = new OverrideSizeMap();
1043     gOverrideHeightMap->set(this, height);
1044 }
1045
1046 void RenderBox::setOverrideLogicalContentWidth(LayoutUnit width)
1047 {
1048     if (!gOverrideWidthMap)
1049         gOverrideWidthMap = new OverrideSizeMap();
1050     gOverrideWidthMap->set(this, width);
1051 }
1052
1053 void RenderBox::clearOverrideLogicalContentHeight()
1054 {
1055     if (gOverrideHeightMap)
1056         gOverrideHeightMap->remove(this);
1057 }
1058
1059 void RenderBox::clearOverrideLogicalContentWidth()
1060 {
1061     if (gOverrideWidthMap)
1062         gOverrideWidthMap->remove(this);
1063 }
1064
1065 void RenderBox::clearOverrideSize()
1066 {
1067     clearOverrideLogicalContentHeight();
1068     clearOverrideLogicalContentWidth();
1069 }
1070
1071 LayoutUnit RenderBox::overrideLogicalContentWidth() const
1072 {
1073     ASSERT(hasOverrideLogicalContentWidth());
1074     return gOverrideWidthMap->get(this);
1075 }
1076
1077 LayoutUnit RenderBox::overrideLogicalContentHeight() const
1078 {
1079     ASSERT(hasOverrideLogicalContentHeight());
1080     return gOverrideHeightMap->get(this);
1081 }
1082
1083 std::optional<LayoutUnit> RenderBox::overrideContainingBlockContentLogicalWidth() const
1084 {
1085     ASSERT(hasOverrideContainingBlockLogicalWidth());
1086     return gOverrideContainingBlockLogicalWidthMap->get(this);
1087 }
1088
1089 std::optional<LayoutUnit> RenderBox::overrideContainingBlockContentLogicalHeight() const
1090 {
1091     ASSERT(hasOverrideContainingBlockLogicalHeight());
1092     return gOverrideContainingBlockLogicalHeightMap->get(this);
1093 }
1094
1095 bool RenderBox::hasOverrideContainingBlockLogicalWidth() const
1096 {
1097     return gOverrideContainingBlockLogicalWidthMap && gOverrideContainingBlockLogicalWidthMap->contains(this);
1098 }
1099
1100 bool RenderBox::hasOverrideContainingBlockLogicalHeight() const
1101 {
1102     return gOverrideContainingBlockLogicalHeightMap && gOverrideContainingBlockLogicalHeightMap->contains(this);
1103 }
1104
1105 void RenderBox::setOverrideContainingBlockContentLogicalWidth(std::optional<LayoutUnit> logicalWidth)
1106 {
1107     if (!gOverrideContainingBlockLogicalWidthMap)
1108         gOverrideContainingBlockLogicalWidthMap = new OverrideOptionalSizeMap;
1109     gOverrideContainingBlockLogicalWidthMap->set(this, logicalWidth);
1110 }
1111
1112 void RenderBox::setOverrideContainingBlockContentLogicalHeight(std::optional<LayoutUnit> logicalHeight)
1113 {
1114     if (!gOverrideContainingBlockLogicalHeightMap)
1115         gOverrideContainingBlockLogicalHeightMap = new OverrideOptionalSizeMap;
1116     gOverrideContainingBlockLogicalHeightMap->set(this, logicalHeight);
1117 }
1118
1119 void RenderBox::clearContainingBlockOverrideSize()
1120 {
1121     if (gOverrideContainingBlockLogicalWidthMap)
1122         gOverrideContainingBlockLogicalWidthMap->remove(this);
1123     clearOverrideContainingBlockContentLogicalHeight();
1124 }
1125
1126 void RenderBox::clearOverrideContainingBlockContentLogicalHeight()
1127 {
1128     if (gOverrideContainingBlockLogicalHeightMap)
1129         gOverrideContainingBlockLogicalHeightMap->remove(this);
1130 }
1131
1132 LayoutUnit RenderBox::adjustBorderBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1133 {
1134     LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
1135     if (style().boxSizing() == CONTENT_BOX)
1136         return width + bordersPlusPadding;
1137     return std::max(width, bordersPlusPadding);
1138 }
1139
1140 LayoutUnit RenderBox::adjustBorderBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1141 {
1142     LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
1143     if (style().boxSizing() == CONTENT_BOX)
1144         return height + bordersPlusPadding;
1145     return std::max(height, bordersPlusPadding);
1146 }
1147
1148 LayoutUnit RenderBox::adjustContentBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1149 {
1150     if (style().boxSizing() == BORDER_BOX)
1151         width -= borderAndPaddingLogicalWidth();
1152     return std::max<LayoutUnit>(0, width);
1153 }
1154
1155 LayoutUnit RenderBox::adjustContentBoxLogicalHeightForBoxSizing(std::optional<LayoutUnit> height) const
1156 {
1157     if (!height)
1158         return 0;
1159     LayoutUnit result = height.value();
1160     if (style().boxSizing() == BORDER_BOX)
1161         result -= borderAndPaddingLogicalHeight();
1162     return std::max(LayoutUnit(), result);
1163 }
1164
1165 // Hit Testing
1166 bool RenderBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
1167 {
1168     LayoutPoint adjustedLocation = accumulatedOffset + location();
1169
1170     // Check kids first.
1171     for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
1172         if (!child->hasLayer() && child->nodeAtPoint(request, result, locationInContainer, adjustedLocation, action)) {
1173             updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1174             return true;
1175         }
1176     }
1177
1178     // Check our bounds next. For this purpose always assume that we can only be hit in the
1179     // foreground phase (which is true for replaced elements like images).
1180     LayoutRect boundsRect = borderBoxRectInFragment(nullptr);
1181     boundsRect.moveBy(adjustedLocation);
1182     if (visibleToHitTesting() && action == HitTestForeground && locationInContainer.intersects(boundsRect)) {
1183         updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1184         if (result.addNodeToListBasedTestResult(element(), request, locationInContainer, boundsRect) == HitTestProgress::Stop)
1185             return true;
1186     }
1187
1188     return false;
1189 }
1190
1191 // --------------------- painting stuff -------------------------------
1192
1193 void RenderBox::paintRootBoxFillLayers(const PaintInfo& paintInfo)
1194 {
1195     ASSERT(isDocumentElementRenderer());
1196     if (paintInfo.skipRootBackground())
1197         return;
1198
1199     auto* rootBackgroundRenderer = view().rendererForRootBackground();
1200     if (!rootBackgroundRenderer)
1201         return;
1202
1203     auto& style = rootBackgroundRenderer->style();
1204     auto color = style.visitedDependentColor(CSSPropertyBackgroundColor);
1205     paintFillLayers(paintInfo, color, style.backgroundLayers(), view().backgroundRect(), BackgroundBleedNone, CompositeSourceOver, rootBackgroundRenderer);
1206 }
1207
1208 BackgroundBleedAvoidance RenderBox::determineBackgroundBleedAvoidance(GraphicsContext& context) const
1209 {
1210     if (context.paintingDisabled())
1211         return BackgroundBleedNone;
1212
1213     const RenderStyle& style = this->style();
1214
1215     if (!style.hasBackground() || !style.hasBorder() || !style.hasBorderRadius() || borderImageIsLoadedAndCanBeRendered())
1216         return BackgroundBleedNone;
1217
1218     AffineTransform ctm = context.getCTM();
1219     FloatSize contextScaling(static_cast<float>(ctm.xScale()), static_cast<float>(ctm.yScale()));
1220
1221     // Because RoundedRect uses IntRect internally the inset applied by the 
1222     // BackgroundBleedShrinkBackground strategy cannot be less than one integer
1223     // layout coordinate, even with subpixel layout enabled. To take that into
1224     // account, we clamp the contextScaling to 1.0 for the following test so
1225     // that borderObscuresBackgroundEdge can only return true if the border
1226     // widths are greater than 2 in both layout coordinates and screen
1227     // coordinates.
1228     // This precaution will become obsolete if RoundedRect is ever promoted to
1229     // a sub-pixel representation.
1230     if (contextScaling.width() > 1) 
1231         contextScaling.setWidth(1);
1232     if (contextScaling.height() > 1) 
1233         contextScaling.setHeight(1);
1234
1235     if (borderObscuresBackgroundEdge(contextScaling))
1236         return BackgroundBleedShrinkBackground;
1237     if (!style.hasAppearance() && borderObscuresBackground() && backgroundHasOpaqueTopLayer())
1238         return BackgroundBleedBackgroundOverBorder;
1239
1240     return BackgroundBleedUseTransparencyLayer;
1241 }
1242
1243 void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1244 {
1245     if (!paintInfo.shouldPaintWithinRoot(*this))
1246         return;
1247
1248     LayoutRect paintRect = borderBoxRectInFragment(nullptr);
1249     paintRect.moveBy(paintOffset);
1250     adjustBorderBoxRectForPainting(paintRect);
1251
1252 #if PLATFORM(IOS)
1253     // Workaround for <rdar://problem/6209763>. Force the painting bounds of checkboxes and radio controls to be square.
1254     if (style().appearance() == CheckboxPart || style().appearance() == RadioPart) {
1255         int width = std::min(paintRect.width(), paintRect.height());
1256         int height = width;
1257         paintRect = IntRect(paintRect.x(), paintRect.y() + (this->height() - height) / 2, width, height); // Vertically center the checkbox, like on desktop
1258     }
1259 #endif
1260     BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context());
1261
1262     // FIXME: Should eventually give the theme control over whether the box shadow should paint, since controls could have
1263     // custom shadows of their own.
1264     if (!boxShadowShouldBeAppliedToBackground(paintRect.location(), bleedAvoidance))
1265         paintBoxShadow(paintInfo, paintRect, style(), Normal);
1266
1267     GraphicsContextStateSaver stateSaver(paintInfo.context(), false);
1268     if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
1269         // To avoid the background color bleeding out behind the border, we'll render background and border
1270         // into a transparency layer, and then clip that in one go (which requires setting up the clip before
1271         // beginning the layer).
1272         stateSaver.save();
1273         paintInfo.context().clipRoundedRect(style().getRoundedBorderFor(paintRect).pixelSnappedRoundedRectForPainting(document().deviceScaleFactor()));
1274         paintInfo.context().beginTransparencyLayer(1);
1275     }
1276
1277     // If we have a native theme appearance, paint that before painting our background.
1278     // The theme will tell us whether or not we should also paint the CSS background.
1279     bool borderOrBackgroundPaintingIsNeeded = true;
1280     if (style().hasAppearance()) {
1281         ControlStates* controlStates = controlStatesForRenderer(*this);
1282         borderOrBackgroundPaintingIsNeeded = theme().paint(*this, *controlStates, paintInfo, paintRect);
1283         if (controlStates->needsRepaint())
1284             view().scheduleLazyRepaint(*this);
1285     }
1286
1287     if (borderOrBackgroundPaintingIsNeeded) {
1288         if (bleedAvoidance == BackgroundBleedBackgroundOverBorder)
1289             paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1290
1291         paintBackground(paintInfo, paintRect, bleedAvoidance);
1292
1293         if (style().hasAppearance())
1294             theme().paintDecorations(*this, paintInfo, paintRect);
1295     }
1296     paintBoxShadow(paintInfo, paintRect, style(), Inset);
1297
1298     // The theme will tell us whether or not we should also paint the CSS border.
1299     if (bleedAvoidance != BackgroundBleedBackgroundOverBorder && (!style().hasAppearance() || (borderOrBackgroundPaintingIsNeeded && theme().paintBorderOnly(*this, paintInfo, paintRect))) && style().hasVisibleBorderDecoration())
1300         paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1301
1302     if (bleedAvoidance == BackgroundBleedUseTransparencyLayer)
1303         paintInfo.context().endTransparencyLayer();
1304 }
1305
1306 bool RenderBox::paintsOwnBackground() const
1307 {
1308     if (isBody()) {
1309         // The <body> only paints its background if the root element has defined a background independent of the body,
1310         // or if the <body>'s parent is not the document element's renderer (e.g. inside SVG foreignObject).
1311         auto documentElementRenderer = document().documentElement()->renderer();
1312         return !documentElementRenderer
1313             || documentElementRenderer->hasBackground()
1314             || (documentElementRenderer != parent());
1315     }
1316     
1317     return true;
1318 }
1319
1320 void RenderBox::paintBackground(const PaintInfo& paintInfo, const LayoutRect& paintRect, BackgroundBleedAvoidance bleedAvoidance)
1321 {
1322     if (isDocumentElementRenderer()) {
1323         paintRootBoxFillLayers(paintInfo);
1324         return;
1325     }
1326
1327     if (!paintsOwnBackground())
1328         return;
1329
1330     if (backgroundIsKnownToBeObscured(paintRect.location()) && !boxShadowShouldBeAppliedToBackground(paintRect.location(), bleedAvoidance))
1331         return;
1332
1333     paintFillLayers(paintInfo, style().visitedDependentColor(CSSPropertyBackgroundColor), style().backgroundLayers(), paintRect, bleedAvoidance);
1334 }
1335
1336 bool RenderBox::getBackgroundPaintedExtent(const LayoutPoint& paintOffset, LayoutRect& paintedExtent) const
1337 {
1338     ASSERT(hasBackground());
1339     LayoutRect backgroundRect = snappedIntRect(borderBoxRect());
1340
1341     Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1342     if (backgroundColor.isVisible()) {
1343         paintedExtent = backgroundRect;
1344         return true;
1345     }
1346
1347     auto& layers = style().backgroundLayers();
1348     if (!layers.image() || layers.next()) {
1349         paintedExtent =  backgroundRect;
1350         return true;
1351     }
1352
1353     auto geometry = calculateBackgroundImageGeometry(nullptr, layers, paintOffset, backgroundRect);
1354     paintedExtent = geometry.destRect();
1355     return !geometry.hasNonLocalGeometry();
1356 }
1357
1358 bool RenderBox::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
1359 {
1360     if (!paintsOwnBackground())
1361         return false;
1362
1363     Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1364     if (!backgroundColor.isOpaque())
1365         return false;
1366
1367     // If the element has appearance, it might be painted by theme.
1368     // We cannot be sure if theme paints the background opaque.
1369     // In this case it is safe to not assume opaqueness.
1370     // FIXME: May be ask theme if it paints opaque.
1371     if (style().hasAppearance())
1372         return false;
1373     // FIXME: Check the opaqueness of background images.
1374
1375     if (hasClip() || hasClipPath())
1376         return false;
1377
1378     // FIXME: Use rounded rect if border radius is present.
1379     if (style().hasBorderRadius())
1380         return false;
1381     
1382     // FIXME: The background color clip is defined by the last layer.
1383     if (style().backgroundLayers().next())
1384         return false;
1385     LayoutRect backgroundRect;
1386     switch (style().backgroundClip()) {
1387     case BorderFillBox:
1388         backgroundRect = borderBoxRect();
1389         break;
1390     case PaddingFillBox:
1391         backgroundRect = paddingBoxRect();
1392         break;
1393     case ContentFillBox:
1394         backgroundRect = contentBoxRect();
1395         break;
1396     default:
1397         break;
1398     }
1399     return backgroundRect.contains(localRect);
1400 }
1401
1402 static bool isCandidateForOpaquenessTest(const RenderBox& childBox)
1403 {
1404     const RenderStyle& childStyle = childBox.style();
1405     if (childStyle.position() != StaticPosition && childBox.containingBlock() != childBox.parent())
1406         return false;
1407     if (childStyle.visibility() != VISIBLE)
1408         return false;
1409     if (childStyle.shapeOutside())
1410         return false;
1411     if (!childBox.width() || !childBox.height())
1412         return false;
1413     if (RenderLayer* childLayer = childBox.layer()) {
1414         if (childLayer->isComposited())
1415             return false;
1416         // FIXME: Deal with z-index.
1417         if (!childStyle.hasAutoZIndex())
1418             return false;
1419         if (childLayer->hasTransform() || childLayer->isTransparent() || childLayer->hasFilter())
1420             return false;
1421         if (!childBox.scrollPosition().isZero())
1422             return false;
1423     }
1424     return true;
1425 }
1426
1427 bool RenderBox::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const
1428 {
1429     if (!maxDepthToTest)
1430         return false;
1431     for (auto& childBox : childrenOfType<RenderBox>(*this)) {
1432         if (!isCandidateForOpaquenessTest(childBox))
1433             continue;
1434         LayoutPoint childLocation = childBox.location();
1435         if (childBox.isRelPositioned())
1436             childLocation.move(childBox.relativePositionOffset());
1437         LayoutRect childLocalRect = localRect;
1438         childLocalRect.moveBy(-childLocation);
1439         if (childLocalRect.y() < 0 || childLocalRect.x() < 0) {
1440             // If there is unobscured area above/left of a static positioned box then the rect is probably not covered.
1441             if (childBox.style().position() == StaticPosition)
1442                 return false;
1443             continue;
1444         }
1445         if (childLocalRect.maxY() > childBox.height() || childLocalRect.maxX() > childBox.width())
1446             continue;
1447         if (childBox.backgroundIsKnownToBeOpaqueInRect(childLocalRect))
1448             return true;
1449         if (childBox.foregroundIsKnownToBeOpaqueInRect(childLocalRect, maxDepthToTest - 1))
1450             return true;
1451     }
1452     return false;
1453 }
1454
1455 bool RenderBox::computeBackgroundIsKnownToBeObscured(const LayoutPoint& paintOffset)
1456 {
1457     // Test to see if the children trivially obscure the background.
1458     // FIXME: This test can be much more comprehensive.
1459     if (!hasBackground())
1460         return false;
1461     // Table and root background painting is special.
1462     if (isTable() || isDocumentElementRenderer())
1463         return false;
1464
1465     LayoutRect backgroundRect;
1466     if (!getBackgroundPaintedExtent(paintOffset, backgroundRect))
1467         return false;
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().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().layoutStateEnabled() && !repaintContainer) {
1930         LayoutState* layoutState = view().layoutState();
1931         LayoutSize offset = layoutState->m_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 = style().position() == FixedPosition;
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 = style().position() == FixedPosition;
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 = style().position() == FixedPosition;
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& renderer, const LayoutPoint&, bool* offsetDependsOnPoint) const
2026 {
2027     // A fragment "has" boxes inside it without being their container. 
2028     ASSERT(&renderer == container() || is<RenderFragmentContainer>(renderer));
2029
2030     LayoutSize offset;    
2031     if (isInFlowPositioned())
2032         offset += offsetForInFlowPosition();
2033
2034     if (!isInline() || isReplaced())
2035         offset += topLeftLocationOffset();
2036
2037     if (is<RenderBox>(renderer))
2038         offset -= toLayoutSize(downcast<RenderBox>(renderer).scrollPosition());
2039
2040     if (style().position() == AbsolutePosition && renderer.isInFlowPositioned() && is<RenderInline>(renderer))
2041         offset += downcast<RenderInline>(renderer).offsetForInFlowPositionedInline(this);
2042
2043     if (offsetDependsOnPoint)
2044         *offsetDependsOnPoint |= is<RenderFragmentedFlow>(renderer);
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().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     // LayoutState is only valid for root-relative, non-fixed position repainting
2145     if (view().layoutStateEnabled() && !repaintContainer && styleToUse.position() != FixedPosition) {
2146         LayoutState* layoutState = view().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->m_paintOffset);
2157         if (layoutState->m_clipped)
2158             adjustedRect.intersect(layoutState->m_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().layoutPending() && view().frameView().layoutRoot() == 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         }
2989         FALLTHROUGH;
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                 LayoutUnit newHeight = block.adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3087                 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, newHeight));
3088             }
3089             
3090             // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
3091             // containing block's block-flow.
3092             // https://bugs.webkit.org/show_bug.cgi?id=46496
3093             LayoutUnit availableHeight;
3094             if (isOutOfFlowPositioned())
3095                 availableHeight = containingBlockLogicalHeightForPositioned(downcast<RenderBoxModelObject>(*container));
3096             else if (stretchedHeight)
3097                 availableHeight = stretchedHeight.value();
3098             else {
3099                 availableHeight = containingBlockLogicalHeightForContent(IncludeMarginBorderPadding);
3100                 // It is necessary to use the border-box to match WinIE's broken
3101                 // box model.  This is essential for sizing inside
3102                 // table cells using percentage heights.
3103                 // FIXME: This needs to be made block-flow-aware.  If the cell and image are perpendicular block-flows, this isn't right.
3104                 // https://bugs.webkit.org/show_bug.cgi?id=46997
3105                 while (container && !is<RenderView>(*container)
3106                     && (container->style().logicalHeight().isAuto() || container->style().logicalHeight().isPercentOrCalculated())) {
3107                     if (container->isTableCell()) {
3108                         // Don't let table cells squeeze percent-height replaced elements
3109                         // <http://bugs.webkit.org/show_bug.cgi?id=15359>
3110                         availableHeight = std::max(availableHeight, intrinsicLogicalHeight());
3111                         return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight());
3112                     }
3113                     downcast<RenderBlock>(*container).addPercentHeightDescendant(const_cast<RenderBox&>(*this));
3114                     container = container->containingBlock();
3115                 }
3116             }
3117             return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight));
3118         }
3119         case MinContent:
3120         case MaxContent:
3121         case FitContent:
3122         case FillAvailable:
3123             return adjustContentBoxLogicalHeightForBoxSizing(computeIntrinsicLogicalContentHeightUsing(logicalHeight, intrinsicLogicalHeight(), borderAndPaddingLogicalHeight()));
3124         default:
3125             return intrinsicLogicalHeight();
3126     }
3127 }
3128
3129 LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const
3130 {
3131     return constrainLogicalHeightByMinMax(availableLogicalHeightUsing(style().logicalHeight(), heightType), std::nullopt);
3132 }
3133
3134 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const
3135 {
3136     // We need to stop here, since we don't want to increase the height of the table
3137     // artificially.  We're going to rely on this cell getting expanded to some new
3138     // height, and then when we lay out again we'll use the calculation below.
3139     if (isTableCell() && (h.isAuto() || h.isPercentOrCalculated())) {
3140         if (hasOverrideLogicalContentHeight())
3141             return overrideLogicalContentHeight();
3142         return logicalHeight() - borderAndPaddingLogicalHeight();
3143     }
3144
3145     if (isFlexItem()) {
3146         auto& flexBox = downcast<RenderFlexibleBox>(*parent());
3147         auto stretchedHeight = flexBox.childLogicalHeightForPercentageResolution(*this);
3148         if (stretchedHeight)
3149             return stretchedHeight.value();
3150     }
3151
3152     if (h.isPercentOrCalculated() && isOutOfFlowPositioned() && !isRenderFragmentedFlow()) {
3153         // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3154         LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(*containingBlock());
3155         return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight));
3156     }
3157
3158     if (std::optional<LayoutUnit> heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(MainOrPreferredSize, h, std::nullopt))
3159         return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
3160
3161     // FIXME: Check logicalTop/logicalBottom here to correctly handle vertical writing-mode.
3162     // https://bugs.webkit.org/show_bug.cgi?id=46500
3163     if (is<RenderBlock>(*this) && isOutOfFlowPositioned() && style().height().isAuto() && !(style().top().isAuto() || style().bottom().isAuto())) {
3164         RenderBlock& block = const_cast<RenderBlock&>(downcast<RenderBlock>(*this));
3165         auto computedValues = block.computeLogicalHeight(block.logicalHeight(), 0);
3166         LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3167         return adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3168     }
3169
3170     // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3171     LayoutUnit availableHeight = containingBlockLogicalHeightForContent(heightType);
3172     if (heightType == ExcludeMarginBorderPadding) {
3173         // FIXME: Margin collapsing hasn't happened yet, so this incorrectly removes collapsed margins.
3174         availableHeight -= marginBefore() + marginAfter() + borderAndPaddingLogicalHeight();
3175     }
3176     return availableHeight;
3177 }
3178
3179 void RenderBox::computeBlockDirectionMargins(const RenderBlock& containingBlock, LayoutUnit& marginBefore, LayoutUnit& marginAfter) const
3180 {
3181     if (isTableCell()) {
3182         // FIXME: Not right if we allow cells to have different directionality than the table.  If we do allow this, though,
3183         // we may just do it with an extra anonymous block inside the cell.
3184         marginBefore = 0;
3185         marginAfter = 0;
3186         return;
3187     }
3188
3189     // Margins are calculated with respect to the logical width of
3190     // the containing block (8.3)
3191     LayoutUnit cw = containingBlockLogicalWidthForContent();
3192     const RenderStyle& containingBlockStyle = containingBlock.style();
3193     marginBefore = minimumValueForLength(style().marginBeforeUsing(&containingBlockStyle), cw);
3194     marginAfter = minimumValueForLength(style().marginAfterUsing(&containingBlockStyle), cw);
3195 }
3196
3197 void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock& containingBlock)
3198 {
3199     LayoutUnit marginBefore;
3200     LayoutUnit marginAfter;
3201     computeBlockDirectionMargins(containingBlock, marginBefore, marginAfter);
3202     containingBlock.setMarginBeforeForChild(*this, marginBefore);
3203     containingBlock.setMarginAfterForChild(*this, marginAfter);
3204 }
3205
3206 LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject& containingBlock, RenderFragmentContainer* fragment, bool checkForPerpendicularWritingMode) const
3207 {
3208     if (checkForPerpendicularWritingMode && containingBlock.isHorizontalWritingMode() != isHorizontalWritingMode())
3209         return containingBlockLogicalHeightForPositioned(containingBlock, false);
3210
3211     if (hasOverrideContainingBlockLogicalWidth()) {
3212         if (auto overrideLogicalWidth = overrideContainingBlockContentLogicalWidth())
3213             return overrideLogicalWidth.value();
3214     }
3215
3216     if (is<RenderBox>(containingBlock)) {
3217         bool isFixedPosition = style().position() == FixedPosition;
3218
3219         RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
3220         if (!fragmentedFlow) {
3221             if (isFixedPosition && is<RenderView>(containingBlock))
3222                 return downcast<RenderView>(containingBlock).clientLogicalWidthForFixedPosition();
3223
3224             return downcast<RenderBox>(containingBlock).clientLogicalWidth();
3225         }
3226
3227         if (!is<RenderBlock>(containingBlock))
3228             return downcast<RenderBox>(containingBlock).clientLogicalWidth();
3229
3230         const RenderBlock& cb = downcast<RenderBlock>(containingBlock);
3231         RenderBoxFragmentInfo* boxInfo = nullptr;
3232         if (!fragment) {
3233             if (is<RenderFragmentedFlow>(containingBlock) && !checkForPerpendicularWritingMode)
3234                 return downcast<RenderFragmentedFlow>(containingBlock).contentLogicalWidthOfFirstFragment();
3235             if (isWritingModeRoot()) {
3236                 LayoutUnit cbPageOffset = cb.offsetFromLogicalTopOfFirstPage();
3237                 RenderFragmentContainer* cbFragment = cb.fragmentAtBlockOffset(cbPageOffset);
3238                 if (cbFragment)
3239                     boxInfo = cb.renderBoxFragmentInfo(cbFragment);
3240             }
3241         } else if (fragmentedFlow->isHorizontalWritingMode() == containingBlock.isHorizontalWritingMode()) {
3242             RenderFragmentContainer* containingBlockFragment = cb.clampToStartAndEndFragments(fragment);
3243             boxInfo = cb.renderBoxFragmentInfo(containingBlockFragment);
3244         }
3245         return (boxInfo) ? std::max<LayoutUnit>(0, cb.clientLogicalWidth() - (cb.logicalWidth() - boxInfo->logicalWidth())) : cb.clientLogicalWidth();
3246     }
3247
3248     ASSERT(containingBlock.isInFlowPositioned());
3249
3250     const auto& flow = downcast<RenderInline>(containingBlock);
3251     InlineFlowBox* first = flow.firstLineBox();
3252     InlineFlowBox* last = flow.lastLineBox();
3253
3254     // If the containing block is empty, return a width of 0.
3255     if (!first || !last)
3256         return 0;
3257
3258     LayoutUnit fromLeft;
3259     LayoutUnit fromRight;
3260     if (containingBlock.style().isLeftToRightDirection()) {
3261         fromLeft = first->logicalLeft() + first->borderLogicalLeft();
3262         fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
3263     } else {
3264         fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
3265         fromLeft = last->logicalLeft() + last->borderLogicalLeft();
3266     }
3267
3268     return std::max<LayoutUnit>(0, fromRight - fromLeft);
3269 }
3270
3271 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject& containingBlock, bool checkForPerpendicularWritingMode) const
3272 {
3273     if (checkForPerpendicularWritingMode && containingBlock.isHorizontalWritingMode() != isHorizontalWritingMode())
3274         return containingBlockLogicalWidthForPositioned(containingBlock, nullptr, false);
3275
3276     if (hasOverrideContainingBlockLogicalHeight()) {
3277         if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight())
3278             return overrideLogicalHeight.value();
3279     }
3280
3281     if (containingBlock.isBox()) {
3282         bool isFixedPosition = style().position() == FixedPosition;
3283
3284         if (isFixedPosition && is<RenderView>(containingBlock))
3285             return downcast<RenderView>(containingBlock).clientLogicalHeightForFixedPosition();
3286
3287         const RenderBlock& cb = is<RenderBlock>(containingBlock) ? downcast<RenderBlock>(containingBlock) : *containingBlock.containingBlock();
3288         LayoutUnit result = cb.clientLogicalHeight();
3289         RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
3290         if (fragmentedFlow && is<RenderFragmentedFlow>(containingBlock) && fragmentedFlow->isHorizontalWritingMode() == containingBlock.isHorizontalWritingMode())
3291             return downcast<RenderFragmentedFlow>(containingBlock).contentLogicalHeightOfFirstFragment();
3292         return result;
3293     }
3294         
3295     ASSERT(containingBlock.isInFlowPositioned());
3296
3297     const auto& flow = downcast<RenderInline>(containingBlock);
3298     InlineFlowBox* first = flow.firstLineBox();
3299     InlineFlowBox* last = flow.lastLineBox();
3300
3301     // If the containing block is empty, return a height of 0.
3302     if (!first || !last)
3303         return 0;
3304
3305     LayoutUnit heightResult;
3306     LayoutRect boundingBox = flow.linesBoundingBox();
3307     if (containingBlock.isHorizontalWritingMode())
3308         heightResult = boundingBox.height();
3309     else
3310         heightResult = boundingBox.width();
3311     heightResult -= (containingBlock.borderBefore() + containingBlock.borderAfter());
3312     return heightResult;
3313 }
3314
3315 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject& containerBlock, LayoutUnit containerLogicalWidth, RenderFragmentContainer* fragment)
3316 {
3317     if (!logicalLeft.isAuto() || !logicalRight.isAuto())
3318         return;
3319
3320     RenderObject* parent = child->parent();
3321     TextDirection parentDirection = parent->style().direction();
3322
3323     // This method is using enclosingBox() which is wrong for absolutely
3324     // positioned grid items, as they rely on the grid area. So for grid items if
3325     // both "left" and "right" properties are "auto", we can consider that one of
3326     // them (depending on the direction) is simply "0".
3327     if (parent->isRenderGrid() && parent == child->containingBlock()) {
3328         if (parentDirection == LTR)
3329             logicalLeft.setValue(Fixed, 0);
3330         else
3331             logicalRight.setValue(Fixed, 0);
3332         return;
3333     }
3334
3335     // FIXME: The static distance computation has not been patched for mixed writing modes yet.
3336     if (parentDirection == LTR) {
3337         LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock.borderLogicalLeft();
3338         for (auto* current = parent; current && current != &containerBlock; current = current->container()) {
3339             if (!is<RenderBox>(*current))
3340                 continue;
3341             const auto& renderBox = downcast<RenderBox>(*current);
3342             staticPosition += renderBox.logicalLeft();
3343             if (renderBox.isInFlowPositioned())
3344                 staticPosition += renderBox.isHorizontalWritingMode() ? renderBox.offsetForInFlowPosition().width() : renderBox.offsetForInFlowPosition().height();
3345             if (fragment && is<RenderBlock>(*current)) {
3346                 const RenderBlock& currentBlock = downcast<RenderBlock>(*current);
3347                 fragment = currentBlock.clampToStartAndEndFragments(fragment);
3348                 RenderBoxFragmentInfo* boxInfo = currentBlock.renderBoxFragmentInfo(fragment);
3349                 if (boxInfo)
3350                     staticPosition += boxInfo->logicalLeft();
3351             }
3352         }
3353         logicalLeft.setValue(Fixed, staticPosition);
3354     } else {
3355         LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock.borderLogicalLeft();
3356         auto& enclosingBox = parent->enclosingBox();
3357         if (&enclosingBox != &containerBlock && containerBlock.isDescendantOf(&enclosingBox)) {
3358             logicalRight.setValue(Fixed, staticPosition);
3359             return;
3360         }
3361
3362         staticPosition -= enclosingBox.logicalWidth();
3363         for (const RenderElement* current = &enclosingBox; current; current = current->container()) {
3364             if (!is<RenderBox>(*current))
3365                 continue;
3366
3367             if (current != &containerBlock) {
3368                 auto& renderBox = downcast<RenderBox>(*current);
3369                 staticPosition -= renderBox.logicalLeft();
3370                 if (renderBox.isInFlowPositioned())
3371                     staticPosition -= renderBox.isHorizontalWritingMode() ? renderBox.offsetForInFlowPosition().width() : renderBox.offsetForInFlowPosition().height();
3372             }
3373             if (fragment && is<RenderBlock>(*current)) {
3374                 auto& currentBlock = downcast<RenderBlock>(*current);
3375                 fragment = currentBlock.clampToStartAndEndFragments(fragment);
3376                 RenderBoxFragmentInfo* boxInfo = currentBlock.renderBoxFragmentInfo(fragment);
3377                 if (boxInfo) {
3378                     if (current != &containerBlock)
3379                         staticPosition -= currentBlock.logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth());
3380                     if (current == &enclosingBox)
3381                         staticPosition += enclosingBox.logicalWidth() - boxInfo->logicalWidth();
3382                 }
3383             }
3384             if (current == &containerBlock)
3385                 break;
3386         }
3387         logicalRight.setValue(Fixed, staticPosition);
3388     }
3389 }
3390
3391 void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues, RenderFragmentContainer* fragment) const
3392 {
3393     if (isReplaced()) {
3394         // FIXME: Positioned replaced elements inside a flow thread are not working properly
3395         // with variable width fragments (see https://bugs.webkit.org/show_bug.cgi?id=69896 ).
3396         computePositionedLogicalWidthReplaced(computedValues);
3397         return;
3398     }
3399
3400     // QUESTIONS
3401     // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
3402     // the type 'static' in determining whether to calculate the static distance?
3403     // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
3404
3405     // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
3406     // than or less than the computed width().  Be careful of box-sizing and
3407     // percentage issues.
3408
3409     // The following is based off of the W3C Working Draft from April 11, 2006 of
3410     // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
3411     // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
3412     // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
3413     // correspond to text from the spec)
3414
3415
3416     // We don't use containingBlock(), since we may be positioned by an enclosing
3417     // relative positioned inline.
3418     const RenderBoxModelObject& containerBlock = downcast<RenderBoxModelObject>(*container());
3419     
3420     const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, fragment);
3421
3422     // Use the container block's direction except when calculating the static distance
3423     // This conforms with the reference results for abspos-replaced-width-margin-000.htm
3424     // of the CSS 2.1 test suite
3425     TextDirection containerDirection = containerBlock.style().direction();
3426
3427     bool isHorizontal = isHorizontalWritingMode();
3428     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
3429     const Length marginLogicalLeft = isHorizontal ? style().marginLeft() : style().marginTop();
3430     const Length marginLogicalRight = isHorizontal ? style().marginRight() : style().marginBottom();
3431
3432     Length logicalLeftLength = style().logicalLeft();
3433     Length logicalRightLength = style().logicalRight();
3434
3435     /*---------------------------------------------------------------------------*\
3436      * For the purposes of this section and the next, the term "static position"
3437      * (of an element) refers, roughly, to the position an element would have had
3438      * in the normal flow. More precisely:
3439      *
3440      * * The static position for 'left' is the distance from the left edge of the
3441      *   containing block to the left margin edge of a hypothetical box that would
3442      *   have been the first box of the element if its 'position' property had
3443      *   been 'static' and 'float' had been 'none'. The value is negative if the
3444      *   hypothetical box is to the left of the containing block.
3445      * * The static position for 'right' is the distance from the right edge of the
3446      *   containing block to the right margin edge of the same hypothetical box as
3447      *   above. The value is positive if the hypothetical box is to the left of the
3448      *   containing block's edge.
3449      *
3450      * But rather than actually calculating the dimensions of that hypothetical box,
3451      * user agents are free to make a guess at its probable position.
3452      *
3453      * For the purposes of calculating the static position, the containing block of
3454      * fixed positioned elements is the initial containing block instead of the
3455      * viewport, and all scrollable boxes should be assumed to be scrolled to their
3456      * origin.
3457     \*---------------------------------------------------------------------------*/
3458
3459     // see FIXME 1
3460     // Calculate the static distance if needed.
3461     computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth, fragment);
3462     
3463     // Calculate constraint equation values for 'width' case.
3464     computePositionedLogicalWidthUsing(MainOrPreferredSize, style().logicalWidth(), containerBlock, containerDirection,
3465                                        containerLogicalWidth, bordersPlusPadding,
3466                                        logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3467                                        computedValues);
3468
3469     // Calculate constraint equation values for 'max-width' case.
3470     if (!style().logicalMaxWidth().isUndefined()) {
3471         LogicalExtentComputedValues maxValues;
3472
3473         computePositionedLogicalWidthUsing(MaxSize, style().logicalMaxWidth(), containerBlock, containerDirection,
3474                                            containerLogicalWidth, bordersPlusPadding,
3475                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3476                                            maxValues);
3477
3478         if (computedValues.m_extent > maxValues.m_extent) {
3479             computedValues.m_extent = maxValues.m_extent;
3480             computedValues.m_position = maxValues.m_position;
3481             computedValues.m_margins.m_start = maxValues.m_margins.m_start;
3482             computedValues.m_margins.m_end = maxValues.m_margins.m_end;
3483         }
3484     }
3485
3486     // Calculate constraint equation values for 'min-width' case.
3487     if (!style().logicalMinWidth().isZero() || style().logicalMinWidth().isIntrinsic()) {
3488         LogicalExtentComputedValues minValues;
3489
3490         computePositionedLogicalWidthUsing(MinSize, style().logicalMinWidth(), containerBlock, containerDirection,
3491                                            containerLogicalWidth, bordersPlusPadding,
3492                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3493                                            minValues);
3494
3495         if (computedValues.m_extent < minValues.m_extent) {
3496             computedValues.m_extent = minValues.m_extent;
3497             computedValues.m_position = minValues.m_position;
3498             computedValues.m_margins.m_start = minValues.m_margins.m_start;
3499             computedValues.m_margins.m_end = minValues.m_margins.m_end;
3500         }
3501     }
3502
3503     computedValues.m_extent += bordersPlusPadding;
3504     if (is<RenderBox>(containerBlock)) {
3505         auto& containingBox = downcast<RenderBox>(containerBlock);
3506         if (containingBox.shouldPlaceBlockDirectionScrollbarOnLeft())
3507             computedValues.m_position += containingBox.verticalScrollbarWidth();
3508     }
3509     
3510     // Adjust logicalLeft if we need to for the flipped version of our writing mode in fragments.
3511     // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock.
3512     RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
3513     if (fragmentedFlow && !fragment && isWritingModeRoot() && isHorizontalWritingMode() == containerBlock.isHorizontalWritingMode() && is<RenderBlock>(containerBlock)) {
3514         ASSERT(containerBlock.canHaveBoxInfoInFragment());
3515         LayoutUnit logicalLeftPos = computedValues.m_position;
3516         const RenderBlock& renderBlock = downcast<RenderBlock>(containerBlock);
3517         LayoutUnit cbPageOffset = renderBlock.offsetFromLogicalTopOfFirstPage();
3518         RenderFragmentContainer* cbFragment = renderBlock.fragmentAtBlockOffset(cbPageOffset);
3519         if (cbFragment) {
3520             RenderBoxFragmentInfo* boxInfo = renderBlock.renderBoxFragmentInfo(cbFragment);
3521             if (boxInfo) {
3522                 logicalLeftPos += boxInfo->logicalLeft();
3523                 computedValues.m_position = logicalLeftPos;
3524             }
3525         }
3526     }
3527 }
3528
3529 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject& containerBlock, LayoutUnit containerLogicalWidth)
3530 {
3531     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3532     // 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.
3533     if (containerBlock.isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock.style().isFlippedBlocksWritingMode()) {
3534         logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
3535         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock.borderRight() : containerBlock.borderBottom());
3536     } else
3537         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock.borderLeft() : containerBlock.borderTop());
3538 }
3539
3540 void RenderBox::computePositionedLogicalWidthUsing(SizeType widthType, Length logicalWidth, const RenderBoxModelObject& containerBlock, TextDirection containerDirection,
3541                                                    LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
3542                                                    Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight,
3543                                                    LogicalExtentComputedValues& computedValues) const
3544 {
3545     ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto());
3546     if (widthType == MinSize && logicalWidth.isAuto())
3547         logicalWidth = Length(0, Fixed);
3548     else if (logicalWidth.isIntrinsic())
3549         logicalWidth = Length(computeIntrinsicLogicalWidthUsing(logicalWidth, containerLogicalWidth, bordersPlusPadding) - bordersPlusPadding, Fixed);
3550
3551     // 'left' and 'right' cannot both be 'auto' because one would of been
3552     // converted to the static position already
3553     ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
3554
3555     LayoutUnit logicalLeftValue = 0;
3556
3557     const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, nullptr, false);
3558
3559     bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
3560     bool logicalLeftIsAuto = logicalLeft.isAuto();
3561     bool logicalRightIsAuto = logicalRight.isAuto();
3562     LayoutUnit& marginLogicalLeftValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
3563     LayoutUnit& marginLogicalRightValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
3564
3565     if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3566         /*-----------------------------------------------------------------------*\
3567          * If none of the three is 'auto': If both 'margin-left' and 'margin-
3568          * right' are 'auto', solve the equation under the extra constraint that
3569          * the two margins get equal values, unless this would make them negative,
3570          * in which case when direction of the containing block is 'ltr' ('rtl'),
3571          * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
3572          * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
3573          * solve the equation for that value. If the values are over-constrained,
3574          * ignore the value for 'left' (in case the 'direction' property of the
3575          * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
3576          * and solve for that value.
3577         \*-----------------------------------------------------------------------*/
3578         // NOTE:  It is not necessary to solve for 'right' in the over constrained
3579         // case because the value is not used for any further calculations.
3580
3581         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3582         computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3583
3584         const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth) + bordersPlusPadding);
3585
3586         // Margins are now the only unknown
3587         if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
3588             // Both margins auto, solve for equality
3589             if (availableSpace >= 0) {
3590                 marginLogicalLeftValue = availableSpace / 2; // split the difference
3591                 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
3592             } else {
3593                 // Use the containing block's direction rather than the parent block's
3594                 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3595                 if (containerDirection == LTR) {
3596                     marginLogicalLeftValue = 0;
3597                     marginLogicalRightValue = availableSpace; // will be negative
3598                 } else {
3599                     marginLogicalLeftValue = availableSpace; // will be negative
3600                     marginLogicalRightValue = 0;
3601                 }
3602             }
3603         } else if (marginLogicalLeft.isAuto()) {
3604             // Solve for left margin
3605             marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3606             marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
3607         } else if (marginLogicalRight.isAuto()) {
3608             // Solve for right margin
3609             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3610             marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
3611         } else {
3612             // Over-constrained, solve for left if direction is RTL
3613             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3614             marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3615
3616             // Use the containing block's direction rather than the parent block's
3617             // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3618             if (containerDirection == RTL)
3619                 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
3620         }
3621     } else {
3622         /*--------------------------------------------------------------------*\
3623          * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
3624          * to 0, and pick the one of the following six rules that applies.
3625          *
3626          * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
3627          *    width is shrink-to-fit. Then solve for 'left'
3628          *
3629          *              OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3630          * ------------------------------------------------------------------
3631          * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
3632          *    the 'direction' property of the containing block is 'ltr' set
3633          *    'left' to the static position, otherwise set 'right' to the
3634          *    static position. Then solve for 'left' (if 'direction is 'rtl')
3635          *    or 'right' (if 'direction' is 'ltr').
3636          * ------------------------------------------------------------------
3637          *
3638          * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
3639          *    width is shrink-to-fit . Then solve for 'right'
3640          * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
3641          *    for 'left'
3642          * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
3643          *    for 'width'
3644          * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
3645          *    for 'right'
3646          *
3647          * Calculation of the shrink-to-fit width is similar to calculating the
3648          * width of a table cell using the automatic table layout algorithm.
3649          * Roughly: calculate the preferred width by formatting the content
3650          * without breaking lines other than where explicit line breaks occur,
3651          * and also calculate the preferred minimum width, e.g., by trying all
3652          * possible line breaks. CSS 2.1 does not define the exact algorithm.
3653          * Thirdly, calculate the available width: this is found by solving
3654          * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
3655          * to 0.
3656          *
3657          * Then the shrink-to-fit width is:
3658          * min(max(preferred minimum width, available width), preferred width).
3659         \*--------------------------------------------------------------------*/
3660         // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
3661         // because the value is not used for any further calculations.
3662
3663         // Calculate margins, 'auto' margins are ignored.
3664         marginLogicalLeftValue = minimumValueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3665         marginLogicalRightValue = minimumValueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3666
3667         const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
3668
3669         // FIXME: Is there a faster way to find the correct case?
3670         // Use rule/case that applies.
3671         if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3672             // RULE 1: (use shrink-to-fit for width, and solve of left)
3673             LayoutUnit logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3674
3675             // FIXME: would it be better to have shrink-to-fit in one step?
3676             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3677             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3678             LayoutUnit availableWidth = availableSpace - logicalRightValue;
3679             computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3680             logicalLeftValue = availableSpace - (computedValues.m_extent + logicalRightValue);
3681         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
3682             // RULE 3: (use shrink-to-fit for width, and no need solve of right)
3683             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3684
3685             // FIXME: would it be better to have shrink-to-fit in one step?
3686             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3687             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3688             LayoutUnit availableWidth = availableSpace - logicalLeftValue;
3689             computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3690         } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3691             // RULE 4: (solve for left)
3692             computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3693             logicalLeftValue = availableSpace - (computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth));
3694         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3695             // RULE 5: (solve for width)
3696             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3697             computedValues.m_extent = availableSpace - (logicalLeftValue + valueForLength(logicalRight, containerLogicalWidth));
3698         } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
3699             // RULE 6: (no need solve for right)
3700             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3701             computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3702         }
3703     }
3704
3705     // Use computed values to calculate the horizontal position.
3706
3707     // FIXME: This hack is needed to calculate the  logical left position for a 'rtl' relatively
3708     // positioned, inline because right now, it is using the logical left position
3709     // of the first line box when really it should use the last line box.  When
3710     // this is fixed elsewhere, this block should be removed.
3711     if (is<RenderInline>(containerBlock) && !containerBlock.style().isLeftToRightDirection()) {
3712         const auto& flow = downcast<RenderInline>(containerBlock);
3713         InlineFlowBox* firstLine = flow.firstLineBox();
3714         InlineFlowBox* lastLine = flow.lastLineBox();
3715         if (firstLine && lastLine && firstLine != lastLine) {
3716             computedValues.m_position = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
3717             return;
3718         }
3719     }
3720
3721     computedValues.m_position = logicalLeftValue + marginLogicalLeftValue;
3722     computeLogicalLeftPositionedOffset(computedValues.m_position, this, computedValues.m_extent, containerBlock, containerLogicalWidth);
3723 }
3724
3725 static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject& containerBlock)
3726 {
3727     if (!logicalTop.isAuto() || !logicalBottom.isAuto())
3728         return;
3729     
3730     // FIXME: The static distance computation has not been patched for mixed writing modes.
3731     LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock.borderBefore();
3732     for (RenderElement* container = child->parent(); container && container != &containerBlock; container = container->container()) {
3733         if (!is<RenderBox>(*container))
3734             continue;
3735         const auto& renderBox = downcast<RenderBox>(*container);
3736         if (!is<RenderTableRow>(renderBox))
3737             staticLogicalTop += renderBox.logicalTop();
3738         if (renderBox.isInFlowPositioned())
3739             staticLogicalTop += renderBox.isHorizontalWritingMode() ? renderBox.offsetForInFlowPosition().height() : renderBox.offsetForInFlowPosition().width();
3740     }
3741     logicalTop.setValue(Fixed, staticLogicalTop);
3742 }
3743
3744 void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& computedValues) const
3745 {
3746     if (isReplaced()) {
3747         computePositionedLogicalHeightReplaced(computedValues);
3748         return;
3749     }
3750
3751     // The following is based off of the W3C Working Draft from April 11, 2006 of
3752     // CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
3753     // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
3754     // (block-style-comments in this function and in computePositionedLogicalHeightUsing()
3755     // correspond to text from the spec)
3756
3757
3758     // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
3759     const RenderBoxModelObject& containerBlock = downcast<RenderBoxModelObject>(*container());
3760
3761     const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
3762
3763     const RenderStyle& styleToUse = style();
3764     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
3765     const Length marginBefore = styleToUse.marginBefore();
3766     const Length marginAfter = styleToUse.marginAfter();
3767     Length logicalTopLength = styleToUse.logicalTop();
3768     Length logicalBottomLength = styleToUse.logicalBottom();
3769
3770     /*---------------------------------------------------------------------------*\
3771      * For the purposes of this section and the next, the term "static position"
3772      * (of an element) refers, roughly, to the position an element would have had
3773      * in the normal flow. More precisely, the static position for 'top' is the
3774      * distance from the top edge of the containing block to the top margin edge
3775      * of a hypothetical box that would have been the first box of the element if
3776      * its 'position' property had been 'static' and 'float' had been 'none'. The
3777      * value is negative if the hypothetical box is above the containing block.
3778      *
3779      * But rather than actually calculating the dimensions of that hypothetical
3780      * box, user agents are free to make a guess at its probable position.
3781      *
3782      * For the purposes of calculating the static position, the containing block
3783      * of fixed positioned elements is the initial containing block instead of
3784      * the viewport.
3785     \*---------------------------------------------------------------------------*/
3786
3787     // see FIXME 1
3788     // Calculate the static distance if needed.
3789     computeBlockStaticDistance(logicalTopLength, logicalBottomLength, this, containerBlock);
3790
3791     // Calculate constraint equation values for 'height' case.
3792     LayoutUnit logicalHeight = computedValues.m_extent;
3793     computePositionedLogicalHeightUsing(MainOrPreferredSize, styleToUse.logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3794                                         logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3795                                         computedValues);
3796
3797     // Avoid doing any work i