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