2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2007 David Smith (catfish.man@gmail.com)
5 * Copyright (C) 2003-2015 Apple Inc. All rights reserved.
6 * Copyright (C) Research In Motion Limited 2010. 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.
25 #include "RenderBlockFlow.h"
28 #include "FloatingObjects.h"
30 #include "FrameSelection.h"
31 #include "HTMLElement.h"
32 #include "HTMLInputElement.h"
33 #include "HTMLParserIdioms.h"
34 #include "HTMLTextAreaElement.h"
35 #include "HitTestLocation.h"
36 #include "InlineTextBox.h"
37 #include "LayoutRepainter.h"
39 #include "RenderCombineText.h"
40 #include "RenderFlexibleBox.h"
41 #include "RenderInline.h"
42 #include "RenderIterator.h"
43 #include "RenderLayer.h"
44 #include "RenderLineBreak.h"
45 #include "RenderListItem.h"
46 #include "RenderMarquee.h"
47 #include "RenderMultiColumnFlow.h"
48 #include "RenderMultiColumnSet.h"
49 #include "RenderTableCell.h"
50 #include "RenderText.h"
51 #include "RenderTreeBuilder.h"
52 #include "RenderView.h"
54 #include "SimpleLineLayoutFunctions.h"
55 #include "SimpleLineLayoutPagination.h"
56 #include "TextAutoSizing.h"
57 #include "VerticalPositionCache.h"
58 #include "VisiblePosition.h"
59 #include <wtf/IsoMallocInlines.h>
63 WTF_MAKE_ISO_ALLOCATED_IMPL(RenderBlockFlow);
65 bool RenderBlock::s_canPropagateFloatIntoSibling = false;
67 struct SameSizeAsMarginInfo {
68 uint32_t bitfields : 16;
69 LayoutUnit margins[2];
72 COMPILE_ASSERT(sizeof(RenderBlockFlow::MarginValues) == sizeof(LayoutUnit[4]), MarginValues_should_stay_small);
73 COMPILE_ASSERT(sizeof(RenderBlockFlow::MarginInfo) == sizeof(SameSizeAsMarginInfo), MarginInfo_should_stay_small);
75 // Our MarginInfo state used when laying out block children.
76 RenderBlockFlow::MarginInfo::MarginInfo(const RenderBlockFlow& block, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding)
77 : m_atBeforeSideOfBlock(true)
78 , m_atAfterSideOfBlock(false)
79 , m_hasMarginBeforeQuirk(false)
80 , m_hasMarginAfterQuirk(false)
81 , m_determinedMarginBeforeQuirk(false)
82 , m_discardMargin(false)
84 const RenderStyle& blockStyle = block.style();
85 ASSERT(block.isRenderView() || block.parent());
86 m_canCollapseWithChildren = !block.createsNewFormattingContext() && !block.isRenderView();
88 m_canCollapseMarginBeforeWithChildren = m_canCollapseWithChildren && !beforeBorderPadding && blockStyle.marginBeforeCollapse() != MSEPARATE;
90 // If any height other than auto is specified in CSS, then we don't collapse our bottom
91 // margins with our children's margins. To do otherwise would be to risk odd visual
92 // effects when the children overflow out of the parent block and yet still collapse
93 // with it. We also don't collapse if we have any bottom border/padding.
94 m_canCollapseMarginAfterWithChildren = m_canCollapseWithChildren && !afterBorderPadding
95 && (blockStyle.logicalHeight().isAuto() && !blockStyle.logicalHeight().value()) && blockStyle.marginAfterCollapse() != MSEPARATE;
97 m_quirkContainer = block.isTableCell() || block.isBody();
99 m_discardMargin = m_canCollapseMarginBeforeWithChildren && block.mustDiscardMarginBefore();
101 m_positiveMargin = (m_canCollapseMarginBeforeWithChildren && !block.mustDiscardMarginBefore()) ? block.maxPositiveMarginBefore() : LayoutUnit();
102 m_negativeMargin = (m_canCollapseMarginBeforeWithChildren && !block.mustDiscardMarginBefore()) ? block.maxNegativeMarginBefore() : LayoutUnit();
105 RenderBlockFlow::RenderBlockFlow(Element& element, RenderStyle&& style)
106 : RenderBlock(element, WTFMove(style), RenderBlockFlowFlag)
107 #if ENABLE(TEXT_AUTOSIZING)
108 , m_widthForTextAutosizing(-1)
109 , m_lineCountForTextAutosizing(NOT_SET)
112 setChildrenInline(true);
115 RenderBlockFlow::RenderBlockFlow(Document& document, RenderStyle&& style)
116 : RenderBlock(document, WTFMove(style), RenderBlockFlowFlag)
117 #if ENABLE(TEXT_AUTOSIZING)
118 , m_widthForTextAutosizing(-1)
119 , m_lineCountForTextAutosizing(NOT_SET)
122 setChildrenInline(true);
125 RenderBlockFlow::~RenderBlockFlow()
127 // Do not add any code here. Add it to willBeDestroyed() instead.
130 void RenderBlockFlow::willBeDestroyed()
132 if (!renderTreeBeingDestroyed()) {
133 if (firstRootBox()) {
134 // We can't wait for RenderBox::destroy to clear the selection,
135 // because by then we will have nuked the line boxes.
136 if (isSelectionBorder())
137 frame().selection().setNeedsSelectionUpdate();
139 // If we are an anonymous block, then our line boxes might have children
140 // that will outlast this block. In the non-anonymous block case those
141 // children will be destroyed by the time we return from this function.
142 if (isAnonymousBlock()) {
143 for (auto* box = firstRootBox(); box; box = box->nextRootBox()) {
144 while (auto childBox = box->firstChild())
145 childBox->removeFromParent();
149 parent()->dirtyLinesFromChangedChild(*this);
152 m_lineBoxes.deleteLineBoxes();
154 blockWillBeDestroyed();
156 // NOTE: This jumps down to RenderBox, bypassing RenderBlock since it would do duplicate work.
157 RenderBox::willBeDestroyed();
160 RenderBlockFlow* RenderBlockFlow::previousSiblingWithOverhangingFloats(bool& parentHasFloats) const
162 // Attempt to locate a previous sibling with overhanging floats. We skip any elements that are
163 // out of flow (like floating/positioned elements), and we also skip over any objects that may have shifted
165 parentHasFloats = false;
166 for (RenderObject* sibling = previousSibling(); sibling; sibling = sibling->previousSibling()) {
167 if (is<RenderBlockFlow>(*sibling)) {
168 auto& siblingBlock = downcast<RenderBlockFlow>(*sibling);
169 if (!siblingBlock.avoidsFloats())
170 return &siblingBlock;
172 if (sibling->isFloating())
173 parentHasFloats = true;
178 void RenderBlockFlow::rebuildFloatingObjectSetFromIntrudingFloats()
180 if (m_floatingObjects)
181 m_floatingObjects->setHorizontalWritingMode(isHorizontalWritingMode());
183 HashSet<RenderBox*> oldIntrudingFloatSet;
184 if (!childrenInline() && m_floatingObjects) {
185 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
186 auto end = floatingObjectSet.end();
187 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
188 FloatingObject* floatingObject = it->get();
189 if (!floatingObject->isDescendant())
190 oldIntrudingFloatSet.add(&floatingObject->renderer());
194 // Inline blocks are covered by the isReplaced() check in the avoidFloats method.
195 if (avoidsFloats() || isDocumentElementRenderer() || isRenderView() || isFloatingOrOutOfFlowPositioned() || isTableCell()) {
196 if (m_floatingObjects)
197 m_floatingObjects->clear();
198 if (!oldIntrudingFloatSet.isEmpty())
199 markAllDescendantsWithFloatsForLayout();
203 RendererToFloatInfoMap floatMap;
205 if (m_floatingObjects) {
206 if (childrenInline())
207 m_floatingObjects->moveAllToFloatInfoMap(floatMap);
209 m_floatingObjects->clear();
212 // We should not process floats if the parent node is not a RenderBlock. Otherwise, we will add
213 // floats in an invalid context. This will cause a crash arising from a bad cast on the parent.
214 // See <rdar://problem/8049753>, where float property is applied on a text node in a SVG.
215 if (!is<RenderBlockFlow>(parent()))
218 // First add in floats from the parent. Self-collapsing blocks let their parent track any floats that intrude into
219 // them (as opposed to floats they contain themselves) so check for those here too.
220 auto& parentBlock = downcast<RenderBlockFlow>(*parent());
221 bool parentHasFloats = false;
222 RenderBlockFlow* previousBlock = previousSiblingWithOverhangingFloats(parentHasFloats);
223 LayoutUnit logicalTopOffset = logicalTop();
224 if (parentHasFloats || (parentBlock.lowestFloatLogicalBottom() > logicalTopOffset && previousBlock && previousBlock->isSelfCollapsingBlock()))
225 addIntrudingFloats(&parentBlock, &parentBlock, parentBlock.logicalLeftOffsetForContent(), logicalTopOffset);
227 LayoutUnit logicalLeftOffset = 0;
229 logicalTopOffset -= previousBlock->logicalTop();
231 previousBlock = &parentBlock;
232 logicalLeftOffset += parentBlock.logicalLeftOffsetForContent();
235 // Add overhanging floats from the previous RenderBlock, but only if it has a float that intrudes into our space.
236 if (previousBlock->m_floatingObjects && previousBlock->lowestFloatLogicalBottom() > logicalTopOffset)
237 addIntrudingFloats(previousBlock, &parentBlock, logicalLeftOffset, logicalTopOffset);
239 if (childrenInline()) {
240 LayoutUnit changeLogicalTop = LayoutUnit::max();
241 LayoutUnit changeLogicalBottom = LayoutUnit::min();
242 if (m_floatingObjects) {
243 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
244 auto end = floatingObjectSet.end();
245 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
246 const auto& floatingObject = *it->get();
247 std::unique_ptr<FloatingObject> oldFloatingObject = floatMap.take(&floatingObject.renderer());
248 LayoutUnit logicalBottom = logicalBottomForFloat(floatingObject);
249 if (oldFloatingObject) {
250 LayoutUnit oldLogicalBottom = logicalBottomForFloat(*oldFloatingObject);
251 if (logicalWidthForFloat(floatingObject) != logicalWidthForFloat(*oldFloatingObject) || logicalLeftForFloat(floatingObject) != logicalLeftForFloat(*oldFloatingObject)) {
252 changeLogicalTop = 0;
253 changeLogicalBottom = std::max(changeLogicalBottom, std::max(logicalBottom, oldLogicalBottom));
255 if (logicalBottom != oldLogicalBottom) {
256 changeLogicalTop = std::min(changeLogicalTop, std::min(logicalBottom, oldLogicalBottom));
257 changeLogicalBottom = std::max(changeLogicalBottom, std::max(logicalBottom, oldLogicalBottom));
259 LayoutUnit logicalTop = logicalTopForFloat(floatingObject);
260 LayoutUnit oldLogicalTop = logicalTopForFloat(*oldFloatingObject);
261 if (logicalTop != oldLogicalTop) {
262 changeLogicalTop = std::min(changeLogicalTop, std::min(logicalTop, oldLogicalTop));
263 changeLogicalBottom = std::max(changeLogicalBottom, std::max(logicalTop, oldLogicalTop));
267 if (oldFloatingObject->originatingLine() && !selfNeedsLayout()) {
268 ASSERT(&oldFloatingObject->originatingLine()->renderer() == this);
269 oldFloatingObject->originatingLine()->markDirty();
272 changeLogicalTop = 0;
273 changeLogicalBottom = std::max(changeLogicalBottom, logicalBottom);
278 auto end = floatMap.end();
279 for (auto it = floatMap.begin(); it != end; ++it) {
280 const auto& floatingObject = *it->value.get();
281 if (!floatingObject.isDescendant()) {
282 changeLogicalTop = 0;
283 changeLogicalBottom = std::max(changeLogicalBottom, logicalBottomForFloat(floatingObject));
287 markLinesDirtyInBlockRange(changeLogicalTop, changeLogicalBottom);
288 } else if (!oldIntrudingFloatSet.isEmpty()) {
289 // If there are previously intruding floats that no longer intrude, then children with floats
290 // should also get layout because they might need their floating object lists cleared.
291 if (m_floatingObjects->set().size() < oldIntrudingFloatSet.size())
292 markAllDescendantsWithFloatsForLayout();
294 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
295 auto end = floatingObjectSet.end();
296 for (auto it = floatingObjectSet.begin(); it != end && !oldIntrudingFloatSet.isEmpty(); ++it)
297 oldIntrudingFloatSet.remove(&(*it)->renderer());
298 if (!oldIntrudingFloatSet.isEmpty())
299 markAllDescendantsWithFloatsForLayout();
304 void RenderBlockFlow::adjustIntrinsicLogicalWidthsForColumns(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
306 if (!style().hasAutoColumnCount() || !style().hasAutoColumnWidth()) {
307 // The min/max intrinsic widths calculated really tell how much space elements need when
308 // laid out inside the columns. In order to eventually end up with the desired column width,
309 // we need to convert them to values pertaining to the multicol container.
310 int columnCount = style().hasAutoColumnCount() ? 1 : style().columnCount();
311 LayoutUnit columnWidth;
312 LayoutUnit colGap = columnGap();
313 LayoutUnit gapExtra = (columnCount - 1) * colGap;
314 if (style().hasAutoColumnWidth())
315 minLogicalWidth = minLogicalWidth * columnCount + gapExtra;
317 columnWidth = style().columnWidth();
318 minLogicalWidth = std::min(minLogicalWidth, columnWidth);
320 // FIXME: If column-count is auto here, we should resolve it to calculate the maximum
321 // intrinsic width, instead of pretending that it's 1. The only way to do that is by
322 // performing a layout pass, but this is not an appropriate time or place for layout. The
323 // good news is that if height is unconstrained and there are no explicit breaks, the
324 // resolved column-count really should be 1.
325 maxLogicalWidth = std::max(maxLogicalWidth, columnWidth) * columnCount + gapExtra;
329 void RenderBlockFlow::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
331 if (childrenInline())
332 computeInlinePreferredLogicalWidths(minLogicalWidth, maxLogicalWidth);
334 computeBlockPreferredLogicalWidths(minLogicalWidth, maxLogicalWidth);
336 maxLogicalWidth = std::max(minLogicalWidth, maxLogicalWidth);
338 adjustIntrinsicLogicalWidthsForColumns(minLogicalWidth, maxLogicalWidth);
340 if (!style().autoWrap() && childrenInline()) {
341 // A horizontal marquee with inline children has no minimum width.
342 if (layer() && layer()->marquee() && layer()->marquee()->isHorizontal())
346 if (is<RenderTableCell>(*this)) {
347 Length tableCellWidth = downcast<RenderTableCell>(*this).styleOrColLogicalWidth();
348 if (tableCellWidth.isFixed() && tableCellWidth.value() > 0)
349 maxLogicalWidth = std::max(minLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(tableCellWidth.value()));
352 int scrollbarWidth = intrinsicScrollbarLogicalWidth();
353 maxLogicalWidth += scrollbarWidth;
354 minLogicalWidth += scrollbarWidth;
357 bool RenderBlockFlow::recomputeLogicalWidthAndColumnWidth()
359 bool changed = recomputeLogicalWidth();
361 LayoutUnit oldColumnWidth = computedColumnWidth();
362 computeColumnCountAndWidth();
364 return changed || oldColumnWidth != computedColumnWidth();
367 LayoutUnit RenderBlockFlow::columnGap() const
369 if (style().columnGap().isNormal())
370 return style().fontDescription().computedPixelSize(); // "1em" is recommended as the normal gap setting. Matches <p> margins.
371 return valueForLength(style().columnGap().length(), availableLogicalWidth());
374 void RenderBlockFlow::computeColumnCountAndWidth()
376 // Calculate our column width and column count.
377 // FIXME: Can overflow on fast/block/float/float-not-removed-from-next-sibling4.html, see https://bugs.webkit.org/show_bug.cgi?id=68744
378 unsigned desiredColumnCount = 1;
379 LayoutUnit desiredColumnWidth = contentLogicalWidth();
381 // For now, we don't support multi-column layouts when printing, since we have to do a lot of work for proper pagination.
382 if (document().paginated() || (style().hasAutoColumnCount() && style().hasAutoColumnWidth()) || !style().hasInlineColumnAxis()) {
383 setComputedColumnCountAndWidth(desiredColumnCount, desiredColumnWidth);
387 LayoutUnit availWidth = desiredColumnWidth;
388 LayoutUnit colGap = columnGap();
389 LayoutUnit colWidth = std::max<LayoutUnit>(1, style().columnWidth());
390 unsigned colCount = std::max<unsigned>(1, style().columnCount());
392 if (style().hasAutoColumnWidth() && !style().hasAutoColumnCount()) {
393 desiredColumnCount = colCount;
394 desiredColumnWidth = std::max<LayoutUnit>(0, (availWidth - ((desiredColumnCount - 1) * colGap)) / desiredColumnCount);
395 } else if (!style().hasAutoColumnWidth() && style().hasAutoColumnCount()) {
396 desiredColumnCount = std::max<unsigned>(1, ((availWidth + colGap) / (colWidth + colGap)).toUnsigned());
397 desiredColumnWidth = ((availWidth + colGap) / desiredColumnCount) - colGap;
399 desiredColumnCount = std::max<unsigned>(std::min(colCount, ((availWidth + colGap) / (colWidth + colGap)).toUnsigned()), 1);
400 desiredColumnWidth = ((availWidth + colGap) / desiredColumnCount) - colGap;
402 setComputedColumnCountAndWidth(desiredColumnCount, desiredColumnWidth);
405 bool RenderBlockFlow::willCreateColumns(std::optional<unsigned> desiredColumnCount) const
407 // The following types are not supposed to create multicol context.
408 if (isFileUploadControl() || isTextControl() || isListBox())
410 if (isRenderSVGBlock() || isRubyRun())
413 if (isRenderMathMLBlock())
415 #endif // ENABLE(MATHML)
420 if (style().styleType() != NOPSEUDO)
423 // If overflow-y is set to paged-x or paged-y on the body or html element, we'll handle the paginating in the RenderView instead.
424 if ((style().overflowY() == OPAGEDX || style().overflowY() == OPAGEDY) && !(isDocumentElementRenderer() || isBody()))
427 // Lines clamping creates columns.
428 if (style().hasLinesClamp())
431 if (!style().specifiesColumns())
434 // column-axis with opposite writing direction initiates MultiColumnFlow.
435 if (!style().hasInlineColumnAxis())
438 // Non-auto column-width always initiates MultiColumnFlow.
439 if (!style().hasAutoColumnWidth())
442 if (desiredColumnCount)
443 return desiredColumnCount.value() > 1;
445 // column-count > 1 always initiates MultiColumnFlow.
446 if (!style().hasAutoColumnCount())
447 return style().columnCount() > 1;
449 ASSERT_NOT_REACHED();
453 void RenderBlockFlow::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight)
455 ASSERT(needsLayout());
457 if (!relayoutChildren && simplifiedLayout())
460 LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
462 if (recomputeLogicalWidthAndColumnWidth())
463 relayoutChildren = true;
465 rebuildFloatingObjectSetFromIntrudingFloats();
467 LayoutUnit previousHeight = logicalHeight();
468 // FIXME: should this start out as borderAndPaddingLogicalHeight() + scrollbarLogicalHeight(),
469 // for consistency with other render classes?
472 bool pageLogicalHeightChanged = false;
473 checkForPaginationLogicalHeightChange(relayoutChildren, pageLogicalHeight, pageLogicalHeightChanged);
475 LayoutUnit repaintLogicalTop = 0;
476 LayoutUnit repaintLogicalBottom = 0;
477 LayoutUnit maxFloatLogicalBottom = 0;
478 const RenderStyle& styleToUse = style();
480 LayoutStateMaintainer statePusher(*this, locationOffset(), hasTransform() || hasReflection() || styleToUse.isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged);
482 preparePaginationBeforeBlockLayout(relayoutChildren);
484 // We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
485 // our current maximal positive and negative margins. These values are used when we
486 // are collapsed with adjacent blocks, so for example, if you have block A and B
487 // collapsing together, then you'd take the maximal positive margin from both A and B
488 // and subtract it from the maximal negative margin from both A and B to get the
489 // true collapsed margin. This algorithm is recursive, so when we finish layout()
490 // our block knows its current maximal positive/negative values.
492 // Start out by setting our margin values to our current margins. Table cells have
493 // no margins, so we don't fill in the values for table cells.
494 bool isCell = isTableCell();
496 initMaxMarginValues();
498 setHasMarginBeforeQuirk(styleToUse.hasMarginBeforeQuirk());
499 setHasMarginAfterQuirk(styleToUse.hasMarginAfterQuirk());
500 setPaginationStrut(0);
502 if (!firstChild() && !isAnonymousBlock())
503 setChildrenInline(true);
504 if (childrenInline())
505 layoutInlineChildren(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
507 layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom);
510 // Expand our intrinsic height to encompass floats.
511 LayoutUnit toAdd = borderAndPaddingAfter() + scrollbarLogicalHeight();
512 if (lowestFloatLogicalBottom() > (logicalHeight() - toAdd) && createsNewFormattingContext())
513 setLogicalHeight(lowestFloatLogicalBottom() + toAdd);
514 if (relayoutForPagination() || relayoutToAvoidWidows()) {
515 ASSERT(!shouldBreakAtLineToAvoidWidow());
519 // Calculate our new height.
520 LayoutUnit oldHeight = logicalHeight();
521 LayoutUnit oldClientAfterEdge = clientLogicalBottom();
523 // Before updating the final size of the flow thread make sure a forced break is applied after the content.
524 // This ensures the size information is correctly computed for the last auto-height fragment receiving content.
525 if (is<RenderFragmentedFlow>(*this))
526 downcast<RenderFragmentedFlow>(*this).applyBreakAfterContent(oldClientAfterEdge);
528 updateLogicalHeight();
529 LayoutUnit newHeight = logicalHeight();
531 // FIXME: This could be removed once relayoutForPagination()/relayoutToAvoidWidows() either stop recursing or we manage to
533 LayoutStateMaintainer statePusher(*this, locationOffset(), hasTransform() || hasReflection() || styleToUse.isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged);
535 if (oldHeight != newHeight) {
536 if (oldHeight > newHeight && maxFloatLogicalBottom > newHeight && !childrenInline()) {
537 // One of our children's floats may have become an overhanging float for us. We need to look for it.
538 for (auto& blockFlow : childrenOfType<RenderBlockFlow>(*this)) {
539 if (blockFlow.isFloatingOrOutOfFlowPositioned())
541 if (blockFlow.lowestFloatLogicalBottom() + blockFlow.logicalTop() > newHeight)
542 addOverhangingFloats(blockFlow, false);
547 bool heightChanged = (previousHeight != newHeight);
549 relayoutChildren = true;
550 layoutPositionedObjects(relayoutChildren || isDocumentElementRenderer());
552 // Add overflow from children (unless we're multi-column, since in that case all our child overflow is clipped anyway).
553 computeOverflow(oldClientAfterEdge);
555 fitBorderToLinesIfNeeded();
557 auto* state = view().frameView().layoutContext().layoutState();
558 if (state && state->pageLogicalHeight())
559 setPageLogicalOffset(state->pageLogicalOffset(this, logicalTop()));
561 updateLayerTransform();
563 // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
564 // we overflow or not.
565 updateScrollInfoAfterLayout();
567 // FIXME: This repaint logic should be moved into a separate helper function!
568 // Repaint with our new bounds if they are different from our old bounds.
569 bool didFullRepaint = repainter.repaintAfterLayout();
570 if (!didFullRepaint && repaintLogicalTop != repaintLogicalBottom && (styleToUse.visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
571 // FIXME: We could tighten up the left and right invalidation points if we let layoutInlineChildren fill them in based off the particular lines
572 // it had to lay out. We wouldn't need the hasOverflowClip() hack in that case either.
573 LayoutUnit repaintLogicalLeft = logicalLeftVisualOverflow();
574 LayoutUnit repaintLogicalRight = logicalRightVisualOverflow();
575 if (hasOverflowClip()) {
576 // If we have clipped overflow, we should use layout overflow as well, since visual overflow from lines didn't propagate to our block's overflow.
577 // Note the old code did this as well but even for overflow:visible. The addition of hasOverflowClip() at least tightens up the hack a bit.
578 // layoutInlineChildren should be patched to compute the entire repaint rect.
579 repaintLogicalLeft = std::min(repaintLogicalLeft, logicalLeftLayoutOverflow());
580 repaintLogicalRight = std::max(repaintLogicalRight, logicalRightLayoutOverflow());
583 LayoutRect repaintRect;
584 if (isHorizontalWritingMode())
585 repaintRect = LayoutRect(repaintLogicalLeft, repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop);
587 repaintRect = LayoutRect(repaintLogicalTop, repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft);
589 if (hasOverflowClip()) {
590 // Adjust repaint rect for scroll offset
591 repaintRect.moveBy(-scrollPosition());
593 // Don't allow this rect to spill out of our overflow box.
594 repaintRect.intersect(LayoutRect(LayoutPoint(), size()));
597 // Make sure the rect is still non-empty after intersecting for overflow above
598 if (!repaintRect.isEmpty()) {
599 repaintRectangle(repaintRect); // We need to do a partial repaint of our content.
601 repaintRectangle(reflectedRect(repaintRect));
608 void RenderBlockFlow::layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom)
610 dirtyForLayoutFromPercentageHeightDescendants();
612 LayoutUnit beforeEdge = borderAndPaddingBefore();
613 LayoutUnit afterEdge = borderAndPaddingAfter() + scrollbarLogicalHeight();
615 setLogicalHeight(beforeEdge);
617 // Lay out our hypothetical grid line as though it occurs at the top of the block.
618 if (view().frameView().layoutContext().layoutState()->lineGrid() == this)
621 // The margin struct caches all our current margin collapsing state.
622 MarginInfo marginInfo(*this, beforeEdge, afterEdge);
624 // Fieldsets need to find their legend and position it inside the border of the object.
625 // The legend then gets skipped during normal layout. The same is true for ruby text.
626 // It doesn't get included in the normal layout process but is instead skipped.
627 layoutExcludedChildren(relayoutChildren);
629 LayoutUnit previousFloatLogicalBottom = 0;
630 maxFloatLogicalBottom = 0;
632 RenderBox* next = firstChildBox();
635 RenderBox& child = *next;
636 next = child.nextSiblingBox();
638 if (child.isExcludedFromNormalLayout())
639 continue; // Skip this child, since it will be positioned by the specialized subclass (fieldsets and ruby runs).
641 updateBlockChildDirtyBitsBeforeLayout(relayoutChildren, child);
643 if (child.isOutOfFlowPositioned()) {
644 child.containingBlock()->insertPositionedObject(child);
645 adjustPositionedBlock(child, marginInfo);
648 if (child.isFloating()) {
649 insertFloatingObject(child);
650 adjustFloatingBlock(marginInfo);
654 // Lay out the child.
655 layoutBlockChild(child, marginInfo, previousFloatLogicalBottom, maxFloatLogicalBottom);
658 // Now do the handling of the bottom of the block, adding in our bottom border/padding and
659 // determining the correct collapsed bottom margin information.
660 handleAfterSideOfBlock(beforeEdge, afterEdge, marginInfo);
663 void RenderBlockFlow::layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom)
665 if (lineLayoutPath() == UndeterminedPath)
666 setLineLayoutPath(SimpleLineLayout::canUseFor(*this) ? SimpleLinesPath : LineBoxesPath);
668 if (lineLayoutPath() == SimpleLinesPath) {
669 layoutSimpleLines(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
673 m_simpleLineLayout = nullptr;
674 layoutLineBoxes(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
677 void RenderBlockFlow::layoutBlockChild(RenderBox& child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom)
679 LayoutUnit oldPosMarginBefore = maxPositiveMarginBefore();
680 LayoutUnit oldNegMarginBefore = maxNegativeMarginBefore();
682 // The child is a normal flow object. Compute the margins we will use for collapsing now.
683 child.computeAndSetBlockDirectionMargins(*this);
685 // Try to guess our correct logical top position. In most cases this guess will
686 // be correct. Only if we're wrong (when we compute the real logical top position)
687 // will we have to potentially relayout.
688 LayoutUnit estimateWithoutPagination;
689 LayoutUnit logicalTopEstimate = estimateLogicalTopPosition(child, marginInfo, estimateWithoutPagination);
691 // Cache our old rect so that we can dirty the proper repaint rects if the child moves.
692 LayoutRect oldRect = child.frameRect();
693 LayoutUnit oldLogicalTop = logicalTopForChild(child);
696 LayoutSize oldLayoutDelta = view().frameView().layoutContext().layoutDelta();
698 // Position the child as though it didn't collapse with the top.
699 setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
700 estimateFragmentRangeForBoxChild(child);
702 RenderBlockFlow* childBlockFlow = is<RenderBlockFlow>(child) ? &downcast<RenderBlockFlow>(child) : nullptr;
703 bool markDescendantsWithFloats = false;
704 if (logicalTopEstimate != oldLogicalTop && !child.avoidsFloats() && childBlockFlow && childBlockFlow->containsFloats())
705 markDescendantsWithFloats = true;
706 else if (UNLIKELY(logicalTopEstimate.mightBeSaturated()))
707 // logicalTopEstimate, returned by estimateLogicalTopPosition, might be saturated for
708 // very large elements. If it does the comparison with oldLogicalTop might yield a
709 // false negative as adding and removing margins, borders etc from a saturated number
710 // might yield incorrect results. If this is the case always mark for layout.
711 markDescendantsWithFloats = true;
712 else if (!child.avoidsFloats() || child.shrinkToAvoidFloats()) {
713 // If an element might be affected by the presence of floats, then always mark it for
715 LayoutUnit fb = std::max(previousFloatLogicalBottom, lowestFloatLogicalBottom());
716 if (fb > logicalTopEstimate)
717 markDescendantsWithFloats = true;
720 if (childBlockFlow) {
721 if (markDescendantsWithFloats)
722 childBlockFlow->markAllDescendantsWithFloatsForLayout();
723 if (!child.isWritingModeRoot())
724 previousFloatLogicalBottom = std::max(previousFloatLogicalBottom, oldLogicalTop + childBlockFlow->lowestFloatLogicalBottom());
727 child.markForPaginationRelayoutIfNeeded();
729 bool childHadLayout = child.everHadLayout();
730 bool childNeededLayout = child.needsLayout();
731 if (childNeededLayout)
734 // Cache if we are at the top of the block right now.
735 bool atBeforeSideOfBlock = marginInfo.atBeforeSideOfBlock();
737 // Now determine the correct ypos based off examination of collapsing margin
739 LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo);
741 // Now check for clear.
742 LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear);
744 bool paginated = view().frameView().layoutContext().layoutState()->isPaginated();
746 logicalTopAfterClear = adjustBlockChildForPagination(logicalTopAfterClear, estimateWithoutPagination, child, atBeforeSideOfBlock && logicalTopBeforeClear == logicalTopAfterClear);
748 setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
750 // Now we have a final top position. See if it really does end up being different from our estimate.
751 // clearFloatsIfNeeded can also mark the child as needing a layout even though we didn't move. This happens
752 // when collapseMargins dynamically adds overhanging floats because of a child with negative margins.
753 if (logicalTopAfterClear != logicalTopEstimate || child.needsLayout() || (paginated && childBlockFlow && childBlockFlow->shouldBreakAtLineToAvoidWidow())) {
754 if (child.shrinkToAvoidFloats()) {
755 // The child's width depends on the line width. When the child shifts to clear an item, its width can
756 // change (because it has more available line width). So mark the item as dirty.
757 child.setChildNeedsLayout(MarkOnlyThis);
760 if (childBlockFlow) {
761 if (!child.avoidsFloats() && childBlockFlow->containsFloats())
762 childBlockFlow->markAllDescendantsWithFloatsForLayout();
763 child.markForPaginationRelayoutIfNeeded();
767 if (updateFragmentRangeForBoxChild(child))
768 child.setNeedsLayout(MarkOnlyThis);
770 // In case our guess was wrong, relayout the child.
771 child.layoutIfNeeded();
773 // We are no longer at the top of the block if we encounter a non-empty child.
774 // This has to be done after checking for clear, so that margins can be reset if a clear occurred.
775 if (marginInfo.atBeforeSideOfBlock() && !child.isSelfCollapsingBlock())
776 marginInfo.setAtBeforeSideOfBlock(false);
778 // Now place the child in the correct left position
779 determineLogicalLeftPositionForChild(child, ApplyLayoutDelta);
781 // Update our height now that the child has been placed in the correct position.
782 setLogicalHeight(logicalHeight() + logicalHeightForChildForFragmentation(child));
783 if (mustSeparateMarginAfterForChild(child)) {
784 setLogicalHeight(logicalHeight() + marginAfterForChild(child));
785 marginInfo.clearMargin();
787 // If the child has overhanging floats that intrude into following siblings (or possibly out
788 // of this block), then the parent gets notified of the floats now.
789 if (childBlockFlow && childBlockFlow->containsFloats())
790 maxFloatLogicalBottom = std::max(maxFloatLogicalBottom, addOverhangingFloats(*childBlockFlow, !childNeededLayout));
792 LayoutSize childOffset = child.location() - oldRect.location();
793 if (childOffset.width() || childOffset.height()) {
794 view().frameView().layoutContext().addLayoutDelta(childOffset);
796 // If the child moved, we have to repaint it as well as any floating/positioned
797 // descendants. An exception is if we need a layout. In this case, we know we're going to
798 // repaint ourselves (and the child) anyway.
799 if (childHadLayout && !selfNeedsLayout() && child.checkForRepaintDuringLayout())
800 child.repaintDuringLayoutIfMoved(oldRect);
803 if (!childHadLayout && child.checkForRepaintDuringLayout()) {
805 child.repaintOverhangingFloats(true);
809 if (RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow())
810 fragmentedFlow->fragmentedFlowDescendantBoxLaidOut(&child);
811 // Check for an after page/column break.
812 LayoutUnit newHeight = applyAfterBreak(child, logicalHeight(), marginInfo);
813 if (newHeight != height())
814 setLogicalHeight(newHeight);
817 ASSERT(view().frameView().layoutContext().layoutDeltaMatches(oldLayoutDelta));
820 void RenderBlockFlow::adjustPositionedBlock(RenderBox& child, const MarginInfo& marginInfo)
822 bool isHorizontal = isHorizontalWritingMode();
823 bool hasStaticBlockPosition = child.style().hasStaticBlockPosition(isHorizontal);
825 LayoutUnit logicalTop = logicalHeight();
826 updateStaticInlinePositionForChild(child, logicalTop, DoNotIndentText);
828 if (!marginInfo.canCollapseWithMarginBefore()) {
829 // Positioned blocks don't collapse margins, so add the margin provided by
830 // the container now. The child's own margin is added later when calculating its logical top.
831 LayoutUnit collapsedBeforePos = marginInfo.positiveMargin();
832 LayoutUnit collapsedBeforeNeg = marginInfo.negativeMargin();
833 logicalTop += collapsedBeforePos - collapsedBeforeNeg;
836 RenderLayer* childLayer = child.layer();
837 if (childLayer->staticBlockPosition() != logicalTop) {
838 childLayer->setStaticBlockPosition(logicalTop);
839 if (hasStaticBlockPosition)
840 child.setChildNeedsLayout(MarkOnlyThis);
844 LayoutUnit RenderBlockFlow::marginOffsetForSelfCollapsingBlock()
846 ASSERT(isSelfCollapsingBlock());
847 RenderBlockFlow* parentBlock = downcast<RenderBlockFlow>(parent());
848 if (parentBlock && style().clear() && parentBlock->getClearDelta(*this, logicalHeight()))
849 return marginValuesForChild(*this).positiveMarginBefore();
853 void RenderBlockFlow::determineLogicalLeftPositionForChild(RenderBox& child, ApplyLayoutDeltaMode applyDelta)
855 LayoutUnit startPosition = borderStart() + paddingStart();
856 if (shouldPlaceBlockDirectionScrollbarOnLeft())
857 startPosition += (style().isLeftToRightDirection() ? 1 : -1) * verticalScrollbarWidth();
858 LayoutUnit totalAvailableLogicalWidth = borderAndPaddingLogicalWidth() + availableLogicalWidth();
860 // Add in our start margin.
861 LayoutUnit childMarginStart = marginStartForChild(child);
862 LayoutUnit newPosition = startPosition + childMarginStart;
864 // Some objects (e.g., tables, horizontal rules, overflow:auto blocks) avoid floats. They need
865 // to shift over as necessary to dodge any floats that might get in the way.
866 if (child.avoidsFloats() && containsFloats())
867 newPosition += computeStartPositionDeltaForChildAvoidingFloats(child, marginStartForChild(child));
869 setLogicalLeftForChild(child, style().isLeftToRightDirection() ? newPosition : totalAvailableLogicalWidth - newPosition - logicalWidthForChild(child), applyDelta);
872 void RenderBlockFlow::adjustFloatingBlock(const MarginInfo& marginInfo)
874 // The float should be positioned taking into account the bottom margin
875 // of the previous flow. We add that margin into the height, get the
876 // float positioned properly, and then subtract the margin out of the
877 // height again. In the case of self-collapsing blocks, we always just
878 // use the top margins, since the self-collapsing block collapsed its
879 // own bottom margin into its top margin.
881 // Note also that the previous flow may collapse its margin into the top of
882 // our block. If this is the case, then we do not add the margin in to our
883 // height when computing the position of the float. This condition can be tested
884 // for by simply calling canCollapseWithMarginBefore. See
885 // http://www.hixie.ch/tests/adhoc/css/box/block/margin-collapse/046.html for
886 // an example of this scenario.
887 LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
888 setLogicalHeight(logicalHeight() + marginOffset);
890 setLogicalHeight(logicalHeight() - marginOffset);
893 void RenderBlockFlow::updateStaticInlinePositionForChild(RenderBox& child, LayoutUnit logicalTop, IndentTextOrNot shouldIndentText)
895 if (child.style().isOriginalDisplayInlineType())
896 setStaticInlinePositionForChild(child, logicalTop, startAlignedOffsetForLine(logicalTop, shouldIndentText));
898 setStaticInlinePositionForChild(child, logicalTop, startOffsetForContent(logicalTop));
901 void RenderBlockFlow::setStaticInlinePositionForChild(RenderBox& child, LayoutUnit blockOffset, LayoutUnit inlinePosition)
903 if (enclosingFragmentedFlow()) {
904 // Shift the inline position to exclude the fragment offset.
905 inlinePosition += startOffsetForContent() - startOffsetForContent(blockOffset);
907 child.layer()->setStaticInlinePosition(inlinePosition);
910 RenderBlockFlow::MarginValues RenderBlockFlow::marginValuesForChild(RenderBox& child) const
912 LayoutUnit childBeforePositive = 0;
913 LayoutUnit childBeforeNegative = 0;
914 LayoutUnit childAfterPositive = 0;
915 LayoutUnit childAfterNegative = 0;
917 LayoutUnit beforeMargin = 0;
918 LayoutUnit afterMargin = 0;
920 RenderBlockFlow* childRenderBlock = is<RenderBlockFlow>(child) ? &downcast<RenderBlockFlow>(child) : nullptr;
922 // If the child has the same directionality as we do, then we can just return its
923 // margins in the same direction.
924 if (!child.isWritingModeRoot()) {
925 if (childRenderBlock) {
926 childBeforePositive = childRenderBlock->maxPositiveMarginBefore();
927 childBeforeNegative = childRenderBlock->maxNegativeMarginBefore();
928 childAfterPositive = childRenderBlock->maxPositiveMarginAfter();
929 childAfterNegative = childRenderBlock->maxNegativeMarginAfter();
931 beforeMargin = child.marginBefore();
932 afterMargin = child.marginAfter();
934 } else if (child.isHorizontalWritingMode() == isHorizontalWritingMode()) {
935 // The child has a different directionality. If the child is parallel, then it's just
936 // flipped relative to us. We can use the margins for the opposite edges.
937 if (childRenderBlock) {
938 childBeforePositive = childRenderBlock->maxPositiveMarginAfter();
939 childBeforeNegative = childRenderBlock->maxNegativeMarginAfter();
940 childAfterPositive = childRenderBlock->maxPositiveMarginBefore();
941 childAfterNegative = childRenderBlock->maxNegativeMarginBefore();
943 beforeMargin = child.marginAfter();
944 afterMargin = child.marginBefore();
947 // The child is perpendicular to us, which means its margins don't collapse but are on the
948 // "logical left/right" sides of the child box. We can just return the raw margin in this case.
949 beforeMargin = marginBeforeForChild(child);
950 afterMargin = marginAfterForChild(child);
953 // Resolve uncollapsing margins into their positive/negative buckets.
955 if (beforeMargin > 0)
956 childBeforePositive = beforeMargin;
958 childBeforeNegative = -beforeMargin;
962 childAfterPositive = afterMargin;
964 childAfterNegative = -afterMargin;
967 return MarginValues(childBeforePositive, childBeforeNegative, childAfterPositive, childAfterNegative);
970 bool RenderBlockFlow::childrenPreventSelfCollapsing() const
972 if (!childrenInline())
973 return RenderBlock::childrenPreventSelfCollapsing();
978 LayoutUnit RenderBlockFlow::collapseMargins(RenderBox& child, MarginInfo& marginInfo)
980 return collapseMarginsWithChildInfo(&child, child.previousSibling(), marginInfo);
983 LayoutUnit RenderBlockFlow::collapseMarginsWithChildInfo(RenderBox* child, RenderObject* prevSibling, MarginInfo& marginInfo)
985 bool childDiscardMarginBefore = child ? mustDiscardMarginBeforeForChild(*child) : false;
986 bool childDiscardMarginAfter = child ? mustDiscardMarginAfterForChild(*child) : false;
987 bool childIsSelfCollapsing = child ? child->isSelfCollapsingBlock() : false;
988 bool beforeQuirk = child ? hasMarginBeforeQuirk(*child) : false;
989 bool afterQuirk = child ? hasMarginAfterQuirk(*child) : false;
991 // The child discards the before margin when the after margin has discarded in the case of a self collapsing block.
992 childDiscardMarginBefore = childDiscardMarginBefore || (childDiscardMarginAfter && childIsSelfCollapsing);
994 // Get the four margin values for the child and cache them.
995 const MarginValues childMargins = child ? marginValuesForChild(*child) : MarginValues(0, 0, 0, 0);
997 // Get our max pos and neg top margins.
998 LayoutUnit posTop = childMargins.positiveMarginBefore();
999 LayoutUnit negTop = childMargins.negativeMarginBefore();
1001 // For self-collapsing blocks, collapse our bottom margins into our
1002 // top to get new posTop and negTop values.
1003 if (childIsSelfCollapsing) {
1004 posTop = std::max(posTop, childMargins.positiveMarginAfter());
1005 negTop = std::max(negTop, childMargins.negativeMarginAfter());
1008 if (marginInfo.canCollapseWithMarginBefore()) {
1009 if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
1010 // This child is collapsing with the top of the
1011 // block. If it has larger margin values, then we need to update
1012 // our own maximal values.
1013 if (!document().inQuirksMode() || !marginInfo.quirkContainer() || !beforeQuirk)
1014 setMaxMarginBeforeValues(std::max(posTop, maxPositiveMarginBefore()), std::max(negTop, maxNegativeMarginBefore()));
1016 // The minute any of the margins involved isn't a quirk, don't
1017 // collapse it away, even if the margin is smaller (www.webreference.com
1018 // has an example of this, a <dt> with 0.8em author-specified inside
1019 // a <dl> inside a <td>.
1020 if (!marginInfo.determinedMarginBeforeQuirk() && !beforeQuirk && (posTop - negTop)) {
1021 setHasMarginBeforeQuirk(false);
1022 marginInfo.setDeterminedMarginBeforeQuirk(true);
1025 if (!marginInfo.determinedMarginBeforeQuirk() && beforeQuirk && !marginBefore()) {
1026 // We have no top margin and our top child has a quirky margin.
1027 // We will pick up this quirky margin and pass it through.
1028 // This deals with the <td><div><p> case.
1029 // Don't do this for a block that split two inlines though. You do
1030 // still apply margins in this case.
1031 setHasMarginBeforeQuirk(true);
1034 // The before margin of the container will also discard all the margins it is collapsing with.
1035 setMustDiscardMarginBefore();
1038 // Once we find a child with discardMarginBefore all the margins collapsing with us must also discard.
1039 if (childDiscardMarginBefore) {
1040 marginInfo.setDiscardMargin(true);
1041 marginInfo.clearMargin();
1044 if (marginInfo.quirkContainer() && marginInfo.atBeforeSideOfBlock() && (posTop - negTop))
1045 marginInfo.setHasMarginBeforeQuirk(beforeQuirk);
1047 LayoutUnit beforeCollapseLogicalTop = logicalHeight();
1048 LayoutUnit logicalTop = beforeCollapseLogicalTop;
1050 LayoutUnit clearanceForSelfCollapsingBlock;
1052 // If the child's previous sibling is a self-collapsing block that cleared a float then its top border edge has been set at the bottom border edge
1053 // of the float. Since we want to collapse the child's top margin with the self-collapsing block's top and bottom margins we need to adjust our parent's height to match the
1054 // margin top of the self-collapsing block. If the resulting collapsed margin leaves the child still intruding into the float then we will want to clear it.
1055 if (!marginInfo.canCollapseWithMarginBefore() && is<RenderBlockFlow>(prevSibling) && downcast<RenderBlockFlow>(*prevSibling).isSelfCollapsingBlock()) {
1056 clearanceForSelfCollapsingBlock = downcast<RenderBlockFlow>(*prevSibling).marginOffsetForSelfCollapsingBlock();
1057 setLogicalHeight(logicalHeight() - clearanceForSelfCollapsingBlock);
1060 if (childIsSelfCollapsing) {
1061 // For a self collapsing block both the before and after margins get discarded. The block doesn't contribute anything to the height of the block.
1062 // Also, the child's top position equals the logical height of the container.
1063 if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
1064 // This child has no height. We need to compute our
1065 // position before we collapse the child's margins together,
1066 // so that we can get an accurate position for the zero-height block.
1067 LayoutUnit collapsedBeforePos = std::max(marginInfo.positiveMargin(), childMargins.positiveMarginBefore());
1068 LayoutUnit collapsedBeforeNeg = std::max(marginInfo.negativeMargin(), childMargins.negativeMarginBefore());
1069 marginInfo.setMargin(collapsedBeforePos, collapsedBeforeNeg);
1071 // Now collapse the child's margins together, which means examining our
1072 // bottom margin values as well.
1073 marginInfo.setPositiveMarginIfLarger(childMargins.positiveMarginAfter());
1074 marginInfo.setNegativeMarginIfLarger(childMargins.negativeMarginAfter());
1076 if (!marginInfo.canCollapseWithMarginBefore())
1077 // We need to make sure that the position of the self-collapsing block
1078 // is correct, since it could have overflowing content
1079 // that needs to be positioned correctly (e.g., a block that
1080 // had a specified height of 0 but that actually had subcontent).
1081 logicalTop = logicalHeight() + collapsedBeforePos - collapsedBeforeNeg;
1084 if (child && mustSeparateMarginBeforeForChild(*child)) {
1085 ASSERT(!marginInfo.discardMargin() || (marginInfo.discardMargin() && !marginInfo.margin()));
1086 // If we are at the before side of the block and we collapse, ignore the computed margin
1087 // and just add the child margin to the container height. This will correctly position
1088 // the child inside the container.
1089 LayoutUnit separateMargin = !marginInfo.canCollapseWithMarginBefore() ? marginInfo.margin() : LayoutUnit::fromPixel(0);
1090 setLogicalHeight(logicalHeight() + separateMargin + marginBeforeForChild(*child));
1091 logicalTop = logicalHeight();
1092 } else if (!marginInfo.discardMargin() && (!marginInfo.atBeforeSideOfBlock()
1093 || (!marginInfo.canCollapseMarginBeforeWithChildren()
1094 && (!document().inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginBeforeQuirk())))) {
1095 // We're collapsing with a previous sibling's margins and not
1096 // with the top of the block.
1097 setLogicalHeight(logicalHeight() + std::max(marginInfo.positiveMargin(), posTop) - std::max(marginInfo.negativeMargin(), negTop));
1098 logicalTop = logicalHeight();
1101 marginInfo.setDiscardMargin(childDiscardMarginAfter);
1103 if (!marginInfo.discardMargin()) {
1104 marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
1105 marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
1107 marginInfo.clearMargin();
1109 if (marginInfo.margin())
1110 marginInfo.setHasMarginAfterQuirk(afterQuirk);
1113 // If margins would pull us past the top of the next page, then we need to pull back and pretend like the margins
1114 // collapsed into the page edge.
1115 auto* layoutState = view().frameView().layoutContext().layoutState();
1116 if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTop > beforeCollapseLogicalTop
1117 && hasNextPage(beforeCollapseLogicalTop)) {
1118 LayoutUnit oldLogicalTop = logicalTop;
1119 logicalTop = std::min(logicalTop, nextPageLogicalTop(beforeCollapseLogicalTop));
1120 setLogicalHeight(logicalHeight() + (logicalTop - oldLogicalTop));
1123 if (is<RenderBlockFlow>(prevSibling) && !prevSibling->isFloatingOrOutOfFlowPositioned()) {
1124 // If |child| is a self-collapsing block it may have collapsed into a previous sibling and although it hasn't reduced the height of the parent yet
1125 // any floats from the parent will now overhang.
1126 RenderBlockFlow& block = downcast<RenderBlockFlow>(*prevSibling);
1127 LayoutUnit oldLogicalHeight = logicalHeight();
1128 setLogicalHeight(logicalTop);
1129 if (block.containsFloats() && !block.avoidsFloats() && (block.logicalTop() + block.lowestFloatLogicalBottom()) > logicalTop)
1130 addOverhangingFloats(block, false);
1131 setLogicalHeight(oldLogicalHeight);
1133 // If |child|'s previous sibling is a self-collapsing block that cleared a float and margin collapsing resulted in |child| moving up
1134 // into the margin area of the self-collapsing block then the float it clears is now intruding into |child|. Layout again so that we can look for
1135 // floats in the parent that overhang |child|'s new logical top.
1136 bool logicalTopIntrudesIntoFloat = clearanceForSelfCollapsingBlock > 0 && logicalTop < beforeCollapseLogicalTop;
1137 if (child && logicalTopIntrudesIntoFloat && containsFloats() && !child->avoidsFloats() && lowestFloatLogicalBottom() > logicalTop)
1138 child->setNeedsLayout();
1144 LayoutUnit RenderBlockFlow::clearFloatsIfNeeded(RenderBox& child, MarginInfo& marginInfo, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos)
1146 LayoutUnit heightIncrease = getClearDelta(child, yPos);
1147 if (!heightIncrease)
1150 if (child.isSelfCollapsingBlock()) {
1151 bool childDiscardMargin = mustDiscardMarginBeforeForChild(child) || mustDiscardMarginAfterForChild(child);
1153 // For self-collapsing blocks that clear, they can still collapse their
1154 // margins with following siblings. Reset the current margins to represent
1155 // the self-collapsing block's margins only.
1156 // If DISCARD is specified for -webkit-margin-collapse, reset the margin values.
1157 MarginValues childMargins = marginValuesForChild(child);
1158 if (!childDiscardMargin) {
1159 marginInfo.setPositiveMargin(std::max(childMargins.positiveMarginBefore(), childMargins.positiveMarginAfter()));
1160 marginInfo.setNegativeMargin(std::max(childMargins.negativeMarginBefore(), childMargins.negativeMarginAfter()));
1162 marginInfo.clearMargin();
1163 marginInfo.setDiscardMargin(childDiscardMargin);
1166 // "If the top and bottom margins of an element with clearance are adjoining, its margins collapse with
1167 // the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block."
1168 // So the parent's bottom margin cannot collapse through this block or any subsequent self-collapsing blocks. Check subsequent siblings
1169 // for a block with height - if none is found then don't allow the margins to collapse with the parent.
1170 bool wouldCollapseMarginsWithParent = marginInfo.canCollapseMarginAfterWithChildren();
1171 for (RenderBox* curr = child.nextSiblingBox(); curr && wouldCollapseMarginsWithParent; curr = curr->nextSiblingBox()) {
1172 if (!curr->isFloatingOrOutOfFlowPositioned() && !curr->isSelfCollapsingBlock())
1173 wouldCollapseMarginsWithParent = false;
1175 if (wouldCollapseMarginsWithParent)
1176 marginInfo.setCanCollapseMarginAfterWithChildren(false);
1178 // For now set the border-top of |child| flush with the bottom border-edge of the float so it can layout any floating or positioned children of
1179 // its own at the correct vertical position. If subsequent siblings attempt to collapse with |child|'s margins in |collapseMargins| we will
1180 // adjust the height of the parent to |child|'s margin top (which if it is positive sits up 'inside' the float it's clearing) so that all three
1181 // margins can collapse at the correct vertical position.
1182 // Per CSS2.1 we need to ensure that any negative margin-top clears |child| beyond the bottom border-edge of the float so that the top border edge of the child
1183 // (i.e. its clearance) is at a position that satisfies the equation: "the amount of clearance is set so that clearance + margin-top = [height of float],
1184 // i.e., clearance = [height of float] - margin-top".
1185 setLogicalHeight(child.logicalTop() + childMargins.negativeMarginBefore());
1187 // Increase our height by the amount we had to clear.
1188 setLogicalHeight(logicalHeight() + heightIncrease);
1190 if (marginInfo.canCollapseWithMarginBefore()) {
1191 // We can no longer collapse with the top of the block since a clear
1192 // occurred. The empty blocks collapse into the cleared block.
1193 // FIXME: This isn't quite correct. Need clarification for what to do
1194 // if the height the cleared block is offset by is smaller than the
1195 // margins involved.
1196 setMaxMarginBeforeValues(oldTopPosMargin, oldTopNegMargin);
1197 marginInfo.setAtBeforeSideOfBlock(false);
1199 // In case the child discarded the before margin of the block we need to reset the mustDiscardMarginBefore flag to the initial value.
1200 setMustDiscardMarginBefore(style().marginBeforeCollapse() == MDISCARD);
1203 return yPos + heightIncrease;
1206 void RenderBlockFlow::marginBeforeEstimateForChild(RenderBox& child, LayoutUnit& positiveMarginBefore, LayoutUnit& negativeMarginBefore, bool& discardMarginBefore) const
1208 // Give up if in quirks mode and we're a body/table cell and the top margin of the child box is quirky.
1209 // Give up if the child specified -webkit-margin-collapse: separate that prevents collapsing.
1210 // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
1211 if ((document().inQuirksMode() && hasMarginAfterQuirk(child) && (isTableCell() || isBody())) || child.style().marginBeforeCollapse() == MSEPARATE)
1214 // The margins are discarded by a child that specified -webkit-margin-collapse: discard.
1215 // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
1216 if (child.style().marginBeforeCollapse() == MDISCARD) {
1217 positiveMarginBefore = 0;
1218 negativeMarginBefore = 0;
1219 discardMarginBefore = true;
1223 LayoutUnit beforeChildMargin = marginBeforeForChild(child);
1224 positiveMarginBefore = std::max(positiveMarginBefore, beforeChildMargin);
1225 negativeMarginBefore = std::max(negativeMarginBefore, -beforeChildMargin);
1227 if (!is<RenderBlockFlow>(child))
1230 RenderBlockFlow& childBlock = downcast<RenderBlockFlow>(child);
1231 if (childBlock.childrenInline() || childBlock.isWritingModeRoot())
1234 MarginInfo childMarginInfo(childBlock, childBlock.borderAndPaddingBefore(), childBlock.borderAndPaddingAfter());
1235 if (!childMarginInfo.canCollapseMarginBeforeWithChildren())
1238 RenderBox* grandchildBox = childBlock.firstChildBox();
1239 for (; grandchildBox; grandchildBox = grandchildBox->nextSiblingBox()) {
1240 if (!grandchildBox->isFloatingOrOutOfFlowPositioned())
1244 // Give up if there is clearance on the box, since it probably won't collapse into us.
1245 if (!grandchildBox || grandchildBox->style().clear() != CNONE)
1248 // Make sure to update the block margins now for the grandchild box so that we're looking at current values.
1249 if (grandchildBox->needsLayout()) {
1250 grandchildBox->computeAndSetBlockDirectionMargins(*this);
1251 if (is<RenderBlock>(*grandchildBox)) {
1252 RenderBlock& grandchildBlock = downcast<RenderBlock>(*grandchildBox);
1253 grandchildBlock.setHasMarginBeforeQuirk(grandchildBox->style().hasMarginBeforeQuirk());
1254 grandchildBlock.setHasMarginAfterQuirk(grandchildBox->style().hasMarginAfterQuirk());
1258 // Collapse the margin of the grandchild box with our own to produce an estimate.
1259 childBlock.marginBeforeEstimateForChild(*grandchildBox, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
1262 LayoutUnit RenderBlockFlow::estimateLogicalTopPosition(RenderBox& child, const MarginInfo& marginInfo, LayoutUnit& estimateWithoutPagination)
1264 // FIXME: We need to eliminate the estimation of vertical position, because when it's wrong we sometimes trigger a pathological
1265 // relayout if there are intruding floats.
1266 LayoutUnit logicalTopEstimate = logicalHeight();
1267 if (!marginInfo.canCollapseWithMarginBefore()) {
1268 LayoutUnit positiveMarginBefore = 0;
1269 LayoutUnit negativeMarginBefore = 0;
1270 bool discardMarginBefore = false;
1271 if (child.selfNeedsLayout()) {
1272 // Try to do a basic estimation of how the collapse is going to go.
1273 marginBeforeEstimateForChild(child, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
1275 // Use the cached collapsed margin values from a previous layout. Most of the time they
1277 MarginValues marginValues = marginValuesForChild(child);
1278 positiveMarginBefore = std::max(positiveMarginBefore, marginValues.positiveMarginBefore());
1279 negativeMarginBefore = std::max(negativeMarginBefore, marginValues.negativeMarginBefore());
1280 discardMarginBefore = mustDiscardMarginBeforeForChild(child);
1283 // Collapse the result with our current margins.
1284 if (!discardMarginBefore)
1285 logicalTopEstimate += std::max(marginInfo.positiveMargin(), positiveMarginBefore) - std::max(marginInfo.negativeMargin(), negativeMarginBefore);
1288 // Adjust logicalTopEstimate down to the next page if the margins are so large that we don't fit on the current
1290 auto* layoutState = view().frameView().layoutContext().layoutState();
1291 if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTopEstimate > logicalHeight()
1292 && hasNextPage(logicalHeight()))
1293 logicalTopEstimate = std::min(logicalTopEstimate, nextPageLogicalTop(logicalHeight()));
1295 logicalTopEstimate += getClearDelta(child, logicalTopEstimate);
1297 estimateWithoutPagination = logicalTopEstimate;
1299 if (layoutState->isPaginated()) {
1300 // If the object has a page or column break value of "before", then we should shift to the top of the next page.
1301 logicalTopEstimate = applyBeforeBreak(child, logicalTopEstimate);
1303 // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
1304 logicalTopEstimate = adjustForUnsplittableChild(child, logicalTopEstimate);
1306 if (!child.selfNeedsLayout() && is<RenderBlock>(child))
1307 logicalTopEstimate += downcast<RenderBlock>(child).paginationStrut();
1310 return logicalTopEstimate;
1313 void RenderBlockFlow::setCollapsedBottomMargin(const MarginInfo& marginInfo)
1315 if (marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()) {
1316 // Update the after side margin of the container to discard if the after margin of the last child also discards and we collapse with it.
1317 // Don't update the max margin values because we won't need them anyway.
1318 if (marginInfo.discardMargin()) {
1319 setMustDiscardMarginAfter();
1323 // Update our max pos/neg bottom margins, since we collapsed our bottom margins
1324 // with our children.
1325 setMaxMarginAfterValues(std::max(maxPositiveMarginAfter(), marginInfo.positiveMargin()), std::max(maxNegativeMarginAfter(), marginInfo.negativeMargin()));
1327 if (!marginInfo.hasMarginAfterQuirk())
1328 setHasMarginAfterQuirk(false);
1330 if (marginInfo.hasMarginAfterQuirk() && !marginAfter())
1331 // We have no bottom margin and our last child has a quirky margin.
1332 // We will pick up this quirky margin and pass it through.
1333 // This deals with the <td><div><p> case.
1334 setHasMarginAfterQuirk(true);
1338 void RenderBlockFlow::handleAfterSideOfBlock(LayoutUnit beforeSide, LayoutUnit afterSide, MarginInfo& marginInfo)
1340 marginInfo.setAtAfterSideOfBlock(true);
1342 // If our last child was a self-collapsing block with clearance then our logical height is flush with the
1343 // bottom edge of the float that the child clears. The correct vertical position for the margin-collapsing we want
1344 // to perform now is at the child's margin-top - so adjust our height to that position.
1345 RenderObject* lastBlock = lastChild();
1346 if (is<RenderBlockFlow>(lastBlock) && downcast<RenderBlockFlow>(*lastBlock).isSelfCollapsingBlock())
1347 setLogicalHeight(logicalHeight() - downcast<RenderBlockFlow>(*lastBlock).marginOffsetForSelfCollapsingBlock());
1349 // If we can't collapse with children then add in the bottom margin.
1350 if (!marginInfo.discardMargin() && (!marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()
1351 && (!document().inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginAfterQuirk())))
1352 setLogicalHeight(logicalHeight() + marginInfo.margin());
1354 // Now add in our bottom border/padding.
1355 setLogicalHeight(logicalHeight() + afterSide);
1357 // Negative margins can cause our height to shrink below our minimal height (border/padding).
1358 // If this happens, ensure that the computed height is increased to the minimal height.
1359 setLogicalHeight(std::max(logicalHeight(), beforeSide + afterSide));
1361 // Update our bottom collapsed margin info.
1362 setCollapsedBottomMargin(marginInfo);
1365 void RenderBlockFlow::setMaxMarginBeforeValues(LayoutUnit pos, LayoutUnit neg)
1367 if (!hasRareBlockFlowData()) {
1368 if (pos == RenderBlockFlowRareData::positiveMarginBeforeDefault(*this) && neg == RenderBlockFlowRareData::negativeMarginBeforeDefault(*this))
1370 materializeRareBlockFlowData();
1373 rareBlockFlowData()->m_margins.setPositiveMarginBefore(pos);
1374 rareBlockFlowData()->m_margins.setNegativeMarginBefore(neg);
1377 void RenderBlockFlow::setMaxMarginAfterValues(LayoutUnit pos, LayoutUnit neg)
1379 if (!hasRareBlockFlowData()) {
1380 if (pos == RenderBlockFlowRareData::positiveMarginAfterDefault(*this) && neg == RenderBlockFlowRareData::negativeMarginAfterDefault(*this))
1382 materializeRareBlockFlowData();
1385 rareBlockFlowData()->m_margins.setPositiveMarginAfter(pos);
1386 rareBlockFlowData()->m_margins.setNegativeMarginAfter(neg);
1389 void RenderBlockFlow::setMustDiscardMarginBefore(bool value)
1391 if (style().marginBeforeCollapse() == MDISCARD) {
1396 if (!hasRareBlockFlowData()) {
1399 materializeRareBlockFlowData();
1402 rareBlockFlowData()->m_discardMarginBefore = value;
1405 void RenderBlockFlow::setMustDiscardMarginAfter(bool value)
1407 if (style().marginAfterCollapse() == MDISCARD) {
1412 if (!hasRareBlockFlowData()) {
1415 materializeRareBlockFlowData();
1418 rareBlockFlowData()->m_discardMarginAfter = value;
1421 bool RenderBlockFlow::mustDiscardMarginBefore() const
1423 return style().marginBeforeCollapse() == MDISCARD || (hasRareBlockFlowData() && rareBlockFlowData()->m_discardMarginBefore);
1426 bool RenderBlockFlow::mustDiscardMarginAfter() const
1428 return style().marginAfterCollapse() == MDISCARD || (hasRareBlockFlowData() && rareBlockFlowData()->m_discardMarginAfter);
1431 bool RenderBlockFlow::mustDiscardMarginBeforeForChild(const RenderBox& child) const
1433 ASSERT(!child.selfNeedsLayout());
1434 if (!child.isWritingModeRoot())
1435 return is<RenderBlockFlow>(child) ? downcast<RenderBlockFlow>(child).mustDiscardMarginBefore() : (child.style().marginBeforeCollapse() == MDISCARD);
1436 if (child.isHorizontalWritingMode() == isHorizontalWritingMode())
1437 return is<RenderBlockFlow>(child) ? downcast<RenderBlockFlow>(child).mustDiscardMarginAfter() : (child.style().marginAfterCollapse() == MDISCARD);
1439 // FIXME: We return false here because the implementation is not geometrically complete. We have values only for before/after, not start/end.
1440 // In case the boxes are perpendicular we assume the property is not specified.
1444 bool RenderBlockFlow::mustDiscardMarginAfterForChild(const RenderBox& child) const
1446 ASSERT(!child.selfNeedsLayout());
1447 if (!child.isWritingModeRoot())
1448 return is<RenderBlockFlow>(child) ? downcast<RenderBlockFlow>(child).mustDiscardMarginAfter() : (child.style().marginAfterCollapse() == MDISCARD);
1449 if (child.isHorizontalWritingMode() == isHorizontalWritingMode())
1450 return is<RenderBlockFlow>(child) ? downcast<RenderBlockFlow>(child).mustDiscardMarginBefore() : (child.style().marginBeforeCollapse() == MDISCARD);
1452 // FIXME: See |mustDiscardMarginBeforeForChild| above.
1456 bool RenderBlockFlow::mustSeparateMarginBeforeForChild(const RenderBox& child) const
1458 ASSERT(!child.selfNeedsLayout());
1459 const RenderStyle& childStyle = child.style();
1460 if (!child.isWritingModeRoot())
1461 return childStyle.marginBeforeCollapse() == MSEPARATE;
1462 if (child.isHorizontalWritingMode() == isHorizontalWritingMode())
1463 return childStyle.marginAfterCollapse() == MSEPARATE;
1465 // FIXME: See |mustDiscardMarginBeforeForChild| above.
1469 bool RenderBlockFlow::mustSeparateMarginAfterForChild(const RenderBox& child) const
1471 ASSERT(!child.selfNeedsLayout());
1472 const RenderStyle& childStyle = child.style();
1473 if (!child.isWritingModeRoot())
1474 return childStyle.marginAfterCollapse() == MSEPARATE;
1475 if (child.isHorizontalWritingMode() == isHorizontalWritingMode())
1476 return childStyle.marginBeforeCollapse() == MSEPARATE;
1478 // FIXME: See |mustDiscardMarginBeforeForChild| above.
1482 static bool inNormalFlow(RenderBox& child)
1484 RenderBlock* curr = child.containingBlock();
1485 while (curr && curr != &child.view()) {
1486 if (curr->isRenderFragmentedFlow())
1488 if (curr->isFloatingOrOutOfFlowPositioned())
1490 curr = curr->containingBlock();
1495 LayoutUnit RenderBlockFlow::applyBeforeBreak(RenderBox& child, LayoutUnit logicalOffset)
1497 // FIXME: Add page break checking here when we support printing.
1498 RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
1499 bool isInsideMulticolFlow = fragmentedFlow;
1500 bool checkColumnBreaks = fragmentedFlow && fragmentedFlow->shouldCheckColumnBreaks();
1501 bool checkPageBreaks = !checkColumnBreaks && view().frameView().layoutContext().layoutState()->pageLogicalHeight(); // FIXME: Once columns can print we have to check this.
1502 bool checkFragmentBreaks = false;
1503 bool checkBeforeAlways = (checkColumnBreaks && child.style().breakBefore() == ColumnBreakBetween)
1504 || (checkPageBreaks && alwaysPageBreak(child.style().breakBefore()));
1505 if (checkBeforeAlways && inNormalFlow(child) && hasNextPage(logicalOffset, IncludePageBoundary)) {
1506 if (checkColumnBreaks) {
1507 if (isInsideMulticolFlow)
1508 checkFragmentBreaks = true;
1510 if (checkFragmentBreaks) {
1511 LayoutUnit offsetBreakAdjustment = 0;
1512 if (fragmentedFlow->addForcedFragmentBreak(this, offsetFromLogicalTopOfFirstPage() + logicalOffset, &child, true, &offsetBreakAdjustment))
1513 return logicalOffset + offsetBreakAdjustment;
1515 return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
1517 return logicalOffset;
1520 LayoutUnit RenderBlockFlow::applyAfterBreak(RenderBox& child, LayoutUnit logicalOffset, MarginInfo& marginInfo)
1522 // FIXME: Add page break checking here when we support printing.
1523 RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
1524 bool isInsideMulticolFlow = fragmentedFlow;
1525 bool checkColumnBreaks = fragmentedFlow && fragmentedFlow->shouldCheckColumnBreaks();
1526 bool checkPageBreaks = !checkColumnBreaks && view().frameView().layoutContext().layoutState()->pageLogicalHeight(); // FIXME: Once columns can print we have to check this.
1527 bool checkFragmentBreaks = false;
1528 bool checkAfterAlways = (checkColumnBreaks && child.style().breakAfter() == ColumnBreakBetween)
1529 || (checkPageBreaks && alwaysPageBreak(child.style().breakAfter()));
1530 if (checkAfterAlways && inNormalFlow(child) && hasNextPage(logicalOffset, IncludePageBoundary)) {
1531 LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
1533 // So our margin doesn't participate in the next collapsing steps.
1534 marginInfo.clearMargin();
1536 if (checkColumnBreaks) {
1537 if (isInsideMulticolFlow)
1538 checkFragmentBreaks = true;
1540 if (checkFragmentBreaks) {
1541 LayoutUnit offsetBreakAdjustment = 0;
1542 if (fragmentedFlow->addForcedFragmentBreak(this, offsetFromLogicalTopOfFirstPage() + logicalOffset + marginOffset, &child, false, &offsetBreakAdjustment))
1543 return logicalOffset + marginOffset + offsetBreakAdjustment;
1545 return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
1547 return logicalOffset;
1550 LayoutUnit RenderBlockFlow::adjustBlockChildForPagination(LayoutUnit logicalTopAfterClear, LayoutUnit estimateWithoutPagination, RenderBox& child, bool atBeforeSideOfBlock)
1552 RenderBlock* childRenderBlock = is<RenderBlock>(child) ? &downcast<RenderBlock>(child) : nullptr;
1554 if (estimateWithoutPagination != logicalTopAfterClear) {
1555 // Our guess prior to pagination movement was wrong. Before we attempt to paginate, let's try again at the new
1557 setLogicalHeight(logicalTopAfterClear);
1558 setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
1560 if (child.shrinkToAvoidFloats()) {
1561 // The child's width depends on the line width. When the child shifts to clear an item, its width can
1562 // change (because it has more available line width). So mark the item as dirty.
1563 child.setChildNeedsLayout(MarkOnlyThis);
1566 if (childRenderBlock) {
1567 if (!child.avoidsFloats() && childRenderBlock->containsFloats())
1568 downcast<RenderBlockFlow>(*childRenderBlock).markAllDescendantsWithFloatsForLayout();
1569 child.markForPaginationRelayoutIfNeeded();
1572 // Our guess was wrong. Make the child lay itself out again.
1573 child.layoutIfNeeded();
1576 LayoutUnit oldTop = logicalTopAfterClear;
1578 // If the object has a page or column break value of "before", then we should shift to the top of the next page.
1579 LayoutUnit result = applyBeforeBreak(child, logicalTopAfterClear);
1581 if (pageLogicalHeightForOffset(result)) {
1582 LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(result, ExcludePageBoundary);
1583 LayoutUnit spaceShortage = child.logicalHeight() - remainingLogicalHeight;
1584 if (spaceShortage > 0) {
1585 // If the child crosses a column boundary, report a break, in case nothing inside it has already
1586 // done so. The column balancer needs to know how much it has to stretch the columns to make more
1587 // content fit. If no breaks are reported (but do occur), the balancer will have no clue. FIXME:
1588 // This should be improved, though, because here we just pretend that the child is
1589 // unsplittable. A splittable child, on the other hand, has break opportunities at every position
1590 // where there's no child content, border or padding. In other words, we risk stretching more
1592 setPageBreak(result, spaceShortage);
1596 // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
1597 LayoutUnit logicalTopBeforeUnsplittableAdjustment = result;
1598 LayoutUnit logicalTopAfterUnsplittableAdjustment = adjustForUnsplittableChild(child, result);
1600 LayoutUnit paginationStrut = 0;
1601 LayoutUnit unsplittableAdjustmentDelta = logicalTopAfterUnsplittableAdjustment - logicalTopBeforeUnsplittableAdjustment;
1602 if (unsplittableAdjustmentDelta)
1603 paginationStrut = unsplittableAdjustmentDelta;
1604 else if (childRenderBlock && childRenderBlock->paginationStrut())
1605 paginationStrut = childRenderBlock->paginationStrut();
1607 if (paginationStrut) {
1608 // We are willing to propagate out to our parent block as long as we were at the top of the block prior
1609 // to collapsing our margins, and as long as we didn't clear or move as a result of other pagination.
1610 if (atBeforeSideOfBlock && oldTop == result && !isOutOfFlowPositioned() && !isTableCell()) {
1611 // FIXME: Should really check if we're exceeding the page height before propagating the strut, but we don't
1612 // have all the information to do so (the strut only has the remaining amount to push). Gecko gets this wrong too
1613 // and pushes to the next page anyway, so not too concerned about it.
1614 setPaginationStrut(result + paginationStrut);
1615 if (childRenderBlock)
1616 childRenderBlock->setPaginationStrut(0);
1618 result += paginationStrut;
1621 // Similar to how we apply clearance. Boost height() to be the place where we're going to position the child.
1622 setLogicalHeight(logicalHeight() + (result - oldTop));
1624 // Return the final adjusted logical top.
1628 static inline LayoutUnit calculateMinimumPageHeight(const RenderStyle& renderStyle, RootInlineBox& lastLine, LayoutUnit lineTop, LayoutUnit lineBottom)
1630 // We may require a certain minimum number of lines per page in order to satisfy
1631 // orphans and widows, and that may affect the minimum page height.
1632 unsigned lineCount = std::max<unsigned>(renderStyle.hasAutoOrphans() ? 1 : renderStyle.orphans(), renderStyle.hasAutoWidows() ? 1 : renderStyle.widows());
1633 if (lineCount > 1) {
1634 RootInlineBox* line = &lastLine;
1635 for (unsigned i = 1; i < lineCount && line->prevRootBox(); i++)
1636 line = line->prevRootBox();
1638 // FIXME: Paginating using line overflow isn't all fine. See FIXME in
1639 // adjustLinePositionForPagination() for more details.
1640 LayoutRect overflow = line->logicalVisualOverflowRect(line->lineTop(), line->lineBottom());
1641 lineTop = std::min(line->lineTopWithLeading(), overflow.y());
1643 return lineBottom - lineTop;
1646 static inline bool needsAppleMailPaginationQuirk(RootInlineBox& lineBox)
1648 auto& renderer = lineBox.renderer();
1650 if (!renderer.settings().appleMailPaginationQuirkEnabled())
1653 if (renderer.element() && renderer.element()->idForStyleResolution() == "messageContentContainer")
1659 static void clearShouldBreakAtLineToAvoidWidowIfNeeded(RenderBlockFlow& blockFlow)
1661 if (!blockFlow.shouldBreakAtLineToAvoidWidow())
1663 blockFlow.clearShouldBreakAtLineToAvoidWidow();
1664 blockFlow.setDidBreakAtLineToAvoidWidow();
1667 void RenderBlockFlow::adjustLinePositionForPagination(RootInlineBox* lineBox, LayoutUnit& delta, bool& overflowsFragment, RenderFragmentedFlow* fragmentedFlow)
1669 // FIXME: For now we paginate using line overflow. This ensures that lines don't overlap at all when we
1670 // put a strut between them for pagination purposes. However, this really isn't the desired rendering, since
1671 // the line on the top of the next page will appear too far down relative to the same kind of line at the top
1672 // of the first column.
1674 // The rendering we would like to see is one where the lineTopWithLeading is at the top of the column, and any line overflow
1675 // simply spills out above the top of the column. This effect would match what happens at the top of the first column.
1676 // We can't achieve this rendering, however, until we stop columns from clipping to the column bounds (thus allowing
1677 // for overflow to occur), and then cache visible overflow for each column rect.
1679 // Furthermore, the paint we have to do when a column has overflow has to be special. We need to exclude
1680 // content that paints in a previous column (and content that paints in the following column).
1682 // For now we'll at least honor the lineTopWithLeading when paginating if it is above the logical top overflow. This will
1683 // at least make positive leading work in typical cases.
1685 // FIXME: Another problem with simply moving lines is that the available line width may change (because of floats).
1686 // Technically if the location we move the line to has a different line width than our old position, then we need to dirty the
1687 // line and all following lines.
1688 overflowsFragment = false;
1689 LayoutRect logicalVisualOverflow = lineBox->logicalVisualOverflowRect(lineBox->lineTop(), lineBox->lineBottom());
1690 LayoutUnit logicalOffset = std::min(lineBox->lineTopWithLeading(), logicalVisualOverflow.y());
1691 LayoutUnit logicalBottom = std::max(lineBox->lineBottomWithLeading(), logicalVisualOverflow.maxY());
1692 LayoutUnit lineHeight = logicalBottom - logicalOffset;
1693 updateMinimumPageHeight(logicalOffset, calculateMinimumPageHeight(style(), *lineBox, logicalOffset, logicalBottom));
1694 logicalOffset += delta;
1695 lineBox->setPaginationStrut(0);
1696 lineBox->setIsFirstAfterPageBreak(false);
1697 LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
1698 bool hasUniformPageLogicalHeight = !fragmentedFlow || fragmentedFlow->fragmentsHaveUniformLogicalHeight();
1699 // If lineHeight is greater than pageLogicalHeight, but logicalVisualOverflow.height() still fits, we are
1700 // still going to add a strut, so that the visible overflow fits on a single page.
1701 if (!pageLogicalHeight || !hasNextPage(logicalOffset)) {
1702 // FIXME: In case the line aligns with the top of the page (or it's slightly shifted downwards) it will not be marked as the first line in the page.
1703 // From here, the fix is not straightforward because it's not easy to always determine when the current line is the first in the page.
1707 if (hasUniformPageLogicalHeight && logicalVisualOverflow.height() > pageLogicalHeight) {
1708 // We are so tall that we are bigger than a page. Before we give up and just leave the line where it is, try drilling into the
1709 // line and computing a new height that excludes anything we consider "blank space". We will discard margins, descent, and even overflow. If we are
1710 // able to fit with the blank space and overflow excluded, we will give the line its own page with the highest non-blank element being aligned with the
1712 // FIXME: We are still honoring gigantic margins, which does leave open the possibility of blank pages caused by this heuristic. It remains to be seen whether or not
1713 // this will be a real-world issue. For now we don't try to deal with this problem.
1714 logicalOffset = intMaxForLayoutUnit;
1715 logicalBottom = intMinForLayoutUnit;
1716 lineBox->computeReplacedAndTextLineTopAndBottom(logicalOffset, logicalBottom);
1717 lineHeight = logicalBottom - logicalOffset;
1718 if (logicalOffset == intMaxForLayoutUnit || lineHeight > pageLogicalHeight) {
1719 // Give up. We're genuinely too big even after excluding blank space and overflow.
1720 clearShouldBreakAtLineToAvoidWidowIfNeeded(*this);
1723 pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
1726 LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset, ExcludePageBoundary);
1727 overflowsFragment = (lineHeight > remainingLogicalHeight);
1729 int lineIndex = lineCount(lineBox);
1730 if (remainingLogicalHeight < lineHeight || (shouldBreakAtLineToAvoidWidow() && lineBreakToAvoidWidow() == lineIndex)) {
1731 if (lineBreakToAvoidWidow() == lineIndex)
1732 clearShouldBreakAtLineToAvoidWidowIfNeeded(*this);
1733 // If we have a non-uniform page height, then we have to shift further possibly.
1734 if (!hasUniformPageLogicalHeight && !pushToNextPageWithMinimumLogicalHeight(remainingLogicalHeight, logicalOffset, lineHeight))
1736 if (lineHeight > pageLogicalHeight) {
1737 // Split the top margin in order to avoid splitting the visible part of the line.
1738 remainingLogicalHeight -= std::min(lineHeight - pageLogicalHeight, std::max<LayoutUnit>(0, logicalVisualOverflow.y() - lineBox->lineTopWithLeading()));
1740 LayoutUnit remainingLogicalHeightAtNewOffset = pageRemainingLogicalHeightForOffset(logicalOffset + remainingLogicalHeight, ExcludePageBoundary);
1741 overflowsFragment = (lineHeight > remainingLogicalHeightAtNewOffset);
1742 LayoutUnit totalLogicalHeight = lineHeight + std::max<LayoutUnit>(0, logicalOffset);
1743 LayoutUnit pageLogicalHeightAtNewOffset = hasUniformPageLogicalHeight ? pageLogicalHeight : pageLogicalHeightForOffset(logicalOffset + remainingLogicalHeight);
1744 setPageBreak(logicalOffset, lineHeight - remainingLogicalHeight);
1745 if (((lineBox == firstRootBox() && totalLogicalHeight < pageLogicalHeightAtNewOffset) || (!style().hasAutoOrphans() && style().orphans() >= lineIndex))
1746 && !isOutOfFlowPositioned() && !isTableCell()) {
1747 auto firstRootBox = this->firstRootBox();
1748 auto firstRootBoxOverflowRect = firstRootBox->logicalVisualOverflowRect(firstRootBox->lineTop(), firstRootBox->lineBottom());
1749 auto firstLineUpperOverhang = std::max(-firstRootBoxOverflowRect.y(), LayoutUnit());
1750 if (needsAppleMailPaginationQuirk(*lineBox))
1752 setPaginationStrut(remainingLogicalHeight + logicalOffset + firstLineUpperOverhang);
1754 delta += remainingLogicalHeight;
1755 lineBox->setPaginationStrut(remainingLogicalHeight);
1756 lineBox->setIsFirstAfterPageBreak(true);
1758 } else if (remainingLogicalHeight == pageLogicalHeight) {
1759 // We're at the very top of a page or column.
1760 if (lineBox != firstRootBox())
1761 lineBox->setIsFirstAfterPageBreak(true);
1762 if (lineBox != firstRootBox() || offsetFromLogicalTopOfFirstPage())
1763 setPageBreak(logicalOffset, lineHeight);
1767 void RenderBlockFlow::setBreakAtLineToAvoidWidow(int lineToBreak)
1769 ASSERT(lineToBreak >= 0);
1770 ASSERT(!ensureRareBlockFlowData().m_didBreakAtLineToAvoidWidow);
1771 ensureRareBlockFlowData().m_lineBreakToAvoidWidow = lineToBreak;
1774 void RenderBlockFlow::setDidBreakAtLineToAvoidWidow()
1776 ASSERT(!shouldBreakAtLineToAvoidWidow());
1777 if (!hasRareBlockFlowData())
1780 rareBlockFlowData()->m_didBreakAtLineToAvoidWidow = true;
1783 void RenderBlockFlow::clearDidBreakAtLineToAvoidWidow()
1785 if (!hasRareBlockFlowData())
1788 rareBlockFlowData()->m_didBreakAtLineToAvoidWidow = false;
1791 void RenderBlockFlow::clearShouldBreakAtLineToAvoidWidow() const
1793 ASSERT(shouldBreakAtLineToAvoidWidow());
1794 if (!hasRareBlockFlowData())
1797 rareBlockFlowData()->m_lineBreakToAvoidWidow = -1;
1800 bool RenderBlockFlow::relayoutToAvoidWidows()
1802 if (!shouldBreakAtLineToAvoidWidow())
1805 setEverHadLayout(true);
1810 bool RenderBlockFlow::hasNextPage(LayoutUnit logicalOffset, PageBoundaryRule pageBoundaryRule) const
1812 ASSERT(view().frameView().layoutContext().layoutState() && view().frameView().layoutContext().layoutState()->isPaginated());
1814 RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
1815 if (!fragmentedFlow)
1816 return true; // Printing and multi-column both make new pages to accommodate content.
1818 // See if we're in the last fragment.
1819 LayoutUnit pageOffset = offsetFromLogicalTopOfFirstPage() + logicalOffset;
1820 RenderFragmentContainer* fragment = fragmentedFlow->fragmentAtBlockOffset(this, pageOffset, true);
1824 if (fragment->isLastFragment())
1825 return fragment->isRenderFragmentContainerSet() || (pageBoundaryRule == IncludePageBoundary && pageOffset == fragment->logicalTopForFragmentedFlowContent());
1827 RenderFragmentContainer* startFragment = nullptr;
1828 RenderFragmentContainer* endFragment = nullptr;
1829 fragmentedFlow->getFragmentRangeForBox(this, startFragment, endFragment);
1830 return (endFragment && fragment != endFragment);
1833 LayoutUnit RenderBlockFlow::adjustForUnsplittableChild(RenderBox& child, LayoutUnit logicalOffset, LayoutUnit childBeforeMargin, LayoutUnit childAfterMargin)
1835 // When flexboxes are embedded inside a block flow, they don't perform any adjustments for unsplittable
1836 // children. We'll treat flexboxes themselves as unsplittable just to get them to paginate properly inside
1838 bool isUnsplittable = childBoxIsUnsplittableForFragmentation(child);
1839 if (!isUnsplittable && !(child.isFlexibleBox() && !downcast<RenderFlexibleBox>(child).isFlexibleBoxImpl()))
1840 return logicalOffset;
1842 RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
1843 LayoutUnit childLogicalHeight = logicalHeightForChild(child) + childBeforeMargin + childAfterMargin;
1844 LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
1845 bool hasUniformPageLogicalHeight = !fragmentedFlow || fragmentedFlow->fragmentsHaveUniformLogicalHeight();
1847 updateMinimumPageHeight(logicalOffset, childLogicalHeight);
1848 if (!pageLogicalHeight || (hasUniformPageLogicalHeight && childLogicalHeight > pageLogicalHeight)
1849 || !hasNextPage(logicalOffset))
1850 return logicalOffset;
1851 LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset, ExcludePageBoundary);
1852 if (remainingLogicalHeight < childLogicalHeight) {
1853 if (!hasUniformPageLogicalHeight && !pushToNextPageWithMinimumLogicalHeight(remainingLogicalHeight, logicalOffset, childLogicalHeight))
1854 return logicalOffset;
1855 auto result = logicalOffset + remainingLogicalHeight;
1856 bool isInitialLetter = child.isFloating() && child.style().styleType() == FIRST_LETTER && child.style().initialLetterDrop() > 0;
1857 if (isInitialLetter) {
1858 // Increase our logical height to ensure that lines all get pushed along with the letter.
1859 setLogicalHeight(logicalOffset + remainingLogicalHeight);
1864 return logicalOffset;
1867 bool RenderBlockFlow::pushToNextPageWithMinimumLogicalHeight(LayoutUnit& adjustment, LayoutUnit logicalOffset, LayoutUnit minimumLogicalHeight) const
1869 bool checkFragment = false;
1870 for (LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset + adjustment); pageLogicalHeight;
1871 pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset + adjustment)) {
1872 if (minimumLogicalHeight <= pageLogicalHeight)
1874 if (!hasNextPage(logicalOffset + adjustment))
1876 adjustment += pageLogicalHeight;
1877 checkFragment = true;
1879 return !checkFragment;
1882 void RenderBlockFlow::setPageBreak(LayoutUnit offset, LayoutUnit spaceShortage)
1884 if (RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow())
1885 fragmentedFlow->setPageBreak(this, offsetFromLogicalTopOfFirstPage() + offset, spaceShortage);
1888 void RenderBlockFlow::updateMinimumPageHeight(LayoutUnit offset, LayoutUnit minHeight)
1890 if (RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow())
1891 fragmentedFlow->updateMinimumPageHeight(this, offsetFromLogicalTopOfFirstPage() + offset, minHeight);
1894 LayoutUnit RenderBlockFlow::nextPageLogicalTop(LayoutUnit logicalOffset, PageBoundaryRule pageBoundaryRule) const
1896 LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
1897 if (!pageLogicalHeight)
1898 return logicalOffset;
1900 // The logicalOffset is in our coordinate space. We can add in our pushed offset.
1901 LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset);
1902 if (pageBoundaryRule == ExcludePageBoundary)
1903 return logicalOffset + (remainingLogicalHeight ? remainingLogicalHeight : pageLogicalHeight);
1904 return logicalOffset + remainingLogicalHeight;
1907 LayoutUnit RenderBlockFlow::pageLogicalTopForOffset(LayoutUnit offset) const
1909 // Unsplittable objects clear out the pageLogicalHeight in the layout state as a way of signaling that no
1910 // pagination should occur. Therefore we have to check this first and bail if the value has been set to 0.
1911 auto* layoutState = view().frameView().layoutContext().layoutState();
1912 LayoutUnit pageLogicalHeight = layoutState->pageLogicalHeight();
1913 if (!pageLogicalHeight)
1916 LayoutUnit firstPageLogicalTop = isHorizontalWritingMode() ? layoutState->pageOffset().height() : layoutState->pageOffset().width();
1917 LayoutUnit blockLogicalTop = isHorizontalWritingMode() ? layoutState->layoutOffset().height() : layoutState->layoutOffset().width();
1919 LayoutUnit cumulativeOffset = offset + blockLogicalTop;
1920 RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
1921 if (!fragmentedFlow)
1922 return cumulativeOffset - roundToInt(cumulativeOffset - firstPageLogicalTop) % roundToInt(pageLogicalHeight);
1923 return firstPageLogicalTop + fragmentedFlow->pageLogicalTopForOffset(cumulativeOffset - firstPageLogicalTop);
1926 LayoutUnit RenderBlockFlow::pageLogicalHeightForOffset(LayoutUnit offset) const
1928 // Unsplittable objects clear out the pageLogicalHeight in the layout state as a way of signaling that no
1929 // pagination should occur. Therefore we have to check this first and bail if the value has been set to 0.
1930 LayoutUnit pageLogicalHeight = view().frameView().layoutContext().layoutState()->pageLogicalHeight();
1931 if (!pageLogicalHeight)
1934 // Now check for a flow thread.
1935 RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
1936 if (!fragmentedFlow)
1937 return pageLogicalHeight;
1938 return fragmentedFlow->pageLogicalHeightForOffset(offset + offsetFromLogicalTopOfFirstPage());
1941 LayoutUnit RenderBlockFlow::pageRemainingLogicalHeightForOffset(LayoutUnit offset, PageBoundaryRule pageBoundaryRule) const
1943 offset += offsetFromLogicalTopOfFirstPage();
1945 RenderFragmentedFlow* fragmentedFlow = enclosingFragmentedFlow();
1946 if (!fragmentedFlow) {
1947 LayoutUnit pageLogicalHeight = view().frameView().layoutContext().layoutState()->pageLogicalHeight();
1948 LayoutUnit remainingHeight = pageLogicalHeight - intMod(offset, pageLogicalHeight);
1949 if (pageBoundaryRule == IncludePageBoundary) {
1950 // If includeBoundaryPoint is true the line exactly on the top edge of a
1951 // column will act as being part of the previous column.
1952 remainingHeight = intMod(remainingHeight, pageLogicalHeight);
1954 return remainingHeight;
1957 return fragmentedFlow->pageRemainingLogicalHeightForOffset(offset, pageBoundaryRule);
1960 LayoutUnit RenderBlockFlow::logicalHeightForChildForFragmentation(const RenderBox& child) const
1962 return logicalHeightForChild(child);
1965 void RenderBlockFlow::layoutLineGridBox()
1967 if (style().lineGrid() == RenderStyle::initialLineGrid()) {
1974 auto lineGridBox = std::make_unique<RootInlineBox>(*this);
1975 lineGridBox->setHasTextChildren(); // Needed to make the line ascent/descent actually be honored in quirks mode.
1976 lineGridBox->setConstructed();
1977 GlyphOverflowAndFallbackFontsMap textBoxDataMap;
1978 VerticalPositionCache verticalPositionCache;
1979 lineGridBox->alignBoxesInBlockDirection(logicalHeight(), textBoxDataMap, verticalPositionCache);
1981 setLineGridBox(WTFMove(lineGridBox));
1983 // FIXME: If any of the characteristics of the box change compared to the old one, then we need to do a deep dirtying
1984 // (similar to what happens when the page height changes). Ideally, though, we only do this if someone is actually snapping
1988 bool RenderBlockFlow::containsFloat(RenderBox& renderer) const
1990 return m_floatingObjects && m_floatingObjects->set().contains<RenderBox&, FloatingObjectHashTranslator>(renderer);
1993 void RenderBlockFlow::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
1995 RenderBlock::styleDidChange(diff, oldStyle);
1997 // After our style changed, if we lose our ability to propagate floats into next sibling
1998 // blocks, then we need to find the top most parent containing that overhanging float and
1999 // then mark its descendants with floats for layout and clear all floats from its next
2000 // sibling blocks that exist in our floating objects list. See bug 56299 and 62875.
2001 bool canPropagateFloatIntoSibling = !isFloatingOrOutOfFlowPositioned() && !avoidsFloats();
2002 if (diff == StyleDifferenceLayout && s_canPropagateFloatIntoSibling && !canPropagateFloatIntoSibling && hasOverhangingFloats()) {
2003 RenderBlockFlow* parentBlock = this;
2004 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2006 for (auto& ancestor : ancestorsOfType<RenderBlockFlow>(*this)) {
2007 if (ancestor.isRenderView())
2009 if (ancestor.hasOverhangingFloats()) {
2010 for (auto it = floatingObjectSet.begin(), end = floatingObjectSet.end(); it != end; ++it) {
2011 RenderBox& renderer = (*it)->renderer();
2012 if (ancestor.hasOverhangingFloat(renderer)) {
2013 parentBlock = &ancestor;
2020 parentBlock->markAllDescendantsWithFloatsForLayout();
2021 parentBlock->markSiblingsWithFloatsForLayout();
2024 if (diff >= StyleDifferenceRepaint) {
2025 // FIXME: This could use a cheaper style-only test instead of SimpleLineLayout::canUseFor.
2026 if (selfNeedsLayout() || !m_simpleLineLayout || !SimpleLineLayout::canUseFor(*this))
2027 invalidateLineLayoutPath();
2030 if (multiColumnFlow())
2031 updateStylesForColumnChildren();
2034 void RenderBlockFlow::updateStylesForColumnChildren()
2036 for (auto* child = firstChildBox(); child && (child->isInFlowRenderFragmentedFlow() || child->isRenderMultiColumnSet()); child = child->nextSiblingBox())
2037 child->setStyle(RenderStyle::createAnonymousStyleWithDisplay(style(), BLOCK));
2040 void RenderBlockFlow::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
2042 const RenderStyle* oldStyle = hasInitializedStyle() ? &style() : nullptr;
2043 s_canPropagateFloatIntoSibling = oldStyle ? !isFloatingOrOutOfFlowPositioned() && !avoidsFloats() : false;
2046 EPosition oldPosition = oldStyle->position();
2047 EPosition newPosition = newStyle.position();
2049 if (parent() && diff == StyleDifferenceLayout && oldPosition != newPosition) {
2050 if (containsFloats() && !isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition())
2051 markAllDescendantsWithFloatsForLayout();
2055 RenderBlock::styleWillChange(diff, newStyle);
2058 void RenderBlockFlow::deleteLines()
2060 if (containsFloats())
2061 m_floatingObjects->clearLineBoxTreePointers();
2063 if (m_simpleLineLayout) {
2064 ASSERT(!m_lineBoxes.firstLineBox());
2065 m_simpleLineLayout = nullptr;
2067 m_lineBoxes.deleteLineBoxTree();
2069 RenderBlock::deleteLines();
2072 void RenderBlockFlow::addFloatsToNewParent(RenderBlockFlow& toBlockFlow) const
2074 // When a portion of the render tree is being detached, anonymous blocks
2075 // will be combined as their children are deleted. In this process, the
2076 // anonymous block later in the tree is merged into the one preceeding it.
2077 // It can happen that the later block (this) contains floats that the
2078 // previous block (toBlockFlow) did not contain, and thus are not in the
2079 // floating objects list for toBlockFlow. This can result in toBlockFlow
2080 // containing floats that are not in it's floating objects list, but are in
2081 // the floating objects lists of siblings and parents. This can cause
2082 // problems when the float itself is deleted, since the deletion code
2083 // assumes that if a float is not in it's containing block's floating
2084 // objects list, it isn't in any floating objects list. In order to
2085 // preserve this condition (removing it has serious performance
2086 // implications), we need to copy the floating objects from the old block
2087 // (this) to the new block (toBlockFlow). The float's metrics will likely
2088 // all be wrong, but since toBlockFlow is already marked for layout, this
2089 // will get fixed before anything gets displayed.
2090 // See bug https://bugs.webkit.org/show_bug.cgi?id=115566
2091 if (!m_floatingObjects)
2094 if (!toBlockFlow.m_floatingObjects)
2095 toBlockFlow.createFloatingObjects();
2097 for (auto& floatingObject : m_floatingObjects->set()) {
2098 if (toBlockFlow.containsFloat(floatingObject->renderer()))
2100 toBlockFlow.m_floatingObjects->add(floatingObject->cloneForNewParent());
2104 void RenderBlockFlow::addOverflowFromFloats()
2106 if (!m_floatingObjects)
2109 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2110 auto end = floatingObjectSet.end();
2111 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
2112 const auto& floatingObject = *it->get();
2113 if (floatingObject.isDescendant())
2114 addOverflowFromChild(&floatingObject.renderer(), floatingObject.locationOffsetOfBorderBox());
2118 void RenderBlockFlow::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
2120 RenderBlock::computeOverflow(oldClientAfterEdge, recomputeFloats);
2122 if (!multiColumnFlow() && (recomputeFloats || createsNewFormattingContext() || hasSelfPaintingLayer()))
2123 addOverflowFromFloats();
2126 void RenderBlockFlow::repaintOverhangingFloats(bool paintAllDescendants)
2128 // Repaint any overhanging floats (if we know we're the one to paint them).
2129 // Otherwise, bail out.
2130 if (!hasOverhangingFloats())
2133 // FIXME: Avoid disabling LayoutState. At the very least, don't disable it for floats originating
2134 // in this block. Better yet would be to push extra state for the containers of other floats.
2135 LayoutStateDisabler layoutStateDisabler(view().frameView().layoutContext());
2136 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2137 auto end = floatingObjectSet.end();
2138 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
2139 const auto& floatingObject = *it->get();
2140 // Only repaint the object if it is overhanging, is not in its own layer, and
2141 // is our responsibility to paint (m_shouldPaint is set). When paintAllDescendants is true, the latter
2142 // condition is replaced with being a descendant of us.
2143 auto& renderer = floatingObject.renderer();
2144 if (logicalBottomForFloat(floatingObject) > logicalHeight()
2145 && !renderer.hasSelfPaintingLayer()
2146 && (floatingObject.shouldPaint() || (paintAllDescendants && renderer.isDescendantOf(this)))) {
2148 renderer.repaintOverhangingFloats(false);
2153 void RenderBlockFlow::paintColumnRules(PaintInfo& paintInfo, const LayoutPoint& point)
2155 RenderBlock::paintColumnRules(paintInfo, point);
2157 if (!multiColumnFlow() || paintInfo.context().paintingDisabled())
2160 // Iterate over our children and paint the column rules as needed.
2161 for (auto& columnSet : childrenOfType<RenderMultiColumnSet>(*this)) {
2162 LayoutPoint childPoint = columnSet.location() + flipForWritingModeForChild(&columnSet, point);
2163 columnSet.paintColumnRules(paintInfo, childPoint);
2167 void RenderBlockFlow::paintFloats(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool preservePhase)
2169 if (!m_floatingObjects)
2172 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2173 auto end = floatingObjectSet.end();
2174 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
2175 const auto& floatingObject = *it->get();
2176 auto& renderer = floatingObject.renderer();
2177 // Only paint the object if our m_shouldPaint flag is set.
2178 if (floatingObject.shouldPaint() && !renderer.hasSelfPaintingLayer()) {
2179 PaintInfo currentPaintInfo(paintInfo);
2180 currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
2181 LayoutPoint childPoint = flipFloatForWritingModeForChild(floatingObject, paintOffset + floatingObject.translationOffsetToAncestor());
2182 renderer.paint(currentPaintInfo, childPoint);
2183 if (!preservePhase) {
2184 currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
2185 renderer.paint(currentPaintInfo, childPoint);
2186 currentPaintInfo.phase = PaintPhaseFloat;
2187 renderer.paint(currentPaintInfo, childPoint);
2188 currentPaintInfo.phase = PaintPhaseForeground;
2189 renderer.paint(currentPaintInfo, childPoint);
2190 currentPaintInfo.phase = PaintPhaseOutline;
2191 renderer.paint(currentPaintInfo, childPoint);
2197 void RenderBlockFlow::clipOutFloatingObjects(RenderBlock& rootBlock, const PaintInfo* paintInfo, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock)
2199 if (m_floatingObjects) {
2200 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2201 auto end = floatingObjectSet.end();
2202 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
2203 const auto& floatingObject = *it->get();
2204 LayoutRect floatBox(offsetFromRootBlock.width(), offsetFromRootBlock.height(), floatingObject.renderer().width(), floatingObject.renderer().height());
2205 floatBox.move(floatingObject.locationOffsetOfBorderBox());
2206 rootBlock.flipForWritingMode(floatBox);
2207 floatBox.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
2208 paintInfo->context().clipOut(snappedIntRect(floatBox));
2213 void RenderBlockFlow::createFloatingObjects()
2215 m_floatingObjects = std::make_unique<FloatingObjects>(*this);
2218 void RenderBlockFlow::removeFloatingObjects()
2220 if (!m_floatingObjects)
2223 markSiblingsWithFloatsForLayout();
2225 m_floatingObjects->clear();
2228 FloatingObject* RenderBlockFlow::insertFloatingObject(RenderBox& floatBox)
2230 ASSERT(floatBox.isFloating());
2232 // Create the list of special objects if we don't aleady have one
2233 if (!m_floatingObjects)
2234 createFloatingObjects();
2236 // Don't insert the floatingObject again if it's already in the list
2237 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2238 auto it = floatingObjectSet.find<RenderBox&, FloatingObjectHashTranslator>(floatBox);
2239 if (it != floatingObjectSet.end())
2243 // Create the special floatingObject entry & append it to the list
2245 std::unique_ptr<FloatingObject> floatingObject = FloatingObject::create(floatBox);
2247 // Our location is irrelevant if we're unsplittable or no pagination is in effect. Just lay out the float.
2248 bool isChildRenderBlock = floatBox.isRenderBlock();
2249 if (isChildRenderBlock && !floatBox.needsLayout() && view().frameView().layoutContext().layoutState()->pageLogicalHeightChanged())
2250 floatBox.setChildNeedsLayout(MarkOnlyThis);
2252 bool needsBlockDirectionLocationSetBeforeLayout = isChildRenderBlock && view().frameView().layoutContext().layoutState()->needsBlockDirectionLocationSetBeforeLayout();
2253 if (!needsBlockDirectionLocationSetBeforeLayout || isWritingModeRoot()) {
2254 // We are unsplittable if we're a block flow root.
2255 floatBox.layoutIfNeeded();
2256 floatingObject->setShouldPaint(!floatBox.hasSelfPaintingLayer());
2259 floatBox.updateLogicalWidth();
2260 floatBox.computeAndSetBlockDirectionMargins(*this);
2263 setLogicalWidthForFloat(*floatingObject, logicalWidthForChild(floatBox) + marginStartForChild(floatBox) + marginEndForChild(floatBox));
2265 return m_floatingObjects->add(WTFMove(floatingObject));
2268 void RenderBlockFlow::removeFloatingObject(RenderBox& floatBox)
2270 if (m_floatingObjects) {
2271 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2272 auto it = floatingObjectSet.find<RenderBox&, FloatingObjectHashTranslator>(floatBox);
2273 if (it != floatingObjectSet.end()) {
2274 auto& floatingObject = *it->get();
2275 if (childrenInline()) {
2276 LayoutUnit logicalTop = logicalTopForFloat(floatingObject);
2277 LayoutUnit logicalBottom = logicalBottomForFloat(floatingObject);
2279 // Fix for https://bugs.webkit.org/show_bug.cgi?id=54995.
2280 if (logicalBottom < 0 || logicalBottom < logicalTop || logicalTop == LayoutUnit::max())
2281 logicalBottom = LayoutUnit::max();
2283 // Special-case zero- and less-than-zero-height floats: those don't touch
2284 // the line that they're on, but it still needs to be dirtied. This is
2285 // accomplished by pretending they have a height of 1.
2286 logicalBottom = std::max(logicalBottom, logicalTop + 1);
2288 if (floatingObject.originatingLine()) {
2289 floatingObject.originatingLine()->removeFloat(floatBox);
2290 if (!selfNeedsLayout()) {
2291 ASSERT(&floatingObject.originatingLine()->renderer() == this);
2292 floatingObject.originatingLine()->markDirty();
2294 #if !ASSERT_DISABLED
2295 floatingObject.clearOriginatingLine();
2298 markLinesDirtyInBlockRange(0, logicalBottom);
2300 m_floatingObjects->remove(&floatingObject);
2305 void RenderBlockFlow::removeFloatingObjectsBelow(FloatingObject* lastFloat, int logicalOffset)
2307 if (!containsFloats())
2310 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2311 FloatingObject* curr = floatingObjectSet.last().get();
2312 while (curr != lastFloat && (!curr->isPlaced() || logicalTopForFloat(*curr) >= logicalOffset)) {
2313 m_floatingObjects->remove(curr);
2314 if (floatingObjectSet.isEmpty())
2316 curr = floatingObjectSet.last().get();
2320 LayoutUnit RenderBlockFlow::logicalLeftOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
2322 LayoutUnit offset = fixedOffset;
2323 if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
2324 offset = m_floatingObjects->logicalLeftOffsetForPositioningFloat(fixedOffset, logicalTop, heightRemaining);
2325 return adjustLogicalLeftOffsetForLine(offset, applyTextIndent);
2328 LayoutUnit RenderBlockFlow::logicalRightOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
2330 LayoutUnit offset = fixedOffset;
2331 if (m_floatingObjects && m_floatingObjects->hasRightObjects())
2332 offset = m_floatingObjects->logicalRightOffsetForPositioningFloat(fixedOffset, logicalTop, heightRemaining);
2333 return adjustLogicalRightOffsetForLine(offset, applyTextIndent);
2336 void RenderBlockFlow::computeLogicalLocationForFloat(FloatingObject& floatingObject, LayoutUnit& logicalTopOffset)
2338 auto& childBox = floatingObject.renderer();
2339 LayoutUnit logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
2340 LayoutUnit logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); // Constant part of right offset.
2342 LayoutUnit floatLogicalWidth = std::min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset); // The width we look for.
2344 LayoutUnit floatLogicalLeft;
2346 bool insideFragmentedFlow = enclosingFragmentedFlow();
2347 bool isInitialLetter = childBox.style().styleType() == FIRST_LETTER && childBox.style().initialLetterDrop() > 0;
2349 if (isInitialLetter) {
2350 int letterClearance = lowestInitialLetterLogicalBottom() - logicalTopOffset;
2351 if (letterClearance > 0) {
2352 logicalTopOffset += letterClearance;
2353 setLogicalHeight(logicalHeight() + letterClearance);
2357 if (childBox.style().floating() == LeftFloat) {
2358 LayoutUnit heightRemainingLeft = 1;
2359 LayoutUnit heightRemainingRight = 1;
2360 floatLogicalLeft = logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
2361 while (logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight) - floatLogicalLeft < floatLogicalWidth) {
2362 logicalTopOffset += std::min(heightRemainingLeft, heightRemainingRight);
2363 floatLogicalLeft = logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
2364 if (insideFragmentedFlow) {
2365 // Have to re-evaluate all of our offsets, since they may have changed.
2366 logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); // Constant part of right offset.
2367 logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
2368 floatLogicalWidth = std::min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
2371 floatLogicalLeft = std::max(logicalLeftOffset - borderAndPaddingLogicalLeft(), floatLogicalLeft);
2373 LayoutUnit heightRemainingLeft = 1;
2374 LayoutUnit heightRemainingRight = 1;
2375 floatLogicalLeft = logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
2376 while (floatLogicalLeft - logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft) < floatLogicalWidth) {
2377 logicalTopOffset += std::min(heightRemainingLeft, heightRemainingRight);
2378 floatLogicalLeft = logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
2379 if (insideFragmentedFlow) {
2380 // Have to re-evaluate all of our offsets, since they may have changed.
2381 logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); // Constant part of right offset.
2382 logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
2383 floatLogicalWidth = std::min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
2386 // Use the original width of the float here, since the local variable
2387 // |floatLogicalWidth| was capped to the available line width. See
2388 // fast/block/float/clamped-right-float.html.
2389 floatLogicalLeft -= logicalWidthForFloat(floatingObject);
2392 LayoutUnit childLogicalLeftMargin = style().isLeftToRightDirection() ? marginStartForChild(childBox) : marginEndForChild(childBox);
2393 LayoutUnit childBeforeMargin = marginBeforeForChild(childBox);
2395 if (isInitialLetter)
2396 adjustInitialLetterPosition(childBox, logicalTopOffset, childBeforeMargin);
2398 setLogicalLeftForFloat(floatingObject, floatLogicalLeft);
2399 setLogicalLeftForChild(childBox, floatLogicalLeft + childLogicalLeftMargin);
2401 setLogicalTopForFloat(floatingObject, logicalTopOffset);
2402 setLogicalTopForChild(childBox, logicalTopOffset + childBeforeMargin);
2404 setLogicalMarginsForFloat(floatingObject, childLogicalLeftMargin, childBeforeMargin);
2407 void RenderBlockFlow::adjustInitialLetterPosition(RenderBox& childBox, LayoutUnit& logicalTopOffset, LayoutUnit& marginBeforeOffset)
2409 const RenderStyle& style = firstLineStyle();
2410 const FontMetrics& fontMetrics = style.fontMetrics();
2411 if (!fontMetrics.hasCapHeight())
2414 LayoutUnit heightOfLine = lineHeight(true, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
2415 LayoutUnit beforeMarginBorderPadding = childBox.borderAndPaddingBefore() + childBox.marginBefore();
2417 // Make an adjustment to align with the cap height of a theoretical block line.
2418 LayoutUnit adjustment = fontMetrics.ascent() + (heightOfLine - fontMetrics.height()) / 2 - fontMetrics.capHeight() - beforeMarginBorderPadding;
2419 logicalTopOffset += adjustment;
2421 // For sunken and raised caps, we have to make some adjustments. Test if we're sunken or raised (dropHeightDelta will be
2422 // positive for raised and negative for sunken).
2423 int dropHeightDelta = childBox.style().initialLetterHeight() - childBox.style().initialLetterDrop();
2425 // If we're sunken, the float needs to shift down but lines still need to avoid it. In order to do that we increase the float's margin.
2426 if (dropHeightDelta < 0)
2427 marginBeforeOffset += -dropHeightDelta * heightOfLine;
2429 // If we're raised, then we actually have to grow the height of the block, since the lines have to be pushed down as though we're placing
2430 // empty lines beside the first letter.
2431 if (dropHeightDelta > 0)
2432 setLogicalHeight(logicalHeight() + dropHeightDelta * heightOfLine);
2435 bool RenderBlockFlow::positionNewFloats()
2437 if (!m_floatingObjects)
2440 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2441 if (floatingObjectSet.isEmpty())
2444 // If all floats have already been positioned, then we have no work to do.
2445 if (floatingObjectSet.last()->isPlaced())
2448 // Move backwards through our floating object list until we find a float that has
2449 // already been positioned. Then we'll be able to move forward, positioning all of
2450 // the new floats that need it.
2451 auto it = floatingObjectSet.end();
2452 --it; // Go to last item.
2453 auto begin = floatingObjectSet.begin();
2454 FloatingObject* lastPlacedFloatingObject = 0;
2455 while (it != begin) {
2457 if ((*it)->isPlaced()) {
2458 lastPlacedFloatingObject = it->get();
2464 LayoutUnit logicalTop = logicalHeight();
2466 // The float cannot start above the top position of the last positioned float.
2467 if (lastPlacedFloatingObject)
2468 logicalTop = std::max(logicalTopForFloat(*lastPlacedFloatingObject), logicalTop);
2470 auto end = floatingObjectSet.end();
2471 // Now walk through the set of unpositioned floats and place them.
2472 for (; it != end; ++it) {
2473 auto& floatingObject = *it->get();
2474 // The containing block is responsible for positioning floats, so if we have floats in our
2475 // list that come from somewhere else, do not attempt to position them.
2476 auto& childBox = floatingObject.renderer();
2477 if (childBox.containingBlock() != this)
2480 LayoutRect oldRect = childBox.frameRect();
2482 if (childBox.style().clear() & CLEFT)
2483 logicalTop = std::max(lowestFloatLogicalBottom(FloatingObject::FloatLeft), logicalTop);
2484 if (childBox.style().clear() & CRIGHT)
2485 logicalTop = std::max(lowestFloatLogicalBottom(FloatingObject::FloatRight), logicalTop);
2487 computeLogicalLocationForFloat(floatingObject, logicalTop);
2488 LayoutUnit childLogicalTop = logicalTopForChild(childBox);
2490 estimateFragmentRangeForBoxChild(childBox);
2492 childBox.markForPaginationRelayoutIfNeeded();
2493 childBox.layoutIfNeeded();
2495 auto* layoutState = view().frameView().layoutContext().layoutState();
2496 bool isPaginated = layoutState->isPaginated();
2498 // If we are unsplittable and don't fit, then we need to move down.
2499 // We include our margins as part of the unsplittable area.
2500 LayoutUnit newLogicalTop = adjustForUnsplittableChild(childBox, logicalTop, childLogicalTop - logicalTop, marginAfterForChild(childBox));
2502 // See if we have a pagination strut that is making us move down further.
2503 // Note that an unsplittable child can't also have a pagination strut, so this
2504 // is exclusive with the case above.
2505 RenderBlock* childBlock = is<RenderBlock>(childBox) ? &downcast<RenderBlock>(childBox) : nullptr;
2506 if (childBlock && childBlock->paginationStrut()) {
2507 newLogicalTop += childBlock->paginationStrut();
2508 childBlock->setPaginationStrut(0);
2511 if (newLogicalTop != logicalTop) {
2512 floatingObject.setPaginationStrut(newLogicalTop - logicalTop);
2513 computeLogicalLocationForFloat(floatingObject, newLogicalTop);
2515 childBlock->setChildNeedsLayout(MarkOnlyThis);
2516 childBox.layoutIfNeeded();
2517 logicalTop = newLogicalTop;
2520 if (updateFragmentRangeForBoxChild(childBox)) {
2521 childBox.setNeedsLayout(MarkOnlyThis);
2522 childBox.layoutIfNeeded();
2526 setLogicalHeightForFloat(floatingObject, logicalHeightForChildForFragmentation(childBox) + (logicalTopForChild(childBox) - logicalTop) + marginAfterForChild(childBox));
2528 m_floatingObjects->addPlacedObject(&floatingObject);
2530 if (ShapeOutsideInfo* shapeOutside = childBox.shapeOutsideInfo())
2531 shapeOutside->setReferenceBoxLogicalSize(logicalSizeForChild(childBox));
2532 // If the child moved, we have to repaint it.
2533 if (childBox.checkForRepaintDuringLayout())
2534 childBox.repaintDuringLayoutIfMoved(oldRect);
2539 void RenderBlockFlow::clearFloats(EClear clear)
2541 positionNewFloats();
2543 LayoutUnit newY = 0;
2546 newY = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
2549 newY = lowestFloatLogicalBottom(FloatingObject::FloatRight);
2552 newY = lowestFloatLogicalBottom();
2557 if (height() < newY)
2558 setLogicalHeight(newY);
2561 LayoutUnit RenderBlockFlow::logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const
2563 if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
2564 return m_floatingObjects->logicalLeftOffset(fixedOffset, logicalTop, logicalHeight);
2569 LayoutUnit RenderBlockFlow::logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const
2571 if (m_floatingObjects && m_floatingObjects->hasRightObjects())
2572 return m_floatingObjects->logicalRightOffset(fixedOffset, logicalTop, logicalHeight);
2577 LayoutUnit RenderBlockFlow::nextFloatLogicalBottomBelow(LayoutUnit logicalHeight) const
2579 if (!m_floatingObjects)
2580 return logicalHeight;
2582 return m_floatingObjects->findNextFloatLogicalBottomBelow(logicalHeight);
2585 LayoutUnit RenderBlockFlow::nextFloatLogicalBottomBelowForBlock(LayoutUnit logicalHeight) const
2587 if (!m_floatingObjects)
2588 return logicalHeight;
2590 return m_floatingObjects->findNextFloatLogicalBottomBelowForBlock(logicalHeight);
2593 LayoutUnit RenderBlockFlow::lowestFloatLogicalBottom(FloatingObject::Type floatType) const
2595 if (!m_floatingObjects)
2597 LayoutUnit lowestFloatBottom = 0;
2598 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2599 auto end = floatingObjectSet.end();
2600 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
2601 const auto& floatingObject = *it->get();
2602 if (floatingObject.isPlaced() && floatingObject.type() & floatType)
2603 lowestFloatBottom = std::max(lowestFloatBottom, logicalBottomForFloat(floatingObject));
2605 return lowestFloatBottom;
2608 LayoutUnit RenderBlockFlow::lowestInitialLetterLogicalBottom() const
2610 if (!m_floatingObjects)
2612 LayoutUnit lowestFloatBottom = 0;
2613 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2614 auto end = floatingObjectSet.end();
2615 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
2616 const auto& floatingObject = *it->get();
2617 if (floatingObject.isPlaced() && floatingObject.renderer().style().styleType() == FIRST_LETTER && floatingObject.renderer().style().initialLetterDrop() > 0)
2618 lowestFloatBottom = std::max(lowestFloatBottom, logicalBottomForFloat(floatingObject));
2620 return lowestFloatBottom;
2623 LayoutUnit RenderBlockFlow::addOverhangingFloats(RenderBlockFlow& child, bool makeChildPaintOtherFloats)
2625 // Prevent floats from being added to the canvas by the root element, e.g., <html>.
2626 if (!child.containsFloats() || child.createsNewFormattingContext())
2629 LayoutUnit childLogicalTop = child.logicalTop();
2630 LayoutUnit childLogicalLeft = child.logicalLeft();
2631 LayoutUnit lowestFloatLogicalBottom = 0;
2633 // Floats that will remain the child's responsibility to paint should factor into its
2635 auto childEnd = child.m_floatingObjects->set().end();
2636 for (auto childIt = child.m_floatingObjects->set().begin(); childIt != childEnd; ++childIt) {
2637 auto& floatingObject = *childIt->get();
2638 LayoutUnit floatLogicalBottom = std::min(logicalBottomForFloat(floatingObject), LayoutUnit::max() - childLogicalTop);
2639 LayoutUnit logicalBottom = childLogicalTop + floatLogicalBottom;
2640 lowestFloatLogicalBottom = std::max(lowestFloatLogicalBottom, logicalBottom);
2642 if (logicalBottom > logicalHeight()) {
2643 // If the object is not in the list, we add it now.
2644 if (!containsFloat(floatingObject.renderer())) {
2645 LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(-childLogicalLeft, -childLogicalTop) : LayoutSize(-childLogicalTop, -childLogicalLeft);
2646 bool shouldPaint = false;
2648 // The nearest enclosing layer always paints the float (so that zindex and stacking
2649 // behaves properly). We always want to propagate the desire to paint the float as
2650 // far out as we can, to the outermost block that overlaps the float, stopping only
2651 // if we hit a self-painting layer boundary.
2652 if (floatingObject.renderer().enclosingFloatPaintingLayer() == enclosingFloatPaintingLayer()) {
2653 floatingObject.setShouldPaint(false);
2656 // We create the floating object list lazily.
2657 if (!m_floatingObjects)
2658 createFloatingObjects();
2660 m_floatingObjects->add(floatingObject.copyToNewContainer(offset, shouldPaint, true));
2663 const auto& renderer = floatingObject.renderer();
2664 if (makeChildPaintOtherFloats && !floatingObject.shouldPaint() && !renderer.hasSelfPaintingLayer()
2665 && renderer.isDescendantOf(&child) && renderer.enclosingFloatPaintingLayer() == child.enclosingFloatPaintingLayer()) {
2666 // The float is not overhanging from this block, so if it is a descendant of the child, the child should
2667 // paint it (the other case is that it is intruding into the child), unless it has its own layer or enclosing
2669 // If makeChildPaintOtherFloats is false, it means that the child must already know about all the floats
2671 floatingObject.setShouldPaint(true);
2674 // Since the float doesn't overhang, it didn't get put into our list. We need to add its overflow in to the child now.
2675 if (floatingObject.isDescendant())
2676 child.addOverflowFromChild(&renderer, floatingObject.locationOffsetOfBorderBox());
2679 return lowestFloatLogicalBottom;
2682 bool RenderBlockFlow::hasOverhangingFloat(RenderBox& renderer)
2684 if (!m_floatingObjects || !parent())
2687 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2688 const auto it = floatingObjectSet.find<RenderBox&, FloatingObjectHashTranslator>(renderer);
2689 if (it == floatingObjectSet.end())
2692 return logicalBottomForFloat(*it->get()) > logicalHeight();
2695 void RenderBlockFlow::addIntrudingFloats(RenderBlockFlow* prev, RenderBlockFlow* container, LayoutUnit logicalLeftOffset, LayoutUnit logicalTopOffset)
2697 ASSERT(!avoidsFloats());
2699 // If we create our own block formatting context then our contents don't interact with floats outside it, even those from our parent.
2700 if (createsNewFormattingContext())
2703 // If the parent or previous sibling doesn't have any floats to add, don't bother.
2704 if (!prev->m_floatingObjects)
2707 logicalLeftOffset += marginLogicalLeft();
2709 const FloatingObjectSet& prevSet = prev->m_floatingObjects->set();
2710 auto prevEnd = prevSet.end();
2711 for (auto prevIt = prevSet.begin(); prevIt != prevEnd; ++prevIt) {
2712 auto& floatingObject = *prevIt->get();
2713 if (logicalBottomForFloat(floatingObject) > logicalTopOffset) {
2714 if (!m_floatingObjects || !m_floatingObjects->set().contains<FloatingObject&, FloatingObjectHashTranslator>(floatingObject)) {
2715 // We create the floating object list lazily.
2716 if (!m_floatingObjects)
2717 createFloatingObjects();
2719 // Applying the child's margin makes no sense in the case where the child was passed in.
2720 // since this margin was added already through the modification of the |logicalLeftOffset| variable
2721 // above. |logicalLeftOffset| will equal the margin in this case, so it's already been taken
2722 // into account. Only apply this code if prev is the parent, since otherwise the left margin
2723 // will get applied twice.
2724 LayoutSize offset = isHorizontalWritingMode()
2725 ? LayoutSize(logicalLeftOffset - (prev != container ? prev->marginLeft() : LayoutUnit()), logicalTopOffset)
2726 : LayoutSize(logicalTopOffset, logicalLeftOffset - (prev != container ? prev->marginTop() : LayoutUnit()));
2728 m_floatingObjects->add(floatingObject.copyToNewContainer(offset));
2734 void RenderBlockFlow::markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove, bool inLayout)
2736 if (!everHadLayout() && !containsFloats())
2739 MarkingBehavior markParents = inLayout ? MarkOnlyThis : MarkContainingBlockChain;
2740 setChildNeedsLayout(markParents);
2743 removeFloatingObject(*floatToRemove);
2744 else if (childrenInline())
2747 // Iterate over our block children and mark them as needed.
2748 for (auto& block : childrenOfType<RenderBlock>(*this)) {
2749 if (!floatToRemove && block.isFloatingOrOutOfFlowPositioned())
2751 if (!is<RenderBlockFlow>(block)) {
2752 if (block.shrinkToAvoidFloats() && block.everHadLayout())
2753 block.setChildNeedsLayout(markParents);
2756 auto& blockFlow = downcast<RenderBlockFlow>(block);
2757 if ((floatToRemove ? blockFlow.containsFloat(*floatToRemove) : blockFlow.containsFloats()) || blockFlow.shrinkToAvoidFloats())
2758 blockFlow.markAllDescendantsWithFloatsForLayout(floatToRemove, inLayout);
2762 void RenderBlockFlow::markSiblingsWithFloatsForLayout(RenderBox* floatToRemove)
2764 if (!m_floatingObjects)
2767 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2768 auto end = floatingObjectSet.end();
2770 for (RenderObject* next = nextSibling(); next; next = next->nextSibling()) {
2771 if (!is<RenderBlockFlow>(*next) || next->isFloatingOrOutOfFlowPositioned())
2774 RenderBlockFlow& nextBlock = downcast<RenderBlockFlow>(*next);
2775 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
2776 RenderBox& floatingBox = (*it)->renderer();
2777 if (floatToRemove && &floatingBox != floatToRemove)
2779 if (nextBlock.containsFloat(floatingBox))
2780 nextBlock.markAllDescendantsWithFloatsForLayout(&floatingBox);
2785 LayoutPoint RenderBlockFlow::flipFloatForWritingModeForChild(const FloatingObject& child, const LayoutPoint& point) const
2787 if (!style().isFlippedBlocksWritingMode())
2790 // This is similar to RenderBox::flipForWritingModeForChild. We have to subtract out our left/top offsets twice, since
2791 // it's going to get added back in. We hide this complication here so that the calling code looks normal for the unflipped
2793 if (isHorizontalWritingMode())
2794 return LayoutPoint(point.x(), point.y() + height() - child.renderer().height() - 2 * child.locationOffsetOfBorderBox().height());
2795 return LayoutPoint(point.x() + width() - child.renderer().width() - 2 * child.locationOffsetOfBorderBox().width(), point.y());
2798 LayoutUnit RenderBlockFlow::getClearDelta(RenderBox& child, LayoutUnit logicalTop)
2800 // There is no need to compute clearance if we have no floats.
2801 if (!containsFloats())
2804 // At least one float is present. We need to perform the clearance computation.
2805 bool clearSet = child.style().clear() != CNONE;
2806 LayoutUnit logicalBottom = 0;
2807 switch (child.style().clear()) {
2811 logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
2814 logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatRight);
2817 logicalBottom = lowestFloatLogicalBottom();
2821 // We also clear floats if we are too big to sit on the same line as a float (and wish to avoid floats by default).
2822 LayoutUnit result = clearSet ? std::max<LayoutUnit>(0, logicalBottom - logicalTop) : LayoutUnit();
2823 if (!result && child.avoidsFloats()) {
2824 LayoutUnit newLogicalTop = logicalTop;
2826 LayoutUnit availableLogicalWidthAtNewLogicalTopOffset = availableLogicalWidthForLine(newLogicalTop, DoNotIndentText, logicalHeightForChild(child));
2827 if (availableLogicalWidthAtNewLogicalTopOffset == availableLogicalWidthForContent(newLogicalTop))
2828 return newLogicalTop - logicalTop;
2830 RenderFragmentContainer* fragment = fragmentAtBlockOffset(logicalTopForChild(child));
2831 LayoutRect borderBox = child.borderBoxRectInFragment(fragment, DoNotCacheRenderBoxFragmentInfo);
2832 LayoutUnit childLogicalWidthAtOldLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
2834 // FIXME: None of this is right for perpendicular writing-mode children.
2835 LayoutUnit childOldLogicalWidth = child.logicalWidth();
2836 LayoutUnit childOldMarginLeft = child.marginLeft();
2837 LayoutUnit childOldMarginRight = child.marginRight();
2838 LayoutUnit childOldLogicalTop = child.logicalTop();
2840 child.setLogicalTop(newLogicalTop);
2841 child.updateLogicalWidth();
2842 fragment = fragmentAtBlockOffset(logicalTopForChild(child));
2843 borderBox = child.borderBoxRectInFragment(fragment, DoNotCacheRenderBoxFragmentInfo);
2844 LayoutUnit childLogicalWidthAtNewLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
2846 child.setLogicalTop(childOldLogicalTop);
2847 child.setLogicalWidth(childOldLogicalWidth);
2848 child.setMarginLeft(childOldMarginLeft);
2849 child.setMarginRight(childOldMarginRight);
2851 if (childLogicalWidthAtNewLogicalTopOffset <= availableLogicalWidthAtNewLogicalTopOffset) {
2852 // Even though we may not be moving, if the logical width did shrink because of the presence of new floats, then
2853 // we need to force a relayout as though we shifted. This happens because of the dynamic addition of overhanging floats
2854 // from previous siblings when negative margins exist on a child (see the addOverhangingFloats call at the end of collapseMargins).
2855 if (childLogicalWidthAtOldLogicalTopOffset != childLogicalWidthAtNewLogicalTopOffset)
2856 child.setChildNeedsLayout(MarkOnlyThis);
2857 return newLogicalTop - logicalTop;
2860 newLogicalTop = nextFloatLogicalBottomBelowForBlock(newLogicalTop);
2861 ASSERT(newLogicalTop >= logicalTop);
2862 if (newLogicalTop < logicalTop)
2865 ASSERT_NOT_REACHED();
2870 bool RenderBlockFlow::hitTestFloats(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset)
2872 if (!m_floatingObjects)
2875 LayoutPoint adjustedLocation = accumulatedOffset;
2876 if (is<RenderView>(*this))
2877 adjustedLocation += toLayoutSize(downcast<RenderView>(*this).frameView().scrollPosition());
2879 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2880 auto begin = floatingObjectSet.begin();
2881 for (auto it = floatingObjectSet.end(); it != begin;) {
2883 const auto& floatingObject = *it->get();
2884 auto& renderer = floatingObject.renderer();
2885 if (floatingObject.shouldPaint() && !renderer.hasSelfPaintingLayer()) {
2886 LayoutPoint childPoint = flipFloatForWritingModeForChild(floatingObject, adjustedLocation + floatingObject.translationOffsetToAncestor());
2887 if (renderer.hitTest(request, result, locationInContainer, childPoint)) {
2888 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(childPoint));
2897 bool RenderBlockFlow::hitTestInlineChildren(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
2899 ASSERT(childrenInline());
2901 if (auto simpleLineLayout = this->simpleLineLayout())
2902 return SimpleLineLayout::hitTestFlow(*this, *simpleLineLayout, request, result, locationInContainer, accumulatedOffset, hitTestAction);
2904 return m_lineBoxes.hitTest(this, request, result, locationInContainer, accumulatedOffset, hitTestAction);
2907 void RenderBlockFlow::adjustForBorderFit(LayoutUnit x, LayoutUnit& left, LayoutUnit& right) const
2909 if (style().visibility() != VISIBLE)
2912 // We don't deal with relative positioning. Our assumption is that you shrink to fit the lines without accounting
2913 // for either overflow or translations via relative positioning.
2914 if (childrenInline()) {
2915 const_cast<RenderBlockFlow&>(*this).ensureLineBoxes();
2917 for (auto* box = firstRootBox(); box; box = box->nextRootBox()) {
2918 if (box->firstChild())
2919 left = std::min(left, x + LayoutUnit(box->firstChild()->x()));
2920 if (box->lastChild())
2921 right = std::max(right, x + LayoutUnit(ceilf(box->lastChild()->logicalRight())));
2924 for (RenderBox* obj = firstChildBox(); obj; obj = obj->nextSiblingBox()) {
2925 if (!obj->isFloatingOrOutOfFlowPositioned()) {
2926 if (is<RenderBlockFlow>(*obj) && !obj->hasOverflowClip())
2927 downcast<RenderBlockFlow>(*obj).adjustForBorderFit(x + obj->x(), left, right);
2928 else if (obj->style().visibility() == VISIBLE) {
2929 // We are a replaced element or some kind of non-block-flow object.
2930 left = std::min(left, x + obj->x());
2931 right = std::max(right, x + obj->x() + obj->width());
2937 if (m_floatingObjects) {
2938 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2939 auto end = floatingObjectSet.end();
2940 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
2941 const auto& floatingObject = *it->get();
2942 // Only examine the object if our m_shouldPaint flag is set.
2943 if (floatingObject.shouldPaint()) {
2944 LayoutUnit floatLeft = floatingObject.translationOffsetToAncestor().width();
2945 LayoutUnit floatRight = floatLeft + floatingObject.renderer().width();
2946 left = std::min(left, floatLeft);
2947 right = std::max(right, floatRight);
2953 void RenderBlockFlow::fitBorderToLinesIfNeeded()
2955 if (style().borderFit() == BorderFitBorder || hasOverrideLogicalContentWidth())
2958 // Walk any normal flow lines to snugly fit.
2959 LayoutUnit left = LayoutUnit::max();
2960 LayoutUnit right = LayoutUnit::min();
2961 LayoutUnit oldWidth = contentWidth();
2962 adjustForBorderFit(0, left, right);
2964 // Clamp to our existing edges. We can never grow. We only shrink.
2965 LayoutUnit leftEdge = borderLeft() + paddingLeft();
2966 LayoutUnit rightEdge = leftEdge + oldWidth;
2967 left = std::min(rightEdge, std::max(leftEdge, left));
2968 right = std::max(leftEdge, std::min(rightEdge, right));
2970 LayoutUnit newContentWidth = right - left;
2971 if (newContentWidth == oldWidth)
2974 setOverrideLogicalContentWidth(newContentWidth);
2976 clearOverrideLogicalContentWidth();
2979 void RenderBlockFlow::markLinesDirtyInBlockRange(LayoutUnit logicalTop, LayoutUnit logicalBottom, RootInlineBox* highest)
2981 if (logicalTop >= logicalBottom)
2984 // Floats currently affect the choice whether to use simple line layout path.
2985 if (m_simpleLineLayout) {
2986 invalidateLineLayoutPath();
2990 RootInlineBox* lowestDirtyLine = lastRootBox();
2991 RootInlineBox* afterLowest = lowestDirtyLine;
2992 while (lowestDirtyLine && lowestDirtyLine->lineBottomWithLeading() >= logicalBottom && logicalBottom < LayoutUnit::max()) {
2993 afterLowest = lowestDirtyLine;
2994 lowestDirtyLine = lowestDirtyLine->prevRootBox();
2997 while (afterLowest && afterLowest != highest && (afterLowest->lineBottomWithLeading() >= logicalTop || afterLowest->lineBottomWithLeading() < 0)) {
2998 afterLowest->markDirty();
2999 afterLowest = afterLowest->prevRootBox();
3003 std::optional<int> RenderBlockFlow::firstLineBaseline() const
3005 if (isWritingModeRoot() && !isRubyRun())
3006 return std::nullopt;
3008 if (!childrenInline())
3009 return RenderBlock::firstLineBaseline();
3012 return std::nullopt;
3014 if (auto simpleLineLayout = this->simpleLineLayout())
3015 return std::optional<int>(SimpleLineLayout::computeFlowFirstLineBaseline(*this, *simpleLineLayout));
3017 ASSERT(firstRootBox());
3018 return firstRootBox()->logicalTop() + firstLineStyle().fontMetrics().ascent(firstRootBox()->baselineType());
3021 std::optional<int> RenderBlockFlow::inlineBlockBaseline(LineDirectionMode lineDirection) const
3023 if (isWritingModeRoot() && !isRubyRun())
3024 return std::nullopt;
3026 // Note that here we only take the left and bottom into consideration. Our caller takes the right and top into consideration.
3027 float boxHeight = lineDirection == HorizontalLine ? height() + m_marginBox.bottom() : width() + m_marginBox.left();
3029 if (!childrenInline()) {
3030 std::optional<int> inlineBlockBaseline = RenderBlock::inlineBlockBaseline(lineDirection);
3031 if (!inlineBlockBaseline)
3032 return inlineBlockBaseline;
3033 lastBaseline = inlineBlockBaseline.value();
3036 if (!hasLineIfEmpty())
3037 return std::nullopt;
3038 const auto& fontMetrics = firstLineStyle().fontMetrics();
3039 return std::optional<int>(fontMetrics.ascent()
3040 + (lineHeight(true, lineDirection, PositionOfInteriorLineBoxes) - fontMetrics.height()) / 2
3041 + (lineDirection == HorizontalLine ? borderTop() + paddingTop() : borderRight() + paddingRight()));
3044 if (auto simpleLineLayout = this->simpleLineLayout())
3045 lastBaseline = SimpleLineLayout::computeFlowLastLineBaseline(*this, *simpleLineLayout);
3047 bool isFirstLine = lastRootBox() == firstRootBox();
3048 const auto& style = isFirstLine ? firstLineStyle() : this->style();
3049 // InlineFlowBox::placeBoxesInBlockDirection will flip lines in case of verticalLR mode, so we can assume verticalRL for now.
3050 lastBaseline = style.fontMetrics().ascent(lastRootBox()->baselineType())
3051 + (style.isFlippedLinesWritingMode() ? logicalHeight() - lastRootBox()->logicalBottom() : lastRootBox()->logicalTop());
3054 // According to the CSS spec http://www.w3.org/TR/CSS21/visudet.html, we shouldn't be performing this min, but should
3055 // instead be returning boxHeight directly. However, we feel that a min here is better behavior (and is consistent
3056 // enough with the spec to not cause tons of breakages).
3057 return style().overflowY() == OVISIBLE ? lastBaseline : std::min(boxHeight, lastBaseline);
3060 void RenderBlockFlow::setSelectionState(SelectionState state)
3062 if (state != SelectionNone)
3064 RenderBoxModelObject::setSelectionState(state);
3067 GapRects RenderBlockFlow::inlineSelectionGaps(RenderBlock& rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3068 LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
3070 ASSERT(!m_simpleLineLayout);
3074 bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
3077 if (containsStart) {
3078 // Update our lastLogicalTop to be the bottom of the block. <hr>s or empty blocks with height can trip this case.
3079 lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
3080 lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight(), cache);
3081 lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight(), cache);
3086 RootInlineBox* lastSelectedLine = 0;
3087 RootInlineBox* curr;
3088 for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
3090 // Now paint the gaps for the lines.
3091 for (; curr && curr->hasSelectedChildren(); curr = curr->nextRootBox()) {
3092 LayoutUnit selTop = curr->selectionTopAdjustedForPrecedingBlock();
3093 LayoutUnit selHeight = curr->selectionHeightAdjustedForPrecedingBlock();
3095 if (!containsStart && !lastSelectedLine &&
3096 selectionState() != SelectionStart && selectionState() != SelectionBoth && !isRubyBase())
3097 result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, selTop, cache, paintInfo));
3099 LayoutRect logicalRect(curr->logicalLeft(), selTop, curr->logicalWidth(), selTop + selHeight);
3100 logicalRect.move(isHorizontalWritingMode() ? offsetFromRootBlock : offsetFromRootBlock.transposedSize());
3101 LayoutRect physicalRect = rootBlock.logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
3102 if (!paintInfo || (isHorizontalWritingMode() && physicalRect.y() < paintInfo->rect.maxY() && physicalRect.maxY() > paintInfo->rect.y())
3103 || (!isHorizontalWritingMode() && physicalRect.x() < paintInfo->rect.maxX() && physicalRect.maxX() > paintInfo->rect.x()))
3104 result.unite(curr->lineSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, selTop, selHeight, cache, paintInfo));
3106 lastSelectedLine = curr;
3109 if (containsStart && !lastSelectedLine)
3110 // VisibleSelection must start just after our last line.
3111 lastSelectedLine = lastRootBox();
3113 if (lastSelectedLine && selectionState() != SelectionEnd && selectionState() != SelectionBoth) {
3114 // Update our lastY to be the bottom of the last selected line.
3115 lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + lastSelectedLine->selectionBottom();
3116 lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, lastSelectedLine->selectionBottom(), cache);
3117 lastLogicalRight = logicalRightSelectionOffset(rootBlock, lastSelectedLine->selectionBottom(), cache);
3122 bool RenderBlockFlow::needsLayoutAfterFragmentRangeChange() const
3124 // A block without floats or that expands to enclose them won't need a relayout
3125 // after a fragment range change. There is no overflow content needing relayout
3126 // in the fragment chain because the fragment range can only shrink after the estimation.
3127 if (!containsFloats() || createsNewFormattingContext())
3133 void RenderBlockFlow::setMultiColumnFlow(RenderMultiColumnFlow& fragmentedFlow)
3135 ASSERT(!hasRareBlockFlowData() || !rareBlockFlowData()->m_multiColumnFlow);
3136 ensureRareBlockFlowData().m_multiColumnFlow = makeWeakPtr(fragmentedFlow);
3139 void RenderBlockFlow::clearMultiColumnFlow()
3141 ASSERT(hasRareBlockFlowData());
3142 ASSERT(rareBlockFlowData()->m_multiColumnFlow);
3143 rareBlockFlowData()->m_multiColumnFlow.clear();
3146 static bool shouldCheckLines(const RenderBlockFlow& blockFlow)
3148 return !blockFlow.isFloatingOrOutOfFlowPositioned() && blockFlow.style().height().isAuto();
3151 RootInlineBox* RenderBlockFlow::lineAtIndex(int i) const
3155 if (style().visibility() != VISIBLE)
3158 if (childrenInline()) {