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, 2006, 2007, 2008, 2009, 2010 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"
29 #include "ChromeClient.h"
31 #include "EventHandler.h"
32 #include "FloatQuad.h"
33 #include "FloatRoundedRect.h"
35 #include "FrameView.h"
36 #include "GraphicsContext.h"
37 #include "HTMLBodyElement.h"
38 #include "HTMLButtonElement.h"
39 #include "HTMLElement.h"
40 #include "HTMLFrameOwnerElement.h"
41 #include "HTMLInputElement.h"
42 #include "HTMLNames.h"
43 #include "HTMLTextAreaElement.h"
44 #include "HitTestResult.h"
45 #include "InlineElementBox.h"
47 #include "PaintInfo.h"
48 #include "RenderBoxRegionInfo.h"
49 #include "RenderDeprecatedFlexibleBox.h"
50 #include "RenderFlexibleBox.h"
51 #include "RenderGeometryMap.h"
52 #include "RenderInline.h"
53 #include "RenderIterator.h"
54 #include "RenderLayer.h"
55 #include "RenderLayerBacking.h"
56 #include "RenderLayerCompositor.h"
57 #include "RenderNamedFlowFragment.h"
58 #include "RenderNamedFlowThread.h"
59 #include "RenderTableCell.h"
60 #include "RenderTheme.h"
61 #include "RenderView.h"
62 #include "ScrollbarTheme.h"
63 #include "TransformState.h"
64 #include "htmlediting.h"
67 #include <wtf/StackStats.h>
75 struct SameSizeAsRenderBox : public RenderBoxModelObject {
76 virtual ~SameSizeAsRenderBox() { }
78 LayoutBoxExtent marginBox;
79 LayoutUnit preferredLogicalWidths[2];
83 COMPILE_ASSERT(sizeof(RenderBox) == sizeof(SameSizeAsRenderBox), RenderBox_should_stay_small);
85 using namespace HTMLNames;
87 // Used by flexible boxes when flexing this element and by table cells.
88 typedef WTF::HashMap<const RenderBox*, LayoutUnit> OverrideSizeMap;
89 static OverrideSizeMap* gOverrideHeightMap = nullptr;
90 static OverrideSizeMap* gOverrideWidthMap = nullptr;
92 #if ENABLE(CSS_GRID_LAYOUT)
93 // Used by grid elements to properly size their grid items.
94 static OverrideSizeMap* gOverrideContainingBlockLogicalHeightMap = nullptr;
95 static OverrideSizeMap* gOverrideContainingBlockLogicalWidthMap = nullptr;
98 // Size of border belt for autoscroll. When mouse pointer in border belt,
99 // autoscroll is started.
100 static const int autoscrollBeltSize = 20;
101 static const unsigned backgroundObscurationTestMaxDepth = 4;
103 bool RenderBox::s_hadOverflowClip = false;
105 static bool skipBodyBackground(const RenderBox* bodyElementRenderer)
107 ASSERT(bodyElementRenderer->isBody());
108 // The <body> only paints its background if the root element has defined a background independent of the body,
109 // or if the <body>'s parent is not the document element's renderer (e.g. inside SVG foreignObject).
110 auto documentElementRenderer = bodyElementRenderer->document().documentElement()->renderer();
112 if (!documentElementRenderer)
115 if (documentElementRenderer->hasBackground())
118 if (documentElementRenderer != bodyElementRenderer->parent())
121 if (bodyElementRenderer->isComposited() && documentElementRenderer->isComposited())
122 return downcast<RenderLayerModelObject>(documentElementRenderer)->layer()->backing()->graphicsLayer()->drawsContent();
127 RenderBox::RenderBox(Element& element, Ref<RenderStyle>&& style, unsigned baseTypeFlags)
128 : RenderBoxModelObject(element, WTF::move(style), baseTypeFlags)
129 , m_minPreferredLogicalWidth(-1)
130 , m_maxPreferredLogicalWidth(-1)
131 , m_inlineBoxWrapper(nullptr)
136 RenderBox::RenderBox(Document& document, Ref<RenderStyle>&& style, unsigned baseTypeFlags)
137 : RenderBoxModelObject(document, WTF::move(style), baseTypeFlags)
138 , m_minPreferredLogicalWidth(-1)
139 , m_maxPreferredLogicalWidth(-1)
140 , m_inlineBoxWrapper(nullptr)
145 RenderBox::~RenderBox()
147 if (frame().eventHandler().autoscrollRenderer() == this)
148 frame().eventHandler().stopAutoscrollTimer(true);
151 #if ENABLE(CSS_GRID_LAYOUT)
152 clearContainingBlockOverrideSize();
155 RenderBlock::removePercentHeightDescendantIfNeeded(*this);
157 #if ENABLE(CSS_SHAPES)
158 ShapeOutsideInfo::removeInfo(*this);
161 view().unscheduleLazyRepaint(*this);
162 if (hasControlStatesForRenderer(this))
163 removeControlStatesForRenderer(this);
166 RenderRegion* RenderBox::clampToStartAndEndRegions(RenderRegion* region) const
168 RenderFlowThread* flowThread = flowThreadContainingBlock();
170 ASSERT(isRenderView() || (region && flowThread));
174 // We need to clamp to the block, since we want any lines or blocks that overflow out of the
175 // logical top or logical bottom of the block to size as though the border box in the first and
176 // last regions extended infinitely. Otherwise the lines are going to size according to the regions
177 // they overflow into, which makes no sense when this block doesn't exist in |region| at all.
178 RenderRegion* startRegion = nullptr;
179 RenderRegion* endRegion = nullptr;
180 if (!flowThread->getRegionRangeForBox(this, startRegion, endRegion))
183 if (region->logicalTopForFlowThreadContent() < startRegion->logicalTopForFlowThreadContent())
185 if (region->logicalTopForFlowThreadContent() > endRegion->logicalTopForFlowThreadContent())
191 bool RenderBox::hasRegionRangeInFlowThread() const
193 RenderFlowThread* flowThread = flowThreadContainingBlock();
194 if (!flowThread || !flowThread->hasValidRegionInfo())
197 return flowThread->hasCachedRegionRangeForBox(this);
200 LayoutRect RenderBox::clientBoxRectInRegion(RenderRegion* region) const
203 return clientBoxRect();
205 LayoutRect clientBox = borderBoxRectInRegion(region);
206 clientBox.setLocation(clientBox.location() + LayoutSize(borderLeft(), borderTop()));
207 clientBox.setSize(clientBox.size() - LayoutSize(borderLeft() + borderRight() + verticalScrollbarWidth(), borderTop() + borderBottom() + horizontalScrollbarHeight()));
212 LayoutRect RenderBox::borderBoxRectInRegion(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
215 return borderBoxRect();
217 RenderFlowThread* flowThread = flowThreadContainingBlock();
219 return borderBoxRect();
221 RenderRegion* startRegion = nullptr;
222 RenderRegion* endRegion = nullptr;
223 if (!flowThread->getRegionRangeForBox(this, startRegion, endRegion)) {
224 // FIXME: In a perfect world this condition should never happen.
225 return borderBoxRect();
228 ASSERT(flowThread->regionInRange(region, startRegion, endRegion));
230 // Compute the logical width and placement in this region.
231 RenderBoxRegionInfo* boxInfo = renderBoxRegionInfo(region, cacheFlag);
233 return borderBoxRect();
235 // We have cached insets.
236 LayoutUnit logicalWidth = boxInfo->logicalWidth();
237 LayoutUnit logicalLeft = boxInfo->logicalLeft();
239 // Now apply the parent inset since it is cumulative whenever anything in the containing block chain shifts.
240 // FIXME: Doesn't work right with perpendicular writing modes.
241 const RenderBlock* currentBox = containingBlock();
242 RenderBoxRegionInfo* currentBoxInfo = isRenderFlowThread() ? nullptr : currentBox->renderBoxRegionInfo(region);
243 while (currentBoxInfo && currentBoxInfo->isShifted()) {
244 if (currentBox->style().direction() == LTR)
245 logicalLeft += currentBoxInfo->logicalLeft();
247 logicalLeft -= (currentBox->logicalWidth() - currentBoxInfo->logicalWidth()) - currentBoxInfo->logicalLeft();
249 // Once we reach the fragmentation container we should stop.
250 if (currentBox->isRenderFlowThread())
253 currentBox = currentBox->containingBlock();
254 region = currentBox->clampToStartAndEndRegions(region);
255 currentBoxInfo = currentBox->renderBoxRegionInfo(region);
258 if (cacheFlag == DoNotCacheRenderBoxRegionInfo)
261 if (isHorizontalWritingMode())
262 return LayoutRect(logicalLeft, 0, logicalWidth, height());
263 return LayoutRect(0, logicalLeft, width(), logicalWidth);
266 RenderBlockFlow* RenderBox::outermostBlockContainingFloatingObject()
268 ASSERT(isFloating());
269 RenderBlockFlow* parentBlock = nullptr;
270 for (auto& ancestor : ancestorsOfType<RenderBlockFlow>(*this)) {
271 if (ancestor.isRenderView())
273 if (!parentBlock || ancestor.containsFloat(*this))
274 parentBlock = &ancestor;
279 void RenderBox::removeFloatingOrPositionedChildFromBlockLists()
281 ASSERT(isFloatingOrOutOfFlowPositioned());
283 if (documentBeingDestroyed())
287 if (RenderBlockFlow* parentBlock = outermostBlockContainingFloatingObject()) {
288 parentBlock->markSiblingsWithFloatsForLayout(this);
289 parentBlock->markAllDescendantsWithFloatsForLayout(this, false);
293 if (isOutOfFlowPositioned())
294 RenderBlock::removePositionedObject(*this);
297 void RenderBox::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
299 s_hadOverflowClip = hasOverflowClip();
301 const RenderStyle* oldStyle = hasInitializedStyle() ? &style() : nullptr;
303 // The background of the root element or the body element could propagate up to
304 // the canvas. Issue full repaint, when our style changes substantially.
305 if (diff >= StyleDifferenceRepaint && (isRoot() || isBody())) {
306 view().repaintRootContents();
307 if (oldStyle->hasEntirelyFixedBackground() != newStyle.hasEntirelyFixedBackground())
308 view().compositor().rootFixedBackgroundsChanged();
311 // When a layout hint happens and an object's position style changes, we have to do a layout
312 // to dirty the render tree using the old position value now.
313 if (diff == StyleDifferenceLayout && parent() && oldStyle->position() != newStyle.position()) {
314 markContainingBlocksForLayout();
315 if (oldStyle->position() == StaticPosition)
317 else if (newStyle.hasOutOfFlowPosition())
318 parent()->setChildNeedsLayout();
319 if (isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition())
320 removeFloatingOrPositionedChildFromBlockLists();
323 view().repaintRootContents();
325 RenderBoxModelObject::styleWillChange(diff, newStyle);
328 void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
330 // Horizontal writing mode definition is updated in RenderBoxModelObject::updateFromStyle,
331 // (as part of the RenderBoxModelObject::styleDidChange call below). So, we can safely cache the horizontal
332 // writing mode value before style change here.
333 bool oldHorizontalWritingMode = isHorizontalWritingMode();
335 RenderBoxModelObject::styleDidChange(diff, oldStyle);
337 const RenderStyle& newStyle = style();
338 if (needsLayout() && oldStyle) {
339 RenderBlock::removePercentHeightDescendantIfNeeded(*this);
341 // Normally we can do optimized positioning layout for absolute/fixed positioned objects. There is one special case, however, which is
342 // 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
343 // to determine the new static position.
344 if (isOutOfFlowPositioned() && newStyle.hasStaticBlockPosition(isHorizontalWritingMode()) && oldStyle->marginBefore() != newStyle.marginBefore()
345 && parent() && !parent()->normalChildNeedsLayout())
346 parent()->setChildNeedsLayout();
349 if (RenderBlock::hasPercentHeightContainerMap() && firstChild()
350 && oldHorizontalWritingMode != isHorizontalWritingMode())
351 RenderBlock::clearPercentHeightDescendantsFrom(*this);
353 // If our zoom factor changes and we have a defined scrollLeft/Top, we need to adjust that value into the
354 // new zoomed coordinate space.
355 if (hasOverflowClip() && oldStyle && oldStyle->effectiveZoom() != newStyle.effectiveZoom()) {
356 if (int left = layer()->scrollXOffset()) {
357 left = (left / oldStyle->effectiveZoom()) * newStyle.effectiveZoom();
358 layer()->scrollToXOffset(left);
360 if (int top = layer()->scrollYOffset()) {
361 top = (top / oldStyle->effectiveZoom()) * newStyle.effectiveZoom();
362 layer()->scrollToYOffset(top);
366 // Our opaqueness might have changed without triggering layout.
367 if (diff >= StyleDifferenceRepaint && diff <= StyleDifferenceRepaintLayer) {
368 auto parentToInvalidate = parent();
369 for (unsigned i = 0; i < backgroundObscurationTestMaxDepth && parentToInvalidate; ++i) {
370 parentToInvalidate->invalidateBackgroundObscurationStatus();
371 parentToInvalidate = parentToInvalidate->parent();
375 bool isBodyRenderer = isBody();
376 bool isRootRenderer = isRoot();
378 // Set the text color if we're the body.
380 document().setTextColor(newStyle.visitedDependentColor(CSSPropertyColor));
382 if (isRootRenderer || isBodyRenderer) {
383 // Propagate the new writing mode and direction up to the RenderView.
384 RenderStyle& viewStyle = view().style();
385 bool viewChangedWritingMode = false;
386 bool rootStyleChanged = false;
387 bool viewStyleChanged = false;
388 RenderObject* rootRenderer = isBodyRenderer ? document().documentElement()->renderer() : nullptr;
389 if (viewStyle.direction() != newStyle.direction() && (isRootRenderer || !document().directionSetOnDocumentElement())) {
390 viewStyle.setDirection(newStyle.direction());
391 viewStyleChanged = true;
392 if (isBodyRenderer) {
393 rootRenderer->style().setDirection(newStyle.direction());
394 rootStyleChanged = true;
396 setNeedsLayoutAndPrefWidthsRecalc();
399 if (viewStyle.writingMode() != newStyle.writingMode() && (isRootRenderer || !document().writingModeSetOnDocumentElement())) {
400 viewStyle.setWritingMode(newStyle.writingMode());
401 viewChangedWritingMode = true;
402 viewStyleChanged = true;
403 view().setHorizontalWritingMode(newStyle.isHorizontalWritingMode());
404 view().markAllDescendantsWithFloatsForLayout();
405 if (isBodyRenderer) {
406 rootStyleChanged = true;
407 rootRenderer->style().setWritingMode(newStyle.writingMode());
408 rootRenderer->setHorizontalWritingMode(newStyle.isHorizontalWritingMode());
410 setNeedsLayoutAndPrefWidthsRecalc();
413 view().frameView().recalculateScrollbarOverlayStyle();
415 const Pagination& pagination = view().frameView().pagination();
416 if (viewChangedWritingMode && pagination.mode != Pagination::Unpaginated) {
417 viewStyle.setColumnStylesFromPaginationMode(pagination.mode);
418 if (view().multiColumnFlowThread())
419 view().updateColumnProgressionFromStyle(viewStyle);
422 if (viewStyleChanged && view().multiColumnFlowThread())
423 view().updateStylesForColumnChildren();
425 if (rootStyleChanged && is<RenderBlockFlow>(rootRenderer) && downcast<RenderBlockFlow>(*rootRenderer).multiColumnFlowThread())
426 downcast<RenderBlockFlow>(*rootRenderer).updateStylesForColumnChildren();
429 #if ENABLE(CSS_SHAPES)
430 if ((oldStyle && oldStyle->shapeOutside()) || style().shapeOutside())
431 updateShapeOutsideInfoAfterStyleChange(style(), oldStyle);
435 #if ENABLE(CSS_SHAPES)
436 void RenderBox::updateShapeOutsideInfoAfterStyleChange(const RenderStyle& style, const RenderStyle* oldStyle)
438 const ShapeValue* shapeOutside = style.shapeOutside();
439 const ShapeValue* oldShapeOutside = oldStyle ? oldStyle->shapeOutside() : nullptr;
441 Length shapeMargin = style.shapeMargin();
442 Length oldShapeMargin = oldStyle ? oldStyle->shapeMargin() : RenderStyle::initialShapeMargin();
444 float shapeImageThreshold = style.shapeImageThreshold();
445 float oldShapeImageThreshold = oldStyle ? oldStyle->shapeImageThreshold() : RenderStyle::initialShapeImageThreshold();
447 // FIXME: A future optimization would do a deep comparison for equality. (bug 100811)
448 if (shapeOutside == oldShapeOutside && shapeMargin == oldShapeMargin && shapeImageThreshold == oldShapeImageThreshold)
452 ShapeOutsideInfo::removeInfo(*this);
454 ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
456 if (shapeOutside || shapeOutside != oldShapeOutside)
457 markShapeOutsideDependentsForLayout();
461 void RenderBox::updateFromStyle()
463 RenderBoxModelObject::updateFromStyle();
465 const RenderStyle& styleToUse = style();
466 bool isRootObject = isRoot();
467 bool isViewObject = isRenderView();
469 // The root and the RenderView always paint their backgrounds/borders.
470 if (isRootObject || isViewObject)
471 setHasBoxDecorations(true);
473 setFloating(!isOutOfFlowPositioned() && styleToUse.isFloating());
475 // We also handle <body> and <html>, whose overflow applies to the viewport.
476 if (styleToUse.overflowX() != OVISIBLE && !isRootObject && isRenderBlock()) {
477 bool boxHasOverflowClip = true;
479 // Overflow on the body can propagate to the viewport under the following conditions.
480 // (1) The root element is <html>.
481 // (2) We are the primary <body> (can be checked by looking at document.body).
482 // (3) The root element has visible overflow.
483 if (is<HTMLHtmlElement>(*document().documentElement())
484 && document().body() == element()
485 && document().documentElement()->renderer()->style().overflowX() == OVISIBLE) {
486 boxHasOverflowClip = false;
490 // Check for overflow clip.
491 // It's sufficient to just check one direction, since it's illegal to have visible on only one overflow value.
492 if (boxHasOverflowClip) {
493 if (!s_hadOverflowClip)
494 // Erase the overflow
496 setHasOverflowClip();
500 setHasTransformRelatedProperty(styleToUse.hasTransformRelatedProperty());
501 setHasReflection(styleToUse.boxReflect());
504 void RenderBox::layout()
506 StackStats::LayoutCheckPoint layoutCheckPoint;
507 ASSERT(needsLayout());
509 RenderObject* child = firstChild();
515 LayoutStateMaintainer statePusher(view(), *this, locationOffset(), style().isFlippedBlocksWritingMode());
517 if (child->needsLayout())
518 downcast<RenderElement>(*child).layout();
519 ASSERT(!child->needsLayout());
520 child = child->nextSibling();
523 invalidateBackgroundObscurationStatus();
527 // More IE extensions. clientWidth and clientHeight represent the interior of an object
528 // excluding border and scrollbar.
529 LayoutUnit RenderBox::clientWidth() const
531 return width() - borderLeft() - borderRight() - verticalScrollbarWidth();
534 LayoutUnit RenderBox::clientHeight() const
536 return height() - borderTop() - borderBottom() - horizontalScrollbarHeight();
539 int RenderBox::pixelSnappedClientWidth() const
541 // FIXME: This should use snappedIntSize() instead with absolute coordinates.
542 return roundToInt(clientWidth());
545 int RenderBox::pixelSnappedClientHeight() const
547 // FIXME: This should use snappedIntSize() instead with absolute coordinates.
548 return roundToInt(clientHeight());
551 int RenderBox::pixelSnappedOffsetWidth() const
553 // FIXME: This should use snappedIntSize() instead with absolute coordinates.
554 return roundToInt(offsetWidth());
557 int RenderBox::pixelSnappedOffsetHeight() const
559 // FIXME: This should use snappedIntSize() instead with absolute coordinates.
560 return roundToInt(offsetHeight());
563 int RenderBox::scrollWidth() const
565 if (hasOverflowClip())
566 return layer()->scrollWidth();
567 // For objects with visible overflow, this matches IE.
568 // FIXME: Need to work right with writing modes.
569 if (style().isLeftToRightDirection()) {
570 // FIXME: This should use snappedIntSize() instead with absolute coordinates.
571 return roundToInt(std::max(clientWidth(), layoutOverflowRect().maxX() - borderLeft()));
573 return clientWidth() - std::min<LayoutUnit>(0, layoutOverflowRect().x() - borderLeft());
576 int RenderBox::scrollHeight() const
578 if (hasOverflowClip())
579 return layer()->scrollHeight();
580 // For objects with visible overflow, this matches IE.
581 // FIXME: Need to work right with writing modes.
582 // FIXME: This should use snappedIntSize() instead with absolute coordinates.
583 return roundToInt(std::max(clientHeight(), layoutOverflowRect().maxY() - borderTop()));
586 int RenderBox::scrollLeft() const
588 return hasOverflowClip() ? layer()->scrollXOffset() : 0;
591 int RenderBox::scrollTop() const
593 return hasOverflowClip() ? layer()->scrollYOffset() : 0;
596 void RenderBox::setScrollLeft(int newLeft)
598 if (hasOverflowClip())
599 layer()->scrollToXOffset(newLeft, RenderLayer::ScrollOffsetClamped);
602 void RenderBox::setScrollTop(int newTop)
604 if (hasOverflowClip())
605 layer()->scrollToYOffset(newTop, RenderLayer::ScrollOffsetClamped);
608 void RenderBox::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
610 rects.append(snappedIntRect(accumulatedOffset, size()));
613 void RenderBox::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
615 FloatRect localRect(0, 0, width(), height());
617 RenderFlowThread* flowThread = flowThreadContainingBlock();
618 if (flowThread && flowThread->absoluteQuadsForBox(quads, wasFixed, this, localRect.y(), localRect.maxY()))
621 quads.append(localToAbsoluteQuad(localRect, UseTransforms, wasFixed));
624 void RenderBox::updateLayerTransform()
626 // Transform-origin depends on box size, so we need to update the layer transform after layout.
628 layer()->updateTransform();
631 LayoutUnit RenderBox::constrainLogicalWidthInRegionByMinMax(LayoutUnit logicalWidth, LayoutUnit availableWidth, RenderBlock* cb, RenderRegion* region) const
633 const RenderStyle& styleToUse = style();
634 if (!styleToUse.logicalMaxWidth().isUndefined())
635 logicalWidth = std::min(logicalWidth, computeLogicalWidthInRegionUsing(MaxSize, styleToUse.logicalMaxWidth(), availableWidth, cb, region));
636 return std::max(logicalWidth, computeLogicalWidthInRegionUsing(MinSize, styleToUse.logicalMinWidth(), availableWidth, cb, region));
639 LayoutUnit RenderBox::constrainLogicalHeightByMinMax(LayoutUnit logicalHeight) const
641 const RenderStyle& styleToUse = style();
642 if (!styleToUse.logicalMaxHeight().isUndefined()) {
643 LayoutUnit maxH = computeLogicalHeightUsing(styleToUse.logicalMaxHeight());
645 logicalHeight = std::min(logicalHeight, maxH);
647 return std::max(logicalHeight, computeLogicalHeightUsing(styleToUse.logicalMinHeight()));
650 LayoutUnit RenderBox::constrainContentBoxLogicalHeightByMinMax(LayoutUnit logicalHeight) const
652 const RenderStyle& styleToUse = style();
653 if (!styleToUse.logicalMaxHeight().isUndefined()) {
654 LayoutUnit maxH = computeContentLogicalHeight(styleToUse.logicalMaxHeight());
656 logicalHeight = std::min(logicalHeight, maxH);
658 return std::max(logicalHeight, computeContentLogicalHeight(styleToUse.logicalMinHeight()));
661 RoundedRect::Radii RenderBox::borderRadii() const
663 RenderStyle& style = this->style();
664 LayoutRect bounds = frameRect();
666 unsigned borderLeft = style.borderLeftWidth();
667 unsigned borderTop = style.borderTopWidth();
668 bounds.moveBy(LayoutPoint(borderLeft, borderTop));
669 bounds.contract(borderLeft + style.borderRightWidth(), borderTop + style.borderBottomWidth());
670 return style.getRoundedBorderFor(bounds).radii();
673 IntRect RenderBox::absoluteContentBox() const
675 // This is wrong with transforms and flipped writing modes.
676 IntRect rect = snappedIntRect(contentBoxRect());
677 FloatPoint absPos = localToAbsolute();
678 rect.move(absPos.x(), absPos.y());
682 FloatQuad RenderBox::absoluteContentQuad() const
684 LayoutRect rect = contentBoxRect();
685 return localToAbsoluteQuad(FloatRect(rect));
688 LayoutRect RenderBox::outlineBoundsForRepaint(const RenderLayerModelObject* repaintContainer, const RenderGeometryMap* geometryMap) const
690 LayoutRect box = borderBoundingBox();
691 adjustRectForOutlineAndShadow(box);
693 if (repaintContainer != this) {
694 FloatQuad containerRelativeQuad;
696 containerRelativeQuad = geometryMap->mapToContainer(box, repaintContainer);
698 containerRelativeQuad = localToContainerQuad(FloatRect(box), repaintContainer);
700 box = LayoutRect(containerRelativeQuad.boundingBox());
703 // FIXME: layoutDelta needs to be applied in parts before/after transforms and
704 // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
705 box.move(view().layoutDelta());
707 return LayoutRect(snapRectToDevicePixels(box, document().deviceScaleFactor()));
710 void RenderBox::addFocusRingRects(Vector<IntRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject*)
712 if (!size().isEmpty())
713 rects.append(snappedIntRect(additionalOffset, size()));
716 int RenderBox::reflectionOffset() const
718 if (!style().boxReflect())
720 if (style().boxReflect()->direction() == ReflectionLeft || style().boxReflect()->direction() == ReflectionRight)
721 return valueForLength(style().boxReflect()->offset(), borderBoxRect().width());
722 return valueForLength(style().boxReflect()->offset(), borderBoxRect().height());
725 LayoutRect RenderBox::reflectedRect(const LayoutRect& r) const
727 if (!style().boxReflect())
730 LayoutRect box = borderBoxRect();
731 LayoutRect result = r;
732 switch (style().boxReflect()->direction()) {
733 case ReflectionBelow:
734 result.setY(box.maxY() + reflectionOffset() + (box.maxY() - r.maxY()));
736 case ReflectionAbove:
737 result.setY(box.y() - reflectionOffset() - box.height() + (box.maxY() - r.maxY()));
740 result.setX(box.x() - reflectionOffset() - box.width() + (box.maxX() - r.maxX()));
742 case ReflectionRight:
743 result.setX(box.maxX() + reflectionOffset() + (box.maxX() - r.maxX()));
749 bool RenderBox::fixedElementLaysOutRelativeToFrame(const FrameView& frameView) const
751 return style().position() == FixedPosition && container()->isRenderView() && frameView.fixedElementsLayoutRelativeToFrame();
754 bool RenderBox::includeVerticalScrollbarSize() const
756 return hasOverflowClip() && !layer()->hasOverlayScrollbars()
757 && (style().overflowY() == OSCROLL || style().overflowY() == OAUTO);
760 bool RenderBox::includeHorizontalScrollbarSize() const
762 return hasOverflowClip() && !layer()->hasOverlayScrollbars()
763 && (style().overflowX() == OSCROLL || style().overflowX() == OAUTO);
766 int RenderBox::verticalScrollbarWidth() const
768 return includeVerticalScrollbarSize() ? layer()->verticalScrollbarWidth() : 0;
771 int RenderBox::horizontalScrollbarHeight() const
773 return includeHorizontalScrollbarSize() ? layer()->horizontalScrollbarHeight() : 0;
776 int RenderBox::instrinsicScrollbarLogicalWidth() const
778 if (!hasOverflowClip())
781 if (isHorizontalWritingMode() && (style().overflowY() == OSCROLL && !hasVerticalScrollbarWithAutoBehavior())) {
782 ASSERT(layer()->hasVerticalScrollbar());
783 return verticalScrollbarWidth();
786 if (!isHorizontalWritingMode() && (style().overflowX() == OSCROLL && !hasHorizontalScrollbarWithAutoBehavior())) {
787 ASSERT(layer()->hasHorizontalScrollbar());
788 return horizontalScrollbarHeight();
794 bool RenderBox::scrollLayer(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement)
796 RenderLayer* boxLayer = layer();
797 if (boxLayer && boxLayer->scroll(direction, granularity, multiplier)) {
799 *stopElement = element();
807 bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement, RenderBox* startBox, const IntPoint& wheelEventAbsolutePoint)
809 if (scrollLayer(direction, granularity, multiplier, stopElement))
812 if (stopElement && *stopElement && *stopElement == element())
815 RenderBlock* nextScrollBlock = containingBlock();
816 if (is<RenderNamedFlowThread>(nextScrollBlock)) {
818 nextScrollBlock = downcast<RenderNamedFlowThread>(*nextScrollBlock).fragmentFromAbsolutePointAndBox(wheelEventAbsolutePoint, *startBox);
821 if (nextScrollBlock && !nextScrollBlock->isRenderView())
822 return nextScrollBlock->scroll(direction, granularity, multiplier, stopElement, startBox, wheelEventAbsolutePoint);
827 bool RenderBox::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement)
829 bool scrolled = false;
831 RenderLayer* l = layer();
834 // On Mac only we reset the inline direction position when doing a document scroll (e.g., hitting Home/End).
835 if (granularity == ScrollByDocument)
836 scrolled = l->scroll(logicalToPhysical(ScrollInlineDirectionBackward, isHorizontalWritingMode(), style().isFlippedBlocksWritingMode()), ScrollByDocument, multiplier);
838 if (l->scroll(logicalToPhysical(direction, isHorizontalWritingMode(), style().isFlippedBlocksWritingMode()), granularity, multiplier))
843 *stopElement = element();
848 if (stopElement && *stopElement && *stopElement == element())
851 RenderBlock* b = containingBlock();
852 if (b && !b->isRenderView())
853 return b->logicalScroll(direction, granularity, multiplier, stopElement);
857 bool RenderBox::canBeScrolledAndHasScrollableArea() const
859 return canBeProgramaticallyScrolled() && (scrollHeight() != clientHeight() || scrollWidth() != clientWidth());
862 bool RenderBox::isScrollableOrRubberbandableBox() const
864 return canBeScrolledAndHasScrollableArea();
867 bool RenderBox::canBeProgramaticallyScrolled() const
872 if (!hasOverflowClip())
875 bool hasScrollableOverflow = hasScrollableOverflowX() || hasScrollableOverflowY();
876 if (scrollsOverflow() && hasScrollableOverflow)
879 return element() && element()->hasEditableStyle();
882 bool RenderBox::usesCompositedScrolling() const
884 return hasOverflowClip() && hasLayer() && layer()->usesCompositedScrolling();
887 void RenderBox::autoscroll(const IntPoint& position)
890 layer()->autoscroll(position);
893 // There are two kinds of renderer that can autoscroll.
894 bool RenderBox::canAutoscroll() const
897 return view().frameView().isScrollable();
899 // Check for a box that can be scrolled in its own right.
900 if (canBeScrolledAndHasScrollableArea())
906 // If specified point is in border belt, returned offset denotes direction of
908 IntSize RenderBox::calculateAutoscrollDirection(const IntPoint& windowPoint) const
910 IntRect box(absoluteBoundingBoxRect());
911 box.move(view().frameView().scrollOffset());
912 IntRect windowBox = view().frameView().contentsToWindow(box);
914 IntPoint windowAutoscrollPoint = windowPoint;
916 if (windowAutoscrollPoint.x() < windowBox.x() + autoscrollBeltSize)
917 windowAutoscrollPoint.move(-autoscrollBeltSize, 0);
918 else if (windowAutoscrollPoint.x() > windowBox.maxX() - autoscrollBeltSize)
919 windowAutoscrollPoint.move(autoscrollBeltSize, 0);
921 if (windowAutoscrollPoint.y() < windowBox.y() + autoscrollBeltSize)
922 windowAutoscrollPoint.move(0, -autoscrollBeltSize);
923 else if (windowAutoscrollPoint.y() > windowBox.maxY() - autoscrollBeltSize)
924 windowAutoscrollPoint.move(0, autoscrollBeltSize);
926 return windowAutoscrollPoint - windowPoint;
929 RenderBox* RenderBox::findAutoscrollable(RenderObject* renderer)
931 while (renderer && !(is<RenderBox>(*renderer) && downcast<RenderBox>(*renderer).canAutoscroll())) {
932 if (is<RenderView>(*renderer) && renderer->document().ownerElement())
933 renderer = renderer->document().ownerElement()->renderer();
935 renderer = renderer->parent();
938 return is<RenderBox>(renderer) ? downcast<RenderBox>(renderer) : nullptr;
941 void RenderBox::panScroll(const IntPoint& source)
944 layer()->panScrollFromPoint(source);
947 bool RenderBox::hasVerticalScrollbarWithAutoBehavior() const
949 bool overflowScrollActsLikeAuto = style().overflowY() == OSCROLL && !style().hasPseudoStyle(SCROLLBAR) && ScrollbarTheme::theme()->usesOverlayScrollbars();
950 return hasOverflowClip() && (style().overflowY() == OAUTO || style().overflowY() == OOVERLAY || overflowScrollActsLikeAuto);
953 bool RenderBox::hasHorizontalScrollbarWithAutoBehavior() const
955 bool overflowScrollActsLikeAuto = style().overflowX() == OSCROLL && !style().hasPseudoStyle(SCROLLBAR) && ScrollbarTheme::theme()->usesOverlayScrollbars();
956 return hasOverflowClip() && (style().overflowX() == OAUTO || style().overflowX() == OOVERLAY || overflowScrollActsLikeAuto);
959 bool RenderBox::needsPreferredWidthsRecalculation() const
961 return style().paddingStart().isPercent() || style().paddingEnd().isPercent();
964 IntSize RenderBox::scrolledContentOffset() const
966 if (!hasOverflowClip())
970 return layer()->scrolledContentOffset();
973 LayoutSize RenderBox::cachedSizeForOverflowClip() const
975 ASSERT(hasOverflowClip());
977 return layer()->size();
980 void RenderBox::applyCachedClipAndScrollOffsetForRepaint(LayoutRect& paintRect) const
982 flipForWritingMode(paintRect);
983 paintRect.move(-scrolledContentOffset()); // For overflow:auto/scroll/hidden.
985 // Do not clip scroll layer contents to reduce the number of repaints while scrolling.
986 if (usesCompositedScrolling()) {
987 flipForWritingMode(paintRect);
991 // height() is inaccurate if we're in the middle of a layout of this RenderBox, so use the
992 // layer's size instead. Even if the layer's size is wrong, the layer itself will repaint
993 // anyway if its size does change.
994 LayoutRect clipRect(LayoutPoint(), cachedSizeForOverflowClip());
995 paintRect = intersection(paintRect, clipRect);
996 flipForWritingMode(paintRect);
999 void RenderBox::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
1001 minLogicalWidth = minPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
1002 maxLogicalWidth = maxPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
1005 LayoutUnit RenderBox::minPreferredLogicalWidth() const
1007 if (preferredLogicalWidthsDirty()) {
1009 SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox*>(this));
1011 const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
1014 return m_minPreferredLogicalWidth;
1017 LayoutUnit RenderBox::maxPreferredLogicalWidth() const
1019 if (preferredLogicalWidthsDirty()) {
1021 SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox*>(this));
1023 const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
1026 return m_maxPreferredLogicalWidth;
1029 bool RenderBox::hasOverrideLogicalContentHeight() const
1031 return gOverrideHeightMap && gOverrideHeightMap->contains(this);
1034 bool RenderBox::hasOverrideLogicalContentWidth() const
1036 return gOverrideWidthMap && gOverrideWidthMap->contains(this);
1039 void RenderBox::setOverrideLogicalContentHeight(LayoutUnit height)
1041 if (!gOverrideHeightMap)
1042 gOverrideHeightMap = new OverrideSizeMap();
1043 gOverrideHeightMap->set(this, height);
1046 void RenderBox::setOverrideLogicalContentWidth(LayoutUnit width)
1048 if (!gOverrideWidthMap)
1049 gOverrideWidthMap = new OverrideSizeMap();
1050 gOverrideWidthMap->set(this, width);
1053 void RenderBox::clearOverrideLogicalContentHeight()
1055 if (gOverrideHeightMap)
1056 gOverrideHeightMap->remove(this);
1059 void RenderBox::clearOverrideLogicalContentWidth()
1061 if (gOverrideWidthMap)
1062 gOverrideWidthMap->remove(this);
1065 void RenderBox::clearOverrideSize()
1067 clearOverrideLogicalContentHeight();
1068 clearOverrideLogicalContentWidth();
1071 LayoutUnit RenderBox::overrideLogicalContentWidth() const
1073 ASSERT(hasOverrideLogicalContentWidth());
1074 return gOverrideWidthMap->get(this);
1077 LayoutUnit RenderBox::overrideLogicalContentHeight() const
1079 ASSERT(hasOverrideLogicalContentHeight());
1080 return gOverrideHeightMap->get(this);
1083 #if ENABLE(CSS_GRID_LAYOUT)
1084 LayoutUnit RenderBox::overrideContainingBlockContentLogicalWidth() const
1086 ASSERT(hasOverrideContainingBlockLogicalWidth());
1087 return gOverrideContainingBlockLogicalWidthMap->get(this);
1090 LayoutUnit RenderBox::overrideContainingBlockContentLogicalHeight() const
1092 ASSERT(hasOverrideContainingBlockLogicalHeight());
1093 return gOverrideContainingBlockLogicalHeightMap->get(this);
1096 bool RenderBox::hasOverrideContainingBlockLogicalWidth() const
1098 return gOverrideContainingBlockLogicalWidthMap && gOverrideContainingBlockLogicalWidthMap->contains(this);
1101 bool RenderBox::hasOverrideContainingBlockLogicalHeight() const
1103 return gOverrideContainingBlockLogicalHeightMap && gOverrideContainingBlockLogicalHeightMap->contains(this);
1106 void RenderBox::setOverrideContainingBlockContentLogicalWidth(LayoutUnit logicalWidth)
1108 if (!gOverrideContainingBlockLogicalWidthMap)
1109 gOverrideContainingBlockLogicalWidthMap = new OverrideSizeMap;
1110 gOverrideContainingBlockLogicalWidthMap->set(this, logicalWidth);
1113 void RenderBox::setOverrideContainingBlockContentLogicalHeight(LayoutUnit logicalHeight)
1115 if (!gOverrideContainingBlockLogicalHeightMap)
1116 gOverrideContainingBlockLogicalHeightMap = new OverrideSizeMap;
1117 gOverrideContainingBlockLogicalHeightMap->set(this, logicalHeight);
1120 void RenderBox::clearContainingBlockOverrideSize()
1122 if (gOverrideContainingBlockLogicalWidthMap)
1123 gOverrideContainingBlockLogicalWidthMap->remove(this);
1124 clearOverrideContainingBlockContentLogicalHeight();
1127 void RenderBox::clearOverrideContainingBlockContentLogicalHeight()
1129 if (gOverrideContainingBlockLogicalHeightMap)
1130 gOverrideContainingBlockLogicalHeightMap->remove(this);
1132 #endif // ENABLE(CSS_GRID_LAYOUT)
1134 LayoutUnit RenderBox::adjustBorderBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1136 LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
1137 if (style().boxSizing() == CONTENT_BOX)
1138 return width + bordersPlusPadding;
1139 return std::max(width, bordersPlusPadding);
1142 LayoutUnit RenderBox::adjustBorderBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1144 LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
1145 if (style().boxSizing() == CONTENT_BOX)
1146 return height + bordersPlusPadding;
1147 return std::max(height, bordersPlusPadding);
1150 LayoutUnit RenderBox::adjustContentBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1152 if (style().boxSizing() == BORDER_BOX)
1153 width -= borderAndPaddingLogicalWidth();
1154 return std::max<LayoutUnit>(0, width);
1157 LayoutUnit RenderBox::adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1159 if (style().boxSizing() == BORDER_BOX)
1160 height -= borderAndPaddingLogicalHeight();
1161 return std::max<LayoutUnit>(0, height);
1165 bool RenderBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
1167 LayoutPoint adjustedLocation = accumulatedOffset + location();
1169 // Check kids first.
1170 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
1171 if (!child->hasLayer() && child->nodeAtPoint(request, result, locationInContainer, adjustedLocation, action)) {
1172 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1177 RenderFlowThread* flowThread = flowThreadContainingBlock();
1178 RenderRegion* regionToUse = flowThread ? downcast<RenderNamedFlowFragment>(flowThread->currentRegion()) : nullptr;
1180 // If the box is not contained by this region there's no point in going further.
1181 if (regionToUse && !flowThread->objectShouldFragmentInFlowRegion(this, regionToUse))
1184 // Check our bounds next. For this purpose always assume that we can only be hit in the
1185 // foreground phase (which is true for replaced elements like images).
1186 LayoutRect boundsRect = borderBoxRectInRegion(regionToUse);
1187 boundsRect.moveBy(adjustedLocation);
1188 if (visibleToHitTesting() && action == HitTestForeground && locationInContainer.intersects(boundsRect)) {
1189 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1190 if (!result.addNodeToRectBasedTestResult(element(), request, locationInContainer, boundsRect))
1197 // --------------------- painting stuff -------------------------------
1199 void RenderBox::paintRootBoxFillLayers(const PaintInfo& paintInfo)
1201 if (paintInfo.skipRootBackground())
1204 auto& rootBackgroundRenderer = rendererForRootBackground();
1206 const FillLayer* bgLayer = rootBackgroundRenderer.style().backgroundLayers();
1207 Color bgColor = rootBackgroundRenderer.style().visitedDependentColor(CSSPropertyBackgroundColor);
1209 paintFillLayers(paintInfo, bgColor, bgLayer, view().backgroundRect(this), BackgroundBleedNone, CompositeSourceOver, &rootBackgroundRenderer);
1212 BackgroundBleedAvoidance RenderBox::determineBackgroundBleedAvoidance(GraphicsContext* context) const
1214 if (context->paintingDisabled())
1215 return BackgroundBleedNone;
1217 const RenderStyle& style = this->style();
1219 if (!style.hasBackground() || !style.hasBorder() || !style.hasBorderRadius() || borderImageIsLoadedAndCanBeRendered())
1220 return BackgroundBleedNone;
1222 AffineTransform ctm = context->getCTM();
1223 FloatSize contextScaling(static_cast<float>(ctm.xScale()), static_cast<float>(ctm.yScale()));
1225 // Because RoundedRect uses IntRect internally the inset applied by the
1226 // BackgroundBleedShrinkBackground strategy cannot be less than one integer
1227 // layout coordinate, even with subpixel layout enabled. To take that into
1228 // account, we clamp the contextScaling to 1.0 for the following test so
1229 // that borderObscuresBackgroundEdge can only return true if the border
1230 // widths are greater than 2 in both layout coordinates and screen
1232 // This precaution will become obsolete if RoundedRect is ever promoted to
1233 // a sub-pixel representation.
1234 if (contextScaling.width() > 1)
1235 contextScaling.setWidth(1);
1236 if (contextScaling.height() > 1)
1237 contextScaling.setHeight(1);
1239 if (borderObscuresBackgroundEdge(contextScaling))
1240 return BackgroundBleedShrinkBackground;
1241 if (!style.hasAppearance() && borderObscuresBackground() && backgroundHasOpaqueTopLayer())
1242 return BackgroundBleedBackgroundOverBorder;
1244 return BackgroundBleedUseTransparencyLayer;
1247 void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1249 if (!paintInfo.shouldPaintWithinRoot(*this))
1252 LayoutRect paintRect = borderBoxRectInRegion(currentRenderNamedFlowFragment());
1253 paintRect.moveBy(paintOffset);
1256 // Workaround for <rdar://problem/6209763>. Force the painting bounds of checkboxes and radio controls to be square.
1257 if (style().appearance() == CheckboxPart || style().appearance() == RadioPart) {
1258 int width = std::min(paintRect.width(), paintRect.height());
1260 paintRect = IntRect(paintRect.x(), paintRect.y() + (this->height() - height) / 2, width, height); // Vertically center the checkbox, like on desktop
1263 BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context);
1265 // FIXME: Should eventually give the theme control over whether the box shadow should paint, since controls could have
1266 // custom shadows of their own.
1267 if (!boxShadowShouldBeAppliedToBackground(bleedAvoidance))
1268 paintBoxShadow(paintInfo, paintRect, style(), Normal);
1270 GraphicsContextStateSaver stateSaver(*paintInfo.context, false);
1271 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
1272 // To avoid the background color bleeding out behind the border, we'll render background and border
1273 // into a transparency layer, and then clip that in one go (which requires setting up the clip before
1274 // beginning the layer).
1276 paintInfo.context->clipRoundedRect(style().getRoundedBorderFor(paintRect).pixelSnappedRoundedRectForPainting(document().deviceScaleFactor()));
1277 paintInfo.context->beginTransparencyLayer(1);
1280 // If we have a native theme appearance, paint that before painting our background.
1281 // The theme will tell us whether or not we should also paint the CSS background.
1282 ControlStates* controlStates = nullptr;
1283 if (style().hasAppearance()) {
1284 if (hasControlStatesForRenderer(this))
1285 controlStates = controlStatesForRenderer(this);
1287 controlStates = new ControlStates();
1288 addControlStatesForRenderer(this, controlStates);
1292 bool themePainted = style().hasAppearance() && !theme().paint(*this, controlStates, paintInfo, paintRect);
1294 if (controlStates && controlStates->needsRepaint())
1295 view().scheduleLazyRepaint(*this);
1297 if (!themePainted) {
1298 if (bleedAvoidance == BackgroundBleedBackgroundOverBorder)
1299 paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1301 paintBackground(paintInfo, paintRect, bleedAvoidance);
1303 if (style().hasAppearance())
1304 theme().paintDecorations(*this, paintInfo, paintRect);
1306 paintBoxShadow(paintInfo, paintRect, style(), Inset);
1308 // The theme will tell us whether or not we should also paint the CSS border.
1309 if (bleedAvoidance != BackgroundBleedBackgroundOverBorder && (!style().hasAppearance() || (!themePainted && theme().paintBorderOnly(*this, paintInfo, paintRect))) && style().hasBorderDecoration())
1310 paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1312 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer)
1313 paintInfo.context->endTransparencyLayer();
1316 void RenderBox::paintBackground(const PaintInfo& paintInfo, const LayoutRect& paintRect, BackgroundBleedAvoidance bleedAvoidance)
1319 paintRootBoxFillLayers(paintInfo);
1322 if (isBody() && skipBodyBackground(this))
1324 if (backgroundIsKnownToBeObscured() && !boxShadowShouldBeAppliedToBackground(bleedAvoidance))
1326 paintFillLayers(paintInfo, style().visitedDependentColor(CSSPropertyBackgroundColor), style().backgroundLayers(), paintRect, bleedAvoidance);
1329 bool RenderBox::getBackgroundPaintedExtent(LayoutRect& paintedExtent) const
1331 ASSERT(hasBackground());
1332 LayoutRect backgroundRect = snappedIntRect(borderBoxRect());
1334 Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1335 if (backgroundColor.isValid() && backgroundColor.alpha()) {
1336 paintedExtent = backgroundRect;
1340 if (!style().backgroundLayers()->image() || style().backgroundLayers()->next()) {
1341 paintedExtent = backgroundRect;
1345 BackgroundImageGeometry geometry = calculateBackgroundImageGeometry(nullptr, *style().backgroundLayers(), backgroundRect);
1346 paintedExtent = geometry.destRect();
1347 return !geometry.hasNonLocalGeometry();
1350 bool RenderBox::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
1352 if (isBody() && skipBodyBackground(this))
1355 Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1356 if (!backgroundColor.isValid() || backgroundColor.hasAlpha())
1359 // If the element has appearance, it might be painted by theme.
1360 // We cannot be sure if theme paints the background opaque.
1361 // In this case it is safe to not assume opaqueness.
1362 // FIXME: May be ask theme if it paints opaque.
1363 if (style().hasAppearance())
1365 // FIXME: Check the opaqueness of background images.
1367 if (hasClip() || hasClipPath())
1370 // FIXME: Use rounded rect if border radius is present.
1371 if (style().hasBorderRadius())
1374 // FIXME: The background color clip is defined by the last layer.
1375 if (style().backgroundLayers()->next())
1377 LayoutRect backgroundRect;
1378 switch (style().backgroundClip()) {
1380 backgroundRect = borderBoxRect();
1382 case PaddingFillBox:
1383 backgroundRect = paddingBoxRect();
1385 case ContentFillBox:
1386 backgroundRect = contentBoxRect();
1391 return backgroundRect.contains(localRect);
1394 static bool isCandidateForOpaquenessTest(const RenderBox& childBox)
1396 const RenderStyle& childStyle = childBox.style();
1397 if (childStyle.position() != StaticPosition && childBox.containingBlock() != childBox.parent())
1399 if (childStyle.visibility() != VISIBLE)
1401 #if ENABLE(CSS_SHAPES)
1402 if (childStyle.shapeOutside())
1405 if (!childBox.width() || !childBox.height())
1407 if (RenderLayer* childLayer = childBox.layer()) {
1408 if (childLayer->isComposited())
1410 // FIXME: Deal with z-index.
1411 if (!childStyle.hasAutoZIndex())
1413 if (childLayer->hasTransform() || childLayer->isTransparent() || childLayer->hasFilter())
1415 if (!childBox.scrolledContentOffset().isZero())
1421 bool RenderBox::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const
1423 if (!maxDepthToTest)
1425 for (auto& childBox : childrenOfType<RenderBox>(*this)) {
1426 if (!isCandidateForOpaquenessTest(childBox))
1428 LayoutPoint childLocation = childBox.location();
1429 if (childBox.isRelPositioned())
1430 childLocation.move(childBox.relativePositionOffset());
1431 LayoutRect childLocalRect = localRect;
1432 childLocalRect.moveBy(-childLocation);
1433 if (childLocalRect.y() < 0 || childLocalRect.x() < 0) {
1434 // If there is unobscured area above/left of a static positioned box then the rect is probably not covered.
1435 if (childBox.style().position() == StaticPosition)
1439 if (childLocalRect.maxY() > childBox.height() || childLocalRect.maxX() > childBox.width())
1441 if (childBox.backgroundIsKnownToBeOpaqueInRect(childLocalRect))
1443 if (childBox.foregroundIsKnownToBeOpaqueInRect(childLocalRect, maxDepthToTest - 1))
1449 bool RenderBox::computeBackgroundIsKnownToBeObscured()
1451 // Test to see if the children trivially obscure the background.
1452 // FIXME: This test can be much more comprehensive.
1453 if (!hasBackground())
1455 // Table and root background painting is special.
1456 if (isTable() || isRoot())
1459 LayoutRect backgroundRect;
1460 if (!getBackgroundPaintedExtent(backgroundRect))
1462 return foregroundIsKnownToBeOpaqueInRect(backgroundRect, backgroundObscurationTestMaxDepth);
1465 bool RenderBox::backgroundHasOpaqueTopLayer() const
1467 const FillLayer* fillLayer = style().backgroundLayers();
1468 if (!fillLayer || fillLayer->clip() != BorderFillBox)
1471 // Clipped with local scrolling
1472 if (hasOverflowClip() && fillLayer->attachment() == LocalBackgroundAttachment)
1475 if (fillLayer->hasOpaqueImage(*this) && fillLayer->hasRepeatXY() && fillLayer->image()->canRender(this, style().effectiveZoom()))
1478 // If there is only one layer and no image, check whether the background color is opaque
1479 if (!fillLayer->next() && !fillLayer->hasImage()) {
1480 Color bgColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1481 if (bgColor.isValid() && bgColor.alpha() == 255)
1488 void RenderBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1490 if (!paintInfo.shouldPaintWithinRoot(*this) || style().visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask || paintInfo.context->paintingDisabled())
1493 LayoutRect paintRect = LayoutRect(paintOffset, size());
1494 paintMaskImages(paintInfo, paintRect);
1497 void RenderBox::paintClippingMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1499 if (!paintInfo.shouldPaintWithinRoot(*this) || style().visibility() != VISIBLE || paintInfo.phase != PaintPhaseClippingMask || paintInfo.context->paintingDisabled())
1502 LayoutRect paintRect = LayoutRect(paintOffset, size());
1503 paintInfo.context->fillRect(snappedIntRect(paintRect), Color::black, style().colorSpace());
1506 void RenderBox::paintMaskImages(const PaintInfo& paintInfo, const LayoutRect& paintRect)
1508 // Figure out if we need to push a transparency layer to render our mask.
1509 bool pushTransparencyLayer = false;
1510 bool compositedMask = hasLayer() && layer()->hasCompositedMask();
1511 bool flattenCompositingLayers = view().frameView().paintBehavior() & PaintBehaviorFlattenCompositingLayers;
1512 CompositeOperator compositeOp = CompositeSourceOver;
1514 bool allMaskImagesLoaded = true;
1516 if (!compositedMask || flattenCompositingLayers) {
1517 pushTransparencyLayer = true;
1518 StyleImage* maskBoxImage = style().maskBoxImage().image();
1519 const FillLayer* maskLayers = style().maskLayers();
1521 // Don't render a masked element until all the mask images have loaded, to prevent a flash of unmasked content.
1523 allMaskImagesLoaded &= maskBoxImage->isLoaded();
1526 allMaskImagesLoaded &= maskLayers->imagesAreLoaded();
1528 paintInfo.context->setCompositeOperation(CompositeDestinationIn);
1529 paintInfo.context->beginTransparencyLayer(1);
1530 compositeOp = CompositeSourceOver;
1533 if (allMaskImagesLoaded) {
1534 paintFillLayers(paintInfo, Color(), style().maskLayers(), paintRect, BackgroundBleedNone, compositeOp);
1535 paintNinePieceImage(paintInfo.context, paintRect, style(), style().maskBoxImage(), compositeOp);
1538 if (pushTransparencyLayer)
1539 paintInfo.context->endTransparencyLayer();
1542 LayoutRect RenderBox::maskClipRect()
1544 const NinePieceImage& maskBoxImage = style().maskBoxImage();
1545 if (maskBoxImage.image()) {
1546 LayoutRect borderImageRect = borderBoxRect();
1548 // Apply outsets to the border box.
1549 borderImageRect.expand(style().maskBoxImageOutsets());
1550 return borderImageRect;
1554 LayoutRect borderBox = borderBoxRect();
1555 for (const FillLayer* maskLayer = style().maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
1556 if (maskLayer->maskImage()) {
1557 // Masks should never have fixed attachment, so it's OK for paintContainer to be null.
1558 BackgroundImageGeometry geometry = calculateBackgroundImageGeometry(nullptr, *maskLayer, borderBox);
1559 result.unite(geometry.destRect());
1565 void RenderBox::paintFillLayers(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1566 BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject)
1568 Vector<const FillLayer*, 8> layers;
1569 const FillLayer* curLayer = fillLayer;
1570 bool shouldDrawBackgroundInSeparateBuffer = false;
1572 layers.append(curLayer);
1573 // Stop traversal when an opaque layer is encountered.
1574 // FIXME : It would be possible for the following occlusion culling test to be more aggressive
1575 // on layers with no repeat by testing whether the image covers the layout rect.
1576 // Testing that here would imply duplicating a lot of calculations that are currently done in
1577 // RenderBoxModelObject::paintFillLayerExtended. A more efficient solution might be to move
1578 // the layer recursion into paintFillLayerExtended, or to compute the layer geometry here
1579 // and pass it down.
1581 if (!shouldDrawBackgroundInSeparateBuffer && curLayer->blendMode() != BlendModeNormal)
1582 shouldDrawBackgroundInSeparateBuffer = true;
1584 // The clipOccludesNextLayers condition must be evaluated first to avoid short-circuiting.
1585 if (curLayer->clipOccludesNextLayers(curLayer == fillLayer) && curLayer->hasOpaqueImage(*this) && curLayer->image()->canRender(this, style().effectiveZoom()) && curLayer->hasRepeatXY() && curLayer->blendMode() == BlendModeNormal)
1587 curLayer = curLayer->next();
1590 GraphicsContext* context = paintInfo.context;
1592 shouldDrawBackgroundInSeparateBuffer = false;
1594 BaseBackgroundColorUsage baseBgColorUsage = BaseBackgroundColorUse;
1596 if (shouldDrawBackgroundInSeparateBuffer) {
1597 paintFillLayer(paintInfo, c, *layers.rbegin(), rect, bleedAvoidance, op, backgroundObject, BaseBackgroundColorOnly);
1598 baseBgColorUsage = BaseBackgroundColorSkip;
1599 context->beginTransparencyLayer(1);
1602 Vector<const FillLayer*>::const_reverse_iterator topLayer = layers.rend();
1603 for (Vector<const FillLayer*>::const_reverse_iterator it = layers.rbegin(); it != topLayer; ++it)
1604 paintFillLayer(paintInfo, c, *it, rect, bleedAvoidance, op, backgroundObject, baseBgColorUsage);
1606 if (shouldDrawBackgroundInSeparateBuffer)
1607 context->endTransparencyLayer();
1610 void RenderBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1611 BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject, BaseBackgroundColorUsage baseBgColorUsage)
1613 paintFillLayerExtended(paintInfo, c, fillLayer, rect, bleedAvoidance, nullptr, LayoutSize(), op, backgroundObject, baseBgColorUsage);
1616 static bool layersUseImage(WrappedImagePtr image, const FillLayer* layers)
1618 for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1619 if (curLayer->image() && image == curLayer->image()->data())
1626 void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
1631 if ((style().borderImage().image() && style().borderImage().image()->data() == image) ||
1632 (style().maskBoxImage().image() && style().maskBoxImage().image()->data() == image)) {
1637 #if ENABLE(CSS_SHAPES)
1638 ShapeValue* shapeOutsideValue = style().shapeOutside();
1639 if (!view().frameView().isInLayout() && isFloating() && shapeOutsideValue && shapeOutsideValue->image() && shapeOutsideValue->image()->data() == image) {
1640 ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
1641 markShapeOutsideDependentsForLayout();
1645 bool didFullRepaint = repaintLayerRectsForImage(image, style().backgroundLayers(), true);
1646 if (!didFullRepaint)
1647 repaintLayerRectsForImage(image, style().maskLayers(), false);
1649 if (!isComposited())
1652 if (layer()->hasCompositedMask() && layersUseImage(image, style().maskLayers()))
1653 layer()->contentChanged(MaskImageChanged);
1654 if (layersUseImage(image, style().backgroundLayers()))
1655 layer()->contentChanged(BackgroundImageChanged);
1658 bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer* layers, bool drawingBackground)
1660 LayoutRect rendererRect;
1661 RenderBox* layerRenderer = nullptr;
1663 for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1664 if (curLayer->image() && image == curLayer->image()->data() && curLayer->image()->canRender(this, style().effectiveZoom())) {
1665 // Now that we know this image is being used, compute the renderer and the rect if we haven't already.
1666 bool drawingRootBackground = drawingBackground && (isRoot() || (isBody() && !document().documentElement()->renderer()->hasBackground()));
1667 if (!layerRenderer) {
1668 if (drawingRootBackground) {
1669 layerRenderer = &view();
1671 LayoutUnit rw = downcast<RenderView>(*layerRenderer).frameView().contentsWidth();
1672 LayoutUnit rh = downcast<RenderView>(*layerRenderer).frameView().contentsHeight();
1674 rendererRect = LayoutRect(-layerRenderer->marginLeft(),
1675 -layerRenderer->marginTop(),
1676 std::max(layerRenderer->width() + layerRenderer->horizontalMarginExtent() + layerRenderer->borderLeft() + layerRenderer->borderRight(), rw),
1677 std::max(layerRenderer->height() + layerRenderer->verticalMarginExtent() + layerRenderer->borderTop() + layerRenderer->borderBottom(), rh));
1679 layerRenderer = this;
1680 rendererRect = borderBoxRect();
1684 BackgroundImageGeometry geometry = layerRenderer->calculateBackgroundImageGeometry(nullptr, *curLayer, rendererRect);
1685 if (geometry.hasNonLocalGeometry()) {
1686 // Rather than incur the costs of computing the paintContainer for renderers with fixed backgrounds
1687 // in order to get the right destRect, just repaint the entire renderer.
1688 layerRenderer->repaint();
1692 LayoutRect rectToRepaint = geometry.destRect();
1693 bool shouldClipToLayer = true;
1695 // If this is the root background layer, we may need to extend the repaintRect if the FrameView has an
1696 // extendedBackground. We should only extend the rect if it is already extending the full width or height
1697 // of the rendererRect.
1698 if (drawingRootBackground && view().frameView().hasExtendedBackgroundRectForPainting()) {
1699 shouldClipToLayer = false;
1700 IntRect extendedBackgroundRect = view().frameView().extendedBackgroundRectForPainting();
1701 if (rectToRepaint.width() == rendererRect.width()) {
1702 rectToRepaint.move(extendedBackgroundRect.x(), 0);
1703 rectToRepaint.setWidth(extendedBackgroundRect.width());
1705 if (rectToRepaint.height() == rendererRect.height()) {
1706 rectToRepaint.move(0, extendedBackgroundRect.y());
1707 rectToRepaint.setHeight(extendedBackgroundRect.height());
1711 layerRenderer->repaintRectangle(rectToRepaint, shouldClipToLayer);
1712 if (geometry.destRect() == rendererRect)
1719 bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset)
1721 if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask)
1724 bool isControlClip = hasControlClip();
1725 bool isOverflowClip = hasOverflowClip() && !layer()->isSelfPaintingLayer();
1727 if (!isControlClip && !isOverflowClip)
1730 if (paintInfo.phase == PaintPhaseOutline)
1731 paintInfo.phase = PaintPhaseChildOutlines;
1732 else if (paintInfo.phase == PaintPhaseChildBlockBackground) {
1733 paintInfo.phase = PaintPhaseBlockBackground;
1734 paintObject(paintInfo, accumulatedOffset);
1735 paintInfo.phase = PaintPhaseChildBlockBackgrounds;
1737 float deviceScaleFactor = document().deviceScaleFactor();
1738 FloatRect clipRect = snapRectToDevicePixels((isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset, currentRenderNamedFlowFragment(), IgnoreOverlayScrollbarSize, paintInfo.phase)), deviceScaleFactor);
1739 paintInfo.context->save();
1740 if (style().hasBorderRadius())
1741 paintInfo.context->clipRoundedRect(style().getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size())).pixelSnappedRoundedRectForPainting(deviceScaleFactor));
1742 paintInfo.context->clip(clipRect);
1746 void RenderBox::popContentsClip(PaintInfo& paintInfo, PaintPhase originalPhase, const LayoutPoint& accumulatedOffset)
1748 ASSERT(hasControlClip() || (hasOverflowClip() && !layer()->isSelfPaintingLayer()));
1750 paintInfo.context->restore();
1751 if (originalPhase == PaintPhaseOutline) {
1752 paintInfo.phase = PaintPhaseSelfOutline;
1753 paintObject(paintInfo, accumulatedOffset);
1754 paintInfo.phase = originalPhase;
1755 } else if (originalPhase == PaintPhaseChildBlockBackground)
1756 paintInfo.phase = originalPhase;
1759 LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, RenderRegion* region, OverlayScrollbarSizeRelevancy relevancy, PaintPhase)
1761 // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
1763 LayoutRect clipRect = borderBoxRectInRegion(region);
1764 clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
1765 clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
1767 // Subtract out scrollbars if we have them.
1769 if (style().shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
1770 clipRect.move(layer()->verticalScrollbarWidth(relevancy), 0);
1771 clipRect.contract(layer()->verticalScrollbarWidth(relevancy), layer()->horizontalScrollbarHeight(relevancy));
1777 LayoutRect RenderBox::clipRect(const LayoutPoint& location, RenderRegion* region)
1779 LayoutRect borderBoxRect = borderBoxRectInRegion(region);
1780 LayoutRect clipRect = LayoutRect(borderBoxRect.location() + location, borderBoxRect.size());
1782 if (!style().clipLeft().isAuto()) {
1783 LayoutUnit c = valueForLength(style().clipLeft(), borderBoxRect.width());
1784 clipRect.move(c, 0);
1785 clipRect.contract(c, 0);
1788 // We don't use the region-specific border box's width and height since clip offsets are (stupidly) specified
1789 // from the left and top edges. Therefore it's better to avoid constraining to smaller widths and heights.
1791 if (!style().clipRight().isAuto())
1792 clipRect.contract(width() - valueForLength(style().clipRight(), width()), 0);
1794 if (!style().clipTop().isAuto()) {
1795 LayoutUnit c = valueForLength(style().clipTop(), borderBoxRect.height());
1796 clipRect.move(0, c);
1797 clipRect.contract(0, c);
1800 if (!style().clipBottom().isAuto())
1801 clipRect.contract(0, height() - valueForLength(style().clipBottom(), height()));
1806 LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock* cb, RenderRegion* region) const
1808 RenderRegion* containingBlockRegion = nullptr;
1809 LayoutUnit logicalTopPosition = logicalTop();
1811 LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1812 logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
1813 containingBlockRegion = cb->clampToStartAndEndRegions(region);
1816 LayoutUnit logicalHeight = cb->logicalHeightForChild(*this);
1817 LayoutUnit result = cb->availableLogicalWidthForLineInRegion(logicalTopPosition, false, containingBlockRegion, logicalHeight) - childMarginStart - childMarginEnd;
1819 // We need to see if margins on either the start side or the end side can contain the floats in question. If they can,
1820 // then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line
1821 // offset at all, but can instead push all the way to the content edge of the containing block. In the case where the float
1822 // 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
1823 // "consumed" by the float. Negative margins aren't consumed by the float, and so we ignore them.
1824 if (childMarginStart > 0) {
1825 LayoutUnit startContentSide = cb->startOffsetForContent(containingBlockRegion);
1826 LayoutUnit startContentSideWithMargin = startContentSide + childMarginStart;
1827 LayoutUnit startOffset = cb->startOffsetForLineInRegion(logicalTopPosition, false, containingBlockRegion, logicalHeight);
1828 if (startOffset > startContentSideWithMargin)
1829 result += childMarginStart;
1831 result += startOffset - startContentSide;
1834 if (childMarginEnd > 0) {
1835 LayoutUnit endContentSide = cb->endOffsetForContent(containingBlockRegion);
1836 LayoutUnit endContentSideWithMargin = endContentSide + childMarginEnd;
1837 LayoutUnit endOffset = cb->endOffsetForLineInRegion(logicalTopPosition, false, containingBlockRegion, logicalHeight);
1838 if (endOffset > endContentSideWithMargin)
1839 result += childMarginEnd;
1841 result += endOffset - endContentSide;
1847 LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const
1849 #if ENABLE(CSS_GRID_LAYOUT)
1850 if (hasOverrideContainingBlockLogicalWidth())
1851 return overrideContainingBlockContentLogicalWidth();
1854 RenderBlock* cb = containingBlock();
1856 return LayoutUnit();
1857 return cb->availableLogicalWidth();
1860 LayoutUnit RenderBox::containingBlockLogicalHeightForContent(AvailableLogicalHeightType heightType) const
1862 #if ENABLE(CSS_GRID_LAYOUT)
1863 if (hasOverrideContainingBlockLogicalHeight())
1864 return overrideContainingBlockContentLogicalHeight();
1867 RenderBlock* cb = containingBlock();
1869 return LayoutUnit();
1870 return cb->availableLogicalHeight(heightType);
1873 LayoutUnit RenderBox::containingBlockLogicalWidthForContentInRegion(RenderRegion* region) const
1876 return containingBlockLogicalWidthForContent();
1878 RenderBlock* cb = containingBlock();
1879 RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
1880 // FIXME: It's unclear if a region's content should use the containing block's override logical width.
1881 // If it should, the following line should call containingBlockLogicalWidthForContent.
1882 LayoutUnit result = cb->availableLogicalWidth();
1883 RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(containingBlockRegion);
1886 return std::max<LayoutUnit>(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
1889 LayoutUnit RenderBox::containingBlockAvailableLineWidthInRegion(RenderRegion* region) const
1891 RenderBlock* cb = containingBlock();
1892 RenderRegion* containingBlockRegion = nullptr;
1893 LayoutUnit logicalTopPosition = logicalTop();
1895 LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1896 logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
1897 containingBlockRegion = cb->clampToStartAndEndRegions(region);
1899 return cb->availableLogicalWidthForLineInRegion(logicalTopPosition, false, containingBlockRegion, availableLogicalHeight(IncludeMarginBorderPadding));
1902 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
1904 #if ENABLE(CSS_GRID_LAYOUT)
1905 if (hasOverrideContainingBlockLogicalHeight())
1906 return overrideContainingBlockContentLogicalHeight();
1909 RenderBlock* cb = containingBlock();
1910 if (cb->hasOverrideLogicalContentHeight())
1911 return cb->overrideLogicalContentHeight();
1913 const RenderStyle& containingBlockStyle = cb->style();
1914 Length logicalHeightLength = containingBlockStyle.logicalHeight();
1916 // FIXME: For now just support fixed heights. Eventually should support percentage heights as well.
1917 if (!logicalHeightLength.isFixed()) {
1918 LayoutUnit fillFallbackExtent = containingBlockStyle.isHorizontalWritingMode() ? view().frameView().visibleHeight() : view().frameView().visibleWidth();
1919 LayoutUnit fillAvailableExtent = containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding);
1920 return std::min(fillAvailableExtent, fillFallbackExtent);
1923 // Use the content box logical height as specified by the style.
1924 return cb->adjustContentBoxLogicalHeightForBoxSizing(logicalHeightLength.value());
1927 void RenderBox::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
1929 if (repaintContainer == this)
1932 if (view().layoutStateEnabled() && !repaintContainer) {
1933 LayoutState* layoutState = view().layoutState();
1934 LayoutSize offset = layoutState->m_paintOffset + locationOffset();
1935 if (style().hasInFlowPosition() && layer())
1936 offset += layer()->offsetForInFlowPosition();
1937 transformState.move(offset);
1941 bool containerSkipped;
1942 RenderElement* container = this->container(repaintContainer, &containerSkipped);
1946 bool isFixedPos = style().position() == FixedPosition;
1947 // If this box has a transform, it acts as a fixed position container for fixed descendants,
1948 // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1949 if (hasTransform() && !isFixedPos)
1951 else if (isFixedPos)
1955 *wasFixed = mode & IsFixed;
1957 LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint(transformState.mappedPoint()));
1959 bool preserve3D = mode & UseTransforms && (container->style().preserves3D() || style().preserves3D());
1960 if (mode & UseTransforms && shouldUseTransformFromContainer(container)) {
1961 TransformationMatrix t;
1962 getTransformFromContainer(container, containerOffset, t);
1963 transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1965 transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1967 if (containerSkipped) {
1968 // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe
1969 // to just subtract the delta between the repaintContainer and o.
1970 LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(*container);
1971 transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1975 mode &= ~ApplyContainerFlip;
1977 // For fixed positioned elements inside out-of-flow named flows, we do not want to
1978 // map their position further to regions based on their coordinates inside the named flows.
1979 if (!container->isOutOfFlowRenderFlowThread() || !fixedPositionedWithNamedFlowContainingBlock())
1980 container->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed);
1982 container->mapLocalToContainer(downcast<RenderLayerModelObject>(container), transformState, mode, wasFixed);
1985 const RenderObject* RenderBox::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
1987 ASSERT(ancestorToStopAt != this);
1989 bool ancestorSkipped;
1990 RenderElement* container = this->container(ancestorToStopAt, &ancestorSkipped);
1994 bool isFixedPos = style().position() == FixedPosition;
1995 LayoutSize adjustmentForSkippedAncestor;
1996 if (ancestorSkipped) {
1997 // There can't be a transform between repaintContainer and container, because transforms create containers, so it should be safe
1998 // to just subtract the delta between the ancestor and container.
1999 adjustmentForSkippedAncestor = -ancestorToStopAt->offsetFromAncestorContainer(*container);
2002 bool offsetDependsOnPoint = false;
2003 LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint(), &offsetDependsOnPoint);
2005 bool preserve3D = container->style().preserves3D() || style().preserves3D();
2006 if (shouldUseTransformFromContainer(container) && (geometryMap.mapCoordinatesFlags() & UseTransforms)) {
2007 TransformationMatrix t;
2008 getTransformFromContainer(container, containerOffset, t);
2009 t.translateRight(adjustmentForSkippedAncestor.width(), adjustmentForSkippedAncestor.height());
2011 geometryMap.push(this, t, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform());
2013 containerOffset += adjustmentForSkippedAncestor;
2014 geometryMap.push(this, containerOffset, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform());
2017 return ancestorSkipped ? ancestorToStopAt : container;
2020 void RenderBox::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
2022 bool isFixedPos = style().position() == FixedPosition;
2023 if (hasTransform() && !isFixedPos) {
2024 // If this box has a transform, it acts as a fixed position container for fixed descendants,
2025 // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
2027 } else if (isFixedPos)
2030 RenderBoxModelObject::mapAbsoluteToLocalPoint(mode, transformState);
2033 LayoutSize RenderBox::offsetFromContainer(RenderElement& renderer, const LayoutPoint&, bool* offsetDependsOnPoint) const
2035 // A region "has" boxes inside it without being their container.
2036 ASSERT(&renderer == container() || is<RenderRegion>(renderer));
2039 if (isInFlowPositioned())
2040 offset += offsetForInFlowPosition();
2042 if (!isInline() || isReplaced())
2043 offset += topLeftLocationOffset();
2045 if (is<RenderBox>(renderer))
2046 offset -= downcast<RenderBox>(renderer).scrolledContentOffset();
2048 if (style().position() == AbsolutePosition && renderer.isInFlowPositioned() && is<RenderInline>(renderer))
2049 offset += downcast<RenderInline>(renderer).offsetForInFlowPositionedInline(this);
2051 if (offsetDependsOnPoint)
2052 *offsetDependsOnPoint |= is<RenderFlowThread>(renderer);
2057 std::unique_ptr<InlineElementBox> RenderBox::createInlineBox()
2059 return std::make_unique<InlineElementBox>(*this);
2062 void RenderBox::dirtyLineBoxes(bool fullLayout)
2064 if (m_inlineBoxWrapper) {
2066 delete m_inlineBoxWrapper;
2067 m_inlineBoxWrapper = nullptr;
2069 m_inlineBoxWrapper->dirtyLineBoxes();
2073 void RenderBox::positionLineBox(InlineElementBox& box)
2075 if (isOutOfFlowPositioned()) {
2076 // Cache the x position only if we were an INLINE type originally.
2077 bool wasInline = style().isOriginalDisplayInlineType();
2079 // The value is cached in the xPos of the box. We only need this value if
2080 // our object was inline originally, since otherwise it would have ended up underneath
2082 RootInlineBox& rootBox = box.root();
2083 rootBox.blockFlow().setStaticInlinePositionForChild(*this, rootBox.lineTopWithLeading(), LayoutUnit::fromFloatRound(box.logicalLeft()));
2084 if (style().hasStaticInlinePosition(box.isHorizontal()))
2085 setChildNeedsLayout(MarkOnlyThis); // Just mark the positioned object as needing layout, so it will update its position properly.
2087 // Our object was a block originally, so we make our normal flow position be
2088 // just below the line box (as though all the inlines that came before us got
2089 // wrapped in an anonymous block, which is what would have happened had we been
2090 // in flow). This value was cached in the y() of the box.
2091 layer()->setStaticBlockPosition(box.logicalTop());
2092 if (style().hasStaticBlockPosition(box.isHorizontal()))
2093 setChildNeedsLayout(MarkOnlyThis); // Just mark the positioned object as needing layout, so it will update its position properly.
2097 box.removeFromParent();
2103 setLocation(LayoutPoint(box.topLeft()));
2104 setInlineBoxWrapper(&box);
2108 void RenderBox::deleteLineBoxWrapper()
2110 if (m_inlineBoxWrapper) {
2111 if (!documentBeingDestroyed())
2112 m_inlineBoxWrapper->removeFromParent();
2113 delete m_inlineBoxWrapper;
2114 m_inlineBoxWrapper = nullptr;
2118 LayoutRect RenderBox::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
2120 if (style().visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
2121 return LayoutRect();
2123 LayoutRect r = visualOverflowRect();
2125 // FIXME: layoutDelta needs to be applied in parts before/after transforms and
2126 // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
2127 r.move(view().layoutDelta());
2129 // We have to use maximalOutlineSize() because a child might have an outline
2130 // that projects outside of our overflowRect.
2131 ASSERT(style().outlineSize() <= view().maximalOutlineSize());
2132 r.inflate(view().maximalOutlineSize());
2134 computeRectForRepaint(repaintContainer, r);
2138 static inline bool shouldApplyContainersClipAndOffset(const RenderLayerModelObject* repaintContainer, RenderBox* containerBox)
2141 if (!repaintContainer || repaintContainer != containerBox)
2144 return !containerBox->hasLayer() || !containerBox->layer()->usesCompositedScrolling();
2146 UNUSED_PARAM(repaintContainer);
2147 UNUSED_PARAM(containerBox);
2152 void RenderBox::computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect& rect, bool fixed) const
2154 // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
2155 // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
2156 // offset corner for the enclosing container). This allows for a fully RL or BT document to repaint
2157 // properly even during layout, since the rect remains flipped all the way until the end.
2159 // RenderView::computeRectForRepaint then converts the rect to physical coordinates. We also convert to
2160 // physical when we hit a repaintContainer boundary. Therefore the final rect returned is always in the
2161 // physical coordinate space of the repaintContainer.
2162 const RenderStyle& styleToUse = style();
2163 // LayoutState is only valid for root-relative, non-fixed position repainting
2164 if (view().layoutStateEnabled() && !repaintContainer && styleToUse.position() != FixedPosition) {
2165 LayoutState* layoutState = view().layoutState();
2167 if (layer() && layer()->transform())
2168 rect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(rect), document().deviceScaleFactor()));
2170 // We can't trust the bits on RenderObject, because this might be called while re-resolving style.
2171 if (styleToUse.hasInFlowPosition() && layer())
2172 rect.move(layer()->offsetForInFlowPosition());
2174 rect.moveBy(location());
2175 rect.move(layoutState->m_paintOffset);
2176 if (layoutState->m_clipped)
2177 rect.intersect(layoutState->m_clipRect);
2181 if (hasReflection())
2182 rect.unite(reflectedRect(rect));
2184 if (repaintContainer == this) {
2185 if (repaintContainer->style().isFlippedBlocksWritingMode())
2186 flipForWritingMode(rect);
2190 bool containerSkipped;
2191 auto* renderer = container(repaintContainer, &containerSkipped);
2195 EPosition position = styleToUse.position();
2197 // This code isn't necessary for in-flow RenderFlowThreads.
2198 // Don't add the location of the region in the flow thread for absolute positioned
2199 // elements because their absolute position already pushes them down through
2200 // the regions so adding this here and then adding the topLeft again would cause
2201 // us to add the height twice.
2202 // The same logic applies for elements flowed directly into the flow thread. Their topLeft member
2203 // will already contain the portion rect of the region.
2204 if (renderer->isOutOfFlowRenderFlowThread() && position != AbsolutePosition && containingBlock() != flowThreadContainingBlock()) {
2205 RenderRegion* firstRegion = nullptr;
2206 RenderRegion* lastRegion = nullptr;
2207 if (downcast<RenderFlowThread>(*renderer).getRegionRangeForBox(this, firstRegion, lastRegion))
2208 rect.moveBy(firstRegion->flowThreadPortionRect().location());
2211 if (isWritingModeRoot() && !isOutOfFlowPositioned())
2212 flipForWritingMode(rect);
2214 LayoutSize locationOffset = this->locationOffset();
2215 // FIXME: This is needed as long as RenderWidget snaps to integral size/position.
2216 if (isRenderReplaced() && isWidget())
2217 locationOffset = toIntSize(flooredIntPoint(locationOffset));
2218 LayoutPoint topLeft = rect.location();
2219 topLeft.move(locationOffset);
2221 // We are now in our parent container's coordinate space. Apply our transform to obtain a bounding box
2222 // in the parent's coordinate space that encloses us.
2223 if (hasLayer() && layer()->transform()) {
2224 fixed = position == FixedPosition;
2225 rect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(rect), document().deviceScaleFactor()));
2226 topLeft = rect.location();
2227 topLeft.move(locationOffset);
2228 } else if (position == FixedPosition)
2231 if (position == AbsolutePosition && renderer->isInFlowPositioned() && is<RenderInline>(*renderer))
2232 topLeft += downcast<RenderInline>(*renderer).offsetForInFlowPositionedInline(this);
2233 else if (styleToUse.hasInFlowPosition() && layer()) {
2234 // Apply the relative position offset when invalidating a rectangle. The layer
2235 // is translated, but the render box isn't, so we need to do this to get the
2236 // right dirty rect. Since this is called from RenderObject::setStyle, the relative position
2237 // flag on the RenderObject has been cleared, so use the one on the style().
2238 topLeft += layer()->offsetForInFlowPosition();
2241 // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
2242 // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
2243 rect.setLocation(topLeft);
2244 if (renderer->hasOverflowClip()) {
2245 RenderBox& containerBox = downcast<RenderBox>(*renderer);
2246 if (shouldApplyContainersClipAndOffset(repaintContainer, &containerBox)) {
2247 containerBox.applyCachedClipAndScrollOffsetForRepaint(rect);
2253 if (containerSkipped) {
2254 // If the repaintContainer is below o, then we need to map the rect into repaintContainer's coordinates.
2255 LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(*renderer);
2256 rect.move(-containerOffset);
2260 renderer->computeRectForRepaint(repaintContainer, rect, fixed);
2263 void RenderBox::repaintDuringLayoutIfMoved(const LayoutRect& oldRect)
2265 if (oldRect.location() != m_frameRect.location()) {
2266 LayoutRect newRect = m_frameRect;
2267 // The child moved. Invalidate the object's old and new positions. We have to do this
2268 // since the object may not have gotten a layout.
2269 m_frameRect = oldRect;
2271 repaintOverhangingFloats(true);
2272 m_frameRect = newRect;
2274 repaintOverhangingFloats(true);
2278 void RenderBox::repaintOverhangingFloats(bool)
2282 void RenderBox::updateLogicalWidth()
2284 LogicalExtentComputedValues computedValues;
2285 computeLogicalWidthInRegion(computedValues);
2287 setLogicalWidth(computedValues.m_extent);
2288 setLogicalLeft(computedValues.m_position);
2289 setMarginStart(computedValues.m_margins.m_start);
2290 setMarginEnd(computedValues.m_margins.m_end);
2293 void RenderBox::computeLogicalWidthInRegion(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
2295 computedValues.m_extent = logicalWidth();
2296 computedValues.m_position = logicalLeft();
2297 computedValues.m_margins.m_start = marginStart();
2298 computedValues.m_margins.m_end = marginEnd();
2300 if (isOutOfFlowPositioned()) {
2301 // FIXME: This calculation is not patched for block-flow yet.
2302 // https://bugs.webkit.org/show_bug.cgi?id=46500
2303 computePositionedLogicalWidth(computedValues, region);
2307 // If layout is limited to a subtree, the subtree root's logical width does not change.
2308 if (element() && view().frameView().layoutRoot(true) == this)
2311 // The parent box is flexing us, so it has increased or decreased our
2312 // width. Use the width from the style context.
2313 // FIXME: Account for block-flow in flexible boxes.
2314 // https://bugs.webkit.org/show_bug.cgi?id=46418
2315 if (hasOverrideLogicalContentWidth() && (isRubyRun() || style().borderFit() == BorderFitLines || parent()->isFlexibleBoxIncludingDeprecated())) {
2316 computedValues.m_extent = overrideLogicalContentWidth() + borderAndPaddingLogicalWidth();
2320 // FIXME: Account for block-flow in flexible boxes.
2321 // https://bugs.webkit.org/show_bug.cgi?id=46418
2322 bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == VERTICAL);
2323 bool stretching = (parent()->style().boxAlign() == BSTRETCH);
2324 bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
2326 const RenderStyle& styleToUse = style();
2327 Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse.logicalWidth();
2329 RenderBlock* cb = containingBlock();
2330 LayoutUnit containerLogicalWidth = std::max<LayoutUnit>(0, containingBlockLogicalWidthForContentInRegion(region));
2331 bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
2333 if (isInline() && !isInlineBlockOrInlineTable()) {
2334 // just calculate margins
2335 computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2336 computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2337 if (treatAsReplaced)
2338 computedValues.m_extent = std::max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
2342 // Width calculations
2343 if (treatAsReplaced)
2344 computedValues.m_extent = logicalWidthLength.value() + borderAndPaddingLogicalWidth();
2346 LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
2347 if (hasPerpendicularContainingBlock)
2348 containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
2349 LayoutUnit preferredWidth = computeLogicalWidthInRegionUsing(MainOrPreferredSize, styleToUse.logicalWidth(), containerWidthInInlineDirection, cb, region);
2350 computedValues.m_extent = constrainLogicalWidthInRegionByMinMax(preferredWidth, containerWidthInInlineDirection, cb, region);
2353 // Margin calculations.
2354 if (hasPerpendicularContainingBlock || isFloating() || isInline()) {
2355 computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2356 computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2358 LayoutUnit containerLogicalWidthForAutoMargins = containerLogicalWidth;
2359 if (avoidsFloats() && cb->containsFloats())
2360 containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInRegion(region);
2361 bool hasInvertedDirection = cb->style().isLeftToRightDirection() != style().isLeftToRightDirection();
2362 computeInlineDirectionMargins(cb, containerLogicalWidthForAutoMargins, computedValues.m_extent,
2363 hasInvertedDirection ? computedValues.m_margins.m_end : computedValues.m_margins.m_start,
2364 hasInvertedDirection ? computedValues.m_margins.m_start : computedValues.m_margins.m_end);
2367 if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (computedValues.m_extent + computedValues.m_margins.m_start + computedValues.m_margins.m_end)
2368 && !isFloating() && !isInline() && !cb->isFlexibleBoxIncludingDeprecated()
2369 #if ENABLE(CSS_GRID_LAYOUT)
2370 && !cb->isRenderGrid()
2373 LayoutUnit newMargin = containerLogicalWidth - computedValues.m_extent - cb->marginStartForChild(*this);
2374 bool hasInvertedDirection = cb->style().isLeftToRightDirection() != style().isLeftToRightDirection();
2375 if (hasInvertedDirection)
2376 computedValues.m_margins.m_start = newMargin;
2378 computedValues.m_margins.m_end = newMargin;
2382 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth) const
2384 LayoutUnit marginStart = 0;
2385 LayoutUnit marginEnd = 0;
2386 return fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2389 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2391 marginStart = minimumValueForLength(style().marginStart(), availableLogicalWidth);
2392 marginEnd = minimumValueForLength(style().marginEnd(), availableLogicalWidth);
2393 return availableLogicalWidth - marginStart - marginEnd;
2396 LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(Length logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const
2398 if (logicalWidthLength.type() == FillAvailable)
2399 return fillAvailableMeasure(availableLogicalWidth);
2401 LayoutUnit minLogicalWidth = 0;
2402 LayoutUnit maxLogicalWidth = 0;
2403 computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
2405 if (logicalWidthLength.type() == MinContent)
2406 return minLogicalWidth + borderAndPadding;
2408 if (logicalWidthLength.type() == MaxContent)
2409 return maxLogicalWidth + borderAndPadding;
2411 if (logicalWidthLength.type() == FitContent) {
2412 minLogicalWidth += borderAndPadding;
2413 maxLogicalWidth += borderAndPadding;
2414 return std::max(minLogicalWidth, std::min(maxLogicalWidth, fillAvailableMeasure(availableLogicalWidth)));
2417 ASSERT_NOT_REACHED();
2421 LayoutUnit RenderBox::computeLogicalWidthInRegionUsing(SizeType widthType, Length logicalWidth, LayoutUnit availableLogicalWidth,
2422 const RenderBlock* cb, RenderRegion* region) const
2424 if (!logicalWidth.isIntrinsicOrAuto()) {
2425 // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
2426 return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth));
2429 if (logicalWidth.isIntrinsic())
2430 return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth());
2432 LayoutUnit marginStart = 0;
2433 LayoutUnit marginEnd = 0;
2434 LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2436 if (shrinkToAvoidFloats() && cb->containsFloats())
2437 logicalWidthResult = std::min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, region));
2439 if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(widthType))
2440 return std::max(minPreferredLogicalWidth(), std::min(maxPreferredLogicalWidth(), logicalWidthResult));
2441 return logicalWidthResult;
2444 static bool flexItemHasStretchAlignment(const RenderBox& flexitem)
2446 auto parent = flexitem.parent();
2447 return RenderStyle::resolveAlignment(parent->style(), flexitem.style(), ItemPositionStretch) == ItemPositionStretch;
2450 static bool isStretchingColumnFlexItem(const RenderBox& flexitem)
2452 auto parent = flexitem.parent();
2453 if (parent->isDeprecatedFlexibleBox() && parent->style().boxOrient() == VERTICAL && parent->style().boxAlign() == BSTRETCH)
2456 // We don't stretch multiline flexboxes because they need to apply line spacing (align-content) first.
2457 if (parent->isFlexibleBox() && parent->style().flexWrap() == FlexNoWrap && parent->style().isColumnFlexDirection() && flexItemHasStretchAlignment(flexitem))
2462 bool RenderBox::sizesLogicalWidthToFitContent(SizeType widthType) const
2464 // Anonymous inline blocks always fill the width of their containing block.
2465 if (isAnonymousInlineBlock())
2468 // Marquees in WinIE are like a mixture of blocks and inline-blocks. They size as though they're blocks,
2469 // but they allow text to sit on the same line as the marquee.
2470 if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee()))
2473 // This code may look a bit strange. Basically width:intrinsic should clamp the size when testing both
2474 // min-width and width. max-width is only clamped if it is also intrinsic.
2475 Length logicalWidth = (widthType == MaxSize) ? style().logicalMaxWidth() : style().logicalWidth();
2476 if (logicalWidth.type() == Intrinsic)
2479 // Children of a horizontal marquee do not fill the container by default.
2480 // FIXME: Need to deal with MAUTO value properly. It could be vertical.
2481 // FIXME: Think about block-flow here. Need to find out how marquee direction relates to
2482 // block-flow (as well as how marquee overflow should relate to block flow).
2483 // https://bugs.webkit.org/show_bug.cgi?id=46472
2484 if (parent()->style().overflowX() == OMARQUEE) {
2485 EMarqueeDirection dir = parent()->style().marqueeDirection();
2486 if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
2490 // Flexible box items should shrink wrap, so we lay them out at their intrinsic widths.
2491 // In the case of columns that have a stretch alignment, we layout at the stretched size
2492 // to avoid an extra layout when applying alignment.
2493 if (parent()->isFlexibleBox()) {
2494 // For multiline columns, we need to apply align-content first, so we can't stretch now.
2495 if (!parent()->style().isColumnFlexDirection() || parent()->style().flexWrap() != FlexNoWrap)
2497 if (!flexItemHasStretchAlignment(*this))
2501 // Flexible horizontal boxes lay out children at their intrinsic widths. Also vertical boxes
2502 // that don't stretch their kids lay out their children at their intrinsic widths.
2503 // FIXME: Think about block-flow here.
2504 // https://bugs.webkit.org/show_bug.cgi?id=46473
2505 if (parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == HORIZONTAL || parent()->style().boxAlign() != BSTRETCH))
2508 // Button, input, select, textarea, and legend treat width value of 'auto' as 'intrinsic' unless it's in a
2509 // stretching column flexbox.
2510 // FIXME: Think about block-flow here.
2511 // https://bugs.webkit.org/show_bug.cgi?id=46473
2512 if (logicalWidth.type() == Auto && !isStretchingColumnFlexItem(*this) && element() && (is<HTMLInputElement>(*element()) || is<HTMLSelectElement>(*element()) || is<HTMLButtonElement>(*element()) || is<HTMLTextAreaElement>(*element()) || is<HTMLLegendElement>(*element())))
2515 if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
2521 void RenderBox::computeInlineDirectionMargins(RenderBlock* containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2523 const RenderStyle& containingBlockStyle = containingBlock->style();
2524 Length marginStartLength = style().marginStartUsing(&containingBlockStyle);
2525 Length marginEndLength = style().marginEndUsing(&containingBlockStyle);
2527 if (isFloating() || isInline()) {
2528 // Inline blocks/tables and floats don't have their margins increased.
2529 marginStart = minimumValueForLength(marginStartLength, containerWidth);
2530 marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2534 // Case One: The object is being centered in the containing block's available logical width.
2535 if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
2536 || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock->style().textAlign() == WEBKIT_CENTER)) {
2537 // Other browsers center the margin box for align=center elements so we match them here.
2538 LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth);
2539 LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth);
2540 LayoutUnit centeredMarginBoxStart = std::max<LayoutUnit>(0, (containerWidth - childWidth - marginStartWidth - marginEndWidth) / 2);
2541 marginStart = centeredMarginBoxStart + marginStartWidth;
2542 marginEnd = containerWidth - childWidth - marginStart + marginEndWidth;
2546 // Case Two: The object is being pushed to the start of the containing block's available logical width.
2547 if (marginEndLength.isAuto() && childWidth < containerWidth) {
2548 marginStart = valueForLength(marginStartLength, containerWidth);
2549 marginEnd = containerWidth - childWidth - marginStart;
2553 // Case Three: The object is being pushed to the end of the containing block's available logical width.
2554 bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_LEFT)
2555 || (containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_RIGHT));
2556 if ((marginStartLength.isAuto() && childWidth < containerWidth) || pushToEndFromTextAlign) {
2557 marginEnd = valueForLength(marginEndLength, containerWidth);
2558 marginStart = containerWidth - childWidth - marginEnd;
2562 // Case Four: Either no auto margins, or our width is >= the container width (css2.1, 10.3.3). In that case
2563 // auto margins will just turn into 0.
2564 marginStart = minimumValueForLength(marginStartLength, containerWidth);
2565 marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2568 RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
2570 // Make sure nobody is trying to call this with a null region.
2574 // If we have computed our width in this region already, it will be cached, and we can
2576 RenderBoxRegionInfo* boxInfo = region->renderBoxRegionInfo(this);
2577 if (boxInfo && cacheFlag == CacheRenderBoxRegionInfo)
2580 // No cached value was found, so we have to compute our insets in this region.
2581 // FIXME: For now we limit this computation to normal RenderBlocks. Future patches will expand
2582 // support to cover all boxes.
2583 RenderFlowThread* flowThread = flowThreadContainingBlock();
2584 if (isRenderFlowThread() || !flowThread || !canHaveBoxInfoInRegion() || flowThread->style().writingMode() != style().writingMode())
2587 LogicalExtentComputedValues computedValues;
2588 computeLogicalWidthInRegion(computedValues, region);
2590 // Now determine the insets based off where this object is supposed to be positioned.
2591 RenderBlock* cb = containingBlock();
2592 RenderRegion* clampedContainingBlockRegion = cb->clampToStartAndEndRegions(region);
2593 RenderBoxRegionInfo* containingBlockInfo = cb->renderBoxRegionInfo(clampedContainingBlockRegion);
2594 LayoutUnit containingBlockLogicalWidth = cb->logicalWidth();
2595 LayoutUnit containingBlockLogicalWidthInRegion = containingBlockInfo ? containingBlockInfo->logicalWidth() : containingBlockLogicalWidth;
2597 LayoutUnit marginStartInRegion = computedValues.m_margins.m_start;
2598 LayoutUnit startMarginDelta = marginStartInRegion - marginStart();
2599 LayoutUnit logicalWidthInRegion = computedValues.m_extent;
2600 LayoutUnit logicalLeftInRegion = computedValues.m_position;
2601 LayoutUnit widthDelta = logicalWidthInRegion - logicalWidth();
2602 LayoutUnit logicalLeftDelta = isOutOfFlowPositioned() ? logicalLeftInRegion - logicalLeft() : startMarginDelta;
2603 LayoutUnit logicalRightInRegion = containingBlockLogicalWidthInRegion - (logicalLeftInRegion + logicalWidthInRegion);
2604 LayoutUnit oldLogicalRight = containingBlockLogicalWidth - (logicalLeft() + logicalWidth());
2605 LayoutUnit logicalRightDelta = isOutOfFlowPositioned() ? logicalRightInRegion - oldLogicalRight : startMarginDelta;
2607 LayoutUnit logicalLeftOffset = 0;
2609 if (!isOutOfFlowPositioned() && avoidsFloats() && cb->containsFloats()) {
2610 LayoutUnit startPositionDelta = cb->computeStartPositionDeltaForChildAvoidingFloats(*this, marginStartInRegion, region);
2611 if (cb->style().isLeftToRightDirection())
2612 logicalLeftDelta += startPositionDelta;
2614 logicalRightDelta += startPositionDelta;
2617 if (cb->style().isLeftToRightDirection())
2618 logicalLeftOffset += logicalLeftDelta;
2620 logicalLeftOffset -= (widthDelta + logicalRightDelta);
2622 LayoutUnit logicalRightOffset = logicalWidth() - (logicalLeftOffset + logicalWidthInRegion);
2623 bool isShifted = (containingBlockInfo && containingBlockInfo->isShifted())
2624 || (style().isLeftToRightDirection() && logicalLeftOffset)
2625 || (!style().isLeftToRightDirection() && logicalRightOffset);
2627 // FIXME: Although it's unlikely, these boxes can go outside our bounds, and so we will need to incorporate them into overflow.
2628 if (cacheFlag == CacheRenderBoxRegionInfo)
2629 return region->setRenderBoxRegionInfo(this, logicalLeftOffset, logicalWidthInRegion, isShifted);
2630 return new RenderBoxRegionInfo(logicalLeftOffset, logicalWidthInRegion, isShifted);
2633 static bool shouldFlipBeforeAfterMargins(const RenderStyle& containingBlockStyle, const RenderStyle* childStyle)
2635 ASSERT(containingBlockStyle.isHorizontalWritingMode() != childStyle->isHorizontalWritingMode());
2636 WritingMode childWritingMode = childStyle->writingMode();
2637 bool shouldFlip = false;
2638 switch (containingBlockStyle.writingMode()) {
2639 case TopToBottomWritingMode:
2640 shouldFlip = (childWritingMode == RightToLeftWritingMode);
2642 case BottomToTopWritingMode:
2643 shouldFlip = (childWritingMode == RightToLeftWritingMode);
2645 case RightToLeftWritingMode:
2646 shouldFlip = (childWritingMode == BottomToTopWritingMode);
2648 case LeftToRightWritingMode:
2649 shouldFlip = (childWritingMode == BottomToTopWritingMode);
2653 if (!containingBlockStyle.isLeftToRightDirection())
2654 shouldFlip = !shouldFlip;
2659 void RenderBox::updateLogicalHeight()
2661 LogicalExtentComputedValues computedValues;
2662 computeLogicalHeight(logicalHeight(), logicalTop(), computedValues);
2664 setLogicalHeight(computedValues.m_extent);
2665 setLogicalTop(computedValues.m_position);
2666 setMarginBefore(computedValues.m_margins.m_before);
2667 setMarginAfter(computedValues.m_margins.m_after);
2670 void RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
2672 computedValues.m_extent = logicalHeight;
2673 computedValues.m_position = logicalTop;
2675 // Cell height is managed by the table and inline non-replaced elements do not support a height property.
2676 if (isTableCell() || (isInline() && !isReplaced()))
2680 if (isOutOfFlowPositioned())
2681 computePositionedLogicalHeight(computedValues);
2683 RenderBlock* cb = containingBlock();
2684 bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
2686 if (!hasPerpendicularContainingBlock) {
2687 bool shouldFlipBeforeAfter = cb->style().writingMode() != style().writingMode();
2688 computeBlockDirectionMargins(cb,
2689 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2690 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2693 // For tables, calculate margins only.
2695 if (hasPerpendicularContainingBlock) {
2696 bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), &style());
2697 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), computedValues.m_extent,
2698 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2699 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2704 // FIXME: Account for block-flow in flexible boxes.
2705 // https://bugs.webkit.org/show_bug.cgi?id=46418
2706 bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style().boxOrient() == HORIZONTAL;
2707 bool stretching = parent()->style().boxAlign() == BSTRETCH;
2708 bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
2709 bool checkMinMaxHeight = false;
2711 // The parent box is flexing us, so it has increased or decreased our height. We have to
2712 // grab our cached flexible height.
2713 // FIXME: Account for block-flow in flexible boxes.
2714 // https://bugs.webkit.org/show_bug.cgi?id=46418
2715 if (hasOverrideLogicalContentHeight() && (parent()->isFlexibleBoxIncludingDeprecated() || parent()->isRenderGrid()))
2716 h = Length(overrideLogicalContentHeight(), Fixed);
2717 else if (treatAsReplaced)
2718 h = Length(computeReplacedLogicalHeight(), Fixed);
2720 h = style().logicalHeight();
2721 checkMinMaxHeight = true;
2724 // Block children of horizontal flexible boxes fill the height of the box.
2725 // FIXME: Account for block-flow in flexible boxes.
2726 // https://bugs.webkit.org/show_bug.cgi?id=46418
2727 if (h.isAuto() && is<RenderDeprecatedFlexibleBox>(*parent()) && parent()->style().boxOrient() == HORIZONTAL
2728 && downcast<RenderDeprecatedFlexibleBox>(*parent()).isStretchingChildren()) {
2729 h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2730 checkMinMaxHeight = false;
2733 LayoutUnit heightResult;
2734 if (checkMinMaxHeight) {
2735 heightResult = computeLogicalHeightUsing(style().logicalHeight());
2736 if (heightResult == -1)
2737 heightResult = computedValues.m_extent;
2738 heightResult = constrainLogicalHeightByMinMax(heightResult);
2740 // The only times we don't check min/max height are when a fixed length has
2741 // been given as an override. Just use that. The value has already been adjusted
2743 heightResult = h.value() + borderAndPaddingLogicalHeight();
2746 computedValues.m_extent = heightResult;
2748 if (hasPerpendicularContainingBlock) {
2749 bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), &style());
2750 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult,
2751 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2752 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2756 // WinIE quirk: The <html> block always fills the entire canvas in quirks mode. The <body> always fills the
2757 // <html> block in quirks mode. Only apply this quirk if the block is normal flow and no height
2758 // is specified. When we're printing, we also need this quirk if the body or root has a percentage
2759 // height since we don't set a height in RenderView when we're printing. So without this quirk, the
2760 // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2761 bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercent()
2762 && (isRoot() || (isBody() && document().documentElement()->renderer()->style().logicalHeight().isPercent())) && !isInline();
2763 if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2764 LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2765 LayoutUnit visibleHeight = view().pageOrViewLogicalHeight();
2767 computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - margins);
2769 LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2770 computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - marginsBordersPadding);
2775 LayoutUnit RenderBox::computeLogicalHeightUsing(const Length& height) const
2777 LayoutUnit logicalHeight = computeContentAndScrollbarLogicalHeightUsing(height);
2778 if (logicalHeight != -1)
2779 logicalHeight = adjustBorderBoxLogicalHeightForBoxSizing(logicalHeight);
2780 return logicalHeight;
2783 LayoutUnit RenderBox::computeContentLogicalHeight(const Length& height) const
2785 LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(height);
2786 if (heightIncludingScrollbar == -1)
2788 return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2791 LayoutUnit RenderBox::computeContentAndScrollbarLogicalHeightUsing(const Length& height) const
2793 if (height.isFixed())
2794 return height.value();
2795 if (height.isPercent())
2796 return computePercentageLogicalHeight(height);
2800 bool RenderBox::skipContainingBlockForPercentHeightCalculation(const RenderBox* containingBlock, bool isPerpendicularWritingMode) const
2802 // Flow threads for multicol or paged overflow should be skipped. They are invisible to the DOM,
2803 // and percent heights of children should be resolved against the multicol or paged container.
2804 if (containingBlock->isInFlowRenderFlowThread() && !isPerpendicularWritingMode)
2807 // For quirks mode and anonymous blocks, we skip auto-height containingBlocks when computing percentages.
2808 // For standards mode, we treat the percentage as auto if it has an auto-height containing block.
2809 if (!document().inQuirksMode() && !containingBlock->isAnonymousBlock())
2811 return !containingBlock->isTableCell() && !containingBlock->isOutOfFlowPositioned() && containingBlock->style().logicalHeight().isAuto() && isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode();
2814 LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height) const
2816 LayoutUnit availableHeight = -1;
2818 bool skippedAutoHeightContainingBlock = false;
2819 RenderBlock* cb = containingBlock();
2820 const RenderBox* containingBlockChild = this;
2821 LayoutUnit rootMarginBorderPaddingHeight = 0;
2822 bool isHorizontal = isHorizontalWritingMode();
2823 while (!cb->isRenderView() && skipContainingBlockForPercentHeightCalculation(cb, isHorizontal != cb->isHorizontalWritingMode())) {
2824 if (cb->isBody() || cb->isRoot())
2825 rootMarginBorderPaddingHeight += cb->marginBefore() + cb->marginAfter() + cb->borderAndPaddingLogicalHeight();
2826 skippedAutoHeightContainingBlock = true;
2827 containingBlockChild = cb;
2828 cb = cb->containingBlock();
2829 cb->addPercentHeightDescendant(const_cast<RenderBox&>(*this));
2832 const RenderStyle& cbstyle = cb->style();
2834 // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
2835 // explicitly specified that can be used for any percentage computations.
2836 bool isOutOfFlowPositionedWithSpecifiedHeight = cb->isOutOfFlowPositioned() && (!cbstyle.logicalHeight().isAuto() || (!cbstyle.logicalTop().isAuto() && !cbstyle.logicalBottom().isAuto()));
2838 bool includeBorderPadding = isTable();
2840 if (isHorizontal != cb->isHorizontalWritingMode())
2841 availableHeight = containingBlockChild->containingBlockLogicalWidthForContent();
2842 #if ENABLE(CSS_GRID_LAYOUT)
2843 else if (hasOverrideContainingBlockLogicalHeight())
2844 availableHeight = overrideContainingBlockContentLogicalHeight();
2846 else if (is<RenderTableCell>(*cb)) {
2847 if (!skippedAutoHeightContainingBlock) {
2848 // Table cells violate what the CSS spec says to do with heights. Basically we
2849 // don't care if the cell specified a height or not. We just always make ourselves
2850 // be a percentage of the cell's current content height.
2851 if (!cb->hasOverrideLogicalContentHeight()) {
2852 // Normally we would let the cell size intrinsically, but scrolling overflow has to be
2853 // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
2854 // While we can't get all cases right, we can at least detect when the cell has a specified
2855 // height or when the table has a specified height. In these cases we want to initially have
2856 // no size and allow the flexing of the table or the cell to its specified height to cause us
2857 // to grow to fill the space. This could end up being wrong in some cases, but it is
2858 // preferable to the alternative (sizing intrinsically and making the row end up too big).
2859 RenderTableCell& cell = downcast<RenderTableCell>(*cb);
2860 if (scrollsOverflowY() && (!cell.style().logicalHeight().isAuto() || !cell.table()->style().logicalHeight().isAuto()))
2864 availableHeight = cb->overrideLogicalContentHeight();
2865 includeBorderPadding = true;
2867 } else if (cbstyle.logicalHeight().isFixed()) {
2868 LayoutUnit contentBoxHeight = cb->adjustContentBoxLogicalHeightForBoxSizing(cbstyle.logicalHeight().value());
2869 availableHeight = std::max<LayoutUnit>(0, cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeight - cb->scrollbarLogicalHeight()));
2870 } else if (cbstyle.logicalHeight().isPercent() && !isOutOfFlowPositionedWithSpecifiedHeight) {
2871 // We need to recur and compute the percentage height for our containing block.
2872 LayoutUnit heightWithScrollbar = cb->computePercentageLogicalHeight(cbstyle.logicalHeight());
2873 if (heightWithScrollbar != -1) {
2874 LayoutUnit contentBoxHeightWithScrollbar = cb->adjustContentBoxLogicalHeightForBoxSizing(heightWithScrollbar);
2875 // We need to adjust for min/max height because this method does not
2876 // handle the min/max of the current block, its caller does. So the
2877 // return value from the recursive call will not have been adjusted
2879 LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight());
2880 availableHeight = std::max<LayoutUnit>(0, contentBoxHeight);
2882 } else if (isOutOfFlowPositionedWithSpecifiedHeight) {
2883 // Don't allow this to affect the block' height() member variable, since this
2884 // can get called while the block is still laying out its kids.
2885 LogicalExtentComputedValues computedValues;
2886 cb->computeLogicalHeight(cb->logicalHeight(), 0, computedValues);
2887 availableHeight = computedValues.m_extent - cb->borderAndPaddingLogicalHeight() - cb->scrollbarLogicalHeight();
2888 } else if (cb->isRenderView())
2889 availableHeight = view().pageOrViewLogicalHeight();
2891 if (availableHeight == -1)
2892 return availableHeight;
2894 availableHeight -= rootMarginBorderPaddingHeight;
2896 LayoutUnit result = valueForLength(height, availableHeight);
2897 if (includeBorderPadding) {
2898 // FIXME: Table cells should default to box-sizing: border-box so we can avoid this hack.
2899 // It is necessary to use the border-box to match WinIE's broken
2900 // box model. This is essential for sizing inside
2901 // table cells using percentage heights.
2902 result -= borderAndPaddingLogicalHeight();
2903 return std::max<LayoutUnit>(0, result);
2908 LayoutUnit RenderBox::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
2910 return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(style().logicalWidth()), shouldComputePreferred);
2913 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, ShouldComputePreferred shouldComputePreferred) const
2915 LayoutUnit minLogicalWidth = (shouldComputePreferred == ComputePreferred && style().logicalMinWidth().isPercent()) || style().logicalMinWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style().logicalMinWidth());
2916 LayoutUnit maxLogicalWidth = (shouldComputePreferred == ComputePreferred && style().logicalMaxWidth().isPercent()) || style().logicalMaxWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style().logicalMaxWidth());
2917 return std::max(minLogicalWidth, std::min(logicalWidth, maxLogicalWidth));
2920 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(Length logicalWidth) const
2922 switch (logicalWidth.type()) {
2924 return adjustContentBoxLogicalWidthForBoxSizing(logicalWidth.value());
2927 // MinContent/MaxContent don't need the availableLogicalWidth argument.
2928 LayoutUnit availableLogicalWidth = 0;
2929 return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2935 // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
2936 // containing block's block-flow.
2937 // https://bugs.webkit.org/show_bug.cgi?id=46496
2938 const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(downcast<RenderBoxModelObject>(container())) : containingBlockLogicalWidthForContent();
2939 Length containerLogicalWidth = containingBlock()->style().logicalWidth();
2940 // FIXME: Handle cases when containing block width is calculated or viewport percent.
2941 // https://bugs.webkit.org/show_bug.cgi?id=91071
2942 if (logicalWidth.isIntrinsic())
2943 return computeIntrinsicLogicalWidthUsing(logicalWidth, cw, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2944 if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercent())))
2945 return adjustContentBoxLogicalWidthForBoxSizing(minimumValueForLength(logicalWidth, cw));
2953 return intrinsicLogicalWidth();
2956 ASSERT_NOT_REACHED();
2960 LayoutUnit RenderBox::computeReplacedLogicalHeight() const
2962 return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(style().logicalHeight()));
2965 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
2967 LayoutUnit minLogicalHeight = computeReplacedLogicalHeightUsing(style().logicalMinHeight());
2968 LayoutUnit maxLogicalHeight = style().logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(style().logicalMaxHeight());
2969 return std::max(minLogicalHeight, std::min(logicalHeight, maxLogicalHeight));
2972 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(Length logicalHeight) const
2974 switch (logicalHeight.type()) {
2976 return adjustContentBoxLogicalHeightForBoxSizing(logicalHeight.value());
2980 auto cb = isOutOfFlowPositioned() ? container() : containingBlock();
2981 while (cb->isAnonymous() && !is<RenderView>(*cb)) {
2982 cb = cb->containingBlock();
2983 downcast<RenderBlock>(*cb).addPercentHeightDescendant(const_cast<RenderBox&>(*this));
2986 // FIXME: This calculation is not patched for block-flow yet.
2987 // https://bugs.webkit.org/show_bug.cgi?id=46500
2988 if (cb->isOutOfFlowPositioned() && cb->style().height().isAuto() && !(cb->style().top().isAuto() || cb->style().bottom().isAuto())) {
2989 ASSERT_WITH_SECURITY_IMPLICATION(cb->isRenderBlock());
2990 RenderBlock& block = downcast<RenderBlock>(*cb);
2991 LogicalExtentComputedValues computedValues;
2992 block.computeLogicalHeight(block.logicalHeight(), 0, computedValues);
2993 LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
2994 LayoutUnit newHeight = block.adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
2995 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, newHeight));
2998 // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
2999 // containing block's block-flow.
3000 // https://bugs.webkit.org/show_bug.cgi?id=46496
3001 LayoutUnit availableHeight;
3002 if (isOutOfFlowPositioned())
3003 availableHeight = containingBlockLogicalHeightForPositioned(downcast<RenderBoxModelObject>(cb));
3005 availableHeight = containingBlockLogicalHeightForContent(IncludeMarginBorderPadding);
3006 // It is necessary to use the border-box to match WinIE's broken
3007 // box model. This is essential for sizing inside
3008 // table cells using percentage heights.
3009 // FIXME: This needs to be made block-flow-aware. If the cell and image are perpendicular block-flows, this isn't right.
3010 // https://bugs.webkit.org/show_bug.cgi?id=46997
3011 while (cb && !cb->isRenderView() && (cb->style().logicalHeight().isAuto() || cb->style().logicalHeight().isPercent())) {
3012 if (cb->isTableCell()) {
3013 // Don't let table cells squeeze percent-height replaced elements
3014 // <http://bugs.webkit.org/show_bug.cgi?id=15359>
3015 availableHeight = std::max(availableHeight, intrinsicLogicalHeight());
3016 return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight());
3018 downcast<RenderBlock>(*cb).addPercentHeightDescendant(const_cast<RenderBox&>(*this));
3019 cb = cb->containingBlock();
3022 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight));
3025 return intrinsicLogicalHeight();
3029 LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const
3031 return constrainLogicalHeightByMinMax(availableLogicalHeightUsing(style().logicalHeight(), heightType));
3034 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const
3036 // We need to stop here, since we don't want to increase the height of the table
3037 // artificially. We're going to rely on this cell getting expanded to some new
3038 // height, and then when we lay out again we'll use the calculation below.
3039 if (isTableCell() && (h.isAuto() || h.isPercent())) {
3040 if (hasOverrideLogicalContentHeight())
3041 return overrideLogicalContentHeight();
3042 return logicalHeight() - borderAndPaddingLogicalHeight();
3045 if (h.isPercent() && isOutOfFlowPositioned() && !isRenderFlowThread()) {
3046 // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3047 LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(containingBlock());
3048 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight));
3051 LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(h);
3052 if (heightIncludingScrollbar != -1)
3053 return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
3055 // FIXME: Check logicalTop/logicalBottom here to correctly handle vertical writing-mode.
3056 // https://bugs.webkit.org/show_bug.cgi?id=46500
3057 if (is<RenderBlock>(*this) && isOutOfFlowPositioned() && style().height().isAuto() && !(style().top().isAuto() || style().bottom().isAuto())) {
3058 RenderBlock& block = const_cast<RenderBlock&>(downcast<RenderBlock>(*this));
3059 LogicalExtentComputedValues computedValues;
3060 block.computeLogicalHeight(block.logicalHeight(), 0, computedValues);
3061 LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3062 return adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3065 // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3066 LayoutUnit availableHeight = containingBlockLogicalHeightForContent(heightType);
3067 if (heightType == ExcludeMarginBorderPadding) {
3068 // FIXME: Margin collapsing hasn't happened yet, so this incorrectly removes collapsed margins.
3069 availableHeight -= marginBefore() + marginAfter() + borderAndPaddingLogicalHeight();
3071 return availableHeight;
3074 void RenderBox::computeBlockDirectionMargins(const RenderBlock* containingBlock, LayoutUnit& marginBefore, LayoutUnit& marginAfter) const
3076 if (isTableCell()) {
3077 // FIXME: Not right if we allow cells to have different directionality than the table. If we do allow this, though,
3078 // we may just do it with an extra anonymous block inside the cell.
3084 // Margins are calculated with respect to the logical width of
3085 // the containing block (8.3)
3086 LayoutUnit cw = containingBlockLogicalWidthForContent();
3087 const RenderStyle& containingBlockStyle = containingBlock->style();
3088 marginBefore = minimumValueForLength(style().marginBeforeUsing(&containingBlockStyle), cw);
3089 marginAfter = minimumValueForLength(style().marginAfterUsing(&containingBlockStyle), cw);
3092 void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock* containingBlock)
3094 LayoutUnit marginBefore;
3095 LayoutUnit marginAfter;
3096 computeBlockDirectionMargins(containingBlock, marginBefore, marginAfter);
3097 containingBlock->setMarginBeforeForChild(*this, marginBefore);
3098 containingBlock->setMarginAfterForChild(*this, marginAfter);
3101 LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, RenderRegion* region, bool checkForPerpendicularWritingMode) const
3103 if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
3104 return containingBlockLogicalHeightForPositioned(containingBlock, false);
3106 if (is<RenderBox>(*containingBlock)) {
3107 bool isFixedPosition = style().position() == FixedPosition;
3109 RenderFlowThread* flowThread = flowThreadContainingBlock();
3111 if (isFixedPosition && is<RenderView>(*containingBlock))
3112 return downcast<RenderView>(*containingBlock).clientLogicalWidthForFixedPosition();
3114 return downcast<RenderBox>(*containingBlock).clientLogicalWidth();
3117 if (isFixedPosition && is<RenderNamedFlowThread>(*containingBlock))
3118 return containingBlock->view().clientLogicalWidth();
3120 if (!is<RenderBlock>(*containingBlock))
3121 return downcast<RenderBox>(*containingBlock).clientLogicalWidth();
3123 const RenderBlock& cb = downcast<RenderBlock>(*containingBlock);
3124 RenderBoxRegionInfo* boxInfo = nullptr;
3126 if (is<RenderFlowThread>(*containingBlock) && !checkForPerpendicularWritingMode)
3127 return downcast<RenderFlowThread>(*containingBlock).contentLogicalWidthOfFirstRegion();
3128 if (isWritingModeRoot()) {
3129 LayoutUnit cbPageOffset = cb.offsetFromLogicalTopOfFirstPage();
3130 RenderRegion* cbRegion = cb.regionAtBlockOffset(cbPageOffset);
3132 boxInfo = cb.renderBoxRegionInfo(cbRegion);
3134 } else if (flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
3135 RenderRegion* containingBlockRegion = cb.clampToStartAndEndRegions(region);
3136 boxInfo = cb.renderBoxRegionInfo(containingBlockRegion);
3138 return (boxInfo) ? std::max<LayoutUnit>(0, cb.clientLogicalWidth() - (cb.logicalWidth() - boxInfo->logicalWidth())) : cb.clientLogicalWidth();
3141 ASSERT(containingBlock->isInFlowPositioned());
3143 const auto& flow = downcast<RenderInline>(*containingBlock);
3144 InlineFlowBox* first = flow.firstLineBox();
3145 InlineFlowBox* last = flow.lastLineBox();
3147 // If the containing block is empty, return a width of 0.
3148 if (!first || !last)
3151 LayoutUnit fromLeft;
3152 LayoutUnit fromRight;
3153 if (containingBlock->style().isLeftToRightDirection()) {
3154 fromLeft = first->logicalLeft() + first->borderLogicalLeft();
3155 fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
3157 fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
3158 fromLeft = last->logicalLeft() + last->borderLogicalLeft();
3161 return std::max<LayoutUnit>(0, fromRight - fromLeft);
3164 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
3166 if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
3167 return containingBlockLogicalWidthForPositioned(containingBlock, nullptr, false);
3169 if (containingBlock->isBox()) {
3170 bool isFixedPosition = style().position() == FixedPosition;
3172 if (isFixedPosition && is<RenderView>(*containingBlock))
3173 return downcast<RenderView>(*containingBlock).clientLogicalHeightForFixedPosition();
3175 const RenderBlock* cb = is<RenderBlock>(*containingBlock) ? downcast<RenderBlock>(containingBlock) : containingBlock->containingBlock();
3176 LayoutUnit result = cb->clientLogicalHeight();
3177 RenderFlowThread* flowThread = flowThreadContainingBlock();
3178 if (flowThread && is<RenderFlowThread>(*containingBlock) && flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
3179 if (is<RenderNamedFlowThread>(*containingBlock) && isFixedPosition)
3180 return containingBlock->view().clientLogicalHeight();
3181 return downcast<RenderFlowThread>(*containingBlock).contentLogicalHeightOfFirstRegion();
3186 ASSERT(containingBlock->isInFlowPositioned());
3188 const auto& flow = downcast<RenderInline>(*containingBlock);
3189 InlineFlowBox* first = flow.firstLineBox();
3190 InlineFlowBox* last = flow.lastLineBox();
3192 // If the containing block is empty, return a height of 0.
3193 if (!first || !last)
3196 LayoutUnit heightResult;
3197 LayoutRect boundingBox = flow.linesBoundingBox();
3198 if (containingBlock->isHorizontalWritingMode())
3199 heightResult = boundingBox.height();
3201 heightResult = boundingBox.width();
3202 heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter());
3203 return heightResult;
3206 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth, RenderRegion* region)
3208 if (!logicalLeft.isAuto() || !logicalRight.isAuto())
3211 // FIXME: The static distance computation has not been patched for mixed writing modes yet.
3212 if (child->parent()->style().direction() == LTR) {
3213 LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock->borderLogicalLeft();
3214 for (auto current = child->parent(); current && current != containerBlock; current = current->container()) {
3215 if (is<RenderBox>(*current)) {
3216 staticPosition += downcast<RenderBox>(*current).logicalLeft();
3217 if (region && is<RenderBlock>(*current)) {
3218 const RenderBlock& currentBlock = downcast<RenderBlock>(*current);
3219 region = currentBlock.clampToStartAndEndRegions(region);
3220 RenderBoxRegionInfo* boxInfo = currentBlock.renderBoxRegionInfo(region);
3222 staticPosition += boxInfo->logicalLeft();
3226 logicalLeft.setValue(Fixed, staticPosition);
3228 RenderBox& enclosingBox = child->parent()->enclosingBox();
3229 LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock->borderLogicalLeft();
3230 for (RenderElement* current = &enclosingBox; current; current = current->container()) {
3231 if (is<RenderBox>(*current)) {
3232 if (current != containerBlock)
3233 staticPosition -= downcast<RenderBox>(*current).logicalLeft();
3234 if (current == &enclosingBox)
3235 staticPosition -= enclosingBox.logicalWidth();
3236 if (region && is<RenderBlock>(*current)) {
3237 const RenderBlock& currentBlock = downcast<RenderBlock>(*current);
3238 region = currentBlock.clampToStartAndEndRegions(region);
3239 RenderBoxRegionInfo* boxInfo = currentBlock.renderBoxRegionInfo(region);
3241 if (current != containerBlock)
3242 staticPosition -= currentBlock.logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth());
3243 if (current == &enclosingBox)
3244 staticPosition += enclosingBox.logicalWidth() - boxInfo->logicalWidth();
3248 if (current == containerBlock)
3251 logicalRight.setValue(Fixed, staticPosition);
3255 void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
3258 // FIXME: Positioned replaced elements inside a flow thread are not working properly
3259 // with variable width regions (see https://bugs.webkit.org/show_bug.cgi?id=69896 ).
3260 computePositionedLogicalWidthReplaced(computedValues);
3265 // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
3266 // the type 'static' in determining whether to calculate the static distance?
3267 // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
3269 // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
3270 // than or less than the computed width(). Be careful of box-sizing and
3271 // percentage issues.
3273 // The following is based off of the W3C Working Draft from April 11, 2006 of
3274 // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
3275 // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
3276 // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
3277 // correspond to text from the spec)
3280 // We don't use containingBlock(), since we may be positioned by an enclosing
3281 // relative positioned inline.
3282 const RenderBoxModelObject* containerBlock = downcast<RenderBoxModelObject>(container());
3284 const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, region);
3286 // Use the container block's direction except when calculating the static distance
3287 // This conforms with the reference results for abspos-replaced-width-margin-000.htm
3288 // of the CSS 2.1 test suite
3289 TextDirection containerDirection = containerBlock->style().direction();
3291 bool isHorizontal = isHorizontalWritingMode();
3292 const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
3293 const Length marginLogicalLeft = isHorizontal ? style().marginLeft() : style().marginTop();
3294 const Length marginLogicalRight = isHorizontal ? style().marginRight() : style().marginBottom();
3296 Length logicalLeftLength = style().logicalLeft();
3297 Length logicalRightLength = style().logicalRight();
3299 /*---------------------------------------------------------------------------*\
3300 * For the purposes of this section and the next, the term "static position"
3301 * (of an element) refers, roughly, to the position an element would have had
3302 * in the normal flow. More precisely:
3304 * * The static position for 'left' is the distance from the left edge of the
3305 * containing block to the left margin edge of a hypothetical box that would
3306 * have been the first box of the element if its 'position' property had
3307 * been 'static' and 'float' had been 'none'. The value is negative if the
3308 * hypothetical box is to the left of the containing block.
3309 * * The static position for 'right' is the distance from the right edge of the
3310 * containing block to the right margin edge of the same hypothetical box as
3311 * above. The value is positive if the hypothetical box is to the left of the
3312 * containing block's edge.
3314 * But rather than actually calculating the dimensions of that hypothetical box,
3315 * user agents are free to make a guess at its probable position.
3317 * For the purposes of calculating the static position, the containing block of
3318 * fixed positioned elements is the initial containing block instead of the
3319 * viewport, and all scrollable boxes should be assumed to be scrolled to their
3321 \*---------------------------------------------------------------------------*/
3324 // Calculate the static distance if needed.
3325 computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth, region);
3327 // Calculate constraint equation values for 'width' case.
3328 computePositionedLogicalWidthUsing(style().logicalWidth(), containerBlock, containerDirection,
3329 containerLogicalWidth, bordersPlusPadding,
3330 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3333 // Calculate constraint equation values for 'max-width' case.
3334 if (!style().logicalMaxWidth().isUndefined()) {
3335 LogicalExtentComputedValues maxValues;