2 * Copyright (C) 2013 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "core/rendering/RenderBlockFlow.h"
34 #include "core/accessibility/AXObjectCache.h"
35 #include "core/frame/FrameView.h"
36 #include "core/frame/LocalFrame.h"
37 #include "core/frame/Settings.h"
38 #include "core/html/HTMLDialogElement.h"
39 #include "core/paint/BlockFlowPainter.h"
40 #include "core/rendering/HitTestLocation.h"
41 #include "core/rendering/RenderFlowThread.h"
42 #include "core/rendering/RenderLayer.h"
43 #include "core/rendering/RenderMultiColumnFlowThread.h"
44 #include "core/rendering/RenderPagedFlowThread.h"
45 #include "core/rendering/RenderText.h"
46 #include "core/rendering/RenderView.h"
47 #include "core/rendering/TextAutosizer.h"
48 #include "core/rendering/line/LineWidth.h"
49 #include "platform/text/BidiTextRun.h"
53 bool RenderBlockFlow::s_canPropagateFloatIntoSibling = false;
55 struct SameSizeAsMarginInfo {
57 LayoutUnit margins[2];
60 COMPILE_ASSERT(sizeof(RenderBlockFlow::MarginValues) == sizeof(LayoutUnit[4]), MarginValues_should_stay_small);
63 // Collapsing flags for whether we can collapse our margins with our children's margins.
64 bool m_canCollapseWithChildren : 1;
65 bool m_canCollapseMarginBeforeWithChildren : 1;
66 bool m_canCollapseMarginAfterWithChildren : 1;
67 bool m_canCollapseMarginAfterWithLastChild: 1;
69 // Whether or not we are a quirky container, i.e., do we collapse away top and bottom
70 // margins in our container. Table cells and the body are the common examples. We
71 // also have a custom style property for Safari RSS to deal with TypePad blog articles.
72 bool m_quirkContainer : 1;
74 // This flag tracks whether we are still looking at child margins that can all collapse together at the beginning of a block.
75 // They may or may not collapse with the top margin of the block (|m_canCollapseTopWithChildren| tells us that), but they will
76 // always be collapsing with one another. This variable can remain set to true through multiple iterations
77 // as long as we keep encountering self-collapsing blocks.
78 bool m_atBeforeSideOfBlock : 1;
80 // This flag is set when we know we're examining bottom margins and we know we're at the bottom of the block.
81 bool m_atAfterSideOfBlock : 1;
83 // These variables are used to detect quirky margins that we need to collapse away (in table cells
84 // and in the body element).
85 bool m_hasMarginBeforeQuirk : 1;
86 bool m_hasMarginAfterQuirk : 1;
87 bool m_determinedMarginBeforeQuirk : 1;
89 bool m_discardMargin : 1;
91 // These flags track the previous maximal positive and negative margins.
92 LayoutUnit m_positiveMargin;
93 LayoutUnit m_negativeMargin;
96 MarginInfo(RenderBlockFlow*, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding);
98 void setAtBeforeSideOfBlock(bool b) { m_atBeforeSideOfBlock = b; }
99 void setAtAfterSideOfBlock(bool b) { m_atAfterSideOfBlock = b; }
102 m_positiveMargin = 0;
103 m_negativeMargin = 0;
105 void setHasMarginBeforeQuirk(bool b) { m_hasMarginBeforeQuirk = b; }
106 void setHasMarginAfterQuirk(bool b) { m_hasMarginAfterQuirk = b; }
107 void setDeterminedMarginBeforeQuirk(bool b) { m_determinedMarginBeforeQuirk = b; }
108 void setPositiveMargin(LayoutUnit p) { ASSERT(!m_discardMargin); m_positiveMargin = p; }
109 void setNegativeMargin(LayoutUnit n) { ASSERT(!m_discardMargin); m_negativeMargin = n; }
110 void setPositiveMarginIfLarger(LayoutUnit p)
112 ASSERT(!m_discardMargin);
113 if (p > m_positiveMargin)
114 m_positiveMargin = p;
116 void setNegativeMarginIfLarger(LayoutUnit n)
118 ASSERT(!m_discardMargin);
119 if (n > m_negativeMargin)
120 m_negativeMargin = n;
123 void setMargin(LayoutUnit p, LayoutUnit n) { ASSERT(!m_discardMargin); m_positiveMargin = p; m_negativeMargin = n; }
124 void setCanCollapseMarginAfterWithChildren(bool collapse) { m_canCollapseMarginAfterWithChildren = collapse; }
125 void setCanCollapseMarginAfterWithLastChild(bool collapse) { m_canCollapseMarginAfterWithLastChild = collapse; }
126 void setDiscardMargin(bool value) { m_discardMargin = value; }
128 bool atBeforeSideOfBlock() const { return m_atBeforeSideOfBlock; }
129 bool canCollapseWithMarginBefore() const { return m_atBeforeSideOfBlock && m_canCollapseMarginBeforeWithChildren; }
130 bool canCollapseWithMarginAfter() const { return m_atAfterSideOfBlock && m_canCollapseMarginAfterWithChildren; }
131 bool canCollapseMarginBeforeWithChildren() const { return m_canCollapseMarginBeforeWithChildren; }
132 bool canCollapseMarginAfterWithChildren() const { return m_canCollapseMarginAfterWithChildren; }
133 bool canCollapseMarginAfterWithLastChild() const { return m_canCollapseMarginAfterWithLastChild; }
134 bool quirkContainer() const { return m_quirkContainer; }
135 bool determinedMarginBeforeQuirk() const { return m_determinedMarginBeforeQuirk; }
136 bool hasMarginBeforeQuirk() const { return m_hasMarginBeforeQuirk; }
137 bool hasMarginAfterQuirk() const { return m_hasMarginAfterQuirk; }
138 LayoutUnit positiveMargin() const { return m_positiveMargin; }
139 LayoutUnit negativeMargin() const { return m_negativeMargin; }
140 bool discardMargin() const { return m_discardMargin; }
141 LayoutUnit margin() const { return m_positiveMargin - m_negativeMargin; }
143 static bool inNormalFlow(RenderBox* child)
145 RenderBlock* curr = child->containingBlock();
146 RenderView* renderView = child->view();
147 while (curr && curr != renderView) {
148 if (curr->hasColumns() || curr->isRenderFlowThread())
150 if (curr->isFloatingOrOutOfFlowPositioned())
152 curr = curr->containingBlock();
157 void RenderBlockFlow::RenderBlockFlowRareData::trace(Visitor* visitor)
159 visitor->trace(m_multiColumnFlowThread);
162 RenderBlockFlow::RenderBlockFlow(ContainerNode* node)
165 COMPILE_ASSERT(sizeof(MarginInfo) == sizeof(SameSizeAsMarginInfo), MarginInfo_should_stay_small);
166 setChildrenInline(true);
169 RenderBlockFlow::~RenderBlockFlow()
173 void RenderBlockFlow::trace(Visitor* visitor)
175 visitor->trace(m_rareData);
176 RenderBlock::trace(visitor);
179 RenderBlockFlow* RenderBlockFlow::createAnonymous(Document* document)
181 RenderBlockFlow* renderer = new RenderBlockFlow(0);
182 renderer->setDocumentForAnonymous(document);
186 RenderObject* RenderBlockFlow::layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope& layoutScope)
188 RenderMultiColumnFlowThread* flowThread = multiColumnFlowThread();
191 setLogicalTopForChild(flowThread, borderBefore() + paddingBefore());
192 flowThread->layoutColumns(relayoutChildren, layoutScope);
193 determineLogicalLeftPositionForChild(flowThread);
197 bool RenderBlockFlow::updateLogicalWidthAndColumnWidth()
199 bool relayoutChildren = RenderBlock::updateLogicalWidthAndColumnWidth();
200 if (RenderMultiColumnFlowThread* flowThread = multiColumnFlowThread()) {
201 if (flowThread->needsNewWidth())
204 return relayoutChildren;
207 void RenderBlockFlow::checkForPaginationLogicalHeightChange(LayoutUnit& pageLogicalHeight, bool& pageLogicalHeightChanged, bool& hasSpecifiedPageLogicalHeight)
209 if (RenderMultiColumnFlowThread* flowThread = multiColumnFlowThread()) {
210 LogicalExtentComputedValues computedValues;
211 computeLogicalHeight(LayoutUnit(), logicalTop(), computedValues);
212 LayoutUnit columnHeight = computedValues.m_extent - borderAndPaddingLogicalHeight() - scrollbarLogicalHeight();
213 pageLogicalHeightChanged = columnHeight != flowThread->columnHeightAvailable();
214 flowThread->setColumnHeightAvailable(std::max<LayoutUnit>(columnHeight, 0));
215 } else if (hasColumns()) {
216 ColumnInfo* colInfo = columnInfo();
218 if (!pageLogicalHeight) {
219 LayoutUnit oldLogicalHeight = logicalHeight();
221 // We need to go ahead and set our explicit page height if one exists, so that we can
222 // avoid doing two layout passes.
223 updateLogicalHeight();
224 LayoutUnit columnHeight = contentLogicalHeight();
225 if (columnHeight > 0) {
226 pageLogicalHeight = columnHeight;
227 hasSpecifiedPageLogicalHeight = true;
229 setLogicalHeight(oldLogicalHeight);
231 if (colInfo->columnHeight() != pageLogicalHeight && everHadLayout()) {
232 colInfo->setColumnHeight(pageLogicalHeight);
233 pageLogicalHeightChanged = true;
236 if (!hasSpecifiedPageLogicalHeight && !pageLogicalHeight)
237 colInfo->clearForcedBreaks();
238 } else if (isRenderFlowThread()) {
239 RenderFlowThread* flowThread = toRenderFlowThread(this);
241 // FIXME: This is a hack to always make sure we have a page logical height, if said height
242 // is known. The page logical height thing in LayoutState is meaningless for flow
243 // thread-based pagination (page height isn't necessarily uniform throughout the flow
244 // thread), but as long as it is used universally as a means to determine whether page
245 // height is known or not, we need this. Page height is unknown when column balancing is
246 // enabled and flow thread height is still unknown (i.e. during the first layout pass). When
247 // it's unknown, we need to prevent the pagination code from assuming page breaks everywhere
248 // and thereby eating every top margin. It should be trivial to clean up and get rid of this
249 // hack once the old multicol implementation is gone.
250 pageLogicalHeight = flowThread->isPageLogicalHeightKnown() ? LayoutUnit(1) : LayoutUnit(0);
252 pageLogicalHeightChanged = flowThread->pageLogicalSizeChanged();
256 bool RenderBlockFlow::shouldRelayoutForPagination(LayoutUnit& pageLogicalHeight, LayoutUnit layoutOverflowLogicalBottom) const
258 // FIXME: We don't balance properly at all in the presence of forced page breaks. We need to understand what
259 // the distance between forced page breaks is so that we can avoid making the minimum column height too tall.
260 ColumnInfo* colInfo = columnInfo();
261 LayoutUnit columnHeight = pageLogicalHeight;
262 const int minColumnCount = colInfo->forcedBreaks() + 1;
263 const int desiredColumnCount = colInfo->desiredColumnCount();
264 if (minColumnCount >= desiredColumnCount) {
265 // The forced page breaks are in control of the balancing. Just set the column height to the
266 // maximum page break distance.
267 if (!pageLogicalHeight) {
268 LayoutUnit distanceBetweenBreaks = std::max<LayoutUnit>(colInfo->maximumDistanceBetweenForcedBreaks(),
269 view()->layoutState()->pageLogicalOffset(*this, borderBefore() + paddingBefore() + layoutOverflowLogicalBottom) - colInfo->forcedBreakOffset());
270 columnHeight = std::max(colInfo->minimumColumnHeight(), distanceBetweenBreaks);
272 } else if (layoutOverflowLogicalBottom > boundedMultiply(pageLogicalHeight, desiredColumnCount)) {
273 // Now that we know the intrinsic height of the columns, we have to rebalance them.
274 columnHeight = std::max<LayoutUnit>(colInfo->minimumColumnHeight(), ceilf(layoutOverflowLogicalBottom.toFloat() / desiredColumnCount));
277 if (columnHeight && columnHeight != pageLogicalHeight) {
278 pageLogicalHeight = columnHeight;
285 void RenderBlockFlow::setColumnCountAndHeight(unsigned count, LayoutUnit pageLogicalHeight)
287 ColumnInfo* colInfo = columnInfo();
288 if (pageLogicalHeight)
289 colInfo->setColumnCountAndHeight(count, pageLogicalHeight);
291 if (columnCount(colInfo)) {
292 setLogicalHeight(borderBefore() + paddingBefore() + colInfo->columnHeight() + borderAfter() + paddingAfter() + scrollbarLogicalHeight());
297 void RenderBlockFlow::setBreakAtLineToAvoidWidow(int lineToBreak)
299 ASSERT(lineToBreak >= 0);
301 ASSERT(!m_rareData->m_didBreakAtLineToAvoidWidow);
302 m_rareData->m_lineBreakToAvoidWidow = lineToBreak;
305 void RenderBlockFlow::setDidBreakAtLineToAvoidWidow()
307 ASSERT(!shouldBreakAtLineToAvoidWidow());
309 // This function should be called only after a break was applied to avoid widows
310 // so assert |m_rareData| exists.
313 m_rareData->m_didBreakAtLineToAvoidWidow = true;
316 void RenderBlockFlow::clearDidBreakAtLineToAvoidWidow()
321 m_rareData->m_didBreakAtLineToAvoidWidow = false;
324 void RenderBlockFlow::clearShouldBreakAtLineToAvoidWidow() const
326 ASSERT(shouldBreakAtLineToAvoidWidow());
330 m_rareData->m_lineBreakToAvoidWidow = -1;
333 bool RenderBlockFlow::isSelfCollapsingBlock() const
335 m_hasOnlySelfCollapsingChildren = RenderBlock::isSelfCollapsingBlock();
336 return m_hasOnlySelfCollapsingChildren;
339 void RenderBlockFlow::layoutBlock(bool relayoutChildren)
341 ASSERT(needsLayout());
342 ASSERT(isInlineBlockOrInlineTable() || !isInline());
344 // If we are self-collapsing with self-collapsing descendants this will get set to save us burrowing through our
345 // descendants every time in |isSelfCollapsingBlock|. We reset it here so that |isSelfCollapsingBlock| attempts to burrow
346 // at least once and so that it always gives a reliable result reflecting the latest layout.
347 m_hasOnlySelfCollapsingChildren = false;
349 if (!relayoutChildren && simplifiedLayout())
352 SubtreeLayoutScope layoutScope(*this);
354 // Multiple passes might be required for column and pagination based layout
355 // In the case of the old column code the number of passes will only be two
356 // however, in the newer column code the number of passes could equal the
357 // number of columns.
359 LayoutUnit pageLogicalHeight = 0;
361 done = layoutBlockFlow(relayoutChildren, pageLogicalHeight, layoutScope);
363 RenderView* renderView = view();
364 if (renderView->layoutState()->pageLogicalHeight())
365 setPageLogicalOffset(renderView->layoutState()->pageLogicalOffset(*this, logicalTop()));
367 updateLayerTransformAfterLayout();
369 // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
370 // we overflow or not.
371 updateScrollInfoAfterLayout();
373 if (m_paintInvalidationLogicalTop != m_paintInvalidationLogicalBottom) {
374 bool hasVisibleContent = style()->visibility() == VISIBLE;
375 if (!hasVisibleContent) {
376 RenderLayer* layer = enclosingLayer();
377 layer->updateDescendantDependentFlags();
378 hasVisibleContent = layer->hasVisibleContent();
380 if (hasVisibleContent)
381 setShouldInvalidateOverflowForPaint(true);
384 if (isHTMLDialogElement(node()) && isOutOfFlowPositioned())
390 inline bool RenderBlockFlow::layoutBlockFlow(bool relayoutChildren, LayoutUnit &pageLogicalHeight, SubtreeLayoutScope& layoutScope)
392 LayoutUnit oldLeft = logicalLeft();
393 bool logicalWidthChanged = updateLogicalWidthAndColumnWidth();
394 relayoutChildren |= logicalWidthChanged;
396 rebuildFloatsFromIntruding();
398 bool pageLogicalHeightChanged = false;
399 bool hasSpecifiedPageLogicalHeight = false;
400 checkForPaginationLogicalHeightChange(pageLogicalHeight, pageLogicalHeightChanged, hasSpecifiedPageLogicalHeight);
401 if (pageLogicalHeightChanged)
402 relayoutChildren = true;
404 LayoutState state(*this, locationOffset(), pageLogicalHeight, pageLogicalHeightChanged, columnInfo(), logicalWidthChanged);
406 // We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
407 // our current maximal positive and negative margins. These values are used when we
408 // are collapsed with adjacent blocks, so for example, if you have block A and B
409 // collapsing together, then you'd take the maximal positive margin from both A and B
410 // and subtract it from the maximal negative margin from both A and B to get the
411 // true collapsed margin. This algorithm is recursive, so when we finish layout()
412 // our block knows its current maximal positive/negative values.
414 // Start out by setting our margin values to our current margins. Table cells have
415 // no margins, so we don't fill in the values for table cells.
416 if (!isTableCell()) {
417 initMaxMarginValues();
418 setHasMarginBeforeQuirk(style()->hasMarginBeforeQuirk());
419 setHasMarginAfterQuirk(style()->hasMarginAfterQuirk());
420 setPaginationStrut(0);
423 LayoutUnit beforeEdge = borderBefore() + paddingBefore();
424 LayoutUnit afterEdge = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
425 LayoutUnit previousHeight = logicalHeight();
426 setLogicalHeight(beforeEdge);
428 m_paintInvalidationLogicalTop = 0;
429 m_paintInvalidationLogicalBottom = 0;
430 if (!firstChild() && !isAnonymousBlock())
431 setChildrenInline(true);
433 TextAutosizer::LayoutScope textAutosizerLayoutScope(this);
435 if (childrenInline())
436 layoutInlineChildren(relayoutChildren, m_paintInvalidationLogicalTop, m_paintInvalidationLogicalBottom, afterEdge);
438 layoutBlockChildren(relayoutChildren, layoutScope, beforeEdge, afterEdge);
440 // Expand our intrinsic height to encompass floats.
441 if (lowestFloatLogicalBottom() > (logicalHeight() - afterEdge) && createsBlockFormattingContext())
442 setLogicalHeight(lowestFloatLogicalBottom() + afterEdge);
444 if (RenderMultiColumnFlowThread* flowThread = multiColumnFlowThread()) {
445 if (flowThread->recalculateColumnHeights()) {
446 setChildNeedsLayout(MarkOnlyThis);
449 } else if (hasColumns()) {
450 OwnPtr<RenderOverflow> savedOverflow = m_overflow.release();
451 if (childrenInline())
452 addOverflowFromInlineChildren();
454 addOverflowFromBlockChildren();
455 LayoutUnit layoutOverflowLogicalBottom = (isHorizontalWritingMode() ? layoutOverflowRect().maxY() : layoutOverflowRect().maxX()) - borderBefore() - paddingBefore();
456 m_overflow = savedOverflow.release();
458 if (!hasSpecifiedPageLogicalHeight && shouldRelayoutForPagination(pageLogicalHeight, layoutOverflowLogicalBottom)) {
459 setEverHadLayout(true);
463 setColumnCountAndHeight(ceilf(layoutOverflowLogicalBottom.toFloat() / pageLogicalHeight.toFloat()), pageLogicalHeight.toFloat());
466 if (shouldBreakAtLineToAvoidWidow()) {
467 setEverHadLayout(true);
471 // Calculate our new height.
472 LayoutUnit oldHeight = logicalHeight();
473 LayoutUnit oldClientAfterEdge = clientLogicalBottom();
475 updateLogicalHeight();
476 LayoutUnit newHeight = logicalHeight();
477 if (oldHeight > newHeight && !childrenInline()) {
478 // One of our children's floats may have become an overhanging float for us.
479 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
480 if (child->isRenderBlockFlow() && !child->isFloatingOrOutOfFlowPositioned()) {
481 RenderBlockFlow* block = toRenderBlockFlow(child);
482 if (block->lowestFloatLogicalBottom() + block->logicalTop() <= newHeight)
484 addOverhangingFloats(block, false);
489 bool heightChanged = (previousHeight != newHeight);
491 relayoutChildren = true;
493 layoutPositionedObjects(relayoutChildren || isDocumentElement(), oldLeft != logicalLeft() ? ForcedLayoutAfterContainingBlockMoved : DefaultLayout);
495 // Add overflow from children (unless we're multi-column, since in that case all our child overflow is clipped anyway).
496 computeOverflow(oldClientAfterEdge);
498 m_descendantsWithFloatsMarkedForLayout = false;
502 void RenderBlockFlow::determineLogicalLeftPositionForChild(RenderBox* child)
504 LayoutUnit startPosition = borderStart() + paddingStart();
505 LayoutUnit initialStartPosition = startPosition;
506 if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
507 startPosition -= verticalScrollbarWidth();
508 LayoutUnit totalAvailableLogicalWidth = borderAndPaddingLogicalWidth() + availableLogicalWidth();
510 LayoutUnit childMarginStart = marginStartForChild(child);
511 LayoutUnit newPosition = startPosition + childMarginStart;
513 LayoutUnit positionToAvoidFloats;
514 if (child->avoidsFloats() && containsFloats() && !flowThreadContainingBlock())
515 positionToAvoidFloats = startOffsetForLine(logicalTopForChild(child), false, logicalHeightForChild(child));
517 // If the child has an offset from the content edge to avoid floats then use that, otherwise let any negative
518 // margin pull it back over the content edge or any positive margin push it out.
519 // If the child is being centred then the margin calculated to do that has factored in any offset required to
520 // avoid floats, so use it if necessary.
521 if (style()->textAlign() == WEBKIT_CENTER || child->style()->marginStartUsing(style()).isAuto())
522 newPosition = std::max(newPosition, positionToAvoidFloats + childMarginStart);
523 else if (positionToAvoidFloats > initialStartPosition)
524 newPosition = std::max(newPosition, positionToAvoidFloats);
526 setLogicalLeftForChild(child, style()->isLeftToRightDirection() ? newPosition : totalAvailableLogicalWidth - newPosition - logicalWidthForChild(child));
529 void RenderBlockFlow::setLogicalLeftForChild(RenderBox* child, LayoutUnit logicalLeft)
531 if (isHorizontalWritingMode()) {
532 child->setX(logicalLeft);
534 child->setY(logicalLeft);
538 void RenderBlockFlow::setLogicalTopForChild(RenderBox* child, LayoutUnit logicalTop)
540 if (isHorizontalWritingMode()) {
541 child->setY(logicalTop);
543 child->setX(logicalTop);
547 void RenderBlockFlow::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom)
549 LayoutUnit oldPosMarginBefore = maxPositiveMarginBefore();
550 LayoutUnit oldNegMarginBefore = maxNegativeMarginBefore();
552 // The child is a normal flow object. Compute the margins we will use for collapsing now.
553 child->computeAndSetBlockDirectionMargins(this);
555 // Try to guess our correct logical top position. In most cases this guess will
556 // be correct. Only if we're wrong (when we compute the real logical top position)
557 // will we have to potentially relayout.
558 LayoutUnit estimateWithoutPagination;
559 LayoutUnit logicalTopEstimate = estimateLogicalTopPosition(child, marginInfo, estimateWithoutPagination);
561 // Cache our old rect so that we can dirty the proper paint invalidation rects if the child moves.
562 LayoutRect oldRect = child->frameRect();
563 LayoutUnit oldLogicalTop = logicalTopForChild(child);
565 // Go ahead and position the child as though it didn't collapse with the top.
566 setLogicalTopForChild(child, logicalTopEstimate);
568 RenderBlockFlow* childRenderBlockFlow = child->isRenderBlockFlow() ? toRenderBlockFlow(child) : 0;
569 bool markDescendantsWithFloats = false;
570 if (logicalTopEstimate != oldLogicalTop && childRenderBlockFlow && !childRenderBlockFlow->avoidsFloats() && childRenderBlockFlow->containsFloats()) {
571 markDescendantsWithFloats = true;
572 } else if (UNLIKELY(logicalTopEstimate.mightBeSaturated())) {
573 // logicalTopEstimate, returned by estimateLogicalTopPosition, might be saturated for
574 // very large elements. If it does the comparison with oldLogicalTop might yield a
575 // false negative as adding and removing margins, borders etc from a saturated number
576 // might yield incorrect results. If this is the case always mark for layout.
577 markDescendantsWithFloats = true;
578 } else if (!child->avoidsFloats() || child->shrinkToAvoidFloats()) {
579 // If an element might be affected by the presence of floats, then always mark it for
581 LayoutUnit fb = std::max(previousFloatLogicalBottom, lowestFloatLogicalBottom());
582 if (fb > logicalTopEstimate)
583 markDescendantsWithFloats = true;
586 if (childRenderBlockFlow) {
587 if (markDescendantsWithFloats)
588 childRenderBlockFlow->markAllDescendantsWithFloatsForLayout();
589 if (!child->isWritingModeRoot())
590 previousFloatLogicalBottom = std::max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlockFlow->lowestFloatLogicalBottom());
593 SubtreeLayoutScope layoutScope(*child);
594 if (!child->needsLayout())
595 child->markForPaginationRelayoutIfNeeded(layoutScope);
597 bool childNeededLayout = child->needsLayout();
598 if (childNeededLayout)
601 // Cache if we are at the top of the block right now.
602 bool atBeforeSideOfBlock = marginInfo.atBeforeSideOfBlock();
603 bool childIsSelfCollapsing = child->isSelfCollapsingBlock();
605 // Now determine the correct ypos based off examination of collapsing margin
607 LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo, childIsSelfCollapsing);
609 // Now check for clear.
610 LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear, childIsSelfCollapsing);
612 bool paginated = view()->layoutState()->isPaginated();
614 logicalTopAfterClear = adjustBlockChildForPagination(logicalTopAfterClear, estimateWithoutPagination, child,
615 atBeforeSideOfBlock && logicalTopBeforeClear == logicalTopAfterClear);
618 setLogicalTopForChild(child, logicalTopAfterClear);
620 // Now we have a final top position. See if it really does end up being different from our estimate.
621 // clearFloatsIfNeeded can also mark the child as needing a layout even though we didn't move. This happens
622 // when collapseMargins dynamically adds overhanging floats because of a child with negative margins.
623 if (logicalTopAfterClear != logicalTopEstimate || child->needsLayout() || (paginated && childRenderBlockFlow && childRenderBlockFlow->shouldBreakAtLineToAvoidWidow())) {
624 SubtreeLayoutScope layoutScope(*child);
625 if (child->shrinkToAvoidFloats()) {
626 // The child's width depends on the line width.
627 // When the child shifts to clear an item, its width can
628 // change (because it has more available line width).
629 // So go ahead and mark the item as dirty.
630 layoutScope.setChildNeedsLayout(child);
633 if (childRenderBlockFlow && !childRenderBlockFlow->avoidsFloats() && childRenderBlockFlow->containsFloats())
634 childRenderBlockFlow->markAllDescendantsWithFloatsForLayout();
636 if (!child->needsLayout())
637 child->markForPaginationRelayoutIfNeeded(layoutScope);
639 // Our guess was wrong. Make the child lay itself out again.
640 child->layoutIfNeeded();
643 // If we previously encountered a self-collapsing sibling of this child that had clearance then
644 // we set this bit to ensure we would not collapse the child's margins, and those of any subsequent
645 // self-collapsing siblings, with our parent. If this child is not self-collapsing then it can
646 // collapse its margins with the parent so reset the bit.
647 if (!marginInfo.canCollapseMarginAfterWithLastChild() && !childIsSelfCollapsing)
648 marginInfo.setCanCollapseMarginAfterWithLastChild(true);
650 // We are no longer at the top of the block if we encounter a non-empty child.
651 // This has to be done after checking for clear, so that margins can be reset if a clear occurred.
652 if (marginInfo.atBeforeSideOfBlock() && !childIsSelfCollapsing)
653 marginInfo.setAtBeforeSideOfBlock(false);
655 // Now place the child in the correct left position
656 determineLogicalLeftPositionForChild(child);
658 LayoutSize childOffset = child->location() - oldRect.location();
660 // Update our height now that the child has been placed in the correct position.
661 setLogicalHeight(logicalHeight() + logicalHeightForChild(child));
662 if (mustSeparateMarginAfterForChild(child)) {
663 setLogicalHeight(logicalHeight() + marginAfterForChild(child));
664 marginInfo.clearMargin();
666 // If the child has overhanging floats that intrude into following siblings (or possibly out
667 // of this block), then the parent gets notified of the floats now.
668 if (childRenderBlockFlow)
669 addOverhangingFloats(childRenderBlockFlow, !childNeededLayout);
671 // If the child moved, we have to invalidate its paint as well as any floating/positioned
672 // descendants. An exception is if we need a layout. In this case, we know we're going to
673 // invalidate our paint (and the child) anyway.
674 if (!selfNeedsLayout() && (childOffset.width() || childOffset.height()))
675 child->invalidatePaintForOverhangingFloats(true);
678 // Check for an after page/column break.
679 LayoutUnit newHeight = applyAfterBreak(child, logicalHeight(), marginInfo);
680 if (newHeight != height())
681 setLogicalHeight(newHeight);
685 LayoutUnit RenderBlockFlow::adjustBlockChildForPagination(LayoutUnit logicalTopAfterClear, LayoutUnit estimateWithoutPagination, RenderBox* child, bool atBeforeSideOfBlock)
687 RenderBlockFlow* childBlockFlow = child->isRenderBlockFlow() ? toRenderBlockFlow(child) : 0;
689 if (estimateWithoutPagination != logicalTopAfterClear) {
690 // Our guess prior to pagination movement was wrong. Before we attempt to paginate, let's try again at the new
692 setLogicalHeight(logicalTopAfterClear);
693 setLogicalTopForChild(child, logicalTopAfterClear);
695 if (child->shrinkToAvoidFloats()) {
696 // The child's width depends on the line width.
697 // When the child shifts to clear an item, its width can
698 // change (because it has more available line width).
699 // So go ahead and mark the item as dirty.
700 child->setChildNeedsLayout(MarkOnlyThis);
703 SubtreeLayoutScope layoutScope(*child);
705 if (childBlockFlow) {
706 if (!childBlockFlow->avoidsFloats() && childBlockFlow->containsFloats())
707 childBlockFlow->markAllDescendantsWithFloatsForLayout();
708 if (!child->needsLayout())
709 child->markForPaginationRelayoutIfNeeded(layoutScope);
712 // Our guess was wrong. Make the child lay itself out again.
713 child->layoutIfNeeded();
716 LayoutUnit oldTop = logicalTopAfterClear;
718 // If the object has a page or column break value of "before", then we should shift to the top of the next page.
719 LayoutUnit result = applyBeforeBreak(child, logicalTopAfterClear);
721 // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
722 LayoutUnit logicalTopBeforeUnsplittableAdjustment = result;
723 LayoutUnit logicalTopAfterUnsplittableAdjustment = adjustForUnsplittableChild(child, result);
725 LayoutUnit paginationStrut = 0;
726 LayoutUnit unsplittableAdjustmentDelta = logicalTopAfterUnsplittableAdjustment - logicalTopBeforeUnsplittableAdjustment;
727 LayoutUnit childLogicalHeight = child->logicalHeight();
728 if (unsplittableAdjustmentDelta) {
729 setPageBreak(result, childLogicalHeight - unsplittableAdjustmentDelta);
730 paginationStrut = unsplittableAdjustmentDelta;
731 } else if (childBlockFlow && childBlockFlow->paginationStrut()) {
732 paginationStrut = childBlockFlow->paginationStrut();
735 if (paginationStrut) {
736 // We are willing to propagate out to our parent block as long as we were at the top of the block prior
737 // to collapsing our margins, and as long as we didn't clear or move as a result of other pagination.
738 if (atBeforeSideOfBlock && oldTop == result && !isOutOfFlowPositioned() && !isTableCell()) {
739 // FIXME: Should really check if we're exceeding the page height before propagating the strut, but we don't
740 // have all the information to do so (the strut only has the remaining amount to push). Gecko gets this wrong too
741 // and pushes to the next page anyway, so not too concerned about it.
742 setPaginationStrut(result + paginationStrut);
744 childBlockFlow->setPaginationStrut(0);
746 result += paginationStrut;
750 if (!unsplittableAdjustmentDelta) {
751 if (LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(result)) {
752 LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(result, ExcludePageBoundary);
753 LayoutUnit spaceShortage = childLogicalHeight - remainingLogicalHeight;
754 if (spaceShortage > 0) {
755 // If the child crosses a column boundary, report a break, in case nothing inside it
756 // has already done so. The column balancer needs to know how much it has to stretch
757 // the columns to make more content fit. If no breaks are reported (but do occur),
758 // the balancer will have no clue. Only measure the space after the last column
759 // boundary, in case it crosses more than one.
760 LayoutUnit spaceShortageInLastColumn = intMod(spaceShortage, pageLogicalHeight);
761 setPageBreak(result, spaceShortageInLastColumn ? spaceShortageInLastColumn : spaceShortage);
762 } else if (remainingLogicalHeight == pageLogicalHeight && offsetFromLogicalTopOfFirstPage() + child->logicalTop()) {
763 // We're at the very top of a page or column, and it's not the first one. This child
764 // may turn out to be the smallest piece of content that causes a page break, so we
765 // need to report it.
766 setPageBreak(result, childLogicalHeight);
771 // Similar to how we apply clearance. Go ahead and boost height() to be the place where we're going to position the child.
772 setLogicalHeight(logicalHeight() + (result - oldTop));
774 // Return the final adjusted logical top.
778 static inline LayoutUnit calculateMinimumPageHeight(RenderStyle* renderStyle, RootInlineBox* lastLine, LayoutUnit lineTop, LayoutUnit lineBottom)
780 // We may require a certain minimum number of lines per page in order to satisfy
781 // orphans and widows, and that may affect the minimum page height.
782 unsigned lineCount = std::max<unsigned>(renderStyle->hasAutoOrphans() ? 1 : renderStyle->orphans(), renderStyle->hasAutoWidows() ? 1 : renderStyle->widows());
784 RootInlineBox* line = lastLine;
785 for (unsigned i = 1; i < lineCount && line->prevRootBox(); i++)
786 line = line->prevRootBox();
788 // FIXME: Paginating using line overflow isn't all fine. See FIXME in
789 // adjustLinePositionForPagination() for more details.
790 LayoutRect overflow = line->logicalVisualOverflowRect(line->lineTop(), line->lineBottom());
791 lineTop = std::min(line->lineTopWithLeading(), overflow.y());
793 return lineBottom - lineTop;
796 void RenderBlockFlow::adjustLinePositionForPagination(RootInlineBox* lineBox, LayoutUnit& delta, RenderFlowThread* flowThread)
798 // FIXME: For now we paginate using line overflow. This ensures that lines don't overlap at all when we
799 // put a strut between them for pagination purposes. However, this really isn't the desired rendering, since
800 // the line on the top of the next page will appear too far down relative to the same kind of line at the top
801 // of the first column.
803 // The rendering we would like to see is one where the lineTopWithLeading is at the top of the column, and any line overflow
804 // simply spills out above the top of the column. This effect would match what happens at the top of the first column.
805 // We can't achieve this rendering, however, until we stop columns from clipping to the column bounds (thus allowing
806 // for overflow to occur), and then cache visible overflow for each column rect.
808 // Furthermore, the paint we have to do when a column has overflow has to be special. We need to exclude
809 // content that paints in a previous column (and content that paints in the following column).
811 // For now we'll at least honor the lineTopWithLeading when paginating if it is above the logical top overflow. This will
812 // at least make positive leading work in typical cases.
814 // FIXME: Another problem with simply moving lines is that the available line width may change (because of floats).
815 // Technically if the location we move the line to has a different line width than our old position, then we need to dirty the
816 // line and all following lines.
817 LayoutRect logicalVisualOverflow = lineBox->logicalVisualOverflowRect(lineBox->lineTop(), lineBox->lineBottom());
818 LayoutUnit logicalOffset = std::min(lineBox->lineTopWithLeading(), logicalVisualOverflow.y());
819 LayoutUnit logicalBottom = std::max(lineBox->lineBottomWithLeading(), logicalVisualOverflow.maxY());
820 LayoutUnit lineHeight = logicalBottom - logicalOffset;
821 updateMinimumPageHeight(logicalOffset, calculateMinimumPageHeight(style(), lineBox, logicalOffset, logicalBottom));
822 logicalOffset += delta;
823 lineBox->setPaginationStrut(0);
824 lineBox->setIsFirstAfterPageBreak(false);
825 LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
826 bool hasUniformPageLogicalHeight = !flowThread || flowThread->regionsHaveUniformLogicalHeight();
827 // If lineHeight is greater than pageLogicalHeight, but logicalVisualOverflow.height() still fits, we are
828 // still going to add a strut, so that the visible overflow fits on a single page.
829 if (!pageLogicalHeight || (hasUniformPageLogicalHeight && logicalVisualOverflow.height() > pageLogicalHeight)) {
830 // 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.
831 // 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.
834 LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset, ExcludePageBoundary);
836 int lineIndex = lineCount(lineBox);
837 if (remainingLogicalHeight < lineHeight || (shouldBreakAtLineToAvoidWidow() && lineBreakToAvoidWidow() == lineIndex)) {
838 if (shouldBreakAtLineToAvoidWidow() && lineBreakToAvoidWidow() == lineIndex) {
839 clearShouldBreakAtLineToAvoidWidow();
840 setDidBreakAtLineToAvoidWidow();
842 if (lineHeight > pageLogicalHeight) {
843 // Split the top margin in order to avoid splitting the visible part of the line.
844 remainingLogicalHeight -= std::min(lineHeight - pageLogicalHeight, std::max<LayoutUnit>(0, logicalVisualOverflow.y() - lineBox->lineTopWithLeading()));
846 LayoutUnit totalLogicalHeight = lineHeight + std::max<LayoutUnit>(0, logicalOffset);
847 LayoutUnit pageLogicalHeightAtNewOffset = hasUniformPageLogicalHeight ? pageLogicalHeight : pageLogicalHeightForOffset(logicalOffset + remainingLogicalHeight);
848 setPageBreak(logicalOffset, lineHeight - remainingLogicalHeight);
849 if (((lineBox == firstRootBox() && totalLogicalHeight < pageLogicalHeightAtNewOffset) || (!style()->hasAutoOrphans() && style()->orphans() >= lineIndex))
850 && !isOutOfFlowPositioned() && !isTableCell()) {
851 setPaginationStrut(remainingLogicalHeight + std::max<LayoutUnit>(0, logicalOffset));
853 delta += remainingLogicalHeight;
854 lineBox->setPaginationStrut(remainingLogicalHeight);
855 lineBox->setIsFirstAfterPageBreak(true);
857 } else if (remainingLogicalHeight == pageLogicalHeight) {
858 // We're at the very top of a page or column.
859 if (lineBox != firstRootBox())
860 lineBox->setIsFirstAfterPageBreak(true);
861 if (lineBox != firstRootBox() || offsetFromLogicalTopOfFirstPage())
862 setPageBreak(logicalOffset, lineHeight);
866 LayoutUnit RenderBlockFlow::adjustForUnsplittableChild(RenderBox* child, LayoutUnit logicalOffset, bool includeMargins)
868 bool checkColumnBreaks = view()->layoutState()->isPaginatingColumns() || flowThreadContainingBlock();
869 bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->pageLogicalHeight();
870 bool isUnsplittable = child->isUnsplittableForPagination() || (checkColumnBreaks && child->style()->columnBreakInside() == PBAVOID)
871 || (checkPageBreaks && child->style()->pageBreakInside() == PBAVOID);
873 return logicalOffset;
874 LayoutUnit childLogicalHeight = logicalHeightForChild(child) + (includeMargins ? marginBeforeForChild(child) + marginAfterForChild(child) : LayoutUnit());
875 LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
876 updateMinimumPageHeight(logicalOffset, childLogicalHeight);
877 if (!pageLogicalHeight || childLogicalHeight > pageLogicalHeight)
878 return logicalOffset;
879 LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset, ExcludePageBoundary);
880 if (remainingLogicalHeight < childLogicalHeight)
881 return logicalOffset + remainingLogicalHeight;
882 return logicalOffset;
885 void RenderBlockFlow::rebuildFloatsFromIntruding()
887 if (m_floatingObjects)
888 m_floatingObjects->setHorizontalWritingMode(isHorizontalWritingMode());
890 HashSet<RenderBox*> oldIntrudingFloatSet;
891 if (!childrenInline() && m_floatingObjects) {
892 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
893 FloatingObjectSetIterator end = floatingObjectSet.end();
894 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
895 FloatingObject* floatingObject = it->get();
896 if (!floatingObject->isDescendant())
897 oldIntrudingFloatSet.add(floatingObject->renderer());
901 // Inline blocks are covered by the isReplaced() check in the avoidFloats method.
902 if (avoidsFloats() || isDocumentElement() || isRenderView() || isFloatingOrOutOfFlowPositioned() || isTableCell()) {
903 if (m_floatingObjects) {
904 m_floatingObjects->clear();
906 if (!oldIntrudingFloatSet.isEmpty())
907 markAllDescendantsWithFloatsForLayout();
911 RendererToFloatInfoMap floatMap;
913 if (m_floatingObjects) {
914 if (childrenInline())
915 m_floatingObjects->moveAllToFloatInfoMap(floatMap);
917 m_floatingObjects->clear();
920 // We should not process floats if the parent node is not a RenderBlockFlow. Otherwise, we will add
921 // floats in an invalid context. This will cause a crash arising from a bad cast on the parent.
922 // See <rdar://problem/8049753>, where float property is applied on a text node in a SVG.
923 if (!parent() || !parent()->isRenderBlockFlow())
926 // Attempt to locate a previous sibling with overhanging floats. We skip any elements that
927 // may have shifted to avoid floats, and any objects whose floats cannot interact with objects
928 // outside it (i.e. objects that create a new block formatting context).
929 RenderBlockFlow* parentBlockFlow = toRenderBlockFlow(parent());
930 bool parentHasFloats = false;
931 RenderObject* prev = previousSibling();
932 while (prev && (!prev->isBox() || !prev->isRenderBlock() || toRenderBlock(prev)->avoidsFloats() || toRenderBlock(prev)->createsBlockFormattingContext())) {
933 if (prev->isFloating())
934 parentHasFloats = true;
935 prev = prev->previousSibling();
938 // First add in floats from the parent. Self-collapsing blocks let their parent track any floats that intrude into
939 // them (as opposed to floats they contain themselves) so check for those here too.
940 LayoutUnit logicalTopOffset = logicalTop();
941 bool parentHasIntrudingFloats = !parentHasFloats && (!prev || toRenderBlockFlow(prev)->isSelfCollapsingBlock()) && parentBlockFlow->lowestFloatLogicalBottom() > logicalTopOffset;
942 if (parentHasFloats || parentHasIntrudingFloats)
943 addIntrudingFloats(parentBlockFlow, parentBlockFlow->logicalLeftOffsetForContent(), logicalTopOffset);
945 // Add overhanging floats from the previous RenderBlockFlow, but only if it has a float that intrudes into our space.
947 RenderBlockFlow* blockFlow = toRenderBlockFlow(prev);
948 logicalTopOffset -= blockFlow->logicalTop();
949 if (blockFlow->lowestFloatLogicalBottom() > logicalTopOffset)
950 addIntrudingFloats(blockFlow, 0, logicalTopOffset);
953 if (childrenInline()) {
954 LayoutUnit changeLogicalTop = LayoutUnit::max();
955 LayoutUnit changeLogicalBottom = LayoutUnit::min();
956 if (m_floatingObjects) {
957 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
958 FloatingObjectSetIterator end = floatingObjectSet.end();
959 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
960 FloatingObject* floatingObject = it->get();
961 FloatingObject* oldFloatingObject = floatMap.get(floatingObject->renderer());
962 LayoutUnit logicalBottom = logicalBottomForFloat(floatingObject);
963 if (oldFloatingObject) {
964 LayoutUnit oldLogicalBottom = logicalBottomForFloat(oldFloatingObject);
965 if (logicalWidthForFloat(floatingObject) != logicalWidthForFloat(oldFloatingObject) || logicalLeftForFloat(floatingObject) != logicalLeftForFloat(oldFloatingObject)) {
966 changeLogicalTop = 0;
967 changeLogicalBottom = std::max(changeLogicalBottom, std::max(logicalBottom, oldLogicalBottom));
969 if (logicalBottom != oldLogicalBottom) {
970 changeLogicalTop = std::min(changeLogicalTop, std::min(logicalBottom, oldLogicalBottom));
971 changeLogicalBottom = std::max(changeLogicalBottom, std::max(logicalBottom, oldLogicalBottom));
973 LayoutUnit logicalTop = logicalTopForFloat(floatingObject);
974 LayoutUnit oldLogicalTop = logicalTopForFloat(oldFloatingObject);
975 if (logicalTop != oldLogicalTop) {
976 changeLogicalTop = std::min(changeLogicalTop, std::min(logicalTop, oldLogicalTop));
977 changeLogicalBottom = std::max(changeLogicalBottom, std::max(logicalTop, oldLogicalTop));
981 if (oldFloatingObject->originatingLine() && !selfNeedsLayout()) {
982 ASSERT(oldFloatingObject->originatingLine()->renderer() == this);
983 oldFloatingObject->originatingLine()->markDirty();
986 floatMap.remove(floatingObject->renderer());
988 changeLogicalTop = 0;
989 changeLogicalBottom = std::max(changeLogicalBottom, logicalBottom);
994 RendererToFloatInfoMap::iterator end = floatMap.end();
995 for (RendererToFloatInfoMap::iterator it = floatMap.begin(); it != end; ++it) {
996 OwnPtr<FloatingObject>& floatingObject = it->value;
997 if (!floatingObject->isDescendant()) {
998 changeLogicalTop = 0;
999 changeLogicalBottom = std::max(changeLogicalBottom, logicalBottomForFloat(floatingObject.get()));
1003 markLinesDirtyInBlockRange(changeLogicalTop, changeLogicalBottom);
1004 } else if (!oldIntrudingFloatSet.isEmpty()) {
1005 // If there are previously intruding floats that no longer intrude, then children with floats
1006 // should also get layout because they might need their floating object lists cleared.
1007 if (m_floatingObjects->set().size() < oldIntrudingFloatSet.size()) {
1008 markAllDescendantsWithFloatsForLayout();
1010 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1011 FloatingObjectSetIterator end = floatingObjectSet.end();
1012 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end && !oldIntrudingFloatSet.isEmpty(); ++it)
1013 oldIntrudingFloatSet.remove((*it)->renderer());
1014 if (!oldIntrudingFloatSet.isEmpty())
1015 markAllDescendantsWithFloatsForLayout();
1020 void RenderBlockFlow::layoutBlockChildren(bool relayoutChildren, SubtreeLayoutScope& layoutScope, LayoutUnit beforeEdge, LayoutUnit afterEdge)
1022 dirtyForLayoutFromPercentageHeightDescendants(layoutScope);
1024 // The margin struct caches all our current margin collapsing state. The compact struct caches state when we encounter compacts,
1025 MarginInfo marginInfo(this, beforeEdge, afterEdge);
1027 // Fieldsets need to find their legend and position it inside the border of the object.
1028 // The legend then gets skipped during normal layout. The same is true for ruby text.
1029 // It doesn't get included in the normal layout process but is instead skipped.
1030 RenderObject* childToExclude = layoutSpecialExcludedChild(relayoutChildren, layoutScope);
1032 LayoutUnit previousFloatLogicalBottom = 0;
1034 RenderBox* next = firstChildBox();
1035 RenderBox* lastNormalFlowChild = 0;
1038 RenderBox* child = next;
1039 next = child->nextSiblingBox();
1041 child->setMayNeedPaintInvalidation(true);
1043 if (childToExclude == child)
1044 continue; // Skip this child, since it will be positioned by the specialized subclass (fieldsets and ruby runs).
1046 updateBlockChildDirtyBitsBeforeLayout(relayoutChildren, child);
1048 if (child->isOutOfFlowPositioned()) {
1049 child->containingBlock()->insertPositionedObject(child);
1050 adjustPositionedBlock(child, marginInfo);
1053 if (child->isFloating()) {
1054 insertFloatingObject(child);
1055 adjustFloatingBlock(marginInfo);
1059 // Lay out the child.
1060 layoutBlockChild(child, marginInfo, previousFloatLogicalBottom);
1061 lastNormalFlowChild = child;
1064 // Now do the handling of the bottom of the block, adding in our bottom border/padding and
1065 // determining the correct collapsed bottom margin information.
1066 handleAfterSideOfBlock(lastNormalFlowChild, beforeEdge, afterEdge, marginInfo);
1069 // Our MarginInfo state used when laying out block children.
1070 MarginInfo::MarginInfo(RenderBlockFlow* blockFlow, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding)
1071 : m_canCollapseMarginAfterWithLastChild(true)
1072 , m_atBeforeSideOfBlock(true)
1073 , m_atAfterSideOfBlock(false)
1074 , m_hasMarginBeforeQuirk(false)
1075 , m_hasMarginAfterQuirk(false)
1076 , m_determinedMarginBeforeQuirk(false)
1077 , m_discardMargin(false)
1079 RenderStyle* blockStyle = blockFlow->style();
1080 ASSERT(blockFlow->isRenderView() || blockFlow->parent());
1081 m_canCollapseWithChildren = !blockFlow->createsBlockFormattingContext() && !blockFlow->isRenderFlowThread() && !blockFlow->isRenderView();
1083 m_canCollapseMarginBeforeWithChildren = m_canCollapseWithChildren && !beforeBorderPadding && blockStyle->marginBeforeCollapse() != MSEPARATE;
1085 // If any height other than auto is specified in CSS, then we don't collapse our bottom
1086 // margins with our children's margins. To do otherwise would be to risk odd visual
1087 // effects when the children overflow out of the parent block and yet still collapse
1088 // with it. We also don't collapse if we have any bottom border/padding.
1089 m_canCollapseMarginAfterWithChildren = m_canCollapseWithChildren && !afterBorderPadding
1090 && (blockStyle->logicalHeight().isAuto() && !blockStyle->logicalHeight().value()) && blockStyle->marginAfterCollapse() != MSEPARATE;
1092 m_quirkContainer = blockFlow->isTableCell() || blockFlow->isBody();
1094 m_discardMargin = m_canCollapseMarginBeforeWithChildren && blockFlow->mustDiscardMarginBefore();
1096 m_positiveMargin = (m_canCollapseMarginBeforeWithChildren && !blockFlow->mustDiscardMarginBefore()) ? blockFlow->maxPositiveMarginBefore() : LayoutUnit();
1097 m_negativeMargin = (m_canCollapseMarginBeforeWithChildren && !blockFlow->mustDiscardMarginBefore()) ? blockFlow->maxNegativeMarginBefore() : LayoutUnit();
1100 RenderBlockFlow::MarginValues RenderBlockFlow::marginValuesForChild(RenderBox* child) const
1102 LayoutUnit childBeforePositive = 0;
1103 LayoutUnit childBeforeNegative = 0;
1104 LayoutUnit childAfterPositive = 0;
1105 LayoutUnit childAfterNegative = 0;
1107 LayoutUnit beforeMargin = 0;
1108 LayoutUnit afterMargin = 0;
1110 RenderBlockFlow* childRenderBlockFlow = child->isRenderBlockFlow() ? toRenderBlockFlow(child) : 0;
1112 // If the child has the same directionality as we do, then we can just return its
1113 // margins in the same direction.
1114 if (!child->isWritingModeRoot()) {
1115 if (childRenderBlockFlow) {
1116 childBeforePositive = childRenderBlockFlow->maxPositiveMarginBefore();
1117 childBeforeNegative = childRenderBlockFlow->maxNegativeMarginBefore();
1118 childAfterPositive = childRenderBlockFlow->maxPositiveMarginAfter();
1119 childAfterNegative = childRenderBlockFlow->maxNegativeMarginAfter();
1121 beforeMargin = child->marginBefore();
1122 afterMargin = child->marginAfter();
1124 } else if (child->isHorizontalWritingMode() == isHorizontalWritingMode()) {
1125 // The child has a different directionality. If the child is parallel, then it's just
1126 // flipped relative to us. We can use the margins for the opposite edges.
1127 if (childRenderBlockFlow) {
1128 childBeforePositive = childRenderBlockFlow->maxPositiveMarginAfter();
1129 childBeforeNegative = childRenderBlockFlow->maxNegativeMarginAfter();
1130 childAfterPositive = childRenderBlockFlow->maxPositiveMarginBefore();
1131 childAfterNegative = childRenderBlockFlow->maxNegativeMarginBefore();
1133 beforeMargin = child->marginAfter();
1134 afterMargin = child->marginBefore();
1137 // The child is perpendicular to us, which means its margins don't collapse but are on the
1138 // "logical left/right" sides of the child box. We can just return the raw margin in this case.
1139 beforeMargin = marginBeforeForChild(child);
1140 afterMargin = marginAfterForChild(child);
1143 // Resolve uncollapsing margins into their positive/negative buckets.
1145 if (beforeMargin > 0)
1146 childBeforePositive = beforeMargin;
1148 childBeforeNegative = -beforeMargin;
1151 if (afterMargin > 0)
1152 childAfterPositive = afterMargin;
1154 childAfterNegative = -afterMargin;
1157 return RenderBlockFlow::MarginValues(childBeforePositive, childBeforeNegative, childAfterPositive, childAfterNegative);
1160 LayoutUnit RenderBlockFlow::collapseMargins(RenderBox* child, MarginInfo& marginInfo, bool childIsSelfCollapsing)
1162 bool childDiscardMarginBefore = mustDiscardMarginBeforeForChild(child);
1163 bool childDiscardMarginAfter = mustDiscardMarginAfterForChild(child);
1165 // The child discards the before margin when the the after margin has discard in the case of a self collapsing block.
1166 childDiscardMarginBefore = childDiscardMarginBefore || (childDiscardMarginAfter && childIsSelfCollapsing);
1168 // Get the four margin values for the child and cache them.
1169 const RenderBlockFlow::MarginValues childMargins = marginValuesForChild(child);
1171 // Get our max pos and neg top margins.
1172 LayoutUnit posTop = childMargins.positiveMarginBefore();
1173 LayoutUnit negTop = childMargins.negativeMarginBefore();
1175 // For self-collapsing blocks, collapse our bottom margins into our
1176 // top to get new posTop and negTop values.
1177 if (childIsSelfCollapsing) {
1178 posTop = std::max(posTop, childMargins.positiveMarginAfter());
1179 negTop = std::max(negTop, childMargins.negativeMarginAfter());
1182 // See if the top margin is quirky. We only care if this child has
1183 // margins that will collapse with us.
1184 bool topQuirk = hasMarginBeforeQuirk(child);
1186 if (marginInfo.canCollapseWithMarginBefore()) {
1187 if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
1188 // This child is collapsing with the top of the
1189 // block. If it has larger margin values, then we need to update
1190 // our own maximal values.
1191 if (!document().inQuirksMode() || !marginInfo.quirkContainer() || !topQuirk)
1192 setMaxMarginBeforeValues(std::max(posTop, maxPositiveMarginBefore()), std::max(negTop, maxNegativeMarginBefore()));
1194 // The minute any of the margins involved isn't a quirk, don't
1195 // collapse it away, even if the margin is smaller (www.webreference.com
1196 // has an example of this, a <dt> with 0.8em author-specified inside
1197 // a <dl> inside a <td>.
1198 if (!marginInfo.determinedMarginBeforeQuirk() && !topQuirk && (posTop - negTop)) {
1199 setHasMarginBeforeQuirk(false);
1200 marginInfo.setDeterminedMarginBeforeQuirk(true);
1203 if (!marginInfo.determinedMarginBeforeQuirk() && topQuirk && !marginBefore()) {
1204 // We have no top margin and our top child has a quirky margin.
1205 // We will pick up this quirky margin and pass it through.
1206 // This deals with the <td><div><p> case.
1207 // Don't do this for a block that split two inlines though. You do
1208 // still apply margins in this case.
1209 setHasMarginBeforeQuirk(true);
1212 // The before margin of the container will also discard all the margins it is collapsing with.
1213 setMustDiscardMarginBefore();
1217 // Once we find a child with discardMarginBefore all the margins collapsing with us must also discard.
1218 if (childDiscardMarginBefore) {
1219 marginInfo.setDiscardMargin(true);
1220 marginInfo.clearMargin();
1223 if (marginInfo.quirkContainer() && marginInfo.atBeforeSideOfBlock() && (posTop - negTop))
1224 marginInfo.setHasMarginBeforeQuirk(topQuirk);
1226 LayoutUnit beforeCollapseLogicalTop = logicalHeight();
1227 LayoutUnit logicalTop = beforeCollapseLogicalTop;
1229 LayoutUnit clearanceForSelfCollapsingBlock;
1230 RenderObject* prev = child->previousSibling();
1231 RenderBlockFlow* previousBlockFlow = prev && prev->isRenderBlockFlow() && !prev->isFloatingOrOutOfFlowPositioned() ? toRenderBlockFlow(prev) : 0;
1232 // 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
1233 // 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
1234 // 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.
1235 if (!marginInfo.canCollapseWithMarginBefore() && previousBlockFlow && previousBlockFlow->isSelfCollapsingBlock()) {
1236 clearanceForSelfCollapsingBlock = previousBlockFlow->marginOffsetForSelfCollapsingBlock();
1237 setLogicalHeight(logicalHeight() - clearanceForSelfCollapsingBlock);
1240 if (childIsSelfCollapsing) {
1241 // 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.
1242 // Also, the child's top position equals the logical height of the container.
1243 if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
1244 // This child has no height. We need to compute our
1245 // position before we collapse the child's margins together,
1246 // so that we can get an accurate position for the zero-height block.
1247 LayoutUnit collapsedBeforePos = std::max(marginInfo.positiveMargin(), childMargins.positiveMarginBefore());
1248 LayoutUnit collapsedBeforeNeg = std::max(marginInfo.negativeMargin(), childMargins.negativeMarginBefore());
1249 marginInfo.setMargin(collapsedBeforePos, collapsedBeforeNeg);
1251 // Now collapse the child's margins together, which means examining our
1252 // bottom margin values as well.
1253 marginInfo.setPositiveMarginIfLarger(childMargins.positiveMarginAfter());
1254 marginInfo.setNegativeMarginIfLarger(childMargins.negativeMarginAfter());
1256 if (!marginInfo.canCollapseWithMarginBefore()) {
1257 // We need to make sure that the position of the self-collapsing block
1258 // is correct, since it could have overflowing content
1259 // that needs to be positioned correctly (e.g., a block that
1260 // had a specified height of 0 but that actually had subcontent).
1261 logicalTop = logicalHeight() + collapsedBeforePos - collapsedBeforeNeg;
1265 if (mustSeparateMarginBeforeForChild(child)) {
1266 ASSERT(!marginInfo.discardMargin() || (marginInfo.discardMargin() && !marginInfo.margin()));
1267 // If we are at the before side of the block and we collapse, ignore the computed margin
1268 // and just add the child margin to the container height. This will correctly position
1269 // the child inside the container.
1270 LayoutUnit separateMargin = !marginInfo.canCollapseWithMarginBefore() ? marginInfo.margin() : LayoutUnit(0);
1271 setLogicalHeight(logicalHeight() + separateMargin + marginBeforeForChild(child));
1272 logicalTop = logicalHeight();
1273 } else if (!marginInfo.discardMargin() && (!marginInfo.atBeforeSideOfBlock()
1274 || (!marginInfo.canCollapseMarginBeforeWithChildren()
1275 && (!document().inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginBeforeQuirk())))) {
1276 // We're collapsing with a previous sibling's margins and not
1277 // with the top of the block.
1278 setLogicalHeight(logicalHeight() + std::max(marginInfo.positiveMargin(), posTop) - std::max(marginInfo.negativeMargin(), negTop));
1279 logicalTop = logicalHeight();
1282 marginInfo.setDiscardMargin(childDiscardMarginAfter);
1284 if (!marginInfo.discardMargin()) {
1285 marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
1286 marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
1288 marginInfo.clearMargin();
1291 if (marginInfo.margin())
1292 marginInfo.setHasMarginAfterQuirk(hasMarginAfterQuirk(child));
1295 // If margins would pull us past the top of the next page, then we need to pull back and pretend like the margins
1296 // collapsed into the page edge.
1297 LayoutState* layoutState = view()->layoutState();
1298 if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTop > beforeCollapseLogicalTop) {
1299 LayoutUnit oldLogicalTop = logicalTop;
1300 logicalTop = std::min(logicalTop, nextPageLogicalTop(beforeCollapseLogicalTop));
1301 setLogicalHeight(logicalHeight() + (logicalTop - oldLogicalTop));
1304 if (previousBlockFlow) {
1305 // 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
1306 // any floats from the parent will now overhang.
1307 LayoutUnit oldLogicalHeight = logicalHeight();
1308 setLogicalHeight(logicalTop);
1309 if (!previousBlockFlow->avoidsFloats() && (previousBlockFlow->logicalTop() + previousBlockFlow->lowestFloatLogicalBottom()) > logicalTop)
1310 addOverhangingFloats(previousBlockFlow, false);
1311 setLogicalHeight(oldLogicalHeight);
1313 // If |child|'s previous sibling is a self-collapsing block that cleared a float and margin collapsing resulted in |child| moving up
1314 // 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
1315 // floats in the parent that overhang |child|'s new logical top.
1316 bool logicalTopIntrudesIntoFloat = clearanceForSelfCollapsingBlock > 0 && logicalTop < beforeCollapseLogicalTop;
1317 if (logicalTopIntrudesIntoFloat && containsFloats() && !child->avoidsFloats() && lowestFloatLogicalBottom() > logicalTop)
1318 child->setNeedsLayoutAndFullPaintInvalidation();
1324 void RenderBlockFlow::adjustPositionedBlock(RenderBox* child, const MarginInfo& marginInfo)
1326 bool isHorizontal = isHorizontalWritingMode();
1327 bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontal);
1329 LayoutUnit logicalTop = logicalHeight();
1330 updateStaticInlinePositionForChild(child, logicalTop);
1332 if (!marginInfo.canCollapseWithMarginBefore()) {
1333 // Positioned blocks don't collapse margins, so add the margin provided by
1334 // the container now. The child's own margin is added later when calculating its logical top.
1335 LayoutUnit collapsedBeforePos = marginInfo.positiveMargin();
1336 LayoutUnit collapsedBeforeNeg = marginInfo.negativeMargin();
1337 logicalTop += collapsedBeforePos - collapsedBeforeNeg;
1340 RenderLayer* childLayer = child->layer();
1341 if (childLayer->staticBlockPosition() != logicalTop) {
1342 childLayer->setStaticBlockPosition(logicalTop);
1343 if (hasStaticBlockPosition)
1344 child->setChildNeedsLayout(MarkOnlyThis);
1348 LayoutUnit RenderBlockFlow::clearFloatsIfNeeded(RenderBox* child, MarginInfo& marginInfo, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos, bool childIsSelfCollapsing)
1350 LayoutUnit heightIncrease = getClearDelta(child, yPos);
1351 if (!heightIncrease)
1354 if (childIsSelfCollapsing) {
1355 bool childDiscardMargin = mustDiscardMarginBeforeForChild(child) || mustDiscardMarginAfterForChild(child);
1357 // For self-collapsing blocks that clear, they can still collapse their
1358 // margins with following siblings. Reset the current margins to represent
1359 // the self-collapsing block's margins only.
1360 // If DISCARD is specified for -webkit-margin-collapse, reset the margin values.
1361 RenderBlockFlow::MarginValues childMargins = marginValuesForChild(child);
1362 if (!childDiscardMargin) {
1363 marginInfo.setPositiveMargin(std::max(childMargins.positiveMarginBefore(), childMargins.positiveMarginAfter()));
1364 marginInfo.setNegativeMargin(std::max(childMargins.negativeMarginBefore(), childMargins.negativeMarginAfter()));
1366 marginInfo.clearMargin();
1368 marginInfo.setDiscardMargin(childDiscardMargin);
1371 // "If the top and bottom margins of an element with clearance are adjoining, its margins collapse with
1372 // the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block."
1373 // So the parent's bottom margin cannot collapse through this block or any subsequent self-collapsing blocks. Set a bit to ensure
1374 // this happens; it will get reset if we encounter an in-flow sibling that is not self-collapsing.
1375 marginInfo.setCanCollapseMarginAfterWithLastChild(false);
1377 // 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
1378 // its own at the correct vertical position. If subsequent siblings attempt to collapse with |child|'s margins in |collapseMargins| we will
1379 // 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
1380 // margins can collapse at the correct vertical position.
1381 // 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
1382 // (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],
1383 // i.e., clearance = [height of float] - margin-top".
1384 setLogicalHeight(child->logicalTop() + childMargins.negativeMarginBefore());
1386 // Increase our height by the amount we had to clear.
1387 setLogicalHeight(logicalHeight() + heightIncrease);
1390 if (marginInfo.canCollapseWithMarginBefore()) {
1391 // We can no longer collapse with the top of the block since a clear
1392 // occurred. The empty blocks collapse into the cleared block.
1393 setMaxMarginBeforeValues(oldTopPosMargin, oldTopNegMargin);
1394 marginInfo.setAtBeforeSideOfBlock(false);
1396 // In case the child discarded the before margin of the block we need to reset the mustDiscardMarginBefore flag to the initial value.
1397 setMustDiscardMarginBefore(style()->marginBeforeCollapse() == MDISCARD);
1400 return yPos + heightIncrease;
1403 void RenderBlockFlow::setCollapsedBottomMargin(const MarginInfo& marginInfo)
1405 if (marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()) {
1406 // 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.
1407 // Don't update the max margin values because we won't need them anyway.
1408 if (marginInfo.discardMargin()) {
1409 setMustDiscardMarginAfter();
1413 // Update our max pos/neg bottom margins, since we collapsed our bottom margins
1414 // with our children.
1415 setMaxMarginAfterValues(std::max(maxPositiveMarginAfter(), marginInfo.positiveMargin()), std::max(maxNegativeMarginAfter(), marginInfo.negativeMargin()));
1417 if (!marginInfo.hasMarginAfterQuirk())
1418 setHasMarginAfterQuirk(false);
1420 if (marginInfo.hasMarginAfterQuirk() && !marginAfter()) {
1421 // We have no bottom margin and our last child has a quirky margin.
1422 // We will pick up this quirky margin and pass it through.
1423 // This deals with the <td><div><p> case.
1424 setHasMarginAfterQuirk(true);
1429 void RenderBlockFlow::marginBeforeEstimateForChild(RenderBox* child, LayoutUnit& positiveMarginBefore, LayoutUnit& negativeMarginBefore, bool& discardMarginBefore) const
1431 // Give up if in quirks mode and we're a body/table cell and the top margin of the child box is quirky.
1432 // Give up if the child specified -webkit-margin-collapse: separate that prevents collapsing.
1433 // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
1434 if ((document().inQuirksMode() && hasMarginBeforeQuirk(child) && (isTableCell() || isBody())) || child->style()->marginBeforeCollapse() == MSEPARATE)
1437 // The margins are discarded by a child that specified -webkit-margin-collapse: discard.
1438 // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
1439 if (child->style()->marginBeforeCollapse() == MDISCARD) {
1440 positiveMarginBefore = 0;
1441 negativeMarginBefore = 0;
1442 discardMarginBefore = true;
1446 LayoutUnit beforeChildMargin = marginBeforeForChild(child);
1447 positiveMarginBefore = std::max(positiveMarginBefore, beforeChildMargin);
1448 negativeMarginBefore = std::max(negativeMarginBefore, -beforeChildMargin);
1450 if (!child->isRenderBlockFlow())
1453 RenderBlockFlow* childBlockFlow = toRenderBlockFlow(child);
1454 if (childBlockFlow->childrenInline() || childBlockFlow->isWritingModeRoot())
1457 MarginInfo childMarginInfo(childBlockFlow, childBlockFlow->borderBefore() + childBlockFlow->paddingBefore(), childBlockFlow->borderAfter() + childBlockFlow->paddingAfter());
1458 if (!childMarginInfo.canCollapseMarginBeforeWithChildren())
1461 RenderBox* grandchildBox = childBlockFlow->firstChildBox();
1462 for ( ; grandchildBox; grandchildBox = grandchildBox->nextSiblingBox()) {
1463 if (!grandchildBox->isFloatingOrOutOfFlowPositioned())
1467 // Give up if there is clearance on the box, since it probably won't collapse into us.
1468 if (!grandchildBox || grandchildBox->style()->clear() != CNONE)
1471 // Make sure to update the block margins now for the grandchild box so that we're looking at current values.
1472 if (grandchildBox->needsLayout()) {
1473 grandchildBox->computeAndSetBlockDirectionMargins(this);
1474 if (grandchildBox->isRenderBlock()) {
1475 RenderBlock* grandchildBlock = toRenderBlock(grandchildBox);
1476 grandchildBlock->setHasMarginBeforeQuirk(grandchildBox->style()->hasMarginBeforeQuirk());
1477 grandchildBlock->setHasMarginAfterQuirk(grandchildBox->style()->hasMarginAfterQuirk());
1481 // Collapse the margin of the grandchild box with our own to produce an estimate.
1482 childBlockFlow->marginBeforeEstimateForChild(grandchildBox, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
1485 LayoutUnit RenderBlockFlow::estimateLogicalTopPosition(RenderBox* child, const MarginInfo& marginInfo, LayoutUnit& estimateWithoutPagination)
1487 // FIXME: We need to eliminate the estimation of vertical position, because when it's wrong we sometimes trigger a pathological
1488 // relayout if there are intruding floats.
1489 LayoutUnit logicalTopEstimate = logicalHeight();
1490 if (!marginInfo.canCollapseWithMarginBefore()) {
1491 LayoutUnit positiveMarginBefore = 0;
1492 LayoutUnit negativeMarginBefore = 0;
1493 bool discardMarginBefore = false;
1494 if (child->selfNeedsLayout()) {
1495 // Try to do a basic estimation of how the collapse is going to go.
1496 marginBeforeEstimateForChild(child, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
1498 // Use the cached collapsed margin values from a previous layout. Most of the time they
1500 RenderBlockFlow::MarginValues marginValues = marginValuesForChild(child);
1501 positiveMarginBefore = std::max(positiveMarginBefore, marginValues.positiveMarginBefore());
1502 negativeMarginBefore = std::max(negativeMarginBefore, marginValues.negativeMarginBefore());
1503 discardMarginBefore = mustDiscardMarginBeforeForChild(child);
1506 // Collapse the result with our current margins.
1507 if (!discardMarginBefore)
1508 logicalTopEstimate += std::max(marginInfo.positiveMargin(), positiveMarginBefore) - std::max(marginInfo.negativeMargin(), negativeMarginBefore);
1511 // Adjust logicalTopEstimate down to the next page if the margins are so large that we don't fit on the current
1513 LayoutState* layoutState = view()->layoutState();
1514 if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTopEstimate > logicalHeight())
1515 logicalTopEstimate = std::min(logicalTopEstimate, nextPageLogicalTop(logicalHeight()));
1517 logicalTopEstimate += getClearDelta(child, logicalTopEstimate);
1519 estimateWithoutPagination = logicalTopEstimate;
1521 if (layoutState->isPaginated()) {
1522 // If the object has a page or column break value of "before", then we should shift to the top of the next page.
1523 logicalTopEstimate = applyBeforeBreak(child, logicalTopEstimate);
1525 // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
1526 logicalTopEstimate = adjustForUnsplittableChild(child, logicalTopEstimate);
1528 if (!child->selfNeedsLayout() && child->isRenderBlockFlow())
1529 logicalTopEstimate += toRenderBlockFlow(child)->paginationStrut();
1532 return logicalTopEstimate;
1535 LayoutUnit RenderBlockFlow::marginOffsetForSelfCollapsingBlock()
1537 ASSERT(isSelfCollapsingBlock());
1538 RenderBlockFlow* parentBlock = toRenderBlockFlow(parent());
1539 if (parentBlock && style()->clear() && parentBlock->getClearDelta(this, logicalHeight()))
1540 return marginValuesForChild(this).positiveMarginBefore();
1541 return LayoutUnit();
1544 void RenderBlockFlow::adjustFloatingBlock(const MarginInfo& marginInfo)
1546 // The float should be positioned taking into account the bottom margin
1547 // of the previous flow. We add that margin into the height, get the
1548 // float positioned properly, and then subtract the margin out of the
1549 // height again. In the case of self-collapsing blocks, we always just
1550 // use the top margins, since the self-collapsing block collapsed its
1551 // own bottom margin into its top margin.
1553 // Note also that the previous flow may collapse its margin into the top of
1554 // our block. If this is the case, then we do not add the margin in to our
1555 // height when computing the position of the float. This condition can be tested
1556 // for by simply calling canCollapseWithMarginBefore. See
1557 // http://www.hixie.ch/tests/adhoc/css/box/block/margin-collapse/046.html for
1558 // an example of this scenario.
1559 LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
1560 setLogicalHeight(logicalHeight() + marginOffset);
1561 positionNewFloats();
1562 setLogicalHeight(logicalHeight() - marginOffset);
1565 void RenderBlockFlow::handleAfterSideOfBlock(RenderBox* lastChild, LayoutUnit beforeSide, LayoutUnit afterSide, MarginInfo& marginInfo)
1567 marginInfo.setAtAfterSideOfBlock(true);
1569 // If our last child was a self-collapsing block with clearance then our logical height is flush with the
1570 // bottom edge of the float that the child clears. The correct vertical position for the margin-collapsing we want
1571 // to perform now is at the child's margin-top - so adjust our height to that position.
1572 if (lastChild && lastChild->isRenderBlockFlow() && lastChild->isSelfCollapsingBlock())
1573 setLogicalHeight(logicalHeight() - toRenderBlockFlow(lastChild)->marginOffsetForSelfCollapsingBlock());
1575 if (marginInfo.canCollapseMarginAfterWithChildren() && !marginInfo.canCollapseMarginAfterWithLastChild())
1576 marginInfo.setCanCollapseMarginAfterWithChildren(false);
1578 // If we can't collapse with children then go ahead and add in the bottom margin.
1579 if (!marginInfo.discardMargin() && (!marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()
1580 && (!document().inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginAfterQuirk())))
1581 setLogicalHeight(logicalHeight() + marginInfo.margin());
1583 // Now add in our bottom border/padding.
1584 setLogicalHeight(logicalHeight() + afterSide);
1586 // Negative margins can cause our height to shrink below our minimal height (border/padding).
1587 // If this happens, ensure that the computed height is increased to the minimal height.
1588 setLogicalHeight(std::max(logicalHeight(), beforeSide + afterSide));
1590 // Update our bottom collapsed margin info.
1591 setCollapsedBottomMargin(marginInfo);
1594 void RenderBlockFlow::setMustDiscardMarginBefore(bool value)
1596 if (style()->marginBeforeCollapse() == MDISCARD) {
1601 if (!m_rareData && !value)
1605 m_rareData = adoptPtrWillBeNoop(new RenderBlockFlowRareData(this));
1607 m_rareData->m_discardMarginBefore = value;
1610 void RenderBlockFlow::setMustDiscardMarginAfter(bool value)
1612 if (style()->marginAfterCollapse() == MDISCARD) {
1617 if (!m_rareData && !value)
1621 m_rareData = adoptPtrWillBeNoop(new RenderBlockFlowRareData(this));
1623 m_rareData->m_discardMarginAfter = value;
1626 bool RenderBlockFlow::mustDiscardMarginBefore() const
1628 return style()->marginBeforeCollapse() == MDISCARD || (m_rareData && m_rareData->m_discardMarginBefore);
1631 bool RenderBlockFlow::mustDiscardMarginAfter() const
1633 return style()->marginAfterCollapse() == MDISCARD || (m_rareData && m_rareData->m_discardMarginAfter);
1636 bool RenderBlockFlow::mustDiscardMarginBeforeForChild(const RenderBox* child) const
1638 ASSERT(!child->selfNeedsLayout());
1639 if (!child->isWritingModeRoot())
1640 return child->isRenderBlockFlow() ? toRenderBlockFlow(child)->mustDiscardMarginBefore() : (child->style()->marginBeforeCollapse() == MDISCARD);
1641 if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
1642 return child->isRenderBlockFlow() ? toRenderBlockFlow(child)->mustDiscardMarginAfter() : (child->style()->marginAfterCollapse() == MDISCARD);
1644 // FIXME: We return false here because the implementation is not geometrically complete. We have values only for before/after, not start/end.
1645 // In case the boxes are perpendicular we assume the property is not specified.
1649 bool RenderBlockFlow::mustDiscardMarginAfterForChild(const RenderBox* child) const
1651 ASSERT(!child->selfNeedsLayout());
1652 if (!child->isWritingModeRoot())
1653 return child->isRenderBlockFlow() ? toRenderBlockFlow(child)->mustDiscardMarginAfter() : (child->style()->marginAfterCollapse() == MDISCARD);
1654 if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
1655 return child->isRenderBlockFlow() ? toRenderBlockFlow(child)->mustDiscardMarginBefore() : (child->style()->marginBeforeCollapse() == MDISCARD);
1657 // FIXME: See |mustDiscardMarginBeforeForChild| above.
1661 void RenderBlockFlow::setMaxMarginBeforeValues(LayoutUnit pos, LayoutUnit neg)
1664 if (pos == RenderBlockFlowRareData::positiveMarginBeforeDefault(this) && neg == RenderBlockFlowRareData::negativeMarginBeforeDefault(this))
1666 m_rareData = adoptPtrWillBeNoop(new RenderBlockFlowRareData(this));
1668 m_rareData->m_margins.setPositiveMarginBefore(pos);
1669 m_rareData->m_margins.setNegativeMarginBefore(neg);
1672 void RenderBlockFlow::setMaxMarginAfterValues(LayoutUnit pos, LayoutUnit neg)
1675 if (pos == RenderBlockFlowRareData::positiveMarginAfterDefault(this) && neg == RenderBlockFlowRareData::negativeMarginAfterDefault(this))
1677 m_rareData = adoptPtrWillBeNoop(new RenderBlockFlowRareData(this));
1679 m_rareData->m_margins.setPositiveMarginAfter(pos);
1680 m_rareData->m_margins.setNegativeMarginAfter(neg);
1683 bool RenderBlockFlow::mustSeparateMarginBeforeForChild(const RenderBox* child) const
1685 ASSERT(!child->selfNeedsLayout());
1686 const RenderStyle* childStyle = child->style();
1687 if (!child->isWritingModeRoot())
1688 return childStyle->marginBeforeCollapse() == MSEPARATE;
1689 if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
1690 return childStyle->marginAfterCollapse() == MSEPARATE;
1692 // FIXME: See |mustDiscardMarginBeforeForChild| above.
1696 bool RenderBlockFlow::mustSeparateMarginAfterForChild(const RenderBox* child) const
1698 ASSERT(!child->selfNeedsLayout());
1699 const RenderStyle* childStyle = child->style();
1700 if (!child->isWritingModeRoot())
1701 return childStyle->marginAfterCollapse() == MSEPARATE;
1702 if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
1703 return childStyle->marginBeforeCollapse() == MSEPARATE;
1705 // FIXME: See |mustDiscardMarginBeforeForChild| above.
1709 LayoutUnit RenderBlockFlow::applyBeforeBreak(RenderBox* child, LayoutUnit logicalOffset)
1711 // FIXME: Add page break checking here when we support printing.
1712 RenderFlowThread* flowThread = flowThreadContainingBlock();
1713 bool isInsideMulticolFlowThread = flowThread;
1714 bool checkColumnBreaks = isInsideMulticolFlowThread || view()->layoutState()->isPaginatingColumns();
1715 bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->pageLogicalHeight(); // FIXME: Once columns can print we have to check this.
1716 bool checkBeforeAlways = (checkColumnBreaks && child->style()->columnBreakBefore() == PBALWAYS)
1717 || (checkPageBreaks && child->style()->pageBreakBefore() == PBALWAYS);
1718 if (checkBeforeAlways && inNormalFlow(child)) {
1719 if (checkColumnBreaks) {
1720 if (isInsideMulticolFlowThread) {
1721 LayoutUnit offsetBreakAdjustment = 0;
1722 if (flowThread->addForcedRegionBreak(offsetFromLogicalTopOfFirstPage() + logicalOffset, child, true, &offsetBreakAdjustment))
1723 return logicalOffset + offsetBreakAdjustment;
1725 view()->layoutState()->addForcedColumnBreak(*child, logicalOffset);
1728 return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
1730 return logicalOffset;
1733 LayoutUnit RenderBlockFlow::applyAfterBreak(RenderBox* child, LayoutUnit logicalOffset, MarginInfo& marginInfo)
1735 // FIXME: Add page break checking here when we support printing.
1736 RenderFlowThread* flowThread = flowThreadContainingBlock();
1737 bool isInsideMulticolFlowThread = flowThread;
1738 bool checkColumnBreaks = isInsideMulticolFlowThread || view()->layoutState()->isPaginatingColumns();
1739 bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->pageLogicalHeight(); // FIXME: Once columns can print we have to check this.
1740 bool checkAfterAlways = (checkColumnBreaks && child->style()->columnBreakAfter() == PBALWAYS)
1741 || (checkPageBreaks && child->style()->pageBreakAfter() == PBALWAYS);
1742 if (checkAfterAlways && inNormalFlow(child)) {
1743 LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
1745 // So our margin doesn't participate in the next collapsing steps.
1746 marginInfo.clearMargin();
1748 if (checkColumnBreaks) {
1749 if (isInsideMulticolFlowThread) {
1750 LayoutUnit offsetBreakAdjustment = 0;
1751 if (flowThread->addForcedRegionBreak(offsetFromLogicalTopOfFirstPage() + logicalOffset + marginOffset, child, false, &offsetBreakAdjustment))
1752 return logicalOffset + marginOffset + offsetBreakAdjustment;
1754 view()->layoutState()->addForcedColumnBreak(*child, logicalOffset);
1757 return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
1759 return logicalOffset;
1762 void RenderBlockFlow::addOverflowFromFloats()
1764 if (!m_floatingObjects)
1767 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1768 FloatingObjectSetIterator end = floatingObjectSet.end();
1769 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1770 FloatingObject* floatingObject = it->get();
1771 if (floatingObject->isDescendant())
1772 addOverflowFromChild(floatingObject->renderer(), IntSize(xPositionForFloatIncludingMargin(floatingObject), yPositionForFloatIncludingMargin(floatingObject)));
1776 void RenderBlockFlow::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
1778 RenderBlock::computeOverflow(oldClientAfterEdge, recomputeFloats);
1779 if (!hasColumns() && (recomputeFloats || createsBlockFormattingContext() || hasSelfPaintingLayer()))
1780 addOverflowFromFloats();
1783 RootInlineBox* RenderBlockFlow::createAndAppendRootInlineBox()
1785 RootInlineBox* rootBox = createRootInlineBox();
1786 m_lineBoxes.appendLineBox(rootBox);
1791 void RenderBlockFlow::deleteLineBoxTree()
1793 if (containsFloats())
1794 m_floatingObjects->clearLineBoxTreePointers();
1796 m_lineBoxes.deleteLineBoxTree();
1799 void RenderBlockFlow::markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove, bool inLayout)
1801 if (!everHadLayout() && !containsFloats())
1804 if (m_descendantsWithFloatsMarkedForLayout && !floatToRemove)
1806 m_descendantsWithFloatsMarkedForLayout |= !floatToRemove;
1808 MarkingBehavior markParents = inLayout ? MarkOnlyThis : MarkContainingBlockChain;
1809 setChildNeedsLayout(markParents);
1812 removeFloatingObject(floatToRemove);
1814 // Iterate over our children and mark them as needed.
1815 if (!childrenInline()) {
1816 for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
1817 if ((!floatToRemove && child->isFloatingOrOutOfFlowPositioned()) || !child->isRenderBlock())
1819 if (!child->isRenderBlockFlow()) {
1820 RenderBlock* childBlock = toRenderBlock(child);
1821 if (childBlock->shrinkToAvoidFloats() && childBlock->everHadLayout())
1822 childBlock->setChildNeedsLayout(markParents);
1825 RenderBlockFlow* childBlockFlow = toRenderBlockFlow(child);
1826 if ((floatToRemove ? childBlockFlow->containsFloat(floatToRemove) : childBlockFlow->containsFloats()) || childBlockFlow->shrinkToAvoidFloats())
1827 childBlockFlow->markAllDescendantsWithFloatsForLayout(floatToRemove, inLayout);
1832 void RenderBlockFlow::markSiblingsWithFloatsForLayout(RenderBox* floatToRemove)
1834 if (!m_floatingObjects)
1837 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1838 FloatingObjectSetIterator end = floatingObjectSet.end();
1840 for (RenderObject* next = nextSibling(); next; next = next->nextSibling()) {
1841 if (!next->isRenderBlockFlow() || next->isFloatingOrOutOfFlowPositioned() || toRenderBlockFlow(next)->avoidsFloats())
1844 RenderBlockFlow* nextBlock = toRenderBlockFlow(next);
1845 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1846 RenderBox* floatingBox = (*it)->renderer();
1847 if (floatToRemove && floatingBox != floatToRemove)
1849 if (nextBlock->containsFloat(floatingBox))
1850 nextBlock->markAllDescendantsWithFloatsForLayout(floatingBox);
1855 LayoutUnit RenderBlockFlow::getClearDelta(RenderBox* child, LayoutUnit logicalTop)
1857 // There is no need to compute clearance if we have no floats.
1858 if (!containsFloats())
1861 // At least one float is present. We need to perform the clearance computation.
1862 bool clearSet = child->style()->clear() != CNONE;
1863 LayoutUnit logicalBottom = 0;
1864 switch (child->style()->clear()) {
1868 logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
1871 logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatRight);
1874 logicalBottom = lowestFloatLogicalBottom();
1878 // 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).
1879 LayoutUnit result = clearSet ? std::max<LayoutUnit>(0, logicalBottom - logicalTop) : LayoutUnit();
1880 if (!result && child->avoidsFloats()) {
1881 LayoutUnit newLogicalTop = logicalTop;
1883 LayoutUnit availableLogicalWidthAtNewLogicalTopOffset = availableLogicalWidthForLine(newLogicalTop, false, logicalHeightForChild(child));
1884 if (availableLogicalWidthAtNewLogicalTopOffset == availableLogicalWidthForContent())
1885 return newLogicalTop - logicalTop;
1887 LayoutRect borderBox = child->borderBoxRect();
1888 LayoutUnit childLogicalWidthAtOldLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
1890 borderBox = child->borderBoxAfterUpdatingLogicalWidth(newLogicalTop);
1891 LayoutUnit childLogicalWidthAtNewLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
1893 if (childLogicalWidthAtNewLogicalTopOffset <= availableLogicalWidthAtNewLogicalTopOffset) {
1894 // Even though we may not be moving, if the logical width did shrink because of the presence of new floats, then
1895 // we need to force a relayout as though we shifted. This happens because of the dynamic addition of overhanging floats
1896 // from previous siblings when negative margins exist on a child (see the addOverhangingFloats call at the end of collapseMargins).
1897 if (childLogicalWidthAtOldLogicalTopOffset != childLogicalWidthAtNewLogicalTopOffset)
1898 child->setChildNeedsLayout(MarkOnlyThis);
1899 return newLogicalTop - logicalTop;
1902 newLogicalTop = nextFloatLogicalBottomBelow(newLogicalTop);
1903 ASSERT(newLogicalTop >= logicalTop);
1904 if (newLogicalTop < logicalTop)
1907 ASSERT_NOT_REACHED();
1912 void RenderBlockFlow::createFloatingObjects()
1914 m_floatingObjects = adoptPtr(new FloatingObjects(this, isHorizontalWritingMode()));
1917 void RenderBlockFlow::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
1919 RenderStyle* oldStyle = style();
1920 s_canPropagateFloatIntoSibling = oldStyle ? !isFloatingOrOutOfFlowPositioned() && !avoidsFloats() : false;
1921 if (oldStyle && parent() && diff.needsFullLayout() && oldStyle->position() != newStyle.position()
1922 && containsFloats() && !isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition())
1923 markAllDescendantsWithFloatsForLayout();
1925 RenderBlock::styleWillChange(diff, newStyle);
1928 void RenderBlockFlow::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
1930 RenderBlock::styleDidChange(diff, oldStyle);
1932 // After our style changed, if we lose our ability to propagate floats into next sibling
1933 // blocks, then we need to find the top most parent containing that overhanging float and
1934 // then mark its descendants with floats for layout and clear all floats from its next
1935 // sibling blocks that exist in our floating objects list. See bug 56299 and 62875.
1936 bool canPropagateFloatIntoSibling = !isFloatingOrOutOfFlowPositioned() && !avoidsFloats();
1937 if (diff.needsFullLayout() && s_canPropagateFloatIntoSibling && !canPropagateFloatIntoSibling && hasOverhangingFloats()) {
1938 RenderBlockFlow* parentBlockFlow = this;
1939 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1940 FloatingObjectSetIterator end = floatingObjectSet.end();
1942 for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
1943 if (curr->isRenderBlockFlow()) {
1944 RenderBlockFlow* currBlock = toRenderBlockFlow(curr);
1946 if (currBlock->hasOverhangingFloats()) {
1947 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1948 RenderBox* renderer = (*it)->renderer();
1949 if (currBlock->hasOverhangingFloat(renderer)) {
1950 parentBlockFlow = currBlock;
1958 parentBlockFlow->markAllDescendantsWithFloatsForLayout();
1959 parentBlockFlow->markSiblingsWithFloatsForLayout();
1962 if (diff.needsFullLayout() || !oldStyle)
1963 createOrDestroyMultiColumnFlowThreadIfNeeded(oldStyle);
1966 void RenderBlockFlow::updateStaticInlinePositionForChild(RenderBox* child, LayoutUnit logicalTop)
1968 if (child->style()->isOriginalDisplayInlineType())
1969 setStaticInlinePositionForChild(child, startAlignedOffsetForLine(logicalTop, false));
1971 setStaticInlinePositionForChild(child, startOffsetForContent());
1974 void RenderBlockFlow::setStaticInlinePositionForChild(RenderBox* child, LayoutUnit inlinePosition)
1976 child->layer()->setStaticInlinePosition(inlinePosition);
1979 void RenderBlockFlow::addChild(RenderObject* newChild, RenderObject* beforeChild)
1981 if (RenderMultiColumnFlowThread* flowThread = multiColumnFlowThread()) {
1982 if (beforeChild == flowThread)
1983 beforeChild = flowThread->firstChild();
1984 ASSERT(!beforeChild || beforeChild->isDescendantOf(flowThread));
1985 flowThread->addChild(newChild, beforeChild);
1988 RenderBlock::addChild(newChild, beforeChild);
1991 void RenderBlockFlow::moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert)
1993 RenderBlockFlow* toBlockFlow = toRenderBlockFlow(toBlock);
1994 moveAllChildrenTo(toBlockFlow, fullRemoveInsert);
1996 // When a portion of the render tree is being detached, anonymous blocks
1997 // will be combined as their children are deleted. In this process, the
1998 // anonymous block later in the tree is merged into the one preceeding it.
1999 // It can happen that the later block (this) contains floats that the
2000 // previous block (toBlockFlow) did not contain, and thus are not in the
2001 // floating objects list for toBlockFlow. This can result in toBlockFlow containing
2002 // floats that are not in it's floating objects list, but are in the
2003 // floating objects lists of siblings and parents. This can cause problems
2004 // when the float itself is deleted, since the deletion code assumes that
2005 // if a float is not in it's containing block's floating objects list, it
2006 // isn't in any floating objects list. In order to preserve this condition
2007 // (removing it has serious performance implications), we need to copy the
2008 // floating objects from the old block (this) to the new block (toBlockFlow).
2009 // The float's metrics will likely all be wrong, but since toBlockFlow is
2010 // already marked for layout, this will get fixed before anything gets
2012 // See bug https://code.google.com/p/chromium/issues/detail?id=230907
2013 if (m_floatingObjects) {
2014 if (!toBlockFlow->m_floatingObjects)
2015 toBlockFlow->createFloatingObjects();
2017 const FloatingObjectSet& fromFloatingObjectSet = m_floatingObjects->set();
2018 FloatingObjectSetIterator end = fromFloatingObjectSet.end();
2020 for (FloatingObjectSetIterator it = fromFloatingObjectSet.begin(); it != end; ++it) {
2021 FloatingObject* floatingObject = it->get();
2023 // Don't insert the object again if it's already in the list
2024 if (toBlockFlow->containsFloat(floatingObject->renderer()))
2027 toBlockFlow->m_floatingObjects->add(floatingObject->unsafeClone());
2033 void RenderBlockFlow::invalidatePaintForOverhangingFloats(bool paintAllDescendants)
2035 // Invalidate paint of any overhanging floats (if we know we're the one to paint them).
2036 // Otherwise, bail out.
2037 if (!hasOverhangingFloats())
2040 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2041 FloatingObjectSetIterator end = floatingObjectSet.end();
2042 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2043 FloatingObject* floatingObject = it->get();
2044 // Only issue paint invaldiations for the object if it is overhanging, is not in its own layer, and
2045 // is our responsibility to paint (m_shouldPaint is set). When paintAllDescendants is true, the latter
2046 // condition is replaced with being a descendant of us.
2047 if (logicalBottomForFloat(floatingObject) > logicalHeight()
2048 && !floatingObject->renderer()->hasSelfPaintingLayer()
2049 && (floatingObject->shouldPaint() || (paintAllDescendants && floatingObject->renderer()->isDescendantOf(this)))) {
2051 RenderBox* floatingRenderer = floatingObject->renderer();
2052 floatingRenderer->setShouldDoFullPaintInvalidation();
2053 floatingRenderer->invalidatePaintForOverhangingFloats(false);
2058 void RenderBlockFlow::invalidatePaintForOverflow()
2060 // FIXME: We could tighten up the left and right invalidation points if we let layoutInlineChildren fill them in based off the particular lines
2061 // it had to lay out. We wouldn't need the hasOverflowClip() hack in that case either.
2062 LayoutUnit paintInvalidationLogicalLeft = logicalLeftVisualOverflow();
2063 LayoutUnit paintInvalidationLogicalRight = logicalRightVisualOverflow();
2064 if (hasOverflowClip()) {
2065 // 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.
2066 // 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.
2067 // layoutInlineChildren should be patched to compute the entire paint invalidation rect.
2068 paintInvalidationLogicalLeft = std::min(paintInvalidationLogicalLeft, logicalLeftLayoutOverflow());
2069 paintInvalidationLogicalRight = std::max(paintInvalidationLogicalRight, logicalRightLayoutOverflow());
2072 LayoutRect paintInvalidationRect;
2073 if (isHorizontalWritingMode())
2074 paintInvalidationRect = LayoutRect(paintInvalidationLogicalLeft, m_paintInvalidationLogicalTop, paintInvalidationLogicalRight - paintInvalidationLogicalLeft, m_paintInvalidationLogicalBottom - m_paintInvalidationLogicalTop);
2076 paintInvalidationRect = LayoutRect(m_paintInvalidationLogicalTop, paintInvalidationLogicalLeft, m_paintInvalidationLogicalBottom - m_paintInvalidationLogicalTop, paintInvalidationLogicalRight - paintInvalidationLogicalLeft);
2078 // The paint invalidation rect may be split across columns, in which case adjustRectForColumns() will return the union.
2079 adjustRectForColumns(paintInvalidationRect);
2081 if (hasOverflowClip()) {
2082 // Adjust the paint invalidation rect for scroll offset
2083 paintInvalidationRect.move(-scrolledContentOffset());
2085 // Don't allow this rect to spill out of our overflow box.
2086 paintInvalidationRect.intersect(LayoutRect(LayoutPoint(), size()));
2089 // Make sure the rect is still non-empty after intersecting for overflow above
2090 if (!paintInvalidationRect.isEmpty()) {
2091 // Hits in media/event-attributes.html
2092 DisableCompositingQueryAsserts disabler;
2094 invalidatePaintRectangle(paintInvalidationRect); // We need to do a partial paint invalidation of our content.
2095 if (hasReflection())
2096 invalidatePaintRectangle(reflectedRect(paintInvalidationRect));
2099 m_paintInvalidationLogicalTop = 0;
2100 m_paintInvalidationLogicalBottom = 0;
2103 void RenderBlockFlow::paintFloats(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool preservePhase)
2105 BlockFlowPainter(*this).paintFloats(paintInfo, paintOffset, preservePhase);
2108 void RenderBlockFlow::clipOutFloatingObjects(const RenderBlock* rootBlock, const PaintInfo* paintInfo, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock) const
2110 if (m_floatingObjects) {
2111 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2112 FloatingObjectSetIterator end = floatingObjectSet.end();
2113 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2114 FloatingObject* floatingObject = it->get();
2115 LayoutRect floatBox(offsetFromRootBlock.width() + xPositionForFloatIncludingMargin(floatingObject),
2116 offsetFromRootBlock.height() + yPositionForFloatIncludingMargin(floatingObject),
2117 floatingObject->renderer()->width(), floatingObject->renderer()->height());
2118 rootBlock->flipForWritingMode(floatBox);
2119 floatBox.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
2120 paintInfo->context->clipOut(pixelSnappedIntRect(floatBox));
2125 void RenderBlockFlow::clearFloats(EClear clear)
2127 positionNewFloats();
2129 LayoutUnit newY = 0;
2132 newY = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
2135 newY = lowestFloatLogicalBottom(FloatingObject::FloatRight);
2138 newY = lowestFloatLogicalBottom();
2142 if (height() < newY)
2143 setLogicalHeight(newY);
2146 bool RenderBlockFlow::containsFloat(RenderBox* renderer) const
2148 return m_floatingObjects && m_floatingObjects->set().contains<FloatingObjectHashTranslator>(renderer);
2151 void RenderBlockFlow::removeFloatingObjects()
2153 if (!m_floatingObjects)
2156 markSiblingsWithFloatsForLayout();
2158 m_floatingObjects->clear();
2161 LayoutPoint RenderBlockFlow::flipFloatForWritingModeForChild(const FloatingObject* child, const LayoutPoint& point) const
2163 if (!style()->slowIsFlippedBlocksWritingMode())
2166 // This is similar to RenderBox::flipForWritingModeForChild. We have to subtract out our left/top offsets twice, since
2167 // it's going to get added back in. We hide this complication here so that the calling code looks normal for the unflipped
2169 if (isHorizontalWritingMode())
2170 return LayoutPoint(point.x(), point.y() + height() - child->renderer()->height() - 2 * yPositionForFloatIncludingMargin(child));
2171 return LayoutPoint(point.x() + width() - child->renderer()->width() - 2 * xPositionForFloatIncludingMargin(child), point.y());
2174 LayoutUnit RenderBlockFlow::logicalLeftOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
2176 LayoutUnit offset = fixedOffset;
2177 if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
2178 offset = m_floatingObjects->logicalLeftOffsetForPositioningFloat(fixedOffset, logicalTop, heightRemaining);
2179 return adjustLogicalLeftOffsetForLine(offset, applyTextIndent);
2182 LayoutUnit RenderBlockFlow::logicalRightOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
2184 LayoutUnit offset = fixedOffset;
2185 if (m_floatingObjects && m_floatingObjects->hasRightObjects())
2186 offset = m_floatingObjects->logicalRightOffsetForPositioningFloat(fixedOffset, logicalTop, heightRemaining);
2187 return adjustLogicalRightOffsetForLine(offset, applyTextIndent);
2190 LayoutUnit RenderBlockFlow::adjustLogicalLeftOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
2192 LayoutUnit left = offsetFromFloats;
2194 if (applyTextIndent && style()->isLeftToRightDirection())
2195 left += textIndentOffset();
2200 LayoutUnit RenderBlockFlow::adjustLogicalRightOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
2202 LayoutUnit right = offsetFromFloats;
2204 if (applyTextIndent && !style()->isLeftToRightDirection())
2205 right -= textIndentOffset();
2210 LayoutPoint RenderBlockFlow::computeLogicalLocationForFloat(const FloatingObject* floatingObject, LayoutUnit logicalTopOffset) const
2212 RenderBox* childBox = floatingObject->renderer();
2213 LayoutUnit logicalLeftOffset = logicalLeftOffsetForContent(); // Constant part of left offset.
2214 LayoutUnit logicalRightOffset; // Constant part of right offset.
2215 logicalRightOffset = logicalRightOffsetForContent();
2217 LayoutUnit floatLogicalWidth = std::min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset); // The width we look for.
2219 LayoutUnit floatLogicalLeft;
2221 bool insideFlowThread = flowThreadContainingBlock();
2223 if (childBox->style()->floating() == LeftFloat) {
2224 LayoutUnit heightRemainingLeft = 1;
2225 LayoutUnit heightRemainingRight = 1;
2226 floatLogicalLeft = logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
2227 while (logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight) - floatLogicalLeft < floatLogicalWidth) {
2228 logicalTopOffset += std::min(heightRemainingLeft, heightRemainingRight);
2229 floatLogicalLeft = logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
2230 if (insideFlowThread) {
2231 // Have to re-evaluate all of our offsets, since they may have changed.
2232 logicalRightOffset = logicalRightOffsetForContent(); // Constant part of right offset.
2233 logicalLeftOffset = logicalLeftOffsetForContent(); // Constant part of left offset.
2234 floatLogicalWidth = std::min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
2237 floatLogicalLeft = std::max(logicalLeftOffset - borderAndPaddingLogicalLeft(), floatLogicalLeft);
2239 LayoutUnit heightRemainingLeft = 1;
2240 LayoutUnit heightRemainingRight = 1;
2241 floatLogicalLeft = logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
2242 while (floatLogicalLeft - logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft) < floatLogicalWidth) {
2243 logicalTopOffset += std::min(heightRemainingLeft, heightRemainingRight);
2244 floatLogicalLeft = logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
2245 if (insideFlowThread) {
2246 // Have to re-evaluate all of our offsets, since they may have changed.
2247 logicalRightOffset = logicalRightOffsetForContent(); // Constant part of right offset.
2248 logicalLeftOffset = logicalLeftOffsetForContent(); // Constant part of left offset.
2249 floatLogicalWidth = std::min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
2252 // Use the original width of the float here, since the local variable
2253 // |floatLogicalWidth| was capped to the available line width. See
2254 // fast/block/float/clamped-right-float.html.
2255 floatLogicalLeft -= logicalWidthForFloat(floatingObject);
2258 return LayoutPoint(floatLogicalLeft, logicalTopOffset);
2261 FloatingObject* RenderBlockFlow::insertFloatingObject(RenderBox* floatBox)
2263 ASSERT(floatBox->isFloating());
2265 // Create the list of special objects if we don't aleady have one
2266 if (!m_floatingObjects) {
2267 createFloatingObjects();
2269 // Don't insert the object again if it's already in the list
2270 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2271 FloatingObjectSetIterator it = floatingObjectSet.find<FloatingObjectHashTranslator>(floatBox);
2272 if (it != floatingObjectSet.end())
2276 // Create the special object entry & append it to the list
2278 OwnPtr<FloatingObject> newObj = FloatingObject::create(floatBox);
2280 // Our location is irrelevant if we're unsplittable or no pagination is in effect.
2281 // Just go ahead and lay out the float.
2282 bool isChildRenderBlock = floatBox->isRenderBlock();
2283 if (isChildRenderBlock && !floatBox->needsLayout() && view()->layoutState()->pageLogicalHeightChanged())
2284 floatBox->setChildNeedsLayout(MarkOnlyThis);
2286 bool needsBlockDirectionLocationSetBeforeLayout = isChildRenderBlock && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout();
2287 if (!needsBlockDirectionLocationSetBeforeLayout || isWritingModeRoot()) { // We are unsplittable if we're a block flow root.
2288 floatBox->layoutIfNeeded();
2290 floatBox->updateLogicalWidth();
2291 floatBox->computeAndSetBlockDirectionMargins(this);
2294 setLogicalWidthForFloat(newObj.get(), logicalWidthForChild(floatBox) + marginStartForChild(floatBox) + marginEndForChild(floatBox));
2296 return m_floatingObjects->add(newObj.release());
2299 void RenderBlockFlow::removeFloatingObject(RenderBox* floatBox)
2301 if (m_floatingObjects) {
2302 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2303 FloatingObjectSetIterator it = floatingObjectSet.find<FloatingObjectHashTranslator>(floatBox);
2304 if (it != floatingObjectSet.end()) {
2305 FloatingObject* floatingObject = it->get();
2306 if (childrenInline()) {
2307 LayoutUnit logicalTop = logicalTopForFloat(floatingObject);
2308 LayoutUnit logicalBottom = logicalBottomForFloat(floatingObject);
2310 // Fix for https://bugs.webkit.org/show_bug.cgi?id=54995.
2311 if (logicalBottom < 0 || logicalBottom < logicalTop || logicalTop == LayoutUnit::max()) {
2312 logicalBottom = LayoutUnit::max();
2314 // Special-case zero- and less-than-zero-height floats: those don't touch
2315 // the line that they're on, but it still needs to be dirtied. This is
2316 // accomplished by pretending they have a height of 1.
2317 logicalBottom = std::max(logicalBottom, logicalTop + 1);
2319 if (floatingObject->originatingLine()) {
2320 if (!selfNeedsLayout()) {
2321 ASSERT(floatingObject->originatingLine()->renderer() == this);
2322 floatingObject->originatingLine()->markDirty();
2325 floatingObject->setOriginatingLine(0);
2328 markLinesDirtyInBlockRange(0, logicalBottom);
2330 m_floatingObjects->remove(floatingObject);
2335 void RenderBlockFlow::removeFloatingObjectsBelow(FloatingObject* lastFloat, int logicalOffset)
2337 if (!containsFloats())
2340 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2341 FloatingObject* curr = floatingObjectSet.last().get();
2342 while (curr != lastFloat && (!curr->isPlaced() || logicalTopForFloat(curr) >= logicalOffset)) {
2343 m_floatingObjects->remove(curr);
2344 if (floatingObjectSet.isEmpty())
2346 curr = floatingObjectSet.last().get();
2350 bool RenderBlockFlow::positionNewFloats()
2352 if (!m_floatingObjects)
2355 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2356 if (floatingObjectSet.isEmpty())
2359 // If all floats have already been positioned, then we have no work to do.
2360 if (floatingObjectSet.last()->isPlaced())
2363 // Move backwards through our floating object list until we find a float that has
2364 // already been positioned. Then we'll be able to move forward, positioning all of
2365 // the new floats that need it.
2366 FloatingObjectSetIterator it = floatingObjectSet.end();
2367 --it; // Go to last item.
2368 FloatingObjectSetIterator begin = floatingObjectSet.begin();
2369 FloatingObject* lastPlacedFloatingObject = 0;
2370 while (it != begin) {
2372 if ((*it)->isPlaced()) {
2373 lastPlacedFloatingObject = it->get();
2379 LayoutUnit logicalTop = logicalHeight();
2381 // The float cannot start above the top position of the last positioned float.
2382 if (lastPlacedFloatingObject)
2383 logicalTop = std::max(logicalTopForFloat(lastPlacedFloatingObject), logicalTop);
2385 FloatingObjectSetIterator end = floatingObjectSet.end();
2386 // Now walk through the set of unpositioned floats and place them.
2387 for (; it != end; ++it) {
2388 FloatingObject* floatingObject = it->get();
2389 // The containing block is responsible for positioning floats, so if we have floats in our
2390 // list that come from somewhere else, do not attempt to position them.
2391 if (floatingObject->renderer()->containingBlock() != this)
2394 RenderBox* childBox = floatingObject->renderer();
2396 // FIXME Investigate if this can be removed. crbug.com/370006
2397 childBox->setMayNeedPaintInvalidation(true);
2399 LayoutUnit childLogicalLeftMargin = style()->isLeftToRightDirection() ? marginStartForChild(childBox) : marginEndForChild(childBox);
2400 if (childBox->style()->clear() & CLEFT)
2401 logicalTop = std::max(lowestFloatLogicalBottom(FloatingObject::FloatLeft), logicalTop);
2402 if (childBox->style()->clear() & CRIGHT)
2403 logicalTop = std::max(lowestFloatLogicalBottom(FloatingObject::FloatRight), logicalTop);
2405 LayoutPoint floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, logicalTop);
2407 setLogicalLeftForFloat(floatingObject, floatLogicalLocation.x());
2409 setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
2410 setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
2412 SubtreeLayoutScope layoutScope(*childBox);
2413 LayoutState* layoutState = view()->layoutState();
2414 bool isPaginated = layoutState->isPaginated();
2415 if (isPaginated && !childBox->needsLayout())
2416 childBox->markForPaginationRelayoutIfNeeded(layoutScope);
2418 childBox->layoutIfNeeded();
2421 // If we are unsplittable and don't fit, then we need to move down.
2422 // We include our margins as part of the unsplittable area.
2423 LayoutUnit newLogicalTop = adjustForUnsplittableChild(childBox, floatLogicalLocation.y(), true);
2425 // See if we have a pagination strut that is making us move down further.
2426 // Note that an unsplittable child can't also have a pagination strut, so this is
2427 // exclusive with the case above.
2428 RenderBlockFlow* childBlockFlow = childBox->isRenderBlockFlow() ? toRenderBlockFlow(childBox) : 0;
2429 if (childBlockFlow && childBlockFlow->paginationStrut()) {
2430 newLogicalTop += childBlockFlow->paginationStrut();
2431 childBlockFlow->setPaginationStrut(0);
2434 if (newLogicalTop != floatLogicalLocation.y()) {
2435 floatingObject->setPaginationStrut(newLogicalTop - floatLogicalLocation.y());
2437 floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, newLogicalTop);
2438 setLogicalLeftForFloat(floatingObject, floatLogicalLocation.x());
2440 setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
2441 setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
2443 if (childBox->isRenderBlock())
2444 childBox->setChildNeedsLayout(MarkOnlyThis);
2445 childBox->layoutIfNeeded();
2449 setLogicalTopForFloat(floatingObject, floatLogicalLocation.y());
2451 setLogicalHeightForFloat(floatingObject, logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox));
2453 m_floatingObjects->addPlacedObject(floatingObject);
2455 if (ShapeOutsideInfo* shapeOutside = childBox->shapeOutsideInfo())
2456 shapeOutside->setReferenceBoxLogicalSize(logicalSizeForChild(childBox));
2461 bool RenderBlockFlow::hasOverhangingFloat(RenderBox* renderer)
2463 if (!m_floatingObjects || hasColumns() || !parent())
2466 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2467 FloatingObjectSetIterator it = floatingObjectSet.find<FloatingObjectHashTranslator>(renderer);
2468 if (it == floatingObjectSet.end())
2471 return logicalBottomForFloat(it->get()) > logicalHeight();
2474 void RenderBlockFlow::addIntrudingFloats(RenderBlockFlow* prev, LayoutUnit logicalLeftOffset, LayoutUnit logicalTopOffset)
2476 ASSERT(!avoidsFloats());
2478 // If we create our own block formatting context then our contents don't interact with floats outside it, even those from our parent.
2479 if (createsBlockFormattingContext())
2482 // If the parent or previous sibling doesn't have any floats to add, don't bother.
2483 if (!prev->m_floatingObjects)
2486 logicalLeftOffset += marginLogicalLeft();
2488 const FloatingObjectSet& prevSet = prev->m_floatingObjects->set();
2489 FloatingObjectSetIterator prevEnd = prevSet.end();
2490 for (FloatingObjectSetIterator prevIt = prevSet.begin(); prevIt != prevEnd; ++prevIt) {
2491 FloatingObject* floatingObject = prevIt->get();
2492 if (logicalBottomForFloat(floatingObject) > logicalTopOffset) {
2493 if (!m_floatingObjects || !m_floatingObjects->set().contains(floatingObject)) {
2494 // We create the floating object list lazily.
2495 if (!m_floatingObjects)
2496 createFloatingObjects();
2498 // Applying the child's margin makes no sense in the case where the child was passed in.
2499 // since this margin was added already through the modification of the |logicalLeftOffset| variable
2500 // above. |logicalLeftOffset| will equal the margin in this case, so it's already been taken
2501 // into account. Only apply this code if prev is the parent, since otherwise the left margin
2502 // will get applied twice.
2503 LayoutSize offset = isHorizontalWritingMode()
2504 ? LayoutSize(logicalLeftOffset - (prev != parent() ? prev->marginLeft() : LayoutUnit()), logicalTopOffset)
2505 : LayoutSize(logicalTopOffset, logicalLeftOffset - (prev != parent() ? prev->marginTop() : LayoutUnit()));
2507 m_floatingObjects->add(floatingObject->copyToNewContainer(offset));
2513 void RenderBlockFlow::addOverhangingFloats(RenderBlockFlow* child, bool makeChildPaintOtherFloats)
2515 // Prevent floats from being added to the canvas by the root element, e.g., <html>.
2516 if (!child->containsFloats() || child->isRenderRegion() || child->createsBlockFormattingContext())
2519 LayoutUnit childLogicalTop = child->logicalTop();
2520 LayoutUnit childLogicalLeft = child->logicalLeft();
2522 // Floats that will remain the child's responsibility to paint should factor into its
2524 FloatingObjectSetIterator childEnd = child->m_floatingObjects->set().end();
2525 for (FloatingObjectSetIterator childIt = child->m_floatingObjects->set().begin(); childIt != childEnd; ++childIt) {
2526 FloatingObject* floatingObject = childIt->get();
2527 LayoutUnit logicalBottomForFloat = std::min(this->logicalBottomForFloat(floatingObject), LayoutUnit::max() - childLogicalTop);
2528 LayoutUnit logicalBottom = childLogicalTop + logicalBottomForFloat;
2530 if (logicalBottom > logicalHeight()) {
2531 // If the object is not in the list, we add it now.
2532 if (!containsFloat(floatingObject->renderer())) {
2533 LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(-childLogicalLeft, -childLogicalTop) : LayoutSize(-childLogicalTop, -childLogicalLeft);
2534 bool shouldPaint = false;
2536 // The nearest enclosing layer always paints the float (so that zindex and stacking
2537 // behaves properly). We always want to propagate the desire to paint the float as
2538 // far out as we can, to the outermost block that overlaps the float, stopping only
2539 // if we hit a self-painting layer boundary.
2540 if (floatingObject->renderer()->enclosingFloatPaintingLayer() == enclosingFloatPaintingLayer()) {
2541 floatingObject->setShouldPaint(false);
2544 // We create the floating object list lazily.
2545 if (!m_floatingObjects)
2546 createFloatingObjects();
2548 m_floatingObjects->add(floatingObject->copyToNewContainer(offset, shouldPaint, true));
2551 if (makeChildPaintOtherFloats && !floatingObject->shouldPaint() && !floatingObject->renderer()->hasSelfPaintingLayer()
2552 && floatingObject->renderer()->isDescendantOf(child) && floatingObject->renderer()->enclosingFloatPaintingLayer() == child->enclosingFloatPaintingLayer()) {
2553 // The float is not overhanging from this block, so if it is a descendant of the child, the child should
2554 // paint it (the other case is that it is intruding into the child), unless it has its own layer or enclosing
2556 // If makeChildPaintOtherFloats is false, it means that the child must already know about all the floats
2558 floatingObject->setShouldPaint(true);
2561 // Since the float doesn't overhang, it didn't get put into our list. We need to go ahead and add its overflow in to the
2563 if (floatingObject->isDescendant())
2564 child->addOverflowFromChild(floatingObject->renderer(), LayoutSize(xPositionForFloatIncludingMargin(floatingObject), yPositionForFloatIncludingMargin(floatingObject)));
2569 LayoutUnit RenderBlockFlow::lowestFloatLogicalBottom(FloatingObject::Type floatType) const
2571 if (!m_floatingObjects)
2574 return m_floatingObjects->lowestFloatLogicalBottom(floatType);
2577 LayoutUnit RenderBlockFlow::nextFloatLogicalBottomBelow(LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode) const
2579 if (!m_floatingObjects)
2580 return logicalHeight;
2582 LayoutUnit logicalBottom;
2583 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2584 FloatingObjectSetIterator end = floatingObjectSet.end();
2585 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2586 FloatingObject* floatingObject = it->get();
2587 LayoutUnit floatLogicalBottom = logicalBottomForFloat(floatingObject);
2588 ShapeOutsideInfo* shapeOutside = floatingObject->renderer()->shapeOutsideInfo();
2589 if (shapeOutside && (offsetMode == ShapeOutsideFloatShapeOffset)) {
2590 LayoutUnit shapeLogicalBottom = logicalTopForFloat(floatingObject) + marginBeforeForChild(floatingObject->renderer()) + shapeOutside->shapeLogicalBottom();
2591 // Use the shapeLogicalBottom unless it extends outside of the margin box, in which case it is clipped.
2592 if (shapeLogicalBottom < floatLogicalBottom)
2593 floatLogicalBottom = shapeLogicalBottom;
2595 if (floatLogicalBottom > logicalHeight)
2596 logicalBottom = logicalBottom ? std::min(floatLogicalBottom, logicalBottom) : floatLogicalBottom;
2599 return logicalBottom;
2602 bool RenderBlockFlow::hitTestFloats(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset)
2604 if (!m_floatingObjects)
2607 LayoutPoint adjustedLocation = accumulatedOffset;
2608 if (isRenderView()) {
2609 adjustedLocation += toLayoutSize(LayoutPoint(toRenderView(this)->frameView()->scrollPositionDouble()));
2612 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2613 FloatingObjectSetIterator begin = floatingObjectSet.begin();
2614 for (FloatingObjectSetIterator it = floatingObjectSet.end(); it != begin;) {
2616 FloatingObject* floatingObject = it->get();
2617 if (floatingObject->shouldPaint() && !floatingObject->renderer()->hasSelfPaintingLayer()) {
2618 LayoutUnit xOffset = xPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->x();
2619 LayoutUnit yOffset = yPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->y();
2620 LayoutPoint childPoint = flipFloatForWritingModeForChild(floatingObject, adjustedLocation + LayoutSize(xOffset, yOffset));
2621 if (floatingObject->renderer()->hitTest(request, result, locationInContainer, childPoint)) {
2622 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(childPoint));
2631 LayoutUnit RenderBlockFlow::logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const
2633 if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
2634 return m_floatingObjects->logicalLeftOffset(fixedOffset, logicalTop, logicalHeight);
2639 LayoutUnit RenderBlockFlow::logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const
2641 if (m_floatingObjects && m_floatingObjects->hasRightObjects())
2642 return m_floatingObjects->logicalRightOffset(fixedOffset, logicalTop, logicalHeight);
2647 GapRects RenderBlockFlow::inlineSelectionGaps(const RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
2648 LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo) const
2652 bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
2654 if (!firstLineBox()) {
2655 if (containsStart) {
2656 // Go ahead and update our lastLogicalTop to be the bottom of the block. <hr>s or empty blocks with height can trip this
2658 lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalHeight();
2659 lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
2660 lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
2665 RootInlineBox* lastSelectedLine = 0;
2666 RootInlineBox* curr;
2667 for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
2669 // Now paint the gaps for the lines.
2670 for (; curr && curr->hasSelectedChildren(); curr = curr->nextRootBox()) {
2671 LayoutUnit selTop = curr->selectionTopAdjustedForPrecedingBlock();
2672 LayoutUnit selHeight = curr->selectionHeightAdjustedForPrecedingBlock();
2674 if (!containsStart && !lastSelectedLine && selectionState() != SelectionStart && selectionState() != SelectionBoth) {
2675 result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop,
2676 lastLogicalLeft, lastLogicalRight, selTop, paintInfo));
2679 LayoutRect logicalRect(curr->logicalLeft(), selTop, curr->logicalWidth(), selTop + selHeight);
2680 logicalRect.move(isHorizontalWritingMode() ? offsetFromRootBlock : offsetFromRootBlock.transposedSize());
2681 LayoutRect physicalRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
2682 if (!paintInfo || (isHorizontalWritingMode() && physicalRect.y() < paintInfo->rect.maxY() && physicalRect.maxY() > paintInfo->rect.y())
2683 || (!isHorizontalWritingMode() && physicalRect.x() < paintInfo->rect.maxX() && physicalRect.maxX() > paintInfo->rect.x()))
2684 result.unite(curr->lineSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, selTop, selHeight, paintInfo));
2686 lastSelectedLine = curr;
2689 if (containsStart && !lastSelectedLine) {
2690 // VisibleSelection must start just after our last line.
2691 lastSelectedLine = lastRootBox();
2694 if (lastSelectedLine && selectionState() != SelectionEnd && selectionState() != SelectionBoth) {
2695 // Go ahead and update our lastY to be the bottom of the last selected line.
2696 lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + lastSelectedLine->selectionBottom();
2697 lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
2698 lastLogicalRight = logicalRightSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
2703 void RenderBlockFlow::setPaginationStrut(LayoutUnit strut)
2708 m_rareData = adoptPtrWillBeNoop(new RenderBlockFlowRareData(this));
2710 m_rareData->m_paginationStrut = strut;
2713 bool RenderBlockFlow::avoidsFloats() const
2715 // Floats can't intrude into our box if we have a non-auto column count or width.
2716 // Note: we need to use RenderBox::avoidsFloats here since RenderBlock::avoidsFloats is always true.
2717 return RenderBox::avoidsFloats() || !style()->hasAutoColumnCount() || !style()->hasAutoColumnWidth();
2720 LayoutUnit RenderBlockFlow::logicalLeftSelectionOffset(const RenderBlock* rootBlock, LayoutUnit position) const
2722 LayoutUnit logicalLeft = logicalLeftOffsetForLine(position, false);
2723 if (logicalLeft == logicalLeftOffsetForContent())
2724 return RenderBlock::logicalLeftSelectionOffset(rootBlock, position);
2726 const RenderBlock* cb = this;
2727 while (cb != rootBlock) {
2728 logicalLeft += cb->logicalLeft();
2729 cb = cb->containingBlock();
2734 LayoutUnit RenderBlockFlow::logicalRightSelectionOffset(const RenderBlock* rootBlock, LayoutUnit position) const
2736 LayoutUnit logicalRight = logicalRightOffsetForLine(position, false);
2737 if (logicalRight == logicalRightOffsetForContent())
2738 return RenderBlock::logicalRightSelectionOffset(rootBlock, position);
2740 const RenderBlock* cb = this;
2741 while (cb != rootBlock) {
2742 logicalRight += cb->logicalLeft();
2743 cb = cb->containingBlock();
2745 return logicalRight;
2748 RootInlineBox* RenderBlockFlow::createRootInlineBox()
2750 return new RootInlineBox(*this);
2753 bool RenderBlockFlow::isPagedOverflow(const RenderStyle* style)
2755 return style->isOverflowPaged() && node() != document().viewportDefiningElement();
2758 RenderBlockFlow::FlowThreadType RenderBlockFlow::flowThreadType(const RenderStyle* style)
2760 if (isPagedOverflow(style))
2761 return PagedFlowThread;
2762 if (style->specifiesColumns())
2763 return MultiColumnFlowThread;
2764 return NoFlowThread;
2767 RenderMultiColumnFlowThread* RenderBlockFlow::createMultiColumnFlowThread(FlowThreadType type)
2770 case MultiColumnFlowThread:
2771 return RenderMultiColumnFlowThread::createAnonymous(document(), style());
2772 case PagedFlowThread:
2773 // Paged overflow is currently done using the multicol implementation.
2774 return RenderPagedFlowThread::createAnonymous(document(), style());
2776 ASSERT_NOT_REACHED();
2781 void RenderBlockFlow::createOrDestroyMultiColumnFlowThreadIfNeeded(const RenderStyle* oldStyle)
2783 if (!document().regionBasedColumnsEnabled())
2786 // Paged overflow trumps multicol in this implementation. Ideally, it should be possible to have
2787 // both paged overflow and multicol on the same element, but then we need two flow
2788 // threads. Anyway, this is nothing to worry about until we can actually nest multicol properly
2789 // inside other fragmentation contexts.
2790 FlowThreadType type = flowThreadType(style());
2792 if (multiColumnFlowThread()) {
2794 if (type != flowThreadType(oldStyle)) {
2795 // If we're no longer to be multicol/paged, destroy the flow thread. Also destroy it
2796 // when switching between multicol and paged, since that affects the column set
2797 // structure (multicol containers may have spanners, paged containers may not).
2798 multiColumnFlowThread()->evacuateAndDestroy();
2799 ASSERT(!multiColumnFlowThread());
2803 if (type == NoFlowThread || multiColumnFlowThread())
2806 RenderMultiColumnFlowThread* flowThread = createMultiColumnFlowThread(type);
2807 addChild(flowThread);
2808 flowThread->populate();
2809 RenderBlockFlowRareData& rareData = ensureRareData();
2810 ASSERT(!rareData.m_multiColumnFlowThread);
2811 rareData.m_multiColumnFlowThread = flowThread;
2814 RenderBlockFlow::RenderBlockFlowRareData& RenderBlockFlow::ensureRareData()
2819 m_rareData = adoptPtrWillBeNoop(new RenderBlockFlowRareData(this));
2823 void RenderBlockFlow::positionDialog()
2825 HTMLDialogElement* dialog = toHTMLDialogElement(node());
2826 if (dialog->centeringMode() == HTMLDialogElement::NotCentered)
2829 bool canCenterDialog = (style()->position() == AbsolutePosition || style()->position() == FixedPosition)
2830 && style()->hasAutoTopAndBottom();
2832 if (dialog->centeringMode() == HTMLDialogElement::Centered) {
2833 if (canCenterDialog)
2834 setY(dialog->centeredPosition());
2838 ASSERT(dialog->centeringMode() == HTMLDialogElement::NeedsCentering);
2839 if (!canCenterDialog) {
2840 dialog->setNotCentered();
2844 FrameView* frameView = document().view();
2845 LayoutUnit top = (style()->position() == FixedPosition) ? 0 : frameView->scrollOffset().height();
2846 int visibleHeight = frameView->visibleContentRect(IncludeScrollbars).height();
2847 if (height() < visibleHeight)
2848 top += (visibleHeight - height()) / 2;
2850 dialog->setCentered(top);
2853 } // namespace blink