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 "HTMLTextAreaElement.h"
34 #include "HitTestLocation.h"
35 #include "InlineTextBox.h"
36 #include "LayoutRepainter.h"
38 #include "RenderCombineText.h"
39 #include "RenderInline.h"
40 #include "RenderIterator.h"
41 #include "RenderLayer.h"
42 #include "RenderLineBreak.h"
43 #include "RenderListItem.h"
44 #include "RenderMarquee.h"
45 #include "RenderMultiColumnFlowThread.h"
46 #include "RenderMultiColumnSet.h"
47 #include "RenderNamedFlowFragment.h"
48 #include "RenderNamedFlowThread.h"
49 #include "RenderTableCell.h"
50 #include "RenderText.h"
51 #include "RenderView.h"
53 #include "SimpleLineLayoutFunctions.h"
54 #include "SimpleLineLayoutPagination.h"
55 #include "VerticalPositionCache.h"
56 #include "VisiblePosition.h"
60 bool RenderBlock::s_canPropagateFloatIntoSibling = false;
62 struct SameSizeAsMarginInfo {
63 uint32_t bitfields : 16;
64 LayoutUnit margins[2];
67 COMPILE_ASSERT(sizeof(RenderBlockFlow::MarginValues) == sizeof(LayoutUnit[4]), MarginValues_should_stay_small);
68 COMPILE_ASSERT(sizeof(RenderBlockFlow::MarginInfo) == sizeof(SameSizeAsMarginInfo), MarginInfo_should_stay_small);
70 // Our MarginInfo state used when laying out block children.
71 RenderBlockFlow::MarginInfo::MarginInfo(const RenderBlockFlow& block, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding)
72 : m_atBeforeSideOfBlock(true)
73 , m_atAfterSideOfBlock(false)
74 , m_hasMarginBeforeQuirk(false)
75 , m_hasMarginAfterQuirk(false)
76 , m_determinedMarginBeforeQuirk(false)
77 , m_discardMargin(false)
79 const RenderStyle& blockStyle = block.style();
80 ASSERT(block.isRenderView() || block.parent());
81 m_canCollapseWithChildren = !block.createsNewFormattingContext() && !block.isRenderView();
83 m_canCollapseMarginBeforeWithChildren = m_canCollapseWithChildren && !beforeBorderPadding && blockStyle.marginBeforeCollapse() != MSEPARATE;
85 // If any height other than auto is specified in CSS, then we don't collapse our bottom
86 // margins with our children's margins. To do otherwise would be to risk odd visual
87 // effects when the children overflow out of the parent block and yet still collapse
88 // with it. We also don't collapse if we have any bottom border/padding.
89 m_canCollapseMarginAfterWithChildren = m_canCollapseWithChildren && !afterBorderPadding
90 && (blockStyle.logicalHeight().isAuto() && !blockStyle.logicalHeight().value()) && blockStyle.marginAfterCollapse() != MSEPARATE;
92 m_quirkContainer = block.isTableCell() || block.isBody();
94 m_discardMargin = m_canCollapseMarginBeforeWithChildren && block.mustDiscardMarginBefore();
96 m_positiveMargin = (m_canCollapseMarginBeforeWithChildren && !block.mustDiscardMarginBefore()) ? block.maxPositiveMarginBefore() : LayoutUnit();
97 m_negativeMargin = (m_canCollapseMarginBeforeWithChildren && !block.mustDiscardMarginBefore()) ? block.maxNegativeMarginBefore() : LayoutUnit();
100 RenderBlockFlow::RenderBlockFlow(Element& element, RenderStyle&& style)
101 : RenderBlock(element, WTFMove(style), RenderBlockFlowFlag)
102 #if ENABLE(TEXT_AUTOSIZING)
103 , m_widthForTextAutosizing(-1)
104 , m_lineCountForTextAutosizing(NOT_SET)
107 setChildrenInline(true);
110 RenderBlockFlow::RenderBlockFlow(Document& document, RenderStyle&& style)
111 : RenderBlock(document, WTFMove(style), RenderBlockFlowFlag)
112 #if ENABLE(TEXT_AUTOSIZING)
113 , m_widthForTextAutosizing(-1)
114 , m_lineCountForTextAutosizing(NOT_SET)
117 setChildrenInline(true);
120 RenderBlockFlow::~RenderBlockFlow()
122 // Do not add any code here. Add it to willBeDestroyed() instead.
125 void RenderBlockFlow::createMultiColumnFlowThread()
127 RenderMultiColumnFlowThread* flowThread = new RenderMultiColumnFlowThread(document(), RenderStyle::createAnonymousStyleWithDisplay(style(), BLOCK));
128 flowThread->initializeStyle();
129 setChildrenInline(false); // Do this to avoid wrapping inline children that are just going to move into the flow thread.
131 RenderBlock::addChild(flowThread);
132 flowThread->populate(); // Called after the flow thread is inserted so that we are reachable by the flow thread.
133 setMultiColumnFlowThread(flowThread);
136 void RenderBlockFlow::destroyMultiColumnFlowThread()
138 multiColumnFlowThread()->evacuateAndDestroy();
139 ASSERT(!multiColumnFlowThread());
142 void RenderBlockFlow::insertedIntoTree()
144 RenderBlock::insertedIntoTree();
145 createRenderNamedFlowFragmentIfNeeded();
148 void RenderBlockFlow::willBeDestroyed()
150 if (renderNamedFlowFragment())
151 setRenderNamedFlowFragment(nullptr);
153 // Make sure to destroy anonymous children first while they are still connected to the rest of the tree, so that they will
154 // properly dirty line boxes that they are removed from. Effects that do :before/:after only on hover could crash otherwise.
155 destroyLeftoverChildren();
157 if (!renderTreeBeingDestroyed()) {
158 if (firstRootBox()) {
159 // We can't wait for RenderBox::destroy to clear the selection,
160 // because by then we will have nuked the line boxes.
161 if (isSelectionBorder())
162 frame().selection().setNeedsSelectionUpdate();
164 // If we are an anonymous block, then our line boxes might have children
165 // that will outlast this block. In the non-anonymous block case those
166 // children will be destroyed by the time we return from this function.
167 if (isAnonymousBlock()) {
168 for (auto* box = firstRootBox(); box; box = box->nextRootBox()) {
169 while (auto childBox = box->firstChild())
170 childBox->removeFromParent();
174 parent()->dirtyLinesFromChangedChild(*this);
177 m_lineBoxes.deleteLineBoxes();
179 blockWillBeDestroyed();
181 // NOTE: This jumps down to RenderBox, bypassing RenderBlock since it would do duplicate work.
182 RenderBox::willBeDestroyed();
185 RenderBlockFlow* RenderBlockFlow::previousSiblingWithOverhangingFloats(bool& parentHasFloats) const
187 // Attempt to locate a previous sibling with overhanging floats. We skip any elements that are
188 // out of flow (like floating/positioned elements), and we also skip over any objects that may have shifted
190 parentHasFloats = false;
191 for (RenderObject* sibling = previousSibling(); sibling; sibling = sibling->previousSibling()) {
192 if (is<RenderBlockFlow>(*sibling)) {
193 auto& siblingBlock = downcast<RenderBlockFlow>(*sibling);
194 if (!siblingBlock.avoidsFloats())
195 return &siblingBlock;
197 if (sibling->isFloating())
198 parentHasFloats = true;
203 void RenderBlockFlow::rebuildFloatingObjectSetFromIntrudingFloats()
205 if (m_floatingObjects)
206 m_floatingObjects->setHorizontalWritingMode(isHorizontalWritingMode());
208 HashSet<RenderBox*> oldIntrudingFloatSet;
209 if (!childrenInline() && m_floatingObjects) {
210 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
211 auto end = floatingObjectSet.end();
212 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
213 FloatingObject* floatingObject = it->get();
214 if (!floatingObject->isDescendant())
215 oldIntrudingFloatSet.add(&floatingObject->renderer());
219 // Inline blocks are covered by the isReplaced() check in the avoidFloats method.
220 if (avoidsFloats() || isDocumentElementRenderer() || isRenderView() || isFloatingOrOutOfFlowPositioned() || isTableCell()) {
221 if (m_floatingObjects)
222 m_floatingObjects->clear();
223 if (!oldIntrudingFloatSet.isEmpty())
224 markAllDescendantsWithFloatsForLayout();
228 RendererToFloatInfoMap floatMap;
230 if (m_floatingObjects) {
231 if (childrenInline())
232 m_floatingObjects->moveAllToFloatInfoMap(floatMap);
234 m_floatingObjects->clear();
237 // We should not process floats if the parent node is not a RenderBlock. Otherwise, we will add
238 // floats in an invalid context. This will cause a crash arising from a bad cast on the parent.
239 // See <rdar://problem/8049753>, where float property is applied on a text node in a SVG.
240 bool isBlockInsideInline = isAnonymousInlineBlock();
241 if (!is<RenderBlockFlow>(parent()) && !isBlockInsideInline)
244 // First add in floats from the parent. Self-collapsing blocks let their parent track any floats that intrude into
245 // them (as opposed to floats they contain themselves) so check for those here too.
246 RenderBlockFlow& parentBlock = downcast<RenderBlockFlow>(isBlockInsideInline ? *containingBlock() : *parent());
247 bool parentHasFloats = isBlockInsideInline ? parentBlock.containsFloats() : false;
248 RenderBlockFlow* previousBlock = nullptr;
249 if (!isBlockInsideInline)
250 previousBlock = previousSiblingWithOverhangingFloats(parentHasFloats);
251 LayoutUnit logicalTopOffset = logicalTop();
252 if (parentHasFloats || (parentBlock.lowestFloatLogicalBottom() > logicalTopOffset && previousBlock && previousBlock->isSelfCollapsingBlock()))
253 addIntrudingFloats(&parentBlock, &parentBlock, parentBlock.logicalLeftOffsetForContent(), logicalTopOffset);
255 LayoutUnit logicalLeftOffset = 0;
257 logicalTopOffset -= previousBlock->logicalTop();
259 previousBlock = &parentBlock;
260 logicalLeftOffset += parentBlock.logicalLeftOffsetForContent();
263 // Add overhanging floats from the previous RenderBlock, but only if it has a float that intrudes into our space.
264 if (previousBlock->m_floatingObjects && previousBlock->lowestFloatLogicalBottom() > logicalTopOffset)
265 addIntrudingFloats(previousBlock, &parentBlock, logicalLeftOffset, logicalTopOffset);
267 if (childrenInline()) {
268 LayoutUnit changeLogicalTop = LayoutUnit::max();
269 LayoutUnit changeLogicalBottom = LayoutUnit::min();
270 if (m_floatingObjects) {
271 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
272 auto end = floatingObjectSet.end();
273 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
274 const auto& floatingObject = *it->get();
275 std::unique_ptr<FloatingObject> oldFloatingObject = floatMap.take(&floatingObject.renderer());
276 LayoutUnit logicalBottom = logicalBottomForFloat(floatingObject);
277 if (oldFloatingObject) {
278 LayoutUnit oldLogicalBottom = logicalBottomForFloat(*oldFloatingObject);
279 if (logicalWidthForFloat(floatingObject) != logicalWidthForFloat(*oldFloatingObject) || logicalLeftForFloat(floatingObject) != logicalLeftForFloat(*oldFloatingObject)) {
280 changeLogicalTop = 0;
281 changeLogicalBottom = std::max(changeLogicalBottom, std::max(logicalBottom, oldLogicalBottom));
283 if (logicalBottom != oldLogicalBottom) {
284 changeLogicalTop = std::min(changeLogicalTop, std::min(logicalBottom, oldLogicalBottom));
285 changeLogicalBottom = std::max(changeLogicalBottom, std::max(logicalBottom, oldLogicalBottom));
287 LayoutUnit logicalTop = logicalTopForFloat(floatingObject);
288 LayoutUnit oldLogicalTop = logicalTopForFloat(*oldFloatingObject);
289 if (logicalTop != oldLogicalTop) {
290 changeLogicalTop = std::min(changeLogicalTop, std::min(logicalTop, oldLogicalTop));
291 changeLogicalBottom = std::max(changeLogicalBottom, std::max(logicalTop, oldLogicalTop));
295 if (oldFloatingObject->originatingLine() && !selfNeedsLayout()) {
296 ASSERT(&oldFloatingObject->originatingLine()->renderer() == this);
297 oldFloatingObject->originatingLine()->markDirty();
300 changeLogicalTop = 0;
301 changeLogicalBottom = std::max(changeLogicalBottom, logicalBottom);
306 auto end = floatMap.end();
307 for (auto it = floatMap.begin(); it != end; ++it) {
308 const auto& floatingObject = *it->value.get();
309 if (!floatingObject.isDescendant()) {
310 changeLogicalTop = 0;
311 changeLogicalBottom = std::max(changeLogicalBottom, logicalBottomForFloat(floatingObject));
315 markLinesDirtyInBlockRange(changeLogicalTop, changeLogicalBottom);
316 } else if (!oldIntrudingFloatSet.isEmpty()) {
317 // If there are previously intruding floats that no longer intrude, then children with floats
318 // should also get layout because they might need their floating object lists cleared.
319 if (m_floatingObjects->set().size() < oldIntrudingFloatSet.size())
320 markAllDescendantsWithFloatsForLayout();
322 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
323 auto end = floatingObjectSet.end();
324 for (auto it = floatingObjectSet.begin(); it != end && !oldIntrudingFloatSet.isEmpty(); ++it)
325 oldIntrudingFloatSet.remove(&(*it)->renderer());
326 if (!oldIntrudingFloatSet.isEmpty())
327 markAllDescendantsWithFloatsForLayout();
332 void RenderBlockFlow::adjustIntrinsicLogicalWidthsForColumns(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
334 if (!style().hasAutoColumnCount() || !style().hasAutoColumnWidth()) {
335 // The min/max intrinsic widths calculated really tell how much space elements need when
336 // laid out inside the columns. In order to eventually end up with the desired column width,
337 // we need to convert them to values pertaining to the multicol container.
338 int columnCount = style().hasAutoColumnCount() ? 1 : style().columnCount();
339 LayoutUnit columnWidth;
340 LayoutUnit colGap = columnGap();
341 LayoutUnit gapExtra = (columnCount - 1) * colGap;
342 if (style().hasAutoColumnWidth())
343 minLogicalWidth = minLogicalWidth * columnCount + gapExtra;
345 columnWidth = style().columnWidth();
346 minLogicalWidth = std::min(minLogicalWidth, columnWidth);
348 // FIXME: If column-count is auto here, we should resolve it to calculate the maximum
349 // intrinsic width, instead of pretending that it's 1. The only way to do that is by
350 // performing a layout pass, but this is not an appropriate time or place for layout. The
351 // good news is that if height is unconstrained and there are no explicit breaks, the
352 // resolved column-count really should be 1.
353 maxLogicalWidth = std::max(maxLogicalWidth, columnWidth) * columnCount + gapExtra;
357 void RenderBlockFlow::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
359 if (childrenInline())
360 computeInlinePreferredLogicalWidths(minLogicalWidth, maxLogicalWidth);
362 computeBlockPreferredLogicalWidths(minLogicalWidth, maxLogicalWidth);
364 maxLogicalWidth = std::max(minLogicalWidth, maxLogicalWidth);
366 adjustIntrinsicLogicalWidthsForColumns(minLogicalWidth, maxLogicalWidth);
368 if (!style().autoWrap() && childrenInline()) {
369 // A horizontal marquee with inline children has no minimum width.
370 if (layer() && layer()->marquee() && layer()->marquee()->isHorizontal())
374 if (is<RenderTableCell>(*this)) {
375 Length tableCellWidth = downcast<RenderTableCell>(*this).styleOrColLogicalWidth();
376 if (tableCellWidth.isFixed() && tableCellWidth.value() > 0)
377 maxLogicalWidth = std::max(minLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(tableCellWidth.value()));
380 int scrollbarWidth = intrinsicScrollbarLogicalWidth();
381 maxLogicalWidth += scrollbarWidth;
382 minLogicalWidth += scrollbarWidth;
385 bool RenderBlockFlow::recomputeLogicalWidthAndColumnWidth()
387 bool changed = recomputeLogicalWidth();
389 LayoutUnit oldColumnWidth = computedColumnWidth();
390 computeColumnCountAndWidth();
392 return changed || oldColumnWidth != computedColumnWidth();
395 LayoutUnit RenderBlockFlow::columnGap() const
397 if (style().hasNormalColumnGap())
398 return style().fontDescription().computedPixelSize(); // "1em" is recommended as the normal gap setting. Matches <p> margins.
399 return style().columnGap();
402 void RenderBlockFlow::computeColumnCountAndWidth()
404 // Calculate our column width and column count.
405 // FIXME: Can overflow on fast/block/float/float-not-removed-from-next-sibling4.html, see https://bugs.webkit.org/show_bug.cgi?id=68744
406 unsigned desiredColumnCount = 1;
407 LayoutUnit desiredColumnWidth = contentLogicalWidth();
409 // For now, we don't support multi-column layouts when printing, since we have to do a lot of work for proper pagination.
410 if (document().paginated() || (style().hasAutoColumnCount() && style().hasAutoColumnWidth()) || !style().hasInlineColumnAxis()) {
411 setComputedColumnCountAndWidth(desiredColumnCount, desiredColumnWidth);
415 LayoutUnit availWidth = desiredColumnWidth;
416 LayoutUnit colGap = columnGap();
417 LayoutUnit colWidth = std::max<LayoutUnit>(1, style().columnWidth());
418 unsigned colCount = std::max<unsigned>(1, style().columnCount());
420 if (style().hasAutoColumnWidth() && !style().hasAutoColumnCount()) {
421 desiredColumnCount = colCount;
422 desiredColumnWidth = std::max<LayoutUnit>(0, (availWidth - ((desiredColumnCount - 1) * colGap)) / desiredColumnCount);
423 } else if (!style().hasAutoColumnWidth() && style().hasAutoColumnCount()) {
424 desiredColumnCount = std::max<unsigned>(1, ((availWidth + colGap) / (colWidth + colGap)).toUnsigned());
425 desiredColumnWidth = ((availWidth + colGap) / desiredColumnCount) - colGap;
427 desiredColumnCount = std::max<unsigned>(std::min(colCount, ((availWidth + colGap) / (colWidth + colGap)).toUnsigned()), 1);
428 desiredColumnWidth = ((availWidth + colGap) / desiredColumnCount) - colGap;
430 setComputedColumnCountAndWidth(desiredColumnCount, desiredColumnWidth);
433 bool RenderBlockFlow::willCreateColumns(std::optional<unsigned> desiredColumnCount) const
435 // The following types are not supposed to create multicol context.
436 if (isFileUploadControl() || isTextControl() || isListBox())
442 // 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.
443 if ((style().overflowY() == OPAGEDX || style().overflowY() == OPAGEDY) && !(isDocumentElementRenderer() || isBody()))
446 if (!style().specifiesColumns())
449 // column-axis with opposite writing direction initiates MultiColumnFlowThread.
450 if (!style().hasInlineColumnAxis())
453 // Non-auto column-width always initiates MultiColumnFlowThread.
454 if (!style().hasAutoColumnWidth())
457 if (desiredColumnCount)
458 return desiredColumnCount.value() > 1;
460 // column-count > 1 always initiates MultiColumnFlowThread.
461 if (!style().hasAutoColumnCount())
462 return style().columnCount() > 1;
464 ASSERT_NOT_REACHED();
468 void RenderBlockFlow::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight)
470 ASSERT(needsLayout());
472 if (!relayoutChildren && simplifiedLayout())
475 LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
477 if (recomputeLogicalWidthAndColumnWidth())
478 relayoutChildren = true;
480 rebuildFloatingObjectSetFromIntrudingFloats();
482 LayoutUnit previousHeight = logicalHeight();
483 // FIXME: should this start out as borderAndPaddingLogicalHeight() + scrollbarLogicalHeight(),
484 // for consistency with other render classes?
487 bool pageLogicalHeightChanged = false;
488 checkForPaginationLogicalHeightChange(relayoutChildren, pageLogicalHeight, pageLogicalHeightChanged);
490 const RenderStyle& styleToUse = style();
491 LayoutStateMaintainer statePusher(view(), *this, locationOffset(), hasTransform() || hasReflection() || styleToUse.isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged);
493 preparePaginationBeforeBlockLayout(relayoutChildren);
494 if (!relayoutChildren)
495 relayoutChildren = namedFlowFragmentNeedsUpdate();
497 // We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
498 // our current maximal positive and negative margins. These values are used when we
499 // are collapsed with adjacent blocks, so for example, if you have block A and B
500 // collapsing together, then you'd take the maximal positive margin from both A and B
501 // and subtract it from the maximal negative margin from both A and B to get the
502 // true collapsed margin. This algorithm is recursive, so when we finish layout()
503 // our block knows its current maximal positive/negative values.
505 // Start out by setting our margin values to our current margins. Table cells have
506 // no margins, so we don't fill in the values for table cells.
507 bool isCell = isTableCell();
509 initMaxMarginValues();
511 setHasMarginBeforeQuirk(styleToUse.hasMarginBeforeQuirk());
512 setHasMarginAfterQuirk(styleToUse.hasMarginAfterQuirk());
513 setPaginationStrut(0);
516 LayoutUnit repaintLogicalTop = 0;
517 LayoutUnit repaintLogicalBottom = 0;
518 LayoutUnit maxFloatLogicalBottom = 0;
519 if (!firstChild() && !isAnonymousBlock())
520 setChildrenInline(true);
521 if (childrenInline())
522 layoutInlineChildren(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
524 layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom);
526 // Expand our intrinsic height to encompass floats.
527 LayoutUnit toAdd = borderAndPaddingAfter() + scrollbarLogicalHeight();
528 if (lowestFloatLogicalBottom() > (logicalHeight() - toAdd) && createsNewFormattingContext())
529 setLogicalHeight(lowestFloatLogicalBottom() + toAdd);
531 if (relayoutForPagination(statePusher) || relayoutToAvoidWidows(statePusher)) {
532 ASSERT(!shouldBreakAtLineToAvoidWidow());
536 // Calculate our new height.
537 LayoutUnit oldHeight = logicalHeight();
538 LayoutUnit oldClientAfterEdge = clientLogicalBottom();
540 // Before updating the final size of the flow thread make sure a forced break is applied after the content.
541 // This ensures the size information is correctly computed for the last auto-height region receiving content.
542 if (is<RenderFlowThread>(*this))
543 downcast<RenderFlowThread>(*this).applyBreakAfterContent(oldClientAfterEdge);
545 updateLogicalHeight();
546 LayoutUnit newHeight = logicalHeight();
547 if (oldHeight != newHeight) {
548 if (oldHeight > newHeight && maxFloatLogicalBottom > newHeight && !childrenInline()) {
549 // One of our children's floats may have become an overhanging float for us. We need to look for it.
550 for (auto& blockFlow : childrenOfType<RenderBlockFlow>(*this)) {
551 if (blockFlow.isFloatingOrOutOfFlowPositioned())
553 if (blockFlow.lowestFloatLogicalBottom() + blockFlow.logicalTop() > newHeight)
554 addOverhangingFloats(blockFlow, false);
559 bool heightChanged = (previousHeight != newHeight);
561 relayoutChildren = true;
563 layoutPositionedObjects(relayoutChildren || isDocumentElementRenderer());
565 // Add overflow from children (unless we're multi-column, since in that case all our child overflow is clipped anyway).
566 computeOverflow(oldClientAfterEdge);
570 fitBorderToLinesIfNeeded();
572 if (view().layoutState()->m_pageLogicalHeight)
573 setPageLogicalOffset(view().layoutState()->pageLogicalOffset(this, logicalTop()));
575 updateLayerTransform();
577 // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
578 // we overflow or not.
579 updateScrollInfoAfterLayout();
581 // FIXME: This repaint logic should be moved into a separate helper function!
582 // Repaint with our new bounds if they are different from our old bounds.
583 bool didFullRepaint = repainter.repaintAfterLayout();
584 if (!didFullRepaint && repaintLogicalTop != repaintLogicalBottom && (styleToUse.visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
585 // FIXME: We could tighten up the left and right invalidation points if we let layoutInlineChildren fill them in based off the particular lines
586 // it had to lay out. We wouldn't need the hasOverflowClip() hack in that case either.
587 LayoutUnit repaintLogicalLeft = logicalLeftVisualOverflow();
588 LayoutUnit repaintLogicalRight = logicalRightVisualOverflow();
589 if (hasOverflowClip()) {
590 // 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.
591 // 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.
592 // layoutInlineChildren should be patched to compute the entire repaint rect.
593 repaintLogicalLeft = std::min(repaintLogicalLeft, logicalLeftLayoutOverflow());
594 repaintLogicalRight = std::max(repaintLogicalRight, logicalRightLayoutOverflow());
597 LayoutRect repaintRect;
598 if (isHorizontalWritingMode())
599 repaintRect = LayoutRect(repaintLogicalLeft, repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop);
601 repaintRect = LayoutRect(repaintLogicalTop, repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft);
603 if (hasOverflowClip()) {
604 // Adjust repaint rect for scroll offset
605 repaintRect.moveBy(-scrollPosition());
607 // Don't allow this rect to spill out of our overflow box.
608 repaintRect.intersect(LayoutRect(LayoutPoint(), size()));
611 // Make sure the rect is still non-empty after intersecting for overflow above
612 if (!repaintRect.isEmpty()) {
613 repaintRectangle(repaintRect); // We need to do a partial repaint of our content.
615 repaintRectangle(reflectedRect(repaintRect));
622 void RenderBlockFlow::layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom)
624 dirtyForLayoutFromPercentageHeightDescendants();
626 LayoutUnit beforeEdge = borderAndPaddingBefore();
627 LayoutUnit afterEdge = borderAndPaddingAfter() + scrollbarLogicalHeight();
629 setLogicalHeight(beforeEdge);
631 // Lay out our hypothetical grid line as though it occurs at the top of the block.
632 if (view().layoutState()->lineGrid() == this)
635 // The margin struct caches all our current margin collapsing state.
636 MarginInfo marginInfo(*this, beforeEdge, afterEdge);
638 // Fieldsets need to find their legend and position it inside the border of the object.
639 // The legend then gets skipped during normal layout. The same is true for ruby text.
640 // It doesn't get included in the normal layout process but is instead skipped.
641 layoutExcludedChildren(relayoutChildren);
643 LayoutUnit previousFloatLogicalBottom = 0;
644 maxFloatLogicalBottom = 0;
646 RenderBox* next = firstChildBox();
649 RenderBox& child = *next;
650 next = child.nextSiblingBox();
652 if (child.isExcludedFromNormalLayout())
653 continue; // Skip this child, since it will be positioned by the specialized subclass (fieldsets and ruby runs).
655 updateBlockChildDirtyBitsBeforeLayout(relayoutChildren, child);
657 if (child.isOutOfFlowPositioned()) {
658 child.containingBlock()->insertPositionedObject(child);
659 adjustPositionedBlock(child, marginInfo);
662 if (child.isFloating()) {
663 insertFloatingObject(child);
664 adjustFloatingBlock(marginInfo);
668 // Lay out the child.
669 layoutBlockChild(child, marginInfo, previousFloatLogicalBottom, maxFloatLogicalBottom);
672 // Now do the handling of the bottom of the block, adding in our bottom border/padding and
673 // determining the correct collapsed bottom margin information.
674 handleAfterSideOfBlock(beforeEdge, afterEdge, marginInfo);
677 void RenderBlockFlow::layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom)
679 if (lineLayoutPath() == UndeterminedPath)
680 setLineLayoutPath(SimpleLineLayout::canUseFor(*this) ? SimpleLinesPath : LineBoxesPath);
682 if (lineLayoutPath() == SimpleLinesPath) {
683 layoutSimpleLines(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
687 m_simpleLineLayout = nullptr;
688 layoutLineBoxes(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
691 void RenderBlockFlow::layoutBlockChild(RenderBox& child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom)
693 LayoutUnit oldPosMarginBefore = maxPositiveMarginBefore();
694 LayoutUnit oldNegMarginBefore = maxNegativeMarginBefore();
696 // The child is a normal flow object. Compute the margins we will use for collapsing now.
697 child.computeAndSetBlockDirectionMargins(*this);
699 // Try to guess our correct logical top position. In most cases this guess will
700 // be correct. Only if we're wrong (when we compute the real logical top position)
701 // will we have to potentially relayout.
702 LayoutUnit estimateWithoutPagination;
703 LayoutUnit logicalTopEstimate = estimateLogicalTopPosition(child, marginInfo, estimateWithoutPagination);
705 // Cache our old rect so that we can dirty the proper repaint rects if the child moves.
706 LayoutRect oldRect = child.frameRect();
707 LayoutUnit oldLogicalTop = logicalTopForChild(child);
710 LayoutSize oldLayoutDelta = view().layoutDelta();
712 // Position the child as though it didn't collapse with the top.
713 setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
714 estimateRegionRangeForBoxChild(child);
716 RenderBlockFlow* childBlockFlow = is<RenderBlockFlow>(child) ? &downcast<RenderBlockFlow>(child) : nullptr;
717 bool markDescendantsWithFloats = false;
718 if (logicalTopEstimate != oldLogicalTop && !child.avoidsFloats() && childBlockFlow && childBlockFlow->containsFloats())
719 markDescendantsWithFloats = true;
720 else if (UNLIKELY(logicalTopEstimate.mightBeSaturated()))
721 // logicalTopEstimate, returned by estimateLogicalTopPosition, might be saturated for
722 // very large elements. If it does the comparison with oldLogicalTop might yield a
723 // false negative as adding and removing margins, borders etc from a saturated number
724 // might yield incorrect results. If this is the case always mark for layout.
725 markDescendantsWithFloats = true;
726 else if (!child.avoidsFloats() || child.shrinkToAvoidFloats()) {
727 // If an element might be affected by the presence of floats, then always mark it for
729 LayoutUnit fb = std::max(previousFloatLogicalBottom, lowestFloatLogicalBottom());
730 if (fb > logicalTopEstimate)
731 markDescendantsWithFloats = true;
734 if (childBlockFlow) {
735 if (markDescendantsWithFloats)
736 childBlockFlow->markAllDescendantsWithFloatsForLayout();
737 if (!child.isWritingModeRoot())
738 previousFloatLogicalBottom = std::max(previousFloatLogicalBottom, oldLogicalTop + childBlockFlow->lowestFloatLogicalBottom());
741 child.markForPaginationRelayoutIfNeeded();
743 bool childHadLayout = child.everHadLayout();
744 bool childNeededLayout = child.needsLayout();
745 if (childNeededLayout)
748 // Cache if we are at the top of the block right now.
749 bool atBeforeSideOfBlock = marginInfo.atBeforeSideOfBlock();
751 // Now determine the correct ypos based off examination of collapsing margin
753 LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo);
755 // Now check for clear.
756 LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear);
758 bool paginated = view().layoutState()->isPaginated();
760 logicalTopAfterClear = adjustBlockChildForPagination(logicalTopAfterClear, estimateWithoutPagination, child, atBeforeSideOfBlock && logicalTopBeforeClear == logicalTopAfterClear);
762 setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
764 // Now we have a final top position. See if it really does end up being different from our estimate.
765 // clearFloatsIfNeeded can also mark the child as needing a layout even though we didn't move. This happens
766 // when collapseMargins dynamically adds overhanging floats because of a child with negative margins.
767 if (logicalTopAfterClear != logicalTopEstimate || child.needsLayout() || (paginated && childBlockFlow && childBlockFlow->shouldBreakAtLineToAvoidWidow())) {
768 if (child.shrinkToAvoidFloats()) {
769 // The child's width depends on the line width. When the child shifts to clear an item, its width can
770 // change (because it has more available line width). So mark the item as dirty.
771 child.setChildNeedsLayout(MarkOnlyThis);
774 if (childBlockFlow) {
775 if (!child.avoidsFloats() && childBlockFlow->containsFloats())
776 childBlockFlow->markAllDescendantsWithFloatsForLayout();
777 child.markForPaginationRelayoutIfNeeded();
781 if (updateRegionRangeForBoxChild(child))
782 child.setNeedsLayout(MarkOnlyThis);
784 // In case our guess was wrong, relayout the child.
785 child.layoutIfNeeded();
787 // We are no longer at the top of the block if we encounter a non-empty child.
788 // This has to be done after checking for clear, so that margins can be reset if a clear occurred.
789 if (marginInfo.atBeforeSideOfBlock() && !child.isSelfCollapsingBlock())
790 marginInfo.setAtBeforeSideOfBlock(false);
792 // Now place the child in the correct left position
793 determineLogicalLeftPositionForChild(child, ApplyLayoutDelta);
795 // Update our height now that the child has been placed in the correct position.
796 setLogicalHeight(logicalHeight() + logicalHeightForChildForFragmentation(child));
797 if (mustSeparateMarginAfterForChild(child)) {
798 setLogicalHeight(logicalHeight() + marginAfterForChild(child));
799 marginInfo.clearMargin();
801 // If the child has overhanging floats that intrude into following siblings (or possibly out
802 // of this block), then the parent gets notified of the floats now.
803 if (childBlockFlow && childBlockFlow->containsFloats())
804 maxFloatLogicalBottom = std::max(maxFloatLogicalBottom, addOverhangingFloats(*childBlockFlow, !childNeededLayout));
806 LayoutSize childOffset = child.location() - oldRect.location();
807 if (childOffset.width() || childOffset.height()) {
808 view().addLayoutDelta(childOffset);
810 // If the child moved, we have to repaint it as well as any floating/positioned
811 // descendants. An exception is if we need a layout. In this case, we know we're going to
812 // repaint ourselves (and the child) anyway.
813 if (childHadLayout && !selfNeedsLayout() && child.checkForRepaintDuringLayout())
814 child.repaintDuringLayoutIfMoved(oldRect);
817 if (!childHadLayout && child.checkForRepaintDuringLayout()) {
819 child.repaintOverhangingFloats(true);
823 if (RenderFlowThread* flowThread = flowThreadContainingBlock())
824 flowThread->flowThreadDescendantBoxLaidOut(&child);
825 // Check for an after page/column break.
826 LayoutUnit newHeight = applyAfterBreak(child, logicalHeight(), marginInfo);
827 if (newHeight != height())
828 setLogicalHeight(newHeight);
831 ASSERT(view().layoutDeltaMatches(oldLayoutDelta));
834 void RenderBlockFlow::adjustPositionedBlock(RenderBox& child, const MarginInfo& marginInfo)
836 bool isHorizontal = isHorizontalWritingMode();
837 bool hasStaticBlockPosition = child.style().hasStaticBlockPosition(isHorizontal);
839 LayoutUnit logicalTop = logicalHeight();
840 updateStaticInlinePositionForChild(child, logicalTop, DoNotIndentText);
842 if (!marginInfo.canCollapseWithMarginBefore()) {
843 // Positioned blocks don't collapse margins, so add the margin provided by
844 // the container now. The child's own margin is added later when calculating its logical top.
845 LayoutUnit collapsedBeforePos = marginInfo.positiveMargin();
846 LayoutUnit collapsedBeforeNeg = marginInfo.negativeMargin();
847 logicalTop += collapsedBeforePos - collapsedBeforeNeg;
850 RenderLayer* childLayer = child.layer();
851 if (childLayer->staticBlockPosition() != logicalTop) {
852 childLayer->setStaticBlockPosition(logicalTop);
853 if (hasStaticBlockPosition)
854 child.setChildNeedsLayout(MarkOnlyThis);
858 LayoutUnit RenderBlockFlow::marginOffsetForSelfCollapsingBlock()
860 ASSERT(isSelfCollapsingBlock());
861 RenderBlockFlow* parentBlock = downcast<RenderBlockFlow>(parent());
862 if (parentBlock && style().clear() && parentBlock->getClearDelta(*this, logicalHeight()))
863 return marginValuesForChild(*this).positiveMarginBefore();
867 void RenderBlockFlow::determineLogicalLeftPositionForChild(RenderBox& child, ApplyLayoutDeltaMode applyDelta)
869 LayoutUnit startPosition = borderStart() + paddingStart();
870 if (shouldPlaceBlockDirectionScrollbarOnLeft())
871 startPosition += (style().isLeftToRightDirection() ? 1 : -1) * verticalScrollbarWidth();
872 LayoutUnit totalAvailableLogicalWidth = borderAndPaddingLogicalWidth() + availableLogicalWidth();
874 // Add in our start margin.
875 LayoutUnit childMarginStart = marginStartForChild(child);
876 LayoutUnit newPosition = startPosition + childMarginStart;
878 // Some objects (e.g., tables, horizontal rules, overflow:auto blocks) avoid floats. They need
879 // to shift over as necessary to dodge any floats that might get in the way.
880 if (child.avoidsFloats() && containsFloats() && !is<RenderNamedFlowThread>(flowThreadContainingBlock()))
881 newPosition += computeStartPositionDeltaForChildAvoidingFloats(child, marginStartForChild(child));
883 setLogicalLeftForChild(child, style().isLeftToRightDirection() ? newPosition : totalAvailableLogicalWidth - newPosition - logicalWidthForChild(child), applyDelta);
886 void RenderBlockFlow::adjustFloatingBlock(const MarginInfo& marginInfo)
888 // The float should be positioned taking into account the bottom margin
889 // of the previous flow. We add that margin into the height, get the
890 // float positioned properly, and then subtract the margin out of the
891 // height again. In the case of self-collapsing blocks, we always just
892 // use the top margins, since the self-collapsing block collapsed its
893 // own bottom margin into its top margin.
895 // Note also that the previous flow may collapse its margin into the top of
896 // our block. If this is the case, then we do not add the margin in to our
897 // height when computing the position of the float. This condition can be tested
898 // for by simply calling canCollapseWithMarginBefore. See
899 // http://www.hixie.ch/tests/adhoc/css/box/block/margin-collapse/046.html for
900 // an example of this scenario.
901 LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
902 setLogicalHeight(logicalHeight() + marginOffset);
904 setLogicalHeight(logicalHeight() - marginOffset);
907 void RenderBlockFlow::updateStaticInlinePositionForChild(RenderBox& child, LayoutUnit logicalTop, IndentTextOrNot shouldIndentText)
909 if (child.style().isOriginalDisplayInlineType())
910 setStaticInlinePositionForChild(child, logicalTop, startAlignedOffsetForLine(logicalTop, shouldIndentText));
912 setStaticInlinePositionForChild(child, logicalTop, startOffsetForContent(logicalTop));
915 void RenderBlockFlow::setStaticInlinePositionForChild(RenderBox& child, LayoutUnit blockOffset, LayoutUnit inlinePosition)
917 if (flowThreadContainingBlock()) {
918 // Shift the inline position to exclude the region offset.
919 inlinePosition += startOffsetForContent() - startOffsetForContent(blockOffset);
921 child.layer()->setStaticInlinePosition(inlinePosition);
924 RenderBlockFlow::MarginValues RenderBlockFlow::marginValuesForChild(RenderBox& child) const
926 LayoutUnit childBeforePositive = 0;
927 LayoutUnit childBeforeNegative = 0;
928 LayoutUnit childAfterPositive = 0;
929 LayoutUnit childAfterNegative = 0;
931 LayoutUnit beforeMargin = 0;
932 LayoutUnit afterMargin = 0;
934 RenderBlockFlow* childRenderBlock = is<RenderBlockFlow>(child) ? &downcast<RenderBlockFlow>(child) : nullptr;
936 // If the child has the same directionality as we do, then we can just return its
937 // margins in the same direction.
938 if (!child.isWritingModeRoot()) {
939 if (childRenderBlock) {
940 childBeforePositive = childRenderBlock->maxPositiveMarginBefore();
941 childBeforeNegative = childRenderBlock->maxNegativeMarginBefore();
942 childAfterPositive = childRenderBlock->maxPositiveMarginAfter();
943 childAfterNegative = childRenderBlock->maxNegativeMarginAfter();
945 beforeMargin = child.marginBefore();
946 afterMargin = child.marginAfter();
948 } else if (child.isHorizontalWritingMode() == isHorizontalWritingMode()) {
949 // The child has a different directionality. If the child is parallel, then it's just
950 // flipped relative to us. We can use the margins for the opposite edges.
951 if (childRenderBlock) {
952 childBeforePositive = childRenderBlock->maxPositiveMarginAfter();
953 childBeforeNegative = childRenderBlock->maxNegativeMarginAfter();
954 childAfterPositive = childRenderBlock->maxPositiveMarginBefore();
955 childAfterNegative = childRenderBlock->maxNegativeMarginBefore();
957 beforeMargin = child.marginAfter();
958 afterMargin = child.marginBefore();
961 // The child is perpendicular to us, which means its margins don't collapse but are on the
962 // "logical left/right" sides of the child box. We can just return the raw margin in this case.
963 beforeMargin = marginBeforeForChild(child);
964 afterMargin = marginAfterForChild(child);
967 // Resolve uncollapsing margins into their positive/negative buckets.
969 if (beforeMargin > 0)
970 childBeforePositive = beforeMargin;
972 childBeforeNegative = -beforeMargin;
976 childAfterPositive = afterMargin;
978 childAfterNegative = -afterMargin;
981 return MarginValues(childBeforePositive, childBeforeNegative, childAfterPositive, childAfterNegative);
984 bool RenderBlockFlow::childrenPreventSelfCollapsing() const
986 if (!childrenInline())
987 return RenderBlock::childrenPreventSelfCollapsing();
989 // If the block has inline children, see if we generated any line boxes. If we have any
990 // line boxes, then we can only be self-collapsing if we have nothing but anonymous inline blocks
991 // that are also self-collapsing inside us.
995 if (simpleLineLayout())
996 return true; // We have simple line layout lines, so we can't be self-collapsing.
998 for (auto* child = firstRootBox(); child; child = child->nextRootBox()) {
999 if (!child->hasAnonymousInlineBlock() || !child->anonymousInlineBlock()->isSelfCollapsingBlock())
1002 return false; // We have no line boxes, so we must be self-collapsing.
1005 LayoutUnit RenderBlockFlow::collapseMargins(RenderBox& child, MarginInfo& marginInfo)
1007 return collapseMarginsWithChildInfo(&child, child.previousSibling(), marginInfo);
1010 LayoutUnit RenderBlockFlow::collapseMarginsWithChildInfo(RenderBox* child, RenderObject* prevSibling, MarginInfo& marginInfo)
1012 bool childDiscardMarginBefore = child ? mustDiscardMarginBeforeForChild(*child) : false;
1013 bool childDiscardMarginAfter = child ? mustDiscardMarginAfterForChild(*child) : false;
1014 bool childIsSelfCollapsing = child ? child->isSelfCollapsingBlock() : false;
1015 bool beforeQuirk = child ? hasMarginBeforeQuirk(*child) : false;
1016 bool afterQuirk = child ? hasMarginAfterQuirk(*child) : false;
1018 // The child discards the before margin when the the after margin has discard in the case of a self collapsing block.
1019 childDiscardMarginBefore = childDiscardMarginBefore || (childDiscardMarginAfter && childIsSelfCollapsing);
1021 // Get the four margin values for the child and cache them.
1022 const MarginValues childMargins = child ? marginValuesForChild(*child) : MarginValues(0, 0, 0, 0);
1024 // Get our max pos and neg top margins.
1025 LayoutUnit posTop = childMargins.positiveMarginBefore();
1026 LayoutUnit negTop = childMargins.negativeMarginBefore();
1028 // For self-collapsing blocks, collapse our bottom margins into our
1029 // top to get new posTop and negTop values.
1030 if (childIsSelfCollapsing) {
1031 posTop = std::max(posTop, childMargins.positiveMarginAfter());
1032 negTop = std::max(negTop, childMargins.negativeMarginAfter());
1035 if (marginInfo.canCollapseWithMarginBefore()) {
1036 if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
1037 // This child is collapsing with the top of the
1038 // block. If it has larger margin values, then we need to update
1039 // our own maximal values.
1040 if (!document().inQuirksMode() || !marginInfo.quirkContainer() || !beforeQuirk)
1041 setMaxMarginBeforeValues(std::max(posTop, maxPositiveMarginBefore()), std::max(negTop, maxNegativeMarginBefore()));
1043 // The minute any of the margins involved isn't a quirk, don't
1044 // collapse it away, even if the margin is smaller (www.webreference.com
1045 // has an example of this, a <dt> with 0.8em author-specified inside
1046 // a <dl> inside a <td>.
1047 if (!marginInfo.determinedMarginBeforeQuirk() && !beforeQuirk && (posTop - negTop)) {
1048 setHasMarginBeforeQuirk(false);
1049 marginInfo.setDeterminedMarginBeforeQuirk(true);
1052 if (!marginInfo.determinedMarginBeforeQuirk() && beforeQuirk && !marginBefore()) {
1053 // We have no top margin and our top child has a quirky margin.
1054 // We will pick up this quirky margin and pass it through.
1055 // This deals with the <td><div><p> case.
1056 // Don't do this for a block that split two inlines though. You do
1057 // still apply margins in this case.
1058 setHasMarginBeforeQuirk(true);
1061 // The before margin of the container will also discard all the margins it is collapsing with.
1062 setMustDiscardMarginBefore();
1065 // Once we find a child with discardMarginBefore all the margins collapsing with us must also discard.
1066 if (childDiscardMarginBefore) {
1067 marginInfo.setDiscardMargin(true);
1068 marginInfo.clearMargin();
1071 if (marginInfo.quirkContainer() && marginInfo.atBeforeSideOfBlock() && (posTop - negTop))
1072 marginInfo.setHasMarginBeforeQuirk(beforeQuirk);
1074 LayoutUnit beforeCollapseLogicalTop = logicalHeight();
1075 LayoutUnit logicalTop = beforeCollapseLogicalTop;
1077 LayoutUnit clearanceForSelfCollapsingBlock;
1079 // 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
1080 // 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
1081 // 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.
1082 if (!marginInfo.canCollapseWithMarginBefore() && is<RenderBlockFlow>(prevSibling) && downcast<RenderBlockFlow>(*prevSibling).isSelfCollapsingBlock()) {
1083 clearanceForSelfCollapsingBlock = downcast<RenderBlockFlow>(*prevSibling).marginOffsetForSelfCollapsingBlock();
1084 setLogicalHeight(logicalHeight() - clearanceForSelfCollapsingBlock);
1087 if (childIsSelfCollapsing) {
1088 // 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.
1089 // Also, the child's top position equals the logical height of the container.
1090 if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
1091 // This child has no height. We need to compute our
1092 // position before we collapse the child's margins together,
1093 // so that we can get an accurate position for the zero-height block.
1094 LayoutUnit collapsedBeforePos = std::max(marginInfo.positiveMargin(), childMargins.positiveMarginBefore());
1095 LayoutUnit collapsedBeforeNeg = std::max(marginInfo.negativeMargin(), childMargins.negativeMarginBefore());
1096 marginInfo.setMargin(collapsedBeforePos, collapsedBeforeNeg);
1098 // Now collapse the child's margins together, which means examining our
1099 // bottom margin values as well.
1100 marginInfo.setPositiveMarginIfLarger(childMargins.positiveMarginAfter());
1101 marginInfo.setNegativeMarginIfLarger(childMargins.negativeMarginAfter());
1103 if (!marginInfo.canCollapseWithMarginBefore())
1104 // We need to make sure that the position of the self-collapsing block
1105 // is correct, since it could have overflowing content
1106 // that needs to be positioned correctly (e.g., a block that
1107 // had a specified height of 0 but that actually had subcontent).
1108 logicalTop = logicalHeight() + collapsedBeforePos - collapsedBeforeNeg;
1111 if (child && mustSeparateMarginBeforeForChild(*child)) {
1112 ASSERT(!marginInfo.discardMargin() || (marginInfo.discardMargin() && !marginInfo.margin()));
1113 // If we are at the before side of the block and we collapse, ignore the computed margin
1114 // and just add the child margin to the container height. This will correctly position
1115 // the child inside the container.
1116 LayoutUnit separateMargin = !marginInfo.canCollapseWithMarginBefore() ? marginInfo.margin() : LayoutUnit::fromPixel(0);
1117 setLogicalHeight(logicalHeight() + separateMargin + marginBeforeForChild(*child));
1118 logicalTop = logicalHeight();
1119 } else if (!marginInfo.discardMargin() && (!marginInfo.atBeforeSideOfBlock()
1120 || (!marginInfo.canCollapseMarginBeforeWithChildren()
1121 && (!document().inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginBeforeQuirk())))) {
1122 // We're collapsing with a previous sibling's margins and not
1123 // with the top of the block.
1124 setLogicalHeight(logicalHeight() + std::max(marginInfo.positiveMargin(), posTop) - std::max(marginInfo.negativeMargin(), negTop));
1125 logicalTop = logicalHeight();
1128 marginInfo.setDiscardMargin(childDiscardMarginAfter);
1130 if (!marginInfo.discardMargin()) {
1131 marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
1132 marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
1134 marginInfo.clearMargin();
1136 if (marginInfo.margin())
1137 marginInfo.setHasMarginAfterQuirk(afterQuirk);
1140 // If margins would pull us past the top of the next page, then we need to pull back and pretend like the margins
1141 // collapsed into the page edge.
1142 LayoutState* layoutState = view().layoutState();
1143 if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTop > beforeCollapseLogicalTop
1144 && hasNextPage(beforeCollapseLogicalTop)) {
1145 LayoutUnit oldLogicalTop = logicalTop;
1146 logicalTop = std::min(logicalTop, nextPageLogicalTop(beforeCollapseLogicalTop));
1147 setLogicalHeight(logicalHeight() + (logicalTop - oldLogicalTop));
1150 if (is<RenderBlockFlow>(prevSibling) && !prevSibling->isFloatingOrOutOfFlowPositioned()) {
1151 // 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
1152 // any floats from the parent will now overhang.
1153 RenderBlockFlow& block = downcast<RenderBlockFlow>(*prevSibling);
1154 LayoutUnit oldLogicalHeight = logicalHeight();
1155 setLogicalHeight(logicalTop);
1156 if (block.containsFloats() && !block.avoidsFloats() && (block.logicalTop() + block.lowestFloatLogicalBottom()) > logicalTop)
1157 addOverhangingFloats(block, false);
1158 setLogicalHeight(oldLogicalHeight);
1160 // If |child|'s previous sibling is a self-collapsing block that cleared a float and margin collapsing resulted in |child| moving up
1161 // 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
1162 // floats in the parent that overhang |child|'s new logical top.
1163 bool logicalTopIntrudesIntoFloat = clearanceForSelfCollapsingBlock > 0 && logicalTop < beforeCollapseLogicalTop;
1164 if (child && logicalTopIntrudesIntoFloat && containsFloats() && !child->avoidsFloats() && lowestFloatLogicalBottom() > logicalTop)
1165 child->setNeedsLayout();
1171 LayoutUnit RenderBlockFlow::clearFloatsIfNeeded(RenderBox& child, MarginInfo& marginInfo, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos)
1173 LayoutUnit heightIncrease = getClearDelta(child, yPos);
1174 if (!heightIncrease)
1177 if (child.isSelfCollapsingBlock()) {
1178 bool childDiscardMargin = mustDiscardMarginBeforeForChild(child) || mustDiscardMarginAfterForChild(child);
1180 // For self-collapsing blocks that clear, they can still collapse their
1181 // margins with following siblings. Reset the current margins to represent
1182 // the self-collapsing block's margins only.
1183 // If DISCARD is specified for -webkit-margin-collapse, reset the margin values.
1184 MarginValues childMargins = marginValuesForChild(child);
1185 if (!childDiscardMargin) {
1186 marginInfo.setPositiveMargin(std::max(childMargins.positiveMarginBefore(), childMargins.positiveMarginAfter()));
1187 marginInfo.setNegativeMargin(std::max(childMargins.negativeMarginBefore(), childMargins.negativeMarginAfter()));
1189 marginInfo.clearMargin();
1190 marginInfo.setDiscardMargin(childDiscardMargin);
1193 // "If the top and bottom margins of an element with clearance are adjoining, its margins collapse with
1194 // the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block."
1195 // So the parent's bottom margin cannot collapse through this block or any subsequent self-collapsing blocks. Check subsequent siblings
1196 // for a block with height - if none is found then don't allow the margins to collapse with the parent.
1197 bool wouldCollapseMarginsWithParent = marginInfo.canCollapseMarginAfterWithChildren();
1198 for (RenderBox* curr = child.nextSiblingBox(); curr && wouldCollapseMarginsWithParent; curr = curr->nextSiblingBox()) {
1199 if (!curr->isFloatingOrOutOfFlowPositioned() && !curr->isSelfCollapsingBlock())
1200 wouldCollapseMarginsWithParent = false;
1202 if (wouldCollapseMarginsWithParent)
1203 marginInfo.setCanCollapseMarginAfterWithChildren(false);
1205 // 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
1206 // its own at the correct vertical position. If subsequent siblings attempt to collapse with |child|'s margins in |collapseMargins| we will
1207 // 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
1208 // margins can collapse at the correct vertical position.
1209 // 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
1210 // (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],
1211 // i.e., clearance = [height of float] - margin-top".
1212 setLogicalHeight(child.logicalTop() + childMargins.negativeMarginBefore());
1214 // Increase our height by the amount we had to clear.
1215 setLogicalHeight(logicalHeight() + heightIncrease);
1217 if (marginInfo.canCollapseWithMarginBefore()) {
1218 // We can no longer collapse with the top of the block since a clear
1219 // occurred. The empty blocks collapse into the cleared block.
1220 // FIXME: This isn't quite correct. Need clarification for what to do
1221 // if the height the cleared block is offset by is smaller than the
1222 // margins involved.
1223 setMaxMarginBeforeValues(oldTopPosMargin, oldTopNegMargin);
1224 marginInfo.setAtBeforeSideOfBlock(false);
1226 // In case the child discarded the before margin of the block we need to reset the mustDiscardMarginBefore flag to the initial value.
1227 setMustDiscardMarginBefore(style().marginBeforeCollapse() == MDISCARD);
1230 return yPos + heightIncrease;
1233 void RenderBlockFlow::marginBeforeEstimateForChild(RenderBox& child, LayoutUnit& positiveMarginBefore, LayoutUnit& negativeMarginBefore, bool& discardMarginBefore) const
1235 // Give up if in quirks mode and we're a body/table cell and the top margin of the child box is quirky.
1236 // Give up if the child specified -webkit-margin-collapse: separate that prevents collapsing.
1237 // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
1238 if ((document().inQuirksMode() && hasMarginAfterQuirk(child) && (isTableCell() || isBody())) || child.style().marginBeforeCollapse() == MSEPARATE)
1241 // The margins are discarded by a child that specified -webkit-margin-collapse: discard.
1242 // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
1243 if (child.style().marginBeforeCollapse() == MDISCARD) {
1244 positiveMarginBefore = 0;
1245 negativeMarginBefore = 0;
1246 discardMarginBefore = true;
1250 LayoutUnit beforeChildMargin = marginBeforeForChild(child);
1251 positiveMarginBefore = std::max(positiveMarginBefore, beforeChildMargin);
1252 negativeMarginBefore = std::max(negativeMarginBefore, -beforeChildMargin);
1254 if (!is<RenderBlockFlow>(child))
1257 RenderBlockFlow& childBlock = downcast<RenderBlockFlow>(child);
1258 if (childBlock.childrenInline() || childBlock.isWritingModeRoot())
1261 MarginInfo childMarginInfo(childBlock, childBlock.borderAndPaddingBefore(), childBlock.borderAndPaddingAfter());
1262 if (!childMarginInfo.canCollapseMarginBeforeWithChildren())
1265 RenderBox* grandchildBox = childBlock.firstChildBox();
1266 for (; grandchildBox; grandchildBox = grandchildBox->nextSiblingBox()) {
1267 if (!grandchildBox->isFloatingOrOutOfFlowPositioned())
1271 // Give up if there is clearance on the box, since it probably won't collapse into us.
1272 if (!grandchildBox || grandchildBox->style().clear() != CNONE)
1275 // Make sure to update the block margins now for the grandchild box so that we're looking at current values.
1276 if (grandchildBox->needsLayout()) {
1277 grandchildBox->computeAndSetBlockDirectionMargins(*this);
1278 if (is<RenderBlock>(*grandchildBox)) {
1279 RenderBlock& grandchildBlock = downcast<RenderBlock>(*grandchildBox);
1280 grandchildBlock.setHasMarginBeforeQuirk(grandchildBox->style().hasMarginBeforeQuirk());
1281 grandchildBlock.setHasMarginAfterQuirk(grandchildBox->style().hasMarginAfterQuirk());
1285 // Collapse the margin of the grandchild box with our own to produce an estimate.
1286 childBlock.marginBeforeEstimateForChild(*grandchildBox, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
1289 LayoutUnit RenderBlockFlow::estimateLogicalTopPosition(RenderBox& child, const MarginInfo& marginInfo, LayoutUnit& estimateWithoutPagination)
1291 // FIXME: We need to eliminate the estimation of vertical position, because when it's wrong we sometimes trigger a pathological
1292 // relayout if there are intruding floats.
1293 LayoutUnit logicalTopEstimate = logicalHeight();
1294 if (!marginInfo.canCollapseWithMarginBefore()) {
1295 LayoutUnit positiveMarginBefore = 0;
1296 LayoutUnit negativeMarginBefore = 0;
1297 bool discardMarginBefore = false;
1298 if (child.selfNeedsLayout()) {
1299 // Try to do a basic estimation of how the collapse is going to go.
1300 marginBeforeEstimateForChild(child, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
1302 // Use the cached collapsed margin values from a previous layout. Most of the time they
1304 MarginValues marginValues = marginValuesForChild(child);
1305 positiveMarginBefore = std::max(positiveMarginBefore, marginValues.positiveMarginBefore());
1306 negativeMarginBefore = std::max(negativeMarginBefore, marginValues.negativeMarginBefore());
1307 discardMarginBefore = mustDiscardMarginBeforeForChild(child);
1310 // Collapse the result with our current margins.
1311 if (!discardMarginBefore)
1312 logicalTopEstimate += std::max(marginInfo.positiveMargin(), positiveMarginBefore) - std::max(marginInfo.negativeMargin(), negativeMarginBefore);
1315 // Adjust logicalTopEstimate down to the next page if the margins are so large that we don't fit on the current
1317 LayoutState* layoutState = view().layoutState();
1318 if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTopEstimate > logicalHeight()
1319 && hasNextPage(logicalHeight()))
1320 logicalTopEstimate = std::min(logicalTopEstimate, nextPageLogicalTop(logicalHeight()));
1322 logicalTopEstimate += getClearDelta(child, logicalTopEstimate);
1324 estimateWithoutPagination = logicalTopEstimate;
1326 if (layoutState->isPaginated()) {
1327 // If the object has a page or column break value of "before", then we should shift to the top of the next page.
1328 logicalTopEstimate = applyBeforeBreak(child, logicalTopEstimate);
1330 // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
1331 logicalTopEstimate = adjustForUnsplittableChild(child, logicalTopEstimate);
1333 if (!child.selfNeedsLayout() && is<RenderBlock>(child))
1334 logicalTopEstimate += downcast<RenderBlock>(child).paginationStrut();
1337 return logicalTopEstimate;
1340 void RenderBlockFlow::setCollapsedBottomMargin(const MarginInfo& marginInfo)
1342 if (marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()) {
1343 // 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.
1344 // Don't update the max margin values because we won't need them anyway.
1345 if (marginInfo.discardMargin()) {
1346 setMustDiscardMarginAfter();
1350 // Update our max pos/neg bottom margins, since we collapsed our bottom margins
1351 // with our children.
1352 setMaxMarginAfterValues(std::max(maxPositiveMarginAfter(), marginInfo.positiveMargin()), std::max(maxNegativeMarginAfter(), marginInfo.negativeMargin()));
1354 if (!marginInfo.hasMarginAfterQuirk())
1355 setHasMarginAfterQuirk(false);
1357 if (marginInfo.hasMarginAfterQuirk() && !marginAfter())
1358 // We have no bottom margin and our last child has a quirky margin.
1359 // We will pick up this quirky margin and pass it through.
1360 // This deals with the <td><div><p> case.
1361 setHasMarginAfterQuirk(true);
1365 void RenderBlockFlow::handleAfterSideOfBlock(LayoutUnit beforeSide, LayoutUnit afterSide, MarginInfo& marginInfo)
1367 marginInfo.setAtAfterSideOfBlock(true);
1369 // If our last child was a self-collapsing block with clearance then our logical height is flush with the
1370 // bottom edge of the float that the child clears. The correct vertical position for the margin-collapsing we want
1371 // to perform now is at the child's margin-top - so adjust our height to that position.
1372 RenderObject* lastBlock = lastChild();
1373 if (is<RenderBlockFlow>(lastBlock) && downcast<RenderBlockFlow>(*lastBlock).isSelfCollapsingBlock())
1374 setLogicalHeight(logicalHeight() - downcast<RenderBlockFlow>(*lastBlock).marginOffsetForSelfCollapsingBlock());
1376 // If we can't collapse with children then add in the bottom margin.
1377 if (!marginInfo.discardMargin() && (!marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()
1378 && (!document().inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginAfterQuirk())))
1379 setLogicalHeight(logicalHeight() + marginInfo.margin());
1381 // Now add in our bottom border/padding.
1382 setLogicalHeight(logicalHeight() + afterSide);
1384 // Negative margins can cause our height to shrink below our minimal height (border/padding).
1385 // If this happens, ensure that the computed height is increased to the minimal height.
1386 setLogicalHeight(std::max(logicalHeight(), beforeSide + afterSide));
1388 // Update our bottom collapsed margin info.
1389 setCollapsedBottomMargin(marginInfo);
1392 void RenderBlockFlow::setMaxMarginBeforeValues(LayoutUnit pos, LayoutUnit neg)
1394 if (!hasRareBlockFlowData()) {
1395 if (pos == RenderBlockFlowRareData::positiveMarginBeforeDefault(*this) && neg == RenderBlockFlowRareData::negativeMarginBeforeDefault(*this))
1397 materializeRareBlockFlowData();
1400 rareBlockFlowData()->m_margins.setPositiveMarginBefore(pos);
1401 rareBlockFlowData()->m_margins.setNegativeMarginBefore(neg);
1404 void RenderBlockFlow::setMaxMarginAfterValues(LayoutUnit pos, LayoutUnit neg)
1406 if (!hasRareBlockFlowData()) {
1407 if (pos == RenderBlockFlowRareData::positiveMarginAfterDefault(*this) && neg == RenderBlockFlowRareData::negativeMarginAfterDefault(*this))
1409 materializeRareBlockFlowData();
1412 rareBlockFlowData()->m_margins.setPositiveMarginAfter(pos);
1413 rareBlockFlowData()->m_margins.setNegativeMarginAfter(neg);
1416 void RenderBlockFlow::setMustDiscardMarginBefore(bool value)
1418 if (style().marginBeforeCollapse() == MDISCARD) {
1423 if (!hasRareBlockFlowData()) {
1426 materializeRareBlockFlowData();
1429 rareBlockFlowData()->m_discardMarginBefore = value;
1432 void RenderBlockFlow::setMustDiscardMarginAfter(bool value)
1434 if (style().marginAfterCollapse() == MDISCARD) {
1439 if (!hasRareBlockFlowData()) {
1442 materializeRareBlockFlowData();
1445 rareBlockFlowData()->m_discardMarginAfter = value;
1448 bool RenderBlockFlow::mustDiscardMarginBefore() const
1450 return style().marginBeforeCollapse() == MDISCARD || (hasRareBlockFlowData() && rareBlockFlowData()->m_discardMarginBefore);
1453 bool RenderBlockFlow::mustDiscardMarginAfter() const
1455 return style().marginAfterCollapse() == MDISCARD || (hasRareBlockFlowData() && rareBlockFlowData()->m_discardMarginAfter);
1458 bool RenderBlockFlow::mustDiscardMarginBeforeForChild(const RenderBox& child) const
1460 ASSERT(!child.selfNeedsLayout());
1461 if (!child.isWritingModeRoot())
1462 return is<RenderBlockFlow>(child) ? downcast<RenderBlockFlow>(child).mustDiscardMarginBefore() : (child.style().marginBeforeCollapse() == MDISCARD);
1463 if (child.isHorizontalWritingMode() == isHorizontalWritingMode())
1464 return is<RenderBlockFlow>(child) ? downcast<RenderBlockFlow>(child).mustDiscardMarginAfter() : (child.style().marginAfterCollapse() == MDISCARD);
1466 // FIXME: We return false here because the implementation is not geometrically complete. We have values only for before/after, not start/end.
1467 // In case the boxes are perpendicular we assume the property is not specified.
1471 bool RenderBlockFlow::mustDiscardMarginAfterForChild(const RenderBox& child) const
1473 ASSERT(!child.selfNeedsLayout());
1474 if (!child.isWritingModeRoot())
1475 return is<RenderBlockFlow>(child) ? downcast<RenderBlockFlow>(child).mustDiscardMarginAfter() : (child.style().marginAfterCollapse() == MDISCARD);
1476 if (child.isHorizontalWritingMode() == isHorizontalWritingMode())
1477 return is<RenderBlockFlow>(child) ? downcast<RenderBlockFlow>(child).mustDiscardMarginBefore() : (child.style().marginBeforeCollapse() == MDISCARD);
1479 // FIXME: See |mustDiscardMarginBeforeForChild| above.
1483 bool RenderBlockFlow::mustSeparateMarginBeforeForChild(const RenderBox& child) const
1485 ASSERT(!child.selfNeedsLayout());
1486 const RenderStyle& childStyle = child.style();
1487 if (!child.isWritingModeRoot())
1488 return childStyle.marginBeforeCollapse() == MSEPARATE;
1489 if (child.isHorizontalWritingMode() == isHorizontalWritingMode())
1490 return childStyle.marginAfterCollapse() == MSEPARATE;
1492 // FIXME: See |mustDiscardMarginBeforeForChild| above.
1496 bool RenderBlockFlow::mustSeparateMarginAfterForChild(const RenderBox& child) const
1498 ASSERT(!child.selfNeedsLayout());
1499 const RenderStyle& childStyle = child.style();
1500 if (!child.isWritingModeRoot())
1501 return childStyle.marginAfterCollapse() == MSEPARATE;
1502 if (child.isHorizontalWritingMode() == isHorizontalWritingMode())
1503 return childStyle.marginBeforeCollapse() == MSEPARATE;
1505 // FIXME: See |mustDiscardMarginBeforeForChild| above.
1509 static bool inNormalFlow(RenderBox& child)
1511 RenderBlock* curr = child.containingBlock();
1512 while (curr && curr != &child.view()) {
1513 if (curr->isRenderFlowThread())
1515 if (curr->isFloatingOrOutOfFlowPositioned())
1517 curr = curr->containingBlock();
1522 LayoutUnit RenderBlockFlow::applyBeforeBreak(RenderBox& child, LayoutUnit logicalOffset)
1524 // FIXME: Add page break checking here when we support printing.
1525 RenderFlowThread* flowThread = flowThreadContainingBlock();
1526 bool isInsideMulticolFlowThread = flowThread && !flowThread->isRenderNamedFlowThread();
1527 bool checkColumnBreaks = flowThread && flowThread->shouldCheckColumnBreaks();
1528 bool checkPageBreaks = !checkColumnBreaks && view().layoutState()->m_pageLogicalHeight; // FIXME: Once columns can print we have to check this.
1529 bool checkRegionBreaks = flowThread && flowThread->isRenderNamedFlowThread();
1530 bool checkBeforeAlways = (checkColumnBreaks && child.style().breakBefore() == ColumnBreakBetween)
1531 || (checkPageBreaks && alwaysPageBreak(child.style().breakBefore()))
1532 || (checkRegionBreaks && child.style().breakBefore() == RegionBreakBetween);
1533 if (checkBeforeAlways && inNormalFlow(child) && hasNextPage(logicalOffset, IncludePageBoundary)) {
1534 if (checkColumnBreaks) {
1535 if (isInsideMulticolFlowThread)
1536 checkRegionBreaks = true;
1538 if (checkRegionBreaks) {
1539 LayoutUnit offsetBreakAdjustment = 0;
1540 if (flowThread->addForcedRegionBreak(this, offsetFromLogicalTopOfFirstPage() + logicalOffset, &child, true, &offsetBreakAdjustment))
1541 return logicalOffset + offsetBreakAdjustment;
1543 return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
1545 return logicalOffset;
1548 LayoutUnit RenderBlockFlow::applyAfterBreak(RenderBox& child, LayoutUnit logicalOffset, MarginInfo& marginInfo)
1550 // FIXME: Add page break checking here when we support printing.
1551 RenderFlowThread* flowThread = flowThreadContainingBlock();
1552 bool isInsideMulticolFlowThread = flowThread && !flowThread->isRenderNamedFlowThread();
1553 bool checkColumnBreaks = flowThread && flowThread->shouldCheckColumnBreaks();
1554 bool checkPageBreaks = !checkColumnBreaks && view().layoutState()->m_pageLogicalHeight; // FIXME: Once columns can print we have to check this.
1555 bool checkRegionBreaks = flowThread && flowThread->isRenderNamedFlowThread();
1556 bool checkAfterAlways = (checkColumnBreaks && child.style().breakAfter() == ColumnBreakBetween)
1557 || (checkPageBreaks && alwaysPageBreak(child.style().breakAfter()))
1558 || (checkRegionBreaks && child.style().breakAfter() == RegionBreakBetween);
1559 if (checkAfterAlways && inNormalFlow(child) && hasNextPage(logicalOffset, IncludePageBoundary)) {
1560 LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
1562 // So our margin doesn't participate in the next collapsing steps.
1563 marginInfo.clearMargin();
1565 if (checkColumnBreaks) {
1566 if (isInsideMulticolFlowThread)
1567 checkRegionBreaks = true;
1569 if (checkRegionBreaks) {
1570 LayoutUnit offsetBreakAdjustment = 0;
1571 if (flowThread->addForcedRegionBreak(this, offsetFromLogicalTopOfFirstPage() + logicalOffset + marginOffset, &child, false, &offsetBreakAdjustment))
1572 return logicalOffset + marginOffset + offsetBreakAdjustment;
1574 return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
1576 return logicalOffset;
1579 LayoutUnit RenderBlockFlow::adjustBlockChildForPagination(LayoutUnit logicalTopAfterClear, LayoutUnit estimateWithoutPagination, RenderBox& child, bool atBeforeSideOfBlock)
1581 RenderBlock* childRenderBlock = is<RenderBlock>(child) ? &downcast<RenderBlock>(child) : nullptr;
1583 if (estimateWithoutPagination != logicalTopAfterClear) {
1584 // Our guess prior to pagination movement was wrong. Before we attempt to paginate, let's try again at the new
1586 setLogicalHeight(logicalTopAfterClear);
1587 setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
1589 if (child.shrinkToAvoidFloats()) {
1590 // The child's width depends on the line width. When the child shifts to clear an item, its width can
1591 // change (because it has more available line width). So mark the item as dirty.
1592 child.setChildNeedsLayout(MarkOnlyThis);
1595 if (childRenderBlock) {
1596 if (!child.avoidsFloats() && childRenderBlock->containsFloats())
1597 downcast<RenderBlockFlow>(*childRenderBlock).markAllDescendantsWithFloatsForLayout();
1598 child.markForPaginationRelayoutIfNeeded();
1601 // Our guess was wrong. Make the child lay itself out again.
1602 child.layoutIfNeeded();
1605 LayoutUnit oldTop = logicalTopAfterClear;
1607 // If the object has a page or column break value of "before", then we should shift to the top of the next page.
1608 LayoutUnit result = applyBeforeBreak(child, logicalTopAfterClear);
1610 if (pageLogicalHeightForOffset(result)) {
1611 LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(result, ExcludePageBoundary);
1612 LayoutUnit spaceShortage = child.logicalHeight() - remainingLogicalHeight;
1613 if (spaceShortage > 0) {
1614 // If the child crosses a column boundary, report a break, in case nothing inside it has already
1615 // done so. The column balancer needs to know how much it has to stretch the columns to make more
1616 // content fit. If no breaks are reported (but do occur), the balancer will have no clue. FIXME:
1617 // This should be improved, though, because here we just pretend that the child is
1618 // unsplittable. A splittable child, on the other hand, has break opportunities at every position
1619 // where there's no child content, border or padding. In other words, we risk stretching more
1621 setPageBreak(result, spaceShortage);
1625 // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
1626 LayoutUnit logicalTopBeforeUnsplittableAdjustment = result;
1627 LayoutUnit logicalTopAfterUnsplittableAdjustment = adjustForUnsplittableChild(child, result);
1629 LayoutUnit paginationStrut = 0;
1630 LayoutUnit unsplittableAdjustmentDelta = logicalTopAfterUnsplittableAdjustment - logicalTopBeforeUnsplittableAdjustment;
1631 if (unsplittableAdjustmentDelta)
1632 paginationStrut = unsplittableAdjustmentDelta;
1633 else if (childRenderBlock && childRenderBlock->paginationStrut())
1634 paginationStrut = childRenderBlock->paginationStrut();
1636 if (paginationStrut) {
1637 // We are willing to propagate out to our parent block as long as we were at the top of the block prior
1638 // to collapsing our margins, and as long as we didn't clear or move as a result of other pagination.
1639 if (atBeforeSideOfBlock && oldTop == result && !isOutOfFlowPositioned() && !isTableCell()) {
1640 // FIXME: Should really check if we're exceeding the page height before propagating the strut, but we don't
1641 // have all the information to do so (the strut only has the remaining amount to push). Gecko gets this wrong too
1642 // and pushes to the next page anyway, so not too concerned about it.
1643 setPaginationStrut(result + paginationStrut);
1644 if (childRenderBlock)
1645 childRenderBlock->setPaginationStrut(0);
1647 result += paginationStrut;
1650 // Similar to how we apply clearance. Boost height() to be the place where we're going to position the child.
1651 setLogicalHeight(logicalHeight() + (result - oldTop));
1653 // Return the final adjusted logical top.
1657 static inline LayoutUnit calculateMinimumPageHeight(const RenderStyle& renderStyle, RootInlineBox& lastLine, LayoutUnit lineTop, LayoutUnit lineBottom)
1659 // We may require a certain minimum number of lines per page in order to satisfy
1660 // orphans and widows, and that may affect the minimum page height.
1661 unsigned lineCount = std::max<unsigned>(renderStyle.hasAutoOrphans() ? 1 : renderStyle.orphans(), renderStyle.hasAutoWidows() ? 1 : renderStyle.widows());
1662 if (lineCount > 1) {
1663 RootInlineBox* line = &lastLine;
1664 for (unsigned i = 1; i < lineCount && line->prevRootBox(); i++)
1665 line = line->prevRootBox();
1667 // FIXME: Paginating using line overflow isn't all fine. See FIXME in
1668 // adjustLinePositionForPagination() for more details.
1669 LayoutRect overflow = line->logicalVisualOverflowRect(line->lineTop(), line->lineBottom());
1670 lineTop = std::min(line->lineTopWithLeading(), overflow.y());
1672 return lineBottom - lineTop;
1675 static inline bool needsAppleMailPaginationQuirk(RootInlineBox& lineBox)
1677 auto& renderer = lineBox.renderer();
1679 if (!renderer.settings().appleMailPaginationQuirkEnabled())
1682 if (renderer.element() && renderer.element()->idForStyleResolution() == "messageContentContainer")
1688 static void clearShouldBreakAtLineToAvoidWidowIfNeeded(RenderBlockFlow& blockFlow)
1690 if (!blockFlow.shouldBreakAtLineToAvoidWidow())
1692 blockFlow.clearShouldBreakAtLineToAvoidWidow();
1693 blockFlow.setDidBreakAtLineToAvoidWidow();
1696 void RenderBlockFlow::adjustLinePositionForPagination(RootInlineBox* lineBox, LayoutUnit& delta, bool& overflowsRegion, RenderFlowThread* flowThread)
1698 // FIXME: Ignore anonymous inline blocks. Handle the delta already having been set because of
1699 // collapsing margins from a previous anonymous inline block.
1700 // FIXME: For now we paginate using line overflow. This ensures that lines don't overlap at all when we
1701 // put a strut between them for pagination purposes. However, this really isn't the desired rendering, since
1702 // the line on the top of the next page will appear too far down relative to the same kind of line at the top
1703 // of the first column.
1705 // The rendering we would like to see is one where the lineTopWithLeading is at the top of the column, and any line overflow
1706 // simply spills out above the top of the column. This effect would match what happens at the top of the first column.
1707 // We can't achieve this rendering, however, until we stop columns from clipping to the column bounds (thus allowing
1708 // for overflow to occur), and then cache visible overflow for each column rect.
1710 // Furthermore, the paint we have to do when a column has overflow has to be special. We need to exclude
1711 // content that paints in a previous column (and content that paints in the following column).
1713 // For now we'll at least honor the lineTopWithLeading when paginating if it is above the logical top overflow. This will
1714 // at least make positive leading work in typical cases.
1716 // FIXME: Another problem with simply moving lines is that the available line width may change (because of floats).
1717 // Technically if the location we move the line to has a different line width than our old position, then we need to dirty the
1718 // line and all following lines.
1719 overflowsRegion = false;
1720 LayoutRect logicalVisualOverflow = lineBox->logicalVisualOverflowRect(lineBox->lineTop(), lineBox->lineBottom());
1721 LayoutUnit logicalOffset = std::min(lineBox->lineTopWithLeading(), logicalVisualOverflow.y());
1722 LayoutUnit logicalBottom = std::max(lineBox->lineBottomWithLeading(), logicalVisualOverflow.maxY());
1723 LayoutUnit lineHeight = logicalBottom - logicalOffset;
1724 updateMinimumPageHeight(logicalOffset, calculateMinimumPageHeight(style(), *lineBox, logicalOffset, logicalBottom));
1725 logicalOffset += delta;
1726 lineBox->setPaginationStrut(0);
1727 lineBox->setIsFirstAfterPageBreak(false);
1728 LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
1729 bool hasUniformPageLogicalHeight = !flowThread || flowThread->regionsHaveUniformLogicalHeight();
1730 // If lineHeight is greater than pageLogicalHeight, but logicalVisualOverflow.height() still fits, we are
1731 // still going to add a strut, so that the visible overflow fits on a single page.
1732 if (!pageLogicalHeight || !hasNextPage(logicalOffset)) {
1733 // 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.
1734 // 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.
1738 if (hasUniformPageLogicalHeight && logicalVisualOverflow.height() > pageLogicalHeight) {
1739 // 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
1740 // line and computing a new height that excludes anything we consider "blank space". We will discard margins, descent, and even overflow. If we are
1741 // 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
1743 // 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
1744 // this will be a real-world issue. For now we don't try to deal with this problem.
1745 logicalOffset = intMaxForLayoutUnit;
1746 logicalBottom = intMinForLayoutUnit;
1747 lineBox->computeReplacedAndTextLineTopAndBottom(logicalOffset, logicalBottom);
1748 lineHeight = logicalBottom - logicalOffset;
1749 if (logicalOffset == intMaxForLayoutUnit || lineHeight > pageLogicalHeight) {
1750 // Give up. We're genuinely too big even after excluding blank space and overflow.
1751 clearShouldBreakAtLineToAvoidWidowIfNeeded(*this);
1754 pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
1757 LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset, ExcludePageBoundary);
1758 overflowsRegion = (lineHeight > remainingLogicalHeight);
1760 int lineIndex = lineCount(lineBox);
1761 if (remainingLogicalHeight < lineHeight || (shouldBreakAtLineToAvoidWidow() && lineBreakToAvoidWidow() == lineIndex)) {
1762 if (lineBreakToAvoidWidow() == lineIndex)
1763 clearShouldBreakAtLineToAvoidWidowIfNeeded(*this);
1764 // If we have a non-uniform page height, then we have to shift further possibly.
1765 if (!hasUniformPageLogicalHeight && !pushToNextPageWithMinimumLogicalHeight(remainingLogicalHeight, logicalOffset, lineHeight))
1767 if (lineHeight > pageLogicalHeight) {
1768 // Split the top margin in order to avoid splitting the visible part of the line.
1769 remainingLogicalHeight -= std::min(lineHeight - pageLogicalHeight, std::max<LayoutUnit>(0, logicalVisualOverflow.y() - lineBox->lineTopWithLeading()));
1771 LayoutUnit remainingLogicalHeightAtNewOffset = pageRemainingLogicalHeightForOffset(logicalOffset + remainingLogicalHeight, ExcludePageBoundary);
1772 overflowsRegion = (lineHeight > remainingLogicalHeightAtNewOffset);
1773 LayoutUnit totalLogicalHeight = lineHeight + std::max<LayoutUnit>(0, logicalOffset);
1774 LayoutUnit pageLogicalHeightAtNewOffset = hasUniformPageLogicalHeight ? pageLogicalHeight : pageLogicalHeightForOffset(logicalOffset + remainingLogicalHeight);
1775 setPageBreak(logicalOffset, lineHeight - remainingLogicalHeight);
1776 if (((lineBox == firstRootBox() && totalLogicalHeight < pageLogicalHeightAtNewOffset) || (!style().hasAutoOrphans() && style().orphans() >= lineIndex))
1777 && !isOutOfFlowPositioned() && !isTableCell()) {
1778 auto firstRootBox = this->firstRootBox();
1779 auto firstRootBoxOverflowRect = firstRootBox->logicalVisualOverflowRect(firstRootBox->lineTop(), firstRootBox->lineBottom());
1780 auto firstLineUpperOverhang = std::max(-firstRootBoxOverflowRect.y(), LayoutUnit());
1781 if (needsAppleMailPaginationQuirk(*lineBox))
1783 setPaginationStrut(remainingLogicalHeight + logicalOffset + firstLineUpperOverhang);
1785 delta += remainingLogicalHeight;
1786 lineBox->setPaginationStrut(remainingLogicalHeight);
1787 lineBox->setIsFirstAfterPageBreak(true);
1789 } else if (remainingLogicalHeight == pageLogicalHeight) {
1790 // We're at the very top of a page or column.
1791 if (lineBox != firstRootBox())
1792 lineBox->setIsFirstAfterPageBreak(true);
1793 if (lineBox != firstRootBox() || offsetFromLogicalTopOfFirstPage())
1794 setPageBreak(logicalOffset, lineHeight);
1798 void RenderBlockFlow::setBreakAtLineToAvoidWidow(int lineToBreak)
1800 ASSERT(lineToBreak >= 0);
1801 ASSERT(!ensureRareBlockFlowData().m_didBreakAtLineToAvoidWidow);
1802 ensureRareBlockFlowData().m_lineBreakToAvoidWidow = lineToBreak;
1805 void RenderBlockFlow::setDidBreakAtLineToAvoidWidow()
1807 ASSERT(!shouldBreakAtLineToAvoidWidow());
1808 if (!hasRareBlockFlowData())
1811 rareBlockFlowData()->m_didBreakAtLineToAvoidWidow = true;
1814 void RenderBlockFlow::clearDidBreakAtLineToAvoidWidow()
1816 if (!hasRareBlockFlowData())
1819 rareBlockFlowData()->m_didBreakAtLineToAvoidWidow = false;
1822 void RenderBlockFlow::clearShouldBreakAtLineToAvoidWidow() const
1824 ASSERT(shouldBreakAtLineToAvoidWidow());
1825 if (!hasRareBlockFlowData())
1828 rareBlockFlowData()->m_lineBreakToAvoidWidow = -1;
1831 bool RenderBlockFlow::relayoutToAvoidWidows(LayoutStateMaintainer& statePusher)
1833 if (!shouldBreakAtLineToAvoidWidow())
1837 setEverHadLayout(true);
1842 bool RenderBlockFlow::hasNextPage(LayoutUnit logicalOffset, PageBoundaryRule pageBoundaryRule) const
1844 ASSERT(view().layoutState() && view().layoutState()->isPaginated());
1846 RenderFlowThread* flowThread = flowThreadContainingBlock();
1848 return true; // Printing and multi-column both make new pages to accommodate content.
1850 // See if we're in the last region.
1851 LayoutUnit pageOffset = offsetFromLogicalTopOfFirstPage() + logicalOffset;
1852 RenderRegion* region = flowThread->regionAtBlockOffset(this, pageOffset, true);
1856 if (region->isLastRegion())
1857 return region->isRenderRegionSet() || region->style().regionFragment() == BreakRegionFragment
1858 || (pageBoundaryRule == IncludePageBoundary && pageOffset == region->logicalTopForFlowThreadContent());
1860 RenderRegion* startRegion = nullptr;
1861 RenderRegion* endRegion = nullptr;
1862 flowThread->getRegionRangeForBox(this, startRegion, endRegion);
1863 return (endRegion && region != endRegion);
1866 LayoutUnit RenderBlockFlow::adjustForUnsplittableChild(RenderBox& child, LayoutUnit logicalOffset, LayoutUnit childBeforeMargin, LayoutUnit childAfterMargin)
1868 if (!childBoxIsUnsplittableForFragmentation(child))
1869 return logicalOffset;
1871 RenderFlowThread* flowThread = flowThreadContainingBlock();
1872 LayoutUnit childLogicalHeight = logicalHeightForChild(child) + childBeforeMargin + childAfterMargin;
1873 LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
1874 bool hasUniformPageLogicalHeight = !flowThread || flowThread->regionsHaveUniformLogicalHeight();
1875 updateMinimumPageHeight(logicalOffset, childLogicalHeight);
1876 if (!pageLogicalHeight || (hasUniformPageLogicalHeight && childLogicalHeight > pageLogicalHeight)
1877 || !hasNextPage(logicalOffset))
1878 return logicalOffset;
1879 LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset, ExcludePageBoundary);
1880 if (remainingLogicalHeight < childLogicalHeight) {
1881 if (!hasUniformPageLogicalHeight && !pushToNextPageWithMinimumLogicalHeight(remainingLogicalHeight, logicalOffset, childLogicalHeight))
1882 return logicalOffset;
1883 auto result = logicalOffset + remainingLogicalHeight;
1884 bool isInitialLetter = child.isFloating() && child.style().styleType() == FIRST_LETTER && child.style().initialLetterDrop() > 0;
1885 if (isInitialLetter) {
1886 // Increase our logical height to ensure that lines all get pushed along with the letter.
1887 setLogicalHeight(logicalOffset + remainingLogicalHeight);
1892 return logicalOffset;
1895 bool RenderBlockFlow::pushToNextPageWithMinimumLogicalHeight(LayoutUnit& adjustment, LayoutUnit logicalOffset, LayoutUnit minimumLogicalHeight) const
1897 bool checkRegion = false;
1898 for (LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset + adjustment); pageLogicalHeight;
1899 pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset + adjustment)) {
1900 if (minimumLogicalHeight <= pageLogicalHeight)
1902 if (!hasNextPage(logicalOffset + adjustment))
1904 adjustment += pageLogicalHeight;
1907 return !checkRegion;
1910 void RenderBlockFlow::setPageBreak(LayoutUnit offset, LayoutUnit spaceShortage)
1912 if (RenderFlowThread* flowThread = flowThreadContainingBlock())
1913 flowThread->setPageBreak(this, offsetFromLogicalTopOfFirstPage() + offset, spaceShortage);
1916 void RenderBlockFlow::updateMinimumPageHeight(LayoutUnit offset, LayoutUnit minHeight)
1918 if (RenderFlowThread* flowThread = flowThreadContainingBlock())
1919 flowThread->updateMinimumPageHeight(this, offsetFromLogicalTopOfFirstPage() + offset, minHeight);
1922 LayoutUnit RenderBlockFlow::nextPageLogicalTop(LayoutUnit logicalOffset, PageBoundaryRule pageBoundaryRule) const
1924 LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
1925 if (!pageLogicalHeight)
1926 return logicalOffset;
1928 // The logicalOffset is in our coordinate space. We can add in our pushed offset.
1929 LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset);
1930 if (pageBoundaryRule == ExcludePageBoundary)
1931 return logicalOffset + (remainingLogicalHeight ? remainingLogicalHeight : pageLogicalHeight);
1932 return logicalOffset + remainingLogicalHeight;
1935 LayoutUnit RenderBlockFlow::pageLogicalTopForOffset(LayoutUnit offset) const
1937 // Unsplittable objects clear out the pageLogicalHeight in the layout state as a way of signaling that no
1938 // pagination should occur. Therefore we have to check this first and bail if the value has been set to 0.
1939 LayoutUnit pageLogicalHeight = view().layoutState()->m_pageLogicalHeight;
1940 if (!pageLogicalHeight)
1943 LayoutUnit firstPageLogicalTop = isHorizontalWritingMode() ? view().layoutState()->m_pageOffset.height() : view().layoutState()->m_pageOffset.width();
1944 LayoutUnit blockLogicalTop = isHorizontalWritingMode() ? view().layoutState()->m_layoutOffset.height() : view().layoutState()->m_layoutOffset.width();
1946 LayoutUnit cumulativeOffset = offset + blockLogicalTop;
1947 RenderFlowThread* flowThread = flowThreadContainingBlock();
1949 return cumulativeOffset - roundToInt(cumulativeOffset - firstPageLogicalTop) % roundToInt(pageLogicalHeight);
1950 return firstPageLogicalTop + flowThread->pageLogicalTopForOffset(cumulativeOffset - firstPageLogicalTop);
1953 LayoutUnit RenderBlockFlow::pageLogicalHeightForOffset(LayoutUnit offset) const
1955 // Unsplittable objects clear out the pageLogicalHeight in the layout state as a way of signaling that no
1956 // pagination should occur. Therefore we have to check this first and bail if the value has been set to 0.
1957 LayoutUnit pageLogicalHeight = view().layoutState()->m_pageLogicalHeight;
1958 if (!pageLogicalHeight)
1961 // Now check for a flow thread.
1962 RenderFlowThread* flowThread = flowThreadContainingBlock();
1964 return pageLogicalHeight;
1965 return flowThread->pageLogicalHeightForOffset(offset + offsetFromLogicalTopOfFirstPage());
1968 LayoutUnit RenderBlockFlow::pageRemainingLogicalHeightForOffset(LayoutUnit offset, PageBoundaryRule pageBoundaryRule) const
1970 offset += offsetFromLogicalTopOfFirstPage();
1972 RenderFlowThread* flowThread = flowThreadContainingBlock();
1974 LayoutUnit pageLogicalHeight = view().layoutState()->m_pageLogicalHeight;
1975 LayoutUnit remainingHeight = pageLogicalHeight - intMod(offset, pageLogicalHeight);
1976 if (pageBoundaryRule == IncludePageBoundary) {
1977 // If includeBoundaryPoint is true the line exactly on the top edge of a
1978 // column will act as being part of the previous column.
1979 remainingHeight = intMod(remainingHeight, pageLogicalHeight);
1981 return remainingHeight;
1984 return flowThread->pageRemainingLogicalHeightForOffset(offset, pageBoundaryRule);
1987 LayoutUnit RenderBlockFlow::logicalHeightForChildForFragmentation(const RenderBox& child) const
1989 // This method is required because regions do not fragment monolithic elements but instead
1990 // they let them overflow the region they flow in. This behaviour is different from the
1991 // multicol/printing implementations, which have not yet been updated to correctly handle
1992 // monolithic elements.
1993 // As a result, for the moment, this method will only be used for regions, the multicol and
1994 // printing implementations will stick to the existing behaviour until their fragmentation
1995 // implementation is updated to match the regions implementation.
1996 if (!flowThreadContainingBlock() || !flowThreadContainingBlock()->isRenderNamedFlowThread())
1997 return logicalHeightForChild(child);
1999 // For unsplittable elements, this method will just return the height of the element that
2000 // fits into the current region, without the height of the part that overflows the region.
2001 // This is done for all regions, except the last one because in that case, the logical
2002 // height of the flow thread needs to also
2003 if (!childBoxIsUnsplittableForFragmentation(child) || !pageLogicalHeightForOffset(logicalTopForChild(child)))
2004 return logicalHeightForChild(child);
2006 // If we're on the last page this block fragments to, the logical height of the flow thread must include
2007 // the entire unsplittable child because any following children will not be moved to the next page
2008 // so they will need to be laid out below the current unsplittable child.
2009 LayoutUnit childLogicalTop = logicalTopForChild(child);
2010 if (!hasNextPage(childLogicalTop))
2011 return logicalHeightForChild(child);
2013 LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(childLogicalTop, ExcludePageBoundary);
2014 return std::min(child.logicalHeight(), remainingLogicalHeight);
2017 void RenderBlockFlow::layoutLineGridBox()
2019 if (style().lineGrid() == RenderStyle::initialLineGrid()) {
2026 auto lineGridBox = std::make_unique<RootInlineBox>(*this);
2027 lineGridBox->setHasTextChildren(); // Needed to make the line ascent/descent actually be honored in quirks mode.
2028 lineGridBox->setConstructed();
2029 GlyphOverflowAndFallbackFontsMap textBoxDataMap;
2030 VerticalPositionCache verticalPositionCache;
2031 lineGridBox->alignBoxesInBlockDirection(logicalHeight(), textBoxDataMap, verticalPositionCache);
2033 setLineGridBox(WTFMove(lineGridBox));
2035 // FIXME: If any of the characteristics of the box change compared to the old one, then we need to do a deep dirtying
2036 // (similar to what happens when the page height changes). Ideally, though, we only do this if someone is actually snapping
2040 bool RenderBlockFlow::containsFloat(RenderBox& renderer) const
2042 return m_floatingObjects && m_floatingObjects->set().contains<RenderBox&, FloatingObjectHashTranslator>(renderer);
2045 void RenderBlockFlow::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
2047 RenderBlock::styleDidChange(diff, oldStyle);
2049 // After our style changed, if we lose our ability to propagate floats into next sibling
2050 // blocks, then we need to find the top most parent containing that overhanging float and
2051 // then mark its descendants with floats for layout and clear all floats from its next
2052 // sibling blocks that exist in our floating objects list. See bug 56299 and 62875.
2053 bool canPropagateFloatIntoSibling = !isFloatingOrOutOfFlowPositioned() && !avoidsFloats();
2054 if (diff == StyleDifferenceLayout && s_canPropagateFloatIntoSibling && !canPropagateFloatIntoSibling && hasOverhangingFloats()) {
2055 RenderBlockFlow* parentBlock = this;
2056 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2058 for (auto& ancestor : ancestorsOfType<RenderBlockFlow>(*this)) {
2059 if (ancestor.isRenderView())
2061 if (ancestor.hasOverhangingFloats()) {
2062 for (auto it = floatingObjectSet.begin(), end = floatingObjectSet.end(); it != end; ++it) {
2063 RenderBox& renderer = (*it)->renderer();
2064 if (ancestor.hasOverhangingFloat(renderer)) {
2065 parentBlock = &ancestor;
2072 parentBlock->markAllDescendantsWithFloatsForLayout();
2073 parentBlock->markSiblingsWithFloatsForLayout();
2075 // Fresh floats need to be reparented if they actually belong to the previous anonymous block.
2076 // It copies the logic of RenderBlock::addChildIgnoringContinuation
2077 if (noLongerAffectsParentBlock() && style().isFloating() && previousSibling() && previousSibling()->isAnonymousBlock())
2078 downcast<RenderBoxModelObject>(*parent()).moveChildTo(&downcast<RenderBoxModelObject>(*previousSibling()), this);
2080 if (auto fragment = renderNamedFlowFragment())
2081 fragment->setStyle(RenderNamedFlowFragment::createStyle(style()));
2083 if (diff >= StyleDifferenceRepaint) {
2084 // FIXME: This could use a cheaper style-only test instead of SimpleLineLayout::canUseFor.
2085 if (selfNeedsLayout() || !m_simpleLineLayout || !SimpleLineLayout::canUseFor(*this))
2086 invalidateLineLayoutPath();
2089 if (multiColumnFlowThread())
2090 updateStylesForColumnChildren();
2093 void RenderBlockFlow::updateStylesForColumnChildren()
2095 for (auto* child = firstChildBox(); child && (child->isInFlowRenderFlowThread() || child->isRenderMultiColumnSet()); child = child->nextSiblingBox())
2096 child->setStyle(RenderStyle::createAnonymousStyleWithDisplay(style(), BLOCK));
2099 void RenderBlockFlow::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
2101 const RenderStyle* oldStyle = hasInitializedStyle() ? &style() : nullptr;
2102 s_canPropagateFloatIntoSibling = oldStyle ? !isFloatingOrOutOfFlowPositioned() && !avoidsFloats() : false;
2105 EPosition oldPosition = oldStyle->position();
2106 EPosition newPosition = newStyle.position();
2108 if (parent() && diff == StyleDifferenceLayout && oldPosition != newPosition) {
2109 if (containsFloats() && !isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition())
2110 markAllDescendantsWithFloatsForLayout();
2114 RenderBlock::styleWillChange(diff, newStyle);
2117 void RenderBlockFlow::deleteLines()
2119 if (containsFloats())
2120 m_floatingObjects->clearLineBoxTreePointers();
2122 if (m_simpleLineLayout) {
2123 ASSERT(!m_lineBoxes.firstLineBox());
2124 m_simpleLineLayout = nullptr;
2126 m_lineBoxes.deleteLineBoxTree();
2128 RenderBlock::deleteLines();
2131 void RenderBlockFlow::addFloatsToNewParent(RenderBlockFlow& toBlockFlow) const
2133 // When a portion of the render tree is being detached, anonymous blocks
2134 // will be combined as their children are deleted. In this process, the
2135 // anonymous block later in the tree is merged into the one preceeding it.
2136 // It can happen that the later block (this) contains floats that the
2137 // previous block (toBlockFlow) did not contain, and thus are not in the
2138 // floating objects list for toBlockFlow. This can result in toBlockFlow
2139 // containing floats that are not in it's floating objects list, but are in
2140 // the floating objects lists of siblings and parents. This can cause
2141 // problems when the float itself is deleted, since the deletion code
2142 // assumes that if a float is not in it's containing block's floating
2143 // objects list, it isn't in any floating objects list. In order to
2144 // preserve this condition (removing it has serious performance
2145 // implications), we need to copy the floating objects from the old block
2146 // (this) to the new block (toBlockFlow). The float's metrics will likely
2147 // all be wrong, but since toBlockFlow is already marked for layout, this
2148 // will get fixed before anything gets displayed.
2149 // See bug https://bugs.webkit.org/show_bug.cgi?id=115566
2150 if (!m_floatingObjects)
2153 if (!toBlockFlow.m_floatingObjects)
2154 toBlockFlow.createFloatingObjects();
2156 for (auto& floatingObject : m_floatingObjects->set()) {
2157 if (toBlockFlow.containsFloat(floatingObject->renderer()))
2159 toBlockFlow.m_floatingObjects->add(floatingObject->cloneForNewParent());
2163 void RenderBlockFlow::moveAllChildrenIncludingFloatsTo(RenderBlock& toBlock, bool fullRemoveInsert)
2165 auto& toBlockFlow = downcast<RenderBlockFlow>(toBlock);
2166 moveAllChildrenTo(&toBlockFlow, fullRemoveInsert);
2167 addFloatsToNewParent(toBlockFlow);
2170 void RenderBlockFlow::addOverflowFromFloats()
2172 if (!m_floatingObjects)
2175 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2176 auto end = floatingObjectSet.end();
2177 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
2178 const auto& floatingObject = *it->get();
2179 if (floatingObject.isDescendant())
2180 addOverflowFromChild(&floatingObject.renderer(), floatingObject.locationOffsetOfBorderBox());
2184 void RenderBlockFlow::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
2186 RenderBlock::computeOverflow(oldClientAfterEdge, recomputeFloats);
2188 if (!multiColumnFlowThread() && (recomputeFloats || createsNewFormattingContext() || hasSelfPaintingLayer()))
2189 addOverflowFromFloats();
2192 void RenderBlockFlow::repaintOverhangingFloats(bool paintAllDescendants)
2194 // Repaint any overhanging floats (if we know we're the one to paint them).
2195 // Otherwise, bail out.
2196 if (!hasOverhangingFloats())
2199 // FIXME: Avoid disabling LayoutState. At the very least, don't disable it for floats originating
2200 // in this block. Better yet would be to push extra state for the containers of other floats.
2201 LayoutStateDisabler layoutStateDisabler(view());
2202 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2203 auto end = floatingObjectSet.end();
2204 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
2205 const auto& floatingObject = *it->get();
2206 // Only repaint the object if it is overhanging, is not in its own layer, and
2207 // is our responsibility to paint (m_shouldPaint is set). When paintAllDescendants is true, the latter
2208 // condition is replaced with being a descendant of us.
2209 auto& renderer = floatingObject.renderer();
2210 if (logicalBottomForFloat(floatingObject) > logicalHeight()
2211 && !renderer.hasSelfPaintingLayer()
2212 && (floatingObject.shouldPaint() || (paintAllDescendants && renderer.isDescendantOf(this)))) {
2214 renderer.repaintOverhangingFloats(false);
2219 void RenderBlockFlow::paintColumnRules(PaintInfo& paintInfo, const LayoutPoint& point)
2221 RenderBlock::paintColumnRules(paintInfo, point);
2223 if (!multiColumnFlowThread() || paintInfo.context().paintingDisabled())
2226 // Iterate over our children and paint the column rules as needed.
2227 for (auto& columnSet : childrenOfType<RenderMultiColumnSet>(*this)) {
2228 LayoutPoint childPoint = columnSet.location() + flipForWritingModeForChild(&columnSet, point);
2229 columnSet.paintColumnRules(paintInfo, childPoint);
2233 void RenderBlockFlow::paintFloats(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool preservePhase)
2235 if (!m_floatingObjects)
2238 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2239 auto end = floatingObjectSet.end();
2240 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
2241 const auto& floatingObject = *it->get();
2242 auto& renderer = floatingObject.renderer();
2243 // Only paint the object if our m_shouldPaint flag is set.
2244 if (floatingObject.shouldPaint() && !renderer.hasSelfPaintingLayer()) {
2245 PaintInfo currentPaintInfo(paintInfo);
2246 currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
2247 LayoutPoint childPoint = flipFloatForWritingModeForChild(floatingObject, paintOffset + floatingObject.translationOffsetToAncestor());
2248 renderer.paint(currentPaintInfo, childPoint);
2249 if (!preservePhase) {
2250 currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
2251 renderer.paint(currentPaintInfo, childPoint);
2252 currentPaintInfo.phase = PaintPhaseFloat;
2253 renderer.paint(currentPaintInfo, childPoint);
2254 currentPaintInfo.phase = PaintPhaseForeground;
2255 renderer.paint(currentPaintInfo, childPoint);
2256 currentPaintInfo.phase = PaintPhaseOutline;
2257 renderer.paint(currentPaintInfo, childPoint);
2263 void RenderBlockFlow::clipOutFloatingObjects(RenderBlock& rootBlock, const PaintInfo* paintInfo, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock)
2265 if (m_floatingObjects) {
2266 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2267 auto end = floatingObjectSet.end();
2268 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
2269 const auto& floatingObject = *it->get();
2270 LayoutRect floatBox(offsetFromRootBlock.width(), offsetFromRootBlock.height(), floatingObject.renderer().width(), floatingObject.renderer().height());
2271 floatBox.move(floatingObject.locationOffsetOfBorderBox());
2272 rootBlock.flipForWritingMode(floatBox);
2273 floatBox.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
2274 paintInfo->context().clipOut(snappedIntRect(floatBox));
2279 void RenderBlockFlow::createFloatingObjects()
2281 m_floatingObjects = std::make_unique<FloatingObjects>(*this);
2284 void RenderBlockFlow::removeFloatingObjects()
2286 if (!m_floatingObjects)
2289 markSiblingsWithFloatsForLayout();
2291 m_floatingObjects->clear();
2294 FloatingObject* RenderBlockFlow::insertFloatingObject(RenderBox& floatBox)
2296 ASSERT(floatBox.isFloating());
2298 // Create the list of special objects if we don't aleady have one
2299 if (!m_floatingObjects)
2300 createFloatingObjects();
2302 // Don't insert the floatingObject again if it's already in the list
2303 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2304 auto it = floatingObjectSet.find<RenderBox&, FloatingObjectHashTranslator>(floatBox);
2305 if (it != floatingObjectSet.end())
2309 // Create the special floatingObject entry & append it to the list
2311 std::unique_ptr<FloatingObject> floatingObject = FloatingObject::create(floatBox);
2313 // Our location is irrelevant if we're unsplittable or no pagination is in effect. Just lay out the float.
2314 bool isChildRenderBlock = floatBox.isRenderBlock();
2315 if (isChildRenderBlock && !floatBox.needsLayout() && view().layoutState()->pageLogicalHeightChanged())
2316 floatBox.setChildNeedsLayout(MarkOnlyThis);
2318 bool needsBlockDirectionLocationSetBeforeLayout = isChildRenderBlock && view().layoutState()->needsBlockDirectionLocationSetBeforeLayout();
2319 if (!needsBlockDirectionLocationSetBeforeLayout || isWritingModeRoot()) {
2320 // We are unsplittable if we're a block flow root.
2321 floatBox.layoutIfNeeded();
2322 floatingObject->setShouldPaint(!floatBox.hasSelfPaintingLayer());
2325 floatBox.updateLogicalWidth();
2326 floatBox.computeAndSetBlockDirectionMargins(*this);
2329 setLogicalWidthForFloat(*floatingObject, logicalWidthForChild(floatBox) + marginStartForChild(floatBox) + marginEndForChild(floatBox));
2331 return m_floatingObjects->add(WTFMove(floatingObject));
2334 void RenderBlockFlow::removeFloatingObject(RenderBox& floatBox)
2336 if (m_floatingObjects) {
2337 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2338 auto it = floatingObjectSet.find<RenderBox&, FloatingObjectHashTranslator>(floatBox);
2339 if (it != floatingObjectSet.end()) {
2340 auto& floatingObject = *it->get();
2341 if (childrenInline()) {
2342 LayoutUnit logicalTop = logicalTopForFloat(floatingObject);
2343 LayoutUnit logicalBottom = logicalBottomForFloat(floatingObject);
2345 // Fix for https://bugs.webkit.org/show_bug.cgi?id=54995.
2346 if (logicalBottom < 0 || logicalBottom < logicalTop || logicalTop == LayoutUnit::max())
2347 logicalBottom = LayoutUnit::max();
2349 // Special-case zero- and less-than-zero-height floats: those don't touch
2350 // the line that they're on, but it still needs to be dirtied. This is
2351 // accomplished by pretending they have a height of 1.
2352 logicalBottom = std::max(logicalBottom, logicalTop + 1);
2354 if (floatingObject.originatingLine()) {
2355 floatingObject.originatingLine()->removeFloat(floatBox);
2356 if (!selfNeedsLayout()) {
2357 ASSERT(&floatingObject.originatingLine()->renderer() == this);
2358 floatingObject.originatingLine()->markDirty();
2360 #if !ASSERT_DISABLED
2361 floatingObject.setOriginatingLine(0);
2364 markLinesDirtyInBlockRange(0, logicalBottom);
2366 m_floatingObjects->remove(&floatingObject);
2371 void RenderBlockFlow::removeFloatingObjectsBelow(FloatingObject* lastFloat, int logicalOffset)
2373 if (!containsFloats())
2376 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2377 FloatingObject* curr = floatingObjectSet.last().get();
2378 while (curr != lastFloat && (!curr->isPlaced() || logicalTopForFloat(*curr) >= logicalOffset)) {
2379 m_floatingObjects->remove(curr);
2380 if (floatingObjectSet.isEmpty())
2382 curr = floatingObjectSet.last().get();
2386 LayoutUnit RenderBlockFlow::logicalLeftOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
2388 LayoutUnit offset = fixedOffset;
2389 if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
2390 offset = m_floatingObjects->logicalLeftOffsetForPositioningFloat(fixedOffset, logicalTop, heightRemaining);
2391 return adjustLogicalLeftOffsetForLine(offset, applyTextIndent);
2394 LayoutUnit RenderBlockFlow::logicalRightOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
2396 LayoutUnit offset = fixedOffset;
2397 if (m_floatingObjects && m_floatingObjects->hasRightObjects())
2398 offset = m_floatingObjects->logicalRightOffsetForPositioningFloat(fixedOffset, logicalTop, heightRemaining);
2399 return adjustLogicalRightOffsetForLine(offset, applyTextIndent);
2402 void RenderBlockFlow::computeLogicalLocationForFloat(FloatingObject& floatingObject, LayoutUnit& logicalTopOffset)
2404 auto& childBox = floatingObject.renderer();
2405 LayoutUnit logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
2406 LayoutUnit logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); // Constant part of right offset.
2408 LayoutUnit floatLogicalWidth = std::min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset); // The width we look for.
2410 LayoutUnit floatLogicalLeft;
2412 bool insideFlowThread = flowThreadContainingBlock();
2413 bool isInitialLetter = childBox.style().styleType() == FIRST_LETTER && childBox.style().initialLetterDrop() > 0;
2415 if (isInitialLetter) {
2416 int letterClearance = lowestInitialLetterLogicalBottom() - logicalTopOffset;
2417 if (letterClearance > 0) {
2418 logicalTopOffset += letterClearance;
2419 setLogicalHeight(logicalHeight() + letterClearance);
2423 if (childBox.style().floating() == LeftFloat) {
2424 LayoutUnit heightRemainingLeft = 1;
2425 LayoutUnit heightRemainingRight = 1;
2426 floatLogicalLeft = logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
2427 while (logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight) - floatLogicalLeft < floatLogicalWidth) {
2428 logicalTopOffset += std::min(heightRemainingLeft, heightRemainingRight);
2429 floatLogicalLeft = logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
2430 if (insideFlowThread) {
2431 // Have to re-evaluate all of our offsets, since they may have changed.
2432 logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); // Constant part of right offset.
2433 logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
2434 floatLogicalWidth = std::min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
2437 floatLogicalLeft = std::max(logicalLeftOffset - borderAndPaddingLogicalLeft(), floatLogicalLeft);
2439 LayoutUnit heightRemainingLeft = 1;
2440 LayoutUnit heightRemainingRight = 1;
2441 floatLogicalLeft = logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
2442 while (floatLogicalLeft - logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft) < floatLogicalWidth) {
2443 logicalTopOffset += std::min(heightRemainingLeft, heightRemainingRight);
2444 floatLogicalLeft = logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
2445 if (insideFlowThread) {
2446 // Have to re-evaluate all of our offsets, since they may have changed.
2447 logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); // Constant part of right offset.
2448 logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
2449 floatLogicalWidth = std::min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
2452 // Use the original width of the float here, since the local variable
2453 // |floatLogicalWidth| was capped to the available line width. See
2454 // fast/block/float/clamped-right-float.html.
2455 floatLogicalLeft -= logicalWidthForFloat(floatingObject);
2458 LayoutUnit childLogicalLeftMargin = style().isLeftToRightDirection() ? marginStartForChild(childBox) : marginEndForChild(childBox);
2459 LayoutUnit childBeforeMargin = marginBeforeForChild(childBox);
2461 if (isInitialLetter)
2462 adjustInitialLetterPosition(childBox, logicalTopOffset, childBeforeMargin);
2464 setLogicalLeftForFloat(floatingObject, floatLogicalLeft);
2465 setLogicalLeftForChild(childBox, floatLogicalLeft + childLogicalLeftMargin);
2467 setLogicalTopForFloat(floatingObject, logicalTopOffset);
2468 setLogicalTopForChild(childBox, logicalTopOffset + childBeforeMargin);
2470 setLogicalMarginsForFloat(floatingObject, childLogicalLeftMargin, childBeforeMargin);
2473 void RenderBlockFlow::adjustInitialLetterPosition(RenderBox& childBox, LayoutUnit& logicalTopOffset, LayoutUnit& marginBeforeOffset)
2475 const RenderStyle& style = firstLineStyle();
2476 const FontMetrics& fontMetrics = style.fontMetrics();
2477 if (!fontMetrics.hasCapHeight())
2480 LayoutUnit heightOfLine = lineHeight(true, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
2481 LayoutUnit beforeMarginBorderPadding = childBox.borderAndPaddingBefore() + childBox.marginBefore();
2483 // Make an adjustment to align with the cap height of a theoretical block line.
2484 LayoutUnit adjustment = fontMetrics.ascent() + (heightOfLine - fontMetrics.height()) / 2 - fontMetrics.capHeight() - beforeMarginBorderPadding;
2485 logicalTopOffset += adjustment;
2487 // For sunken and raised caps, we have to make some adjustments. Test if we're sunken or raised (dropHeightDelta will be
2488 // positive for raised and negative for sunken).
2489 int dropHeightDelta = childBox.style().initialLetterHeight() - childBox.style().initialLetterDrop();
2491 // 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.
2492 if (dropHeightDelta < 0)
2493 marginBeforeOffset += -dropHeightDelta * heightOfLine;
2495 // 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
2496 // empty lines beside the first letter.
2497 if (dropHeightDelta > 0)
2498 setLogicalHeight(logicalHeight() + dropHeightDelta * heightOfLine);
2501 bool RenderBlockFlow::positionNewFloats()
2503 if (!m_floatingObjects)
2506 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2507 if (floatingObjectSet.isEmpty())
2510 // If all floats have already been positioned, then we have no work to do.
2511 if (floatingObjectSet.last()->isPlaced())
2514 // Move backwards through our floating object list until we find a float that has
2515 // already been positioned. Then we'll be able to move forward, positioning all of
2516 // the new floats that need it.
2517 auto it = floatingObjectSet.end();
2518 --it; // Go to last item.
2519 auto begin = floatingObjectSet.begin();
2520 FloatingObject* lastPlacedFloatingObject = 0;
2521 while (it != begin) {
2523 if ((*it)->isPlaced()) {
2524 lastPlacedFloatingObject = it->get();
2530 LayoutUnit logicalTop = logicalHeight();
2532 // The float cannot start above the top position of the last positioned float.
2533 if (lastPlacedFloatingObject)
2534 logicalTop = std::max(logicalTopForFloat(*lastPlacedFloatingObject), logicalTop);
2536 auto end = floatingObjectSet.end();
2537 // Now walk through the set of unpositioned floats and place them.
2538 for (; it != end; ++it) {
2539 auto& floatingObject = *it->get();
2540 // The containing block is responsible for positioning floats, so if we have floats in our
2541 // list that come from somewhere else, do not attempt to position them.
2542 auto& childBox = floatingObject.renderer();
2543 if (childBox.containingBlock() != this)
2546 LayoutRect oldRect = childBox.frameRect();
2548 if (childBox.style().clear() & CLEFT)
2549 logicalTop = std::max(lowestFloatLogicalBottom(FloatingObject::FloatLeft), logicalTop);
2550 if (childBox.style().clear() & CRIGHT)
2551 logicalTop = std::max(lowestFloatLogicalBottom(FloatingObject::FloatRight), logicalTop);
2553 computeLogicalLocationForFloat(floatingObject, logicalTop);
2554 LayoutUnit childLogicalTop = logicalTopForChild(childBox);
2556 estimateRegionRangeForBoxChild(childBox);
2558 childBox.markForPaginationRelayoutIfNeeded();
2559 childBox.layoutIfNeeded();
2561 LayoutState* layoutState = view().layoutState();
2562 bool isPaginated = layoutState->isPaginated();
2564 // If we are unsplittable and don't fit, then we need to move down.
2565 // We include our margins as part of the unsplittable area.
2566 LayoutUnit newLogicalTop = adjustForUnsplittableChild(childBox, logicalTop, childLogicalTop - logicalTop, marginAfterForChild(childBox));
2568 // See if we have a pagination strut that is making us move down further.
2569 // Note that an unsplittable child can't also have a pagination strut, so this
2570 // is exclusive with the case above.
2571 RenderBlock* childBlock = is<RenderBlock>(childBox) ? &downcast<RenderBlock>(childBox) : nullptr;
2572 if (childBlock && childBlock->paginationStrut()) {
2573 newLogicalTop += childBlock->paginationStrut();
2574 childBlock->setPaginationStrut(0);
2577 if (newLogicalTop != logicalTop) {
2578 floatingObject.setPaginationStrut(newLogicalTop - logicalTop);
2579 computeLogicalLocationForFloat(floatingObject, newLogicalTop);
2581 childBlock->setChildNeedsLayout(MarkOnlyThis);
2582 childBox.layoutIfNeeded();
2583 logicalTop = newLogicalTop;
2586 if (updateRegionRangeForBoxChild(childBox)) {
2587 childBox.setNeedsLayout(MarkOnlyThis);
2588 childBox.layoutIfNeeded();
2592 setLogicalHeightForFloat(floatingObject, logicalHeightForChildForFragmentation(childBox) + (logicalTopForChild(childBox) - logicalTop) + marginAfterForChild(childBox));
2594 m_floatingObjects->addPlacedObject(&floatingObject);
2596 if (ShapeOutsideInfo* shapeOutside = childBox.shapeOutsideInfo())
2597 shapeOutside->setReferenceBoxLogicalSize(logicalSizeForChild(childBox));
2598 // If the child moved, we have to repaint it.
2599 if (childBox.checkForRepaintDuringLayout())
2600 childBox.repaintDuringLayoutIfMoved(oldRect);
2605 void RenderBlockFlow::clearFloats(EClear clear)
2607 positionNewFloats();
2609 LayoutUnit newY = 0;
2612 newY = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
2615 newY = lowestFloatLogicalBottom(FloatingObject::FloatRight);
2618 newY = lowestFloatLogicalBottom();
2623 if (height() < newY)
2624 setLogicalHeight(newY);
2627 LayoutUnit RenderBlockFlow::logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const
2629 if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
2630 return m_floatingObjects->logicalLeftOffset(fixedOffset, logicalTop, logicalHeight);
2635 LayoutUnit RenderBlockFlow::logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const
2637 if (m_floatingObjects && m_floatingObjects->hasRightObjects())
2638 return m_floatingObjects->logicalRightOffset(fixedOffset, logicalTop, logicalHeight);
2643 LayoutUnit RenderBlockFlow::nextFloatLogicalBottomBelow(LayoutUnit logicalHeight) const
2645 if (!m_floatingObjects)
2646 return logicalHeight;
2648 return m_floatingObjects->findNextFloatLogicalBottomBelow(logicalHeight);
2651 LayoutUnit RenderBlockFlow::nextFloatLogicalBottomBelowForBlock(LayoutUnit logicalHeight) const
2653 if (!m_floatingObjects)
2654 return logicalHeight;
2656 return m_floatingObjects->findNextFloatLogicalBottomBelowForBlock(logicalHeight);
2659 LayoutUnit RenderBlockFlow::lowestFloatLogicalBottom(FloatingObject::Type floatType) const
2661 if (!m_floatingObjects)
2663 LayoutUnit lowestFloatBottom = 0;
2664 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2665 auto end = floatingObjectSet.end();
2666 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
2667 const auto& floatingObject = *it->get();
2668 if (floatingObject.isPlaced() && floatingObject.type() & floatType)
2669 lowestFloatBottom = std::max(lowestFloatBottom, logicalBottomForFloat(floatingObject));
2671 return lowestFloatBottom;
2674 LayoutUnit RenderBlockFlow::lowestInitialLetterLogicalBottom() const
2676 if (!m_floatingObjects)
2678 LayoutUnit lowestFloatBottom = 0;
2679 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2680 auto end = floatingObjectSet.end();
2681 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
2682 const auto& floatingObject = *it->get();
2683 if (floatingObject.isPlaced() && floatingObject.renderer().style().styleType() == FIRST_LETTER && floatingObject.renderer().style().initialLetterDrop() > 0)
2684 lowestFloatBottom = std::max(lowestFloatBottom, logicalBottomForFloat(floatingObject));
2686 return lowestFloatBottom;
2689 LayoutUnit RenderBlockFlow::addOverhangingFloats(RenderBlockFlow& child, bool makeChildPaintOtherFloats)
2691 // Prevent floats from being added to the canvas by the root element, e.g., <html>.
2692 if (!child.containsFloats() || child.createsNewFormattingContext())
2695 LayoutUnit childLogicalTop = child.logicalTop();
2696 LayoutUnit childLogicalLeft = child.logicalLeft();
2697 LayoutUnit lowestFloatLogicalBottom = 0;
2699 // Floats that will remain the child's responsibility to paint should factor into its
2701 auto childEnd = child.m_floatingObjects->set().end();
2702 for (auto childIt = child.m_floatingObjects->set().begin(); childIt != childEnd; ++childIt) {
2703 auto& floatingObject = *childIt->get();
2704 LayoutUnit floatLogicalBottom = std::min(logicalBottomForFloat(floatingObject), LayoutUnit::max() - childLogicalTop);
2705 LayoutUnit logicalBottom = childLogicalTop + floatLogicalBottom;
2706 lowestFloatLogicalBottom = std::max(lowestFloatLogicalBottom, logicalBottom);
2708 if (logicalBottom > logicalHeight()) {
2709 // If the object is not in the list, we add it now.
2710 if (!containsFloat(floatingObject.renderer())) {
2711 LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(-childLogicalLeft, -childLogicalTop) : LayoutSize(-childLogicalTop, -childLogicalLeft);
2712 bool shouldPaint = false;
2714 // The nearest enclosing layer always paints the float (so that zindex and stacking
2715 // behaves properly). We always want to propagate the desire to paint the float as
2716 // far out as we can, to the outermost block that overlaps the float, stopping only
2717 // if we hit a self-painting layer boundary.
2718 if (floatingObject.renderer().enclosingFloatPaintingLayer() == enclosingFloatPaintingLayer()) {
2719 floatingObject.setShouldPaint(false);
2722 // We create the floating object list lazily.
2723 if (!m_floatingObjects)
2724 createFloatingObjects();
2726 m_floatingObjects->add(floatingObject.copyToNewContainer(offset, shouldPaint, true));
2729 const auto& renderer = floatingObject.renderer();
2730 if (makeChildPaintOtherFloats && !floatingObject.shouldPaint() && !renderer.hasSelfPaintingLayer()
2731 && renderer.isDescendantOf(&child) && renderer.enclosingFloatPaintingLayer() == child.enclosingFloatPaintingLayer()) {
2732 // The float is not overhanging from this block, so if it is a descendant of the child, the child should
2733 // paint it (the other case is that it is intruding into the child), unless it has its own layer or enclosing
2735 // If makeChildPaintOtherFloats is false, it means that the child must already know about all the floats
2737 floatingObject.setShouldPaint(true);
2740 // 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.
2741 if (floatingObject.isDescendant())
2742 child.addOverflowFromChild(&renderer, floatingObject.locationOffsetOfBorderBox());
2745 return lowestFloatLogicalBottom;
2748 bool RenderBlockFlow::hasOverhangingFloat(RenderBox& renderer)
2750 if (!m_floatingObjects || !parent())
2753 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2754 const auto it = floatingObjectSet.find<RenderBox&, FloatingObjectHashTranslator>(renderer);
2755 if (it == floatingObjectSet.end())
2758 return logicalBottomForFloat(*it->get()) > logicalHeight();
2761 void RenderBlockFlow::addIntrudingFloats(RenderBlockFlow* prev, RenderBlockFlow* container, LayoutUnit logicalLeftOffset, LayoutUnit logicalTopOffset)
2763 ASSERT(!avoidsFloats());
2765 // If we create our own block formatting context then our contents don't interact with floats outside it, even those from our parent.
2766 if (createsNewFormattingContext())
2769 // If the parent or previous sibling doesn't have any floats to add, don't bother.
2770 if (!prev->m_floatingObjects)
2773 logicalLeftOffset += marginLogicalLeft();
2775 const FloatingObjectSet& prevSet = prev->m_floatingObjects->set();
2776 auto prevEnd = prevSet.end();
2777 for (auto prevIt = prevSet.begin(); prevIt != prevEnd; ++prevIt) {
2778 auto& floatingObject = *prevIt->get();
2779 if (logicalBottomForFloat(floatingObject) > logicalTopOffset) {
2780 if (!m_floatingObjects || !m_floatingObjects->set().contains<FloatingObject&, FloatingObjectHashTranslator>(floatingObject)) {
2781 // We create the floating object list lazily.
2782 if (!m_floatingObjects)
2783 createFloatingObjects();
2785 // Applying the child's margin makes no sense in the case where the child was passed in.
2786 // since this margin was added already through the modification of the |logicalLeftOffset| variable
2787 // above. |logicalLeftOffset| will equal the margin in this case, so it's already been taken
2788 // into account. Only apply this code if prev is the parent, since otherwise the left margin
2789 // will get applied twice.
2790 LayoutSize offset = isHorizontalWritingMode()
2791 ? LayoutSize(logicalLeftOffset - (prev != container ? prev->marginLeft() : LayoutUnit()), logicalTopOffset)
2792 : LayoutSize(logicalTopOffset, logicalLeftOffset - (prev != container ? prev->marginTop() : LayoutUnit()));
2794 m_floatingObjects->add(floatingObject.copyToNewContainer(offset));
2800 void RenderBlockFlow::markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove, bool inLayout)
2802 if (!everHadLayout() && !containsFloats())
2805 MarkingBehavior markParents = inLayout ? MarkOnlyThis : MarkContainingBlockChain;
2806 setChildNeedsLayout(markParents);
2809 removeFloatingObject(*floatToRemove);
2810 else if (childrenInline())
2813 // Iterate over our block children and mark them as needed.
2814 for (auto& block : childrenOfType<RenderBlock>(*this)) {
2815 if (!floatToRemove && block.isFloatingOrOutOfFlowPositioned())
2817 if (!is<RenderBlockFlow>(block)) {
2818 if (block.shrinkToAvoidFloats() && block.everHadLayout())
2819 block.setChildNeedsLayout(markParents);
2822 auto& blockFlow = downcast<RenderBlockFlow>(block);
2823 if ((floatToRemove ? blockFlow.containsFloat(*floatToRemove) : blockFlow.containsFloats()) || blockFlow.shrinkToAvoidFloats())
2824 blockFlow.markAllDescendantsWithFloatsForLayout(floatToRemove, inLayout);
2828 void RenderBlockFlow::markSiblingsWithFloatsForLayout(RenderBox* floatToRemove)
2830 if (!m_floatingObjects)
2833 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2834 auto end = floatingObjectSet.end();
2836 for (RenderObject* next = nextSibling(); next; next = next->nextSibling()) {
2837 if (!is<RenderBlockFlow>(*next) || next->isFloatingOrOutOfFlowPositioned())
2840 RenderBlockFlow& nextBlock = downcast<RenderBlockFlow>(*next);
2841 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
2842 RenderBox& floatingBox = (*it)->renderer();
2843 if (floatToRemove && &floatingBox != floatToRemove)
2845 if (nextBlock.containsFloat(floatingBox))
2846 nextBlock.markAllDescendantsWithFloatsForLayout(&floatingBox);
2851 LayoutPoint RenderBlockFlow::flipFloatForWritingModeForChild(const FloatingObject& child, const LayoutPoint& point) const
2853 if (!style().isFlippedBlocksWritingMode())
2856 // This is similar to RenderBox::flipForWritingModeForChild. We have to subtract out our left/top offsets twice, since
2857 // it's going to get added back in. We hide this complication here so that the calling code looks normal for the unflipped
2859 if (isHorizontalWritingMode())
2860 return LayoutPoint(point.x(), point.y() + height() - child.renderer().height() - 2 * child.locationOffsetOfBorderBox().height());
2861 return LayoutPoint(point.x() + width() - child.renderer().width() - 2 * child.locationOffsetOfBorderBox().width(), point.y());
2864 LayoutUnit RenderBlockFlow::getClearDelta(RenderBox& child, LayoutUnit logicalTop)
2866 // There is no need to compute clearance if we have no floats.
2867 if (!containsFloats())
2870 // At least one float is present. We need to perform the clearance computation.
2871 bool clearSet = child.style().clear() != CNONE;
2872 LayoutUnit logicalBottom = 0;
2873 switch (child.style().clear()) {
2877 logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
2880 logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatRight);
2883 logicalBottom = lowestFloatLogicalBottom();
2887 // 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).
2888 LayoutUnit result = clearSet ? std::max<LayoutUnit>(0, logicalBottom - logicalTop) : LayoutUnit();
2889 if (!result && child.avoidsFloats()) {
2890 LayoutUnit newLogicalTop = logicalTop;
2892 LayoutUnit availableLogicalWidthAtNewLogicalTopOffset = availableLogicalWidthForLine(newLogicalTop, DoNotIndentText, logicalHeightForChild(child));
2893 if (availableLogicalWidthAtNewLogicalTopOffset == availableLogicalWidthForContent(newLogicalTop))
2894 return newLogicalTop - logicalTop;
2896 RenderRegion* region = regionAtBlockOffset(logicalTopForChild(child));
2897 LayoutRect borderBox = child.borderBoxRectInRegion(region, DoNotCacheRenderBoxRegionInfo);
2898 LayoutUnit childLogicalWidthAtOldLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
2900 // FIXME: None of this is right for perpendicular writing-mode children.
2901 LayoutUnit childOldLogicalWidth = child.logicalWidth();
2902 LayoutUnit childOldMarginLeft = child.marginLeft();
2903 LayoutUnit childOldMarginRight = child.marginRight();
2904 LayoutUnit childOldLogicalTop = child.logicalTop();
2906 child.setLogicalTop(newLogicalTop);
2907 child.updateLogicalWidth();
2908 region = regionAtBlockOffset(logicalTopForChild(child));
2909 borderBox = child.borderBoxRectInRegion(region, DoNotCacheRenderBoxRegionInfo);
2910 LayoutUnit childLogicalWidthAtNewLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
2912 child.setLogicalTop(childOldLogicalTop);
2913 child.setLogicalWidth(childOldLogicalWidth);
2914 child.setMarginLeft(childOldMarginLeft);
2915 child.setMarginRight(childOldMarginRight);
2917 if (childLogicalWidthAtNewLogicalTopOffset <= availableLogicalWidthAtNewLogicalTopOffset) {
2918 // Even though we may not be moving, if the logical width did shrink because of the presence of new floats, then
2919 // we need to force a relayout as though we shifted. This happens because of the dynamic addition of overhanging floats
2920 // from previous siblings when negative margins exist on a child (see the addOverhangingFloats call at the end of collapseMargins).
2921 if (childLogicalWidthAtOldLogicalTopOffset != childLogicalWidthAtNewLogicalTopOffset)
2922 child.setChildNeedsLayout(MarkOnlyThis);
2923 return newLogicalTop - logicalTop;
2926 newLogicalTop = nextFloatLogicalBottomBelowForBlock(newLogicalTop);
2927 ASSERT(newLogicalTop >= logicalTop);
2928 if (newLogicalTop < logicalTop)
2931 ASSERT_NOT_REACHED();
2936 bool RenderBlockFlow::hitTestFloats(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset)
2938 if (!m_floatingObjects)
2941 LayoutPoint adjustedLocation = accumulatedOffset;
2942 if (is<RenderView>(*this))
2943 adjustedLocation += toLayoutSize(downcast<RenderView>(*this).frameView().scrollPosition());
2945 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2946 auto begin = floatingObjectSet.begin();
2947 for (auto it = floatingObjectSet.end(); it != begin;) {
2949 const auto& floatingObject = *it->get();
2950 auto& renderer = floatingObject.renderer();
2951 if (floatingObject.shouldPaint() && !renderer.hasSelfPaintingLayer()) {
2952 LayoutPoint childPoint = flipFloatForWritingModeForChild(floatingObject, adjustedLocation + floatingObject.translationOffsetToAncestor());
2953 if (renderer.hitTest(request, result, locationInContainer, childPoint)) {
2954 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(childPoint));
2963 bool RenderBlockFlow::hitTestInlineChildren(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
2965 ASSERT(childrenInline());
2967 if (auto simpleLineLayout = this->simpleLineLayout())
2968 return SimpleLineLayout::hitTestFlow(*this, *simpleLineLayout, request, result, locationInContainer, accumulatedOffset, hitTestAction);
2970 return m_lineBoxes.hitTest(this, request, result, locationInContainer, accumulatedOffset, hitTestAction);
2973 void RenderBlockFlow::adjustForBorderFit(LayoutUnit x, LayoutUnit& left, LayoutUnit& right) const
2975 if (style().visibility() != VISIBLE)
2978 // We don't deal with relative positioning. Our assumption is that you shrink to fit the lines without accounting
2979 // for either overflow or translations via relative positioning.
2980 if (childrenInline()) {
2981 const_cast<RenderBlockFlow&>(*this).ensureLineBoxes();
2983 for (auto* box = firstRootBox(); box; box = box->nextRootBox()) {
2984 if (box->firstChild())
2985 left = std::min(left, x + LayoutUnit(box->firstChild()->x()));
2986 if (box->lastChild())
2987 right = std::max(right, x + LayoutUnit(ceilf(box->lastChild()->logicalRight())));
2990 for (RenderBox* obj = firstChildBox(); obj; obj = obj->nextSiblingBox()) {
2991 if (!obj->isFloatingOrOutOfFlowPositioned()) {
2992 if (is<RenderBlockFlow>(*obj) && !obj->hasOverflowClip())
2993 downcast<RenderBlockFlow>(*obj).adjustForBorderFit(x + obj->x(), left, right);
2994 else if (obj->style().visibility() == VISIBLE) {
2995 // We are a replaced element or some kind of non-block-flow object.
2996 left = std::min(left, x + obj->x());
2997 right = std::max(right, x + obj->x() + obj->width());
3003 if (m_floatingObjects) {
3004 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
3005 auto end = floatingObjectSet.end();
3006 for (auto it = floatingObjectSet.begin(); it != end; ++it) {
3007 const auto& floatingObject = *it->get();
3008 // Only examine the object if our m_shouldPaint flag is set.
3009 if (floatingObject.shouldPaint()) {
3010 LayoutUnit floatLeft = floatingObject.translationOffsetToAncestor().width();
3011 LayoutUnit floatRight = floatLeft + floatingObject.renderer().width();
3012 left = std::min(left, floatLeft);
3013 right = std::max(right, floatRight);
3019 void RenderBlockFlow::fitBorderToLinesIfNeeded()
3021 if (style().borderFit() == BorderFitBorder || hasOverrideLogicalContentWidth())
3024 // Walk any normal flow lines to snugly fit.
3025 LayoutUnit left = LayoutUnit::max();
3026 LayoutUnit right = LayoutUnit::min();
3027 LayoutUnit oldWidth = contentWidth();
3028 adjustForBorderFit(0, left, right);
3030 // Clamp to our existing edges. We can never grow. We only shrink.
3031 LayoutUnit leftEdge = borderLeft() + paddingLeft();
3032 LayoutUnit rightEdge = leftEdge + oldWidth;
3033 left = std::min(rightEdge, std::max(leftEdge, left));
3034 right = std::max(leftEdge, std::min(rightEdge, right));
3036 LayoutUnit newContentWidth = right - left;
3037 if (newContentWidth == oldWidth)
3040 setOverrideLogicalContentWidth(newContentWidth);
3042 clearOverrideLogicalContentWidth();
3045 void RenderBlockFlow::markLinesDirtyInBlockRange(LayoutUnit logicalTop, LayoutUnit logicalBottom, RootInlineBox* highest)
3047 if (logicalTop >= logicalBottom)
3050 // Floats currently affect the choice whether to use simple line layout path.
3051 if (m_simpleLineLayout) {
3052 invalidateLineLayoutPath();
3056 RootInlineBox* lowestDirtyLine = lastRootBox();
3057 RootInlineBox* afterLowest = lowestDirtyLine;
3058 while (lowestDirtyLine && lowestDirtyLine->lineBottomWithLeading() >= logicalBottom && logicalBottom < LayoutUnit::max()) {
3059 afterLowest = lowestDirtyLine;
3060 lowestDirtyLine = lowestDirtyLine->prevRootBox();
3063 while (afterLowest && afterLowest != highest && (afterLowest->lineBottomWithLeading() >= logicalTop || afterLowest->lineBottomWithLeading() < 0)) {
3064 afterLowest->markDirty();
3065 afterLowest = afterLowest->prevRootBox();
3069 std::optional<int> RenderBlockFlow::firstLineBaseline() const
3071 if (isWritingModeRoot() && !isRubyRun())
3072 return std::optional<int>();
3074 if (!childrenInline())
3075 return RenderBlock::firstLineBaseline();
3078 return std::optional<int>();
3080 if (auto simpleLineLayout = this->simpleLineLayout())
3081 return std::optional<int>(SimpleLineLayout::computeFlowFirstLineBaseline(*this, *simpleLineLayout));
3083 ASSERT(firstRootBox());
3084 return firstRootBox()->logicalTop() + firstLineStyle().fontMetrics().ascent(firstRootBox()->baselineType());
3087 std::optional<int> RenderBlockFlow::inlineBlockBaseline(LineDirectionMode lineDirection) const
3089 if (isWritingModeRoot() && !isRubyRun())
3090 return std::optional<int>();
3092 // Note that here we only take the left and bottom into consideration. Our caller takes the right and top into consideration.
3093 float boxHeight = lineDirection == HorizontalLine ? height() + m_marginBox.bottom() : width() + m_marginBox.left();
3095 if (!childrenInline()) {
3096 std::optional<int> inlineBlockBaseline = RenderBlock::inlineBlockBaseline(lineDirection);
3097 if (!inlineBlockBaseline)
3098 return inlineBlockBaseline;
3099 lastBaseline = inlineBlockBaseline.value();
3102 if (!hasLineIfEmpty())
3103 return std::optional<int>();
3104 const auto& fontMetrics = firstLineStyle().fontMetrics();
3105 return std::optional<int>(fontMetrics.ascent()
3106 + (lineHeight(true, lineDirection, PositionOfInteriorLineBoxes) - fontMetrics.height()) / 2
3107 + (lineDirection == HorizontalLine ? borderTop() + paddingTop() : borderRight() + paddingRight()));
3110 if (auto simpleLineLayout = this->simpleLineLayout())
3111 lastBaseline = SimpleLineLayout::computeFlowLastLineBaseline(*this, *simpleLineLayout);
3113 bool isFirstLine = lastRootBox() == firstRootBox();
3114 const auto& style = isFirstLine ? firstLineStyle() : this->style();
3115 lastBaseline = lastRootBox()->logicalTop() + style.fontMetrics().ascent(lastRootBox()->baselineType());
3118 // According to the CSS spec http://www.w3.org/TR/CSS21/visudet.html, we shouldn't be performing this min, but should
3119 // instead be returning boxHeight directly. However, we feel that a min here is better behavior (and is consistent
3120 // enough with the spec to not cause tons of breakages).
3121 return std::optional<int>(style().overflowY() == OVISIBLE ? lastBaseline : std::min(boxHeight, lastBaseline));
3124 void RenderBlockFlow::setSelectionState(SelectionState state)
3126 if (state != SelectionNone)
3128 RenderBoxModelObject::setSelectionState(state);
3131 GapRects RenderBlockFlow::inlineSelectionGaps(RenderBlock& rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3132 LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
3134 ASSERT(!m_simpleLineLayout);
3138 bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
3141 if (containsStart) {
3142 // Update our lastLogicalTop to be the bottom of the block. <hr>s or empty blocks with height can trip this case.
3143 lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
3144 lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight(), cache);
3145 lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight(), cache);
3150 RootInlineBox* lastSelectedLine = 0;
3151 RootInlineBox* curr;
3152 for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
3154 // Now paint the gaps for the lines.
3155 for (; curr && curr->hasSelectedChildren(); curr = curr->nextRootBox()) {
3156 LayoutUnit selTop = curr->selectionTopAdjustedForPrecedingBlock();
3157 LayoutUnit selHeight = curr->selectionHeightAdjustedForPrecedingBlock();