2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
5 * (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
6 * Copyright (C) 2005-2010, 2015 Apple Inc. All rights reserved.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
18 * You should have received a copy of the GNU Library General Public License
19 * along with this library; see the file COPYING.LIB. If not, write to
20 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 * Boston, MA 02110-1301, USA.
26 #include "RenderBox.h"
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 "ScrollAnimator.h"
63 #include "ScrollbarTheme.h"
64 #include "TransformState.h"
65 #include "htmlediting.h"
68 #include <wtf/StackStats.h>
76 struct SameSizeAsRenderBox : public RenderBoxModelObject {
77 virtual ~SameSizeAsRenderBox() { }
79 LayoutBoxExtent marginBox;
80 LayoutUnit preferredLogicalWidths[2];
84 COMPILE_ASSERT(sizeof(RenderBox) == sizeof(SameSizeAsRenderBox), RenderBox_should_stay_small);
86 using namespace HTMLNames;
88 // Used by flexible boxes when flexing this element and by table cells.
89 typedef WTF::HashMap<const RenderBox*, LayoutUnit> OverrideSizeMap;
90 static OverrideSizeMap* gOverrideHeightMap = nullptr;
91 static OverrideSizeMap* gOverrideWidthMap = nullptr;
93 #if ENABLE(CSS_GRID_LAYOUT)
94 // Used by grid elements to properly size their grid items.
95 static OverrideSizeMap* gOverrideContainingBlockLogicalHeightMap = nullptr;
96 static OverrideSizeMap* gOverrideContainingBlockLogicalWidthMap = nullptr;
99 // Size of border belt for autoscroll. When mouse pointer in border belt,
100 // autoscroll is started.
101 static const int autoscrollBeltSize = 20;
102 static const unsigned backgroundObscurationTestMaxDepth = 4;
104 bool RenderBox::s_hadOverflowClip = false;
106 static bool skipBodyBackground(const RenderBox* bodyElementRenderer)
108 ASSERT(bodyElementRenderer->isBody());
109 // The <body> only paints its background if the root element has defined a background independent of the body,
110 // or if the <body>'s parent is not the document element's renderer (e.g. inside SVG foreignObject).
111 auto documentElementRenderer = bodyElementRenderer->document().documentElement()->renderer();
113 if (!documentElementRenderer)
116 if (documentElementRenderer->hasBackground())
119 if (documentElementRenderer != bodyElementRenderer->parent())
122 if (bodyElementRenderer->isComposited() && documentElementRenderer->isComposited())
123 return downcast<RenderLayerModelObject>(documentElementRenderer)->layer()->backing()->graphicsLayer()->drawsContent();
128 RenderBox::RenderBox(Element& element, Ref<RenderStyle>&& style, unsigned baseTypeFlags)
129 : RenderBoxModelObject(element, WTF::move(style), baseTypeFlags)
130 , m_minPreferredLogicalWidth(-1)
131 , m_maxPreferredLogicalWidth(-1)
132 , m_inlineBoxWrapper(nullptr)
137 RenderBox::RenderBox(Document& document, Ref<RenderStyle>&& style, unsigned baseTypeFlags)
138 : RenderBoxModelObject(document, WTF::move(style), baseTypeFlags)
139 , m_minPreferredLogicalWidth(-1)
140 , m_maxPreferredLogicalWidth(-1)
141 , m_inlineBoxWrapper(nullptr)
146 RenderBox::~RenderBox()
148 if (frame().eventHandler().autoscrollRenderer() == this)
149 frame().eventHandler().stopAutoscrollTimer(true);
152 #if ENABLE(CSS_GRID_LAYOUT)
153 clearContainingBlockOverrideSize();
156 RenderBlock::removePercentHeightDescendantIfNeeded(*this);
158 #if ENABLE(CSS_SHAPES)
159 ShapeOutsideInfo::removeInfo(*this);
162 view().unscheduleLazyRepaint(*this);
163 if (hasControlStatesForRenderer(this))
164 removeControlStatesForRenderer(this);
167 RenderRegion* RenderBox::clampToStartAndEndRegions(RenderRegion* region) const
169 RenderFlowThread* flowThread = flowThreadContainingBlock();
171 ASSERT(isRenderView() || (region && flowThread));
175 // We need to clamp to the block, since we want any lines or blocks that overflow out of the
176 // logical top or logical bottom of the block to size as though the border box in the first and
177 // last regions extended infinitely. Otherwise the lines are going to size according to the regions
178 // they overflow into, which makes no sense when this block doesn't exist in |region| at all.
179 RenderRegion* startRegion = nullptr;
180 RenderRegion* endRegion = nullptr;
181 if (!flowThread->getRegionRangeForBox(this, startRegion, endRegion))
184 if (region->logicalTopForFlowThreadContent() < startRegion->logicalTopForFlowThreadContent())
186 if (region->logicalTopForFlowThreadContent() > endRegion->logicalTopForFlowThreadContent())
192 bool RenderBox::hasRegionRangeInFlowThread() const
194 RenderFlowThread* flowThread = flowThreadContainingBlock();
195 if (!flowThread || !flowThread->hasValidRegionInfo())
198 return flowThread->hasCachedRegionRangeForBox(this);
201 LayoutRect RenderBox::clientBoxRectInRegion(RenderRegion* region) const
204 return clientBoxRect();
206 LayoutRect clientBox = borderBoxRectInRegion(region);
207 clientBox.setLocation(clientBox.location() + LayoutSize(borderLeft(), borderTop()));
208 clientBox.setSize(clientBox.size() - LayoutSize(borderLeft() + borderRight() + verticalScrollbarWidth(), borderTop() + borderBottom() + horizontalScrollbarHeight()));
213 LayoutRect RenderBox::borderBoxRectInRegion(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
216 return borderBoxRect();
218 RenderFlowThread* flowThread = flowThreadContainingBlock();
220 return borderBoxRect();
222 RenderRegion* startRegion = nullptr;
223 RenderRegion* endRegion = nullptr;
224 if (!flowThread->getRegionRangeForBox(this, startRegion, endRegion)) {
225 // FIXME: In a perfect world this condition should never happen.
226 return borderBoxRect();
229 ASSERT(flowThread->regionInRange(region, startRegion, endRegion));
231 // Compute the logical width and placement in this region.
232 RenderBoxRegionInfo* boxInfo = renderBoxRegionInfo(region, cacheFlag);
234 return borderBoxRect();
236 // We have cached insets.
237 LayoutUnit logicalWidth = boxInfo->logicalWidth();
238 LayoutUnit logicalLeft = boxInfo->logicalLeft();
240 // Now apply the parent inset since it is cumulative whenever anything in the containing block chain shifts.
241 // FIXME: Doesn't work right with perpendicular writing modes.
242 const RenderBlock* currentBox = containingBlock();
243 RenderBoxRegionInfo* currentBoxInfo = isRenderFlowThread() ? nullptr : currentBox->renderBoxRegionInfo(region);
244 while (currentBoxInfo && currentBoxInfo->isShifted()) {
245 if (currentBox->style().direction() == LTR)
246 logicalLeft += currentBoxInfo->logicalLeft();
248 logicalLeft -= (currentBox->logicalWidth() - currentBoxInfo->logicalWidth()) - currentBoxInfo->logicalLeft();
250 // Once we reach the fragmentation container we should stop.
251 if (currentBox->isRenderFlowThread())
254 currentBox = currentBox->containingBlock();
255 region = currentBox->clampToStartAndEndRegions(region);
256 currentBoxInfo = currentBox->renderBoxRegionInfo(region);
259 if (cacheFlag == DoNotCacheRenderBoxRegionInfo)
262 if (isHorizontalWritingMode())
263 return LayoutRect(logicalLeft, 0, logicalWidth, height());
264 return LayoutRect(0, logicalLeft, width(), logicalWidth);
267 RenderBlockFlow* RenderBox::outermostBlockContainingFloatingObject()
269 ASSERT(isFloating());
270 RenderBlockFlow* parentBlock = nullptr;
271 for (auto& ancestor : ancestorsOfType<RenderBlockFlow>(*this)) {
272 if (ancestor.isRenderView())
274 if (!parentBlock || ancestor.containsFloat(*this))
275 parentBlock = &ancestor;
280 void RenderBox::removeFloatingOrPositionedChildFromBlockLists()
282 ASSERT(isFloatingOrOutOfFlowPositioned());
284 if (documentBeingDestroyed())
288 if (RenderBlockFlow* parentBlock = outermostBlockContainingFloatingObject()) {
289 parentBlock->markSiblingsWithFloatsForLayout(this);
290 parentBlock->markAllDescendantsWithFloatsForLayout(this, false);
294 if (isOutOfFlowPositioned())
295 RenderBlock::removePositionedObject(*this);
298 void RenderBox::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
300 s_hadOverflowClip = hasOverflowClip();
302 const RenderStyle* oldStyle = hasInitializedStyle() ? &style() : nullptr;
304 // The background of the root element or the body element could propagate up to
305 // the canvas. Issue full repaint, when our style changes substantially.
306 if (diff >= StyleDifferenceRepaint && (isRoot() || isBody())) {
307 view().repaintRootContents();
308 if (oldStyle->hasEntirelyFixedBackground() != newStyle.hasEntirelyFixedBackground())
309 view().compositor().rootFixedBackgroundsChanged();
312 // When a layout hint happens and an object's position style changes, we have to do a layout
313 // to dirty the render tree using the old position value now.
314 if (diff == StyleDifferenceLayout && parent() && oldStyle->position() != newStyle.position()) {
315 markContainingBlocksForLayout();
316 if (oldStyle->position() == StaticPosition)
318 else if (newStyle.hasOutOfFlowPosition())
319 parent()->setChildNeedsLayout();
320 if (isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition())
321 removeFloatingOrPositionedChildFromBlockLists();
324 view().repaintRootContents();
326 RenderBoxModelObject::styleWillChange(diff, newStyle);
329 void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
331 // Horizontal writing mode definition is updated in RenderBoxModelObject::updateFromStyle,
332 // (as part of the RenderBoxModelObject::styleDidChange call below). So, we can safely cache the horizontal
333 // writing mode value before style change here.
334 bool oldHorizontalWritingMode = isHorizontalWritingMode();
336 RenderBoxModelObject::styleDidChange(diff, oldStyle);
338 const RenderStyle& newStyle = style();
339 if (needsLayout() && oldStyle) {
340 RenderBlock::removePercentHeightDescendantIfNeeded(*this);
342 // Normally we can do optimized positioning layout for absolute/fixed positioned objects. There is one special case, however, which is
343 // 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
344 // to determine the new static position.
345 if (isOutOfFlowPositioned() && newStyle.hasStaticBlockPosition(isHorizontalWritingMode()) && oldStyle->marginBefore() != newStyle.marginBefore()
346 && parent() && !parent()->normalChildNeedsLayout())
347 parent()->setChildNeedsLayout();
350 if (RenderBlock::hasPercentHeightContainerMap() && firstChild()
351 && oldHorizontalWritingMode != isHorizontalWritingMode())
352 RenderBlock::clearPercentHeightDescendantsFrom(*this);
354 // If our zoom factor changes and we have a defined scrollLeft/Top, we need to adjust that value into the
355 // new zoomed coordinate space.
356 if (hasOverflowClip() && oldStyle && oldStyle->effectiveZoom() != newStyle.effectiveZoom()) {
357 if (int left = layer()->scrollXOffset()) {
358 left = (left / oldStyle->effectiveZoom()) * newStyle.effectiveZoom();
359 layer()->scrollToXOffset(left);
361 if (int top = layer()->scrollYOffset()) {
362 top = (top / oldStyle->effectiveZoom()) * newStyle.effectiveZoom();
363 layer()->scrollToYOffset(top);
367 // Our opaqueness might have changed without triggering layout.
368 if (diff >= StyleDifferenceRepaint && diff <= StyleDifferenceRepaintLayer) {
369 auto parentToInvalidate = parent();
370 for (unsigned i = 0; i < backgroundObscurationTestMaxDepth && parentToInvalidate; ++i) {
371 parentToInvalidate->invalidateBackgroundObscurationStatus();
372 parentToInvalidate = parentToInvalidate->parent();
376 bool isBodyRenderer = isBody();
377 bool isRootRenderer = isRoot();
379 // Set the text color if we're the body.
381 document().setTextColor(newStyle.visitedDependentColor(CSSPropertyColor));
383 if (isRootRenderer || isBodyRenderer) {
384 // Propagate the new writing mode and direction up to the RenderView.
385 RenderStyle& viewStyle = view().style();
386 bool viewChangedWritingMode = false;
387 bool rootStyleChanged = false;
388 bool viewStyleChanged = false;
389 RenderObject* rootRenderer = isBodyRenderer ? document().documentElement()->renderer() : nullptr;
390 if (viewStyle.direction() != newStyle.direction() && (isRootRenderer || !document().directionSetOnDocumentElement())) {
391 viewStyle.setDirection(newStyle.direction());
392 viewStyleChanged = true;
393 if (isBodyRenderer) {
394 rootRenderer->style().setDirection(newStyle.direction());
395 rootStyleChanged = true;
397 setNeedsLayoutAndPrefWidthsRecalc();
400 if (viewStyle.writingMode() != newStyle.writingMode() && (isRootRenderer || !document().writingModeSetOnDocumentElement())) {
401 viewStyle.setWritingMode(newStyle.writingMode());
402 viewChangedWritingMode = true;
403 viewStyleChanged = true;
404 view().setHorizontalWritingMode(newStyle.isHorizontalWritingMode());
405 view().markAllDescendantsWithFloatsForLayout();
406 if (isBodyRenderer) {
407 rootStyleChanged = true;
408 rootRenderer->style().setWritingMode(newStyle.writingMode());
409 rootRenderer->setHorizontalWritingMode(newStyle.isHorizontalWritingMode());
411 setNeedsLayoutAndPrefWidthsRecalc();
414 view().frameView().recalculateScrollbarOverlayStyle();
416 const Pagination& pagination = view().frameView().pagination();
417 if (viewChangedWritingMode && pagination.mode != Pagination::Unpaginated) {
418 viewStyle.setColumnStylesFromPaginationMode(pagination.mode);
419 if (view().multiColumnFlowThread())
420 view().updateColumnProgressionFromStyle(viewStyle);
423 if (viewStyleChanged && view().multiColumnFlowThread())
424 view().updateStylesForColumnChildren();
426 if (rootStyleChanged && is<RenderBlockFlow>(rootRenderer) && downcast<RenderBlockFlow>(*rootRenderer).multiColumnFlowThread())
427 downcast<RenderBlockFlow>(*rootRenderer).updateStylesForColumnChildren();
429 if (diff != StyleDifferenceEqual)
430 view().compositor().rootBackgroundTransparencyChanged();
433 #if ENABLE(CSS_SHAPES)
434 if ((oldStyle && oldStyle->shapeOutside()) || style().shapeOutside())
435 updateShapeOutsideInfoAfterStyleChange(style(), oldStyle);
439 #if ENABLE(CSS_SHAPES)
440 void RenderBox::updateShapeOutsideInfoAfterStyleChange(const RenderStyle& style, const RenderStyle* oldStyle)
442 const ShapeValue* shapeOutside = style.shapeOutside();
443 const ShapeValue* oldShapeOutside = oldStyle ? oldStyle->shapeOutside() : nullptr;
445 Length shapeMargin = style.shapeMargin();
446 Length oldShapeMargin = oldStyle ? oldStyle->shapeMargin() : RenderStyle::initialShapeMargin();
448 float shapeImageThreshold = style.shapeImageThreshold();
449 float oldShapeImageThreshold = oldStyle ? oldStyle->shapeImageThreshold() : RenderStyle::initialShapeImageThreshold();
451 // FIXME: A future optimization would do a deep comparison for equality. (bug 100811)
452 if (shapeOutside == oldShapeOutside && shapeMargin == oldShapeMargin && shapeImageThreshold == oldShapeImageThreshold)
456 ShapeOutsideInfo::removeInfo(*this);
458 ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
460 if (shapeOutside || shapeOutside != oldShapeOutside)
461 markShapeOutsideDependentsForLayout();
465 void RenderBox::updateFromStyle()
467 RenderBoxModelObject::updateFromStyle();
469 const RenderStyle& styleToUse = style();
470 bool isRootObject = isRoot();
471 bool isViewObject = isRenderView();
473 // The root and the RenderView always paint their backgrounds/borders.
474 if (isRootObject || isViewObject)
475 setHasBoxDecorations(true);
477 setFloating(!isOutOfFlowPositioned() && styleToUse.isFloating());
479 // We also handle <body> and <html>, whose overflow applies to the viewport.
480 if (styleToUse.overflowX() != OVISIBLE && !isRootObject && isRenderBlock()) {
481 bool boxHasOverflowClip = true;
483 // Overflow on the body can propagate to the viewport under the following conditions.
484 // (1) The root element is <html>.
485 // (2) We are the primary <body> (can be checked by looking at document.body).
486 // (3) The root element has visible overflow.
487 if (is<HTMLHtmlElement>(*document().documentElement())
488 && document().body() == element()
489 && document().documentElement()->renderer()->style().overflowX() == OVISIBLE) {
490 boxHasOverflowClip = false;
494 // Check for overflow clip.
495 // It's sufficient to just check one direction, since it's illegal to have visible on only one overflow value.
496 if (boxHasOverflowClip) {
497 if (!s_hadOverflowClip)
498 // Erase the overflow
500 setHasOverflowClip();
504 setHasTransformRelatedProperty(styleToUse.hasTransformRelatedProperty());
505 setHasReflection(styleToUse.boxReflect());
508 void RenderBox::layout()
510 StackStats::LayoutCheckPoint layoutCheckPoint;
511 ASSERT(needsLayout());
513 RenderObject* child = firstChild();
519 LayoutStateMaintainer statePusher(view(), *this, locationOffset(), style().isFlippedBlocksWritingMode());
521 if (child->needsLayout())
522 downcast<RenderElement>(*child).layout();
523 ASSERT(!child->needsLayout());
524 child = child->nextSibling();
527 invalidateBackgroundObscurationStatus();
531 // More IE extensions. clientWidth and clientHeight represent the interior of an object
532 // excluding border and scrollbar.
533 LayoutUnit RenderBox::clientWidth() const
535 return width() - borderLeft() - borderRight() - verticalScrollbarWidth();
538 LayoutUnit RenderBox::clientHeight() const
540 return height() - borderTop() - borderBottom() - horizontalScrollbarHeight();
543 int RenderBox::pixelSnappedClientWidth() const
545 // FIXME: This should use snappedIntSize() instead with absolute coordinates.
546 return roundToInt(clientWidth());
549 int RenderBox::pixelSnappedClientHeight() const
551 // FIXME: This should use snappedIntSize() instead with absolute coordinates.
552 return roundToInt(clientHeight());
555 int RenderBox::pixelSnappedOffsetWidth() const
557 // FIXME: This should use snappedIntSize() instead with absolute coordinates.
558 return roundToInt(offsetWidth());
561 int RenderBox::pixelSnappedOffsetHeight() const
563 // FIXME: This should use snappedIntSize() instead with absolute coordinates.
564 return roundToInt(offsetHeight());
567 int RenderBox::scrollWidth() const
569 if (hasOverflowClip())
570 return layer()->scrollWidth();
571 // For objects with visible overflow, this matches IE.
572 // FIXME: Need to work right with writing modes.
573 if (style().isLeftToRightDirection()) {
574 // FIXME: This should use snappedIntSize() instead with absolute coordinates.
575 return roundToInt(std::max(clientWidth(), layoutOverflowRect().maxX() - borderLeft()));
577 return clientWidth() - std::min<LayoutUnit>(0, layoutOverflowRect().x() - borderLeft());
580 int RenderBox::scrollHeight() const
582 if (hasOverflowClip())
583 return layer()->scrollHeight();
584 // For objects with visible overflow, this matches IE.
585 // FIXME: Need to work right with writing modes.
586 // FIXME: This should use snappedIntSize() instead with absolute coordinates.
587 return roundToInt(std::max(clientHeight(), layoutOverflowRect().maxY() - borderTop()));
590 int RenderBox::scrollLeft() const
592 return hasOverflowClip() ? layer()->scrollXOffset() : 0;
595 int RenderBox::scrollTop() const
597 return hasOverflowClip() ? layer()->scrollYOffset() : 0;
600 static void setupWheelEventTestTrigger(RenderLayer& layer, Frame* frame)
605 Page* page = frame->page();
606 if (!page || !page->expectsWheelEventTriggers())
609 layer.scrollAnimator().setWheelEventTestTrigger(page->testTrigger());
612 void RenderBox::setScrollLeft(int newLeft)
614 if (hasOverflowClip()) {
615 setupWheelEventTestTrigger(*layer(), document().frame());
616 layer()->scrollToXOffset(newLeft, RenderLayer::ScrollOffsetClamped);
620 void RenderBox::setScrollTop(int newTop)
622 if (hasOverflowClip()) {
623 setupWheelEventTestTrigger(*layer(), document().frame());
624 layer()->scrollToYOffset(newTop, RenderLayer::ScrollOffsetClamped);
628 void RenderBox::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
630 rects.append(snappedIntRect(accumulatedOffset, size()));
633 void RenderBox::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
635 FloatRect localRect(0, 0, width(), height());
637 RenderFlowThread* flowThread = flowThreadContainingBlock();
638 if (flowThread && flowThread->absoluteQuadsForBox(quads, wasFixed, this, localRect.y(), localRect.maxY()))
641 quads.append(localToAbsoluteQuad(localRect, UseTransforms, wasFixed));
644 void RenderBox::updateLayerTransform()
646 // Transform-origin depends on box size, so we need to update the layer transform after layout.
648 layer()->updateTransform();
651 LayoutUnit RenderBox::constrainLogicalWidthInRegionByMinMax(LayoutUnit logicalWidth, LayoutUnit availableWidth, RenderBlock* cb, RenderRegion* region) const
653 const RenderStyle& styleToUse = style();
654 if (!styleToUse.logicalMaxWidth().isUndefined())
655 logicalWidth = std::min(logicalWidth, computeLogicalWidthInRegionUsing(MaxSize, styleToUse.logicalMaxWidth(), availableWidth, cb, region));
656 return std::max(logicalWidth, computeLogicalWidthInRegionUsing(MinSize, styleToUse.logicalMinWidth(), availableWidth, cb, region));
659 LayoutUnit RenderBox::constrainLogicalHeightByMinMax(LayoutUnit logicalHeight) const
661 const RenderStyle& styleToUse = style();
662 if (!styleToUse.logicalMaxHeight().isUndefined()) {
663 LayoutUnit maxH = computeLogicalHeightUsing(styleToUse.logicalMaxHeight());
665 logicalHeight = std::min(logicalHeight, maxH);
667 return std::max(logicalHeight, computeLogicalHeightUsing(styleToUse.logicalMinHeight()));
670 LayoutUnit RenderBox::constrainContentBoxLogicalHeightByMinMax(LayoutUnit logicalHeight) const
672 const RenderStyle& styleToUse = style();
673 if (!styleToUse.logicalMaxHeight().isUndefined()) {
674 LayoutUnit maxH = computeContentLogicalHeight(styleToUse.logicalMaxHeight());
676 logicalHeight = std::min(logicalHeight, maxH);
678 return std::max(logicalHeight, computeContentLogicalHeight(styleToUse.logicalMinHeight()));
681 RoundedRect::Radii RenderBox::borderRadii() const
683 RenderStyle& style = this->style();
684 LayoutRect bounds = frameRect();
686 unsigned borderLeft = style.borderLeftWidth();
687 unsigned borderTop = style.borderTopWidth();
688 bounds.moveBy(LayoutPoint(borderLeft, borderTop));
689 bounds.contract(borderLeft + style.borderRightWidth(), borderTop + style.borderBottomWidth());
690 return style.getRoundedBorderFor(bounds).radii();
693 IntRect RenderBox::absoluteContentBox() const
695 // This is wrong with transforms and flipped writing modes.
696 IntRect rect = snappedIntRect(contentBoxRect());
697 FloatPoint absPos = localToAbsolute();
698 rect.move(absPos.x(), absPos.y());
702 FloatQuad RenderBox::absoluteContentQuad() const
704 LayoutRect rect = contentBoxRect();
705 return localToAbsoluteQuad(FloatRect(rect));
708 LayoutRect RenderBox::outlineBoundsForRepaint(const RenderLayerModelObject* repaintContainer, const RenderGeometryMap* geometryMap) const
710 LayoutRect box = borderBoundingBox();
711 adjustRectForOutlineAndShadow(box);
713 if (repaintContainer != this) {
714 FloatQuad containerRelativeQuad;
716 containerRelativeQuad = geometryMap->mapToContainer(box, repaintContainer);
718 containerRelativeQuad = localToContainerQuad(FloatRect(box), repaintContainer);
720 box = LayoutRect(containerRelativeQuad.boundingBox());
723 // FIXME: layoutDelta needs to be applied in parts before/after transforms and
724 // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
725 box.move(view().layoutDelta());
727 return LayoutRect(snapRectToDevicePixels(box, document().deviceScaleFactor()));
730 void RenderBox::addFocusRingRects(Vector<IntRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject*)
732 if (!size().isEmpty())
733 rects.append(snappedIntRect(additionalOffset, size()));
736 int RenderBox::reflectionOffset() const
738 if (!style().boxReflect())
740 if (style().boxReflect()->direction() == ReflectionLeft || style().boxReflect()->direction() == ReflectionRight)
741 return valueForLength(style().boxReflect()->offset(), borderBoxRect().width());
742 return valueForLength(style().boxReflect()->offset(), borderBoxRect().height());
745 LayoutRect RenderBox::reflectedRect(const LayoutRect& r) const
747 if (!style().boxReflect())
750 LayoutRect box = borderBoxRect();
751 LayoutRect result = r;
752 switch (style().boxReflect()->direction()) {
753 case ReflectionBelow:
754 result.setY(box.maxY() + reflectionOffset() + (box.maxY() - r.maxY()));
756 case ReflectionAbove:
757 result.setY(box.y() - reflectionOffset() - box.height() + (box.maxY() - r.maxY()));
760 result.setX(box.x() - reflectionOffset() - box.width() + (box.maxX() - r.maxX()));
762 case ReflectionRight:
763 result.setX(box.maxX() + reflectionOffset() + (box.maxX() - r.maxX()));
769 bool RenderBox::fixedElementLaysOutRelativeToFrame(const FrameView& frameView) const
771 return style().position() == FixedPosition && container()->isRenderView() && frameView.fixedElementsLayoutRelativeToFrame();
774 bool RenderBox::includeVerticalScrollbarSize() const
776 return hasOverflowClip() && !layer()->hasOverlayScrollbars()
777 && (style().overflowY() == OSCROLL || style().overflowY() == OAUTO);
780 bool RenderBox::includeHorizontalScrollbarSize() const
782 return hasOverflowClip() && !layer()->hasOverlayScrollbars()
783 && (style().overflowX() == OSCROLL || style().overflowX() == OAUTO);
786 int RenderBox::verticalScrollbarWidth() const
788 return includeVerticalScrollbarSize() ? layer()->verticalScrollbarWidth() : 0;
791 int RenderBox::horizontalScrollbarHeight() const
793 return includeHorizontalScrollbarSize() ? layer()->horizontalScrollbarHeight() : 0;
796 int RenderBox::intrinsicScrollbarLogicalWidth() const
798 if (!hasOverflowClip())
801 if (isHorizontalWritingMode() && (style().overflowY() == OSCROLL && !hasVerticalScrollbarWithAutoBehavior())) {
802 ASSERT(layer()->hasVerticalScrollbar());
803 return verticalScrollbarWidth();
806 if (!isHorizontalWritingMode() && (style().overflowX() == OSCROLL && !hasHorizontalScrollbarWithAutoBehavior())) {
807 ASSERT(layer()->hasHorizontalScrollbar());
808 return horizontalScrollbarHeight();
814 bool RenderBox::scrollLayer(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement)
816 RenderLayer* boxLayer = layer();
817 if (boxLayer && boxLayer->scroll(direction, granularity, multiplier)) {
819 *stopElement = element();
827 bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement, RenderBox* startBox, const IntPoint& wheelEventAbsolutePoint)
829 if (scrollLayer(direction, granularity, multiplier, stopElement))
832 if (stopElement && *stopElement && *stopElement == element())
835 RenderBlock* nextScrollBlock = containingBlock();
836 if (is<RenderNamedFlowThread>(nextScrollBlock)) {
838 nextScrollBlock = downcast<RenderNamedFlowThread>(*nextScrollBlock).fragmentFromAbsolutePointAndBox(wheelEventAbsolutePoint, *startBox);
841 if (nextScrollBlock && !nextScrollBlock->isRenderView())
842 return nextScrollBlock->scroll(direction, granularity, multiplier, stopElement, startBox, wheelEventAbsolutePoint);
847 bool RenderBox::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement)
849 bool scrolled = false;
851 RenderLayer* l = layer();
854 // On Mac only we reset the inline direction position when doing a document scroll (e.g., hitting Home/End).
855 if (granularity == ScrollByDocument)
856 scrolled = l->scroll(logicalToPhysical(ScrollInlineDirectionBackward, isHorizontalWritingMode(), style().isFlippedBlocksWritingMode()), ScrollByDocument, multiplier);
858 if (l->scroll(logicalToPhysical(direction, isHorizontalWritingMode(), style().isFlippedBlocksWritingMode()), granularity, multiplier))
863 *stopElement = element();
868 if (stopElement && *stopElement && *stopElement == element())
871 RenderBlock* b = containingBlock();
872 if (b && !b->isRenderView())
873 return b->logicalScroll(direction, granularity, multiplier, stopElement);
877 bool RenderBox::canBeScrolledAndHasScrollableArea() const
879 return canBeProgramaticallyScrolled() && (scrollHeight() != clientHeight() || scrollWidth() != clientWidth());
882 bool RenderBox::isScrollableOrRubberbandableBox() const
884 return canBeScrolledAndHasScrollableArea();
887 bool RenderBox::canBeProgramaticallyScrolled() const
892 if (!hasOverflowClip())
895 bool hasScrollableOverflow = hasScrollableOverflowX() || hasScrollableOverflowY();
896 if (scrollsOverflow() && hasScrollableOverflow)
899 return element() && element()->hasEditableStyle();
902 bool RenderBox::usesCompositedScrolling() const
904 return hasOverflowClip() && hasLayer() && layer()->usesCompositedScrolling();
907 void RenderBox::autoscroll(const IntPoint& position)
910 layer()->autoscroll(position);
913 // There are two kinds of renderer that can autoscroll.
914 bool RenderBox::canAutoscroll() const
917 return view().frameView().isScrollable();
919 // Check for a box that can be scrolled in its own right.
920 if (canBeScrolledAndHasScrollableArea())
926 // If specified point is in border belt, returned offset denotes direction of
928 IntSize RenderBox::calculateAutoscrollDirection(const IntPoint& windowPoint) const
930 IntRect box(absoluteBoundingBoxRect());
931 box.move(view().frameView().scrollOffset());
932 IntRect windowBox = view().frameView().contentsToWindow(box);
934 IntPoint windowAutoscrollPoint = windowPoint;
936 if (windowAutoscrollPoint.x() < windowBox.x() + autoscrollBeltSize)
937 windowAutoscrollPoint.move(-autoscrollBeltSize, 0);
938 else if (windowAutoscrollPoint.x() > windowBox.maxX() - autoscrollBeltSize)
939 windowAutoscrollPoint.move(autoscrollBeltSize, 0);
941 if (windowAutoscrollPoint.y() < windowBox.y() + autoscrollBeltSize)
942 windowAutoscrollPoint.move(0, -autoscrollBeltSize);
943 else if (windowAutoscrollPoint.y() > windowBox.maxY() - autoscrollBeltSize)
944 windowAutoscrollPoint.move(0, autoscrollBeltSize);
946 return windowAutoscrollPoint - windowPoint;
949 RenderBox* RenderBox::findAutoscrollable(RenderObject* renderer)
951 while (renderer && !(is<RenderBox>(*renderer) && downcast<RenderBox>(*renderer).canAutoscroll())) {
952 if (is<RenderView>(*renderer) && renderer->document().ownerElement())
953 renderer = renderer->document().ownerElement()->renderer();
955 renderer = renderer->parent();
958 return is<RenderBox>(renderer) ? downcast<RenderBox>(renderer) : nullptr;
961 void RenderBox::panScroll(const IntPoint& source)
964 layer()->panScrollFromPoint(source);
967 bool RenderBox::hasVerticalScrollbarWithAutoBehavior() const
969 bool overflowScrollActsLikeAuto = style().overflowY() == OSCROLL && !style().hasPseudoStyle(SCROLLBAR) && ScrollbarTheme::theme()->usesOverlayScrollbars();
970 return hasOverflowClip() && (style().overflowY() == OAUTO || style().overflowY() == OOVERLAY || overflowScrollActsLikeAuto);
973 bool RenderBox::hasHorizontalScrollbarWithAutoBehavior() const
975 bool overflowScrollActsLikeAuto = style().overflowX() == OSCROLL && !style().hasPseudoStyle(SCROLLBAR) && ScrollbarTheme::theme()->usesOverlayScrollbars();
976 return hasOverflowClip() && (style().overflowX() == OAUTO || style().overflowX() == OOVERLAY || overflowScrollActsLikeAuto);
979 bool RenderBox::needsPreferredWidthsRecalculation() const
981 return style().paddingStart().isPercentOrCalculated() || style().paddingEnd().isPercentOrCalculated();
984 IntSize RenderBox::scrolledContentOffset() const
986 if (!hasOverflowClip())
990 return layer()->scrolledContentOffset();
993 LayoutSize RenderBox::cachedSizeForOverflowClip() const
995 ASSERT(hasOverflowClip());
997 return layer()->size();
1000 void RenderBox::applyCachedClipAndScrollOffsetForRepaint(LayoutRect& paintRect) const
1002 flipForWritingMode(paintRect);
1003 paintRect.move(-scrolledContentOffset()); // For overflow:auto/scroll/hidden.
1005 // Do not clip scroll layer contents to reduce the number of repaints while scrolling.
1006 if (usesCompositedScrolling()) {
1007 flipForWritingMode(paintRect);
1011 // height() is inaccurate if we're in the middle of a layout of this RenderBox, so use the
1012 // layer's size instead. Even if the layer's size is wrong, the layer itself will repaint
1013 // anyway if its size does change.
1014 LayoutRect clipRect(LayoutPoint(), cachedSizeForOverflowClip());
1015 paintRect = intersection(paintRect, clipRect);
1016 flipForWritingMode(paintRect);
1019 void RenderBox::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
1021 minLogicalWidth = minPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
1022 maxLogicalWidth = maxPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
1025 LayoutUnit RenderBox::minPreferredLogicalWidth() const
1027 if (preferredLogicalWidthsDirty()) {
1029 SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox*>(this));
1031 const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
1034 return m_minPreferredLogicalWidth;
1037 LayoutUnit RenderBox::maxPreferredLogicalWidth() const
1039 if (preferredLogicalWidthsDirty()) {
1041 SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox*>(this));
1043 const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
1046 return m_maxPreferredLogicalWidth;
1049 bool RenderBox::hasOverrideLogicalContentHeight() const
1051 return gOverrideHeightMap && gOverrideHeightMap->contains(this);
1054 bool RenderBox::hasOverrideLogicalContentWidth() const
1056 return gOverrideWidthMap && gOverrideWidthMap->contains(this);
1059 void RenderBox::setOverrideLogicalContentHeight(LayoutUnit height)
1061 if (!gOverrideHeightMap)
1062 gOverrideHeightMap = new OverrideSizeMap();
1063 gOverrideHeightMap->set(this, height);
1066 void RenderBox::setOverrideLogicalContentWidth(LayoutUnit width)
1068 if (!gOverrideWidthMap)
1069 gOverrideWidthMap = new OverrideSizeMap();
1070 gOverrideWidthMap->set(this, width);
1073 void RenderBox::clearOverrideLogicalContentHeight()
1075 if (gOverrideHeightMap)
1076 gOverrideHeightMap->remove(this);
1079 void RenderBox::clearOverrideLogicalContentWidth()
1081 if (gOverrideWidthMap)
1082 gOverrideWidthMap->remove(this);
1085 void RenderBox::clearOverrideSize()
1087 clearOverrideLogicalContentHeight();
1088 clearOverrideLogicalContentWidth();
1091 LayoutUnit RenderBox::overrideLogicalContentWidth() const
1093 ASSERT(hasOverrideLogicalContentWidth());
1094 return gOverrideWidthMap->get(this);
1097 LayoutUnit RenderBox::overrideLogicalContentHeight() const
1099 ASSERT(hasOverrideLogicalContentHeight());
1100 return gOverrideHeightMap->get(this);
1103 #if ENABLE(CSS_GRID_LAYOUT)
1104 LayoutUnit RenderBox::overrideContainingBlockContentLogicalWidth() const
1106 ASSERT(hasOverrideContainingBlockLogicalWidth());
1107 return gOverrideContainingBlockLogicalWidthMap->get(this);
1110 LayoutUnit RenderBox::overrideContainingBlockContentLogicalHeight() const
1112 ASSERT(hasOverrideContainingBlockLogicalHeight());
1113 return gOverrideContainingBlockLogicalHeightMap->get(this);
1116 bool RenderBox::hasOverrideContainingBlockLogicalWidth() const
1118 return gOverrideContainingBlockLogicalWidthMap && gOverrideContainingBlockLogicalWidthMap->contains(this);
1121 bool RenderBox::hasOverrideContainingBlockLogicalHeight() const
1123 return gOverrideContainingBlockLogicalHeightMap && gOverrideContainingBlockLogicalHeightMap->contains(this);
1126 void RenderBox::setOverrideContainingBlockContentLogicalWidth(LayoutUnit logicalWidth)
1128 if (!gOverrideContainingBlockLogicalWidthMap)
1129 gOverrideContainingBlockLogicalWidthMap = new OverrideSizeMap;
1130 gOverrideContainingBlockLogicalWidthMap->set(this, logicalWidth);
1133 void RenderBox::setOverrideContainingBlockContentLogicalHeight(LayoutUnit logicalHeight)
1135 if (!gOverrideContainingBlockLogicalHeightMap)
1136 gOverrideContainingBlockLogicalHeightMap = new OverrideSizeMap;
1137 gOverrideContainingBlockLogicalHeightMap->set(this, logicalHeight);
1140 void RenderBox::clearContainingBlockOverrideSize()
1142 if (gOverrideContainingBlockLogicalWidthMap)
1143 gOverrideContainingBlockLogicalWidthMap->remove(this);
1144 clearOverrideContainingBlockContentLogicalHeight();
1147 void RenderBox::clearOverrideContainingBlockContentLogicalHeight()
1149 if (gOverrideContainingBlockLogicalHeightMap)
1150 gOverrideContainingBlockLogicalHeightMap->remove(this);
1152 #endif // ENABLE(CSS_GRID_LAYOUT)
1154 LayoutUnit RenderBox::adjustBorderBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1156 LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
1157 if (style().boxSizing() == CONTENT_BOX)
1158 return width + bordersPlusPadding;
1159 return std::max(width, bordersPlusPadding);
1162 LayoutUnit RenderBox::adjustBorderBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1164 LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
1165 if (style().boxSizing() == CONTENT_BOX)
1166 return height + bordersPlusPadding;
1167 return std::max(height, bordersPlusPadding);
1170 LayoutUnit RenderBox::adjustContentBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1172 if (style().boxSizing() == BORDER_BOX)
1173 width -= borderAndPaddingLogicalWidth();
1174 return std::max<LayoutUnit>(0, width);
1177 LayoutUnit RenderBox::adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1179 if (style().boxSizing() == BORDER_BOX)
1180 height -= borderAndPaddingLogicalHeight();
1181 return std::max<LayoutUnit>(0, height);
1185 bool RenderBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
1187 LayoutPoint adjustedLocation = accumulatedOffset + location();
1189 // Check kids first.
1190 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
1191 if (!child->hasLayer() && child->nodeAtPoint(request, result, locationInContainer, adjustedLocation, action)) {
1192 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1197 RenderFlowThread* flowThread = flowThreadContainingBlock();
1198 RenderRegion* regionToUse = flowThread ? downcast<RenderNamedFlowFragment>(flowThread->currentRegion()) : nullptr;
1200 // If the box is not contained by this region there's no point in going further.
1201 if (regionToUse && !flowThread->objectShouldFragmentInFlowRegion(this, regionToUse))
1204 // Check our bounds next. For this purpose always assume that we can only be hit in the
1205 // foreground phase (which is true for replaced elements like images).
1206 LayoutRect boundsRect = borderBoxRectInRegion(regionToUse);
1207 boundsRect.moveBy(adjustedLocation);
1208 if (visibleToHitTesting() && action == HitTestForeground && locationInContainer.intersects(boundsRect)) {
1209 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1210 if (!result.addNodeToRectBasedTestResult(element(), request, locationInContainer, boundsRect))
1217 // --------------------- painting stuff -------------------------------
1219 void RenderBox::paintRootBoxFillLayers(const PaintInfo& paintInfo)
1221 if (paintInfo.skipRootBackground())
1224 auto& rootBackgroundRenderer = rendererForRootBackground();
1226 const FillLayer* bgLayer = rootBackgroundRenderer.style().backgroundLayers();
1227 Color bgColor = rootBackgroundRenderer.style().visitedDependentColor(CSSPropertyBackgroundColor);
1229 paintFillLayers(paintInfo, bgColor, bgLayer, view().backgroundRect(this), BackgroundBleedNone, CompositeSourceOver, &rootBackgroundRenderer);
1232 BackgroundBleedAvoidance RenderBox::determineBackgroundBleedAvoidance(GraphicsContext* context) const
1234 if (context->paintingDisabled())
1235 return BackgroundBleedNone;
1237 const RenderStyle& style = this->style();
1239 if (!style.hasBackground() || !style.hasBorder() || !style.hasBorderRadius() || borderImageIsLoadedAndCanBeRendered())
1240 return BackgroundBleedNone;
1242 AffineTransform ctm = context->getCTM();
1243 FloatSize contextScaling(static_cast<float>(ctm.xScale()), static_cast<float>(ctm.yScale()));
1245 // Because RoundedRect uses IntRect internally the inset applied by the
1246 // BackgroundBleedShrinkBackground strategy cannot be less than one integer
1247 // layout coordinate, even with subpixel layout enabled. To take that into
1248 // account, we clamp the contextScaling to 1.0 for the following test so
1249 // that borderObscuresBackgroundEdge can only return true if the border
1250 // widths are greater than 2 in both layout coordinates and screen
1252 // This precaution will become obsolete if RoundedRect is ever promoted to
1253 // a sub-pixel representation.
1254 if (contextScaling.width() > 1)
1255 contextScaling.setWidth(1);
1256 if (contextScaling.height() > 1)
1257 contextScaling.setHeight(1);
1259 if (borderObscuresBackgroundEdge(contextScaling))
1260 return BackgroundBleedShrinkBackground;
1261 if (!style.hasAppearance() && borderObscuresBackground() && backgroundHasOpaqueTopLayer())
1262 return BackgroundBleedBackgroundOverBorder;
1264 return BackgroundBleedUseTransparencyLayer;
1267 void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1269 if (!paintInfo.shouldPaintWithinRoot(*this))
1272 LayoutRect paintRect = borderBoxRectInRegion(currentRenderNamedFlowFragment());
1273 paintRect.moveBy(paintOffset);
1276 // Workaround for <rdar://problem/6209763>. Force the painting bounds of checkboxes and radio controls to be square.
1277 if (style().appearance() == CheckboxPart || style().appearance() == RadioPart) {
1278 int width = std::min(paintRect.width(), paintRect.height());
1280 paintRect = IntRect(paintRect.x(), paintRect.y() + (this->height() - height) / 2, width, height); // Vertically center the checkbox, like on desktop
1283 BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context);
1285 // FIXME: Should eventually give the theme control over whether the box shadow should paint, since controls could have
1286 // custom shadows of their own.
1287 if (!boxShadowShouldBeAppliedToBackground(bleedAvoidance))
1288 paintBoxShadow(paintInfo, paintRect, style(), Normal);
1290 GraphicsContextStateSaver stateSaver(*paintInfo.context, false);
1291 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
1292 // To avoid the background color bleeding out behind the border, we'll render background and border
1293 // into a transparency layer, and then clip that in one go (which requires setting up the clip before
1294 // beginning the layer).
1296 paintInfo.context->clipRoundedRect(style().getRoundedBorderFor(paintRect).pixelSnappedRoundedRectForPainting(document().deviceScaleFactor()));
1297 paintInfo.context->beginTransparencyLayer(1);
1300 // If we have a native theme appearance, paint that before painting our background.
1301 // The theme will tell us whether or not we should also paint the CSS background.
1302 ControlStates* controlStates = nullptr;
1303 if (style().hasAppearance()) {
1304 if (hasControlStatesForRenderer(this))
1305 controlStates = controlStatesForRenderer(this);
1307 controlStates = new ControlStates();
1308 addControlStatesForRenderer(this, controlStates);
1312 bool themePainted = style().hasAppearance() && !theme().paint(*this, controlStates, paintInfo, paintRect);
1314 if (controlStates && controlStates->needsRepaint())
1315 view().scheduleLazyRepaint(*this);
1317 if (!themePainted) {
1318 if (bleedAvoidance == BackgroundBleedBackgroundOverBorder)
1319 paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1321 paintBackground(paintInfo, paintRect, bleedAvoidance);
1323 if (style().hasAppearance())
1324 theme().paintDecorations(*this, paintInfo, paintRect);
1326 paintBoxShadow(paintInfo, paintRect, style(), Inset);
1328 // The theme will tell us whether or not we should also paint the CSS border.
1329 if (bleedAvoidance != BackgroundBleedBackgroundOverBorder && (!style().hasAppearance() || (!themePainted && theme().paintBorderOnly(*this, paintInfo, paintRect))) && style().hasBorderDecoration())
1330 paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1332 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer)
1333 paintInfo.context->endTransparencyLayer();
1336 void RenderBox::paintBackground(const PaintInfo& paintInfo, const LayoutRect& paintRect, BackgroundBleedAvoidance bleedAvoidance)
1339 paintRootBoxFillLayers(paintInfo);
1342 if (isBody() && skipBodyBackground(this))
1344 if (backgroundIsKnownToBeObscured() && !boxShadowShouldBeAppliedToBackground(bleedAvoidance))
1346 paintFillLayers(paintInfo, style().visitedDependentColor(CSSPropertyBackgroundColor), style().backgroundLayers(), paintRect, bleedAvoidance);
1349 bool RenderBox::getBackgroundPaintedExtent(LayoutRect& paintedExtent) const
1351 ASSERT(hasBackground());
1352 LayoutRect backgroundRect = snappedIntRect(borderBoxRect());
1354 Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1355 if (backgroundColor.isValid() && backgroundColor.alpha()) {
1356 paintedExtent = backgroundRect;
1360 if (!style().backgroundLayers()->image() || style().backgroundLayers()->next()) {
1361 paintedExtent = backgroundRect;
1365 BackgroundImageGeometry geometry = calculateBackgroundImageGeometry(nullptr, *style().backgroundLayers(), backgroundRect);
1366 paintedExtent = geometry.destRect();
1367 return !geometry.hasNonLocalGeometry();
1370 bool RenderBox::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
1372 if (isBody() && skipBodyBackground(this))
1375 Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1376 if (!backgroundColor.isValid() || backgroundColor.hasAlpha())
1379 // If the element has appearance, it might be painted by theme.
1380 // We cannot be sure if theme paints the background opaque.
1381 // In this case it is safe to not assume opaqueness.
1382 // FIXME: May be ask theme if it paints opaque.
1383 if (style().hasAppearance())
1385 // FIXME: Check the opaqueness of background images.
1387 if (hasClip() || hasClipPath())
1390 // FIXME: Use rounded rect if border radius is present.
1391 if (style().hasBorderRadius())
1394 // FIXME: The background color clip is defined by the last layer.
1395 if (style().backgroundLayers()->next())
1397 LayoutRect backgroundRect;
1398 switch (style().backgroundClip()) {
1400 backgroundRect = borderBoxRect();
1402 case PaddingFillBox:
1403 backgroundRect = paddingBoxRect();
1405 case ContentFillBox:
1406 backgroundRect = contentBoxRect();
1411 return backgroundRect.contains(localRect);
1414 static bool isCandidateForOpaquenessTest(const RenderBox& childBox)
1416 const RenderStyle& childStyle = childBox.style();
1417 if (childStyle.position() != StaticPosition && childBox.containingBlock() != childBox.parent())
1419 if (childStyle.visibility() != VISIBLE)
1421 #if ENABLE(CSS_SHAPES)
1422 if (childStyle.shapeOutside())
1425 if (!childBox.width() || !childBox.height())
1427 if (RenderLayer* childLayer = childBox.layer()) {
1428 if (childLayer->isComposited())
1430 // FIXME: Deal with z-index.
1431 if (!childStyle.hasAutoZIndex())
1433 if (childLayer->hasTransform() || childLayer->isTransparent() || childLayer->hasFilter())
1435 if (!childBox.scrolledContentOffset().isZero())
1441 bool RenderBox::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const
1443 if (!maxDepthToTest)
1445 for (auto& childBox : childrenOfType<RenderBox>(*this)) {
1446 if (!isCandidateForOpaquenessTest(childBox))
1448 LayoutPoint childLocation = childBox.location();
1449 if (childBox.isRelPositioned())
1450 childLocation.move(childBox.relativePositionOffset());
1451 LayoutRect childLocalRect = localRect;
1452 childLocalRect.moveBy(-childLocation);
1453 if (childLocalRect.y() < 0 || childLocalRect.x() < 0) {
1454 // If there is unobscured area above/left of a static positioned box then the rect is probably not covered.
1455 if (childBox.style().position() == StaticPosition)
1459 if (childLocalRect.maxY() > childBox.height() || childLocalRect.maxX() > childBox.width())
1461 if (childBox.backgroundIsKnownToBeOpaqueInRect(childLocalRect))
1463 if (childBox.foregroundIsKnownToBeOpaqueInRect(childLocalRect, maxDepthToTest - 1))
1469 bool RenderBox::computeBackgroundIsKnownToBeObscured()
1471 // Test to see if the children trivially obscure the background.
1472 // FIXME: This test can be much more comprehensive.
1473 if (!hasBackground())
1475 // Table and root background painting is special.
1476 if (isTable() || isRoot())
1479 LayoutRect backgroundRect;
1480 if (!getBackgroundPaintedExtent(backgroundRect))
1482 return foregroundIsKnownToBeOpaqueInRect(backgroundRect, backgroundObscurationTestMaxDepth);
1485 bool RenderBox::backgroundHasOpaqueTopLayer() const
1487 const FillLayer* fillLayer = style().backgroundLayers();
1488 if (!fillLayer || fillLayer->clip() != BorderFillBox)
1491 // Clipped with local scrolling
1492 if (hasOverflowClip() && fillLayer->attachment() == LocalBackgroundAttachment)
1495 if (fillLayer->hasOpaqueImage(*this) && fillLayer->hasRepeatXY() && fillLayer->image()->canRender(this, style().effectiveZoom()))
1498 // If there is only one layer and no image, check whether the background color is opaque
1499 if (!fillLayer->next() && !fillLayer->hasImage()) {
1500 Color bgColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1501 if (bgColor.isValid() && bgColor.alpha() == 255)
1508 void RenderBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1510 if (!paintInfo.shouldPaintWithinRoot(*this) || style().visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask || paintInfo.context->paintingDisabled())
1513 LayoutRect paintRect = LayoutRect(paintOffset, size());
1514 paintMaskImages(paintInfo, paintRect);
1517 void RenderBox::paintClippingMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1519 if (!paintInfo.shouldPaintWithinRoot(*this) || style().visibility() != VISIBLE || paintInfo.phase != PaintPhaseClippingMask || paintInfo.context->paintingDisabled())
1522 LayoutRect paintRect = LayoutRect(paintOffset, size());
1523 paintInfo.context->fillRect(snappedIntRect(paintRect), Color::black, style().colorSpace());
1526 void RenderBox::paintMaskImages(const PaintInfo& paintInfo, const LayoutRect& paintRect)
1528 // Figure out if we need to push a transparency layer to render our mask.
1529 bool pushTransparencyLayer = false;
1530 bool compositedMask = hasLayer() && layer()->hasCompositedMask();
1531 bool flattenCompositingLayers = view().frameView().paintBehavior() & PaintBehaviorFlattenCompositingLayers;
1532 CompositeOperator compositeOp = CompositeSourceOver;
1534 bool allMaskImagesLoaded = true;
1536 if (!compositedMask || flattenCompositingLayers) {
1537 pushTransparencyLayer = true;
1538 StyleImage* maskBoxImage = style().maskBoxImage().image();
1539 const FillLayer* maskLayers = style().maskLayers();
1541 // Don't render a masked element until all the mask images have loaded, to prevent a flash of unmasked content.
1543 allMaskImagesLoaded &= maskBoxImage->isLoaded();
1546 allMaskImagesLoaded &= maskLayers->imagesAreLoaded();
1548 paintInfo.context->setCompositeOperation(CompositeDestinationIn);
1549 paintInfo.context->beginTransparencyLayer(1);
1550 compositeOp = CompositeSourceOver;
1553 if (allMaskImagesLoaded) {
1554 paintFillLayers(paintInfo, Color(), style().maskLayers(), paintRect, BackgroundBleedNone, compositeOp);
1555 paintNinePieceImage(paintInfo.context, paintRect, style(), style().maskBoxImage(), compositeOp);
1558 if (pushTransparencyLayer)
1559 paintInfo.context->endTransparencyLayer();
1562 LayoutRect RenderBox::maskClipRect()
1564 const NinePieceImage& maskBoxImage = style().maskBoxImage();
1565 if (maskBoxImage.image()) {
1566 LayoutRect borderImageRect = borderBoxRect();
1568 // Apply outsets to the border box.
1569 borderImageRect.expand(style().maskBoxImageOutsets());
1570 return borderImageRect;
1574 LayoutRect borderBox = borderBoxRect();
1575 for (const FillLayer* maskLayer = style().maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
1576 if (maskLayer->maskImage()) {
1577 // Masks should never have fixed attachment, so it's OK for paintContainer to be null.
1578 BackgroundImageGeometry geometry = calculateBackgroundImageGeometry(nullptr, *maskLayer, borderBox);
1579 result.unite(geometry.destRect());
1585 void RenderBox::paintFillLayers(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1586 BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject)
1588 Vector<const FillLayer*, 8> layers;
1589 const FillLayer* curLayer = fillLayer;
1590 bool shouldDrawBackgroundInSeparateBuffer = false;
1592 layers.append(curLayer);
1593 // Stop traversal when an opaque layer is encountered.
1594 // FIXME : It would be possible for the following occlusion culling test to be more aggressive
1595 // on layers with no repeat by testing whether the image covers the layout rect.
1596 // Testing that here would imply duplicating a lot of calculations that are currently done in
1597 // RenderBoxModelObject::paintFillLayerExtended. A more efficient solution might be to move
1598 // the layer recursion into paintFillLayerExtended, or to compute the layer geometry here
1599 // and pass it down.
1601 if (!shouldDrawBackgroundInSeparateBuffer && curLayer->blendMode() != BlendModeNormal)
1602 shouldDrawBackgroundInSeparateBuffer = true;
1604 // The clipOccludesNextLayers condition must be evaluated first to avoid short-circuiting.
1605 if (curLayer->clipOccludesNextLayers(curLayer == fillLayer) && curLayer->hasOpaqueImage(*this) && curLayer->image()->canRender(this, style().effectiveZoom()) && curLayer->hasRepeatXY() && curLayer->blendMode() == BlendModeNormal)
1607 curLayer = curLayer->next();
1610 GraphicsContext* context = paintInfo.context;
1612 shouldDrawBackgroundInSeparateBuffer = false;
1614 BaseBackgroundColorUsage baseBgColorUsage = BaseBackgroundColorUse;
1616 if (shouldDrawBackgroundInSeparateBuffer) {
1617 paintFillLayer(paintInfo, c, *layers.rbegin(), rect, bleedAvoidance, op, backgroundObject, BaseBackgroundColorOnly);
1618 baseBgColorUsage = BaseBackgroundColorSkip;
1619 context->beginTransparencyLayer(1);
1622 Vector<const FillLayer*>::const_reverse_iterator topLayer = layers.rend();
1623 for (Vector<const FillLayer*>::const_reverse_iterator it = layers.rbegin(); it != topLayer; ++it)
1624 paintFillLayer(paintInfo, c, *it, rect, bleedAvoidance, op, backgroundObject, baseBgColorUsage);
1626 if (shouldDrawBackgroundInSeparateBuffer)
1627 context->endTransparencyLayer();
1630 void RenderBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1631 BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject, BaseBackgroundColorUsage baseBgColorUsage)
1633 paintFillLayerExtended(paintInfo, c, fillLayer, rect, bleedAvoidance, nullptr, LayoutSize(), op, backgroundObject, baseBgColorUsage);
1636 static bool layersUseImage(WrappedImagePtr image, const FillLayer* layers)
1638 for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1639 if (curLayer->image() && image == curLayer->image()->data())
1646 void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
1651 if ((style().borderImage().image() && style().borderImage().image()->data() == image) ||
1652 (style().maskBoxImage().image() && style().maskBoxImage().image()->data() == image)) {
1657 #if ENABLE(CSS_SHAPES)
1658 ShapeValue* shapeOutsideValue = style().shapeOutside();
1659 if (!view().frameView().isInLayout() && isFloating() && shapeOutsideValue && shapeOutsideValue->image() && shapeOutsideValue->image()->data() == image) {
1660 ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
1661 markShapeOutsideDependentsForLayout();
1665 bool didFullRepaint = repaintLayerRectsForImage(image, style().backgroundLayers(), true);
1666 if (!didFullRepaint)
1667 repaintLayerRectsForImage(image, style().maskLayers(), false);
1669 if (!isComposited())
1672 if (layer()->hasCompositedMask() && layersUseImage(image, style().maskLayers()))
1673 layer()->contentChanged(MaskImageChanged);
1674 if (layersUseImage(image, style().backgroundLayers()))
1675 layer()->contentChanged(BackgroundImageChanged);
1678 bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer* layers, bool drawingBackground)
1680 LayoutRect rendererRect;
1681 RenderBox* layerRenderer = nullptr;
1683 for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1684 if (curLayer->image() && image == curLayer->image()->data() && curLayer->image()->canRender(this, style().effectiveZoom())) {
1685 // Now that we know this image is being used, compute the renderer and the rect if we haven't already.
1686 bool drawingRootBackground = drawingBackground && (isRoot() || (isBody() && !document().documentElement()->renderer()->hasBackground()));
1687 if (!layerRenderer) {
1688 if (drawingRootBackground) {
1689 layerRenderer = &view();
1691 LayoutUnit rw = downcast<RenderView>(*layerRenderer).frameView().contentsWidth();
1692 LayoutUnit rh = downcast<RenderView>(*layerRenderer).frameView().contentsHeight();
1694 rendererRect = LayoutRect(-layerRenderer->marginLeft(),
1695 -layerRenderer->marginTop(),
1696 std::max(layerRenderer->width() + layerRenderer->horizontalMarginExtent() + layerRenderer->borderLeft() + layerRenderer->borderRight(), rw),
1697 std::max(layerRenderer->height() + layerRenderer->verticalMarginExtent() + layerRenderer->borderTop() + layerRenderer->borderBottom(), rh));
1699 layerRenderer = this;
1700 rendererRect = borderBoxRect();
1704 BackgroundImageGeometry geometry = layerRenderer->calculateBackgroundImageGeometry(nullptr, *curLayer, rendererRect);
1705 if (geometry.hasNonLocalGeometry()) {
1706 // Rather than incur the costs of computing the paintContainer for renderers with fixed backgrounds
1707 // in order to get the right destRect, just repaint the entire renderer.
1708 layerRenderer->repaint();
1712 LayoutRect rectToRepaint = geometry.destRect();
1713 bool shouldClipToLayer = true;
1715 // If this is the root background layer, we may need to extend the repaintRect if the FrameView has an
1716 // extendedBackground. We should only extend the rect if it is already extending the full width or height
1717 // of the rendererRect.
1718 if (drawingRootBackground && view().frameView().hasExtendedBackgroundRectForPainting()) {
1719 shouldClipToLayer = false;
1720 IntRect extendedBackgroundRect = view().frameView().extendedBackgroundRectForPainting();
1721 if (rectToRepaint.width() == rendererRect.width()) {
1722 rectToRepaint.move(extendedBackgroundRect.x(), 0);
1723 rectToRepaint.setWidth(extendedBackgroundRect.width());
1725 if (rectToRepaint.height() == rendererRect.height()) {
1726 rectToRepaint.move(0, extendedBackgroundRect.y());
1727 rectToRepaint.setHeight(extendedBackgroundRect.height());
1731 layerRenderer->repaintRectangle(rectToRepaint, shouldClipToLayer);
1732 if (geometry.destRect() == rendererRect)
1739 bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset)
1741 if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask)
1744 bool isControlClip = hasControlClip();
1745 bool isOverflowClip = hasOverflowClip() && !layer()->isSelfPaintingLayer();
1747 if (!isControlClip && !isOverflowClip)
1750 if (paintInfo.phase == PaintPhaseOutline)
1751 paintInfo.phase = PaintPhaseChildOutlines;
1752 else if (paintInfo.phase == PaintPhaseChildBlockBackground) {
1753 paintInfo.phase = PaintPhaseBlockBackground;
1754 paintObject(paintInfo, accumulatedOffset);
1755 paintInfo.phase = PaintPhaseChildBlockBackgrounds;
1757 float deviceScaleFactor = document().deviceScaleFactor();
1758 FloatRect clipRect = snapRectToDevicePixels((isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset, currentRenderNamedFlowFragment(), IgnoreOverlayScrollbarSize, paintInfo.phase)), deviceScaleFactor);
1759 paintInfo.context->save();
1760 if (style().hasBorderRadius())
1761 paintInfo.context->clipRoundedRect(style().getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size())).pixelSnappedRoundedRectForPainting(deviceScaleFactor));
1762 paintInfo.context->clip(clipRect);
1766 void RenderBox::popContentsClip(PaintInfo& paintInfo, PaintPhase originalPhase, const LayoutPoint& accumulatedOffset)
1768 ASSERT(hasControlClip() || (hasOverflowClip() && !layer()->isSelfPaintingLayer()));
1770 paintInfo.context->restore();
1771 if (originalPhase == PaintPhaseOutline) {
1772 paintInfo.phase = PaintPhaseSelfOutline;
1773 paintObject(paintInfo, accumulatedOffset);
1774 paintInfo.phase = originalPhase;
1775 } else if (originalPhase == PaintPhaseChildBlockBackground)
1776 paintInfo.phase = originalPhase;
1779 LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, RenderRegion* region, OverlayScrollbarSizeRelevancy relevancy, PaintPhase)
1781 // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
1783 LayoutRect clipRect = borderBoxRectInRegion(region);
1784 clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
1785 clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
1787 // Subtract out scrollbars if we have them.
1789 if (style().shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
1790 clipRect.move(layer()->verticalScrollbarWidth(relevancy), 0);
1791 clipRect.contract(layer()->verticalScrollbarWidth(relevancy), layer()->horizontalScrollbarHeight(relevancy));
1797 LayoutRect RenderBox::clipRect(const LayoutPoint& location, RenderRegion* region)
1799 LayoutRect borderBoxRect = borderBoxRectInRegion(region);
1800 LayoutRect clipRect = LayoutRect(borderBoxRect.location() + location, borderBoxRect.size());
1802 if (!style().clipLeft().isAuto()) {
1803 LayoutUnit c = valueForLength(style().clipLeft(), borderBoxRect.width());
1804 clipRect.move(c, 0);
1805 clipRect.contract(c, 0);
1808 // We don't use the region-specific border box's width and height since clip offsets are (stupidly) specified
1809 // from the left and top edges. Therefore it's better to avoid constraining to smaller widths and heights.
1811 if (!style().clipRight().isAuto())
1812 clipRect.contract(width() - valueForLength(style().clipRight(), width()), 0);
1814 if (!style().clipTop().isAuto()) {
1815 LayoutUnit c = valueForLength(style().clipTop(), borderBoxRect.height());
1816 clipRect.move(0, c);
1817 clipRect.contract(0, c);
1820 if (!style().clipBottom().isAuto())
1821 clipRect.contract(0, height() - valueForLength(style().clipBottom(), height()));
1826 LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock* cb, RenderRegion* region) const
1828 RenderRegion* containingBlockRegion = nullptr;
1829 LayoutUnit logicalTopPosition = logicalTop();
1831 LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1832 logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
1833 containingBlockRegion = cb->clampToStartAndEndRegions(region);
1836 LayoutUnit logicalHeight = cb->logicalHeightForChild(*this);
1837 LayoutUnit result = cb->availableLogicalWidthForLineInRegion(logicalTopPosition, false, containingBlockRegion, logicalHeight) - childMarginStart - childMarginEnd;
1839 // We need to see if margins on either the start side or the end side can contain the floats in question. If they can,
1840 // then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line
1841 // offset at all, but can instead push all the way to the content edge of the containing block. In the case where the float
1842 // 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
1843 // "consumed" by the float. Negative margins aren't consumed by the float, and so we ignore them.
1844 if (childMarginStart > 0) {
1845 LayoutUnit startContentSide = cb->startOffsetForContent(containingBlockRegion);
1846 LayoutUnit startContentSideWithMargin = startContentSide + childMarginStart;
1847 LayoutUnit startOffset = cb->startOffsetForLineInRegion(logicalTopPosition, false, containingBlockRegion, logicalHeight);
1848 if (startOffset > startContentSideWithMargin)
1849 result += childMarginStart;
1851 result += startOffset - startContentSide;
1854 if (childMarginEnd > 0) {
1855 LayoutUnit endContentSide = cb->endOffsetForContent(containingBlockRegion);
1856 LayoutUnit endContentSideWithMargin = endContentSide + childMarginEnd;
1857 LayoutUnit endOffset = cb->endOffsetForLineInRegion(logicalTopPosition, false, containingBlockRegion, logicalHeight);
1858 if (endOffset > endContentSideWithMargin)
1859 result += childMarginEnd;
1861 result += endOffset - endContentSide;
1867 LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const
1869 #if ENABLE(CSS_GRID_LAYOUT)
1870 if (hasOverrideContainingBlockLogicalWidth())
1871 return overrideContainingBlockContentLogicalWidth();
1874 RenderBlock* cb = containingBlock();
1876 return LayoutUnit();
1877 return cb->availableLogicalWidth();
1880 LayoutUnit RenderBox::containingBlockLogicalHeightForContent(AvailableLogicalHeightType heightType) const
1882 #if ENABLE(CSS_GRID_LAYOUT)
1883 if (hasOverrideContainingBlockLogicalHeight())
1884 return overrideContainingBlockContentLogicalHeight();
1887 RenderBlock* cb = containingBlock();
1889 return LayoutUnit();
1890 return cb->availableLogicalHeight(heightType);
1893 LayoutUnit RenderBox::containingBlockLogicalWidthForContentInRegion(RenderRegion* region) const
1896 return containingBlockLogicalWidthForContent();
1898 RenderBlock* cb = containingBlock();
1899 RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
1900 // FIXME: It's unclear if a region's content should use the containing block's override logical width.
1901 // If it should, the following line should call containingBlockLogicalWidthForContent.
1902 LayoutUnit result = cb->availableLogicalWidth();
1903 RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(containingBlockRegion);
1906 return std::max<LayoutUnit>(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
1909 LayoutUnit RenderBox::containingBlockAvailableLineWidthInRegion(RenderRegion* region) const
1911 RenderBlock* cb = containingBlock();
1912 RenderRegion* containingBlockRegion = nullptr;
1913 LayoutUnit logicalTopPosition = logicalTop();
1915 LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1916 logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
1917 containingBlockRegion = cb->clampToStartAndEndRegions(region);
1919 return cb->availableLogicalWidthForLineInRegion(logicalTopPosition, false, containingBlockRegion, availableLogicalHeight(IncludeMarginBorderPadding));
1922 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
1924 #if ENABLE(CSS_GRID_LAYOUT)
1925 if (hasOverrideContainingBlockLogicalHeight())
1926 return overrideContainingBlockContentLogicalHeight();
1929 RenderBlock* cb = containingBlock();
1930 if (cb->hasOverrideLogicalContentHeight())
1931 return cb->overrideLogicalContentHeight();
1933 const RenderStyle& containingBlockStyle = cb->style();
1934 Length logicalHeightLength = containingBlockStyle.logicalHeight();
1936 // FIXME: For now just support fixed heights. Eventually should support percentage heights as well.
1937 if (!logicalHeightLength.isFixed()) {
1938 LayoutUnit fillFallbackExtent = containingBlockStyle.isHorizontalWritingMode() ? view().frameView().visibleHeight() : view().frameView().visibleWidth();
1939 LayoutUnit fillAvailableExtent = containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding);
1940 return std::min(fillAvailableExtent, fillFallbackExtent);
1943 // Use the content box logical height as specified by the style.
1944 return cb->adjustContentBoxLogicalHeightForBoxSizing(logicalHeightLength.value());
1947 void RenderBox::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
1949 if (repaintContainer == this)
1952 if (view().layoutStateEnabled() && !repaintContainer) {
1953 LayoutState* layoutState = view().layoutState();
1954 LayoutSize offset = layoutState->m_paintOffset + locationOffset();
1955 if (style().hasInFlowPosition() && layer())
1956 offset += layer()->offsetForInFlowPosition();
1957 transformState.move(offset);
1961 bool containerSkipped;
1962 RenderElement* container = this->container(repaintContainer, &containerSkipped);
1966 bool isFixedPos = style().position() == FixedPosition;
1967 // If this box has a transform, it acts as a fixed position container for fixed descendants,
1968 // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1969 if (hasTransform() && !isFixedPos)
1971 else if (isFixedPos)
1975 *wasFixed = mode & IsFixed;
1977 LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint(transformState.mappedPoint()));
1979 bool preserve3D = mode & UseTransforms && (container->style().preserves3D() || style().preserves3D());
1980 if (mode & UseTransforms && shouldUseTransformFromContainer(container)) {
1981 TransformationMatrix t;
1982 getTransformFromContainer(container, containerOffset, t);
1983 transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1985 transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1987 if (containerSkipped) {
1988 // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe
1989 // to just subtract the delta between the repaintContainer and o.
1990 LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(*container);
1991 transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1995 mode &= ~ApplyContainerFlip;
1997 // For fixed positioned elements inside out-of-flow named flows, we do not want to
1998 // map their position further to regions based on their coordinates inside the named flows.
1999 if (!container->isOutOfFlowRenderFlowThread() || !fixedPositionedWithNamedFlowContainingBlock())
2000 container->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed);
2002 container->mapLocalToContainer(downcast<RenderLayerModelObject>(container), transformState, mode, wasFixed);
2005 const RenderObject* RenderBox::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
2007 ASSERT(ancestorToStopAt != this);
2009 bool ancestorSkipped;
2010 RenderElement* container = this->container(ancestorToStopAt, &ancestorSkipped);
2014 bool isFixedPos = style().position() == FixedPosition;
2015 LayoutSize adjustmentForSkippedAncestor;
2016 if (ancestorSkipped) {
2017 // There can't be a transform between repaintContainer and container, because transforms create containers, so it should be safe
2018 // to just subtract the delta between the ancestor and container.
2019 adjustmentForSkippedAncestor = -ancestorToStopAt->offsetFromAncestorContainer(*container);
2022 bool offsetDependsOnPoint = false;
2023 LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint(), &offsetDependsOnPoint);
2025 bool preserve3D = container->style().preserves3D() || style().preserves3D();
2026 if (shouldUseTransformFromContainer(container) && (geometryMap.mapCoordinatesFlags() & UseTransforms)) {
2027 TransformationMatrix t;
2028 getTransformFromContainer(container, containerOffset, t);
2029 t.translateRight(adjustmentForSkippedAncestor.width(), adjustmentForSkippedAncestor.height());
2031 geometryMap.push(this, t, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform());
2033 containerOffset += adjustmentForSkippedAncestor;
2034 geometryMap.push(this, containerOffset, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform());
2037 return ancestorSkipped ? ancestorToStopAt : container;
2040 void RenderBox::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
2042 bool isFixedPos = style().position() == FixedPosition;
2043 if (hasTransform() && !isFixedPos) {
2044 // If this box has a transform, it acts as a fixed position container for fixed descendants,
2045 // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
2047 } else if (isFixedPos)
2050 RenderBoxModelObject::mapAbsoluteToLocalPoint(mode, transformState);
2053 LayoutSize RenderBox::offsetFromContainer(RenderElement& renderer, const LayoutPoint&, bool* offsetDependsOnPoint) const
2055 // A region "has" boxes inside it without being their container.
2056 ASSERT(&renderer == container() || is<RenderRegion>(renderer));
2059 if (isInFlowPositioned())
2060 offset += offsetForInFlowPosition();
2062 if (!isInline() || isReplaced())
2063 offset += topLeftLocationOffset();
2065 if (is<RenderBox>(renderer))
2066 offset -= downcast<RenderBox>(renderer).scrolledContentOffset();
2068 if (style().position() == AbsolutePosition && renderer.isInFlowPositioned() && is<RenderInline>(renderer))
2069 offset += downcast<RenderInline>(renderer).offsetForInFlowPositionedInline(this);
2071 if (offsetDependsOnPoint)
2072 *offsetDependsOnPoint |= is<RenderFlowThread>(renderer);
2077 std::unique_ptr<InlineElementBox> RenderBox::createInlineBox()
2079 return std::make_unique<InlineElementBox>(*this);
2082 void RenderBox::dirtyLineBoxes(bool fullLayout)
2084 if (m_inlineBoxWrapper) {
2086 delete m_inlineBoxWrapper;
2087 m_inlineBoxWrapper = nullptr;
2089 m_inlineBoxWrapper->dirtyLineBoxes();
2093 void RenderBox::positionLineBox(InlineElementBox& box)
2095 if (isOutOfFlowPositioned()) {
2096 // Cache the x position only if we were an INLINE type originally.
2097 bool wasInline = style().isOriginalDisplayInlineType();
2099 // The value is cached in the xPos of the box. We only need this value if
2100 // our object was inline originally, since otherwise it would have ended up underneath
2102 RootInlineBox& rootBox = box.root();
2103 rootBox.blockFlow().setStaticInlinePositionForChild(*this, rootBox.lineTopWithLeading(), LayoutUnit::fromFloatRound(box.logicalLeft()));
2104 if (style().hasStaticInlinePosition(box.isHorizontal()))
2105 setChildNeedsLayout(MarkOnlyThis); // Just mark the positioned object as needing layout, so it will update its position properly.
2107 // Our object was a block originally, so we make our normal flow position be
2108 // just below the line box (as though all the inlines that came before us got
2109 // wrapped in an anonymous block, which is what would have happened had we been
2110 // in flow). This value was cached in the y() of the box.
2111 layer()->setStaticBlockPosition(box.logicalTop());
2112 if (style().hasStaticBlockPosition(box.isHorizontal()))
2113 setChildNeedsLayout(MarkOnlyThis); // Just mark the positioned object as needing layout, so it will update its position properly.
2117 box.removeFromParent();
2123 setLocation(LayoutPoint(box.topLeft()));
2124 setInlineBoxWrapper(&box);
2128 void RenderBox::deleteLineBoxWrapper()
2130 if (m_inlineBoxWrapper) {
2131 if (!documentBeingDestroyed())
2132 m_inlineBoxWrapper->removeFromParent();
2133 delete m_inlineBoxWrapper;
2134 m_inlineBoxWrapper = nullptr;
2138 LayoutRect RenderBox::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
2140 if (style().visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
2141 return LayoutRect();
2143 LayoutRect r = visualOverflowRect();
2145 // FIXME: layoutDelta needs to be applied in parts before/after transforms and
2146 // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
2147 r.move(view().layoutDelta());
2149 // We have to use maximalOutlineSize() because a child might have an outline
2150 // that projects outside of our overflowRect.
2151 ASSERT(style().outlineSize() <= view().maximalOutlineSize());
2152 r.inflate(view().maximalOutlineSize());
2154 computeRectForRepaint(repaintContainer, r);
2158 static inline bool shouldApplyContainersClipAndOffset(const RenderLayerModelObject* repaintContainer, RenderBox* containerBox)
2161 if (!repaintContainer || repaintContainer != containerBox)
2164 return !containerBox->hasLayer() || !containerBox->layer()->usesCompositedScrolling();
2166 UNUSED_PARAM(repaintContainer);
2167 UNUSED_PARAM(containerBox);
2172 void RenderBox::computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect& rect, bool fixed) const
2174 // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
2175 // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
2176 // offset corner for the enclosing container). This allows for a fully RL or BT document to repaint
2177 // properly even during layout, since the rect remains flipped all the way until the end.
2179 // RenderView::computeRectForRepaint then converts the rect to physical coordinates. We also convert to
2180 // physical when we hit a repaintContainer boundary. Therefore the final rect returned is always in the
2181 // physical coordinate space of the repaintContainer.
2182 const RenderStyle& styleToUse = style();
2183 // LayoutState is only valid for root-relative, non-fixed position repainting
2184 if (view().layoutStateEnabled() && !repaintContainer && styleToUse.position() != FixedPosition) {
2185 LayoutState* layoutState = view().layoutState();
2187 if (layer() && layer()->transform())
2188 rect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(rect), document().deviceScaleFactor()));
2190 // We can't trust the bits on RenderObject, because this might be called while re-resolving style.
2191 if (styleToUse.hasInFlowPosition() && layer())
2192 rect.move(layer()->offsetForInFlowPosition());
2194 rect.moveBy(location());
2195 rect.move(layoutState->m_paintOffset);
2196 if (layoutState->m_clipped)
2197 rect.intersect(layoutState->m_clipRect);
2201 if (hasReflection())
2202 rect.unite(reflectedRect(rect));
2204 if (repaintContainer == this) {
2205 if (repaintContainer->style().isFlippedBlocksWritingMode())
2206 flipForWritingMode(rect);
2210 bool containerSkipped;
2211 auto* renderer = container(repaintContainer, &containerSkipped);
2215 EPosition position = styleToUse.position();
2217 // This code isn't necessary for in-flow RenderFlowThreads.
2218 // Don't add the location of the region in the flow thread for absolute positioned
2219 // elements because their absolute position already pushes them down through
2220 // the regions so adding this here and then adding the topLeft again would cause
2221 // us to add the height twice.
2222 // The same logic applies for elements flowed directly into the flow thread. Their topLeft member
2223 // will already contain the portion rect of the region.
2224 if (renderer->isOutOfFlowRenderFlowThread() && position != AbsolutePosition && containingBlock() != flowThreadContainingBlock()) {
2225 RenderRegion* firstRegion = nullptr;
2226 RenderRegion* lastRegion = nullptr;
2227 if (downcast<RenderFlowThread>(*renderer).getRegionRangeForBox(this, firstRegion, lastRegion))
2228 rect.moveBy(firstRegion->flowThreadPortionRect().location());
2231 if (isWritingModeRoot() && !isOutOfFlowPositioned())
2232 flipForWritingMode(rect);
2234 LayoutSize locationOffset = this->locationOffset();
2235 // FIXME: This is needed as long as RenderWidget snaps to integral size/position.
2236 if (isRenderReplaced() && isWidget())
2237 locationOffset = toIntSize(flooredIntPoint(locationOffset));
2238 LayoutPoint topLeft = rect.location();
2239 topLeft.move(locationOffset);
2241 // We are now in our parent container's coordinate space. Apply our transform to obtain a bounding box
2242 // in the parent's coordinate space that encloses us.
2243 if (hasLayer() && layer()->transform()) {
2244 fixed = position == FixedPosition;
2245 rect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(rect), document().deviceScaleFactor()));
2246 topLeft = rect.location();
2247 topLeft.move(locationOffset);
2248 } else if (position == FixedPosition)
2251 if (position == AbsolutePosition && renderer->isInFlowPositioned() && is<RenderInline>(*renderer))
2252 topLeft += downcast<RenderInline>(*renderer).offsetForInFlowPositionedInline(this);
2253 else if (styleToUse.hasInFlowPosition() && layer()) {
2254 // Apply the relative position offset when invalidating a rectangle. The layer
2255 // is translated, but the render box isn't, so we need to do this to get the
2256 // right dirty rect. Since this is called from RenderObject::setStyle, the relative position
2257 // flag on the RenderObject has been cleared, so use the one on the style().
2258 topLeft += layer()->offsetForInFlowPosition();
2261 // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
2262 // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
2263 rect.setLocation(topLeft);
2264 if (renderer->hasOverflowClip()) {
2265 RenderBox& containerBox = downcast<RenderBox>(*renderer);
2266 if (shouldApplyContainersClipAndOffset(repaintContainer, &containerBox)) {
2267 containerBox.applyCachedClipAndScrollOffsetForRepaint(rect);
2273 if (containerSkipped) {
2274 // If the repaintContainer is below o, then we need to map the rect into repaintContainer's coordinates.
2275 LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(*renderer);
2276 rect.move(-containerOffset);
2280 renderer->computeRectForRepaint(repaintContainer, rect, fixed);
2283 void RenderBox::repaintDuringLayoutIfMoved(const LayoutRect& oldRect)
2285 if (oldRect.location() != m_frameRect.location()) {
2286 LayoutRect newRect = m_frameRect;
2287 // The child moved. Invalidate the object's old and new positions. We have to do this
2288 // since the object may not have gotten a layout.
2289 m_frameRect = oldRect;
2291 repaintOverhangingFloats(true);
2292 m_frameRect = newRect;
2294 repaintOverhangingFloats(true);
2298 void RenderBox::repaintOverhangingFloats(bool)
2302 void RenderBox::updateLogicalWidth()
2304 LogicalExtentComputedValues computedValues;
2305 computeLogicalWidthInRegion(computedValues);
2307 setLogicalWidth(computedValues.m_extent);
2308 setLogicalLeft(computedValues.m_position);
2309 setMarginStart(computedValues.m_margins.m_start);
2310 setMarginEnd(computedValues.m_margins.m_end);
2313 void RenderBox::computeLogicalWidthInRegion(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
2315 computedValues.m_extent = logicalWidth();
2316 computedValues.m_position = logicalLeft();
2317 computedValues.m_margins.m_start = marginStart();
2318 computedValues.m_margins.m_end = marginEnd();
2320 if (isOutOfFlowPositioned()) {
2321 // FIXME: This calculation is not patched for block-flow yet.
2322 // https://bugs.webkit.org/show_bug.cgi?id=46500
2323 computePositionedLogicalWidth(computedValues, region);
2327 // If layout is limited to a subtree, the subtree root's logical width does not change.
2328 if (element() && view().frameView().layoutRoot(true) == this)
2331 // The parent box is flexing us, so it has increased or decreased our
2332 // width. Use the width from the style context.
2333 // FIXME: Account for block-flow in flexible boxes.
2334 // https://bugs.webkit.org/show_bug.cgi?id=46418
2335 if (hasOverrideLogicalContentWidth() && (isRubyRun() || style().borderFit() == BorderFitLines || parent()->isFlexibleBoxIncludingDeprecated())) {
2336 computedValues.m_extent = overrideLogicalContentWidth() + borderAndPaddingLogicalWidth();
2340 // FIXME: Account for block-flow in flexible boxes.
2341 // https://bugs.webkit.org/show_bug.cgi?id=46418
2342 bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == VERTICAL);
2343 bool stretching = (parent()->style().boxAlign() == BSTRETCH);
2344 bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
2346 const RenderStyle& styleToUse = style();
2347 Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse.logicalWidth();
2349 RenderBlock* cb = containingBlock();
2350 LayoutUnit containerLogicalWidth = std::max<LayoutUnit>(0, containingBlockLogicalWidthForContentInRegion(region));
2351 bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
2353 if (isInline() && !isInlineBlockOrInlineTable()) {
2354 // just calculate margins
2355 computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2356 computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2357 if (treatAsReplaced)
2358 computedValues.m_extent = std::max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
2362 // Width calculations
2363 if (treatAsReplaced)
2364 computedValues.m_extent = logicalWidthLength.value() + borderAndPaddingLogicalWidth();
2366 LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
2367 if (hasPerpendicularContainingBlock)
2368 containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
2369 LayoutUnit preferredWidth = computeLogicalWidthInRegionUsing(MainOrPreferredSize, styleToUse.logicalWidth(), containerWidthInInlineDirection, cb, region);
2370 computedValues.m_extent = constrainLogicalWidthInRegionByMinMax(preferredWidth, containerWidthInInlineDirection, cb, region);
2373 // Margin calculations.
2374 if (hasPerpendicularContainingBlock || isFloating() || isInline()) {
2375 computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2376 computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2378 LayoutUnit containerLogicalWidthForAutoMargins = containerLogicalWidth;
2379 if (avoidsFloats() && cb->containsFloats())
2380 containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInRegion(region);
2381 bool hasInvertedDirection = cb->style().isLeftToRightDirection() != style().isLeftToRightDirection();
2382 computeInlineDirectionMargins(cb, containerLogicalWidthForAutoMargins, computedValues.m_extent,
2383 hasInvertedDirection ? computedValues.m_margins.m_end : computedValues.m_margins.m_start,
2384 hasInvertedDirection ? computedValues.m_margins.m_start : computedValues.m_margins.m_end);
2387 if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (computedValues.m_extent + computedValues.m_margins.m_start + computedValues.m_margins.m_end)
2388 && !isFloating() && !isInline() && !cb->isFlexibleBoxIncludingDeprecated()
2389 #if ENABLE(CSS_GRID_LAYOUT)
2390 && !cb->isRenderGrid()
2393 LayoutUnit newMargin = containerLogicalWidth - computedValues.m_extent - cb->marginStartForChild(*this);
2394 bool hasInvertedDirection = cb->style().isLeftToRightDirection() != style().isLeftToRightDirection();
2395 if (hasInvertedDirection)
2396 computedValues.m_margins.m_start = newMargin;
2398 computedValues.m_margins.m_end = newMargin;
2402 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth) const
2404 LayoutUnit marginStart = 0;
2405 LayoutUnit marginEnd = 0;
2406 return fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2409 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2411 marginStart = minimumValueForLength(style().marginStart(), availableLogicalWidth);
2412 marginEnd = minimumValueForLength(style().marginEnd(), availableLogicalWidth);
2413 return availableLogicalWidth - marginStart - marginEnd;
2416 LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(Length logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const
2418 if (logicalWidthLength.type() == FillAvailable)
2419 return fillAvailableMeasure(availableLogicalWidth);
2421 LayoutUnit minLogicalWidth = 0;
2422 LayoutUnit maxLogicalWidth = 0;
2423 computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
2425 if (logicalWidthLength.type() == MinContent)
2426 return minLogicalWidth + borderAndPadding;
2428 if (logicalWidthLength.type() == MaxContent)
2429 return maxLogicalWidth + borderAndPadding;
2431 if (logicalWidthLength.type() == FitContent) {
2432 minLogicalWidth += borderAndPadding;
2433 maxLogicalWidth += borderAndPadding;
2434 return std::max(minLogicalWidth, std::min(maxLogicalWidth, fillAvailableMeasure(availableLogicalWidth)));
2437 ASSERT_NOT_REACHED();
2441 LayoutUnit RenderBox::computeLogicalWidthInRegionUsing(SizeType widthType, Length logicalWidth, LayoutUnit availableLogicalWidth,
2442 const RenderBlock* cb, RenderRegion* region) const
2444 if (!logicalWidth.isIntrinsicOrAuto()) {
2445 // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
2446 return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth));
2449 if (logicalWidth.isIntrinsic())
2450 return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth());
2452 LayoutUnit marginStart = 0;
2453 LayoutUnit marginEnd = 0;
2454 LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2456 if (shrinkToAvoidFloats() && cb->containsFloats())
2457 logicalWidthResult = std::min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, region));
2459 if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(widthType))
2460 return std::max(minPreferredLogicalWidth(), std::min(maxPreferredLogicalWidth(), logicalWidthResult));
2461 return logicalWidthResult;
2464 static bool flexItemHasStretchAlignment(const RenderBox& flexitem)
2466 auto parent = flexitem.parent();
2467 return RenderStyle::resolveAlignment(parent->style(), flexitem.style(), ItemPositionStretch) == ItemPositionStretch;
2470 static bool isStretchingColumnFlexItem(const RenderBox& flexitem)
2472 auto parent = flexitem.parent();
2473 if (parent->isDeprecatedFlexibleBox() && parent->style().boxOrient() == VERTICAL && parent->style().boxAlign() == BSTRETCH)
2476 // We don't stretch multiline flexboxes because they need to apply line spacing (align-content) first.
2477 if (parent->isFlexibleBox() && parent->style().flexWrap() == FlexNoWrap && parent->style().isColumnFlexDirection() && flexItemHasStretchAlignment(flexitem))
2482 bool RenderBox::sizesLogicalWidthToFitContent(SizeType widthType) const
2484 // Anonymous inline blocks always fill the width of their containing block.
2485 if (isAnonymousInlineBlock())
2488 // Marquees in WinIE are like a mixture of blocks and inline-blocks. They size as though they're blocks,
2489 // but they allow text to sit on the same line as the marquee.
2490 if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee()))
2493 // This code may look a bit strange. Basically width:intrinsic should clamp the size when testing both
2494 // min-width and width. max-width is only clamped if it is also intrinsic.
2495 Length logicalWidth = (widthType == MaxSize) ? style().logicalMaxWidth() : style().logicalWidth();
2496 if (logicalWidth.type() == Intrinsic)
2499 // Children of a horizontal marquee do not fill the container by default.
2500 // FIXME: Need to deal with MAUTO value properly. It could be vertical.
2501 // FIXME: Think about block-flow here. Need to find out how marquee direction relates to
2502 // block-flow (as well as how marquee overflow should relate to block flow).
2503 // https://bugs.webkit.org/show_bug.cgi?id=46472
2504 if (parent()->style().overflowX() == OMARQUEE) {
2505 EMarqueeDirection dir = parent()->style().marqueeDirection();
2506 if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
2510 // Flexible box items should shrink wrap, so we lay them out at their intrinsic widths.
2511 // In the case of columns that have a stretch alignment, we layout at the stretched size
2512 // to avoid an extra layout when applying alignment.
2513 if (parent()->isFlexibleBox()) {
2514 // For multiline columns, we need to apply align-content first, so we can't stretch now.
2515 if (!parent()->style().isColumnFlexDirection() || parent()->style().flexWrap() != FlexNoWrap)
2517 if (!flexItemHasStretchAlignment(*this))
2521 // Flexible horizontal boxes lay out children at their intrinsic widths. Also vertical boxes
2522 // that don't stretch their kids lay out their children at their intrinsic widths.
2523 // FIXME: Think about block-flow here.
2524 // https://bugs.webkit.org/show_bug.cgi?id=46473
2525 if (parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == HORIZONTAL || parent()->style().boxAlign() != BSTRETCH))
2528 // Button, input, select, textarea, and legend treat width value of 'auto' as 'intrinsic' unless it's in a
2529 // stretching column flexbox.
2530 // FIXME: Think about block-flow here.
2531 // https://bugs.webkit.org/show_bug.cgi?id=46473
2532 if (logicalWidth.type() == Auto && !isStretchingColumnFlexItem(*this) && element() && (is<HTMLInputElement>(*element()) || is<HTMLSelectElement>(*element()) || is<HTMLButtonElement>(*element()) || is<HTMLTextAreaElement>(*element()) || is<HTMLLegendElement>(*element())))
2535 if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
2541 void RenderBox::computeInlineDirectionMargins(RenderBlock* containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2543 const RenderStyle& containingBlockStyle = containingBlock->style();
2544 Length marginStartLength = style().marginStartUsing(&containingBlockStyle);
2545 Length marginEndLength = style().marginEndUsing(&containingBlockStyle);
2547 if (isFloating() || isInline()) {
2548 // Inline blocks/tables and floats don't have their margins increased.
2549 marginStart = minimumValueForLength(marginStartLength, containerWidth);
2550 marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2554 // Case One: The object is being centered in the containing block's available logical width.
2555 if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
2556 || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock->style().textAlign() == WEBKIT_CENTER)) {
2557 // Other browsers center the margin box for align=center elements so we match them here.
2558 LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth);
2559 LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth);
2560 LayoutUnit centeredMarginBoxStart = std::max<LayoutUnit>(0, (containerWidth - childWidth - marginStartWidth - marginEndWidth) / 2);
2561 marginStart = centeredMarginBoxStart + marginStartWidth;
2562 marginEnd = containerWidth - childWidth - marginStart + marginEndWidth;
2566 // Case Two: The object is being pushed to the start of the containing block's available logical width.
2567 if (marginEndLength.isAuto() && childWidth < containerWidth) {
2568 marginStart = valueForLength(marginStartLength, containerWidth);
2569 marginEnd = containerWidth - childWidth - marginStart;
2573 // Case Three: The object is being pushed to the end of the containing block's available logical width.
2574 bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_LEFT)
2575 || (containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_RIGHT));
2576 if ((marginStartLength.isAuto() && childWidth < containerWidth) || pushToEndFromTextAlign) {
2577 marginEnd = valueForLength(marginEndLength, containerWidth);
2578 marginStart = containerWidth - childWidth - marginEnd;
2582 // Case Four: Either no auto margins, or our width is >= the container width (css2.1, 10.3.3). In that case
2583 // auto margins will just turn into 0.
2584 marginStart = minimumValueForLength(marginStartLength, containerWidth);
2585 marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2588 RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
2590 // Make sure nobody is trying to call this with a null region.
2594 // If we have computed our width in this region already, it will be cached, and we can
2596 RenderBoxRegionInfo* boxInfo = region->renderBoxRegionInfo(this);
2597 if (boxInfo && cacheFlag == CacheRenderBoxRegionInfo)
2600 // No cached value was found, so we have to compute our insets in this region.
2601 // FIXME: For now we limit this computation to normal RenderBlocks. Future patches will expand
2602 // support to cover all boxes.
2603 RenderFlowThread* flowThread = flowThreadContainingBlock();
2604 if (isRenderFlowThread() || !flowThread || !canHaveBoxInfoInRegion() || flowThread->style().writingMode() != style().writingMode())
2607 LogicalExtentComputedValues computedValues;
2608 computeLogicalWidthInRegion(computedValues, region);
2610 // Now determine the insets based off where this object is supposed to be positioned.
2611 RenderBlock* cb = containingBlock();
2612 RenderRegion* clampedContainingBlockRegion = cb->clampToStartAndEndRegions(region);
2613 RenderBoxRegionInfo* containingBlockInfo = cb->renderBoxRegionInfo(clampedContainingBlockRegion);
2614 LayoutUnit containingBlockLogicalWidth = cb->logicalWidth();
2615 LayoutUnit containingBlockLogicalWidthInRegion = containingBlockInfo ? containingBlockInfo->logicalWidth() : containingBlockLogicalWidth;
2617 LayoutUnit marginStartInRegion = computedValues.m_margins.m_start;
2618 LayoutUnit startMarginDelta = marginStartInRegion - marginStart();
2619 LayoutUnit logicalWidthInRegion = computedValues.m_extent;
2620 LayoutUnit logicalLeftInRegion = computedValues.m_position;
2621 LayoutUnit widthDelta = logicalWidthInRegion - logicalWidth();
2622 LayoutUnit logicalLeftDelta = isOutOfFlowPositioned() ? logicalLeftInRegion - logicalLeft() : startMarginDelta;
2623 LayoutUnit logicalRightInRegion = containingBlockLogicalWidthInRegion - (logicalLeftInRegion + logicalWidthInRegion);
2624 LayoutUnit oldLogicalRight = containingBlockLogicalWidth - (logicalLeft() + logicalWidth());
2625 LayoutUnit logicalRightDelta = isOutOfFlowPositioned() ? logicalRightInRegion - oldLogicalRight : startMarginDelta;
2627 LayoutUnit logicalLeftOffset = 0;
2629 if (!isOutOfFlowPositioned() && avoidsFloats() && cb->containsFloats()) {
2630 LayoutUnit startPositionDelta = cb->computeStartPositionDeltaForChildAvoidingFloats(*this, marginStartInRegion, region);
2631 if (cb->style().isLeftToRightDirection())
2632 logicalLeftDelta += startPositionDelta;
2634 logicalRightDelta += startPositionDelta;
2637 if (cb->style().isLeftToRightDirection())
2638 logicalLeftOffset += logicalLeftDelta;
2640 logicalLeftOffset -= (widthDelta + logicalRightDelta);
2642 LayoutUnit logicalRightOffset = logicalWidth() - (logicalLeftOffset + logicalWidthInRegion);
2643 bool isShifted = (containingBlockInfo && containingBlockInfo->isShifted())
2644 || (style().isLeftToRightDirection() && logicalLeftOffset)
2645 || (!style().isLeftToRightDirection() && logicalRightOffset);
2647 // FIXME: Although it's unlikely, these boxes can go outside our bounds, and so we will need to incorporate them into overflow.
2648 if (cacheFlag == CacheRenderBoxRegionInfo)
2649 return region->setRenderBoxRegionInfo(this, logicalLeftOffset, logicalWidthInRegion, isShifted);
2650 return new RenderBoxRegionInfo(logicalLeftOffset, logicalWidthInRegion, isShifted);
2653 static bool shouldFlipBeforeAfterMargins(const RenderStyle& containingBlockStyle, const RenderStyle* childStyle)
2655 ASSERT(containingBlockStyle.isHorizontalWritingMode() != childStyle->isHorizontalWritingMode());
2656 WritingMode childWritingMode = childStyle->writingMode();
2657 bool shouldFlip = false;
2658 switch (containingBlockStyle.writingMode()) {
2659 case TopToBottomWritingMode:
2660 shouldFlip = (childWritingMode == RightToLeftWritingMode);
2662 case BottomToTopWritingMode:
2663 shouldFlip = (childWritingMode == RightToLeftWritingMode);
2665 case RightToLeftWritingMode:
2666 shouldFlip = (childWritingMode == BottomToTopWritingMode);
2668 case LeftToRightWritingMode:
2669 shouldFlip = (childWritingMode == BottomToTopWritingMode);
2673 if (!containingBlockStyle.isLeftToRightDirection())
2674 shouldFlip = !shouldFlip;
2679 void RenderBox::updateLogicalHeight()
2681 LogicalExtentComputedValues computedValues;
2682 computeLogicalHeight(logicalHeight(), logicalTop(), computedValues);
2684 setLogicalHeight(computedValues.m_extent);
2685 setLogicalTop(computedValues.m_position);
2686 setMarginBefore(computedValues.m_margins.m_before);
2687 setMarginAfter(computedValues.m_margins.m_after);
2690 void RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
2692 computedValues.m_extent = logicalHeight;
2693 computedValues.m_position = logicalTop;
2695 // Cell height is managed by the table and inline non-replaced elements do not support a height property.
2696 if (isTableCell() || (isInline() && !isReplaced()))
2700 if (isOutOfFlowPositioned())
2701 computePositionedLogicalHeight(computedValues);
2703 RenderBlock* cb = containingBlock();
2704 bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
2706 if (!hasPerpendicularContainingBlock) {
2707 bool shouldFlipBeforeAfter = cb->style().writingMode() != style().writingMode();
2708 computeBlockDirectionMargins(cb,
2709 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2710 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2713 // For tables, calculate margins only.
2715 if (hasPerpendicularContainingBlock) {
2716 bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), &style());
2717 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), computedValues.m_extent,
2718 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2719 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2724 // FIXME: Account for block-flow in flexible boxes.
2725 // https://bugs.webkit.org/show_bug.cgi?id=46418
2726 bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style().boxOrient() == HORIZONTAL;
2727 bool stretching = parent()->style().boxAlign() == BSTRETCH;
2728 bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
2729 bool checkMinMaxHeight = false;
2731 // The parent box is flexing us, so it has increased or decreased our height. We have to
2732 // grab our cached flexible height.
2733 // FIXME: Account for block-flow in flexible boxes.
2734 // https://bugs.webkit.org/show_bug.cgi?id=46418
2735 if (hasOverrideLogicalContentHeight() && (parent()->isFlexibleBoxIncludingDeprecated()
2736 #if ENABLE(CSS_GRID_LAYOUT)
2737 || parent()->isRenderGrid()
2740 h = Length(overrideLogicalContentHeight(), Fixed);
2741 else if (treatAsReplaced)
2742 h = Length(computeReplacedLogicalHeight(), Fixed);
2744 h = style().logicalHeight();
2745 checkMinMaxHeight = true;
2748 // Block children of horizontal flexible boxes fill the height of the box.
2749 // FIXME: Account for block-flow in flexible boxes.
2750 // https://bugs.webkit.org/show_bug.cgi?id=46418
2751 if (h.isAuto() && is<RenderDeprecatedFlexibleBox>(*parent()) && parent()->style().boxOrient() == HORIZONTAL
2752 && downcast<RenderDeprecatedFlexibleBox>(*parent()).isStretchingChildren()) {
2753 h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2754 checkMinMaxHeight = false;
2757 LayoutUnit heightResult;
2758 if (checkMinMaxHeight) {
2759 heightResult = computeLogicalHeightUsing(style().logicalHeight());
2760 if (heightResult == -1)
2761 heightResult = computedValues.m_extent;
2762 heightResult = constrainLogicalHeightByMinMax(heightResult);
2764 // The only times we don't check min/max height are when a fixed length has
2765 // been given as an override. Just use that. The value has already been adjusted
2767 heightResult = h.value() + borderAndPaddingLogicalHeight();
2770 computedValues.m_extent = heightResult;
2772 if (hasPerpendicularContainingBlock) {
2773 bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), &style());
2774 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult,
2775 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2776 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2780 // WinIE quirk: The <html> block always fills the entire canvas in quirks mode. The <body> always fills the
2781 // <html> block in quirks mode. Only apply this quirk if the block is normal flow and no height
2782 // is specified. When we're printing, we also need this quirk if the body or root has a percentage
2783 // height since we don't set a height in RenderView when we're printing. So without this quirk, the
2784 // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2785 bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercentOrCalculated()
2786 && (isRoot() || (isBody() && document().documentElement()->renderer()->style().logicalHeight().isPercentOrCalculated())) && !isInline();
2787 if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2788 LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2789 LayoutUnit visibleHeight = view().pageOrViewLogicalHeight();
2791 computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - margins);
2793 LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2794 computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - marginsBordersPadding);
2799 LayoutUnit RenderBox::computeLogicalHeightUsing(const Length& height) const
2801 LayoutUnit logicalHeight = computeContentAndScrollbarLogicalHeightUsing(height);
2802 if (logicalHeight != -1)
2803 logicalHeight = adjustBorderBoxLogicalHeightForBoxSizing(logicalHeight);
2804 return logicalHeight;
2807 LayoutUnit RenderBox::computeContentLogicalHeight(const Length& height) const
2809 LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(height);
2810 if (heightIncludingScrollbar == -1)
2812 return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2815 LayoutUnit RenderBox::computeContentAndScrollbarLogicalHeightUsing(const Length& height) const
2817 if (height.isFixed())
2818 return height.value();
2819 if (height.isPercentOrCalculated())
2820 return computePercentageLogicalHeight(height);
2824 bool RenderBox::skipContainingBlockForPercentHeightCalculation(const RenderBox* containingBlock, bool isPerpendicularWritingMode) const
2826 // Flow threads for multicol or paged overflow should be skipped. They are invisible to the DOM,
2827 // and percent heights of children should be resolved against the multicol or paged container.
2828 if (containingBlock->isInFlowRenderFlowThread() && !isPerpendicularWritingMode)
2831 // For quirks mode and anonymous blocks, we skip auto-height containingBlocks when computing percentages.
2832 // For standards mode, we treat the percentage as auto if it has an auto-height containing block.
2833 if (!document().inQuirksMode() && !containingBlock->isAnonymousBlock())
2835 return !containingBlock->isTableCell() && !containingBlock->isOutOfFlowPositioned() && containingBlock->style().logicalHeight().isAuto() && isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode();
2838 LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height) const
2840 LayoutUnit availableHeight = -1;
2842 bool skippedAutoHeightContainingBlock = false;
2843 RenderBlock* cb = containingBlock();
2844 const RenderBox* containingBlockChild = this;
2845 LayoutUnit rootMarginBorderPaddingHeight = 0;
2846 bool isHorizontal = isHorizontalWritingMode();
2847 while (!cb->isRenderView() && skipContainingBlockForPercentHeightCalculation(cb, isHorizontal != cb->isHorizontalWritingMode())) {
2848 if (cb->isBody() || cb->isRoot())
2849 rootMarginBorderPaddingHeight += cb->marginBefore() + cb->marginAfter() + cb->borderAndPaddingLogicalHeight();
2850 skippedAutoHeightContainingBlock = true;
2851 containingBlockChild = cb;
2852 cb = cb->containingBlock();
2853 cb->addPercentHeightDescendant(const_cast<RenderBox&>(*this));
2856 const RenderStyle& cbstyle = cb->style();
2858 // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
2859 // explicitly specified that can be used for any percentage computations.
2860 bool isOutOfFlowPositionedWithSpecifiedHeight = cb->isOutOfFlowPositioned() && (!cbstyle.logicalHeight().isAuto() || (!cbstyle.logicalTop().isAuto() && !cbstyle.logicalBottom().isAuto()));
2862 bool includeBorderPadding = isTable();
2864 if (isHorizontal != cb->isHorizontalWritingMode())
2865 availableHeight = containingBlockChild->containingBlockLogicalWidthForContent();
2866 #if ENABLE(CSS_GRID_LAYOUT)
2867 else if (hasOverrideContainingBlockLogicalHeight())
2868 availableHeight = overrideContainingBlockContentLogicalHeight();
2870 else if (is<RenderTableCell>(*cb)) {
2871 if (!skippedAutoHeightContainingBlock) {
2872 // Table cells violate what the CSS spec says to do with heights. Basically we
2873 // don't care if the cell specified a height or not. We just always make ourselves
2874 // be a percentage of the cell's current content height.
2875 if (!cb->hasOverrideLogicalContentHeight()) {
2876 // Normally we would let the cell size intrinsically, but scrolling overflow has to be
2877 // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
2878 // While we can't get all cases right, we can at least detect when the cell has a specified
2879 // height or when the table has a specified height. In these cases we want to initially have
2880 // no size and allow the flexing of the table or the cell to its specified height to cause us
2881 // to grow to fill the space. This could end up being wrong in some cases, but it is
2882 // preferable to the alternative (sizing intrinsically and making the row end up too big).
2883 RenderTableCell& cell = downcast<RenderTableCell>(*cb);
2884 if (scrollsOverflowY() && (!cell.style().logicalHeight().isAuto() || !cell.table()->style().logicalHeight().isAuto()))
2888 availableHeight = cb->overrideLogicalContentHeight();
2889 includeBorderPadding = true;
2891 } else if (cbstyle.logicalHeight().isFixed()) {
2892 LayoutUnit contentBoxHeight = cb->adjustContentBoxLogicalHeightForBoxSizing(cbstyle.logicalHeight().value());
2893 availableHeight = std::max<LayoutUnit>(0, cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeight - cb->scrollbarLogicalHeight()));
2894 } else if (cbstyle.logicalHeight().isPercentOrCalculated() && !isOutOfFlowPositionedWithSpecifiedHeight) {
2895 // We need to recur and compute the percentage height for our containing block.
2896 LayoutUnit heightWithScrollbar = cb->computePercentageLogicalHeight(cbstyle.logicalHeight());
2897 if (heightWithScrollbar != -1) {
2898 LayoutUnit contentBoxHeightWithScrollbar = cb->adjustContentBoxLogicalHeightForBoxSizing(heightWithScrollbar);
2899 // We need to adjust for min/max height because this method does not
2900 // handle the min/max of the current block, its caller does. So the
2901 // return value from the recursive call will not have been adjusted
2903 LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight());
2904 availableHeight = std::max<LayoutUnit>(0, contentBoxHeight);
2906 } else if (isOutOfFlowPositionedWithSpecifiedHeight) {
2907 // Don't allow this to affect the block' height() member variable, since this
2908 // can get called while the block is still laying out its kids.
2909 LogicalExtentComputedValues computedValues;
2910 cb->computeLogicalHeight(cb->logicalHeight(), 0, computedValues);
2911 availableHeight = computedValues.m_extent - cb->borderAndPaddingLogicalHeight() - cb->scrollbarLogicalHeight();
2912 } else if (cb->isRenderView())
2913 availableHeight = view().pageOrViewLogicalHeight();
2915 if (availableHeight == -1)
2916 return availableHeight;
2918 availableHeight -= rootMarginBorderPaddingHeight;
2920 LayoutUnit result = valueForLength(height, availableHeight);
2921 if (includeBorderPadding) {
2922 // FIXME: Table cells should default to box-sizing: border-box so we can avoid this hack.
2923 // It is necessary to use the border-box to match WinIE's broken
2924 // box model. This is essential for sizing inside
2925 // table cells using percentage heights.
2926 result -= borderAndPaddingLogicalHeight();
2927 return std::max<LayoutUnit>(0, result);
2932 LayoutUnit RenderBox::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
2934 return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(style().logicalWidth()), shouldComputePreferred);
2937 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, ShouldComputePreferred shouldComputePreferred) const
2939 LayoutUnit minLogicalWidth = (shouldComputePreferred == ComputePreferred && style().logicalMinWidth().isPercentOrCalculated()) || style().logicalMinWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style().logicalMinWidth());
2940 LayoutUnit maxLogicalWidth = (shouldComputePreferred == ComputePreferred && style().logicalMaxWidth().isPercentOrCalculated()) || style().logicalMaxWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style().logicalMaxWidth());
2941 return std::max(minLogicalWidth, std::min(logicalWidth, maxLogicalWidth));
2944 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(Length logicalWidth) const
2946 switch (logicalWidth.type()) {
2948 return adjustContentBoxLogicalWidthForBoxSizing(logicalWidth.value());
2951 // MinContent/MaxContent don't need the availableLogicalWidth argument.
2952 LayoutUnit availableLogicalWidth = 0;
2953 return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2959 // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
2960 // containing block's block-flow.
2961 // https://bugs.webkit.org/show_bug.cgi?id=46496
2962 const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(downcast<RenderBoxModelObject>(container())) : containingBlockLogicalWidthForContent();
2963 Length containerLogicalWidth = containingBlock()->style().logicalWidth();
2964 // FIXME: Handle cases when containing block width is calculated or viewport percent.
2965 // https://bugs.webkit.org/show_bug.cgi?id=91071
2966 if (logicalWidth.isIntrinsic())
2967 return computeIntrinsicLogicalWidthUsing(logicalWidth, cw, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2968 if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercentOrCalculated())))
2969 return adjustContentBoxLogicalWidthForBoxSizing(minimumValueForLength(logicalWidth, cw));
2977 return intrinsicLogicalWidth();
2980 ASSERT_NOT_REACHED();
2984 LayoutUnit RenderBox::computeReplacedLogicalHeight() const
2986 return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(style().logicalHeight()));
2989 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
2991 LayoutUnit minLogicalHeight = computeReplacedLogicalHeightUsing(style().logicalMinHeight());
2992 LayoutUnit maxLogicalHeight = style().logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(style().logicalMaxHeight());
2993 return std::max(minLogicalHeight, std::min(logicalHeight, maxLogicalHeight));
2996 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(Length logicalHeight) const
2998 switch (logicalHeight.type()) {
3000 return adjustContentBoxLogicalHeightForBoxSizing(logicalHeight.value());
3004 auto cb = isOutOfFlowPositioned() ? container() : containingBlock();
3005 while (cb->isAnonymous() && !is<RenderView>(*cb)) {
3006 cb = cb->containingBlock();
3007 downcast<RenderBlock>(*cb).addPercentHeightDescendant(const_cast<RenderBox&>(*this));
3010 // FIXME: This calculation is not patched for block-flow yet.
3011 // https://bugs.webkit.org/show_bug.cgi?id=46500
3012 if (cb->isOutOfFlowPositioned() && cb->style().height().isAuto() && !(cb->style().top().isAuto() || cb->style().bottom().isAuto())) {
3013 ASSERT_WITH_SECURITY_IMPLICATION(cb->isRenderBlock());
3014 RenderBlock& block = downcast<RenderBlock>(*cb);
3015 LogicalExtentComputedValues computedValues;
3016 block.computeLogicalHeight(block.logicalHeight(), 0, computedValues);
3017 LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3018 LayoutUnit newHeight = block.adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3019 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, newHeight));
3022 // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
3023 // containing block's block-flow.
3024 // https://bugs.webkit.org/show_bug.cgi?id=46496
3025 LayoutUnit availableHeight;
3026 if (isOutOfFlowPositioned())
3027 availableHeight = containingBlockLogicalHeightForPositioned(downcast<RenderBoxModelObject>(cb));
3029 availableHeight = containingBlockLogicalHeightForContent(IncludeMarginBorderPadding);
3030 // It is necessary to use the border-box to match WinIE's broken
3031 // box model. This is essential for sizing inside
3032 // table cells using percentage heights.
3033 // FIXME: This needs to be made block-flow-aware. If the cell and image are perpendicular block-flows, this isn't right.
3034 // https://bugs.webkit.org/show_bug.cgi?id=46997
3035 while (cb && !cb->isRenderView() && (cb->style().logicalHeight().isAuto() || cb->style().logicalHeight().isPercentOrCalculated())) {
3036 if (cb->isTableCell()) {
3037 // Don't let table cells squeeze percent-height replaced elements
3038 // <http://bugs.webkit.org/show_bug.cgi?id=15359>
3039 availableHeight = std::max(availableHeight, intrinsicLogicalHeight());
3040 return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight());
3042 downcast<RenderBlock>(*cb).addPercentHeightDescendant(const_cast<RenderBox&>(*this));
3043 cb = cb->containingBlock();
3046 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight));
3049 return intrinsicLogicalHeight();
3053 LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const
3055 return constrainLogicalHeightByMinMax(availableLogicalHeightUsing(style().logicalHeight(), heightType));
3058 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const
3060 // We need to stop here, since we don't want to increase the height of the table
3061 // artificially. We're going to rely on this cell getting expanded to some new
3062 // height, and then when we lay out again we'll use the calculation below.
3063 if (isTableCell() && (h.isAuto() || h.isPercentOrCalculated())) {
3064 if (hasOverrideLogicalContentHeight())
3065 return overrideLogicalContentHeight();
3066 return logicalHeight() - borderAndPaddingLogicalHeight();
3069 if (h.isPercentOrCalculated() && isOutOfFlowPositioned() && !isRenderFlowThread()) {
3070 // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3071 LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(containingBlock());
3072 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight));
3075 LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(h);
3076 if (heightIncludingScrollbar != -1)
3077 return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
3079 // FIXME: Check logicalTop/logicalBottom here to correctly handle vertical writing-mode.
3080 // https://bugs.webkit.org/show_bug.cgi?id=46500
3081 if (is<RenderBlock>(*this) && isOutOfFlowPositioned() && style().height().isAuto() && !(style().top().isAuto() || style().bottom().isAuto())) {
3082 RenderBlock& block = const_cast<RenderBlock&>(downcast<RenderBlock>(*this));
3083 LogicalExtentComputedValues computedValues;
3084 block.computeLogicalHeight(block.logicalHeight(), 0, computedValues);
3085 LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3086 return adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3089 // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3090 LayoutUnit availableHeight = containingBlockLogicalHeightForContent(heightType);
3091 if (heightType == ExcludeMarginBorderPadding) {
3092 // FIXME: Margin collapsing hasn't happened yet, so this incorrectly removes collapsed margins.
3093 availableHeight -= marginBefore() + marginAfter() + borderAndPaddingLogicalHeight();
3095 return availableHeight;
3098 void RenderBox::computeBlockDirectionMargins(const RenderBlock* containingBlock, LayoutUnit& marginBefore, LayoutUnit& marginAfter) const
3100 if (isTableCell()) {
3101 // FIXME: Not right if we allow cells to have different directionality than the table. If we do allow this, though,
3102 // we may just do it with an extra anonymous block inside the cell.
3108 // Margins are calculated with respect to the logical width of
3109 // the containing block (8.3)
3110 LayoutUnit cw = containingBlockLogicalWidthForContent();
3111 const RenderStyle& containingBlockStyle = containingBlock->style();
3112 marginBefore = minimumValueForLength(style().marginBeforeUsing(&containingBlockStyle), cw);
3113 marginAfter = minimumValueForLength(style().marginAfterUsing(&containingBlockStyle), cw);
3116 void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock* containingBlock)
3118 LayoutUnit marginBefore;
3119 LayoutUnit marginAfter;
3120 computeBlockDirectionMargins(containingBlock, marginBefore, marginAfter);
3121 containingBlock->setMarginBeforeForChild(*this, marginBefore);
3122 containingBlock->setMarginAfterForChild(*this, marginAfter);
3125 LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, RenderRegion* region, bool checkForPerpendicularWritingMode) const
3127 if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
3128 return containingBlockLogicalHeightForPositioned(containingBlock, false);
3130 if (is<RenderBox>(*containingBlock)) {
3131 bool isFixedPosition = style().position() == FixedPosition;
3133 RenderFlowThread* flowThread = flowThreadContainingBlock();
3135 if (isFixedPosition && is<RenderView>(*containingBlock))
3136 return downcast<RenderView>(*containingBlock).clientLogicalWidthForFixedPosition();
3138 return downcast<RenderBox>(*containingBlock).clientLogicalWidth();
3141 if (isFixedPosition && is<RenderNamedFlowThread>(*containingBlock))
3142 return containingBlock->view().clientLogicalWidth();
3144 if (!is<RenderBlock>(*containingBlock))
3145 return downcast<RenderBox>(*containingBlock).clientLogicalWidth();
3147 const RenderBlock& cb = downcast<RenderBlock>(*containingBlock);
3148 RenderBoxRegionInfo* boxInfo = nullptr;
3150 if (is<RenderFlowThread>(*containingBlock) && !checkForPerpendicularWritingMode)
3151 return downcast<RenderFlowThread>(*containingBlock).contentLogicalWidthOfFirstRegion();
3152 if (isWritingModeRoot()) {
3153 LayoutUnit cbPageOffset = cb.offsetFromLogicalTopOfFirstPage();
3154 RenderRegion* cbRegion = cb.regionAtBlockOffset(cbPageOffset);
3156 boxInfo = cb.renderBoxRegionInfo(cbRegion);
3158 } else if (flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
3159 RenderRegion* containingBlockRegion = cb.clampToStartAndEndRegions(region);
3160 boxInfo = cb.renderBoxRegionInfo(containingBlockRegion);
3162 return (boxInfo) ? std::max<LayoutUnit>(0, cb.clientLogicalWidth() - (cb.logicalWidth() - boxInfo->logicalWidth())) : cb.clientLogicalWidth();
3165 ASSERT(containingBlock->isInFlowPositioned());
3167 const auto& flow = downcast<RenderInline>(*containingBlock);
3168 InlineFlowBox* first = flow.firstLineBox();
3169 InlineFlowBox* last = flow.lastLineBox();
3171 // If the containing block is empty, return a width of 0.
3172 if (!first || !last)
3175 LayoutUnit fromLeft;
3176 LayoutUnit fromRight;
3177 if (containingBlock->style().isLeftToRightDirection()) {
3178 fromLeft = first->logicalLeft() + first->borderLogicalLeft();
3179 fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
3181 fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
3182 fromLeft = last->logicalLeft() + last->borderLogicalLeft();
3185 return std::max<LayoutUnit>(0, fromRight - fromLeft);
3188 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
3190 if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
3191 return containingBlockLogicalWidthForPositioned(containingBlock, nullptr, false);
3193 if (containingBlock->isBox()) {
3194 bool isFixedPosition = style().position() == FixedPosition;
3196 if (isFixedPosition && is<RenderView>(*containingBlock))
3197 return downcast<RenderView>(*containingBlock).clientLogicalHeightForFixedPosition();
3199 const RenderBlock* cb = is<RenderBlock>(*containingBlock) ? downcast<RenderBlock>(containingBlock) : containingBlock->containingBlock();
3200 LayoutUnit result = cb->clientLogicalHeight();
3201 RenderFlowThread* flowThread = flowThreadContainingBlock();
3202 if (flowThread && is<RenderFlowThread>(*containingBlock) && flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
3203 if (is<RenderNamedFlowThread>(*containingBlock) && isFixedPosition)
3204 return containingBlock->view().clientLogicalHeight();
3205 return downcast<RenderFlowThread>(*containingBlock).contentLogicalHeightOfFirstRegion();
3210 ASSERT(containingBlock->isInFlowPositioned());
3212 const auto& flow = downcast<RenderInline>(*containingBlock);
3213 InlineFlowBox* first = flow.firstLineBox();
3214 InlineFlowBox* last = flow.lastLineBox();
3216 // If the containing block is empty, return a height of 0.
3217 if (!first || !last)
3220 LayoutUnit heightResult;
3221 LayoutRect boundingBox = flow.linesBoundingBox();
3222 if (containingBlock->isHorizontalWritingMode())
3223 heightResult = boundingBox.height();
3225 heightResult = boundingBox.width();
3226 heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter());
3227 return heightResult;
3230 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth, RenderRegion* region)
3232 if (!logicalLeft.isAuto() || !logicalRight.isAuto())
3235 // FIXME: The static distance computation has not been patched for mixed writing modes yet.
3236 if (child->parent()->style().direction() == LTR) {
3237 LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock->borderLogicalLeft();
3238 for (auto current = child->parent(); current && current != containerBlock; current = current->container()) {
3239 if (is<RenderBox>(*current)) {
3240 staticPosition += downcast<RenderBox>(*current).logicalLeft();
3241 if (region && is<RenderBlock>(*current)) {
3242 const RenderBlock& currentBlock = downcast<RenderBlock>(*current);
3243 region = currentBlock.clampToStartAndEndRegions(region);
3244 RenderBoxRegionInfo* boxInfo = currentBlock.renderBoxRegionInfo(region);
3246 staticPosition += boxInfo->logicalLeft();
3250 logicalLeft.setValue(Fixed, staticPosition);
3252 RenderBox& enclosingBox = child->parent()->enclosingBox();
3253 LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock->borderLogicalLeft();
3254 for (RenderElement* current = &enclosingBox; current; current = current->container()) {
3255 if (is<RenderBox>(*current)) {
3256 if (current != containerBlock)
3257 staticPosition -= downcast<RenderBox>(*current).logicalLeft();
3258 if (current == &enclosingBox)
3259 staticPosition -= enclosingBox.logicalWidth();
3260 if (region && is<RenderBlock>(*current)) {
3261 const RenderBlock& currentBlock = downcast<RenderBlock>(*current);
3262 region = currentBlock.clampToStartAndEndRegions(region);
3263 RenderBoxRegionInfo* boxInfo = currentBlock.renderBoxRegionInfo(region);
3265 if (current != containerBlock)
3266 staticPosition -= currentBlock.logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth());
3267 if (current == &enclosingBox)
3268 staticPosition += enclosingBox.logicalWidth() - boxInfo->logicalWidth();
3272 if (current == containerBlock)
3275 logicalRight.setValue(Fixed, staticPosition);
3279 void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
3282 // FIXME: Positioned replaced elements inside a flow thread are not working properly
3283 // with variable width regions (see https://bugs.webkit.org/show_bug.cgi?id=69896 ).
3284 computePositionedLogicalWidthReplaced(computedValues);
3289 // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
3290 // the type 'static' in determining whether to calculate the static distance?
3291 // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
3293 // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
3294 // than or less than the computed width(). Be careful of box-sizing and
3295 // percentage issues.
3297 // The following is based off of the W3C Working Draft from April 11, 2006 of
3298 // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
3299 // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
3300 // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
3301 // correspond to text from the spec)
3304 // We don't use containingBlock(), since we may be positioned by an enclosing
3305 // relative positioned inline.
3306 const RenderBoxModelObject* containerBlock = downcast<RenderBoxModelObject>(container());
3308 const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, region);
3310 // Use the container block's direction except when calculating the static distance
3311 // This conforms with the reference results for abspos-replaced-width-margin-000.htm
3312 // of the CSS 2.1 test suite
3313 TextDirection containerDirection = containerBlock->style().direction();
3315 bool isHorizontal = isHorizontalWritingMode();
3316 const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
3317 const Length marginLogicalLeft = isHorizontal ? style().marginLeft() : style().marginTop();
3318 const Length marginLogicalRight = isHorizontal ? style().marginRight() : style().marginBottom();
3320 Length logicalLeftLength = style().logicalLeft();
3321 Length logicalRightLength = style().logicalRight();
3323 /*---------------------------------------------------------------------------*\
3324 * For the purposes of this section and the next, the term "static position"
3325 * (of an element) refers, roughly, to the position an element would have had
3326 * in the normal flow. More precisely:
3328 * * The static position for 'left' is the distance from the left edge of the
3329 * containing block to the left margin edge of a hypothetical box that would
3330 * have been the first box of the element if its 'position' property had
3331 * been 'static' and 'float' had been 'none'. The value is negative if the
3332 * hypothetical box is to the left of the containing block.
3333 * * The static position for 'right' is the distance from the right edge of the
3334 * containing block to the right margin edge of the same hypothetical box as
3335 * above. The value is positive if the hypothetical box is to the left of the
3336 * containing block's edge.
3338 * But rather than actually calculating the dimensions of that hypothetical box,
3339 * user agents are free to make a guess at its probable position.
3341 * For the purposes of calculating the static position, the containing block of
3342 * fixed positioned elements is the initial containing block instead of the
3343 * viewport, and all scrollable boxes should be assumed to be scrolled to their
3345 \*---------------------------------------------------------------------------*/
3348 // Calculate the static distance if needed.
3349 computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth, region);
3351 // Calculate constraint equation values for 'width' case.
3352 computePositionedLogicalWidthUsing(style().logicalWidth(), containerBlock, containerDirection,
3353 containerLogicalWidth, bordersPlusPadding,
3354 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3357 // Calculate constraint equation values for 'max-width' case.
3358 if (!style().logicalMaxWidth().isUndefined()) {
3359 LogicalExtentComputedValues maxValues;
3361 computePositionedLogicalWidthUsing(style().logicalMaxWidth(), containerBlock, containerDirection,
3362 containerLogicalWidth, bordersPlusPadding,
3363 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3366 if (computedValues.m_extent > maxValues.m_extent) {
3367 computedValues.m_extent = maxValues.m_extent;
3368 computedValues.m_position = maxValues.m_position;
3369 computedValues.m_margins.m_start = maxValues.m_margins.m_start;
3370 computedValues.m_margins.m_end = maxValues.m_margins.m_end;
3374 // Calculate constraint equation values for 'min-width' case.
3375 if (!style().logicalMinWidth().isZero() || style().logicalMinWidth().isIntrinsic()) {
3376 LogicalExtentComputedValues minValues;
3378 computePositionedLogicalWidthUsing(style().logicalMinWidth(), containerBlock, containerDirection,
3379 containerLogicalWidth, bordersPlusPadding,
3380 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3383 if (computedValues.m_extent < minValues.m_extent) {
3384 computedValues.m_extent = minValues.m_extent;
3385 computedValues.m_position = minValues.m_position;
3386 computedValues.m_margins.m_start = minValues.m_margins.m_start;
3387 computedValues.m_margins.m_end = minValues.m_margins.m_end;
3391 computedValues.m_extent += bordersPlusPadding;
3393 // Adjust logicalLeft if we need to for the flipped version of our writing mode in regions.
3394 // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock.
3395 RenderFlowThread* flowThread = flowThreadContainingBlock();
3396 if (flowThread && !region && isWritingModeRoot() && isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode() && is<RenderBlock>(*containerBlock)) {
3397 ASSERT(containerBlock->canHaveBoxInfoInRegion());
3398 LayoutUnit logicalLeftPos = computedValues.m_position;
3399 const RenderBlock& renderBlock = downcast<RenderBlock>(*containerBlock);
3400 LayoutUnit cbPageOffset = renderBlock.offsetFromLogicalTopOfFirstPage();
3401 RenderRegion* cbRegion = renderBlock.regionAtBlockOffset(cbPageOffset);
3403 RenderBoxRegionInfo* boxInfo = renderBlock.renderBoxRegionInfo(cbRegion);
3405 logicalLeftPos += boxInfo->logicalLeft();
3406 computedValues.m_position = logicalLeftPos;
3412 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
3414 // Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3415 // along this axis, then we need to flip the coordinate. This can only happen if the containing block is both a flipped mode and perpendicular to us.
3416 if (containerBlock->isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock->style().isFlippedBlocksWritingMode()) {
3417 logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
3418 logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderRight() : containerBlock->borderBottom());
3420 logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderLeft() : containerBlock->borderTop());
3423 void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const RenderBoxModelObject* containerBlock, TextDirection containerDirection,
3424 LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
3425 Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight,
3426 LogicalExtentComputedValues& computedValues) const
3428 if (logicalWidth.isIntrinsic())
3429 logicalWidth = Length(computeIntrinsicLogicalWidthUsing(logicalWidth, containerLogicalWidth, bordersPlusPadding) - bordersPlusPadding, Fixed);
3431 // 'left' and 'right' cannot both be 'auto' because one would of been
3432 // converted to the static position already
3433 ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
3435 LayoutUnit logicalLeftValue = 0;
3437 const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, nullptr, false);
3439 bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
3440 bool logicalLeftIsAuto = logicalLeft.isAuto();
3441 bool logicalRightIsAuto = logicalRight.isAuto();
3442 LayoutUnit& marginLogicalLeftValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
3443 LayoutUnit& marginLogicalRightValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
3445 if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3446 /*-----------------------------------------------------------------------*\
3447 * If none of the three is 'auto': If both 'margin-left' and 'margin-
3448 * right' are 'auto', solve the equation under the extra constraint that
3449 * the two margins get equal values, unless this would make them negative,
3450 * in which case when direction of the containing block is 'ltr' ('rtl'),
3451 * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
3452 * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
3453 * solve the equation for that value. If the values are over-constrained,
3454 * ignore the value for 'left' (in case the 'direction' property of the
3455 * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
3456 * and solve for that value.
3457 \*-----------------------------------------------------------------------*/
3458 // NOTE: It is not necessary to solve for 'right' in the over constrained
3459 // case because the value is not used for any further calculations.
3461 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3462 computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3464 const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth) + bordersPlusPadding);
3466 // Margins are now the only unknown
3467 if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
3468 // Both margins auto, solve for equality
3469 if (availableSpace >= 0) {
3470 marginLogicalLeftValue = availableSpace / 2; // split the difference
3471 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
3473 // Use the containing block's direction rather than the parent block's
3474 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3475 if (containerDirection == LTR) {
3476 marginLogicalLeftValue = 0;
3477 marginLogicalRightValue = availableSpace; // will be negative
3479 marginLogicalLeftValue = availableSpace; // will be negative
3480 marginLogicalRightValue = 0;
3483 } else if (marginLogicalLeft.isAuto()) {
3484 // Solve for left margin
3485 marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3486 marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
3487 } else if (marginLogicalRight.isAuto()) {
3488 // Solve for right margin
3489 marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3490 marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
3492 // Over-constrained, solve for left if direction is RTL
3493 marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3494 marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3496 // Use the containing block's direction rather than the parent block's
3497 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3498 if (containerDirection == RTL)
3499 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
3502 /*--------------------------------------------------------------------*\
3503 * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
3504 * to 0, and pick the one of the following six rules that applies.
3506 * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
3507 * width is shrink-to-fit. Then solve for 'left'
3509 * OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3510 * ------------------------------------------------------------------
3511 * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
3512 * the 'direction' property of the containing block is 'ltr' set
3513 * 'left' to the static position, otherwise set 'right' to the
3514 * static position. Then solve for 'left' (if 'direction is 'rtl')
3515 * or 'right' (if 'direction' is 'ltr').
3516 * ------------------------------------------------------------------
3518 * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
3519 * width is shrink-to-fit . Then solve for 'right'
3520 * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
3522 * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
3524 * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
3527 * Calculation of the shrink-to-fit width is similar to calculating the
3528 * width of a table cell using the automatic table layout algorithm.
3529 * Roughly: calculate the preferred width by formatting the content
3530 * without breaking lines other than where explicit line breaks occur,
3531 * and also calculate the preferred minimum width, e.g., by trying all
3532 * possible line breaks. CSS 2.1 does not define the exact algorithm.
3533 * Thirdly, calculate the available width: this is found by solving
3534 * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
3537 * Then the shrink-to-fit width is:
3538 * min(max(preferred minimum width, available width), preferred width).
3539 \*--------------------------------------------------------------------*/
3540 // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
3541 // because the value is not used for any further calculations.
3543 // Calculate margins, 'auto' margins are ignored.
3544 marginLogicalLeftValue = minimumValueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3545 marginLogicalRightValue = minimumValueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3547 const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
3549 // FIXME: Is there a faster way to find the correct case?
3550 // Use rule/case that applies.
3551 if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3552 // RULE 1: (use shrink-to-fit for width, and solve of left)
3553 LayoutUnit logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3555 // FIXME: would it be better to have shrink-to-fit in one step?
3556 LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3557 LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3558 LayoutUnit availableWidth = availableSpace - logicalRightValue;
3559 computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3560 logicalLeftValue = availableSpace - (computedValues.m_extent + logicalRightValue);
3561 } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
3562 // RULE 3: (use shrink-to-fit for width, and no need solve of right)
3563 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3565 // FIXME: would it be better to have shrink-to-fit in one step?
3566 LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3567 LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3568 LayoutUnit availableWidth = availableSpace - logicalLeftValue;
3569 computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3570 } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3571 // RULE 4: (solve for left)
3572 computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3573 logicalLeftValue = availableSpace - (computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth));
3574 } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3575 // RULE 5: (solve for width)
3576 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3577 computedValues.m_extent = availableSpace - (logicalLeftValue + valueForLength(logicalRight, containerLogicalWidth));
3578 } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
3579 // RULE 6: (no need solve for right)
3580 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3581 computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3585 // Use computed values to calculate the horizontal position.
3587 // FIXME: This hack is needed to calculate the logical left position for a 'rtl' relatively
3588 // positioned, inline because right now, it is using the logical left position
3589 // of the first line box when really it should use the last line box. When
3590 // this is fixed elsewhere, this block should be removed.
3591 if (is<RenderInline>(*containerBlock) && !containerBlock->style().isLeftToRightDirection()) {
3592 const auto& flow = downcast<RenderInline>(*containerBlock);
3593 InlineFlowBox* firstLine = flow.firstLineBox();
3594 InlineFlowBox* lastLine = flow.lastLineBox();
3595 if (firstLine && lastLine && firstLine != lastLine) {
3596 computedValues.m_position = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
3601 computedValues.m_position = logicalLeftValue + marginLogicalLeftValue;
3602 computeLogicalLeftPositionedOffset(computedValues.m_position, this, computedValues.m_extent, containerBlock, containerLogicalWidth);
3605 static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject* containerBlock)
3607 if (!logicalTop.isAuto() || !logicalBottom.isAuto())
3610 // FIXME: The static distance computation has not been patched for mixed writing modes.
3611 LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock->borderBefore();
3612 for (RenderElement* container = child->parent(); container && container != containerBlock; container = container->container()) {
3613 if (is<RenderBox>(*container) && !is<RenderTableRow>(*container))
3614 staticLogicalTop += downcast<RenderBox>(*container).logicalTop();
3616 logicalTop.setValue(Fixed, staticLogicalTop);
3619 void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& computedValues) const
3622 computePositionedLogicalHeightReplaced(computedValues);
3626 // The following is based off of the W3C Working Draft from April 11, 2006 of
3627 // CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
3628 // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
3629 // (block-style-comments in this function and in computePositionedLogicalHeightUsing()
3630 // correspond to text from the spec)
3633 // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
3634 const RenderBoxModelObject* containerBlock = downcast<RenderBoxModelObject>(container());
3636 const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
3638 const RenderStyle& styleToUse = style();
3639 const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
3640 const Length marginBefore = styleToUse.marginBefore();
3641 const Length marginAfter = styleToUse.marginAfter();
3642 Length logicalTopLength = styleToUse.logicalTop();
3643 Length logicalBottomLength = styleToUse.logicalBottom();
3645 /*---------------------------------------------------------------------------*\
3646 * For the purposes of this section and the next, the term "static position"
3647 * (of an element) refers, roughly, to the position an element would have had
3648 * in the normal flow. More precisely, the static position for 'top' is the
3649 * distance from the top edge of the containing block to the top margin edge
3650 * of a hypothetical box that would have been the first box of the element if
3651 * its 'position' property had been 'static' and 'float' had been 'none'. The
3652 * value is negative if the hypothetical box is above the containing block.
3654 * But rather than actually calculating the dimensions of that hypothetical
3655 * box, user agents are free to make a guess at its probable position.
3657 * For the purposes of calculating the static position, the containing block
3658 * of fixed positioned elements is the initial containing block instead of
3660 \*---------------------------------------------------------------------------*/
3663 // Calculate the static distance if needed.
3664 computeBlockStaticDistance(logicalTopLength, logicalBottomLength, this, containerBlock);
3666 // Calculate constraint equation values for 'height' case.
3667 LayoutUnit logicalHeight = computedValues.m_extent;
3668 computePositionedLogicalHeightUsing(styleToUse.logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3669 logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3672 // Avoid doing any work in the common case (where the values of min-height and max-height are their defaults).
3675 // Calculate constraint equation values for 'max-height' case.
3676 if (!styleToUse.logicalMaxHeight().isUndefined()) {
3677 LogicalExtentComputedValues maxValues;
3679 computePositionedLogicalHeightUsing(styleToUse.logicalMaxHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3680 logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3683 if (computedValues.m_extent > maxValues.m_extent) {
3684 computedValues.m_extent = maxValues.m_extent;
3685 computedValues.m_position = maxValues.m_position;
3686 computedValues.m_margins.m_before = maxValues.m_margins.m_before;
3687 computedValues.m_margins.m_after = maxValues.m_margins.m_after;
3691 // Calculate constraint equation values for 'min-height' case.
3692 if (!styleToUse.logicalMinHeight().isZero()) {
3693 LogicalExtentComputedValues minValues;
3695 computePositionedLogicalHeightUsing(styleToUse.logicalMinHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3696 logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3699 if (computedValues.m_extent < minValues.m_extent) {
3700 computedValues.m_extent = minValues.m_extent;
3701 computedValues.m_position = minValues.m_position;
3702 computedValues.m_margins.m_before = minValues.m_margins.m_before;
3703 computedValues.m_margins.m_after = minValues.m_margins.m_after;
3707 // Set final height value.
3708 computedValues.m_extent += bordersPlusPadding;
3710 // Adjust logicalTop if we need to for perpendicular writing modes in regions.
3711 // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock.
3712 RenderFlowThread* flowThread = flowThreadContainingBlock();
3713 if (flowThread && isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode() && is<RenderBlock>(*containerBlock)) {
3714 ASSERT(containerBlock->canHaveBoxInfoInRegion());
3715 LayoutUnit logicalTopPos = computedValues.m_position;
3716 const RenderBlock& renderBox = downcast<RenderBlock>(*containerBlock);
3717 LayoutUnit cbPageOffset = renderBox.offsetFromLogicalTopOfFirstPage() - logicalLeft();
3718 RenderRegion* cbRegion = renderBox.regionAtBlockOffset(cbPageOffset);
3720 RenderBoxRegionInfo* boxInfo = renderBox.renderBoxRegionInfo(cbRegion);
3722 logicalTopPos += boxInfo->logicalLeft();
3723 computedValues.m_position = logicalTopPos;
3729 static void computeLogicalTopPositionedOffset(LayoutUnit& logicalTopPos, const RenderBox* child, LayoutUnit logicalHeightValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalHeight)
3731 // Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3732 // along this axis, then we need to flip the coordinate. This can only happen if the containing block is both a flipped mode and perpendicular to us.
3733 if ((child->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode())
3734 || (child->style().isFlippedBlocksWritingMode() != containerBlock->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()))
3735 logicalTopPos = containerLogicalHeight - logicalHeightValue - logicalTopPos;
3737 // Our offset is from the logical bottom edge in a flipped environment, e.g., right for vertical-rl and bottom for horizontal-bt.
3738 if (containerBlock->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
3739 if (child->isHorizontalWritingMode())
3740 logicalTopPos += containerBlock->borderBottom();
3742 logicalTopPos += containerBlock->borderRight();
3744 if (child->isHorizontalWritingMode())
3745 logicalTopPos += containerBlock->borderTop();
3747 logicalTopPos += containerBlock->borderLeft();
3751 void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, const RenderBoxModelObject* containerBlock,
3752 LayoutUnit containerLogicalHeight, LayoutUnit bordersPlusPadding, LayoutUnit logicalHeight,
3753 Length logicalTop, Length logicalBottom, Length marginBefore, Length marginAfter,
3754 LogicalExtentComputedValues& computedValues) const
3756 // 'top' and 'bottom' cannot both be 'auto' because 'top would of been
3757 // converted to the static position in computePositionedLogicalHeight()
3758 ASSERT(!(logicalTop.isAuto() && logicalBottom.isAuto()));
3760 LayoutUnit logicalHeightValue;
3761 LayoutUnit contentLogicalHeight = logicalHeight - bordersPlusPadding;
3763 const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, nullptr, false);
3765 LayoutUnit logicalTopValue = 0;
3766 LayoutUnit resolvedLogicalHeight = 0;
3768 bool logicalHeightIsAuto = logicalHeightLength.isAuto();
3769 bool logicalTopIsAuto = logicalTop.isAuto();
3770 bool logicalBottomIsAuto = logicalBottom.isAuto();
3772 // Height is never unsolved for tables.
3774 resolvedLogicalHeight = contentLogicalHeight;
3775 logicalHeightIsAuto = false;
3777 resolvedLogicalHeight = adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeightLength, containerLogicalHeight));
3779 if (!logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
3780 /*-----------------------------------------------------------------------*\
3781 * If none of the three are 'auto': If both 'margin-top' and 'margin-
3782 * bottom' are 'auto', solve the equation under the extra constraint that
3783 * the two margins get equal values. If one of 'margin-top' or 'margin-
3784 * bottom' is 'auto', solve the equation for that value. If the values
3785 * are over-constrained, ignore the value for 'bottom' and solve for that
3787 \*-----------------------------------------------------------------------*/
3788 // NOTE: It is not necessary to solve for 'bottom' in the over constrained
3789 // case because the value is not used for any further calculations.
3791 logicalHeightValue = resolvedLogicalHeight;
3792 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3794 const LayoutUnit availableSpace = containerLogicalHeight - (logicalTopValue + logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight) + bordersPlusPadding);
3796 // Margins are now the only unknown
3797 if (marginBefore.isAuto() && marginAfter.isAuto()) {
3798 // Both margins auto, solve for equality
3799 // NOTE: This may result in negative values.
3800 computedValues.m_margins.m_before = availableSpace / 2; // split the difference
3801 computedValues.m_margins.m_after = availableSpace - computedValues.m_margins.m_before; // account for odd valued differences
3802 } else if (marginBefore.isAuto()) {
3803 // Solve for top margin
3804 computedValues.m_margins.m_after = valueForLength(marginAfter, containerRelativeLogicalWidth);
3805 computedValues.m_margins.m_before = availableSpace - computedValues.m_margins.m_after;
3806 } else if (marginAfter.isAuto()) {
3807 // Solve for bottom margin
3808 computedValues.m_margins.m_before = valueForLength(marginBefore, containerRelativeLogicalWidth);
3809 computedValues.m_margins.m_after = availableSpace - computedValues.m_margins.m_before;
3811 // Over-constrained, (no need solve for bottom)
3812 computedValues.m_margins.m_before = valueForLength(marginBefore, containerRelativeLogicalWidth);
3813 computedValues.m_margins.m_after = valueForLength(marginAfter, containerRelativeLogicalWidth);