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.
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.
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.
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.
26 #include "RenderBox.h"
28 #include "CSSFontSelector.h"
30 #include "ChromeClient.h"
32 #include "EventHandler.h"
33 #include "FloatQuad.h"
34 #include "FloatRoundedRect.h"
36 #include "FrameView.h"
37 #include "GraphicsContext.h"
38 #include "HTMLBodyElement.h"
39 #include "HTMLButtonElement.h"
40 #include "HTMLElement.h"
41 #include "HTMLFrameOwnerElement.h"
42 #include "HTMLInputElement.h"
43 #include "HTMLNames.h"
44 #include "HTMLTextAreaElement.h"
45 #include "HitTestResult.h"
46 #include "InlineElementBox.h"
47 #include "MainFrame.h"
49 #include "PaintInfo.h"
50 #include "RenderBoxRegionInfo.h"
51 #include "RenderDeprecatedFlexibleBox.h"
52 #include "RenderFlexibleBox.h"
53 #include "RenderGeometryMap.h"
54 #include "RenderInline.h"
55 #include "RenderIterator.h"
56 #include "RenderLayer.h"
57 #include "RenderLayerCompositor.h"
58 #include "RenderNamedFlowFragment.h"
59 #include "RenderNamedFlowThread.h"
60 #include "RenderTableCell.h"
61 #include "RenderTheme.h"
62 #include "RenderView.h"
63 #include "ScrollAnimator.h"
64 #include "ScrollbarTheme.h"
65 #include "TransformState.h"
66 #include "htmlediting.h"
69 #include <wtf/StackStats.h>
77 struct SameSizeAsRenderBox : public RenderBoxModelObject {
78 virtual ~SameSizeAsRenderBox() { }
80 LayoutBoxExtent marginBox;
81 LayoutUnit preferredLogicalWidths[2];
85 COMPILE_ASSERT(sizeof(RenderBox) == sizeof(SameSizeAsRenderBox), RenderBox_should_stay_small);
87 using namespace HTMLNames;
89 // Used by flexible boxes when flexing this element and by table cells.
90 typedef WTF::HashMap<const RenderBox*, LayoutUnit> OverrideSizeMap;
91 static OverrideSizeMap* gOverrideHeightMap = nullptr;
92 static OverrideSizeMap* gOverrideWidthMap = nullptr;
94 #if ENABLE(CSS_GRID_LAYOUT)
95 // Used by grid elements to properly size their grid items.
96 typedef WTF::HashMap<const RenderBox*, Optional<LayoutUnit>> OverrideOptionalSizeMap;
97 static OverrideOptionalSizeMap* gOverrideContainingBlockLogicalHeightMap = nullptr;
98 static OverrideOptionalSizeMap* gOverrideContainingBlockLogicalWidthMap = nullptr;
99 static OverrideSizeMap* gExtraInlineOffsetMap = nullptr;
100 static OverrideSizeMap* gExtraBlockOffsetMap = nullptr;
103 // Size of border belt for autoscroll. When mouse pointer in border belt,
104 // autoscroll is started.
105 static const int autoscrollBeltSize = 20;
106 static const unsigned backgroundObscurationTestMaxDepth = 4;
108 bool RenderBox::s_hadOverflowClip = false;
110 static bool skipBodyBackground(const RenderBox* bodyElementRenderer)
112 ASSERT(bodyElementRenderer->isBody());
113 // The <body> only paints its background if the root element has defined a background independent of the body,
114 // or if the <body>'s parent is not the document element's renderer (e.g. inside SVG foreignObject).
115 auto documentElementRenderer = bodyElementRenderer->document().documentElement()->renderer();
116 return documentElementRenderer
117 && !documentElementRenderer->hasBackground()
118 && (documentElementRenderer == bodyElementRenderer->parent());
121 RenderBox::RenderBox(Element& element, Ref<RenderStyle>&& style, BaseTypeFlags baseTypeFlags)
122 : RenderBoxModelObject(element, WTFMove(style), baseTypeFlags)
123 , m_minPreferredLogicalWidth(-1)
124 , m_maxPreferredLogicalWidth(-1)
125 , m_inlineBoxWrapper(nullptr)
130 RenderBox::RenderBox(Document& document, Ref<RenderStyle>&& style, BaseTypeFlags baseTypeFlags)
131 : RenderBoxModelObject(document, WTFMove(style), baseTypeFlags)
132 , m_minPreferredLogicalWidth(-1)
133 , m_maxPreferredLogicalWidth(-1)
134 , m_inlineBoxWrapper(nullptr)
139 RenderBox::~RenderBox()
141 if (frame().eventHandler().autoscrollRenderer() == this)
142 frame().eventHandler().stopAutoscrollTimer(true);
145 #if ENABLE(CSS_GRID_LAYOUT)
146 clearContainingBlockOverrideSize();
147 clearExtraInlineAndBlockOffests();
150 RenderBlock::removePercentHeightDescendantIfNeeded(*this);
152 #if ENABLE(CSS_SHAPES)
153 ShapeOutsideInfo::removeInfo(*this);
156 view().unscheduleLazyRepaint(*this);
157 if (hasControlStatesForRenderer(this))
158 removeControlStatesForRenderer(this);
161 RenderRegion* RenderBox::clampToStartAndEndRegions(RenderRegion* region) const
163 RenderFlowThread* flowThread = flowThreadContainingBlock();
165 ASSERT(isRenderView() || (region && flowThread));
169 // We need to clamp to the block, since we want any lines or blocks that overflow out of the
170 // logical top or logical bottom of the block to size as though the border box in the first and
171 // last regions extended infinitely. Otherwise the lines are going to size according to the regions
172 // they overflow into, which makes no sense when this block doesn't exist in |region| at all.
173 RenderRegion* startRegion = nullptr;
174 RenderRegion* endRegion = nullptr;
175 if (!flowThread->getRegionRangeForBox(this, startRegion, endRegion))
178 if (region->logicalTopForFlowThreadContent() < startRegion->logicalTopForFlowThreadContent())
180 if (region->logicalTopForFlowThreadContent() > endRegion->logicalTopForFlowThreadContent())
186 bool RenderBox::hasRegionRangeInFlowThread() const
188 RenderFlowThread* flowThread = flowThreadContainingBlock();
189 if (!flowThread || !flowThread->hasValidRegionInfo())
192 return flowThread->hasCachedRegionRangeForBox(this);
195 LayoutRect RenderBox::clientBoxRectInRegion(RenderRegion* region) const
198 return clientBoxRect();
200 LayoutRect clientBox = borderBoxRectInRegion(region);
201 clientBox.setLocation(clientBox.location() + LayoutSize(borderLeft(), borderTop()));
202 clientBox.setSize(clientBox.size() - LayoutSize(borderLeft() + borderRight() + verticalScrollbarWidth(), borderTop() + borderBottom() + horizontalScrollbarHeight()));
207 LayoutRect RenderBox::borderBoxRectInRegion(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
210 return borderBoxRect();
212 RenderFlowThread* flowThread = flowThreadContainingBlock();
214 return borderBoxRect();
216 RenderRegion* startRegion = nullptr;
217 RenderRegion* endRegion = nullptr;
218 if (!flowThread->getRegionRangeForBox(this, startRegion, endRegion)) {
219 // FIXME: In a perfect world this condition should never happen.
220 return borderBoxRect();
223 ASSERT(flowThread->regionInRange(region, startRegion, endRegion));
225 // Compute the logical width and placement in this region.
226 RenderBoxRegionInfo* boxInfo = renderBoxRegionInfo(region, cacheFlag);
228 return borderBoxRect();
230 // We have cached insets.
231 LayoutUnit logicalWidth = boxInfo->logicalWidth();
232 LayoutUnit logicalLeft = boxInfo->logicalLeft();
234 // Now apply the parent inset since it is cumulative whenever anything in the containing block chain shifts.
235 // FIXME: Doesn't work right with perpendicular writing modes.
236 const RenderBlock* currentBox = containingBlock();
237 RenderBoxRegionInfo* currentBoxInfo = isRenderFlowThread() ? nullptr : currentBox->renderBoxRegionInfo(region);
238 while (currentBoxInfo && currentBoxInfo->isShifted()) {
239 if (currentBox->style().direction() == LTR)
240 logicalLeft += currentBoxInfo->logicalLeft();
242 logicalLeft -= (currentBox->logicalWidth() - currentBoxInfo->logicalWidth()) - currentBoxInfo->logicalLeft();
244 // Once we reach the fragmentation container we should stop.
245 if (currentBox->isRenderFlowThread())
248 currentBox = currentBox->containingBlock();
251 region = currentBox->clampToStartAndEndRegions(region);
252 currentBoxInfo = currentBox->renderBoxRegionInfo(region);
255 if (cacheFlag == DoNotCacheRenderBoxRegionInfo)
258 if (isHorizontalWritingMode())
259 return LayoutRect(logicalLeft, 0, logicalWidth, height());
260 return LayoutRect(0, logicalLeft, width(), logicalWidth);
263 static RenderBlockFlow* outermostBlockContainingFloatingObject(RenderBox& box)
265 ASSERT(box.isFloating());
266 RenderBlockFlow* parentBlock = nullptr;
267 for (auto& ancestor : ancestorsOfType<RenderBlockFlow>(box)) {
268 if (ancestor.isRenderView())
270 if (!parentBlock || ancestor.containsFloat(box))
271 parentBlock = &ancestor;
276 void RenderBox::removeFloatingOrPositionedChildFromBlockLists()
278 ASSERT(isFloatingOrOutOfFlowPositioned());
280 if (documentBeingDestroyed())
284 if (RenderBlockFlow* parentBlock = outermostBlockContainingFloatingObject(*this)) {
285 parentBlock->markSiblingsWithFloatsForLayout(this);
286 parentBlock->markAllDescendantsWithFloatsForLayout(this, false);
290 if (isOutOfFlowPositioned())
291 RenderBlock::removePositionedObject(*this);
294 void RenderBox::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
296 s_hadOverflowClip = hasOverflowClip();
298 const RenderStyle* oldStyle = hasInitializedStyle() ? &style() : nullptr;
300 // The background of the root element or the body element could propagate up to
301 // the canvas. Issue full repaint, when our style changes substantially.
302 if (diff >= StyleDifferenceRepaint && (isDocumentElementRenderer() || isBody())) {
303 view().repaintRootContents();
304 if (oldStyle->hasEntirelyFixedBackground() != newStyle.hasEntirelyFixedBackground())
305 view().compositor().rootFixedBackgroundsChanged();
308 // When a layout hint happens and an object's position style changes, we have to do a layout
309 // to dirty the render tree using the old position value now.
310 if (diff == StyleDifferenceLayout && parent() && oldStyle->position() != newStyle.position()) {
311 markContainingBlocksForLayout();
312 if (oldStyle->position() == StaticPosition)
314 else if (newStyle.hasOutOfFlowPosition())
315 parent()->setChildNeedsLayout();
316 if (isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition())
317 removeFloatingOrPositionedChildFromBlockLists();
320 view().repaintRootContents();
322 #if ENABLE(CSS_SCROLL_SNAP)
323 if (!newStyle.scrollSnapCoordinates().isEmpty() || (oldStyle && !oldStyle->scrollSnapCoordinates().isEmpty())) {
324 if (newStyle.scrollSnapCoordinates().isEmpty())
325 view().unregisterBoxWithScrollSnapCoordinates(*this);
327 view().registerBoxWithScrollSnapCoordinates(*this);
331 RenderBoxModelObject::styleWillChange(diff, newStyle);
334 void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
336 // Horizontal writing mode definition is updated in RenderBoxModelObject::updateFromStyle,
337 // (as part of the RenderBoxModelObject::styleDidChange call below). So, we can safely cache the horizontal
338 // writing mode value before style change here.
339 bool oldHorizontalWritingMode = isHorizontalWritingMode();
341 RenderBoxModelObject::styleDidChange(diff, oldStyle);
343 const RenderStyle& newStyle = style();
344 if (needsLayout() && oldStyle) {
345 RenderBlock::removePercentHeightDescendantIfNeeded(*this);
347 // Normally we can do optimized positioning layout for absolute/fixed positioned objects. There is one special case, however, which is
348 // 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
349 // to determine the new static position.
350 if (isOutOfFlowPositioned() && newStyle.hasStaticBlockPosition(isHorizontalWritingMode()) && oldStyle->marginBefore() != newStyle.marginBefore()
351 && parent() && !parent()->normalChildNeedsLayout())
352 parent()->setChildNeedsLayout();
355 if (RenderBlock::hasPercentHeightContainerMap() && firstChild()
356 && oldHorizontalWritingMode != isHorizontalWritingMode())
357 RenderBlock::clearPercentHeightDescendantsFrom(*this);
359 // If our zoom factor changes and we have a defined scrollLeft/Top, we need to adjust that value into the
360 // new zoomed coordinate space.
361 if (hasOverflowClip() && layer() && oldStyle && oldStyle->effectiveZoom() != newStyle.effectiveZoom()) {
362 if (int left = layer()->scrollOffset().x()) {
363 left = (left / oldStyle->effectiveZoom()) * newStyle.effectiveZoom();
364 layer()->scrollToXOffset(left);
366 if (int top = layer()->scrollOffset().y()) {
367 top = (top / oldStyle->effectiveZoom()) * newStyle.effectiveZoom();
368 layer()->scrollToYOffset(top);
372 // Our opaqueness might have changed without triggering layout.
373 if (diff >= StyleDifferenceRepaint && diff <= StyleDifferenceRepaintLayer) {
374 auto parentToInvalidate = parent();
375 for (unsigned i = 0; i < backgroundObscurationTestMaxDepth && parentToInvalidate; ++i) {
376 parentToInvalidate->invalidateBackgroundObscurationStatus();
377 parentToInvalidate = parentToInvalidate->parent();
381 bool isBodyRenderer = isBody();
382 bool isDocElementRenderer = isDocumentElementRenderer();
384 if (isDocElementRenderer || isBodyRenderer) {
385 // Propagate the new writing mode and direction up to the RenderView.
386 auto* documentElementRenderer = document().documentElement()->renderer();
387 RenderStyle& viewStyle = view().style();
388 bool viewChangedWritingMode = false;
389 bool rootStyleChanged = false;
390 bool viewStyleChanged = false;
391 auto* rootRenderer = isBodyRenderer ? documentElementRenderer : nullptr;
392 if (viewStyle.direction() != newStyle.direction() && (isDocElementRenderer || !documentElementRenderer->style().hasExplicitlySetDirection())) {
393 viewStyle.setDirection(newStyle.direction());
394 viewStyleChanged = true;
395 if (isBodyRenderer) {
396 rootRenderer->style().setDirection(newStyle.direction());
397 rootStyleChanged = true;
399 setNeedsLayoutAndPrefWidthsRecalc();
402 if (viewStyle.writingMode() != newStyle.writingMode() && (isDocElementRenderer || !documentElementRenderer->style().hasExplicitlySetWritingMode())) {
403 viewStyle.setWritingMode(newStyle.writingMode());
404 viewChangedWritingMode = true;
405 viewStyleChanged = true;
406 view().setHorizontalWritingMode(newStyle.isHorizontalWritingMode());
407 view().markAllDescendantsWithFloatsForLayout();
408 if (isBodyRenderer) {
409 rootStyleChanged = true;
410 rootRenderer->style().setWritingMode(newStyle.writingMode());
411 rootRenderer->setHorizontalWritingMode(newStyle.isHorizontalWritingMode());
413 setNeedsLayoutAndPrefWidthsRecalc();
416 view().frameView().recalculateScrollbarOverlayStyle();
418 const Pagination& pagination = view().frameView().pagination();
419 if (viewChangedWritingMode && pagination.mode != Pagination::Unpaginated) {
420 viewStyle.setColumnStylesFromPaginationMode(pagination.mode);
421 if (view().multiColumnFlowThread())
422 view().updateColumnProgressionFromStyle(viewStyle);
425 if (viewStyleChanged && view().multiColumnFlowThread())
426 view().updateStylesForColumnChildren();
428 if (rootStyleChanged && is<RenderBlockFlow>(rootRenderer) && downcast<RenderBlockFlow>(*rootRenderer).multiColumnFlowThread())
429 downcast<RenderBlockFlow>(*rootRenderer).updateStylesForColumnChildren();
431 if (isBodyRenderer && pagination.mode != Pagination::Unpaginated && frame().page()->paginationLineGridEnabled()) {
432 // Propagate the body font back up to the RenderView and use it as
433 // the basis of the grid.
434 if (newStyle.fontDescription() != view().style().fontDescription()) {
435 view().style().setFontDescription(newStyle.fontDescription());
436 view().style().fontCascade().update(&document().fontSelector());
440 if (diff != StyleDifferenceEqual)
441 view().compositor().rootOrBodyStyleChanged(*this, oldStyle);
444 #if ENABLE(CSS_SHAPES)
445 if ((oldStyle && oldStyle->shapeOutside()) || style().shapeOutside())
446 updateShapeOutsideInfoAfterStyleChange(style(), oldStyle);
450 void RenderBox::willBeRemovedFromTree()
452 #if ENABLE(CSS_SCROLL_SNAP)
453 if (hasInitializedStyle() && !style().scrollSnapCoordinates().isEmpty())
454 view().unregisterBoxWithScrollSnapCoordinates(*this);
457 RenderBoxModelObject::willBeRemovedFromTree();
461 #if ENABLE(CSS_SHAPES)
462 void RenderBox::updateShapeOutsideInfoAfterStyleChange(const RenderStyle& style, const RenderStyle* oldStyle)
464 const ShapeValue* shapeOutside = style.shapeOutside();
465 const ShapeValue* oldShapeOutside = oldStyle ? oldStyle->shapeOutside() : nullptr;
467 Length shapeMargin = style.shapeMargin();
468 Length oldShapeMargin = oldStyle ? oldStyle->shapeMargin() : RenderStyle::initialShapeMargin();
470 float shapeImageThreshold = style.shapeImageThreshold();
471 float oldShapeImageThreshold = oldStyle ? oldStyle->shapeImageThreshold() : RenderStyle::initialShapeImageThreshold();
473 // FIXME: A future optimization would do a deep comparison for equality. (bug 100811)
474 if (shapeOutside == oldShapeOutside && shapeMargin == oldShapeMargin && shapeImageThreshold == oldShapeImageThreshold)
478 ShapeOutsideInfo::removeInfo(*this);
480 ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
482 if (shapeOutside || shapeOutside != oldShapeOutside)
483 markShapeOutsideDependentsForLayout();
487 void RenderBox::updateFromStyle()
489 RenderBoxModelObject::updateFromStyle();
491 const RenderStyle& styleToUse = style();
492 bool isDocElementRenderer = isDocumentElementRenderer();
493 bool isViewObject = isRenderView();
495 // The root and the RenderView always paint their backgrounds/borders.
496 if (isDocElementRenderer || isViewObject)
497 setHasBoxDecorations(true);
499 setFloating(!isOutOfFlowPositioned() && styleToUse.isFloating());
501 // We also handle <body> and <html>, whose overflow applies to the viewport.
502 if (styleToUse.overflowX() != OVISIBLE && !isDocElementRenderer && isRenderBlock()) {
503 bool boxHasOverflowClip = true;
505 // Overflow on the body can propagate to the viewport under the following conditions.
506 // (1) The root element is <html>.
507 // (2) We are the primary <body> (can be checked by looking at document.body).
508 // (3) The root element has visible overflow.
509 if (is<HTMLHtmlElement>(*document().documentElement())
510 && document().body() == element()
511 && document().documentElement()->renderer()->style().overflowX() == OVISIBLE) {
512 boxHasOverflowClip = false;
516 // Check for overflow clip.
517 // It's sufficient to just check one direction, since it's illegal to have visible on only one overflow value.
518 if (boxHasOverflowClip) {
519 if (!s_hadOverflowClip)
520 // Erase the overflow
522 setHasOverflowClip();
526 setHasTransformRelatedProperty(styleToUse.hasTransformRelatedProperty());
527 setHasReflection(styleToUse.boxReflect());
530 void RenderBox::layout()
532 StackStats::LayoutCheckPoint layoutCheckPoint;
533 ASSERT(needsLayout());
535 RenderObject* child = firstChild();
541 LayoutStateMaintainer statePusher(view(), *this, locationOffset(), style().isFlippedBlocksWritingMode());
543 if (child->needsLayout())
544 downcast<RenderElement>(*child).layout();
545 ASSERT(!child->needsLayout());
546 child = child->nextSibling();
549 invalidateBackgroundObscurationStatus();
553 // More IE extensions. clientWidth and clientHeight represent the interior of an object
554 // excluding border and scrollbar.
555 LayoutUnit RenderBox::clientWidth() const
557 return width() - borderLeft() - borderRight() - verticalScrollbarWidth();
560 LayoutUnit RenderBox::clientHeight() const
562 return height() - borderTop() - borderBottom() - horizontalScrollbarHeight();
565 int RenderBox::scrollWidth() const
567 if (hasOverflowClip() && layer())
568 return layer()->scrollWidth();
569 // For objects with visible overflow, this matches IE.
570 // FIXME: Need to work right with writing modes.
571 if (style().isLeftToRightDirection()) {
572 // FIXME: This should use snappedIntSize() instead with absolute coordinates.
573 return roundToInt(std::max(clientWidth(), layoutOverflowRect().maxX() - borderLeft()));
575 return clientWidth() - std::min<LayoutUnit>(0, layoutOverflowRect().x() - borderLeft());
578 int RenderBox::scrollHeight() const
580 if (hasOverflowClip() && layer())
581 return layer()->scrollHeight();
582 // For objects with visible overflow, this matches IE.
583 // FIXME: Need to work right with writing modes.
584 // FIXME: This should use snappedIntSize() instead with absolute coordinates.
585 return roundToInt(std::max(clientHeight(), layoutOverflowRect().maxY() - borderTop()));
588 int RenderBox::scrollLeft() const
590 return hasOverflowClip() && layer() ? layer()->scrollPosition().x() : 0;
593 int RenderBox::scrollTop() const
595 return hasOverflowClip() && layer() ? layer()->scrollPosition().y() : 0;
598 static void setupWheelEventTestTrigger(RenderLayer& layer, Frame* frame)
603 Page* page = frame->page();
604 if (!page || !page->expectsWheelEventTriggers())
607 layer.scrollAnimator().setWheelEventTestTrigger(page->testTrigger());
610 void RenderBox::setScrollLeft(int newLeft)
612 if (!hasOverflowClip() || !layer())
614 setupWheelEventTestTrigger(*layer(), document().frame());
615 layer()->scrollToXPosition(newLeft, RenderLayer::ScrollOffsetClamped);
618 void RenderBox::setScrollTop(int newTop)
620 if (!hasOverflowClip() || !layer())
622 setupWheelEventTestTrigger(*layer(), document().frame());
623 layer()->scrollToYPosition(newTop, RenderLayer::ScrollOffsetClamped);
626 void RenderBox::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
628 rects.append(snappedIntRect(accumulatedOffset, size()));
631 void RenderBox::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
633 FloatRect localRect(0, 0, width(), height());
635 RenderFlowThread* flowThread = flowThreadContainingBlock();
636 if (flowThread && flowThread->absoluteQuadsForBox(quads, wasFixed, this, localRect.y(), localRect.maxY()))
639 quads.append(localToAbsoluteQuad(localRect, UseTransforms, wasFixed));
642 void RenderBox::updateLayerTransform()
644 // Transform-origin depends on box size, so we need to update the layer transform after layout.
646 layer()->updateTransform();
649 LayoutUnit RenderBox::constrainLogicalWidthInRegionByMinMax(LayoutUnit logicalWidth, LayoutUnit availableWidth, RenderBlock& cb, RenderRegion* region) const
651 const RenderStyle& styleToUse = style();
652 if (!styleToUse.logicalMaxWidth().isUndefined())
653 logicalWidth = std::min(logicalWidth, computeLogicalWidthInRegionUsing(MaxSize, styleToUse.logicalMaxWidth(), availableWidth, cb, region));
654 return std::max(logicalWidth, computeLogicalWidthInRegionUsing(MinSize, styleToUse.logicalMinWidth(), availableWidth, cb, region));
657 LayoutUnit RenderBox::constrainLogicalHeightByMinMax(LayoutUnit logicalHeight, Optional<LayoutUnit> intrinsicContentHeight) const
659 const RenderStyle& styleToUse = style();
660 if (!styleToUse.logicalMaxHeight().isUndefined()) {
661 if (Optional<LayoutUnit> maxH = computeLogicalHeightUsing(MaxSize, styleToUse.logicalMaxHeight(), intrinsicContentHeight))
662 logicalHeight = std::min(logicalHeight, maxH.value());
664 if (Optional<LayoutUnit> computedLogicalHeight = computeLogicalHeightUsing(MinSize, styleToUse.logicalMinHeight(), intrinsicContentHeight))
665 return std::max(logicalHeight, computedLogicalHeight.value());
666 return logicalHeight;
669 LayoutUnit RenderBox::constrainContentBoxLogicalHeightByMinMax(LayoutUnit logicalHeight, Optional<LayoutUnit> intrinsicContentHeight) const
671 const RenderStyle& styleToUse = style();
672 if (!styleToUse.logicalMaxHeight().isUndefined()) {
673 if (Optional<LayoutUnit> maxH = computeContentLogicalHeight(MaxSize, styleToUse.logicalMaxHeight(), intrinsicContentHeight))
674 logicalHeight = std::min(logicalHeight, maxH.value());
676 if (Optional<LayoutUnit> computedContentLogicalHeight = computeContentLogicalHeight(MinSize, styleToUse.logicalMinHeight(), intrinsicContentHeight))
677 return std::max(logicalHeight, computedContentLogicalHeight.value());
678 return logicalHeight;
681 RoundedRect::Radii RenderBox::borderRadii() const
683 RenderStyle& style = this->style();
684 LayoutRect bounds = frameRect();
686 unsigned borderLeft = style.borderLeftWidth();
687 unsigned borderTop = style.borderTopWidth();
688 bounds.moveBy(LayoutPoint(borderLeft, borderTop));
689 bounds.contract(borderLeft + style.borderRightWidth(), borderTop + style.borderBottomWidth());
690 return style.getRoundedBorderFor(bounds).radii();
693 IntRect RenderBox::absoluteContentBox() const
695 // This is wrong with transforms and flipped writing modes.
696 IntRect rect = snappedIntRect(contentBoxRect());
697 FloatPoint absPos = localToAbsolute();
698 rect.move(absPos.x(), absPos.y());
702 FloatQuad RenderBox::absoluteContentQuad() const
704 LayoutRect rect = contentBoxRect();
705 return localToAbsoluteQuad(FloatRect(rect));
708 LayoutRect RenderBox::outlineBoundsForRepaint(const RenderLayerModelObject* repaintContainer, const RenderGeometryMap* geometryMap) const
710 LayoutRect box = borderBoundingBox();
711 adjustRectForOutlineAndShadow(box);
713 if (repaintContainer != this) {
714 FloatQuad containerRelativeQuad;
716 containerRelativeQuad = geometryMap->mapToContainer(box, repaintContainer);
718 containerRelativeQuad = localToContainerQuad(FloatRect(box), repaintContainer);
720 box = LayoutRect(containerRelativeQuad.boundingBox());
723 // FIXME: layoutDelta needs to be applied in parts before/after transforms and
724 // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
725 box.move(view().layoutDelta());
727 return LayoutRect(snapRectToDevicePixels(box, document().deviceScaleFactor()));
730 void RenderBox::addFocusRingRects(Vector<LayoutRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject*)
732 if (!size().isEmpty())
733 rects.append(LayoutRect(additionalOffset, size()));
736 int RenderBox::reflectionOffset() const
738 if (!style().boxReflect())
740 if (style().boxReflect()->direction() == ReflectionLeft || style().boxReflect()->direction() == ReflectionRight)
741 return valueForLength(style().boxReflect()->offset(), borderBoxRect().width());
742 return valueForLength(style().boxReflect()->offset(), borderBoxRect().height());
745 LayoutRect RenderBox::reflectedRect(const LayoutRect& r) const
747 if (!style().boxReflect())
750 LayoutRect box = borderBoxRect();
751 LayoutRect result = r;
752 switch (style().boxReflect()->direction()) {
753 case ReflectionBelow:
754 result.setY(box.maxY() + reflectionOffset() + (box.maxY() - r.maxY()));
756 case ReflectionAbove:
757 result.setY(box.y() - reflectionOffset() - box.height() + (box.maxY() - r.maxY()));
760 result.setX(box.x() - reflectionOffset() - box.width() + (box.maxX() - r.maxX()));
762 case ReflectionRight:
763 result.setX(box.maxX() + reflectionOffset() + (box.maxX() - r.maxX()));
769 bool RenderBox::fixedElementLaysOutRelativeToFrame(const FrameView& frameView) const
771 return style().position() == FixedPosition && container()->isRenderView() && frameView.fixedElementsLayoutRelativeToFrame();
774 bool RenderBox::includeVerticalScrollbarSize() const
776 return hasOverflowClip() && layer() && !layer()->hasOverlayScrollbars()
777 && (style().overflowY() == OSCROLL || style().overflowY() == OAUTO);
780 bool RenderBox::includeHorizontalScrollbarSize() const
782 return hasOverflowClip() && layer() && !layer()->hasOverlayScrollbars()
783 && (style().overflowX() == OSCROLL || style().overflowX() == OAUTO);
786 int RenderBox::verticalScrollbarWidth() const
788 return includeVerticalScrollbarSize() ? layer()->verticalScrollbarWidth() : 0;
791 int RenderBox::horizontalScrollbarHeight() const
793 return includeHorizontalScrollbarSize() ? layer()->horizontalScrollbarHeight() : 0;
796 int RenderBox::intrinsicScrollbarLogicalWidth() const
798 if (!hasOverflowClip())
801 if (isHorizontalWritingMode() && (style().overflowY() == OSCROLL && !hasVerticalScrollbarWithAutoBehavior())) {
802 ASSERT(layer() && layer()->hasVerticalScrollbar());
803 return verticalScrollbarWidth();
806 if (!isHorizontalWritingMode() && (style().overflowX() == OSCROLL && !hasHorizontalScrollbarWithAutoBehavior())) {
807 ASSERT(layer() && layer()->hasHorizontalScrollbar());
808 return horizontalScrollbarHeight();
814 bool RenderBox::scrollLayer(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement)
816 RenderLayer* boxLayer = layer();
817 if (boxLayer && boxLayer->scroll(direction, granularity, multiplier)) {
819 *stopElement = element();
827 bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement, RenderBox* startBox, const IntPoint& wheelEventAbsolutePoint)
829 if (scrollLayer(direction, granularity, multiplier, stopElement))
832 if (stopElement && *stopElement && *stopElement == element())
835 RenderBlock* nextScrollBlock = containingBlock();
836 if (is<RenderNamedFlowThread>(nextScrollBlock)) {
838 nextScrollBlock = downcast<RenderNamedFlowThread>(*nextScrollBlock).fragmentFromAbsolutePointAndBox(wheelEventAbsolutePoint, *startBox);
841 if (nextScrollBlock && !nextScrollBlock->isRenderView())
842 return nextScrollBlock->scroll(direction, granularity, multiplier, stopElement, startBox, wheelEventAbsolutePoint);
847 bool RenderBox::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement)
849 bool scrolled = false;
851 RenderLayer* l = layer();
854 // On Mac only we reset the inline direction position when doing a document scroll (e.g., hitting Home/End).
855 if (granularity == ScrollByDocument)
856 scrolled = l->scroll(logicalToPhysical(ScrollInlineDirectionBackward, isHorizontalWritingMode(), style().isFlippedBlocksWritingMode()), ScrollByDocument, multiplier);
858 if (l->scroll(logicalToPhysical(direction, isHorizontalWritingMode(), style().isFlippedBlocksWritingMode()), granularity, multiplier))
863 *stopElement = element();
868 if (stopElement && *stopElement && *stopElement == element())
871 RenderBlock* b = containingBlock();
872 if (b && !b->isRenderView())
873 return b->logicalScroll(direction, granularity, multiplier, stopElement);
877 bool RenderBox::canBeScrolledAndHasScrollableArea() const
879 return canBeProgramaticallyScrolled() && (hasHorizontalOverflow() || hasVerticalOverflow());
882 bool RenderBox::isScrollableOrRubberbandableBox() const
884 return canBeScrolledAndHasScrollableArea();
887 // FIXME: This is badly named. overflow:hidden can be programmatically scrolled, yet this returns false in that case.
888 bool RenderBox::canBeProgramaticallyScrolled() const
893 if (!hasOverflowClip())
896 if (hasScrollableOverflowX() || hasScrollableOverflowY())
899 return element() && element()->hasEditableStyle();
902 bool RenderBox::usesCompositedScrolling() const
904 return hasOverflowClip() && hasLayer() && layer()->usesCompositedScrolling();
907 void RenderBox::autoscroll(const IntPoint& position)
910 layer()->autoscroll(position);
913 // There are two kinds of renderer that can autoscroll.
914 bool RenderBox::canAutoscroll() const
917 return view().frameView().isScrollable();
919 // Check for a box that can be scrolled in its own right.
920 if (canBeScrolledAndHasScrollableArea())
926 // If specified point is in border belt, returned offset denotes direction of
928 IntSize RenderBox::calculateAutoscrollDirection(const IntPoint& windowPoint) const
930 IntRect box(absoluteBoundingBoxRect());
931 box.moveBy(view().frameView().scrollPosition());
932 IntRect windowBox = view().frameView().contentsToWindow(box);
934 IntPoint windowAutoscrollPoint = windowPoint;
936 if (windowAutoscrollPoint.x() < windowBox.x() + autoscrollBeltSize)
937 windowAutoscrollPoint.move(-autoscrollBeltSize, 0);
938 else if (windowAutoscrollPoint.x() > windowBox.maxX() - autoscrollBeltSize)
939 windowAutoscrollPoint.move(autoscrollBeltSize, 0);
941 if (windowAutoscrollPoint.y() < windowBox.y() + autoscrollBeltSize)
942 windowAutoscrollPoint.move(0, -autoscrollBeltSize);
943 else if (windowAutoscrollPoint.y() > windowBox.maxY() - autoscrollBeltSize)
944 windowAutoscrollPoint.move(0, autoscrollBeltSize);
946 return windowAutoscrollPoint - windowPoint;
949 RenderBox* RenderBox::findAutoscrollable(RenderObject* renderer)
951 while (renderer && !(is<RenderBox>(*renderer) && downcast<RenderBox>(*renderer).canAutoscroll())) {
952 if (is<RenderView>(*renderer) && renderer->document().ownerElement())
953 renderer = renderer->document().ownerElement()->renderer();
955 renderer = renderer->parent();
958 return is<RenderBox>(renderer) ? downcast<RenderBox>(renderer) : nullptr;
961 void RenderBox::panScroll(const IntPoint& source)
964 layer()->panScrollFromPoint(source);
967 bool RenderBox::hasVerticalScrollbarWithAutoBehavior() const
969 bool overflowScrollActsLikeAuto = style().overflowY() == OSCROLL && !style().hasPseudoStyle(SCROLLBAR) && ScrollbarTheme::theme().usesOverlayScrollbars();
970 return hasOverflowClip() && (style().overflowY() == OAUTO || style().overflowY() == OOVERLAY || overflowScrollActsLikeAuto);
973 bool RenderBox::hasHorizontalScrollbarWithAutoBehavior() const
975 bool overflowScrollActsLikeAuto = style().overflowX() == OSCROLL && !style().hasPseudoStyle(SCROLLBAR) && ScrollbarTheme::theme().usesOverlayScrollbars();
976 return hasOverflowClip() && (style().overflowX() == OAUTO || style().overflowX() == OOVERLAY || overflowScrollActsLikeAuto);
979 bool RenderBox::needsPreferredWidthsRecalculation() const
981 return style().paddingStart().isPercentOrCalculated() || style().paddingEnd().isPercentOrCalculated();
984 IntSize RenderBox::scrolledContentOffset() const
986 if (!hasOverflowClip())
990 // FIXME: Renderer code needs scrollOffset/scrollPosition disambiguation.
991 return layer()->scrolledContentOffset();
994 LayoutSize RenderBox::cachedSizeForOverflowClip() const
996 ASSERT(hasOverflowClip());
998 return layer()->size();
1001 void RenderBox::applyCachedClipAndScrollOffsetForRepaint(LayoutRect& paintRect) const
1003 flipForWritingMode(paintRect);
1004 paintRect.move(-scrolledContentOffset()); // For overflow:auto/scroll/hidden.
1006 // Do not clip scroll layer contents to reduce the number of repaints while scrolling.
1007 if (usesCompositedScrolling()) {
1008 flipForWritingMode(paintRect);
1012 // height() is inaccurate if we're in the middle of a layout of this RenderBox, so use the
1013 // layer's size instead. Even if the layer's size is wrong, the layer itself will repaint
1014 // anyway if its size does change.
1015 LayoutRect clipRect(LayoutPoint(), cachedSizeForOverflowClip());
1016 paintRect = intersection(paintRect, clipRect);
1017 flipForWritingMode(paintRect);
1020 void RenderBox::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
1022 minLogicalWidth = minPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
1023 maxLogicalWidth = maxPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
1026 LayoutUnit RenderBox::minPreferredLogicalWidth() const
1028 if (preferredLogicalWidthsDirty()) {
1030 SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox*>(this));
1032 const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
1035 return m_minPreferredLogicalWidth;
1038 LayoutUnit RenderBox::maxPreferredLogicalWidth() const
1040 if (preferredLogicalWidthsDirty()) {
1042 SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox*>(this));
1044 const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
1047 return m_maxPreferredLogicalWidth;
1050 bool RenderBox::hasOverrideLogicalContentHeight() const
1052 return gOverrideHeightMap && gOverrideHeightMap->contains(this);
1055 bool RenderBox::hasOverrideLogicalContentWidth() const
1057 return gOverrideWidthMap && gOverrideWidthMap->contains(this);
1060 void RenderBox::setOverrideLogicalContentHeight(LayoutUnit height)
1062 if (!gOverrideHeightMap)
1063 gOverrideHeightMap = new OverrideSizeMap();
1064 gOverrideHeightMap->set(this, height);
1067 void RenderBox::setOverrideLogicalContentWidth(LayoutUnit width)
1069 if (!gOverrideWidthMap)
1070 gOverrideWidthMap = new OverrideSizeMap();
1071 gOverrideWidthMap->set(this, width);
1074 void RenderBox::clearOverrideLogicalContentHeight()
1076 if (gOverrideHeightMap)
1077 gOverrideHeightMap->remove(this);
1080 void RenderBox::clearOverrideLogicalContentWidth()
1082 if (gOverrideWidthMap)
1083 gOverrideWidthMap->remove(this);
1086 void RenderBox::clearOverrideSize()
1088 clearOverrideLogicalContentHeight();
1089 clearOverrideLogicalContentWidth();
1092 LayoutUnit RenderBox::overrideLogicalContentWidth() const
1094 ASSERT(hasOverrideLogicalContentWidth());
1095 return gOverrideWidthMap->get(this);
1098 LayoutUnit RenderBox::overrideLogicalContentHeight() const
1100 ASSERT(hasOverrideLogicalContentHeight());
1101 return gOverrideHeightMap->get(this);
1104 #if ENABLE(CSS_GRID_LAYOUT)
1105 Optional<LayoutUnit> RenderBox::overrideContainingBlockContentLogicalWidth() const
1107 ASSERT(hasOverrideContainingBlockLogicalWidth());
1108 return gOverrideContainingBlockLogicalWidthMap->get(this);
1111 Optional<LayoutUnit> RenderBox::overrideContainingBlockContentLogicalHeight() const
1113 ASSERT(hasOverrideContainingBlockLogicalHeight());
1114 return gOverrideContainingBlockLogicalHeightMap->get(this);
1117 bool RenderBox::hasOverrideContainingBlockLogicalWidth() const
1119 return gOverrideContainingBlockLogicalWidthMap && gOverrideContainingBlockLogicalWidthMap->contains(this);
1122 bool RenderBox::hasOverrideContainingBlockLogicalHeight() const
1124 return gOverrideContainingBlockLogicalHeightMap && gOverrideContainingBlockLogicalHeightMap->contains(this);
1127 void RenderBox::setOverrideContainingBlockContentLogicalWidth(Optional<LayoutUnit> logicalWidth)
1129 if (!gOverrideContainingBlockLogicalWidthMap)
1130 gOverrideContainingBlockLogicalWidthMap = new OverrideOptionalSizeMap;
1131 gOverrideContainingBlockLogicalWidthMap->set(this, logicalWidth);
1134 void RenderBox::setOverrideContainingBlockContentLogicalHeight(Optional<LayoutUnit> logicalHeight)
1136 if (!gOverrideContainingBlockLogicalHeightMap)
1137 gOverrideContainingBlockLogicalHeightMap = new OverrideOptionalSizeMap;
1138 gOverrideContainingBlockLogicalHeightMap->set(this, logicalHeight);
1141 void RenderBox::clearContainingBlockOverrideSize()
1143 if (gOverrideContainingBlockLogicalWidthMap)
1144 gOverrideContainingBlockLogicalWidthMap->remove(this);
1145 clearOverrideContainingBlockContentLogicalHeight();
1148 void RenderBox::clearOverrideContainingBlockContentLogicalHeight()
1150 if (gOverrideContainingBlockLogicalHeightMap)
1151 gOverrideContainingBlockLogicalHeightMap->remove(this);
1154 LayoutUnit RenderBox::extraInlineOffset() const
1156 return gExtraInlineOffsetMap ? gExtraInlineOffsetMap->get(this) : LayoutUnit();
1159 LayoutUnit RenderBox::extraBlockOffset() const
1161 return gExtraBlockOffsetMap ? gExtraBlockOffsetMap->get(this) : LayoutUnit();
1164 void RenderBox::setExtraInlineOffset(LayoutUnit inlineOffest)
1166 if (!gExtraInlineOffsetMap)
1167 gExtraInlineOffsetMap = new OverrideSizeMap;
1168 gExtraInlineOffsetMap->set(this, inlineOffest);
1171 void RenderBox::setExtraBlockOffset(LayoutUnit blockOffest)
1173 if (!gExtraBlockOffsetMap)
1174 gExtraBlockOffsetMap = new OverrideSizeMap;
1175 gExtraBlockOffsetMap->set(this, blockOffest);
1178 void RenderBox::clearExtraInlineAndBlockOffests()
1180 if (gExtraInlineOffsetMap)
1181 gExtraInlineOffsetMap->remove(this);
1182 if (gExtraBlockOffsetMap)
1183 gExtraBlockOffsetMap->remove(this);
1185 #endif // ENABLE(CSS_GRID_LAYOUT)
1187 LayoutUnit RenderBox::adjustBorderBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1189 LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
1190 if (style().boxSizing() == CONTENT_BOX)
1191 return width + bordersPlusPadding;
1192 return std::max(width, bordersPlusPadding);
1195 LayoutUnit RenderBox::adjustBorderBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1197 LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
1198 if (style().boxSizing() == CONTENT_BOX)
1199 return height + bordersPlusPadding;
1200 return std::max(height, bordersPlusPadding);
1203 LayoutUnit RenderBox::adjustContentBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1205 if (style().boxSizing() == BORDER_BOX)
1206 width -= borderAndPaddingLogicalWidth();
1207 return std::max<LayoutUnit>(0, width);
1210 LayoutUnit RenderBox::adjustContentBoxLogicalHeightForBoxSizing(Optional<LayoutUnit> height) const
1214 LayoutUnit result = height.value();
1215 if (style().boxSizing() == BORDER_BOX)
1216 result -= borderAndPaddingLogicalHeight();
1217 return std::max(LayoutUnit(), result);
1221 bool RenderBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
1223 LayoutPoint adjustedLocation = accumulatedOffset + location();
1225 // Check kids first.
1226 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
1227 if (!child->hasLayer() && child->nodeAtPoint(request, result, locationInContainer, adjustedLocation, action)) {
1228 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1233 RenderFlowThread* flowThread = flowThreadContainingBlock();
1234 RenderRegion* regionToUse = flowThread ? downcast<RenderNamedFlowFragment>(flowThread->currentRegion()) : nullptr;
1236 // If the box is not contained by this region there's no point in going further.
1237 if (regionToUse && !flowThread->objectShouldFragmentInFlowRegion(this, regionToUse))
1240 // Check our bounds next. For this purpose always assume that we can only be hit in the
1241 // foreground phase (which is true for replaced elements like images).
1242 LayoutRect boundsRect = borderBoxRectInRegion(regionToUse);
1243 boundsRect.moveBy(adjustedLocation);
1244 if (visibleToHitTesting() && action == HitTestForeground && locationInContainer.intersects(boundsRect)) {
1245 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1246 if (!result.addNodeToRectBasedTestResult(element(), request, locationInContainer, boundsRect))
1253 // --------------------- painting stuff -------------------------------
1255 void RenderBox::paintRootBoxFillLayers(const PaintInfo& paintInfo)
1257 if (paintInfo.skipRootBackground())
1260 auto& rootBackgroundRenderer = rendererForRootBackground();
1262 const FillLayer* bgLayer = rootBackgroundRenderer.style().backgroundLayers();
1263 Color bgColor = rootBackgroundRenderer.style().visitedDependentColor(CSSPropertyBackgroundColor);
1265 paintFillLayers(paintInfo, bgColor, bgLayer, view().backgroundRect(), BackgroundBleedNone, CompositeSourceOver, &rootBackgroundRenderer);
1268 BackgroundBleedAvoidance RenderBox::determineBackgroundBleedAvoidance(GraphicsContext& context) const
1270 if (context.paintingDisabled())
1271 return BackgroundBleedNone;
1273 const RenderStyle& style = this->style();
1275 if (!style.hasBackground() || !style.hasBorder() || !style.hasBorderRadius() || borderImageIsLoadedAndCanBeRendered())
1276 return BackgroundBleedNone;
1278 AffineTransform ctm = context.getCTM();
1279 FloatSize contextScaling(static_cast<float>(ctm.xScale()), static_cast<float>(ctm.yScale()));
1281 // Because RoundedRect uses IntRect internally the inset applied by the
1282 // BackgroundBleedShrinkBackground strategy cannot be less than one integer
1283 // layout coordinate, even with subpixel layout enabled. To take that into
1284 // account, we clamp the contextScaling to 1.0 for the following test so
1285 // that borderObscuresBackgroundEdge can only return true if the border
1286 // widths are greater than 2 in both layout coordinates and screen
1288 // This precaution will become obsolete if RoundedRect is ever promoted to
1289 // a sub-pixel representation.
1290 if (contextScaling.width() > 1)
1291 contextScaling.setWidth(1);
1292 if (contextScaling.height() > 1)
1293 contextScaling.setHeight(1);
1295 if (borderObscuresBackgroundEdge(contextScaling))
1296 return BackgroundBleedShrinkBackground;
1297 if (!style.hasAppearance() && borderObscuresBackground() && backgroundHasOpaqueTopLayer())
1298 return BackgroundBleedBackgroundOverBorder;
1300 return BackgroundBleedUseTransparencyLayer;
1303 void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1305 if (!paintInfo.shouldPaintWithinRoot(*this))
1308 LayoutRect paintRect = borderBoxRectInRegion(currentRenderNamedFlowFragment());
1309 paintRect.moveBy(paintOffset);
1312 // Workaround for <rdar://problem/6209763>. Force the painting bounds of checkboxes and radio controls to be square.
1313 if (style().appearance() == CheckboxPart || style().appearance() == RadioPart) {
1314 int width = std::min(paintRect.width(), paintRect.height());
1316 paintRect = IntRect(paintRect.x(), paintRect.y() + (this->height() - height) / 2, width, height); // Vertically center the checkbox, like on desktop
1319 BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context());
1321 // FIXME: Should eventually give the theme control over whether the box shadow should paint, since controls could have
1322 // custom shadows of their own.
1323 if (!boxShadowShouldBeAppliedToBackground(paintRect.location(), bleedAvoidance))
1324 paintBoxShadow(paintInfo, paintRect, style(), Normal);
1326 GraphicsContextStateSaver stateSaver(paintInfo.context(), false);
1327 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
1328 // To avoid the background color bleeding out behind the border, we'll render background and border
1329 // into a transparency layer, and then clip that in one go (which requires setting up the clip before
1330 // beginning the layer).
1332 paintInfo.context().clipRoundedRect(style().getRoundedBorderFor(paintRect).pixelSnappedRoundedRectForPainting(document().deviceScaleFactor()));
1333 paintInfo.context().beginTransparencyLayer(1);
1336 // If we have a native theme appearance, paint that before painting our background.
1337 // The theme will tell us whether or not we should also paint the CSS background.
1338 ControlStates* controlStates = nullptr;
1339 bool borderOrBackgroundPaintingIsNeeded = true;
1340 if (style().hasAppearance()) {
1341 if (hasControlStatesForRenderer(this))
1342 controlStates = controlStatesForRenderer(this);
1344 controlStates = new ControlStates();
1345 addControlStatesForRenderer(this, controlStates);
1347 borderOrBackgroundPaintingIsNeeded = theme().paint(*this, *controlStates, paintInfo, paintRect);
1348 if (controlStates->needsRepaint())
1349 view().scheduleLazyRepaint(*this);
1352 if (borderOrBackgroundPaintingIsNeeded) {
1353 if (bleedAvoidance == BackgroundBleedBackgroundOverBorder)
1354 paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1356 paintBackground(paintInfo, paintRect, bleedAvoidance);
1358 if (style().hasAppearance())
1359 theme().paintDecorations(*this, paintInfo, paintRect);
1361 paintBoxShadow(paintInfo, paintRect, style(), Inset);
1363 // The theme will tell us whether or not we should also paint the CSS border.
1364 if (bleedAvoidance != BackgroundBleedBackgroundOverBorder && (!style().hasAppearance() || (borderOrBackgroundPaintingIsNeeded && theme().paintBorderOnly(*this, paintInfo, paintRect))) && style().hasBorderDecoration())
1365 paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1367 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer)
1368 paintInfo.context().endTransparencyLayer();
1371 void RenderBox::paintBackground(const PaintInfo& paintInfo, const LayoutRect& paintRect, BackgroundBleedAvoidance bleedAvoidance)
1373 if (isDocumentElementRenderer()) {
1374 paintRootBoxFillLayers(paintInfo);
1377 if (isBody() && skipBodyBackground(this))
1379 if (backgroundIsKnownToBeObscured(paintRect.location()) && !boxShadowShouldBeAppliedToBackground(paintRect.location(), bleedAvoidance))
1381 paintFillLayers(paintInfo, style().visitedDependentColor(CSSPropertyBackgroundColor), style().backgroundLayers(), paintRect, bleedAvoidance);
1384 bool RenderBox::getBackgroundPaintedExtent(const LayoutPoint& paintOffset, LayoutRect& paintedExtent) const
1386 ASSERT(hasBackground());
1387 LayoutRect backgroundRect = snappedIntRect(borderBoxRect());
1389 Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1390 if (backgroundColor.isValid() && backgroundColor.alpha()) {
1391 paintedExtent = backgroundRect;
1395 if (!style().backgroundLayers()->image() || style().backgroundLayers()->next()) {
1396 paintedExtent = backgroundRect;
1400 BackgroundImageGeometry geometry = calculateBackgroundImageGeometry(nullptr, *style().backgroundLayers(), paintOffset, backgroundRect);
1401 paintedExtent = geometry.destRect();
1402 return !geometry.hasNonLocalGeometry();
1405 bool RenderBox::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
1407 if (isBody() && skipBodyBackground(this))
1410 Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1411 if (!backgroundColor.isValid() || backgroundColor.hasAlpha())
1414 // If the element has appearance, it might be painted by theme.
1415 // We cannot be sure if theme paints the background opaque.
1416 // In this case it is safe to not assume opaqueness.
1417 // FIXME: May be ask theme if it paints opaque.
1418 if (style().hasAppearance())
1420 // FIXME: Check the opaqueness of background images.
1422 if (hasClip() || hasClipPath())
1425 // FIXME: Use rounded rect if border radius is present.
1426 if (style().hasBorderRadius())
1429 // FIXME: The background color clip is defined by the last layer.
1430 if (style().backgroundLayers()->next())
1432 LayoutRect backgroundRect;
1433 switch (style().backgroundClip()) {
1435 backgroundRect = borderBoxRect();
1437 case PaddingFillBox:
1438 backgroundRect = paddingBoxRect();
1440 case ContentFillBox:
1441 backgroundRect = contentBoxRect();
1446 return backgroundRect.contains(localRect);
1449 static bool isCandidateForOpaquenessTest(const RenderBox& childBox)
1451 const RenderStyle& childStyle = childBox.style();
1452 if (childStyle.position() != StaticPosition && childBox.containingBlock() != childBox.parent())
1454 if (childStyle.visibility() != VISIBLE)
1456 #if ENABLE(CSS_SHAPES)
1457 if (childStyle.shapeOutside())
1460 if (!childBox.width() || !childBox.height())
1462 if (RenderLayer* childLayer = childBox.layer()) {
1463 if (childLayer->isComposited())
1465 // FIXME: Deal with z-index.
1466 if (!childStyle.hasAutoZIndex())
1468 if (childLayer->hasTransform() || childLayer->isTransparent() || childLayer->hasFilter())
1470 if (!childBox.scrolledContentOffset().isZero())
1476 bool RenderBox::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const
1478 if (!maxDepthToTest)
1480 for (auto& childBox : childrenOfType<RenderBox>(*this)) {
1481 if (!isCandidateForOpaquenessTest(childBox))
1483 LayoutPoint childLocation = childBox.location();
1484 if (childBox.isRelPositioned())
1485 childLocation.move(childBox.relativePositionOffset());
1486 LayoutRect childLocalRect = localRect;
1487 childLocalRect.moveBy(-childLocation);
1488 if (childLocalRect.y() < 0 || childLocalRect.x() < 0) {
1489 // If there is unobscured area above/left of a static positioned box then the rect is probably not covered.
1490 if (childBox.style().position() == StaticPosition)
1494 if (childLocalRect.maxY() > childBox.height() || childLocalRect.maxX() > childBox.width())
1496 if (childBox.backgroundIsKnownToBeOpaqueInRect(childLocalRect))
1498 if (childBox.foregroundIsKnownToBeOpaqueInRect(childLocalRect, maxDepthToTest - 1))
1504 bool RenderBox::computeBackgroundIsKnownToBeObscured(const LayoutPoint& paintOffset)
1506 // Test to see if the children trivially obscure the background.
1507 // FIXME: This test can be much more comprehensive.
1508 if (!hasBackground())
1510 // Table and root background painting is special.
1511 if (isTable() || isDocumentElementRenderer())
1514 LayoutRect backgroundRect;
1515 if (!getBackgroundPaintedExtent(paintOffset, backgroundRect))
1517 return foregroundIsKnownToBeOpaqueInRect(backgroundRect, backgroundObscurationTestMaxDepth);
1520 bool RenderBox::backgroundHasOpaqueTopLayer() const
1522 const FillLayer* fillLayer = style().backgroundLayers();
1523 if (!fillLayer || fillLayer->clip() != BorderFillBox)
1526 // Clipped with local scrolling
1527 if (hasOverflowClip() && fillLayer->attachment() == LocalBackgroundAttachment)
1530 if (fillLayer->hasOpaqueImage(*this) && fillLayer->hasRepeatXY() && fillLayer->image()->canRender(this, style().effectiveZoom()))
1533 // If there is only one layer and no image, check whether the background color is opaque
1534 if (!fillLayer->next() && !fillLayer->hasImage()) {
1535 Color bgColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1536 if (bgColor.isValid() && bgColor.alpha() == 255)
1543 void RenderBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1545 if (!paintInfo.shouldPaintWithinRoot(*this) || style().visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask || paintInfo.context().paintingDisabled())
1548 LayoutRect paintRect = LayoutRect(paintOffset, size());
1549 paintMaskImages(paintInfo, paintRect);
1552 void RenderBox::paintClippingMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1554 if (!paintInfo.shouldPaintWithinRoot(*this) || style().visibility() != VISIBLE || paintInfo.phase != PaintPhaseClippingMask || paintInfo.context().paintingDisabled())
1557 LayoutRect paintRect = LayoutRect(paintOffset, size());
1558 paintInfo.context().fillRect(snappedIntRect(paintRect), Color::black);
1561 void RenderBox::paintMaskImages(const PaintInfo& paintInfo, const LayoutRect& paintRect)
1563 // Figure out if we need to push a transparency layer to render our mask.
1564 bool pushTransparencyLayer = false;
1565 bool compositedMask = hasLayer() && layer()->hasCompositedMask();
1566 bool flattenCompositingLayers = view().frameView().paintBehavior() & PaintBehaviorFlattenCompositingLayers;
1567 CompositeOperator compositeOp = CompositeSourceOver;
1569 bool allMaskImagesLoaded = true;
1571 if (!compositedMask || flattenCompositingLayers) {
1572 pushTransparencyLayer = true;
1573 StyleImage* maskBoxImage = style().maskBoxImage().image();
1574 const FillLayer* maskLayers = style().maskLayers();
1576 // Don't render a masked element until all the mask images have loaded, to prevent a flash of unmasked content.
1578 allMaskImagesLoaded &= maskBoxImage->isLoaded();
1581 allMaskImagesLoaded &= maskLayers->imagesAreLoaded();
1583 paintInfo.context().setCompositeOperation(CompositeDestinationIn);
1584 paintInfo.context().beginTransparencyLayer(1);
1585 compositeOp = CompositeSourceOver;
1588 if (allMaskImagesLoaded) {
1589 paintFillLayers(paintInfo, Color(), style().maskLayers(), paintRect, BackgroundBleedNone, compositeOp);
1590 paintNinePieceImage(paintInfo.context(), paintRect, style(), style().maskBoxImage(), compositeOp);
1593 if (pushTransparencyLayer)
1594 paintInfo.context().endTransparencyLayer();
1597 LayoutRect RenderBox::maskClipRect(const LayoutPoint& paintOffset)
1599 const NinePieceImage& maskBoxImage = style().maskBoxImage();
1600 if (maskBoxImage.image()) {
1601 LayoutRect borderImageRect = borderBoxRect();
1603 // Apply outsets to the border box.
1604 borderImageRect.expand(style().maskBoxImageOutsets());
1605 return borderImageRect;
1609 LayoutRect borderBox = borderBoxRect();
1610 for (const FillLayer* maskLayer = style().maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
1611 if (maskLayer->image()) {
1612 // Masks should never have fixed attachment, so it's OK for paintContainer to be null.
1613 BackgroundImageGeometry geometry = calculateBackgroundImageGeometry(nullptr, *maskLayer, paintOffset, borderBox);
1614 result.unite(geometry.destRect());
1620 void RenderBox::paintFillLayers(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1621 BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject)
1623 Vector<const FillLayer*, 8> layers;
1624 const FillLayer* curLayer = fillLayer;
1625 bool shouldDrawBackgroundInSeparateBuffer = false;
1627 layers.append(curLayer);
1628 // Stop traversal when an opaque layer is encountered.
1629 // FIXME : It would be possible for the following occlusion culling test to be more aggressive
1630 // on layers with no repeat by testing whether the image covers the layout rect.
1631 // Testing that here would imply duplicating a lot of calculations that are currently done in
1632 // RenderBoxModelObject::paintFillLayerExtended. A more efficient solution might be to move
1633 // the layer recursion into paintFillLayerExtended, or to compute the layer geometry here
1634 // and pass it down.
1636 if (!shouldDrawBackgroundInSeparateBuffer && curLayer->blendMode() != BlendModeNormal)
1637 shouldDrawBackgroundInSeparateBuffer = true;
1639 // The clipOccludesNextLayers condition must be evaluated first to avoid short-circuiting.
1640 if (curLayer->clipOccludesNextLayers(curLayer == fillLayer) && curLayer->hasOpaqueImage(*this) && curLayer->image()->canRender(this, style().effectiveZoom()) && curLayer->hasRepeatXY() && curLayer->blendMode() == BlendModeNormal)
1642 curLayer = curLayer->next();
1645 GraphicsContext& context = paintInfo.context();
1646 BaseBackgroundColorUsage baseBgColorUsage = BaseBackgroundColorUse;
1648 if (shouldDrawBackgroundInSeparateBuffer) {
1649 paintFillLayer(paintInfo, c, *layers.rbegin(), rect, bleedAvoidance, op, backgroundObject, BaseBackgroundColorOnly);
1650 baseBgColorUsage = BaseBackgroundColorSkip;
1651 context.beginTransparencyLayer(1);
1654 Vector<const FillLayer*>::const_reverse_iterator topLayer = layers.rend();
1655 for (Vector<const FillLayer*>::const_reverse_iterator it = layers.rbegin(); it != topLayer; ++it)
1656 paintFillLayer(paintInfo, c, *it, rect, bleedAvoidance, op, backgroundObject, baseBgColorUsage);
1658 if (shouldDrawBackgroundInSeparateBuffer)
1659 context.endTransparencyLayer();
1662 void RenderBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1663 BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject, BaseBackgroundColorUsage baseBgColorUsage)
1665 paintFillLayerExtended(paintInfo, c, fillLayer, rect, bleedAvoidance, nullptr, LayoutSize(), op, backgroundObject, baseBgColorUsage);
1668 static bool layersUseImage(WrappedImagePtr image, const FillLayer* layers)
1670 for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1671 if (curLayer->image() && image == curLayer->image()->data())
1678 void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
1683 if ((style().borderImage().image() && style().borderImage().image()->data() == image) ||
1684 (style().maskBoxImage().image() && style().maskBoxImage().image()->data() == image)) {
1689 #if ENABLE(CSS_SHAPES)
1690 ShapeValue* shapeOutsideValue = style().shapeOutside();
1691 if (!view().frameView().isInRenderTreeLayout() && isFloating() && shapeOutsideValue && shapeOutsideValue->image() && shapeOutsideValue->image()->data() == image) {
1692 ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
1693 markShapeOutsideDependentsForLayout();
1697 bool didFullRepaint = repaintLayerRectsForImage(image, style().backgroundLayers(), true);
1698 if (!didFullRepaint)
1699 repaintLayerRectsForImage(image, style().maskLayers(), false);
1701 if (!isComposited())
1704 if (layer()->hasCompositedMask() && layersUseImage(image, style().maskLayers()))
1705 layer()->contentChanged(MaskImageChanged);
1706 if (layersUseImage(image, style().backgroundLayers()))
1707 layer()->contentChanged(BackgroundImageChanged);
1710 bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer* layers, bool drawingBackground)
1712 LayoutRect rendererRect;
1713 RenderBox* layerRenderer = nullptr;
1715 for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1716 if (curLayer->image() && image == curLayer->image()->data() && curLayer->image()->canRender(this, style().effectiveZoom())) {
1717 // Now that we know this image is being used, compute the renderer and the rect if we haven't already.
1718 bool drawingRootBackground = drawingBackground && (isDocumentElementRenderer() || (isBody() && !document().documentElement()->renderer()->hasBackground()));
1719 if (!layerRenderer) {
1720 if (drawingRootBackground) {
1721 layerRenderer = &view();
1723 LayoutUnit rw = downcast<RenderView>(*layerRenderer).frameView().contentsWidth();
1724 LayoutUnit rh = downcast<RenderView>(*layerRenderer).frameView().contentsHeight();
1726 rendererRect = LayoutRect(-layerRenderer->marginLeft(),
1727 -layerRenderer->marginTop(),
1728 std::max(layerRenderer->width() + layerRenderer->horizontalMarginExtent() + layerRenderer->borderLeft() + layerRenderer->borderRight(), rw),
1729 std::max(layerRenderer->height() + layerRenderer->verticalMarginExtent() + layerRenderer->borderTop() + layerRenderer->borderBottom(), rh));
1731 layerRenderer = this;
1732 rendererRect = borderBoxRect();
1735 // FIXME: Figure out how to pass absolute position to calculateBackgroundImageGeometry (for pixel snapping)
1736 BackgroundImageGeometry geometry = layerRenderer->calculateBackgroundImageGeometry(nullptr, *curLayer, LayoutPoint(), rendererRect);
1737 if (geometry.hasNonLocalGeometry()) {
1738 // Rather than incur the costs of computing the paintContainer for renderers with fixed backgrounds
1739 // in order to get the right destRect, just repaint the entire renderer.
1740 layerRenderer->repaint();
1744 LayoutRect rectToRepaint = geometry.destRect();
1745 bool shouldClipToLayer = true;
1747 // If this is the root background layer, we may need to extend the repaintRect if the FrameView has an
1748 // extendedBackground. We should only extend the rect if it is already extending the full width or height
1749 // of the rendererRect.
1750 if (drawingRootBackground && view().frameView().hasExtendedBackgroundRectForPainting()) {
1751 shouldClipToLayer = false;
1752 IntRect extendedBackgroundRect = view().frameView().extendedBackgroundRectForPainting();
1753 if (rectToRepaint.width() == rendererRect.width()) {
1754 rectToRepaint.move(extendedBackgroundRect.x(), 0);
1755 rectToRepaint.setWidth(extendedBackgroundRect.width());
1757 if (rectToRepaint.height() == rendererRect.height()) {
1758 rectToRepaint.move(0, extendedBackgroundRect.y());
1759 rectToRepaint.setHeight(extendedBackgroundRect.height());
1763 layerRenderer->repaintRectangle(rectToRepaint, shouldClipToLayer);
1764 if (geometry.destRect() == rendererRect)
1771 bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset)
1773 if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask)
1776 bool isControlClip = hasControlClip();
1777 bool isOverflowClip = hasOverflowClip() && !layer()->isSelfPaintingLayer();
1779 if (!isControlClip && !isOverflowClip)
1782 if (paintInfo.phase == PaintPhaseOutline)
1783 paintInfo.phase = PaintPhaseChildOutlines;
1784 else if (paintInfo.phase == PaintPhaseChildBlockBackground) {
1785 paintInfo.phase = PaintPhaseBlockBackground;
1786 paintObject(paintInfo, accumulatedOffset);
1787 paintInfo.phase = PaintPhaseChildBlockBackgrounds;
1789 float deviceScaleFactor = document().deviceScaleFactor();
1790 FloatRect clipRect = snapRectToDevicePixels((isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset, currentRenderNamedFlowFragment(), IgnoreOverlayScrollbarSize, paintInfo.phase)), deviceScaleFactor);
1791 paintInfo.context().save();
1792 if (style().hasBorderRadius())
1793 paintInfo.context().clipRoundedRect(style().getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size())).pixelSnappedRoundedRectForPainting(deviceScaleFactor));
1794 paintInfo.context().clip(clipRect);
1798 void RenderBox::popContentsClip(PaintInfo& paintInfo, PaintPhase originalPhase, const LayoutPoint& accumulatedOffset)
1800 ASSERT(hasControlClip() || (hasOverflowClip() && !layer()->isSelfPaintingLayer()));
1802 paintInfo.context().restore();
1803 if (originalPhase == PaintPhaseOutline) {
1804 paintInfo.phase = PaintPhaseSelfOutline;
1805 paintObject(paintInfo, accumulatedOffset);
1806 paintInfo.phase = originalPhase;
1807 } else if (originalPhase == PaintPhaseChildBlockBackground)
1808 paintInfo.phase = originalPhase;
1811 LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, RenderRegion* region, OverlayScrollbarSizeRelevancy relevancy, PaintPhase)
1813 // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
1815 LayoutRect clipRect = borderBoxRectInRegion(region);
1816 clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
1817 clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
1819 // Subtract out scrollbars if we have them.
1821 if (style().shouldPlaceBlockDirectionScrollbarOnLeft())
1822 clipRect.move(layer()->verticalScrollbarWidth(relevancy), 0);
1823 clipRect.contract(layer()->verticalScrollbarWidth(relevancy), layer()->horizontalScrollbarHeight(relevancy));
1829 LayoutRect RenderBox::clipRect(const LayoutPoint& location, RenderRegion* region)
1831 LayoutRect borderBoxRect = borderBoxRectInRegion(region);
1832 LayoutRect clipRect = LayoutRect(borderBoxRect.location() + location, borderBoxRect.size());
1834 if (!style().clipLeft().isAuto()) {
1835 LayoutUnit c = valueForLength(style().clipLeft(), borderBoxRect.width());
1836 clipRect.move(c, 0);
1837 clipRect.contract(c, 0);
1840 // We don't use the region-specific border box's width and height since clip offsets are (stupidly) specified
1841 // from the left and top edges. Therefore it's better to avoid constraining to smaller widths and heights.
1843 if (!style().clipRight().isAuto())
1844 clipRect.contract(width() - valueForLength(style().clipRight(), width()), 0);
1846 if (!style().clipTop().isAuto()) {
1847 LayoutUnit c = valueForLength(style().clipTop(), borderBoxRect.height());
1848 clipRect.move(0, c);
1849 clipRect.contract(0, c);
1852 if (!style().clipBottom().isAuto())
1853 clipRect.contract(0, height() - valueForLength(style().clipBottom(), height()));
1858 LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock& cb, RenderRegion* region) const
1860 RenderRegion* containingBlockRegion = nullptr;
1861 LayoutUnit logicalTopPosition = logicalTop();
1863 LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1864 logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
1865 containingBlockRegion = cb.clampToStartAndEndRegions(region);
1868 LayoutUnit logicalHeight = cb.logicalHeightForChild(*this);
1869 LayoutUnit result = cb.availableLogicalWidthForLineInRegion(logicalTopPosition, DoNotIndentText, containingBlockRegion, logicalHeight) - childMarginStart - childMarginEnd;
1871 // We need to see if margins on either the start side or the end side can contain the floats in question. If they can,
1872 // then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line
1873 // offset at all, but can instead push all the way to the content edge of the containing block. In the case where the float
1874 // 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
1875 // "consumed" by the float. Negative margins aren't consumed by the float, and so we ignore them.
1876 if (childMarginStart > 0) {
1877 LayoutUnit startContentSide = cb.startOffsetForContent(containingBlockRegion);
1878 LayoutUnit startContentSideWithMargin = startContentSide + childMarginStart;
1879 LayoutUnit startOffset = cb.startOffsetForLineInRegion(logicalTopPosition, DoNotIndentText, containingBlockRegion, logicalHeight);
1880 if (startOffset > startContentSideWithMargin)
1881 result += childMarginStart;
1883 result += startOffset - startContentSide;
1886 if (childMarginEnd > 0) {
1887 LayoutUnit endContentSide = cb.endOffsetForContent(containingBlockRegion);
1888 LayoutUnit endContentSideWithMargin = endContentSide + childMarginEnd;
1889 LayoutUnit endOffset = cb.endOffsetForLineInRegion(logicalTopPosition, DoNotIndentText, containingBlockRegion, logicalHeight);
1890 if (endOffset > endContentSideWithMargin)
1891 result += childMarginEnd;
1893 result += endOffset - endContentSide;
1899 LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const
1901 #if ENABLE(CSS_GRID_LAYOUT)
1902 if (hasOverrideContainingBlockLogicalWidth()) {
1903 if (auto overrideLogicalWidth = overrideContainingBlockContentLogicalWidth())
1904 return overrideLogicalWidth.value();
1908 if (RenderBlock* cb = containingBlock())
1909 return cb->availableLogicalWidth();
1910 return LayoutUnit();
1913 LayoutUnit RenderBox::containingBlockLogicalHeightForContent(AvailableLogicalHeightType heightType) const
1915 #if ENABLE(CSS_GRID_LAYOUT)
1916 if (hasOverrideContainingBlockLogicalHeight()) {
1917 if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight())
1918 return overrideLogicalHeight.value();
1922 if (RenderBlock* cb = containingBlock())
1923 return cb->availableLogicalHeight(heightType);
1924 return LayoutUnit();
1927 LayoutUnit RenderBox::containingBlockLogicalWidthForContentInRegion(RenderRegion* region) const
1930 return containingBlockLogicalWidthForContent();
1932 RenderBlock* cb = containingBlock();
1933 RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
1934 // FIXME: It's unclear if a region's content should use the containing block's override logical width.
1935 // If it should, the following line should call containingBlockLogicalWidthForContent.
1936 LayoutUnit result = cb->availableLogicalWidth();
1937 RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(containingBlockRegion);
1940 return std::max<LayoutUnit>(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
1943 LayoutUnit RenderBox::containingBlockAvailableLineWidthInRegion(RenderRegion* region) const
1945 RenderBlock* cb = containingBlock();
1946 RenderRegion* containingBlockRegion = nullptr;
1947 LayoutUnit logicalTopPosition = logicalTop();
1949 LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1950 logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
1951 containingBlockRegion = cb->clampToStartAndEndRegions(region);
1953 return cb->availableLogicalWidthForLineInRegion(logicalTopPosition, DoNotIndentText, containingBlockRegion, availableLogicalHeight(IncludeMarginBorderPadding));
1956 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
1958 #if ENABLE(CSS_GRID_LAYOUT)
1959 if (hasOverrideContainingBlockLogicalHeight()) {
1960 if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight())
1961 return overrideLogicalHeight.value();
1965 RenderBlock* cb = containingBlock();
1966 if (cb->hasOverrideLogicalContentHeight())
1967 return cb->overrideLogicalContentHeight();
1969 const RenderStyle& containingBlockStyle = cb->style();
1970 Length logicalHeightLength = containingBlockStyle.logicalHeight();
1972 // FIXME: For now just support fixed heights. Eventually should support percentage heights as well.
1973 if (!logicalHeightLength.isFixed()) {
1974 LayoutUnit fillFallbackExtent = containingBlockStyle.isHorizontalWritingMode() ? view().frameView().visibleHeight() : view().frameView().visibleWidth();
1975 LayoutUnit fillAvailableExtent = containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding);
1976 return std::min(fillAvailableExtent, fillFallbackExtent);
1979 // Use the content box logical height as specified by the style.
1980 return cb->adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(logicalHeightLength.value()));
1983 void RenderBox::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
1985 if (repaintContainer == this)
1988 if (view().layoutStateEnabled() && !repaintContainer) {
1989 LayoutState* layoutState = view().layoutState();
1990 LayoutSize offset = layoutState->m_paintOffset + locationOffset();
1991 if (style().hasInFlowPosition() && layer())
1992 offset += layer()->offsetForInFlowPosition();
1993 transformState.move(offset);
1997 bool containerSkipped;
1998 RenderElement* container = this->container(repaintContainer, &containerSkipped);
2002 bool isFixedPos = style().position() == FixedPosition;
2003 // If this box has a transform, it acts as a fixed position container for fixed descendants,
2004 // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
2005 if (hasTransform() && !isFixedPos)
2007 else if (isFixedPos)
2011 *wasFixed = mode & IsFixed;
2013 LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint(transformState.mappedPoint()));
2015 bool preserve3D = mode & UseTransforms && (container->style().preserves3D() || style().preserves3D());
2016 if (mode & UseTransforms && shouldUseTransformFromContainer(container)) {
2017 TransformationMatrix t;
2018 getTransformFromContainer(container, containerOffset, t);
2019 transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2021 transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2023 if (containerSkipped) {
2024 // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe
2025 // to just subtract the delta between the repaintContainer and o.
2026 LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(*container);
2027 transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2031 mode &= ~ApplyContainerFlip;
2033 // For fixed positioned elements inside out-of-flow named flows, we do not want to
2034 // map their position further to regions based on their coordinates inside the named flows.
2035 if (!container->isOutOfFlowRenderFlowThread() || !fixedPositionedWithNamedFlowContainingBlock())
2036 container->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed);
2038 container->mapLocalToContainer(downcast<RenderLayerModelObject>(container), transformState, mode, wasFixed);
2041 const RenderObject* RenderBox::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
2043 ASSERT(ancestorToStopAt != this);
2045 bool ancestorSkipped;
2046 RenderElement* container = this->container(ancestorToStopAt, &ancestorSkipped);
2050 bool isFixedPos = style().position() == FixedPosition;
2051 LayoutSize adjustmentForSkippedAncestor;
2052 if (ancestorSkipped) {
2053 // There can't be a transform between repaintContainer and container, because transforms create containers, so it should be safe
2054 // to just subtract the delta between the ancestor and container.
2055 adjustmentForSkippedAncestor = -ancestorToStopAt->offsetFromAncestorContainer(*container);
2058 bool offsetDependsOnPoint = false;
2059 LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint(), &offsetDependsOnPoint);
2061 bool preserve3D = container->style().preserves3D() || style().preserves3D();
2062 if (shouldUseTransformFromContainer(container) && (geometryMap.mapCoordinatesFlags() & UseTransforms)) {
2063 TransformationMatrix t;
2064 getTransformFromContainer(container, containerOffset, t);
2065 t.translateRight(adjustmentForSkippedAncestor.width(), adjustmentForSkippedAncestor.height());
2067 geometryMap.push(this, t, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform());
2069 containerOffset += adjustmentForSkippedAncestor;
2070 geometryMap.push(this, containerOffset, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform());
2073 return ancestorSkipped ? ancestorToStopAt : container;
2076 void RenderBox::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
2078 bool isFixedPos = style().position() == FixedPosition;
2079 if (hasTransform() && !isFixedPos) {
2080 // If this box has a transform, it acts as a fixed position container for fixed descendants,
2081 // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
2083 } else if (isFixedPos)
2086 RenderBoxModelObject::mapAbsoluteToLocalPoint(mode, transformState);
2089 LayoutSize RenderBox::offsetFromContainer(RenderElement& renderer, const LayoutPoint&, bool* offsetDependsOnPoint) const
2091 // A region "has" boxes inside it without being their container.
2092 ASSERT(&renderer == container() || is<RenderRegion>(renderer));
2095 if (isInFlowPositioned())
2096 offset += offsetForInFlowPosition();
2098 if (!isInline() || isReplaced())
2099 offset += topLeftLocationOffset();
2101 if (is<RenderBox>(renderer))
2102 offset -= downcast<RenderBox>(renderer).scrolledContentOffset();
2104 if (style().position() == AbsolutePosition && renderer.isInFlowPositioned() && is<RenderInline>(renderer))
2105 offset += downcast<RenderInline>(renderer).offsetForInFlowPositionedInline(this);
2107 if (offsetDependsOnPoint)
2108 *offsetDependsOnPoint |= is<RenderFlowThread>(renderer);
2113 std::unique_ptr<InlineElementBox> RenderBox::createInlineBox()
2115 return std::make_unique<InlineElementBox>(*this);
2118 void RenderBox::dirtyLineBoxes(bool fullLayout)
2120 if (m_inlineBoxWrapper) {
2122 delete m_inlineBoxWrapper;
2123 m_inlineBoxWrapper = nullptr;
2125 m_inlineBoxWrapper->dirtyLineBoxes();
2129 void RenderBox::positionLineBox(InlineElementBox& box)
2131 if (isOutOfFlowPositioned()) {
2132 // Cache the x position only if we were an INLINE type originally.
2133 bool wasInline = style().isOriginalDisplayInlineType();
2135 // The value is cached in the xPos of the box. We only need this value if
2136 // our object was inline originally, since otherwise it would have ended up underneath
2138 RootInlineBox& rootBox = box.root();
2139 rootBox.blockFlow().setStaticInlinePositionForChild(*this, rootBox.lineTopWithLeading(), LayoutUnit::fromFloatRound(box.logicalLeft()));
2140 if (style().hasStaticInlinePosition(box.isHorizontal()))
2141 setChildNeedsLayout(MarkOnlyThis); // Just mark the positioned object as needing layout, so it will update its position properly.
2143 // Our object was a block originally, so we make our normal flow position be
2144 // just below the line box (as though all the inlines that came before us got
2145 // wrapped in an anonymous block, which is what would have happened had we been
2146 // in flow). This value was cached in the y() of the box.
2147 layer()->setStaticBlockPosition(box.logicalTop());
2148 if (style().hasStaticBlockPosition(box.isHorizontal()))
2149 setChildNeedsLayout(MarkOnlyThis); // Just mark the positioned object as needing layout, so it will update its position properly.
2153 box.removeFromParent();
2159 setLocation(LayoutPoint(box.topLeft()));
2160 setInlineBoxWrapper(&box);
2164 void RenderBox::deleteLineBoxWrapper()
2166 if (m_inlineBoxWrapper) {
2167 if (!documentBeingDestroyed())
2168 m_inlineBoxWrapper->removeFromParent();
2169 delete m_inlineBoxWrapper;
2170 m_inlineBoxWrapper = nullptr;
2174 LayoutRect RenderBox::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
2176 if (style().visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
2177 return LayoutRect();
2178 LayoutRect r = visualOverflowRect();
2179 // FIXME: layoutDelta needs to be applied in parts before/after transforms and
2180 // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
2181 r.move(view().layoutDelta());
2182 return computeRectForRepaint(r, repaintContainer);
2185 static inline bool shouldApplyContainersClipAndOffset(const RenderLayerModelObject* repaintContainer, RenderBox* containerBox)
2188 if (!repaintContainer || repaintContainer != containerBox)
2191 return !containerBox->hasLayer() || !containerBox->layer()->usesCompositedScrolling();
2193 UNUSED_PARAM(repaintContainer);
2194 UNUSED_PARAM(containerBox);
2199 LayoutRect RenderBox::computeRectForRepaint(const LayoutRect& rect, const RenderLayerModelObject* repaintContainer, bool fixed) const
2201 // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
2202 // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
2203 // offset corner for the enclosing container). This allows for a fully RL or BT document to repaint
2204 // properly even during layout, since the rect remains flipped all the way until the end.
2206 // RenderView::computeRectForRepaint then converts the rect to physical coordinates. We also convert to
2207 // physical when we hit a repaintContainer boundary. Therefore the final rect returned is always in the
2208 // physical coordinate space of the repaintContainer.
2209 LayoutRect adjustedRect = rect;
2210 const RenderStyle& styleToUse = style();
2211 // LayoutState is only valid for root-relative, non-fixed position repainting
2212 if (view().layoutStateEnabled() && !repaintContainer && styleToUse.position() != FixedPosition) {
2213 LayoutState* layoutState = view().layoutState();
2215 if (layer() && layer()->transform())
2216 adjustedRect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(adjustedRect), document().deviceScaleFactor()));
2218 // We can't trust the bits on RenderObject, because this might be called while re-resolving style.
2219 if (styleToUse.hasInFlowPosition() && layer())
2220 adjustedRect.move(layer()->offsetForInFlowPosition());
2222 adjustedRect.moveBy(location());
2223 adjustedRect.move(layoutState->m_paintOffset);
2224 if (layoutState->m_clipped)
2225 adjustedRect.intersect(layoutState->m_clipRect);
2226 return adjustedRect;
2229 if (hasReflection())
2230 adjustedRect.unite(reflectedRect(adjustedRect));
2232 if (repaintContainer == this) {
2233 if (repaintContainer->style().isFlippedBlocksWritingMode())
2234 flipForWritingMode(adjustedRect);
2235 return adjustedRect;
2238 bool containerSkipped;
2239 auto* renderer = container(repaintContainer, &containerSkipped);
2241 return adjustedRect;
2243 EPosition position = styleToUse.position();
2245 // This code isn't necessary for in-flow RenderFlowThreads.
2246 // Don't add the location of the region in the flow thread for absolute positioned
2247 // elements because their absolute position already pushes them down through
2248 // the regions so adding this here and then adding the topLeft again would cause
2249 // us to add the height twice.
2250 // The same logic applies for elements flowed directly into the flow thread. Their topLeft member
2251 // will already contain the portion rect of the region.
2252 if (renderer->isOutOfFlowRenderFlowThread() && position != AbsolutePosition && containingBlock() != flowThreadContainingBlock()) {
2253 RenderRegion* firstRegion = nullptr;
2254 RenderRegion* lastRegion = nullptr;
2255 if (downcast<RenderFlowThread>(*renderer).getRegionRangeForBox(this, firstRegion, lastRegion))
2256 adjustedRect.moveBy(firstRegion->flowThreadPortionRect().location());
2259 if (isWritingModeRoot() && !isOutOfFlowPositioned())
2260 flipForWritingMode(adjustedRect);
2262 LayoutSize locationOffset = this->locationOffset();
2263 // FIXME: This is needed as long as RenderWidget snaps to integral size/position.
2264 if (isRenderReplaced() && isWidget()) {
2265 LayoutSize flooredLocationOffset = toIntSize(flooredIntPoint(locationOffset));
2266 adjustedRect.expand(locationOffset - flooredLocationOffset);
2267 locationOffset = flooredLocationOffset;
2269 LayoutPoint topLeft = adjustedRect.location();
2270 topLeft.move(locationOffset);
2272 // We are now in our parent container's coordinate space. Apply our transform to obtain a bounding box
2273 // in the parent's coordinate space that encloses us.
2274 if (hasLayer() && layer()->transform()) {
2275 fixed = position == FixedPosition;
2276 adjustedRect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(adjustedRect), document().deviceScaleFactor()));
2277 topLeft = adjustedRect.location();
2278 topLeft.move(locationOffset);
2279 } else if (position == FixedPosition)
2282 if (position == AbsolutePosition && renderer->isInFlowPositioned() && is<RenderInline>(*renderer))
2283 topLeft += downcast<RenderInline>(*renderer).offsetForInFlowPositionedInline(this);
2284 else if (styleToUse.hasInFlowPosition() && layer()) {
2285 // Apply the relative position offset when invalidating a rectangle. The layer
2286 // is translated, but the render box isn't, so we need to do this to get the
2287 // right dirty rect. Since this is called from RenderObject::setStyle, the relative position
2288 // flag on the RenderObject has been cleared, so use the one on the style().
2289 topLeft += layer()->offsetForInFlowPosition();
2292 // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
2293 // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
2294 adjustedRect.setLocation(topLeft);
2295 if (renderer->hasOverflowClip()) {
2296 RenderBox& containerBox = downcast<RenderBox>(*renderer);
2297 if (shouldApplyContainersClipAndOffset(repaintContainer, &containerBox)) {
2298 containerBox.applyCachedClipAndScrollOffsetForRepaint(adjustedRect);
2299 if (adjustedRect.isEmpty())
2300 return adjustedRect;
2304 if (containerSkipped) {
2305 // If the repaintContainer is below o, then we need to map the rect into repaintContainer's coordinates.
2306 LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(*renderer);
2307 adjustedRect.move(-containerOffset);
2308 return adjustedRect;
2310 return renderer->computeRectForRepaint(adjustedRect, repaintContainer, fixed);
2313 void RenderBox::repaintDuringLayoutIfMoved(const LayoutRect& oldRect)
2315 if (oldRect.location() != m_frameRect.location()) {
2316 LayoutRect newRect = m_frameRect;
2317 // The child moved. Invalidate the object's old and new positions. We have to do this
2318 // since the object may not have gotten a layout.
2319 m_frameRect = oldRect;
2321 repaintOverhangingFloats(true);
2322 m_frameRect = newRect;
2324 repaintOverhangingFloats(true);
2328 void RenderBox::repaintOverhangingFloats(bool)
2332 void RenderBox::updateLogicalWidth()
2334 LogicalExtentComputedValues computedValues;
2335 computeLogicalWidthInRegion(computedValues);
2337 setLogicalWidth(computedValues.m_extent);
2338 setLogicalLeft(computedValues.m_position);
2339 setMarginStart(computedValues.m_margins.m_start);
2340 setMarginEnd(computedValues.m_margins.m_end);
2343 void RenderBox::computeLogicalWidthInRegion(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
2345 computedValues.m_extent = logicalWidth();
2346 computedValues.m_position = logicalLeft();
2347 computedValues.m_margins.m_start = marginStart();
2348 computedValues.m_margins.m_end = marginEnd();
2350 if (isOutOfFlowPositioned()) {
2351 // FIXME: This calculation is not patched for block-flow yet.
2352 // https://bugs.webkit.org/show_bug.cgi?id=46500
2353 computePositionedLogicalWidth(computedValues, region);
2357 // If layout is limited to a subtree, the subtree root's logical width does not change.
2358 if (element() && !view().frameView().layoutPending() && view().frameView().layoutRoot() == this)
2361 // The parent box is flexing us, so it has increased or decreased our
2362 // width. Use the width from the style context.
2363 // FIXME: Account for block-flow in flexible boxes.
2364 // https://bugs.webkit.org/show_bug.cgi?id=46418
2365 if (hasOverrideLogicalContentWidth() && (isRubyRun() || style().borderFit() == BorderFitLines || (parent()->isFlexibleBoxIncludingDeprecated()))) {
2366 computedValues.m_extent = overrideLogicalContentWidth() + borderAndPaddingLogicalWidth();
2370 // FIXME: Account for block-flow in flexible boxes.
2371 // https://bugs.webkit.org/show_bug.cgi?id=46418
2372 bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == VERTICAL);
2373 bool stretching = (parent()->style().boxAlign() == BSTRETCH);
2374 // FIXME: Stretching is the only reason why we don't want the box to be treated as a replaced element, so we could perhaps
2375 // refactor all this logic, not only for flex and grid since alignment is intended to be applied to any block.
2376 bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
2377 #if ENABLE(CSS_GRID_LAYOUT)
2378 treatAsReplaced = treatAsReplaced && (!isGridItem() || !hasStretchedLogicalWidth());
2381 const RenderStyle& styleToUse = style();
2382 Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse.logicalWidth();
2384 RenderBlock& cb = *containingBlock();
2385 LayoutUnit containerLogicalWidth = std::max<LayoutUnit>(0, containingBlockLogicalWidthForContentInRegion(region));
2386 bool hasPerpendicularContainingBlock = cb.isHorizontalWritingMode() != isHorizontalWritingMode();
2388 if (isInline() && !isInlineBlockOrInlineTable()) {
2389 // just calculate margins
2390 computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2391 computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2392 if (treatAsReplaced)
2393 computedValues.m_extent = std::max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
2397 // Width calculations
2398 if (treatAsReplaced) {
2399 computedValues.m_extent = logicalWidthLength.value() + borderAndPaddingLogicalWidth();
2400 #if ENABLE(CSS_GRID_LAYOUT)
2401 } else if (parent()->isRenderGrid() && style().logicalWidth().isAuto() && style().logicalMinWidth().isAuto() && style().overflowX() == OVISIBLE && containerLogicalWidth < minPreferredLogicalWidth()) {
2402 // TODO (lajava) Move this logic to the LayoutGrid class.
2403 // Implied minimum size of Grid items.
2404 computedValues.m_extent = constrainLogicalWidthInRegionByMinMax(minPreferredLogicalWidth(), containerLogicalWidth, cb);
2407 LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
2408 if (hasPerpendicularContainingBlock)
2409 containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
2410 LayoutUnit preferredWidth = computeLogicalWidthInRegionUsing(MainOrPreferredSize, styleToUse.logicalWidth(), containerWidthInInlineDirection, cb, region);
2411 computedValues.m_extent = constrainLogicalWidthInRegionByMinMax(preferredWidth, containerWidthInInlineDirection, cb, region);
2414 // Margin calculations.
2415 if (hasPerpendicularContainingBlock || isFloating() || isInline()) {
2416 computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2417 computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2419 LayoutUnit containerLogicalWidthForAutoMargins = containerLogicalWidth;
2420 if (avoidsFloats() && cb.containsFloats())
2421 containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInRegion(region);
2422 bool hasInvertedDirection = cb.style().isLeftToRightDirection() != style().isLeftToRightDirection();
2423 computeInlineDirectionMargins(cb, containerLogicalWidthForAutoMargins, computedValues.m_extent,
2424 hasInvertedDirection ? computedValues.m_margins.m_end : computedValues.m_margins.m_start,
2425 hasInvertedDirection ? computedValues.m_margins.m_start : computedValues.m_margins.m_end);
2428 if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (computedValues.m_extent + computedValues.m_margins.m_start + computedValues.m_margins.m_end)
2429 && !isFloating() && !isInline() && !cb.isFlexibleBoxIncludingDeprecated()
2430 #if ENABLE(CSS_GRID_LAYOUT)
2431 && !cb.isRenderGrid()
2434 LayoutUnit newMargin = containerLogicalWidth - computedValues.m_extent - cb.marginStartForChild(*this);
2435 bool hasInvertedDirection = cb.style().isLeftToRightDirection() != style().isLeftToRightDirection();
2436 if (hasInvertedDirection)
2437 computedValues.m_margins.m_start = newMargin;
2439 computedValues.m_margins.m_end = newMargin;
2443 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth) const
2445 LayoutUnit marginStart = 0;
2446 LayoutUnit marginEnd = 0;
2447 return fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2450 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2452 marginStart = minimumValueForLength(style().marginStart(), availableLogicalWidth);
2453 marginEnd = minimumValueForLength(style().marginEnd(), availableLogicalWidth);
2454 return availableLogicalWidth - marginStart - marginEnd;
2457 LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(Length logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const
2459 if (logicalWidthLength.type() == FillAvailable)
2460 return fillAvailableMeasure(availableLogicalWidth);
2462 LayoutUnit minLogicalWidth = 0;
2463 LayoutUnit maxLogicalWidth = 0;
2464 computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
2466 if (logicalWidthLength.type() == MinContent)
2467 return minLogicalWidth + borderAndPadding;
2469 if (logicalWidthLength.type() == MaxContent)
2470 return maxLogicalWidth + borderAndPadding;
2472 if (logicalWidthLength.type() == FitContent) {
2473 minLogicalWidth += borderAndPadding;
2474 maxLogicalWidth += borderAndPadding;
2475 return std::max(minLogicalWidth, std::min(maxLogicalWidth, fillAvailableMeasure(availableLogicalWidth)));
2478 ASSERT_NOT_REACHED();
2482 LayoutUnit RenderBox::computeLogicalWidthInRegionUsing(SizeType widthType, Length logicalWidth, LayoutUnit availableLogicalWidth,
2483 const RenderBlock& cb, RenderRegion* region) const
2485 ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto());
2486 if (widthType == MinSize && logicalWidth.isAuto())
2487 return adjustBorderBoxLogicalWidthForBoxSizing(0);
2489 if (!logicalWidth.isIntrinsicOrAuto()) {
2490 // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
2491 return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth));
2494 if (logicalWidth.isIntrinsic())
2495 return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth());
2497 LayoutUnit marginStart = 0;
2498 LayoutUnit marginEnd = 0;
2499 LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2501 if (shrinkToAvoidFloats() && cb.containsFloats())
2502 logicalWidthResult = std::min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, region));
2504 if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(widthType))
2505 return std::max(minPreferredLogicalWidth(), std::min(maxPreferredLogicalWidth(), logicalWidthResult));
2506 return logicalWidthResult;
2509 static bool flexItemHasStretchAlignment(const RenderBox& flexitem)
2511 auto parent = flexitem.parent();
2512 return RenderStyle::resolveAlignment(parent->style(), flexitem.style(), ItemPositionStretch) == ItemPositionStretch;
2515 static bool isStretchingColumnFlexItem(const RenderBox& flexitem)
2517 auto parent = flexitem.parent();
2518 if (parent->isDeprecatedFlexibleBox() && parent->style().boxOrient() == VERTICAL && parent->style().boxAlign() == BSTRETCH)
2521 // We don't stretch multiline flexboxes because they need to apply line spacing (align-content) first.
2522 if (parent->isFlexibleBox() && parent->style().flexWrap() == FlexNoWrap && parent->style().isColumnFlexDirection() && flexItemHasStretchAlignment(flexitem))
2527 // FIXME: Can/Should we move this inside specific layout classes (flex. grid)? Can we refactor columnFlexItemHasStretchAlignment logic?
2528 bool RenderBox::hasStretchedLogicalWidth() const
2530 auto& style = this->style();
2531 if (!style.logicalWidth().isAuto() || style.marginStart().isAuto() || style.marginEnd().isAuto())
2533 RenderBlock* containingBlock = this->containingBlock();
2534 if (!containingBlock) {
2535 // We are evaluating align-self/justify-self, which default to 'normal' for the root element.
2536 // The 'normal' value behaves like 'start' except for Flexbox Items, which obviously should have a container.
2539 if (containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2540 return RenderStyle::resolveAlignment(containingBlock->style(), style, ItemPositionStretch) == ItemPositionStretch;
2541 return RenderStyle::resolveJustification(containingBlock->style(), style, ItemPositionStretch) == ItemPositionStretch;
2544 bool RenderBox::sizesLogicalWidthToFitContent(SizeType widthType) const
2546 // Anonymous inline blocks always fill the width of their containing block.
2547 if (isAnonymousInlineBlock())
2550 // Marquees in WinIE are like a mixture of blocks and inline-blocks. They size as though they're blocks,
2551 // but they allow text to sit on the same line as the marquee.
2552 if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee()))
2555 #if ENABLE(CSS_GRID_LAYOUT)
2557 return !hasStretchedLogicalWidth();
2560 // This code may look a bit strange. Basically width:intrinsic should clamp the size when testing both
2561 // min-width and width. max-width is only clamped if it is also intrinsic.
2562 Length logicalWidth = (widthType == MaxSize) ? style().logicalMaxWidth() : style().logicalWidth();
2563 if (logicalWidth.type() == Intrinsic)
2566 // Children of a horizontal marquee do not fill the container by default.
2567 // FIXME: Need to deal with MAUTO value properly. It could be vertical.
2568 // FIXME: Think about block-flow here. Need to find out how marquee direction relates to
2569 // block-flow (as well as how marquee overflow should relate to block flow).
2570 // https://bugs.webkit.org/show_bug.cgi?id=46472
2571 if (parent()->isHTMLMarquee()) {
2572 EMarqueeDirection dir = parent()->style().marqueeDirection();
2573 if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
2577 // Flexible box items should shrink wrap, so we lay them out at their intrinsic widths.
2578 // In the case of columns that have a stretch alignment, we layout at the stretched size
2579 // to avoid an extra layout when applying alignment.
2580 if (parent()->isFlexibleBox()) {
2581 // For multiline columns, we need to apply align-content first, so we can't stretch now.
2582 if (!parent()->style().isColumnFlexDirection() || parent()->style().flexWrap() != FlexNoWrap)
2584 if (!flexItemHasStretchAlignment(*this))
2588 // Flexible horizontal boxes lay out children at their intrinsic widths. Also vertical boxes
2589 // that don't stretch their kids lay out their children at their intrinsic widths.
2590 // FIXME: Think about block-flow here.
2591 // https://bugs.webkit.org/show_bug.cgi?id=46473
2592 if (parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == HORIZONTAL || parent()->style().boxAlign() != BSTRETCH))
2595 // Button, input, select, textarea, and legend treat width value of 'auto' as 'intrinsic' unless it's in a
2596 // stretching column flexbox.
2597 // FIXME: Think about block-flow here.
2598 // https://bugs.webkit.org/show_bug.cgi?id=46473
2599 if (logicalWidth.type() == Auto && !isStretchingColumnFlexItem(*this) && element() && (is<HTMLInputElement>(*element()) || is<HTMLSelectElement>(*element()) || is<HTMLButtonElement>(*element()) || is<HTMLTextAreaElement>(*element()) || is<HTMLLegendElement>(*element())))
2602 if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
2608 void RenderBox::computeInlineDirectionMargins(RenderBlock& containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2610 const RenderStyle& containingBlockStyle = containingBlock.style();
2611 Length marginStartLength = style().marginStartUsing(&containingBlockStyle);
2612 Length marginEndLength = style().marginEndUsing(&containingBlockStyle);
2614 if (isFloating() || isInline()) {
2615 // Inline blocks/tables and floats don't have their margins increased.
2616 marginStart = minimumValueForLength(marginStartLength, containerWidth);
2617 marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2621 // Case One: The object is being centered in the containing block's available logical width.
2622 if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
2623 || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock.style().textAlign() == WEBKIT_CENTER)) {
2624 // Other browsers center the margin box for align=center elements so we match them here.
2625 LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth);
2626 LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth);
2627 LayoutUnit centeredMarginBoxStart = std::max<LayoutUnit>(0, (containerWidth - childWidth - marginStartWidth - marginEndWidth) / 2);
2628 marginStart = centeredMarginBoxStart + marginStartWidth;
2629 marginEnd = containerWidth - childWidth - marginStart + marginEndWidth;
2633 // Case Two: The object is being pushed to the start of the containing block's available logical width.
2634 if (marginEndLength.isAuto() && childWidth < containerWidth) {
2635 marginStart = valueForLength(marginStartLength, containerWidth);
2636 marginEnd = containerWidth - childWidth - marginStart;
2640 // Case Three: The object is being pushed to the end of the containing block's available logical width.
2641 bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_LEFT)
2642 || (containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_RIGHT));
2643 if ((marginStartLength.isAuto() && childWidth < containerWidth) || pushToEndFromTextAlign) {
2644 marginEnd = valueForLength(marginEndLength, containerWidth);
2645 marginStart = containerWidth - childWidth - marginEnd;
2649 // Case Four: Either no auto margins, or our width is >= the container width (css2.1, 10.3.3). In that case
2650 // auto margins will just turn into 0.
2651 marginStart = minimumValueForLength(marginStartLength, containerWidth);
2652 marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2655 RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
2657 // Make sure nobody is trying to call this with a null region.
2661 // If we have computed our width in this region already, it will be cached, and we can
2663 RenderBoxRegionInfo* boxInfo = region->renderBoxRegionInfo(this);
2664 if (boxInfo && cacheFlag == CacheRenderBoxRegionInfo)
2667 // No cached value was found, so we have to compute our insets in this region.
2668 // FIXME: For now we limit this computation to normal RenderBlocks. Future patches will expand
2669 // support to cover all boxes.
2670 RenderFlowThread* flowThread = flowThreadContainingBlock();
2671 if (isRenderFlowThread() || !flowThread || !canHaveBoxInfoInRegion() || flowThread->style().writingMode() != style().writingMode())
2674 LogicalExtentComputedValues computedValues;
2675 computeLogicalWidthInRegion(computedValues, region);
2677 // Now determine the insets based off where this object is supposed to be positioned.
2678 RenderBlock& cb = *containingBlock();
2679 RenderRegion* clampedContainingBlockRegion = cb.clampToStartAndEndRegions(region);
2680 RenderBoxRegionInfo* containingBlockInfo = cb.renderBoxRegionInfo(clampedContainingBlockRegion);
2681 LayoutUnit containingBlockLogicalWidth = cb.logicalWidth();
2682 LayoutUnit containingBlockLogicalWidthInRegion = containingBlockInfo ? containingBlockInfo->logicalWidth() : containingBlockLogicalWidth;
2684 LayoutUnit marginStartInRegion = computedValues.m_margins.m_start;
2685 LayoutUnit startMarginDelta = marginStartInRegion - marginStart();
2686 LayoutUnit logicalWidthInRegion = computedValues.m_extent;
2687 LayoutUnit logicalLeftInRegion = computedValues.m_position;
2688 LayoutUnit widthDelta = logicalWidthInRegion - logicalWidth();
2689 LayoutUnit logicalLeftDelta = isOutOfFlowPositioned() ? logicalLeftInRegion - logicalLeft() : startMarginDelta;
2690 LayoutUnit logicalRightInRegion = containingBlockLogicalWidthInRegion - (logicalLeftInRegion + logicalWidthInRegion);
2691 LayoutUnit oldLogicalRight = containingBlockLogicalWidth - (logicalLeft() + logicalWidth());
2692 LayoutUnit logicalRightDelta = isOutOfFlowPositioned() ? logicalRightInRegion - oldLogicalRight : startMarginDelta;
2694 LayoutUnit logicalLeftOffset = 0;
2696 if (!isOutOfFlowPositioned() && avoidsFloats() && cb.containsFloats()) {
2697 LayoutUnit startPositionDelta = cb.computeStartPositionDeltaForChildAvoidingFloats(*this, marginStartInRegion, region);
2698 if (cb.style().isLeftToRightDirection())
2699 logicalLeftDelta += startPositionDelta;
2701 logicalRightDelta += startPositionDelta;
2704 if (cb.style().isLeftToRightDirection())
2705 logicalLeftOffset += logicalLeftDelta;
2707 logicalLeftOffset -= (widthDelta + logicalRightDelta);
2709 LayoutUnit logicalRightOffset = logicalWidth() - (logicalLeftOffset + logicalWidthInRegion);
2710 bool isShifted = (containingBlockInfo && containingBlockInfo->isShifted())
2711 || (style().isLeftToRightDirection() && logicalLeftOffset)
2712 || (!style().isLeftToRightDirection() && logicalRightOffset);
2714 // FIXME: Although it's unlikely, these boxes can go outside our bounds, and so we will need to incorporate them into overflow.
2715 if (cacheFlag == CacheRenderBoxRegionInfo)
2716 return region->setRenderBoxRegionInfo(this, logicalLeftOffset, logicalWidthInRegion, isShifted);
2717 return new RenderBoxRegionInfo(logicalLeftOffset, logicalWidthInRegion, isShifted);
2720 static bool shouldFlipBeforeAfterMargins(const RenderStyle& containingBlockStyle, const RenderStyle* childStyle)
2722 ASSERT(containingBlockStyle.isHorizontalWritingMode() != childStyle->isHorizontalWritingMode());
2723 WritingMode childWritingMode = childStyle->writingMode();
2724 bool shouldFlip = false;
2725 switch (containingBlockStyle.writingMode()) {
2726 case TopToBottomWritingMode:
2727 shouldFlip = (childWritingMode == RightToLeftWritingMode);
2729 case BottomToTopWritingMode:
2730 shouldFlip = (childWritingMode == RightToLeftWritingMode);
2732 case RightToLeftWritingMode:
2733 shouldFlip = (childWritingMode == BottomToTopWritingMode);
2735 case LeftToRightWritingMode:
2736 shouldFlip = (childWritingMode == BottomToTopWritingMode);
2740 if (!containingBlockStyle.isLeftToRightDirection())
2741 shouldFlip = !shouldFlip;
2746 void RenderBox::updateLogicalHeight()
2748 LogicalExtentComputedValues computedValues;
2749 computeLogicalHeight(logicalHeight(), logicalTop(), computedValues);
2751 setLogicalHeight(computedValues.m_extent);
2752 setLogicalTop(computedValues.m_position);
2753 setMarginBefore(computedValues.m_margins.m_before);
2754 setMarginAfter(computedValues.m_margins.m_after);
2757 void RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
2759 computedValues.m_extent = logicalHeight;
2760 computedValues.m_position = logicalTop;
2762 // Cell height is managed by the table and inline non-replaced elements do not support a height property.
2763 if (isTableCell() || (isInline() && !isReplaced()))
2767 if (isOutOfFlowPositioned())
2768 computePositionedLogicalHeight(computedValues);
2770 RenderBlock& cb = *containingBlock();
2771 bool hasPerpendicularContainingBlock = cb.isHorizontalWritingMode() != isHorizontalWritingMode();
2773 if (!hasPerpendicularContainingBlock) {
2774 bool shouldFlipBeforeAfter = cb.style().writingMode() != style().writingMode();
2775 computeBlockDirectionMargins(cb,
2776 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2777 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2780 // For tables, calculate margins only.
2782 if (hasPerpendicularContainingBlock) {
2783 bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb.style(), &style());
2784 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), computedValues.m_extent,
2785 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2786 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2791 // FIXME: Account for block-flow in flexible boxes.
2792 // https://bugs.webkit.org/show_bug.cgi?id=46418
2793 bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style().boxOrient() == HORIZONTAL;
2794 bool stretching = parent()->style().boxAlign() == BSTRETCH;
2795 bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
2796 bool checkMinMaxHeight = false;
2798 // The parent box is flexing us, so it has increased or decreased our height. We have to
2799 // grab our cached flexible height.
2800 // FIXME: Account for block-flow in flexible boxes.
2801 // https://bugs.webkit.org/show_bug.cgi?id=46418
2802 if (hasOverrideLogicalContentHeight() && (parent()->isFlexibleBoxIncludingDeprecated()
2803 #if ENABLE(CSS_GRID_LAYOUT)
2804 || parent()->isRenderGrid()
2807 LayoutUnit contentHeight = overrideLogicalContentHeight();
2808 #if ENABLE(CSS_GRID_LAYOUT)
2809 if (parent()->isRenderGrid() && style().logicalHeight().isAuto() && style().logicalMinHeight().isAuto() && style().overflowX() == OVISIBLE) {
2810 LayoutUnit intrinsicContentHeight = computedValues.m_extent - borderAndPaddingLogicalHeight();
2811 if (auto minContentHeight = computeContentLogicalHeight(MinSize, Length(MinContent), intrinsicContentHeight))
2812 contentHeight = std::max(contentHeight, constrainContentBoxLogicalHeightByMinMax(minContentHeight.value(), intrinsicContentHeight));
2815 h = Length(contentHeight, Fixed);
2816 } else if (treatAsReplaced)
2817 h = Length(computeReplacedLogicalHeight(), Fixed);
2819 h = style().logicalHeight();
2820 checkMinMaxHeight = true;
2823 // Block children of horizontal flexible boxes fill the height of the box.
2824 // FIXME: Account for block-flow in flexible boxes.
2825 // https://bugs.webkit.org/show_bug.cgi?id=46418
2826 if (h.isAuto() && is<RenderDeprecatedFlexibleBox>(*parent()) && parent()->style().boxOrient() == HORIZONTAL
2827 && downcast<RenderDeprecatedFlexibleBox>(*parent()).isStretchingChildren()) {
2828 h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2829 checkMinMaxHeight = false;
2832 LayoutUnit heightResult;
2833 if (checkMinMaxHeight) {
2834 LayoutUnit intrinsicHeight = computedValues.m_extent - borderAndPaddingLogicalHeight();
2835 heightResult = computeLogicalHeightUsing(MainOrPreferredSize, style().logicalHeight(), intrinsicHeight).valueOr(computedValues.m_extent);
2836 heightResult = constrainLogicalHeightByMinMax(heightResult, intrinsicHeight);
2838 // The only times we don't check min/max height are when a fixed length has
2839 // been given as an override. Just use that. The value has already been adjusted
2841 ASSERT(h.isFixed());
2842 heightResult = h.value() + borderAndPaddingLogicalHeight();
2845 computedValues.m_extent = heightResult;
2847 if (hasPerpendicularContainingBlock) {
2848 bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb.style(), &style());
2849 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult,
2850 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2851 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2855 // WinIE quirk: The <html> block always fills the entire canvas in quirks mode. The <body> always fills the
2856 // <html> block in quirks mode. Only apply this quirk if the block is normal flow and no height
2857 // is specified. When we're printing, we also need this quirk if the body or root has a percentage
2858 // height since we don't set a height in RenderView when we're printing. So without this quirk, the
2859 // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2860 bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercentOrCalculated()
2861 && (isDocumentElementRenderer() || (isBody() && document().documentElement()->renderer()->style().logicalHeight().isPercentOrCalculated())) && !isInline();
2862 if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2863 LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2864 LayoutUnit visibleHeight = view().pageOrViewLogicalHeight();
2865 if (isDocumentElementRenderer())
2866 computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - margins);
2868 LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2869 computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - marginsBordersPadding);
2874 Optional<LayoutUnit> RenderBox::computeLogicalHeightUsing(SizeType heightType, const Length& height, Optional<LayoutUnit> intrinsicContentHeight) const
2876 if (Optional<LayoutUnit> logicalHeight = computeContentAndScrollbarLogicalHeightUsing(heightType, height, intrinsicContentHeight))
2877 return adjustBorderBoxLogicalHeightForBoxSizing(logicalHeight.value());
2881 Optional<LayoutUnit> RenderBox::computeContentLogicalHeight(SizeType heightType, const Length& height, Optional<LayoutUnit> intrinsicContentHeight) const
2883 if (Optional<LayoutUnit> heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(heightType, height, intrinsicContentHeight))
2884 return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2888 Optional<LayoutUnit> RenderBox::computeIntrinsicLogicalContentHeightUsing(Length logicalHeightLength, Optional<LayoutUnit> intrinsicContentHeight, LayoutUnit borderAndPadding) const
2890 // FIXME: The CSS sizing spec is considering changing what min-content/max-content should resolve to.
2891 // If that happens, this code will have to change.
2892 if (logicalHeightLength.isMinContent() || logicalHeightLength.isMaxContent() || logicalHeightLength.isFitContent())
2893 return intrinsicContentHeight;
2894 if (logicalHeightLength.isFillAvailable())
2895 return containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding) - borderAndPadding;
2896 ASSERT_NOT_REACHED();
2897 return LayoutUnit(0);
2900 Optional<LayoutUnit> RenderBox::computeContentAndScrollbarLogicalHeightUsing(SizeType heightType, const Length& height, Optional<LayoutUnit> intrinsicContentHeight) const
2902 if (height.isAuto())
2903 return heightType == MinSize ? Optional<LayoutUnit>(0) : Nullopt;
2904 // FIXME: The CSS sizing spec is considering changing what min-content/max-content should resolve to.
2905 // If that happens, this code will have to change.
2906 if (height.isIntrinsic())
2907 return computeIntrinsicLogicalContentHeightUsing(height, intrinsicContentHeight, borderAndPaddingLogicalHeight());
2908 if (height.isFixed())
2909 return LayoutUnit(height.value());
2910 if (height.isPercentOrCalculated())
2911 return computePercentageLogicalHeight(height);
2915 bool RenderBox::skipContainingBlockForPercentHeightCalculation(const RenderBox& containingBlock, bool isPerpendicularWritingMode) const
2917 // Flow threads for multicol or paged overflow should be skipped. They are invisible to the DOM,
2918 // and percent heights of children should be resolved against the multicol or paged container.
2919 if (containingBlock.isInFlowRenderFlowThread() && !isPerpendicularWritingMode)
2922 // For quirks mode and anonymous blocks, we skip auto-height containingBlocks when computing percentages.
2923 // For standards mode, we treat the percentage as auto if it has an auto-height containing block.
2924 if (!document().inQuirksMode() && !containingBlock.isAnonymousBlock())
2926 return !containingBlock.isTableCell() && !containingBlock.isOutOfFlowPositioned() && containingBlock.style().logicalHeight().isAuto() && isHorizontalWritingMode() == containingBlock.isHorizontalWritingMode();
2929 static bool tableCellShouldHaveZeroInitialSize(const RenderBlock& block, bool scrollsOverflowY)
2931 // Normally we would let the cell size intrinsically, but scrolling overflow has to be
2932 // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
2933 // While we can't get all cases right, we can at least detect when the cell has a specified
2934 // height or when the table has a specified height. In these cases we want to initially have
2935 // no size and allow the flexing of the table or the cell to its specified height to cause us
2936 // to grow to fill the space. This could end up being wrong in some cases, but it is
2937 // preferable to the alternative (sizing intrinsically and making the row end up too big).
2938 const RenderTableCell& cell = downcast<RenderTableCell>(block);
2939 return scrollsOverflowY && (!cell.style().logicalHeight().isAuto() || !cell.table()->style().logicalHeight().isAuto());
2942 Optional<LayoutUnit> RenderBox::computePercentageLogicalHeight(const Length& height) const
2944 Optional<LayoutUnit> availableHeight;
2946 bool skippedAutoHeightContainingBlock = false;
2947 RenderBlock* cb = containingBlock();
2948 const RenderBox* containingBlockChild = this;
2949 LayoutUnit rootMarginBorderPaddingHeight = 0;
2950 bool isHorizontal = isHorizontalWritingMode();
2951 while (cb && !is<RenderView>(*cb) && skipContainingBlockForPercentHeightCalculation(*cb, isHorizontal != cb->isHorizontalWritingMode())) {
2952 if (cb->isBody() || cb->isDocumentElementRenderer())
2953 rootMarginBorderPaddingHeight += cb->marginBefore() + cb->marginAfter() + cb->borderAndPaddingLogicalHeight();
2954 skippedAutoHeightContainingBlock = true;
2955 containingBlockChild = cb;
2956 cb = cb->containingBlock();
2957 cb->addPercentHeightDescendant(const_cast<RenderBox&>(*this));
2960 const RenderStyle& cbstyle = cb->style();
2962 // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
2963 // explicitly specified that can be used for any percentage computations.
2964 bool isOutOfFlowPositionedWithSpecifiedHeight = cb->isOutOfFlowPositioned() && (!cbstyle.logicalHeight().isAuto() || (!cbstyle.logicalTop().isAuto() && !cbstyle.logicalBottom().isAuto()));
2966 bool includeBorderPadding = isTable();
2968 if (isHorizontal != cb->isHorizontalWritingMode())
2969 availableHeight = containingBlockChild->containingBlockLogicalWidthForContent();
2970 #if ENABLE(CSS_GRID_LAYOUT)
2971 else if (hasOverrideContainingBlockLogicalHeight())
2972 availableHeight = overrideContainingBlockContentLogicalHeight();
2974 else if (is<RenderTableCell>(*cb)) {
2975 if (!skippedAutoHeightContainingBlock) {
2976 // Table cells violate what the CSS spec says to do with heights. Basically we
2977 // don't care if the cell specified a height or not. We just always make ourselves
2978 // be a percentage of the cell's current content height.
2979 if (!cb->hasOverrideLogicalContentHeight())
2980 return tableCellShouldHaveZeroInitialSize(*cb, scrollsOverflowY()) ? Optional<LayoutUnit>() : Nullopt;
2982 availableHeight = cb->overrideLogicalContentHeight();
2983 includeBorderPadding = true;
2985 } else if (cbstyle.logicalHeight().isFixed()) {
2986 LayoutUnit contentBoxHeight = cb->adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(cbstyle.logicalHeight().value()));
2987 availableHeight = std::max<LayoutUnit>(0, cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeight - cb->scrollbarLogicalHeight(), Nullopt));
2988 } else if (cbstyle.logicalHeight().isPercentOrCalculated() && !isOutOfFlowPositionedWithSpecifiedHeight) {
2989 // We need to recur and compute the percentage height for our containing block.
2990 if (Optional<LayoutUnit> heightWithScrollbar = cb->computePercentageLogicalHeight(cbstyle.logicalHeight())) {
2991 LayoutUnit contentBoxHeightWithScrollbar = cb->adjustContentBoxLogicalHeightForBoxSizing(heightWithScrollbar);
2992 // We need to adjust for min/max height because this method does not
2993 // handle the min/max of the current block, its caller does. So the
2994 // return value from the recursive call will not have been adjusted
2996 LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight(), Nullopt);
2997 availableHeight = std::max<LayoutUnit>(0, contentBoxHeight);
2999 } else if (isOutOfFlowPositionedWithSpecifiedHeight) {
3000 // Don't allow this to affect the block' height() member variable, since this
3001 // can get called while the block is still laying out its kids.
3002 LogicalExtentComputedValues computedValues;
3003 cb->computeLogicalHeight(cb->logicalHeight(), 0, computedValues);
3004 availableHeight = computedValues.m_extent - cb->borderAndPaddingLogicalHeight() - cb->scrollbarLogicalHeight();
3005 } else if (cb->isRenderView())
3006 availableHeight = view().pageOrViewLogicalHeight();
3008 if (!availableHeight)
3009 return availableHeight;
3011 LayoutUnit result = valueForLength(height, availableHeight.value() - rootMarginBorderPaddingHeight);
3012 if (includeBorderPadding) {
3013 // FIXME: Table cells should default to box-sizing: border-box so we can avoid this hack.
3014 // It is necessary to use the border-box to match WinIE's broken
3015 // box model. This is essential for sizing inside
3016 // table cells using percentage heights.
3017 result -= borderAndPaddingLogicalHeight();
3018 return std::max<LayoutUnit>(0, result);
3023 LayoutUnit RenderBox::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
3025 return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(MainOrPreferredSize, style().logicalWidth()), shouldComputePreferred);
3028 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, ShouldComputePreferred shouldComputePreferred) const
3030 LayoutUnit minLogicalWidth = (shouldComputePreferred == ComputePreferred && style().logicalMinWidth().isPercentOrCalculated()) || style().logicalMinWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(MinSize, style().logicalMinWidth());
3031 LayoutUnit maxLogicalWidth = (shouldComputePreferred == ComputePreferred && style().logicalMaxWidth().isPercentOrCalculated()) || style().logicalMaxWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(MaxSize, style().logicalMaxWidth());
3032 return std::max(minLogicalWidth, std::min(logicalWidth, maxLogicalWidth));
3035 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(SizeType widthType, Length logicalWidth) const
3037 ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto());
3038 if (widthType == MinSize && logicalWidth.isAuto())
3039 return adjustContentBoxLogicalWidthForBoxSizing(0);
3041 switch (logicalWidth.type()) {
3043 return adjustContentBoxLogicalWidthForBoxSizing(logicalWidth.value());
3046 // MinContent/MaxContent don't need the availableLogicalWidth argument.
3047 LayoutUnit availableLogicalWidth = 0;
3048 return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
3054 // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
3055 // containing block's block-flow.
3056 // https://bugs.webkit.org/show_bug.cgi?id=46496
3057 const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(downcast<RenderBoxModelObject>(*container())) : containingBlockLogicalWidthForContent();
3058 Length containerLogicalWidth = containingBlock()->style().logicalWidth();
3059 // FIXME: Handle cases when containing block width is calculated or viewport percent.
3060 // https://bugs.webkit.org/show_bug.cgi?id=91071
3061 if (logicalWidth.isIntrinsic())
3062 return computeIntrinsicLogicalWidthUsing(logicalWidth, cw, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
3063 if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercentOrCalculated())))
3064 return adjustContentBoxLogicalWidthForBoxSizing(minimumValueForLength(logicalWidth, cw));
3072 return intrinsicLogicalWidth();
3075 ASSERT_NOT_REACHED();
3079 LayoutUnit RenderBox::computeReplacedLogicalHeight() const
3081 return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(MainOrPreferredSize, style().logicalHeight()));
3084 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
3086 LayoutUnit minLogicalHeight = computeReplacedLogicalHeightUsing(MinSize, style().logicalMinHeight());
3087 LayoutUnit maxLogicalHeight = style().logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(MaxSize, style().logicalMaxHeight());
3088 return std::max(minLogicalHeight, std::min(logicalHeight, maxLogicalHeight));
3091 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(SizeType heightType, Length logicalHeight) const
3093 ASSERT(heightType == MinSize || heightType == MainOrPreferredSize || !logicalHeight.isAuto());
3094 if (heightType == MinSize && logicalHeight.isAuto())
3095 return adjustContentBoxLogicalHeightForBoxSizing(Optional<LayoutUnit>(0));
3097 switch (logicalHeight.type()) {
3099 return adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit(logicalHeight.value()));
3103 auto cb = isOutOfFlowPositioned() ? container() : containingBlock();
3104 while (cb && cb->isAnonymous() && !is<RenderView>(*cb)) {
3105 cb = cb->containingBlock();
3106 downcast<RenderBlock>(*cb).addPercentHeightDescendant(const_cast<RenderBox&>(*this));
3109 // FIXME: This calculation is not patched for block-flow yet.
3110 // https://bugs.webkit.org/show_bug.cgi?id=46500
3111 if (cb->isOutOfFlowPositioned() && cb->style().height().isAuto() && !(cb->style().top().isAuto() || cb->style().bottom().isAuto())) {
3112 ASSERT_WITH_SECURITY_IMPLICATION(cb->isRenderBlock());
3113 RenderBlock& block = downcast<RenderBlock>(*cb);
3114 LogicalExtentComputedValues computedValues;
3115 block.computeLogicalHeight(block.logicalHeight(), 0, computedValues);
3116 LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3117 LayoutUnit newHeight = block.adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3118 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, newHeight));
3121 // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
3122 // containing block's block-flow.
3123 // https://bugs.webkit.org/show_bug.cgi?id=46496
3124 LayoutUnit availableHeight;
3125 if (isOutOfFlowPositioned())
3126 availableHeight = containingBlockLogicalHeightForPositioned(downcast<RenderBoxModelObject>(*cb));
3128 availableHeight = containingBlockLogicalHeightForContent(IncludeMarginBorderPadding);
3129 // It is necessary to use the border-box to match WinIE's broken
3130 // box model. This is essential for sizing inside
3131 // table cells using percentage heights.
3132 // FIXME: This needs to be made block-flow-aware. If the cell and image are perpendicular block-flows, this isn't right.
3133 // https://bugs.webkit.org/show_bug.cgi?id=46997
3134 while (cb && !is<RenderView>(*cb) && (cb->style().logicalHeight().isAuto() || cb->style().logicalHeight().isPercentOrCalculated())) {
3135 if (cb->isTableCell()) {
3136 // Don't let table cells squeeze percent-height replaced elements
3137 // <http://bugs.webkit.org/show_bug.cgi?id=15359>
3138 availableHeight = std::max(availableHeight, intrinsicLogicalHeight());
3139 return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight());
3141 downcast<RenderBlock>(*cb).addPercentHeightDescendant(const_cast<RenderBox&>(*this));
3142 cb = cb->containingBlock();
3145 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight));
3151 return adjustContentBoxLogicalHeightForBoxSizing(computeIntrinsicLogicalContentHeightUsing(logicalHeight, intrinsicLogicalHeight(), borderAndPaddingLogicalHeight()));
3153 return intrinsicLogicalHeight();
3157 LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const
3159 return constrainLogicalHeightByMinMax(availableLogicalHeightUsing(style().logicalHeight(), heightType), Nullopt);
3162 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const
3164 // We need to stop here, since we don't want to increase the height of the table
3165 // artificially. We're going to rely on this cell getting expanded to some new
3166 // height, and then when we lay out again we'll use the calculation below.
3167 if (isTableCell() && (h.isAuto() || h.isPercentOrCalculated())) {
3168 if (hasOverrideLogicalContentHeight())
3169 return overrideLogicalContentHeight();
3170 return logicalHeight() - borderAndPaddingLogicalHeight();
3173 if (h.isPercentOrCalculated() && isOutOfFlowPositioned() && !isRenderFlowThread()) {
3174 // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3175 LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(*containingBlock());
3176 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight));
3179 if (Optional<LayoutUnit> heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(MainOrPreferredSize, h, Nullopt))
3180 return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
3182 // FIXME: Check logicalTop/logicalBottom here to correctly handle vertical writing-mode.
3183 // https://bugs.webkit.org/show_bug.cgi?id=46500
3184 if (is<RenderBlock>(*this) && isOutOfFlowPositioned() && style().height().isAuto() && !(style().top().isAuto() || style().bottom().isAuto())) {
3185 RenderBlock& block = const_cast<RenderBlock&>(downcast<RenderBlock>(*this));
3186 LogicalExtentComputedValues computedValues;
3187 block.computeLogicalHeight(block.logicalHeight(), 0, computedValues);
3188 LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3189 return adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3192 // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3193 LayoutUnit availableHeight = containingBlockLogicalHeightForContent(heightType);
3194 if (heightType == ExcludeMarginBorderPadding) {
3195 // FIXME: Margin collapsing hasn't happened yet, so this incorrectly removes collapsed margins.
3196 availableHeight -= marginBefore() + marginAfter() + borderAndPaddingLogicalHeight();
3198 return availableHeight;
3201 void RenderBox::computeBlockDirectionMargins(const RenderBlock& containingBlock, LayoutUnit& marginBefore, LayoutUnit& marginAfter) const
3203 if (isTableCell()) {
3204 // FIXME: Not right if we allow cells to have different directionality than the table. If we do allow this, though,
3205 // we may just do it with an extra anonymous block inside the cell.
3211 // Margins are calculated with respect to the logical width of
3212 // the containing block (8.3)
3213 LayoutUnit cw = containingBlockLogicalWidthForContent();
3214 const RenderStyle& containingBlockStyle = containingBlock.style();
3215 marginBefore = minimumValueForLength(style().marginBeforeUsing(&containingBlockStyle), cw);
3216 marginAfter = minimumValueForLength(style().marginAfterUsing(&containingBlockStyle), cw);
3219 void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock& containingBlock)
3221 LayoutUnit marginBefore;
3222 LayoutUnit marginAfter;
3223 computeBlockDirectionMargins(containingBlock, marginBefore, marginAfter);
3224 containingBlock.setMarginBeforeForChild(*this, marginBefore);
3225 containingBlock.setMarginAfterForChild(*this, marginAfter);
3228 LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject& containingBlock, RenderRegion* region, bool checkForPerpendicularWritingMode) const
3230 if (checkForPerpendicularWritingMode && containingBlock.isHorizontalWritingMode() != isHorizontalWritingMode())
3231 return containingBlockLogicalHeightForPositioned(containingBlock, false);
3233 #if ENABLE(CSS_GRID_LAYOUT)
3234 if (hasOverrideContainingBlockLogicalWidth()) {
3235 if (auto overrideLogicalWidth = overrideContainingBlockContentLogicalWidth())
3236 return overrideLogicalWidth.value();
3240 if (is<RenderBox>(containingBlock)) {
3241 bool isFixedPosition = style().position() == FixedPosition;
3243 RenderFlowThread* flowThread = flowThreadContainingBlock();
3245 if (isFixedPosition && is<RenderView>(containingBlock))
3246 return downcast<RenderView>(containingBlock).clientLogicalWidthForFixedPosition();
3248 return downcast<RenderBox>(containingBlock).clientLogicalWidth();
3251 if (isFixedPosition && is<RenderNamedFlowThread>(containingBlock))
3252 return containingBlock.view().clientLogicalWidth();
3254 if (!is<RenderBlock>(containingBlock))
3255 return downcast<RenderBox>(containingBlock).clientLogicalWidth();
3257 const RenderBlock& cb = downcast<RenderBlock>(containingBlock);
3258 RenderBoxRegionInfo* boxInfo = nullptr;
3260 if (is<RenderFlowThread>(containingBlock) && !checkForPerpendicularWritingMode)
3261 return downcast<RenderFlowThread>(containingBlock).contentLogicalWidthOfFirstRegion();
3262 if (isWritingModeRoot()) {
3263 LayoutUnit cbPageOffset = cb.offsetFromLogicalTopOfFirstPage();
3264 RenderRegion* cbRegion = cb.regionAtBlockOffset(cbPageOffset);
3266 boxInfo = cb.renderBoxRegionInfo(cbRegion);
3268 } else if (flowThread->isHorizontalWritingMode() == containingBlock.isHorizontalWritingMode()) {
3269 RenderRegion* containingBlockRegion = cb.clampToStartAndEndRegions(region);
3270 boxInfo = cb.renderBoxRegionInfo(containingBlockRegion);
3272 return (boxInfo) ? std::max<LayoutUnit>(0, cb.clientLogicalWidth() - (cb.logicalWidth() - boxInfo->logicalWidth())) : cb.clientLogicalWidth();
3275 ASSERT(containingBlock.isInFlowPositioned());
3277 const auto& flow = downcast<RenderInline>(containingBlock);
3278 InlineFlowBox* first = flow.firstLineBox();
3279 InlineFlowBox* last = flow.lastLineBox();
3281 // If the containing block is empty, return a width of 0.
3282 if (!first || !last)
3285 LayoutUnit fromLeft;
3286 LayoutUnit fromRight;
3287 if (containingBlock.style().isLeftToRightDirection()) {
3288 fromLeft = first->logicalLeft() + first->borderLogicalLeft();
3289 fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
3291 fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
3292 fromLeft = last->logicalLeft() + last->borderLogicalLeft();
3295 return std::max<LayoutUnit>(0, fromRight - fromLeft);
3298 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject& containingBlock, bool checkForPerpendicularWritingMode) const
3300 if (checkForPerpendicularWritingMode && containingBlock.isHorizontalWritingMode() != isHorizontalWritingMode())
3301 return containingBlockLogicalWidthForPositioned(containingBlock, nullptr, false);
3303 #if ENABLE(CSS_GRID_LAYOUT)
3304 if (hasOverrideContainingBlockLogicalHeight()) {
3305 if (auto overrideLogicalHeight = overrideContainingBlockContentLogicalHeight())
3306 return overrideLogicalHeight.value();
3310 if (containingBlock.isBox()) {
3311 bool isFixedPosition = style().position() == FixedPosition;
3313 if (isFixedPosition && is<RenderView>(containingBlock))
3314 return downcast<RenderView>(containingBlock).clientLogicalHeightForFixedPosition();
3316 const RenderBlock& cb = is<RenderBlock>(containingBlock) ? downcast<RenderBlock>(containingBlock) : *containingBlock.containingBlock();
3317 LayoutUnit result = cb.clientLogicalHeight();
3318 RenderFlowThread* flowThread = flowThreadContainingBlock();
3319 if (flowThread && is<RenderFlowThread>(containingBlock) && flowThread->isHorizontalWritingMode() == containingBlock.isHorizontalWritingMode()) {
3320 if (is<RenderNamedFlowThread>(containingBlock) && isFixedPosition)
3321 return containingBlock.view().clientLogicalHeight();
3322 return downcast<RenderFlowThread>(containingBlock).contentLogicalHeightOfFirstRegion();
3327 ASSERT(containingBlock.isInFlowPositioned());
3329 const auto& flow = downcast<RenderInline>(containingBlock);
3330 InlineFlowBox* first = flow.firstLineBox();
3331 InlineFlowBox* last = flow.lastLineBox();
3333 // If the containing block is empty, return a height of 0.
3334 if (!first || !last)
3337 LayoutUnit heightResult;
3338 LayoutRect boundingBox = flow.linesBoundingBox();
3339 if (containingBlock.isHorizontalWritingMode())
3340 heightResult = boundingBox.height();
3342 heightResult = boundingBox.width();
3343 heightResult -= (containingBlock.borderBefore() + containingBlock.borderAfter());
3344 return heightResult;
3347 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject& containerBlock, LayoutUnit containerLogicalWidth, RenderRegion* region)
3349 if (!logicalLeft.isAuto() || !logicalRight.isAuto())
3352 // FIXME: The static distance computation has not been patched for mixed writing modes yet.
3353 if (child->parent()->style().direction() == LTR) {
3354 LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock.borderLogicalLeft();
3355 for (auto* current = child->parent(); current && current != &containerBlock; current = current->container()) {
3356 if (!is<RenderBox>(*current))
3358 const auto& renderBox = downcast<RenderBox>(*current);
3359 staticPosition += renderBox.logicalLeft();
3360 if (renderBox.isInFlowPositioned())
3361 staticPosition += renderBox.isHorizontalWritingMode() ? renderBox.offsetForInFlowPosition().width() : renderBox.offsetForInFlowPosition().height();
3362 if (region && is<RenderBlock>(*current)) {
3363 const RenderBlock& currentBlock = downcast<RenderBlock>(*current);
3364 region = currentBlock.clampToStartAndEndRegions(region);
3365 RenderBoxRegionInfo* boxInfo = currentBlock.renderBoxRegionInfo(region);
3367 staticPosition += boxInfo->logicalLeft();
3370 logicalLeft.setValue(Fixed, staticPosition);
3372 const RenderBox& enclosingBox = child->parent()->enclosingBox();
3373 LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock.borderLogicalLeft();
3374 for (const RenderElement* current = &enclosingBox; current; current = current->container()) {
3375 if (is<RenderBox>(*current)) {
3376 if (current != &containerBlock) {
3377 const auto& renderBox = downcast<RenderBox>(*current);
3378 staticPosition -= renderBox.logicalLeft();
3379 if (renderBox.isInFlowPositioned())
3380 staticPosition -= renderBox.isHorizontalWritingMode() ? renderBox.offsetForInFlowPosition().width() : renderBox.offsetForInFlowPosition().height();
3382 if (current == &enclosingBox)
3383 staticPosition -= enclosingBox.logicalWidth();
3384 if (region && is<RenderBlock>(*current)) {
3385 const RenderBlock& currentBlock = downcast<RenderBlock>(*current);
3386 region = currentBlock.clampToStartAndEndRegions(region);
3387 RenderBoxRegionInfo* boxInfo = currentBlock.renderBoxRegionInfo(region);
3389 if (current != &containerBlock)
3390 staticPosition -= currentBlock.logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth());
3391 if (current == &enclosingBox)
3392 staticPosition += enclosingBox.logicalWidth() - boxInfo->logicalWidth();
3396 if (current == &containerBlock)
3399 logicalRight.setValue(Fixed, staticPosition);
3403 void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
3406 // FIXME: Positioned replaced elements inside a flow thread are not working properly
3407 // with variable width regions (see https://bugs.webkit.org/show_bug.cgi?id=69896 ).
3408 computePositionedLogicalWidthReplaced(computedValues);
3413 // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
3414 // the type 'static' in determining whether to calculate the static distance?
3415 // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
3417 // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
3418 // than or less than the computed width(). Be careful of box-sizing and
3419 // percentage issues.
3421 // The following is based off of the W3C Working Draft from April 11, 2006 of
3422 // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
3423 // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
3424 // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
3425 // correspond to text from the spec)
3428 // We don't use containingBlock(), since we may be positioned by an enclosing
3429 // relative positioned inline.
3430 const RenderBoxModelObject& containerBlock = downcast<RenderBoxModelObject>(*container());
3432 const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, region);
3434 // Use the container block's direction except when calculating the static distance
3435 // This conforms with the reference results for abspos-replaced-width-margin-000.htm
3436 // of the CSS 2.1 test suite
3437 TextDirection containerDirection = containerBlock.style().direction();
3439 bool isHorizontal = isHorizontalWritingMode();
3440 const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
3441 const Length marginLogicalLeft = isHorizontal ? style().marginLeft() : style().marginTop();
3442 const Length marginLogicalRight = isHorizontal ? style().marginRight() : style().marginBottom();
3444 Length logicalLeftLength = style().logicalLeft();
3445 Length logicalRightLength = style().logicalRight();
3447 /*---------------------------------------------------------------------------*\
3448 * For the purposes of this section and the next, the term "static position"
3449 * (of an element) refers, roughly, to the position an element would have had
3450 * in the normal flow. More precisely:
3452 * * The static position for 'left' is the distance from the left edge of the
3453 * containing block to the left margin edge of a hypothetical box that would
3454 * have been the first box of the element if its 'position' property had
3455 * been 'static' and 'float' had been 'none'. The value is negative if the
3456 * hypothetical box is to the left of the containing block.
3457 * * The static position for 'right' is the distance from the right edge of the
3458 * containing block to the right margin edge of the same hypothetical box as
3459 * above. The value is positive if the hypothetical box is to the left of the
3460 * containing block's edge.
3462 * But rather than actually calculating the dimensions of that hypothetical box,
3463 * user agents are free to make a guess at its probable position.
3465 * For the purposes of calculating the static position, the containing block of
3466 * fixed positioned elements is the initial containing block instead of the
3467 * viewport, and all scrollable boxes should be assumed to be scrolled to their
3469 \*---------------------------------------------------------------------------*/
3472 // Calculate the static distance if needed.
3473 computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth, region);
3475 // Calculate constraint equation values for 'width' case.
3476 computePositionedLogicalWidthUsing(MainOrPreferredSize, style().logicalWidth(), containerBlock, containerDirection,
3477 containerLogicalWidth, bordersPlusPadding,
3478 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3481 // Calculate constraint equation values for 'max-width' case.
3482 if (!style().logicalMaxWidth().isUndefined()) {
3483 LogicalExtentComputedValues maxValues;
3485 computePositionedLogicalWidthUsing(MaxSize, style().logicalMaxWidth(), containerBlock, containerDirection,
3486 containerLogicalWidth, bordersPlusPadding,
3487 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3490 if (computedValues.m_extent > maxValues.m_extent) {
3491 computedValues.m_extent = maxValues.m_extent;
3492 computedValues.m_position = maxValues.m_position;
3493 computedValues.m_margins.m_start = maxValues.m_margins.m_start;
3494 computedValues.m_margins.m_end = maxValues.m_margins.m_end;
3498 // Calculate constraint equation values for 'min-width' case.
3499 if (!style().logicalMinWidth().isZero() || style().logicalMinWidth().isIntrinsic()) {
3500 LogicalExtentComputedValues minValues;
3502 computePositionedLogicalWidthUsing(MinSize, style().logicalMinWidth(), containerBlock, containerDirection,
3503 containerLogicalWidth, bordersPlusPadding,
3504 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3507 if (computedValues.m_extent < minValues.m_extent) {
3508 computedValues.m_extent = minValues.m_extent;
3509 computedValues.m_position = minValues.m_position;
3510 computedValues.m_margins.m_start = minValues.m_margins.m_start;
3511 computedValues.m_margins.m_end = minValues.m_margins.m_end;
3515 #if ENABLE(CSS_GRID_LAYOUT)
3516 if (!style().hasStaticInlinePosition(isHorizontal))
3517 computedValues.m_position += extraInlineOffset();
3520 computedValues.m_extent += bordersPlusPadding;
3521 if (is<RenderBox>(containerBlock)) {
3522 auto& containingBox = downcast<RenderBox>(containerBlock);
3523 if (containingBox.layer() && containingBox.layer()->verticalScrollbarIsOnLeft())
3524 computedValues.m_position += containingBox.verticalScrollbarWidth();
3527 // Adjust logicalLeft if we need to for the flipped version of our writing mode in regions.
3528 // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock.
3529 RenderFlowThread* flowThread = flowThreadContainingBlock();
3530 if (flowThread && !region && isWritingModeRoot() && isHorizontalWritingMode() == containerBlock.isHorizontalWritingMode() && is<RenderBlock>(containerBlock)) {
3531 ASSERT(containerBlock.canHaveBoxInfoInRegion());
3532 LayoutUnit logicalLeftPos = computedValues.m_position;
3533 const RenderBlock& renderBlock = downcast<RenderBlock>(containerBlock);
3534 LayoutUnit cbPageOffset = renderBlock.offsetFromLogicalTopOfFirstPage();
3535 RenderRegion* cbRegion = renderBlock.regionAtBlockOffset(cbPageOffset);
3537 RenderBoxRegionInfo* boxInfo = renderBlock.renderBoxRegionInfo(cbRegion);
3539 logicalLeftPos += boxInfo->logicalLeft();
3540 computedValues.m_position = logicalLeftPos;
3546 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject& containerBlock, LayoutUnit containerLogicalWidth)
3548 // Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3549 // 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.
3550 if (containerBlock.isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock.style().isFlippedBlocksWritingMode()) {
3551 logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
3552 logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock.borderRight() : containerBlock.borderBottom());
3554 logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock.borderLeft() : containerBlock.borderTop());
3557 void RenderBox::computePositionedLogicalWidthUsing(SizeType widthType, Length logicalWidth, const RenderBoxModelObject& containerBlock, TextDirection containerDirection,
3558 LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
3559 Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight,
3560 LogicalExtentComputedValues& computedValues) const
3562 ASSERT(widthType == MinSize || widthType == MainOrPreferredSize || !logicalWidth.isAuto());
3563 if (widthType == MinSize && logicalWidth.isAuto())
3564 logicalWidth = Length(0, Fixed);
3565 else if (logicalWidth.isIntrinsic())
3566 logicalWidth = Length(computeIntrinsicLogicalWidthUsing(logicalWidth, containerLogicalWidth, bordersPlusPadding) - bordersPlusPadding, Fixed);
3568 // 'left' and 'right' cannot both be 'auto' because one would of been
3569 // converted to the static position already
3570 ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
3572 LayoutUnit logicalLeftValue = 0;
3574 const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, nullptr, false);
3576 bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
3577 bool logicalLeftIsAuto = logicalLeft.isAuto();
3578 bool logicalRightIsAuto = logicalRight.isAuto();
3579 LayoutUnit& marginLogicalLeftValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
3580 LayoutUnit& marginLogicalRightValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
3582 if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3583 /*-----------------------------------------------------------------------*\
3584 * If none of the three is 'auto': If both 'margin-left' and 'margin-
3585 * right' are 'auto', solve the equation under the extra constraint that
3586 * the two margins get equal values, unless this would make them negative,
3587 * in which case when direction of the containing block is 'ltr' ('rtl'),
3588 * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
3589 * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
3590 * solve the equation for that value. If the values are over-constrained,
3591 * ignore the value for 'left' (in case the 'direction' property of the
3592 * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
3593 * and solve for that value.
3594 \*-----------------------------------------------------------------------*/
3595 // NOTE: It is not necessary to solve for 'right' in the over constrained
3596 // case because the value is not used for any further calculations.
3598 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3599 computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3601 const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth) + bordersPlusPadding);
3603 // Margins are now the only unknown
3604 if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
3605 // Both margins auto, solve for equality
3606 if (availableSpace >= 0) {
3607 marginLogicalLeftValue = availableSpace / 2; // split the difference
3608 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
3610 // Use the containing block's direction rather than the parent block's
3611 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3612 if (containerDirection == LTR) {
3613 marginLogicalLeftValue = 0;
3614 marginLogicalRightValue = availableSpace; // will be negative
3616 marginLogicalLeftValue = availableSpace; // will be negative
3617 marginLogicalRightValue = 0;
3620 } else if (marginLogicalLeft.isAuto()) {
3621 // Solve for left margin
3622 marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3623 marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
3624 } else if (marginLogicalRight.isAuto()) {
3625 // Solve for right margin
3626 marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3627 marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
3629 // Over-constrained, solve for left if direction is RTL
3630 marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3631 marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3633 // Use the containing block's direction rather than the parent block's
3634 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3635 if (containerDirection == RTL)
3636 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
3639 /*--------------------------------------------------------------------*\
3640 * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
3641 * to 0, and pick the one of the following six rules that applies.
3643 * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
3644 * width is shrink-to-fit. Then solve for 'left'
3646 * OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3647 * ------------------------------------------------------------------
3648 * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
3649 * the 'direction' property of the containing block is 'ltr' set
3650 * 'left' to the static position, otherwise set 'right' to the
3651 * static position. Then solve for 'left' (if 'direction is 'rtl')
3652 * or 'right' (if 'direction' is 'ltr').
3653 * ------------------------------------------------------------------
3655 * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
3656 * width is shrink-to-fit . Then solve for 'right'
3657 * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
3659 * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
3661 * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
3664 * Calculation of the shrink-to-fit width is similar to calculating the
3665 * width of a table cell using the automatic table layout algorithm.
3666 * Roughly: calculate the preferred width by formatting the content
3667 * without breaking lines other than where explicit line breaks occur,
3668 * and also calculate the preferred minimum width, e.g., by trying all
3669 * possible line breaks. CSS 2.1 does not define the exact algorithm.
3670 * Thirdly, calculate the available width: this is found by solving
3671 * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
3674 * Then the shrink-to-fit width is:
3675 * min(max(preferred minimum width, available width), preferred width).
3676 \*--------------------------------------------------------------------*/
3677 // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
3678 // because the value is not used for any further calculations.
3680 // Calculate margins, 'auto' margins are ignored.
3681 marginLogicalLeftValue = minimumValueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3682 marginLogicalRightValue = minimumValueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3684 const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
3686 // FIXME: Is there a faster way to find the correct case?
3687 // Use rule/case that applies.
3688 if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3689 // RULE 1: (use shrink-to-fit for width, and solve of left)
3690 LayoutUnit logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3692 // FIXME: would it be better to have shrink-to-fit in one step?
3693 LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3694 LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3695 LayoutUnit availableWidth = availableSpace - logicalRightValue;
3696 computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3697 logicalLeftValue = availableSpace - (computedValues.m_extent + logicalRightValue);
3698 } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
3699 // RULE 3: (use shrink-to-fit for width, and no need solve of right)
3700 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3702 // FIXME: would it be better to have shrink-to-fit in one step?
3703 LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3704 LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3705 LayoutUnit availableWidth = availableSpace - logicalLeftValue;
3706 computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3707 } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3708 // RULE 4: (solve for left)
3709 computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3710 logicalLeftValue = availableSpace - (computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth));
3711 } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3712 // RULE 5: (solve for width)
3713 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3714 computedValues.m_extent = availableSpace - (logicalLeftValue + valueForLength(logicalRight, containerLogicalWidth));
3715 } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
3716 // RULE 6: (no need solve for right)
3717 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3718 computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3722 // Use computed values to calculate the horizontal position.
3724 // FIXME: This hack is needed to calculate the logical left position for a 'rtl' relatively
3725 // positioned, inline because right now, it is using the logical left position
3726 // of the first line box when really it should use the last line box. When
3727 // this is fixed elsewhere, this block should be removed.
3728 if (is<RenderInline>(containerBlock) && !containerBlock.style().isLeftToRightDirection()) {
3729 const auto& flow = downcast<RenderInline>(containerBlock);
3730 InlineFlowBox* firstLine = flow.firstLineBox();
3731 InlineFlowBox* lastLine = flow.lastLineBox();
3732 if (firstLine && lastLine && firstLine != lastLine) {
3733 computedValues.m_position = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
3738 computedValues.m_position = logicalLeftValue + marginLogicalLeftValue;
3739 computeLogicalLeftPositionedOffset(computedValues.m_position, this, computedValues.m_extent, containerBlock, containerLogicalWidth);
3742 static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject& containerBlock)
3744 if (!logicalTop.isAuto() || !logicalBottom.isAuto())
3747 // FIXME: The static distance computation has not been patched for mixed writing modes.
3748 LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock.borderBefore();
3749 for (RenderElement* container = child->parent(); container && container != &containerBlock; container = container->container()) {
3750 if (!is<RenderBox>(*container))
3752 const auto& renderBox = downcast<RenderBox>(*container);
3753 if (!is<RenderTableRow>(renderBox))
3754 staticLogicalTop += renderBox.logicalTop();
3755 if (renderBox.isInFlowPositioned())
3756 staticLogicalTop += renderBox.isHorizontalWritingMode() ? renderBox.offsetForInFlowPosition().height() : renderBox.offsetForInFlowPosition().width();
3758 logicalTop.setValue(Fixed, staticLogicalTop);
3761 void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& computedValues) const
3764 computePositionedLogicalHeightReplaced(computedValues);
3768 // The following is based off of the W3C Working Draft from April 11, 2006 of
3769 // CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
3770 // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
3771 // (block-style-comments in this function and in computePositionedLogicalHeightUsing()
3772 // correspond to text from the spec)
3775 // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
3776 const RenderBoxModelObject& containerBlock = downcast<RenderBoxModelObject>(*container());
3778 const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
3780 const RenderStyle& styleToUse = style();
3781 const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
3782 const Length marginBefore = styleToUse.marginBefore();
3783 const Length marginAfter = styleToUse.marginAfter();
3784 Length logicalTopLength = styleToUse.logicalTop();
3785 Length logicalBottomLength = styleToUse.logicalBottom();
3787 /*---------------------------------------------------------------------------*\
3788 * For the purposes of this section and the next, the term "static position"
3789 * (of an element) refers, roughly, to the position an element would have had
3790 * in the normal flow. More precisely, the static position for 'top' is the
3791 * distance from the top edge of the containing block to the top margin edge
3792 * of a hypothetical box that would have been the first box of the element if
3793 * its 'position' property had been 'static' and 'float' had been 'none'. The
3794 * value is negative if the hypothetical box is above the containing block.
3796 * But rather than actually calculating the dimensions of that hypothetical
3797 * box, user agents are free to make a guess at its probable position.
3799 * For the purposes of calculating the static position, the containing block
3800 * of fixed positioned elements is the initial containing block instead of
3802 \*---------------------------------------------------------------------------*/
3805 // Calculate the static distance if needed.
3806 computeBlockStaticDistance(logicalTopLength, logicalBottomLength, this, containerBlock);
3808 // Calculate constraint equation values for 'height' case.
3809 LayoutUnit logicalHeight = computedValues.m_extent;
3810 computePositionedLogicalHeightUsing(MainOrPreferredSize, styleToUse.logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3811 logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3814 // Avoid doing any work in the common case (where the values of min-height and max-height are their defaults).